Skip to content

Commit

Permalink
Merge pull request #55 from oqc-community/jd/ruff
Browse files Browse the repository at this point in the history
Adding Ruff, applying format on composite build
  • Loading branch information
chemix-lunacy authored Jul 12, 2024
2 parents 56733b2 + 645b06f commit b7600b0
Show file tree
Hide file tree
Showing 18 changed files with 300 additions and 203 deletions.
File renamed without changes.
14 changes: 14 additions & 0 deletions src/rasqal/.ruff.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
fix-only = true

[format]
skip-magic-trailing-comma = true

[lint.flake8-unused-arguments]
ignore-variadic-names = true

[lint.flake8-annotations]
allow-star-arg-any = true
suppress-dummy-args = true

[lint.flake8-comprehensions]
allow-dict-calls-with-keyword-arguments = true
54 changes: 14 additions & 40 deletions src/rasqal/rasqal/_native.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@

from typing import Any, Optional, List

from .adaptors import BuilderAdaptor, RuntimeAdaptor

from .adaptors import RuntimeAdaptor

DEFAULT_LOG_FILE = ""

Expand All @@ -14,50 +13,25 @@ def initialize_file_logger(file_path: str):
def initialize_commandline_logger():
pass


class Graph:
...

class Graph: ...

class Executor:
def trace_graphs(self):
...

def trace_runtime(self):
...

def trace_projections(self):
...

def step_count_limit(self, limit: int):
...

def run(
self,
file_path: str,
runtimes: List[RuntimeAdaptor]
) -> Any:
""" Runs this file using the automatically-detected entry-point with no arguments. """
def trace_graphs(self): ...
def trace_runtime(self): ...
def trace_projections(self): ...
def step_count_limit(self, limit: int): ...
def run(self, file_path: str, runtimes: List[RuntimeAdaptor]) -> Any:
"""Runs this file using the automatically-detected entry-point with no arguments."""

def run_with_args(
self,
file_path: str,
arguments: List[Any],
runtimes: List[RuntimeAdaptor]
self, file_path: str, arguments: List[Any], runtimes: List[RuntimeAdaptor]
) -> Any:
""" Runs this file using the automatically-detected entry-point. """
"""Runs this file using the automatically-detected entry-point."""

def parse_file(
self,
file: str,
entry_point: Optional[str]
) -> Graph:
""" Evaluates and builds this file into the internal execution graph and returns it. """
def parse_file(self, file: str, entry_point: Optional[str]) -> Graph:
"""Evaluates and builds this file into the internal execution graph and returns it."""

def run_graph(
self,
graph: Graph,
arguments: List[Any],
runtime_adaptor: RuntimeAdaptor
self, graph: Graph, arguments: List[Any], runtime_adaptor: RuntimeAdaptor
) -> Any:
""" Runs a pre-built execution graph with the passed-in arguments. """
"""Runs a pre-built execution graph with the passed-in arguments."""
32 changes: 12 additions & 20 deletions src/rasqal/rasqal/adaptors.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (c) 2024 Oxford Quantum Circuits Ltd

import abc
from typing import Dict


Expand All @@ -15,32 +14,24 @@ class BuilderAdaptor:
This builder will then be passed to the provided runtime for execution.
"""
def cx(self, controls, target, radii):
...

def cz(self, controls, target, radii):
...
def cx(self, controls, target, radii): ...

def cy(self, controls, target, radii):
...
def cz(self, controls, target, radii): ...

def x(self, qubit, radii):
...
def cy(self, controls, target, radii): ...

def y(self, qubit, radii):
...
def x(self, qubit, radii): ...

def z(self, qubit, radii):
...
def y(self, qubit, radii): ...

def swap(self, qubit1, qubit2):
...
def z(self, qubit, radii): ...

def reset(self, qubit):
...
def swap(self, qubit1, qubit2): ...

def measure(self, qubit):
...
def reset(self, qubit): ...

def measure(self, qubit): ...


class RuntimeAdaptor:
Expand All @@ -53,6 +44,7 @@ class RuntimeAdaptor:
Every time a quantum blob needs to be executed it will query whether a particular runtime is able to support
it and then use that builder/runtime combination to execute it, if applicable.
"""

def execute(self, builder) -> Dict[str, int]:
"""
Executes the passed-in builder against the backend and returns a result distribution.
Expand All @@ -62,7 +54,7 @@ def execute(self, builder) -> Dict[str, int]:
return dict()

def create_builder(self) -> BuilderAdaptor:
""" Creates a builder to be used with this runtime. """
"""Creates a builder to be used with this runtime."""
return BuilderAdaptor()

def has_features(self, required_features: "RequiredFeatures"):
Expand Down
11 changes: 9 additions & 2 deletions src/rasqal/rasqal/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,13 @@ def __init__(

# Set the root to the lowest non-custom log level activated.
root.setLevel(
min([val.level for val in self.loggers if (float(val.level / 10)).is_integer()])
min(
[
val.level
for val in self.loggers
if (float(val.level / 10)).is_integer()
]
)
)

def add_loggers(self, loggers_or_names: List[Union[str, logging.Logger]] = ()):
Expand Down Expand Up @@ -579,7 +585,8 @@ def get_default_logger():

stack = traceback.extract_stack()
is_test_env = any(
val.filename is not None and val.filename.endswith(f"unittest\\loader.py")
val.filename is not None
and val.filename.endswith("unittest\\loader.py")
for val in stack
)
if is_test_env:
Expand Down
36 changes: 28 additions & 8 deletions src/rasqal/rasqal/routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@ def build_ring_architecture(num_qubits):
return [(i % num_qubits, (i + 1) % num_qubits) for i in range(num_qubits)]


def apply_routing(couplings: Union[Architecture, List[Tuple[int, int]]], runtime: Union[RasqalRunner, RuntimeAdaptor]):
def apply_routing(
couplings: Union[Architecture, List[Tuple[int, int]]],
runtime: Union[RasqalRunner, RuntimeAdaptor],
):
if isinstance(runtime, RasqalRunner):
runtime.runtimes = [TketRuntime(couplings, rt) for rt in runtime.runtimes]
return runtime
Expand Down Expand Up @@ -80,15 +83,20 @@ class TketRuntime(RuntimeAdaptor):
Can be
"""

