-
Notifications
You must be signed in to change notification settings - Fork 22
/
circuit_database.py
67 lines (53 loc) · 1.89 KB
/
circuit_database.py
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
67
from abc import ABC, abstractmethod
import tempfile
import uuid
from .compile import compile
import coreir
from .logging import warning
class CircuitDatabaseInterface(ABC):
@abstractmethod
def insert(self, circuit):
pass
@abstractmethod
def clear(self):
pass
class ConservativeCircuitDatabase(CircuitDatabaseInterface):
def insert(self, circuit):
name = circuit.name
new_name = name + "-" + str(uuid.uuid4())
type(circuit).rename(circuit, new_name)
def clear(self):
pass
class CircuitDatabase(CircuitDatabaseInterface):
class Entry:
def __init__(self, name):
self.name = name
self.circuits = {}
def hash(self, circuit):
with tempfile.TemporaryDirectory() as tempdir:
try:
compile(tempdir + "/circuit", circuit, output="coreir", context=coreir.Context())
json_str = open(tempdir + "/circuit.json").read()
except Exception as e:
warning(f"Could not compile circuit: '{str(e)}'. Uniquifying anyway.")
json_str = uuid.uuid4()
return hash(json_str)
def add_circuit(self, circuit):
hash_ = self.hash(circuit)
if hash_ in self.circuits:
index = self.circuits[hash_][0]
else:
index = len(self.circuits)
self.circuits[hash_] = (index, circuit)
if index > 0:
type(circuit).rename(circuit, circuit.name + "_unq" + str(index))
def __repr__(self):
return repr(self.circuits)
def __init__(self):
self.entries = {}
def insert(self, circuit):
name = circuit.name
entry = self.entries.setdefault(name, CircuitDatabase.Entry(name))
entry.add_circuit(circuit)
def clear(self):
self.entries = {}