qref 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
qref/__init__.py ADDED
@@ -0,0 +1,44 @@
1
+ # Copyright 2024 PsiQuantum, Corp.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Public API of QREF."""
16
+
17
+ from typing import Any
18
+
19
+ from ._schema_v1 import SchemaV1, generate_schema_v1
20
+
21
+ SCHEMA_GENERATORS = {"v1": generate_schema_v1}
22
+ MODELS = {"v1": SchemaV1}
23
+ LATEST_SCHEMA_VERSION = "v1"
24
+
25
+
26
+ def generate_program_schema(version: str = LATEST_SCHEMA_VERSION) -> dict[str, Any]:
27
+ """Generate Program schema of given version.
28
+
29
+ Args:
30
+ version: version identifier of the schema.
31
+
32
+ Returns:
33
+ A dictionary with JSON schema describing program.
34
+
35
+ Raises:
36
+ ValueError: if `version` does not match any known version schema.
37
+ """
38
+ try:
39
+ return SCHEMA_GENERATORS[version]()
40
+ except KeyError:
41
+ raise ValueError(f"Unknown schema version {version}")
42
+
43
+
44
+ __all__ = ["generate_program_schema", "SchemaV1"]
qref/_schema_v1.py ADDED
@@ -0,0 +1,113 @@
1
+ # Copyright 2024 PsiQuantum, Corp.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Pydantic models used for defining V1 schema of Routine."""
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Annotated, Any, Literal, Optional, Union
20
+
21
+ from pydantic import BaseModel, ConfigDict, Field, StringConstraints
22
+ from pydantic.json_schema import GenerateJsonSchema
23
+
24
+ NAME_PATTERN = "[A-Za-z_][A-Za-z0-9_]*"
25
+ NAMESPACED_NAME_PATTERN = rf"{NAME_PATTERN}\.{NAME_PATTERN}"
26
+
27
+ Name = Annotated[str, StringConstraints(pattern=rf"^{NAME_PATTERN}$")]
28
+ NamespacedName = Annotated[str, StringConstraints(pattern=rf"^{NAMESPACED_NAME_PATTERN}")]
29
+ OptionallyNamespacedName = Annotated[
30
+ str, StringConstraints(pattern=rf"^(({NAME_PATTERN})|({NAMESPACED_NAME_PATTERN}))$")
31
+ ]
32
+ _Value = Union[int, float, str]
33
+
34
+
35
+ class _PortV1(BaseModel):
36
+ name: Name
37
+ direction: Literal["input", "output", "through"]
38
+ size: Optional[_Value]
39
+ model_config = ConfigDict(title="Port")
40
+
41
+
42
+ class _ConnectionV1(BaseModel):
43
+ source: OptionallyNamespacedName
44
+ target: OptionallyNamespacedName
45
+
46
+ model_config = ConfigDict(title="Connection", use_enum_values=True)
47
+
48
+
49
+ class _ResourceV1(BaseModel):
50
+ name: Name
51
+ type: Literal["additive", "multiplicative", "qubits", "other"]
52
+ value: Union[int, float, str, None]
53
+
54
+ model_config = ConfigDict(title="Resource")
55
+
56
+
57
+ class _ParamLinkV1(BaseModel):
58
+ source: Name
59
+ targets: list[NamespacedName]
60
+
61
+ model_config = ConfigDict(title="ParamLink")
62
+
63
+
64
+ class RoutineV1(BaseModel):
65
+ """Description of Routine in V1 schema.
66
+
67
+ Note:
68
+ This is NOT a top-level object in the schema. Instead, RoutineV1 is wrapped in
69
+ SchemaV1.
70
+ """
71
+
72
+ name: Name
73
+ children: list[RoutineV1] = Field(default_factory=list)
74
+ type: Optional[str] = None
75
+ ports: list[_PortV1] = Field(default_factory=list)
76
+ resources: list[_ResourceV1] = Field(default_factory=list)
77
+ connections: list[_ConnectionV1] = Field(default_factory=list)
78
+ input_params: list[Name] = Field(default_factory=list)
79
+ local_variables: list[str] = Field(default_factory=list)
80
+ linked_params: list[_ParamLinkV1] = Field(default_factory=list)
81
+ meta: dict[str, Any] = Field(default_factory=dict)
82
+
83
+ model_config = ConfigDict(title="Routine")
84
+
85
+ def __init__(self, **data: Any):
86
+ super().__init__(**{k: v for k, v in data.items() if v != [] and v != {}})
87
+
88
+
89
+ class SchemaV1(BaseModel):
90
+ """Root object in Program schema V1."""
91
+
92
+ version: Literal["v1"]
93
+ program: RoutineV1
94
+
95
+
96
+ class _GenerateV1JsonSchema(GenerateJsonSchema):
97
+ def generate(self, schema, mode="validation"):
98
+ json_schema = super().generate(schema, mode=mode)
99
+ json_schema["title"] = "FTQC-ready quantum program"
100
+ json_schema["$schema"] = self.schema_dialect
101
+ return json_schema
102
+
103
+ def normalize_name(self, name):
104
+ return name.removeprefix("_").replace("V1", "")
105
+
106
+
107
+ def generate_schema_v1() -> dict[str, Any]:
108
+ """Generate Routine schema V1.
109
+
110
+ The schema is generated from DocumentRootV1 model, and then enriched with
111
+ additional fields "title" and "$schema".
112
+ """
113
+ return SchemaV1.model_json_schema(schema_generator=_GenerateV1JsonSchema)
@@ -0,0 +1,14 @@
1
+ # Copyright 2024 PsiQuantum, Corp.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
@@ -0,0 +1,182 @@
1
+ # Copyright 2024 PsiQuantum, Corp.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Experimental visualization capabilities for QREF.
16
+
17
+ Currently, the visualizations are done with graphviz, which does not suport
18
+ hierarchical structures. Therefore, we have to use a somewhat hacky representation
19
+ of our routines:
20
+
21
+ - The leaf nodes are drawn as a single graphviz node (this is not surprising) with
22
+ Mrecord shape. This allows to visually separate routine name from its ports.
23
+ - The non-leaf nodes are represented as clusters.
24
+ - Clusters can't use Mrecord shape, and so the ports are drawn as separate nodes.
25
+ - Input and output ports are grouped into subgraphs with the same rank, which
26
+ forces all inputs / all outputs to be placed in a single column.
27
+
28
+ Because of the above dichotomy, care has to be taken when constructing edges.
29
+ - If addressing port of a leaf, it must be specified as graphviz port, e.g:
30
+ "root.child:in_0"
31
+ - If addressing port of a non-leaf, you use normal node reference, e.g:
32
+ "root.child.in_0"
33
+ """
34
+
35
+ from argparse import ArgumentParser
36
+ from pathlib import Path
37
+ from typing import Union
38
+
39
+ import graphviz
40
+ import yaml
41
+
42
+ from .. import SchemaV1
43
+
44
+ # Dictionary of default graph attributes, used for non-leaf nodes
45
+ GRAPH_ATTRS = {
46
+ "rankdir": "LR", # Draw left to right (default is top to bottom)
47
+ "fontname": "Helvetica",
48
+ }
49
+
50
+ # Keyword args passed to dag.node for drawing leaf nodes
51
+ LEAF_NODE_KWARGS = {
52
+ "shape": "Mrecord", # Allow drawing leafs split into labels/ports
53
+ "style": "bold", # Bold border
54
+ "color": "#0288f5", # Nice blue color
55
+ "fontsize": "12", # Larger font size then e.g. ports of non-leafs
56
+ }
57
+
58
+ # Keyword args passed to dag.node for drawing ports of non-leaf nodes
59
+ PORT_NODE_KWARGS = {
60
+ "style": "bold", # Bold border
61
+ "color": "#ffa44a", # Orange border color
62
+ "fontsize": "10", # Smaller font size than the rest of the graph
63
+ "shape": "circle",
64
+ }
65
+
66
+ # Additional attributes of subgraphs of ports (ports of the same direction
67
+ # are grouped into such subgraphs)
68
+ PORT_GROUP_ATTRS = {"rank": "same"} # Place all ports in the group in the same column
69
+
70
+ # Additional kwargs passed to dag.subgraph for defining non-leaf clusters
71
+ CLUSTER_KWARGS = {"style": "rounded"} # Make cluster edges rounded
72
+
73
+
74
+ def _format_node_name(node_name, parent):
75
+ """Given a node name and a parent container, format it accordingly.
76
+
77
+ Read the module-level docstring for explanation why different port formats
78
+ of ports are being used.
79
+ """
80
+ if "." not in node_name: # Case 1: parent port (=> port is a graphviz node)
81
+ return node_name
82
+
83
+ # Resolve the child, assume the graph is correct and thus the child exists.
84
+ child_name, port_name = node_name.split(".")
85
+ child = next(iter((child for child in parent.children if child.name == child_name)))
86
+ if child.children: # Case 2: port of non-leaf child (=> port is a graphviz node)
87
+ return node_name
88
+ else: # Case 3: port of leaf child (=> port is an actual port of Mrecord, use ":")
89
+ return f"{child_name}:{port_name}"
90
+
91
+
92
+ def _add_nonleaf_ports(ports, parent_cluster, parent_path: str, group_name):
93
+ with parent_cluster.subgraph(
94
+ name=f"{parent_path}:{group_name}", graph_attr=PORT_GROUP_ATTRS
95
+ ) as subgraph:
96
+ for port in ports:
97
+ subgraph.node(name=f"{parent_path}.{port.name}", label=port.name, **PORT_NODE_KWARGS)
98
+
99
+
100
+ def _split_ports(ports):
101
+ input_ports = []
102
+ output_ports = []
103
+ for port in ports:
104
+ if port.direction == "input":
105
+ input_ports.append(port)
106
+ elif port.direction == "output":
107
+ output_ports.append(port)
108
+ else:
109
+ raise ValueError("Bi-directional ports are not yet supported for rendering")
110
+ return input_ports, output_ports
111
+
112
+
113
+ def _add_nonleaf(routine, dag: graphviz.Digraph, parent_path: str) -> None:
114
+ input_ports, output_ports = _split_ports(routine.ports)
115
+ full_path = f"{parent_path}.{routine.name}"
116
+
117
+ with dag.subgraph(
118
+ name=f"cluster_{full_path}", graph_attr={"label": routine.name, **CLUSTER_KWARGS}
119
+ ) as cluster:
120
+ _add_nonleaf_ports(input_ports, cluster, full_path, "inputs")
121
+ _add_nonleaf_ports(output_ports, cluster, full_path, "outputs")
122
+
123
+ for child in routine.children:
124
+ _add_routine(child, cluster, f"{parent_path}.{routine.name}")
125
+
126
+ for connection in routine.connections:
127
+ cluster.edge(
128
+ full_path + "." + _format_node_name(connection.source, routine),
129
+ full_path + "." + _format_node_name(connection.target, routine),
130
+ )
131
+
132
+
133
+ def _ports_row(ports) -> str:
134
+ return "{" + "|".join(f"<{port.name}> {port.name}" for port in ports) + "}"
135
+
136
+
137
+ def _add_leaf(routine, dag: graphviz.Digraph, parent_path: str) -> None:
138
+ input_ports, output_ports = _split_ports(routine.ports)
139
+ label = f"{{ {_ports_row(input_ports)} | {routine.name } | {_ports_row(output_ports)} }}"
140
+ dag.node(".".join((parent_path, routine.name)), label=label, **LEAF_NODE_KWARGS)
141
+
142
+
143
+ def _add_routine(routine, dag: graphviz.Digraph, parent_path: str = "") -> None:
144
+ if routine.children:
145
+ _add_nonleaf(routine, dag, parent_path)
146
+ else:
147
+ _add_leaf(routine, dag, parent_path)
148
+
149
+
150
+ def _ensure_schema_v1(data: Union[dict, SchemaV1]) -> SchemaV1:
151
+ return data if isinstance(data, SchemaV1) else SchemaV1(**data)
152
+
153
+
154
+ def to_graphviz(data: Union[dict, SchemaV1]) -> graphviz.Digraph:
155
+ """Convert routine encoded with v1 schema to a graphviz DAG."""
156
+ data = _ensure_schema_v1(data)
157
+ dag = graphviz.Digraph(graph_attr=GRAPH_ATTRS)
158
+ _add_routine(data.program, dag)
159
+ return dag
160
+
161
+
162
+ def render_entry_point():
163
+ parser = ArgumentParser()
164
+ parser.add_argument(
165
+ "input", help="Path to the YAML or JSON file with Routine in V1 schema", type=Path
166
+ )
167
+ parser.add_argument(
168
+ "output",
169
+ help=(
170
+ "Path to the output file. File format is determined based on the extension, "
171
+ "which should be either .svg or .pdf"
172
+ ),
173
+ type=Path,
174
+ )
175
+
176
+ args = parser.parse_args()
177
+
178
+ with open(args.input) as f:
179
+ routine = SchemaV1.model_validate(yaml.safe_load(f))
180
+
181
+ dag = to_graphviz(routine)
182
+ dag.render(args.output.with_suffix(""), format=args.output.suffix.strip("."))
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,161 @@
1
+ Metadata-Version: 2.1
2
+ Name: qref
3
+ Version: 0.1.0
4
+ Summary: Quantum Resource Estimation Format
5
+ License: Apache 2.0
6
+ Author: PsiQuantum, Corp.
7
+ Requires-Python: >=3.9,<4.0
8
+ Classifier: License :: Other/Proprietary License
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Programming Language :: Python :: 3.9
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Dist: graphviz (>=0.20.3,<0.21.0)
15
+ Requires-Dist: pydantic (>=2.0,<3.0)
16
+ Description-Content-Type: text/markdown
17
+
18
+ # QREF
19
+ Quantum Resource Estimation Format (QREF) is an open format for representing
20
+ quantum algorithms, optimized for usage in quantum resource estimation (QRE).
21
+
22
+ QREF comprises:
23
+
24
+ - Definition of data format, formalized as a JSON schema.
25
+ - A Python library for validation of quantum programs written in QREF format using [Pydantic](https://docs.pydantic.dev/).
26
+ - Rudimentary visualization tool `qref-render`.
27
+
28
+ ## Installation
29
+
30
+ Using QREF data format does not require installation - you can easily write quantum
31
+ programs in YAML or JSON.
32
+
33
+ To install QREF Python package, clone this repository and install it as usual with `pip`:
34
+
35
+ ```bash
36
+ # Clone QREF repo (you can use HTTP link as well)
37
+ git clone git@github.com:PsiQ/qref.git
38
+ cd qref
39
+ pip install .
40
+ ```
41
+
42
+ ## QREF format
43
+
44
+ QREF format represents quantum programs as a hierarchical directed acyclic graphs (DAGs).
45
+ That's a mouthful, so let us unpack what it means:
46
+
47
+ - *hierarchical*: each node can contain subgraphs, i.e. routines can be nested inside
48
+ larger routines.
49
+ - *directed*: information flow is unidirectional, and the direction is unambiguous.
50
+ - *acyclic*: meaning there are no loops.
51
+
52
+ Consider the following hierarchical DAG of a hypothetical quantum program:
53
+
54
+ ![program example](example_routine.svg)
55
+
56
+ It can be succinctly written in QREF format as:
57
+
58
+
59
+ ```yaml
60
+ version: v1
61
+ program:
62
+ name: my_algorithm
63
+ ports:
64
+ - direction: input
65
+ name: in_0
66
+ size: 2
67
+ - direction: input
68
+ name: in_1
69
+ size: 2
70
+ - direction: output
71
+ name: out_0
72
+ size: 4
73
+ children:
74
+ - name: subroutine_1
75
+ ports:
76
+ - direction: input
77
+ name: in_0
78
+ size: 2
79
+ - direction: output
80
+ name: out_0
81
+ size: 3
82
+ - name: subroutine_2
83
+ ports:
84
+ - direction: input
85
+ name: in_0
86
+ size: 2
87
+ - direction: output
88
+ name: out_0
89
+ size: 1
90
+ - direction: output
91
+ name: out_1
92
+ size: 1
93
+ - name: merge
94
+ ports:
95
+ - direction: input
96
+ name: in_0
97
+ size: 1
98
+ - direction: input
99
+ name: in_1
100
+ size: 1
101
+ - direction: input
102
+ name: in_2
103
+ size: 2
104
+ - direction: output
105
+ name: out_0
106
+ size: 4
107
+ connections:
108
+ - source: in_0
109
+ target: subroutine_1.in_0
110
+ - source: in_1
111
+ target: subroutine_2.in_0
112
+ - source: subroutine_1.out_0
113
+ target: merge.in_2
114
+ - source: subroutine_2.out_0
115
+ target: merge.in_0
116
+ - source: subroutine_2.out_1
117
+ target: merge.in_1
118
+ - source: merge.out_0
119
+ target: out_0
120
+ ```
121
+
122
+
123
+ For full description of QREF format, check our [docs](https://example.com).
124
+
125
+ ## Using QREF package
126
+
127
+ ### Using JSON schema for validating data in QREF format
128
+
129
+ JSON schema for QREF format can be obtained by calling `generate_program_schema` function.
130
+ Such schema can be then used for validating user's input, e.g. using `jsonschema` package:
131
+
132
+ ```python
133
+ from jsonschema import validate
134
+ from qref import generate_program_schema
135
+
136
+ # Hypothetical function loading your data as native Python dictionary.
137
+ data = load_some_program()
138
+ schema = generate_program_schema()
139
+
140
+ # This will raise if there are some validation errors.
141
+ validate(schema, data)
142
+ ```
143
+
144
+ ### Validation using Pydantic models
145
+
146
+ If you are familiar with Pydantic, you might find it easier to work with QREF Pydantic
147
+ models instead of interacting with JSON schema directly. In the example below, we create
148
+ an instance of `SchemaV1` model from validated data stored in QREF format:
149
+
150
+ ```python
151
+ from qref import SchemaV1
152
+
153
+ data = load_some_program()
154
+
155
+ # This will raise if data is not valid
156
+ program = SchemaV1.model_validate(data)
157
+ ```
158
+
159
+ ## Development
160
+
161
+ In order to install development environment or build documentation locally, please refer to [Development Guide](TODO).
@@ -0,0 +1,9 @@
1
+ qref/__init__.py,sha256=uMtizSoCcJi9QCmf63qQRA1lw8EsBHrx0CP9asheLUc,1342
2
+ qref/_schema_v1.py,sha256=mauU9DaIBbhuhPa5zfKQSC9psjbvt9SgzWo87iwiYd8,3684
3
+ qref/experimental/__init__.py,sha256=3FgqI0lVKJqOfNerLss4QDdJaeFW_3RcO31mvZI6ax0,582
4
+ qref/experimental/rendering.py,sha256=XHNauOlSpYUGn_jKEIBnh0l1wERG2q8lqXzNRlNgVcM,6805
5
+ qref-0.1.0.dist-info/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
6
+ qref-0.1.0.dist-info/METADATA,sha256=HJw29O_7bNlEb8nBpPSotoJCex0xGD5DCS2KFOFiek0,4237
7
+ qref-0.1.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
8
+ qref-0.1.0.dist-info/entry_points.txt,sha256=0r4egTAx84xjcp_W-cpOm9kuvc-TQ2DmNMybjcafHRs,78
9
+ qref-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ qref-render=qref.experimental.rendering:render_entry_point
3
+