Skip to content

Commit

Permalink
Adding logging (#8)
Browse files Browse the repository at this point in the history
* Adding logging

* rogue prints

---------

Co-authored-by: Neal Erickson <[email protected]>
  • Loading branch information
neal-erickson and nealerickson-qtm authored Oct 13, 2023
1 parent 3732427 commit 6dd0c63
Show file tree
Hide file tree
Showing 8 changed files with 40 additions and 23 deletions.
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,7 @@ pythonpath = [
"."
]
log_cli = true
log_cli_level = "DEBUG"
filterwarnings = ["ignore:::lark.s*"]
log_format = "%(asctime)s.%(msecs)03d %(levelname)s %(message)s"
log_date_format = "%Y-%m-%d %H:%M:%S"
11 changes: 9 additions & 2 deletions pytket/phir/api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import logging

from pytket.circuit import Circuit
from pytket.phir.qtm_machine import QtmMachine
from pytket.phir.rebasing.rebaser import rebase_to_qtm_machine
from pytket.phir.sharding.sharder import Sharder

logger = logging.getLogger(__name__)


def pytket_to_phir(
circuit: Circuit,
Expand All @@ -19,13 +23,16 @@ def pytket_to_phir(
-------
PHIR JSON as a str
"""
logger.info(f"Starting phir conversion process for circuit {circuit}")
if qtm_machine:
logger.info(f"Rebasing to machine {qtm_machine}")
circuit = rebase_to_qtm_machine(circuit, qtm_machine.value)

sharder = Sharder(circuit)
shards = sharder.shard()

phir_output = str(shards) # Just returning fake string for now
# TODO: Pass shards[] into placement, routing, etc
# TODO: Convert to PHIR JSON spec and return

return str(shards) # Just returning fake string for now
logger.info("Output: %s", phir_output)
return phir_output
Empty file added pytket/phir/py.typed
Empty file.
30 changes: 17 additions & 13 deletions pytket/phir/sharding/sharder.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from typing import cast

from pytket.circuit import Circuit, Command, Conditional, Op, OpType
Expand All @@ -15,6 +16,8 @@
OpType.RangePredicate,
]

logger = logging.getLogger(__name__)


class Sharder:
"""The Sharder class.
Expand All @@ -34,7 +37,7 @@ def __init__(self, circuit: Circuit) -> None:
self._circuit = circuit
self._pending_commands: dict[UnitID, list[Command]] = {}
self._shards: list[Shard] = []
print(f"Sharder created for circuit {self._circuit}")
logger.debug(f"Sharder created for circuit {self._circuit}")

def shard(self) -> list[Shard]:
"""Performs sharding algorithm on the circuit the Sharder was initialized with.
Expand All @@ -43,15 +46,14 @@ def shard(self) -> list[Shard]:
-------
list of Shards needed to schedule
"""
print("Sharding begins....")
logger.debug("Sharding begins....")
for command in self._circuit.get_commands():
self._process_command(command)
self._cleanup_remaining_commands()

print("--------------------------------------------")
print("Shard output:")
logger.debug("Shard output:")
for shard in self._shards:
print(shard.pretty_print())
logger.debug(shard)
return self._shards

def _process_command(self, command: Command) -> None:
Expand All @@ -60,13 +62,15 @@ def _process_command(self, command: Command) -> None:
Args:
command: tket command (operation, bits, etc)
"""
print("Processing command: ", command.op, command.op.type, command.args)
logger.debug(
f"Processing command: {command.op} {command.op.type} args: {command.args}",
)
if command.op.type in NOT_IMPLEMENTED_OP_TYPES:
msg = f"OpType {command.op.type} not supported!"
raise NotImplementedError(msg)

if self.should_op_create_shard(command.op):
print(
logger.debug(
f"Building shard for command: {command}",
)
self._build_shard(command)
Expand Down Expand Up @@ -109,7 +113,7 @@ def _build_shard(self, command: Command) -> None:
# Check qubit dependencies (R/W implicitly) since all commands
# on a given qubit need to be ordered as the circuit dictated
if not shard.qubits_used.isdisjoint(command.qubits):
print(f"...adding shard dep {shard.ID} -> qubit overlap")
logger.debug(f"...adding shard dep {shard.ID} -> qubit overlap")
depends_upon.add(shard.ID)
# Check classical dependencies, which depend on writing and reading
# hazards: RAW, WAW, WAR
Expand All @@ -118,17 +122,17 @@ def _build_shard(self, command: Command) -> None:
# Check for write-after-write (changing order would change final value)
# by looking at overlap of bits_written
elif not shard.bits_written.isdisjoint(bits_written):
print(f"...adding shard dep {shard.ID} -> WAW")
logger.debug(f"...adding shard dep {shard.ID} -> WAW")
depends_upon.add(shard.ID)

# Check for read-after-write (value seen would change if reordered)
elif not shard.bits_written.isdisjoint(bits_read):
print(f"...adding shard dep {shard.ID} -> RAW")
logger.debug(f"...adding shard dep {shard.ID} -> RAW")
depends_upon.add(shard.ID)

# Check for write-after-read (no reordering or read is changed)
elif not shard.bits_written.isdisjoint(bits_read):
print(f"...adding shard dep {shard.ID} -> WAR")
logger.debug(f"...adding shard dep {shard.ID} -> WAR")
depends_upon.add(shard.ID)

shard = Shard(
Expand All @@ -140,7 +144,7 @@ def _build_shard(self, command: Command) -> None:
depends_upon,
)
self._shards.append(shard)
print("Appended shard:", shard)
logger.debug(f"Appended shard: {shard}")

def _cleanup_remaining_commands(self) -> None:
remaining_qubits = [k for k, v in self._pending_commands.items() if v]
Expand All @@ -165,7 +169,7 @@ def _add_pending_sub_command(self, command: Command) -> None:
if key not in self._pending_commands:
self._pending_commands[key] = []
self._pending_commands[key].append(command)
print(
logger.debug(
f"Adding pending command {command}",
)

Expand Down
2 changes: 1 addition & 1 deletion ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ select = [
]

ignore = [
"T201", # no prints flake-8
"FIX002", # Allow todos
"TD002", # Allow no author todos
"TD003", # allow todos with no issues
"D100", # Missing docstring in public module
"G004", # F-string in logging invocation
]

[per-file-ignores]
Expand Down
2 changes: 0 additions & 2 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ def test_pytket_to_phir_no_machine(self) -> None:
phir = pytket_to_phir(circuit)

# TODO: Make this test more valuable once PHIR is actually returned
print(phir)
assert len(phir) > 0

def test_pytket_to_phir_h1_1(self) -> None:
Expand All @@ -20,5 +19,4 @@ def test_pytket_to_phir_h1_1(self) -> None:
phir = pytket_to_phir(circuit, QtmMachine.H1_1)

# TODO: Make this test more valuable once PHIR is actually returned
print(phir)
assert len(phir) > 0
8 changes: 6 additions & 2 deletions tests/test_rebaser.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import logging

from pytket.circuit import Circuit, OpType
from pytket.phir.rebasing.rebaser import rebase_to_qtm_machine

Expand All @@ -11,13 +13,15 @@
]


logger = logging.getLogger(__name__)


class TestRebaser:
def test_rebaser_happy_path_arc1a(self) -> None:
circ = get_qasm_as_circuit(QasmFiles.baby)
rebased: Circuit = rebase_to_qtm_machine(circ, "H1-1")

print(rebased)
logger.info(rebased)
for command in rebased.get_commands():
print(command)
if command.op.is_gate():
assert command.op.type in EXPECTED_GATES
7 changes: 4 additions & 3 deletions tests/test_sharder.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@ def test_shard_hashing(self) -> None:
shards = sharder.shard()

shard_set = set(shards)
assert len(shard_set) == 3

assert len(shard_set) > 0
first_shard = next(iter(shard_set))
shard_set.add(first_shard)
assert len(shard_set) == 3

def test_should_op_create_shard(self) -> None:
expected_true: list[Op] = [
Expand Down Expand Up @@ -46,7 +49,6 @@ def test_with_baby_circuit(self) -> None:
assert not shards[0].primary_command.bits
assert len(shards[0].sub_commands) == 2
sub_commands = list(shards[0].sub_commands.items())
print(sub_commands)
assert sub_commands[0][1][0].op.type == OpType.H
assert len(shards[0].depends_upon) == 0

Expand All @@ -70,7 +72,6 @@ def test_rollup_behavior(self) -> None:
assert not shards[0].primary_command.bits
assert len(shards[0].sub_commands) == 2
sub_commands = list(shards[0].sub_commands.items())
print(sub_commands)
assert sub_commands[0][1][0].op.type == OpType.H
assert len(shards[0].depends_upon) == 0

Expand Down

0 comments on commit 6dd0c63

Please sign in to comment.