Skip to content

Commit

Permalink
Linting of files
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex-Kolar committed Aug 23, 2024
1 parent 11f5257 commit 73a5f2a
Show file tree
Hide file tree
Showing 11 changed files with 56 additions and 53 deletions.
7 changes: 4 additions & 3 deletions sequence/components/detector.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Models for photon detection devices.
This module models a single photon detector (SPD) for measurement of individual photons.
It also defines a QSDetector class, which combines models of different hardware devices to measure photon states in different bases.
It also defines a QSDetector class,
which combines models of different hardware devices to measure photon states in different bases.
QSDetector is defined as an abstract template and as implementations for polarization and time bin qubits.
"""

Expand Down Expand Up @@ -84,7 +85,7 @@ def get(self, photon=None, **kwargs) -> None:
if self.get_generator().random() < self.efficiency:
self.record_detection()
else:
log.logger.debug(f'Oops! Photon loss in the detector {self.name}')
log.logger.debug(f'Photon loss in detector {self.name}')

def add_dark_count(self) -> None:
"""Method to schedule false positive detection events.
Expand Down Expand Up @@ -489,7 +490,7 @@ def _generate_povms(self):
povm0_1 = eye((truncation+1) ** 2) - povm1_1
# for detector2 (index 1)
series_elem_list2 = [(-1)**i * fractional_matrix_power(create2, i+1).dot(
fractional_matrix_power(destroy2,i+1)) / factorial(i+1) for i in range(truncation)]
fractional_matrix_power(destroy2, i+1)) / factorial(i+1) for i in range(truncation)]
povm1_2 = sum(series_elem_list2)
povm0_2 = eye((truncation+1) ** 2) - povm1_2

Expand Down
4 changes: 2 additions & 2 deletions sequence/components/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ def const(t):


class MemoryArray(Entity):
"""Aggregator for Memory objects. An array of single atom memories
"""Aggregator for Memory objects.
Equivalent to an array of single atom memories.
The MemoryArray can be accessed as a list to get individual memories.
Attributes:
Expand Down Expand Up @@ -106,7 +107,6 @@ def get_memory_by_name(self, name: str) -> "Memory":
return self.memories[index]



class Memory(Entity):
"""Individual single-atom memory.
Expand Down
6 changes: 3 additions & 3 deletions sequence/entanglement_management/swapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __init__(self, own: "Node", name: str, left_memo: "Memory", right_memo: "Mem
self.right_protocol_name = None

def is_ready(self) -> bool:
"""Return True if left_protocol and right_protocol are both set
"""Return True if left_protocol and right_protocol are both set.
"""

return (self.left_protocol_name is not None) and (self.right_protocol_name is not None)
Expand Down Expand Up @@ -162,7 +162,7 @@ def start(self) -> None:
assert self.right_memo.entangled_memory["node_id"] == self.right_node

if self.owner.get_generator().random() < self.success_probability():
# swapping successed
# swapping succeeded
fidelity = self.updated_fidelity(self.left_memo.fidelity, self.right_memo.fidelity)
self.is_success = True

Expand All @@ -173,7 +173,7 @@ def start(self) -> None:
self.circuit, [self.left_memo.qstate_key, self.right_memo.qstate_key], meas_samp)
meas_res = [meas_res[self.left_memo.qstate_key], meas_res[self.right_memo.qstate_key]]

log.logger.info(f"{self.name} swapping successed, meas_res={meas_res[0]},{meas_res[1]}")
log.logger.info(f"{self.name} swapping succeeded, meas_res={meas_res[0]},{meas_res[1]}")

