Skip to content

Commit

Permalink
Format Python files with Black (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
bamarsha authored Sep 3, 2022
1 parent 2194614 commit 71ca368
Show file tree
Hide file tree
Showing 20 changed files with 209 additions and 301 deletions.
12 changes: 11 additions & 1 deletion eng/psakefile.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ task default -depends qirlib, pyqir-tests, parser, generator, evaluator, metawhe

task build -depends qirlib, generator, evaluator, parser

task checks -depends cargo-fmt, cargo-clippy, mypy
task checks -depends cargo-fmt, cargo-clippy, black, mypy

task manylinux -depends build-manylinux-container-image, run-manylinux-container-image, run-examples-in-containers

Expand Down Expand Up @@ -100,6 +100,16 @@ task cargo-clippy -depends init {
}
}

task black -depends check-environment {
exec {
pip install black
}

Invoke-LoggedCommand -workingDirectory $repo.root -errorMessage "Please run black before pushing" {
black --check --extend-exclude "^/examples/generator/mock_language/" .
}
}

task mypy -depends python-requirements {
exec {
& $python -m pip install mypy
Expand Down
4 changes: 3 additions & 1 deletion examples/evaluator/teleport.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
from typing import List, Tuple


def teleport(qis: BasicQisBuilder, qubits: Tuple[Value, ...], results: Tuple[Value, ...]) -> None:
def teleport(
qis: BasicQisBuilder, qubits: Tuple[Value, ...], results: Tuple[Value, ...]
) -> None:
msg = qubits[0]
target = qubits[1]
register = qubits[2]
Expand Down
3 changes: 1 addition & 2 deletions examples/generator/arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
# external_functions.py.
i32 = types.Int(32)
get_int = mod.add_external_function("get_int", types.Function([], i32))
take_int = mod.add_external_function(
"take_int", types.Function([i32], types.VOID))
take_int = mod.add_external_function("take_int", types.Function([i32], types.VOID))

# Add 3 to a number and multiply the result by 2.
a = mod.builder.call(get_int, [])
Expand Down
14 changes: 5 additions & 9 deletions examples/generator/dynamic_allocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,20 @@
# appropriate runtime functions.
mod = SimpleModule("dynamic_allocation", num_qubits=0, num_results=0)
qubit_allocate = mod.add_external_function(
"__quantum__rt__qubit_allocate",
types.Function([], types.QUBIT)
"__quantum__rt__qubit_allocate", types.Function([], types.QUBIT)
)
qubit_release = mod.add_external_function(
"__quantum__rt__qubit_release",
types.Function([types.QUBIT], types.VOID)
"__quantum__rt__qubit_release", types.Function([types.QUBIT], types.VOID)
)
result_get_one = mod.add_external_function(
"__quantum__rt__result_get_one",
types.Function([], types.RESULT)
"__quantum__rt__result_get_one", types.Function([], types.RESULT)
)
result_equal = mod.add_external_function(
"__quantum__rt__result_equal",
types.Function([types.RESULT, types.RESULT], types.BOOL)
types.Function([types.RESULT, types.RESULT], types.BOOL),
)
m = mod.add_external_function(
"__quantum__qis__m__body",
types.Function([types.QUBIT], types.RESULT)
"__quantum__qis__m__body", types.Function([types.QUBIT], types.RESULT)
)

# Instead of mod.qubits[i], use __quantum__rt__qubit_allocate.
Expand Down
8 changes: 2 additions & 6 deletions examples/generator/external_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@

# Declare an externally linked function named that has no parameters and returns
# void.
my_function = mod.add_external_function(
"my_function", types.Function([], types.VOID)
)
my_function = mod.add_external_function("my_function", types.Function([], types.VOID))

# Call the function with no arguments (the empty list).
mod.builder.call(my_function, [])
Expand All @@ -24,9 +22,7 @@
mod.builder.call(my_gate, [const(types.Int(64), 123), mod.qubits[0]])

# Declare a function that returns a double.
get_angle = mod.add_external_function(
"get_angle", types.Function([], types.DOUBLE)
)
get_angle = mod.add_external_function("get_angle", types.Function([], types.DOUBLE))

# Use the return value of the function as the input to a rotation gate.
angle = mod.builder.call(get_angle, [])
Expand Down
27 changes: 10 additions & 17 deletions examples/generator/mock_to_qir.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

class QirGenerator(MockLanguageListener): # type: ignore[misc]
"""
Class that generates QIR when walking the parse tree
Class that generates QIR when walking the parse tree
of a Mock language program.
"""

Expand All @@ -35,17 +35,13 @@ def parse_qubit(self, id: str) -> Value:
try:
return self.module.qubits[int(id)]
except IndexError as e:
raise ValueError(
"Parsed progam uses more qubits than allocated"
) from e
raise ValueError("Parsed progam uses more qubits than allocated") from e

def parse_result(self, id: str) -> Value:
try:
return self.module.results[int(id)]
except IndexError as e:
raise ValueError(
"Parsed progam uses more results than allocated"
) from e
raise ValueError("Parsed progam uses more results than allocated") from e

def enterXGate(self, ctx: MockLanguageParser.XGateContext) -> None:
qubit = self.parse_qubit(ctx.target.text)
Expand All @@ -69,8 +65,8 @@ def enterMzGate(self, ctx: MockLanguageParser.MzGateContext) -> None:
def mock_program_to_qir(num_qubits: int, input_file: str) -> str:
"""
Parses a Mock program and generates QIR based on the syntax tree.
Usually the language-specific compiler would fully validate and
potentially optimize the program before QIR is generated, but for
Usually the language-specific compiler would fully validate and
potentially optimize the program before QIR is generated, but for
illustration purposes we omit that from this example.
:param num_qubits: The total number of qubits used in the program.
Expand All @@ -88,26 +84,23 @@ def mock_program_to_qir(num_qubits: int, input_file: str) -> str:
return generator.ir()


if __name__ == '__main__':
if __name__ == "__main__":
command_line = ArgumentParser()
command_line.add_argument(
'input_file', type=str,
help='Path of the file containing the Mock program.'
"input_file", type=str, help="Path of the file containing the Mock program."
)
command_line.add_argument(
'num_qubits', type=int,
help='The total number of qubits used in the program.'
"num_qubits", type=int, help="The total number of qubits used in the program."
)
command_line.add_argument(
'-o', '--output_file', type=str,
help='Path of the file to write the IR to.'
"-o", "--output_file", type=str, help="Path of the file to write the IR to."
)
args = command_line.parse_args()

generated_qir = mock_program_to_qir(args.num_qubits, args.input_file)

if args.output_file is not None:
with open(args.output_file, 'w') as file:
with open(args.output_file, "w") as file:
file.write(generated_qir)
else:
print(generated_qir)
9 changes: 3 additions & 6 deletions examples/generator/python2qir.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,22 @@ def visit_Call(self, node: ast.Call) -> None:
if name.id == "QuantumCircuit":
num_qubits = int_value(node.args[0])
num_results = int_value(node.args[1])
self.module = SimpleModule(
"python2qir", num_qubits, num_results)
self.module = SimpleModule("python2qir", num_qubits, num_results)
self.builder = BasicQisBuilder(self.module.builder)

if isinstance(node.func, ast.Attribute):
attribute: ast.Attribute = node.func
if attribute.attr == "cx":
control = int_value(node.args[0])
target = int_value(node.args[1])
self.builder.cx(
self.module.qubits[control], self.module.qubits[target])
self.builder.cx(self.module.qubits[control], self.module.qubits[target])
if attribute.attr == "h":
qubit = int_value(node.args[0])
self.builder.h(self.module.qubits[qubit])
if attribute.attr == "measure":
qubit = int_value(node.args[0])
bit = int_value(node.args[1])
self.builder.mz(
self.module.qubits[qubit], self.module.results[bit])
self.builder.mz(self.module.qubits[qubit], self.module.results[bit])
if attribute.attr == "z":
qubit = int_value(node.args[0])
self.builder.z(self.module.qubits[qubit])
Expand Down
4 changes: 3 additions & 1 deletion pyqir-evaluator/pyqir/evaluator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@

from pyqir.evaluator._gatelogger import GateLogger as GateLogger
from pyqir.evaluator._gateset import GateSet as GateSet
from pyqir.evaluator._nonadaptiveevaluator import NonadaptiveEvaluator as NonadaptiveEvaluator
from pyqir.evaluator._nonadaptiveevaluator import (
NonadaptiveEvaluator as NonadaptiveEvaluator,
)
6 changes: 2 additions & 4 deletions pyqir-evaluator/pyqir/evaluator/_native.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,11 @@
from pyqir.evaluator._gateset import GateSet
from typing import List, Optional


class PyNonadaptiveJit:
def eval(
self,
file_path: str,
gateset: GateSet,
entry_point: Optional[str],
result_stream: Optional[List[bool]]
) -> None:
...
result_stream: Optional[List[bool]],
) -> None: ...
11 changes: 7 additions & 4 deletions pyqir-evaluator/tests/test_unknown_external_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@ def test_unknown_external_func() -> None:
fd.write(content)
fd.flush()
evaluator.eval(fd.name, logger)
assert (str(excinfo.value)
== "Unsupported functions `__quantum__rt__bool_to_string`.")
assert (
str(excinfo.value) == "Unsupported functions `__quantum__rt__bool_to_string`."
)


def test_multiple_unknown_external_funcs() -> None:
Expand Down Expand Up @@ -62,5 +63,7 @@ def test_multiple_unknown_external_funcs() -> None:
fd.write(content)
fd.flush()
evaluator.eval(fd.name, logger)
assert (str(excinfo.value)
== "Unsupported functions `__quantum__rt__bool_to_string`, `__quantum__rt__int_to_string`.")
assert (
str(excinfo.value)
== "Unsupported functions `__quantum__rt__bool_to_string`, `__quantum__rt__int_to_string`."
)
79 changes: 18 additions & 61 deletions pyqir-generator/pyqir/generator/_native.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -5,117 +5,74 @@ from pyqir.generator._builder import IntPredicate
from pyqir.generator.types import Type
from typing import Callable, Optional, Sequence, Tuple, Union


class Function:
...


class Value:
...

class Function: ...
class Value: ...

def const(ty: Type, value: Union[int, float]) -> Value: ...


class Builder:
def and_(self, lhs: Value, rhs: Value) -> Value: ...

def or_(self, lhs: Value, rhs: Value) -> Value: ...

def xor(self, lhs: Value, rhs: Value) -> Value: ...

def add(self, lhs: Value, rhs: Value) -> Value: ...

def sub(self, lhs: Value, rhs: Value) -> Value: ...

def mul(self, lhs: Value, rhs: Value) -> Value: ...

def shl(self, lhs: Value, rhs: Value) -> Value: ...

def lshr(self, lhs: Value, rhs: Value) -> Value: ...

def icmp(self, pred: IntPredicate, lhs: Value, rhs: Value) -> Value: ...

def call(
self,
function: Function,
args: Sequence[Union[Value, bool, int, float]],
) -> Optional[Value]:
...

) -> Optional[Value]: ...
def if_(
self, cond: Value, true: Callable[[], None] = ..., false: Callable[[], None] = ...
) -> None:
...

self,
cond: Value,
true: Callable[[], None] = ...,
false: Callable[[], None] = ...,
) -> None: ...

class SimpleModule:
def __init__(
self, name: str, num_qubits: int, num_results: int
) -> None:
...

def __init__(self, name: str, num_qubits: int, num_results: int) -> None: ...
@property
def qubits(self) -> Tuple[Value, ...]: ...

@property
def results(self) -> Tuple[Value, ...]: ...

@property
def builder(self) -> Builder: ...

def ir(self) -> str: ...

def bitcode(self) -> bytes: ...

def add_external_function(self, name: str, ty: Type) -> Function: ...


class BasicQisBuilder:
def __init__(self, builder: Builder) -> None: ...

def cx(self, control: Value, target: Value) -> None: ...

def cz(self, control: Value, target: Value) -> None: ...

def h(self, qubit: Value) -> None: ...

def mz(self, qubit: Value, result: Value) -> None: ...

def reset(self, qubit: Value) -> None: ...

def rx(self, theta: Union[Value, float], qubit: Value) -> None: ...

def ry(self, theta: Union[Value, float], qubit: Value) -> None: ...

def rz(self, theta: Union[Value, float], qubit: Value) -> None: ...

def s(self, qubit: Value) -> None: ...

def s_adj(self, qubit: Value) -> None: ...

def t(self, qubit: Value) -> None: ...

def t_adj(self, qubit: Value) -> None: ...

def x(self, qubit: Value) -> None: ...

def y(self, qubit: Value) -> None: ...

def z(self, qubit: Value) -> None: ...

def if_result(
self, result: Value, one: Callable[[], None] = ..., zero: Callable[[], None] = ...
self,
result: Value,
one: Callable[[], None] = ...,
zero: Callable[[], None] = ...,
) -> None: ...


def ir_to_bitcode(
ir: str, module_name: Optional[str] = ..., source_file_name: Optional[str] = ...
) -> bytes:
...


) -> bytes: ...
def bitcode_to_ir(
bitcode: bytes, module_name: Optional[str] = ..., source_file_name: Optional[str] = ...
) -> str:
...
bitcode: bytes,
module_name: Optional[str] = ...,
source_file_name: Optional[str] = ...,
) -> str: ...
Loading

0 comments on commit 71ca368

Please sign in to comment.