-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp_circuit.py
More file actions
66 lines (53 loc) · 1.83 KB
/
Copy pathp_circuit.py
File metadata and controls
66 lines (53 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from .port import *
import numpy as np
from typing import Dict, Any
class PCircuit:
"""Create and holds J and h parameters.
Parameters
----------
n_pbits: string
Identifier of the pipeline (for log purposes).
Attributes
----------
h : np.array((n_pbits, 1))
biases
J : np.array((n_pbits, n_pbits))
weights
ports: dict[str, object]
Circuit ports
"""
def __init__(self, n_pbits: int, ports: Dict[str, Any] = None):
self.n_pbits = n_pbits
self.ports = ports #Kept for copy behavior
self.h = np.zeros((n_pbits,))
self.J = np.zeros((n_pbits, n_pbits))
self._connections = {}
if ports:
self._initialize_ports(ports)
def _initialize_ports(self, port_attrs: Dict[str, Any]) -> None:
"""Initialize ports from attributes dictionary."""
# Build cumulative index mapping respecting port widths
port_indices = {}
idx = 0
for name, port in port_attrs.items():
port_indices[name] = idx
idx += port.width
# Set up each port
for name, port in port_attrs.items():
new_port = Port(name=port.name, width=port.width)
new_port.circuit = self
new_port.index = port_indices[name]
# Check ports name doesn't conflict with reserved attributes.
assert name != "ports"
assert name != "h"
assert name != "J"
setattr(self, name, new_port)
def set_weight(self, from_pbit, to_pbit, weight, sym=True):
self.J[from_pbit, to_pbit] = weight
if sym:
self.J[to_pbit, from_pbit] = weight
def copy(self):
new_circuit = PCircuit(self.n_pbits, self.ports)
new_circuit.J = self.J
new_circuit.h = self.h
return new_circuit