msg_l = EntanglementSwappingMessage(SwappingMsgType.SWAP_RES,
self.left_protocol_name, fidelity=fidelity,
Expand Down
2 changes: 1 addition & 1 deletion sequence/kernel/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Process:
Attributes:
owner (Any): the object of process.
activation_method (str): the function name of object.
activation (str): the function name of object.
activation_args (List[Any]): the (non-keyword) arguments of object's function.
activation_kwargs (Dict[Any, Any]): the keyword arguments of object's function.
"""
Expand Down
3 changes: 2 additions & 1 deletion sequence/kernel/quantum_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .quantum_utils import *
from ..constants import EPSILON


def swap_bits(num, pos1, pos2):
"""Swaps bits in num at positions 1 and 2.
Expand Down Expand Up @@ -58,7 +59,7 @@ def serialize(self) -> Dict:
res = {"keys": self.keys}
state = []
for cplx_n in self.state:
if type(cplx_n) == float:
if type(cplx_n) is float:
state.append(cplx_n)
state.append(0)
elif isinstance(cplx_n, complex):
Expand Down
13 changes: 7 additions & 6 deletions sequence/network_management/network_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ def received_message(self, src: str, msg: "NetworkManagerMessage"):
log.logger.info("{} network manager receives message from {}: {}".format(self.owner.name, src, msg))
self.protocol_stack[0].pop(src=src, msg=msg.payload)

def request(self, responder: str, start_time: int, end_time: int, memory_size: int, target_fidelity: float,
entanglement_number: int = 1, id: int = 0) -> None:
def request(self, responder: str, start_time: int, end_time: int, memory_size: int, target_fidelity: float,
entanglement_number: int = 1, identity: int = 0) -> None:
"""Method to make an entanglement request.
Will defer request to top protocol in protocol stack.
Expand All @@ -133,14 +133,15 @@ def request(self, responder: str, start_time: int, end_time: int, memory_size: i
end_time (int): simulation end time of entanglement.
memory_size (int): number of entangled memory pairs to create.
target_fidelity (float): desired fidelity of entanglement.
entanglement_number (int): the number of entanglement requested
id (int): the ID of the request
entanglement_number (int): the number of entanglement requested.
identity (int): the ID of the request.
Side Effects:
Will invoke `push` method of -1 indexed protocol in `protocol_stack`, which is the resource reservation protocol
Will invoke `push` method of -1 indexed protocol in `protocol_stack`,
which is the resource reservation protocol.
"""

self.protocol_stack[-1].push(responder, start_time, end_time, memory_size, target_fidelity, entanglement_number, id)
self.protocol_stack[-1].push(responder, start_time, end_time, memory_size, target_fidelity, entanglement_number, identity)


def NewNetworkManager(owner: "QuantumRouter", memory_array_name: str) -> "NetworkManager":
Expand Down
4 changes: 2 additions & 2 deletions sequence/resource_management/memory_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ class MemoryInfo:
entangle_time (int): time at which most recent entanglement is achieved.
"""

RAW = "RAW"
OCCUPIED = "OCCUPIED"
RAW = "RAW"
OCCUPIED = "OCCUPIED"
ENTANGLED = "ENTANGLED"

def __init__(self, memory: "Memory", index: int, state="RAW"):
Expand Down
15 changes: 8 additions & 7 deletions sequence/resource_management/resource_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ class ResourceManagerMessage(Message):
Attributes:
ini_protocol_name (str): name of protocol that creates the original REQUEST message.
ini_node_name (str): name of the node that creates the original REQUEST message.
ini_memories_name (str): name of the memories
string (str): for __str__() purpose
ini_memories_name (str): name of the memories.
string (str): for __str__() purpose.
request_fun (func): a function using ResourceManager to search eligible protocols on remote node (if `msg_type` == REQUEST).
is_approved (bool): acceptance/failure of condition function (if `msg_type` == RESPONSE).
paired_protocol (str): protocol that is paired with ini_protocol (if `msg-type` == RESPONSE).
Expand Down Expand Up @@ -84,7 +84,6 @@ def __str__(self) -> str:
return self.string



class ResourceManager:
"""Class to define the resource manager.
Expand Down Expand Up @@ -123,7 +122,7 @@ def load(self, rule: "Rule") -> bool:
"""Method to load rules for entanglement management.
Attempts to add rules to the rule manager.
Will automatically execute rule action if conditions met on a piece of memory.
Will automatically execute rule action if conditions met on a memory.
Args:
rule (Rule): rule to load.
Expand Down Expand Up @@ -174,7 +173,8 @@ def update(self, protocol: "EntanglementProtocol", memory: "Memory", state: str)
"""Method to update state of memory after completion of entanglement management protocol.
Args:
protocol (EntanglementProtocol): concerned protocol. If not None, then remove it from everywhere
protocol (EntanglementProtocol): concerned protocol.
If not None, then remove all references.
memory (Memory): memory to update.
state (str): new state for the memory.
Expand Down Expand Up @@ -252,7 +252,8 @@ def received_message(self, src: str, msg: "ResourceManagerMessage") -> None:

log.logger.debug("{} resource manager receive message from {}: {}".format(self.owner.name, src, msg))
if msg.msg_type is ResourceManagerMsgType.REQUEST:
protocol = msg.req_condition_func(self.waiting_protocols, msg.req_args) # select the wait-for-request protocol to respond to the message
# select the wait-for-request protocol to respond to the message
protocol = msg.req_condition_func(self.waiting_protocols, msg.req_args)
if protocol is not None:
protocol.set_others(msg.ini_protocol_name, msg.ini_node_name, msg.ini_memories_name)
memo_names = [memo.name for memo in protocol.memories]
Expand All @@ -264,7 +265,7 @@ def received_message(self, src: str, msg: "ResourceManagerMessage") -> None:
self.owner.protocols.append(protocol)
protocol.start()
else:
# non of the self.waiting_protocol satisfy the req_condition_func --> is_approved=False
# none of the self.waiting_protocol satisfy the req_condition_func --> is_approved=False
new_msg = ResourceManagerMessage(ResourceManagerMsgType.RESPONSE, protocol=msg.ini_protocol_name,
node=msg.ini_node_name, memories=msg.ini_memories_name, is_approved=False,
paired_protocol=None, paired_node=None, paired_memories=None)
Expand Down
4 changes: 2 additions & 2 deletions sequence/resource_management/rule_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,8 @@ def expire(self, rule: "Rule") -> List["EntanglementProtocol"]:
rule (Rule): rule to remove.
Returns:
List[EntanglementProtocol]: list of protocols created by rule (if any).
Note that when a protocol finishes, it will be removed from rule.protocols
List[EntanglementProtocol]: list of protocols created by rule (if any).
Note that when a protocol finishes, it will be removed from rule.protocols.
"""

self.rules.remove(rule)
Expand Down
43 changes: 22 additions & 21 deletions sequence/topology/node.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,11 +282,13 @@ def __init__(self, name, tl, memo_size=50, seed=None, component_templates=None):
self.app = None

def receive_message(self, src: str, msg: "Message") -> None:
"""Determine what to do when a message is received, based on the msg.receiver
"""Determine what to do when a message is received, based on the msg.receiver.
Args:
src (str): name of node that sends the message
msg (Message): the message
src (str): name of node that sent the message.
msg (Message): the received message.
"""

log.logger.info("{} receive message {} from {}".format(self.name, msg, src))
if msg.receiver == "network_manager":
self.network_manager.received_message(src, msg)
Expand All @@ -304,29 +306,28 @@ def receive_message(self, src: str, msg: "Message") -> None:
break

def init_managers(self, memo_arr_name: str):
'''initialize resource manager and network manager
"""Initialize resource manager and network manager.
Args:
memo_arr_name: the name of the memory array
'''
memo_arr_name (str): the name of the memory array.
"""
resource_manager = ResourceManager(self, memo_arr_name)
network_manager = NewNetworkManager(self, memo_arr_name)
self.set_resource_manager(resource_manager)
self.set_network_manager(network_manager)

def set_resource_manager(self, resource_manager: ResourceManager):
'''set the resource manager
'''
"""Assigns the resource manager."""
self.resource_manager = resource_manager

def set_network_manager(self, network_manager: NetworkManager):
'''set the network manager
'''
"""Assigns the network manager."""
self.network_manager = network_manager

def init(self):
"""Method to initialize quantum router node.
Inherit parent function
Inherit parent function.
"""

super().init()
Expand All @@ -335,8 +336,8 @@ def add_bsm_node(self, bsm_name: str, router_name: str):
"""Method to record connected BSM nodes
Args:
bsm_name (str): the BSM node between nodes self and router_name
router_name (str): the name of another router connected with the BSM node
bsm_name (str): the BSM node between nodes self and router_name.
router_name (str): the name of another router connected with the BSM node.
"""
self.map_to_middle_node[router_name] = bsm_name

Expand All @@ -362,22 +363,22 @@ def set_app(self, app: "RequestApp"):
self.app = app

def reserve_net_resource(self, responder: str, start_time: int, end_time: int, memory_size: int,
target_fidelity: float, entanglement_number: int = 1, id: int = 0) -> None:
target_fidelity: float, entanglement_number: int = 1, identity: int = 0) -> None:
"""Method to request a reservation.
Can be used by local applications.
Can be used by local applications.`1
Args:
responder (str): name of the node with which entanglement is requested.
start_time (int): desired simulation start time of entanglement.
end_time (int): desired simulation end time of entanglement.
memory_size (int): number of memories requested.
target_fidelity (float): desired fidelity of entanglement.
entanglement_number (int): the number of entanglement that the request ask for.
id (int): the ID of the request.
entanglement_number (int): the number of entanglement that the request ask for (default 1).
identity (int): the ID of the request (default 0).
"""

self.network_manager.request(responder, start_time, end_time, memory_size, target_fidelity, entanglement_number, id)
self.network_manager.request(responder, start_time, end_time, memory_size, target_fidelity, entanglement_number, identity)

def get_idle_memory(self, info: "MemoryInfo") -> None:
"""Method for application to receive available memories."""
Expand All @@ -389,8 +390,8 @@ def get_reservation_result(self, reservation: "Reservation", result: bool) -> No
"""Method for application to receive reservations results
Args:
reservation: the reservation created by the reservation protocol at this node (the initiator)
result: whether the reservation has been approved by the responder
reservation (Reservation): the reservation created by the reservation protocol at this node (the initiator).
result (bool): whether the reservation has been approved by the responder.
"""

if self.app:
Expand All @@ -400,7 +401,7 @@ def get_other_reservation(self, reservation: "Reservation"):
"""Method for application to add the approved reservation that is requested by other nodes
Args:
reservation: the reservation created by the other node (this node is the responder)
reservation (Reservation): the reservation created by the other node (this node is the responder)
"""

if self.app:
Expand Down
8 changes: 3 additions & 5 deletions sequence/topology/router_net_topo.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ def _add_bsm_node_to_router(self):
r1.add_bsm_node(bsm, r0_str)

def _add_qconnections(self, config: dict):
'''generate bsm_info, qc_info, and cc_info for the q_connections
'''
"""generate bsm_info, qc_info, and cc_info for the q_connections."""
for q_connect in config.get(Topo.ALL_QC_CONNECT, []):
node1 = q_connect[Topo.CONNECT_NODE_1]
node2 = q_connect[Topo.CONNECT_NODE_2]
Expand Down Expand Up @@ -172,8 +171,7 @@ def _add_qconnections(self, config: dict):
raise NotImplementedError("Unknown type of quantum connection")

def _generate_forwarding_table(self, config: dict):
'''for static routing
'''
"""For static routing."""
graph = Graph()
for node in config[Topo.ALL_NODE]:
if node[Topo.TYPE] == self.QUANTUM_ROUTER:
Expand Down Expand Up @@ -209,7 +207,7 @@ def _generate_forwarding_table(self, config: dict):
path = dijkstra_path(graph, dst_name, src.name)[::-1]
next_hop = path[1]
# routing protocol locates at the bottom of the stack
routing_protocol = src.network_manager.protocol_stack[0] # gaurantee that [0] is the routing protocol?
routing_protocol = src.network_manager.protocol_stack[0] # guarantee that [0] is the routing protocol?
routing_protocol.add_forwarding_rule(dst_name, next_hop)
except exception.NetworkXNoPath:
pass

0 comments on commit 73a5f2a

Please sign in to comment.