This repository was archived by the owner on Feb 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgates.py
60 lines (48 loc) · 2.08 KB
/
gates.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
# SPDX-License-Identifier: MIT
# Copyright : JP Morgan Chase & Co and QC Ware
from pyrsistent import pvector, pset, pmap
from pyrsistent.typing import PSet, PMap
from icontract import require # type: ignore
from typing import Union, Sequence, Set
import attr
def _qubit_ids(qubits: Union[int, Sequence[int]]):
return pvector(range(qubits)) if isinstance(qubits,
int) else pvector(qubits)
@attr.s(frozen=True)
class GateDef(object):
"""
A gate definition, consisting only of a name, a set of names
for parameters, and an ordered collection of integer qubit IDs.
GateDefs can also support variable numbers of qubit args if
varargs == true. This is not currently exploited
"""
name = attr.ib(type=str)
parameter_names = attr.ib(type=Set[str], converter=pset)
qubit_ids = attr.ib(type=Sequence[int], converter=_qubit_ids)
has_varargs = attr.ib(type=bool, default=False)
def __str__(self):
return "".join([self.name, "("] +
[",".join([s
for s in self.parameter_names])] + ["), ("] +
[",".join([str(i) for i in self.qubit_ids])] + [")"])
@attr.s(frozen=True)
class Dialect(object):
"""
A "dialect" -- essentially just a named set of gate definitions
"""
name = attr.ib(type=str)
gate_defs = attr.ib(type=PSet[GateDef], converter=pset)
gate_map = attr.ib(type=PMap[str, GateDef], init=False)
def __attrs_post_init__(self):
# build an index by gate name to speed things up a bit
gate_map: PMap[str,
GateDef] = pmap({g.name: g
for g in self.gate_defs})
object.__setattr__(self, "gate_map", gate_map)
def __str__(self):
return "\n ".join([self.name] + [str(g) for g in self.gate_defs])
def has_gate_named(self, name: str) -> bool:
return name in self.gate_map
@require(lambda self, name: self.has_gate_named(name))
def gate_named(self, name: str) -> GateDef:
return self.gate_map[name]