def __init__(self, couplings: Union[Architecture, List[Tuple[int, int]]],
forwarded_runtime: RuntimeAdaptor):
def __init__(
self,
couplings: Union[Architecture, List[Tuple[int, int]]],
forwarded_runtime: RuntimeAdaptor,
):
self.forwarded = forwarded_runtime
if isinstance(couplings, list):
self.arch = Architecture(couplings)
elif isinstance(couplings, Architecture):
self.arch = couplings
else:
raise ValueError(f"Invalid architecture or coupling mappings: {str(couplings)}")
raise ValueError(
f"Invalid architecture or coupling mappings: {str(couplings)}"
)

def execute(self, builder) -> Dict[str, int]:
builder: TketBuilder
Expand All @@ -97,7 +105,7 @@ def execute(self, builder) -> Dict[str, int]:
return self.forwarded.execute(self._forward_circuit(builder))

def _forward_circuit(self, builder) -> BuilderAdaptor:
""" Forwards the Tket circuit on to the new builder to be run in the forwarding runtime. """
"""Forwards the Tket circuit on to the new builder to be run in the forwarding runtime."""
fbuilder = self.forwarded.create_builder()
for gate in builder.circuit:
if gate.op.type == OpType.Rz:
Expand All @@ -107,11 +115,23 @@ def _forward_circuit(self, builder) -> BuilderAdaptor:
elif gate.op.type == OpType.Ry:
fbuilder.y(gate.qubits[0].index[0], gate.op.params[0])
elif gate.op.type == OpType.CRx:
fbuilder.cx([gate.qubits[0].index[0]], gate.qubits[1].index[0], gate.op.params[0])
fbuilder.cx(
[gate.qubits[0].index[0]],
gate.qubits[1].index[0],
gate.op.params[0],
)
elif gate.op.type == OpType.CRy:
fbuilder.cy([gate.qubits[0].index[0]], gate.qubits[1].index[0], gate.op.params[0])
fbuilder.cy(
[gate.qubits[0].index[0]],
gate.qubits[1].index[0],
gate.op.params[0],
)
elif gate.op.type == OpType.CRz:
fbuilder.cz([gate.qubits[0].index[0]], gate.qubits[1].index[0], gate.op.params[0])
fbuilder.cz(
[gate.qubits[0].index[0]],
gate.qubits[1].index[0],
gate.op.params[0],
)
elif gate.op.type == OpType.SWAP:
fbuilder.swap(gate.qubits[0].index[0], gate.qubits[1].index[0])
elif gate.op.type == OpType.Measure:
Expand Down
4 changes: 1 addition & 3 deletions src/rasqal/rasqal/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,5 @@ def run(self, file_path: str, args: List[Any] = None):
Runs an .ll or .bc file with the passed-in arguments.
Arguments can only be Python primitives or otherwise easily transformable to Rust objects.
"""
results = self.executor.run_with_args(
file_path, args or [], self.runtimes
)
results = self.executor.run_with_args(file_path, args or [], self.runtimes)
return results
6 changes: 5 additions & 1 deletion src/rasqal/rasqal/simulators.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class QASMBuilder(BuilderAdaptor):
"""
Builder which builds Qiskit quantum circuits.
"""

def __init__(self, qubit_count: int):
super().__init__()
self.circuit = QuantumCircuit(qubit_count, qubit_count)
Expand Down Expand Up @@ -65,11 +66,14 @@ class QASMRuntime(RuntimeAdaptor):
Qiskit-backed runtime.
Builds and runs a pure QASM simulation as a backend.
"""

def __init__(self, qubit_count=30):
self.qubit_count = qubit_count

def execute(self, builder: QASMBuilder) -> Dict[str, int]:
aer_config = QasmBackendConfiguration.from_dict(AerSimulator._DEFAULT_CONFIGURATION)
aer_config = QasmBackendConfiguration.from_dict(
AerSimulator._DEFAULT_CONFIGURATION
)
aer_config.n_qubits = builder.circuit.num_qubits
qasm_sim = AerSimulator(aer_config)

Expand Down
6 changes: 5 additions & 1 deletion src/rasqal/rasqal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

from typing import Optional

from ._native import initialize_file_logger, initialize_commandline_logger, DEFAULT_LOG_FILE
from ._native import (
initialize_file_logger,
initialize_commandline_logger,
DEFAULT_LOG_FILE, # noqa
)


def initialize_logger(file_path: Optional[str] = None):
Expand Down
7 changes: 0 additions & 7 deletions src/rasqal/src/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,13 +255,6 @@ impl PyBuilderAdaptor {
return Ptr::is_null(self.builder.borrow()) || self.builder.is_none();
}

pub fn ab(&self) -> Result<&PyAny, String> {
let target = self.builder.getattr("ab").expect("'ab' doesn't exist on builder");
Python::with_gil(|py| {
target.call0().map_err(|err| err.value(py).to_string())
})
}

python_methods!(self.builder.x(qubit: i64, radians: f64));
python_methods!(self.builder.y(qubit: i64, radians: f64));
python_methods!(self.builder.z(qubit: i64, radians: f64));
Expand Down
Loading

0 comments on commit b7600b0

Please sign in to comment.