Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Remove pydantic dependency #1738

Merged
merged 4 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ test:
.PHONY: test-fast
test-fast:
poetry install --extras latex
pytest -v --cov=pyquil test/unit
pytest -vx --cov=pyquil test/unit

.PHONY: e2e
e2e:
Expand Down
89 changes: 27 additions & 62 deletions poetry.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ numpy = "^1.22"
scipy = "^1.7.3"
lark = "^0.11.1"
rpcq = "^3.10.0"
pydantic = "^1.10.7"
networkx = ">=2.5"
importlib-metadata = { version = ">=3.7.3,<5", python = "<3.8" }
qcs-sdk-python = "0.16.4"
Expand Down Expand Up @@ -70,6 +69,7 @@ docs = ["Sphinx", "sphinx-rtd-theme", "nbsphinx", "recommonmark", "pandoc", "mat

[tool.poetry.group.dev.dependencies]
setuptools = {version = "^69.0.2", python = ">=3.12"}
mypy = "^1.8.0"

[tool.ruff]
line-length = 120
Expand Down
294 changes: 248 additions & 46 deletions pyquil/external/rpcq.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,270 @@
from typing import Dict, List, Union, Optional, Any
from typing_extensions import Literal
from pydantic import BaseModel, Field
import json
from typing import Dict, List, Union, Optional, Any, Literal

from deprecated.sphinx import deprecated
from rpcq.messages import TargetDevice as TargetQuantumProcessor
from dataclasses import dataclass, field

JsonValue = Union[type(None), bool, int, float, str, List["JsonValue"], Dict[str, "JsonValue"]]

class Operator(BaseModel):
@dataclass
class Operator:
operator: Optional[str] = None
duration: Optional[float] = None
fidelity: Optional[float] = None


def __post_init__(self):
self.duration = float(self.duration) if self.duration is not None else None
self.fidelity = float(self.fidelity) if self.fidelity is not None else None

def _dict(self) -> Dict[str, JsonValue]:
if type(self) is Operator:
raise ValueError("Should be a subclass")
return dict(
operator=self.operator,
duration=self.duration,
fidelity=self.fidelity,
)

@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def dict(self):
return self._dict()

@classmethod
def _parse_obj(cls, dictionary: Dict):
return Operator(**dictionary)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_obj(cls, dictionary: Dict):
return cls._parse_obj(dictionary)


@dataclass
class MeasureInfo(Operator):
qubit: Optional[Union[int, str]] = None
target: Optional[Union[int, str]] = None
operator_type: Literal["measure"] = "measure"


def __post_init__(self):
self.qubit = str(self.qubit)

def _dict(self) -> Dict[str, JsonValue]:
return dict(
operator_type=self.operator_type,
operator=self.operator,
duration=self.duration,
fidelity=self.fidelity,
qubit=self.qubit,
target=self.target,
)

@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def dict(self):
return self._dict()

@classmethod
def _parse_obj(cls, dictionary: Dict) -> "MeasureInfo":
return MeasureInfo(
operator=dictionary.get("operator"),
duration=dictionary.get("duration"),
fidelity=dictionary.get("fidelity"),
qubit=dictionary.get("qubit"),
target=dictionary.get("target"),
)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_obj(cls, dictionary: Dict):
return cls._parse_obj(dictionary)


@dataclass
class GateInfo(Operator):
parameters: List[Union[float, str]] = Field(default_factory=list)
arguments: List[Union[int, str]] = Field(default_factory=list)
parameters: List[Union[float, str]] = field(default_factory=list)
arguments: List[Union[int, str]] = field(default_factory=list)
operator_type: Literal["gate"] = "gate"
MarquessV marked this conversation as resolved.
Show resolved Hide resolved


class Qubit(BaseModel):
def _dict(self) -> Dict[str, JsonValue]:
return dict(
operator_type=self.operator_type,
operator=self.operator,
duration=self.duration,
fidelity=self.fidelity,
parameters=self.parameters,
arguments=self.arguments,
)

@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def dict(self):
return self._dict()

@classmethod
def _parse_obj(cls, dictionary: dict) -> "GateInfo":
return GateInfo(
operator=dictionary.get("operator"),
duration=dictionary.get("duration"),
fidelity=dictionary.get("fidelity"),
parameters=dictionary["parameters"],
arguments=dictionary["arguments"],
)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_obj(cls, dictionary: Dict):
return cls._parse_obj(dictionary)


def _parse_operator(dictionary: dict) -> Union[GateInfo, MeasureInfo]:
operator_type = dictionary["operator_type"]
if operator_type == "measure":
return MeasureInfo._parse_obj(dictionary)
if operator_type == "gate":
return GateInfo._parse_obj(dictionary)
raise ValueError("Should be a subclass of Operator")


@dataclass
class Qubit:
id: int
dead: Optional[bool] = False
gates: List[Union[GateInfo, MeasureInfo]] = Field(default_factory=list)

def dict(self, **kwargs: Any) -> Dict[str, Any]:
exclude = kwargs.get("exclude") or set()
if not self.dead:
exclude.add("dead")
kwargs["exclude"] = exclude
return super().dict(**kwargs)


class Edge(BaseModel):
gates: List[Union[GateInfo, MeasureInfo]] = field(default_factory=list)

def _dict(self) -> Dict[str, JsonValue]:
encoding = dict(
id=self.id,
gates=[g._dict() for g in self.gates]
)
if self.dead:
encoding["dead"] = self.dead
return encoding

@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def dict(self):
return self._dict()

@classmethod
def _parse_obj(cls, dictionary: Dict) -> "Qubit":
return Qubit(
id=dictionary["id"],
dead=bool(dictionary.get("dead")),
gates=[_parse_operator(v) for v in dictionary.get("gates", [])],
)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_obj(cls, dictionary: Dict):
return cls._parse_obj(dictionary)


@dataclass
class Edge:
ids: List[int]
dead: Optional[bool] = False
gates: List[GateInfo] = Field(default_factory=list)
gates: List[GateInfo] = field(default_factory=list)

def _dict(self) -> Dict[str, JsonValue]:
encoding = dict(
ids=self.ids,
gates=[g._dict() for g in self.gates]
)
if self.dead:
encoding["dead"] = self.dead
return encoding

@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def dict(self):
return self._dict()

@classmethod
def _parse_obj(cls, dictionary: dict) -> "Edge":
return Edge(
ids=dictionary["ids"],
dead=bool(dictionary.get("dead")),
gates=[GateInfo._parse_obj(g) for g in dictionary.get("gates", [])]
)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_obj(cls, dictionary: Dict):
return cls._parse_obj(dictionary)


@dataclass
class CompilerISA:
qubits: Dict[str, Qubit] = field(default_factory=dict)
edges: Dict[str, Edge] = field(default_factory=dict)

def _dict(self) -> Dict[str, JsonValue]:
return {
"1Q": {k: q._dict() for k, q in self.qubits.items()},
"2Q": {k: e._dict() for k, e in self.edges.items()}
}

@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def dict(self):
return self._dict()

@classmethod
def _parse_obj(cls, dictionary: Dict):
qubit_dict = dictionary.get("1Q", {})
edge_dict = dictionary.get("2Q", {})
return CompilerISA(
qubits={k: Qubit._parse_obj(v) for k, v in qubit_dict.items()},
edges={k: Edge._parse_obj(v) for k, v in edge_dict.items()},
)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_obj(cls, dictionary: Dict):
return cls._parse_obj(dictionary)

@classmethod
@deprecated(
version="4.7",
reason="No longer requires serialization of RPCQ objects and is dropping Pydantic as a dependency.", # noqa: E501
)
def parse_file(cls, filename: str):
with open(filename, "r") as file:
json_dict = json.load(file)
return cls._parse_obj(json_dict)

def dict(self, **kwargs: Any) -> Dict[str, Any]:
exclude = kwargs.get("exclude") or set()
if not self.dead:
exclude.add("dead")
kwargs["exclude"] = exclude
return super().dict(**kwargs)


class CompilerISA(BaseModel):
qubits: Dict[str, Qubit] = Field(default_factory=dict, alias="1Q")
edges: Dict[str, Edge] = Field(default_factory=dict, alias="2Q")


def add_qubit(quantum_processor: CompilerISA, node_id: int) -> Qubit:
Expand Down Expand Up @@ -79,20 +293,8 @@ def get_edge(quantum_processor: CompilerISA, qubit1: int, qubit2: int) -> Option
return quantum_processor.edges.get(edge_id)


def _edge_ids_from_id(edge_id: str) -> List[int]:
return [int(node_id) for node_id in edge_id.split("-")]


def _compiler_isa_from_dict(data: Dict[str, Dict[str, Any]]) -> CompilerISA:
compiler_isa_data = {
"1Q": {k: {"id": int(k), **v} for k, v in data.get("1Q", {}).items()},
"2Q": {k: {"ids": _edge_ids_from_id(k), **v} for k, v in data.get("2Q", {}).items()},
}
return CompilerISA.parse_obj(compiler_isa_data)


def compiler_isa_to_target_quantum_processor(compiler_isa: CompilerISA) -> TargetQuantumProcessor:
return TargetQuantumProcessor(isa=compiler_isa.dict(by_alias=True), specs={})
return TargetQuantumProcessor(isa=compiler_isa._dict(), specs={})


class Supported1QGate:
Expand Down
Loading
Loading