├── .gitignore
├── LICENSE
├── README.md
├── dist
├── pygridsynth-1.1.0-py3-none-any.whl
└── pygridsynth-1.1.0.tar.gz
├── pygridsynth
├── __init__.py
├── __main__.py
├── diophantine.py
├── grid_op.py
├── gridsynth.py
├── mymath.py
├── myplot.py
├── normal_form.py
├── odgp.py
├── region.py
├── ring.py
├── synthesis_of_cliffordT.py
├── tdgp.py
├── to_upright.py
└── unitary.py
├── pyproject.toml
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | **/__pycache__/**
2 | build/
3 | .venv/
4 | pygridsynth.egg-info/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pygridsynth
2 |
3 | `pygridsynth` is a Python library for approximating arbitrary Z-rotations using the Clifford+T gate set, based on a given angle `θ` and tolerance `ε`. It is particularly useful for addressing approximate gate synthesis problems in quantum computing and algorithm research.
4 |
5 | ## Features
6 |
7 | - **Inspired by Established Work:** This library is based on P. Selinger's gridsynth program ([newsynth](https://www.mathstat.dal.ca/~selinger/newsynth/)), adapted for Python with additional functionality.
8 | - **High Precision:** Utilizes the `mpmath` library to support high-precision calculations.
9 | - **Customizable:** Allows adjustment of calculation precision (`dps`) and verbosity of output.
10 | - **Graph Visualization:** Provides an option to visualize decomposition results as a graph.
11 |
12 | ## Installation
13 |
14 | You can install `pygridsynth` via pip:
15 |
16 | ```bash
17 | pip install pygridsynth
18 | ```
19 |
20 | Or, to install from source:
21 |
22 | ```bash
23 | pip install git+https://github.com/quantum-programming/pygridsynth.git
24 | ```
25 |
26 | ## Usage
27 |
28 | `pygridsynth` can be used as a command-line tool.
29 |
30 | ### Command-Line Example
31 |
32 | ```bash
33 | python -m pygridsynth [options]
34 | ```
35 |
36 | ### Arguments
37 |
38 | - `theta` (required): The rotation angle to decompose, specified in radians (e.g., `0.5`).
39 | - `epsilon` (required): The allowable error tolerance (e.g., `1e-10`).
40 |
41 | ### Options
42 |
43 | - `--dps`: Sets the calculation precision (default: `128`).
44 | - `--dtimeout`, `-dt`: Sets the timeout for solving diophantine equations in milliseconds (default: `200`).
45 | - `--ftimeout`, `-ft`: Sets the timeout for factorization in milliseconds (default: `50`).
46 | - `--verbose`, `-v`: Enables detailed output.
47 | - `--time`, `-t`: Measures the execution time.
48 | - `--showgraph`, `-g`: Displays the decomposition result as a graph.
49 |
50 | ### Example Execution
51 |
52 | ```bash
53 | python -m pygridsynth 0.5 1e-50 --dps 256 --verbose --time
54 | ```
55 |
56 | This command will:
57 | 1. Compute the Clifford+T gate decomposition of a Z-rotation gate with $\theta = 0.5$ and $\epsilon = 0.01$.
58 | 2. Set the calculation precision to 256 decimal places.
59 | 3. Display detailed output and measure the execution time.
60 |
61 | ## Using as a Library
62 |
63 | You can also use `pygridsynth` directly in your scripts:
64 |
65 | ```python
66 | from pygridsynth.gridsynth import gridsynth_gates
67 | import mpmath
68 |
69 | mpmath.mp.dps = 128
70 | theta = mpmath.mpmathify("0.5")
71 | epsilon = mpmath.mpmathify("1e-10")
72 |
73 | gates = gridsynth_gates(theta=theta, epsilon=epsilon)
74 | print(gates)
75 | ```
76 |
77 | ## Contributing
78 |
79 | Bug reports and feature requests are welcome. Please submit them via the [GitHub repository](https://github.com/quantum-programming/pygridsynth) Issues section. Contributions must comply with the GNU General Public License v3 or later.
80 |
81 | ## License
82 |
83 | This project is licensed under the GNU General Public License v3 or later.
84 |
85 | ## References
86 |
87 | - Brett Giles and Peter Selinger. Remarks on Matsumoto and Amano's normal form for single-qubit Clifford+T operators, 2019.
88 | - Ken Matsumoto and Kazuyuki Amano. Representation of Quantum Circuits with Clifford and π/8 Gates, 2008.
89 | - Neil J. Ross and Peter Selinger. Optimal ancilla-free Clifford+T approximation of z-rotations, 2016.
90 | - Peter Selinger. Efficient Clifford+T approximation of single-qubit operators, 2014.
91 | - Peter Selinger and Neil J. Ross. Exact and approximate synthesis of quantum circuits. https://www.mathstat.dal.ca/~selinger/newsynth/, 2018.
92 | - Vadym Kliuchnikov, Dmitri Maslov, and Michele Mosca. Fast and efficient exact synthesis of single qubit unitaries generated by Clifford and T gates, 2013.
--------------------------------------------------------------------------------
/dist/pygridsynth-1.1.0-py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quantum-programming/pygridsynth/5868c650ce819227adcd80eaa8d8e065f4001022/dist/pygridsynth-1.1.0-py3-none-any.whl
--------------------------------------------------------------------------------
/dist/pygridsynth-1.1.0.tar.gz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/quantum-programming/pygridsynth/5868c650ce819227adcd80eaa8d8e065f4001022/dist/pygridsynth-1.1.0.tar.gz
--------------------------------------------------------------------------------
/pygridsynth/__init__.py:
--------------------------------------------------------------------------------
1 | from .gridsynth import *
2 |
--------------------------------------------------------------------------------
/pygridsynth/__main__.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import mpmath
3 |
4 | from .gridsynth import gridsynth_gates
5 |
6 |
7 | def main():
8 | parser = argparse.ArgumentParser()
9 |
10 | parser.add_argument('theta', type=str)
11 | parser.add_argument('epsilon', type=str)
12 | parser.add_argument('--dps', type=int, default=128)
13 | parser.add_argument('--dtimeout', '-dt', type=int, default=200)
14 | parser.add_argument('--ftimeout', '-ft', type=int, default=50)
15 | parser.add_argument('--verbose', '-v', action='store_true')
16 | parser.add_argument('--time', '-t', action='store_true')
17 | parser.add_argument('--showgraph', '-g', action='store_true')
18 |
19 | args = parser.parse_args()
20 | mpmath.mp.dps = args.dps
21 | mpmath.mp.pretty = True
22 | theta = mpmath.mpmathify(args.theta)
23 | epsilon = mpmath.mpmathify(args.epsilon)
24 |
25 | gates = gridsynth_gates(theta=theta, epsilon=epsilon,
26 | verbose=args.verbose, measure_time=args.time,
27 | show_graph=args.showgraph)
28 | print(gates)
29 | return gates
30 |
31 |
32 | if __name__ == "__main__":
33 | main()
34 |
--------------------------------------------------------------------------------
/pygridsynth/diophantine.py:
--------------------------------------------------------------------------------
1 | import warnings
2 | import numbers
3 | import math
4 | import random
5 | import time
6 |
7 | from .ring import ZRootTwo, ZOmega, DOmega
8 |
9 | NO_SOLUTION = "no solution"
10 |
11 |
12 | def _find_factor(n, factoring_timeout, M=128):
13 | if not (n & 1) and n > 2:
14 | return 2
15 |
16 | a = random.randint(1, n)
17 | y, r, k = a, 1, 0
18 | L = int(10 ** (len(str(n)) / 4) * 1.1774 + 10)
19 |
20 | start_factoring = time.time()
21 | while True:
22 | x = y + n
23 | while k < r:
24 | q = 1
25 | y0 = y
26 | for _ in range(M):
27 | y = (y * y + a) % n
28 | q = q * (x - y) % n
29 | k += 1
30 | if k == r:
31 | break
32 | g = math.gcd(q, n)
33 | if g != 1:
34 | if g == n:
35 | y = y0
36 | for _ in range(M):
37 | y = (y * y + a) % n
38 | g = math.gcd(x - y, n)
39 | if g != 1:
40 | break
41 | return None if g == n else g
42 | if k >= L or (time.time() - start_factoring) * 1000 >= factoring_timeout:
43 | return None
44 | r <<= 1
45 |
46 |
47 | def _sqrt_negative_one(p, L=100):
48 | for _ in range(L):
49 | b = random.randint(1, p - 1)
50 | h = pow(b, (p - 1) >> 2, p)
51 | r = h * h % p
52 | if r == p - 1:
53 | return h
54 | elif r != 1:
55 | return None
56 |
57 |
58 | class F_p2():
59 | base = 0
60 | p = 0
61 |
62 | def __init__(self, a, b):
63 | if a < 0 or a >= self.__class__.p:
64 | a %= self.__class__.p
65 | if b < 0 or b >= self.__class__.p:
66 | b %= self.__class__.p
67 | self._a = a
68 | self._b = b
69 |
70 | @property
71 | def a(self):
72 | return self._a
73 |
74 | @property
75 | def b(self):
76 | return self._b
77 |
78 | def __mul__(self, other):
79 | if isinstance(other, self.__class__):
80 | new_a = self._a * other.a + self._b * other.b % self.__class__.p * self.__class__.base
81 | new_b = self._a * other.b + self._b * other.a
82 | return self.__class__(new_a, new_b)
83 | else:
84 | return NotImplemented
85 |
86 | def __pow__(self, other):
87 | if isinstance(other, numbers.Integral):
88 | if other < 0:
89 | return NotImplemented
90 | else:
91 | new = self.__class__(1, 0)
92 | tmp = self
93 | while other > 0:
94 | if other & 1:
95 | new *= tmp
96 | tmp *= tmp
97 | other >>= 1
98 | return new
99 | else:
100 | return NotImplemented
101 |
102 |
103 | def _root_mod(x, p, L=100):
104 | x = x % p
105 | if p == 2:
106 | return x
107 | if x == 0:
108 | return 0
109 | if not (p & 1) and p > 2:
110 | return None
111 | if pow(x, (p - 1) // 2, p) != 1:
112 | return None
113 |
114 | for _ in range(L):
115 | b = random.randint(1, p - 1)
116 | r = pow(b, p - 1, p)
117 | if r != 1:
118 | return None
119 |
120 | base = (b * b + p - x) % p
121 | if pow(base, (p - 1) // 2, p) != 1:
122 | F_p2.p = p
123 | F_p2.base = base
124 | return (F_p2(b, 1) ** ((p + 1) // 2)).a
125 |
126 |
127 | def _is_prime(n, L=4):
128 | if n < 0:
129 | n = -n
130 | if n == 0 or n == 1:
131 | return False
132 | if not (n & 1):
133 | return True if n == 2 else False
134 |
135 | r, d = 0, n - 1
136 | while not (d & 1):
137 | r += 1
138 | d >>= 1
139 | for _ in range(L):
140 | a = random.randint(1, n - 1)
141 | a = pow(a, d, n)
142 | if a == 1:
143 | return True
144 |
145 | for _ in range(r):
146 | if a == n - 1:
147 | return True
148 | a = a * a % n
149 | return False
150 |
151 |
152 | def _decompose_relatively_int_prime(partial_facs):
153 | u = 1
154 | stack = list(reversed(partial_facs))
155 | facs = []
156 | while len(stack):
157 | b, k_b = stack.pop()
158 | i = 0
159 | while True:
160 | if i >= len(facs):
161 | if b == 1 or b == -1:
162 | if b == -1 and (k_b & 1):
163 | u = -u
164 | else:
165 | facs.append((b, k_b))
166 | break
167 | a, k_a = facs[i]
168 | if a == b or a == -b:
169 | if a == -b and (k_b & 1):
170 | u = -u
171 | facs[i] = (a, k_a + k_b)
172 | break
173 | else:
174 | g = math.gcd(a, b)
175 | if g == 1 or g == -1:
176 | i += 1
177 | continue
178 | else:
179 | partial_facs = [(a // g, k_a), (g, k_a + k_b)]
180 | u_a, facs_a = _decompose_relatively_int_prime(partial_facs)
181 | u *= u_a
182 | facs[i] = facs_a[0]
183 | facs = facs + facs_a[1:]
184 | stack.append((b // g, k_b))
185 | break
186 |
187 | return u, facs
188 |
189 |
190 | def _adj_decompose_int_prime(p):
191 | if p < 0:
192 | p = -p
193 | if p == 0 or p == 1:
194 | return ZOmega.from_int(p)
195 | if p == 2:
196 | return ZOmega(-1, 0, 1, 0)
197 |
198 | if _is_prime(p):
199 | if p & 0b11 == 1:
200 | h = _sqrt_negative_one(p)
201 | if h is None:
202 | return None
203 | else:
204 | t = ZOmega.gcd(h + ZOmega(0, 1, 0, 0), p)
205 | return t if t.conj * t == p or t.conj * t == -p else None
206 | elif p & 0b111 == 3:
207 | h = _root_mod(-2, p)
208 | if h is None:
209 | return None
210 | else:
211 | t = ZOmega.gcd(h + ZOmega(1, 0, 1, 0), p)
212 | return t if t.conj * t == p or t.conj * t == -p else None
213 | elif p & 0b111 == 7:
214 | h = _root_mod(2, p)
215 | if h is not None:
216 | return NO_SOLUTION
217 | else:
218 | return None
219 | else:
220 | return None
221 | else:
222 | if p & 0b111 == 7:
223 | h = _root_mod(2, p)
224 | if h is not None:
225 | return NO_SOLUTION
226 | else:
227 | return None
228 | else:
229 | return None
230 |
231 |
232 | def _adj_decompose_int_prime_power(p, k):
233 | if not (k & 1):
234 | return p ** (k // 2)
235 | else:
236 | t = _adj_decompose_int_prime(p)
237 | if t is None or t == NO_SOLUTION:
238 | return t
239 | else:
240 | return t ** k
241 |
242 |
243 | def _adj_decompose_int(n, diophantine_timeout, factoring_timeout, start_time):
244 | if n < 0:
245 | n = -n
246 | facs = [(n, 1)]
247 | t = ZOmega.from_int(1)
248 | while len(facs):
249 | p, k = facs.pop()
250 | t_p = _adj_decompose_int_prime_power(p, k)
251 | if t_p == NO_SOLUTION:
252 | return NO_SOLUTION
253 | elif t_p is None:
254 | fac = _find_factor(p, factoring_timeout)
255 | if fac is None:
256 | facs.append((p, k))
257 | if (time.time() - start_time) * 1000 >= diophantine_timeout:
258 | return NO_SOLUTION
259 | else:
260 | facs.append((p // fac, k))
261 | facs.append((fac, k))
262 | _, facs = _decompose_relatively_int_prime(facs)
263 | else:
264 | t *= t_p
265 | return t
266 |
267 |
268 | def _adj_decompose_selfassociate(xi, diophantine_timeout, factoring_timeout, start_time):
269 | # xi \sim xi.conj_sq2
270 | if xi == 0:
271 | return ZOmega.from_int(0)
272 |
273 | n = math.gcd(xi.a, xi.b)
274 | r = xi // n
275 | t1 = _adj_decompose_int(n, diophantine_timeout, factoring_timeout, start_time)
276 | t2 = ZOmega(0, 0, 1, 1) if r % ZRootTwo(0, 1) == 0 else 1
277 | if t1 is None:
278 | return None
279 | elif t1 == NO_SOLUTION:
280 | return NO_SOLUTION
281 | else:
282 | return t1 * t2
283 |
284 |
285 | def _decompose_relatively_zomega_prime(partial_facs):
286 | u = 1
287 | stack = list(reversed(partial_facs))
288 | facs = []
289 | while len(stack):
290 | b, k_b = stack.pop()
291 | i = 0
292 | while True:
293 | if i >= len(facs):
294 | if ZRootTwo.sim(b, 1):
295 | u *= b ** k_b
296 | else:
297 | facs.append((b, k_b))
298 | break
299 | a, k_a = facs[i]
300 | if ZRootTwo.sim(a, b):
301 | u *= (b // a) ** k_b
302 | facs[i] = (a, k_a + k_b)
303 | break
304 | else:
305 | g = ZRootTwo.gcd(a, b)
306 | if ZRootTwo.sim(g, 1):
307 | i += 1
308 | continue
309 | else:
310 | partial_facs = [(a // g, k_a), (g, k_a + k_b)]
311 | u_a, facs_a = _decompose_relatively_zomega_prime(partial_facs)
312 | u *= u_a
313 | facs[i] = facs_a[0]
314 | facs = facs + facs_a[1:]
315 | stack.append((b // g, k_b))
316 | break
317 |
318 | return u, facs
319 |
320 |
321 | def _adj_decompose_zomega_prime(eta):
322 | p = eta.norm
323 |
324 | if p < 0:
325 | p = -p
326 | if p == 0 or p == 1:
327 | return ZOmega.from_int(p)
328 | elif p == 2:
329 | return ZOmega(-1, 0, 1, 0)
330 |
331 | if _is_prime(p):
332 | if p & 0b11 == 1:
333 | h = _sqrt_negative_one(p)
334 | if h is None:
335 | return None
336 | else:
337 | t = ZOmega.gcd(h + ZOmega(0, 1, 0, 0), eta)
338 | return t if ZRootTwo.sim(t.conj * t, eta) else None
339 | elif p & 0b111 == 3:
340 | h = _root_mod(-2, p)
341 | if h is None:
342 | return None
343 | else:
344 | t = ZOmega.gcd(h + ZOmega(1, 0, 1, 0), eta)
345 | return t if ZRootTwo.sim(t.conj * t, eta) else None
346 | elif p & 0b111 == 7:
347 | h = _root_mod(2, p)
348 | if h is not None:
349 | return NO_SOLUTION
350 | else:
351 | return None
352 | else:
353 | return None
354 | else:
355 | if p & 0b111 == 7:
356 | h = _root_mod(2, p)
357 | if h is not None:
358 | return NO_SOLUTION
359 | else:
360 | return None
361 | else:
362 | return None
363 |
364 |
365 | def _adj_decompose_zomega_prime_power(eta, k):
366 | if not (k & 1):
367 | return eta ** (k // 2)
368 | else:
369 | t = _adj_decompose_zomega_prime(eta)
370 | if t is None or t == NO_SOLUTION:
371 | return t
372 | else:
373 | return t ** k
374 |
375 |
376 | def _adj_decompose_selfcoprime(xi, diophantine_timeout, factoring_timeout, start_time):
377 | # gcd(xi, xi.conj_sq2) = 1
378 | facs = [(xi, 1)]
379 | t = ZOmega.from_int(1)
380 | while len(facs):
381 | eta, k = facs.pop()
382 | t_eta = _adj_decompose_zomega_prime_power(eta, k)
383 | if t_eta == NO_SOLUTION:
384 | return NO_SOLUTION
385 | elif t_eta is None:
386 | n = eta.norm
387 | if n < 0:
388 | n = -n
389 | fac_n = _find_factor(n, factoring_timeout)
390 | if fac_n is None:
391 | facs.append((eta, k))
392 | if (time.time() - start_time) * 1000 >= diophantine_timeout:
393 | return NO_SOLUTION
394 | else:
395 | fac = ZRootTwo.gcd(xi, fac_n)
396 | facs.append((eta // fac, k))
397 | facs.append((fac, k))
398 | _, facs = _decompose_relatively_zomega_prime(facs)
399 | else:
400 | t *= t_eta
401 | return t
402 |
403 |
404 | def _adj_decompose(xi, diophantine_timeout, factoring_timeout, start_time):
405 | if xi == 0:
406 | return ZOmega.from_int(0)
407 |
408 | d = ZRootTwo.gcd(xi, xi.conj_sq2)
409 | eta = xi // d
410 | t1 = _adj_decompose_selfassociate(d, diophantine_timeout, factoring_timeout, start_time)
411 | if t1 == NO_SOLUTION:
412 | return NO_SOLUTION
413 | else:
414 | t2 = _adj_decompose_selfcoprime(eta, diophantine_timeout, factoring_timeout, start_time)
415 | if t2 == NO_SOLUTION:
416 | return NO_SOLUTION
417 | else:
418 | return t1 * t2
419 |
420 |
421 | def _diophantine(xi, diophantine_timeout, factoring_timeout, start_time):
422 | if xi == 0:
423 | return ZOmega.from_int(0)
424 | elif xi < 0 or xi.conj_sq2 < 0:
425 | return NO_SOLUTION
426 |
427 | t = _adj_decompose(xi, diophantine_timeout, factoring_timeout, start_time)
428 | if t == NO_SOLUTION:
429 | return NO_SOLUTION
430 | else:
431 | xi_associate = ZRootTwo.from_zomega(t.conj * t)
432 | u = xi // xi_associate
433 | v = u.sqrt()
434 | if v is None:
435 | warnings.warn("cannot find square root of u")
436 | return NO_SOLUTION
437 | else:
438 | return v * t
439 |
440 |
441 | def diophantine_dyadic(xi, diophantine_timeout=200, factoring_timeout=50):
442 | k_div_2, k_mod_2 = xi.k >> 1, xi.k & 1
443 |
444 | t = _diophantine(xi.alpha * ZRootTwo(1, 1) if k_mod_2 else xi.alpha,
445 | diophantine_timeout=diophantine_timeout, factoring_timeout=factoring_timeout,
446 | start_time=time.time())
447 | if t == NO_SOLUTION:
448 | return NO_SOLUTION
449 | else:
450 | if k_mod_2:
451 | t *= ZOmega(0, -1, 1, 0)
452 | return DOmega(t, k_div_2 + k_mod_2)
453 |
--------------------------------------------------------------------------------
/pygridsynth/grid_op.py:
--------------------------------------------------------------------------------
1 | from functools import cached_property
2 | import mpmath
3 |
4 | from .ring import ZOmega, DOmega
5 |
6 |
7 | class EllipsePair():
8 | def __init__(self, A, B):
9 | self.A = A
10 | self.B = B
11 |
12 | @property
13 | def skew(self):
14 | return self.A.skew + self.B.skew
15 |
16 | @property
17 | def bias(self):
18 | return self.B.bias / self.A.bias
19 |
20 | def __rmul__(self, other):
21 | if isinstance(other, GridOp):
22 | return self.__class__(other * self.A, other.conj_sq2 * self.B)
23 | else:
24 | return NotImplemented
25 |
26 |
27 | class GridOp():
28 | def __init__(self, u0, u1):
29 | self._u0 = u0
30 | self._u1 = u1
31 | # d0 + b0 + d1 + b1 : even
32 | # a0 + c0 + a1 + c1 : even
33 |
34 | @property
35 | def u0(self):
36 | return self._u0
37 |
38 | @property
39 | def u1(self):
40 | return self._u1
41 |
42 | @property
43 | def a0(self):
44 | return self._u0.a
45 |
46 | @property
47 | def b0(self):
48 | return self._u0.b
49 |
50 | @property
51 | def c0(self):
52 | return self._u0.c
53 |
54 | @property
55 | def d0(self):
56 | return self._u0.d
57 |
58 | @property
59 | def a1(self):
60 | return self._u1.a
61 |
62 | @property
63 | def b1(self):
64 | return self._u1.b
65 |
66 | @property
67 | def c1(self):
68 | return self._u1.c
69 |
70 | @property
71 | def d1(self):
72 | return self._u1.d
73 |
74 | def __str__(self):
75 | return (f"[[{self.d0}{self.c0 - self.a0:+}/√2, {self.d1}{self.c1 - self.a1:+}/√2],\n"
76 | f" [{self.b0}{self.c0 + self.a0:+}/√2, {self.b1}{self.c1 + self.a1:+}/√2]]")
77 |
78 | @cached_property
79 | def _det_vec(self):
80 | return self._u0.conj * self._u1
81 |
82 | @cached_property
83 | def is_special(self):
84 | v = self._det_vec
85 | return v.a + v.c == 0 and (v.b == 1 or v.b == -1)
86 |
87 | @cached_property
88 | def toMat(self):
89 | return mpmath.matrix([[self._u0.real, self._u1.real], [self._u0.imag, self._u1.imag]])
90 |
91 | def __mul__(self, other):
92 | if isinstance(other, self.__class__):
93 | return GridOp(self * other.u0, self * other.u1)
94 | elif isinstance(other, ZOmega):
95 | new_d = (self.d0 * other.d + self.d1 * other.b
96 | + (self.c1 - self.a1 + self.c0 - self.a0) // 2 * other.c
97 | + (self.c1 - self.a1 - self.c0 + self.a0) // 2 * other.a)
98 | new_c = (self.c0 * other.d + self.c1 * other.b
99 | + (self.b1 + self.d1 + self.b0 + self.d0) // 2 * other.c
100 | + (self.b1 + self.d1 - self.b0 - self.d0) // 2 * other.a)
101 | new_b = (self.b0 * other.d + self.b1 * other.b
102 | + (self.c1 + self.a1 + self.c0 + self.a0) // 2 * other.c
103 | + (self.c1 + self.a1 - self.c0 - self.a0) // 2 * other.a)
104 | new_a = (self.a0 * other.d + self.a1 * other.b
105 | + (self.b1 - self.d1 + self.b0 - self.d0) // 2 * other.c
106 | + (self.b1 - self.d1 - self.b0 + self.d0) // 2 * other.a)
107 | return ZOmega(new_a, new_b, new_c, new_d)
108 | elif isinstance(other, DOmega):
109 | return DOmega(self * other.u, other.k)
110 | else:
111 | return NotImplemented
112 |
113 | @cached_property
114 | def inv(self):
115 | if not self.is_special:
116 | return None
117 |
118 | new_c0 = (self.c1 + self.a1 - self.c0 - self.a0) // 2
119 | new_a0 = (- self.c1 - self.a1 - self.c0 - self.a0) // 2
120 | new_u0 = ZOmega(new_a0, -self.b0, new_c0, self.b1)
121 | new_c1 = (- self.c1 + self.a1 + self.c0 - self.a0) // 2
122 | new_a1 = (self.c1 - self.a1 + self.c0 - self.a0) // 2
123 | new_u1 = ZOmega(new_a1, self.d0, new_c1, -self.d1)
124 | if self._det_vec.b == -1:
125 | new_u0 = -new_u0
126 | new_u1 = -new_u1
127 | return GridOp(new_u0, new_u1)
128 |
129 | def __pow__(self, other):
130 | if isinstance(other, int):
131 | if other < 0:
132 | return self.inv ** (-other)
133 |
134 | new = self.__class__(ZOmega(0, 0, 0, 1), ZOmega(0, 1, 0, 0))
135 | tmp = self
136 | while other > 0:
137 | if other & 1:
138 | new *= tmp
139 | tmp *= tmp
140 | other >>= 1
141 | return new
142 | else:
143 | return NotImplemented
144 |
145 | @cached_property
146 | def adj(self):
147 | new_c0 = (self.c1 - self.a1 + self.c0 - self.a0) // 2
148 | new_a0 = (self.c1 - self.a1 - self.c0 + self.a0) // 2
149 | new_u0 = ZOmega(new_a0, self.d1, new_c0, self.d0)
150 | new_c1 = (self.c1 + self.a1 + self.c0 + self.a0) // 2
151 | new_a1 = (self.c1 + self.a1 - self.c0 - self.a0) // 2
152 | new_u1 = ZOmega(new_a1, self.b1, new_c1, self.b0)
153 | return self.__class__(new_u0, new_u1)
154 |
155 | @cached_property
156 | def conj_sq2(self):
157 | return self.__class__(self._u0.conj_sq2, self._u1.conj_sq2)
158 |
--------------------------------------------------------------------------------
/pygridsynth/gridsynth.py:
--------------------------------------------------------------------------------
1 | import mpmath
2 | import time
3 |
4 | from .mymath import sqrt, solve_quadratic
5 | from .ring import DRootTwo
6 | from .region import Ellipse, ConvexSet
7 | from .to_upright import to_upright_set_pair
8 | from .tdgp import solve_TDGP
9 | from .diophantine import NO_SOLUTION, diophantine_dyadic
10 | from .unitary import DOmegaUnitary
11 | from .synthesis_of_cliffordT import decompose_domega_unitary
12 |
13 |
14 | class EpsilonRegion(ConvexSet):
15 | def __init__(self, theta, epsilon):
16 | self._theta = theta
17 | self._epsilon = epsilon
18 | self._d = 1 - epsilon ** 2 / 2
19 | self._z_x = mpmath.cos(-theta / 2)
20 | self._z_y = mpmath.sin(-theta / 2)
21 | D_1 = mpmath.matrix([[self._z_x, -self._z_y], [self._z_y, self._z_x]])
22 | D_2 = mpmath.matrix([[4 * (1 / epsilon) ** 4, 0], [0, (1 / epsilon) ** 2]])
23 | D_3 = mpmath.matrix([[self._z_x, self._z_y], [-self._z_y, self._z_x]])
24 | p = mpmath.matrix([self._d * self._z_x, self._d * self._z_y])
25 | ellipse = Ellipse(D_1 * D_2 * D_3, p)
26 | super().__init__(ellipse)
27 |
28 | @property
29 | def theta(self):
30 | return self._theta
31 |
32 | @property
33 | def epsilon(self):
34 | return self._epsilon
35 |
36 | def inside(self, u):
37 | cos_similarity = (self._z_x * u.real + self._z_y * u.imag)
38 | return DRootTwo.fromDOmega(u.conj * u) <= 1 and cos_similarity >= self._d
39 |
40 | def intersect(self, u0, v):
41 | a = v.conj * v
42 | b = 2 * v.conj * u0
43 | c = u0.conj * u0 - 1
44 |
45 | vz = self._z_x * v.real + self._z_y * v.imag
46 | rhs = self._d - self._z_x * u0.real - self._z_y * u0.imag
47 | t = solve_quadratic(a.real, b.real, c.real)
48 | if t is None:
49 | return None
50 | t0, t1 = t
51 | if vz > 0:
52 | t2 = rhs / vz
53 | return (t0, t1) if t0 > t2 else (t2, t1)
54 | elif vz < 0:
55 | t2 = rhs / vz
56 | return (t0, t1) if t1 < t2 else (t0, t2)
57 | else:
58 | return (t0, t1) if rhs <= 0 else None
59 |
60 |
61 | class UnitDisk(ConvexSet):
62 | def __init__(self):
63 | ellipse = Ellipse(mpmath.matrix([[1, 0], [0, 1]]), mpmath.matrix([0, 0]))
64 | super().__init__(ellipse)
65 |
66 | def inside(self, u):
67 | return DRootTwo.fromDOmega(u.conj * u) <= 1
68 |
69 | def intersect(self, u0, v):
70 | a = v.conj * v
71 | b = 2 * v.conj * u0
72 | c = u0.conj * u0 - 1
73 | return solve_quadratic(a.real, b.real, c.real)
74 |
75 |
76 | def generate_complex_unitary(sol):
77 | u, t = sol
78 | return mpmath.matrix([[u.to_complex, -t.conj.to_complex],
79 | [t.to_complex, u.conj.to_complex]])
80 |
81 |
82 | def generate_target_Rz(theta):
83 | return mpmath.matrix([[mpmath.exp(- 1.j * theta / 2), 0],
84 | [0, mpmath.exp(1.j * theta / 2)]])
85 |
86 |
87 | def error(theta, gates):
88 | Rz = generate_target_Rz(theta)
89 | U = DOmegaUnitary.from_gates(gates).to_complex_matrix
90 | E = U - Rz
91 | return sqrt(mpmath.fabs(E[0, 0] * E[1, 1] - E[0, 1] * E[1, 0]))
92 |
93 |
94 | def check(theta, gates):
95 | t_count = gates.count("T")
96 | h_count = gates.count("H")
97 | U_decomp = DOmegaUnitary.from_gates(gates)
98 | # Rz = generate_target_Rz(theta)
99 | # U = U_decomp.to_complex_matrix
100 | e = error(theta, gates)
101 | print(f"{gates=}")
102 | print(f"{t_count=}, {h_count=}")
103 | # print(f"{Rz=}")
104 | print(f"U_decomp={U_decomp.to_matrix}")
105 | # print(f"{U=}")
106 | print(f"{e=}")
107 |
108 |
109 | def gridsynth(theta, epsilon,
110 | diophantine_timeout=200, factoring_timeout=50,
111 | verbose=False, measure_time=False, show_graph=False):
112 | epsilon_region = EpsilonRegion(theta, epsilon)
113 | unit_disk = UnitDisk()
114 | k = 0
115 |
116 | if measure_time:
117 | start = time.time()
118 | transformed = to_upright_set_pair(epsilon_region, unit_disk,
119 | verbose=verbose, show_graph=show_graph)
120 | if measure_time:
121 | print(f"to_upright_set_pair: {time.time() - start} s")
122 | if verbose:
123 | print("------------------")
124 |
125 | time_of_solve_TDGP = 0
126 | time_of_diophantine_dyadic = 0
127 | while True:
128 | if measure_time:
129 | start = time.time()
130 | sol = solve_TDGP(epsilon_region, unit_disk, *transformed, k,
131 | verbose=verbose, show_graph=show_graph)
132 | if measure_time:
133 | time_of_solve_TDGP += time.time() - start
134 | start = time.time()
135 |
136 | for z in sol:
137 | if (z * z.conj).residue == 0:
138 | continue
139 | xi = 1 - DRootTwo.fromDOmega(z.conj * z)
140 | w = diophantine_dyadic(xi,
141 | diophantine_timeout=diophantine_timeout,
142 | factoring_timeout=factoring_timeout)
143 | if w != NO_SOLUTION:
144 | z = z.reduce_denomexp()
145 | w = w.reduce_denomexp()
146 | if z.k > w.k:
147 | w = w.renew_denomexp(z.k)
148 | elif z.k < w.k:
149 | z = z.renew_denomexp(w.k)
150 | if (z + w).reduce_denomexp().k < z.k:
151 | u_approx = DOmegaUnitary(z, w, 0)
152 | else:
153 | u_approx = DOmegaUnitary(z, w.mul_by_omega(), 0)
154 | if measure_time:
155 | time_of_diophantine_dyadic += time.time() - start
156 | print(f"time of solve_TDGP: {time_of_solve_TDGP * 1000} ms")
157 | print(f"time of diophantine_dyadic: {time_of_diophantine_dyadic * 1000} ms")
158 | if verbose:
159 | print(f"{z=}, {w=}")
160 | print("------------------")
161 | return u_approx
162 | if measure_time:
163 | time_of_diophantine_dyadic += time.time() - start
164 | k += 1
165 |
166 |
167 | def gridsynth_gates(theta, epsilon,
168 | diophantine_timeout=200, factoring_timeout=50,
169 | verbose=False, measure_time=False, show_graph=False):
170 | if measure_time:
171 | start_total = time.time()
172 | u_approx = gridsynth(theta=theta, epsilon=epsilon,
173 | diophantine_timeout=diophantine_timeout,
174 | factoring_timeout=factoring_timeout,
175 | verbose=verbose, measure_time=measure_time, show_graph=show_graph)
176 | if measure_time:
177 | start = time.time()
178 | gates = decompose_domega_unitary(u_approx)
179 | if measure_time:
180 | print(f"time of decompose_domega_unitary: {(time.time() - start) * 1000} ms")
181 | print(f"total time: {(time.time() - start_total) * 1000} ms")
182 | return gates
183 |
--------------------------------------------------------------------------------
/pygridsynth/mymath.py:
--------------------------------------------------------------------------------
1 | import mpmath
2 | from itertools import accumulate
3 |
4 |
5 | def SQRT2():
6 | return mpmath.sqrt(2)
7 |
8 |
9 | def ntz(n):
10 | return 0 if n == 0 else ((n & -n) - 1).bit_count()
11 |
12 |
13 | def floor(x):
14 | return int(mpmath.floor(x, prec=0))
15 |
16 |
17 | def ceil(x):
18 | return int(mpmath.ceil(x, prec=0))
19 |
20 |
21 | def sqrt(x):
22 | return mpmath.sqrt(x)
23 |
24 |
25 | def log(x):
26 | return mpmath.log(x)
27 |
28 |
29 | def sign(x):
30 | return 1 if x > 0 else -1 if x < 0 else 0
31 |
32 |
33 | def floorsqrt(x):
34 | if x < 0:
35 | raise ValueError
36 | ok = 0
37 | ng = ceil(x) + 1
38 | while ng - ok > 1:
39 | mid = ok + (ng - ok) // 2
40 | if mid * mid <= x:
41 | ok = mid
42 | else:
43 | ng = mid
44 | return ok
45 |
46 |
47 | def rounddiv(x, y):
48 | return (x + y // 2) // y if y > 0 else (x - (- y) // 2) // y
49 |
50 |
51 | def pow_sqrt2(k):
52 | k_div_2, k_mod_2 = k >> 1, k & 1
53 | return (1 << k_div_2) * SQRT2() if k_mod_2 else 1 << k_div_2
54 |
55 |
56 | def floorlog(x, y):
57 | if x <= 0:
58 | raise ValueError("math domain error")
59 |
60 | tmp = y
61 | m = 0
62 | while x >= tmp or x * tmp < 1:
63 | tmp *= tmp
64 | m += 1
65 |
66 | pow_y = reversed(list(accumulate([0] * (m - 1), lambda x0, x1: x0 * x0, initial=y)))
67 | n, r = (0, x) if x >= 1 else (-1, x * tmp)
68 | for p in pow_y:
69 | n <<= 1
70 | if r > p:
71 | r /= p
72 | n += 1
73 | return (n, r)
74 |
75 |
76 | def solve_quadratic(a, b, c):
77 | if a < 0:
78 | a, b, c = -a, -b, -c
79 | discriminant = b ** 2 - 4 * a * c
80 | if discriminant < 0:
81 | return None
82 | s1 = - b - sqrt(discriminant)
83 | s2 = - b + sqrt(discriminant)
84 | if b >= 0:
85 | return (s1 / (2 * a), s2 / (2 * a))
86 | else:
87 | return ((2 * c) / s2, (2 * c) / s1)
88 |
--------------------------------------------------------------------------------
/pygridsynth/myplot.py:
--------------------------------------------------------------------------------
1 |
2 | def plot_sol(sol_list, ellipseA, ellipseB, bboxA=None, bboxB=None,
3 | color_list=None, size_list=None):
4 | import matplotlib.pyplot as plt
5 |
6 | if color_list is None:
7 | color_list = plt.rcParams['axes.prop_cycle'].by_key()['color']
8 | if size_list is None:
9 | size_list = [5] * len(sol_list)
10 |
11 | fig = plt.figure(figsize=(12, 6))
12 | ax1 = fig.add_subplot(1, 2, 1)
13 | ax1.set_aspect('equal')
14 | ax1.set_xlabel(r"$\mathrm{Re}[u]$")
15 | ax1.set_ylabel(r"$\mathrm{Im}[u]$")
16 | ax2 = fig.add_subplot(1, 2, 2)
17 | ax2.set_aspect('equal')
18 | ax2.set_xlabel(r"$\mathrm{Re}[u^\bullet]$")
19 | ax2.set_ylabel(r"$\mathrm{Im}[u^\bullet]$")
20 |
21 | for sol, color, size in zip(sol_list, color_list, size_list):
22 | x = [u.real for u in sol]
23 | y = [u.imag for u in sol]
24 | ax1.scatter(x, y, c=color, s=size)
25 | x = [u.conj_sq2.real for u in sol]
26 | y = [u.conj_sq2.imag for u in sol]
27 | ax2.scatter(x, y, c=color, s=size)
28 |
29 | ellipseA.plot(ax1)
30 | ellipseB.plot(ax2)
31 |
32 | if bboxA is not None:
33 | bboxA.plot(ax1)
34 | if bboxB is not None:
35 | bboxB.plot(ax2)
36 |
37 | plt.show()
38 |
--------------------------------------------------------------------------------
/pygridsynth/normal_form.py:
--------------------------------------------------------------------------------
1 | from enum import Enum
2 |
3 |
4 | class Axis(Enum):
5 | I = 0
6 | H = 1
7 | SH = 2
8 |
9 |
10 | class Syllable(Enum):
11 | I = 0
12 | T = 1
13 | HT = 2
14 | SHT = 3
15 |
16 |
17 | CONJ2_TABLE = [(0, 0), (0, 0), (1, 0), (3, 2), (2, 0), (2, 4), (3, 0), (1, 6)]
18 | CONJ3_TABLE = [(0, 0, 0, 0), (0, 0, 1, 0), (0, 0, 2, 0), (0, 0, 3, 0),
19 | (0, 1, 0, 0), (0, 1, 1, 0), (0, 1, 2, 0), (0, 1, 3, 0),
20 | (1, 0, 0, 0), (2, 0, 3, 6), (1, 1, 2, 2), (2, 1, 3, 6),
21 | (1, 0, 2, 0), (2, 1, 1, 0), (1, 1, 0, 6), (2, 0, 1, 4),
22 | (2, 0, 0, 0), (1, 1, 3, 4), (2, 1, 0, 0), (1, 0, 1, 2),
23 | (2, 1, 2, 2), (1, 1, 1, 0), (2, 0, 2, 6), (1, 0, 3, 2)]
24 | CINV_TABLE = [(0, 0, 0, 0), (0, 0, 3, 0), (0, 0, 2, 0), (0, 0, 1, 0),
25 | (0, 1, 0, 0), (0, 1, 1, 6), (0, 1, 2, 4), (0, 1, 3, 2),
26 | (2, 0, 0, 0), (1, 0, 1, 2), (2, 1, 0, 0), (1, 1, 3, 4),
27 | (2, 1, 1, 2), (1, 1, 1, 6), (2, 0, 2, 2), (1, 0, 3, 4),
28 | (1, 0, 0, 0), (2, 1, 3, 6), (1, 1, 2, 2), (2, 0, 3, 6),
29 | (1, 0, 2, 0), (2, 1, 1, 6), (1, 1, 0, 2), (2, 0, 1, 6)]
30 | TCONJ_TABLE = [(Axis.I, 0, 0), (Axis.I, 1, 7),
31 | (Axis.H, 3, 3), (Axis.H, 2, 0),
32 | (Axis.SH, 0, 5), (Axis.SH, 1, 4)]
33 |
34 |
35 | class Clifford():
36 | def __init__(self, a, b, c, d):
37 | if a >= 3 or a < 0:
38 | a %= 3
39 | if b >= 2 or b < 0:
40 | b &= 1
41 | if c >= 4 or c < 0:
42 | c &= 0b11
43 | if d >= 8 or d < 0:
44 | d &= 0b111
45 | self._a = a
46 | self._b = b
47 | self._c = c
48 | self._d = d
49 |
50 | @property
51 | def a(self):
52 | return self._a
53 |
54 | @property
55 | def b(self):
56 | return self._b
57 |
58 | @property
59 | def c(self):
60 | return self._c
61 |
62 | @property
63 | def d(self):
64 | return self._d
65 |
66 | def __repr__(self):
67 | return f"Clifford({self._a}, {self._b}, {self._c}, {self._d})"
68 |
69 | def __str__(self):
70 | return f"E^{self._a} X^{self._b} S^{self._c} ω^{self._d}"
71 |
72 | @classmethod
73 | def from_str(cls, g):
74 | if g == "H":
75 | return CLIFFORD_H
76 | elif g == "S":
77 | return CLIFFORD_S
78 | elif g == "X":
79 | return CLIFFORD_X
80 | elif g == "W":
81 | return CLIFFORD_W
82 | else:
83 | raise ValueError
84 |
85 | def __eq__(self, other):
86 | if isinstance(other, self.__class__):
87 | return (self._a == other.a and self._b == other.b
88 | and self._c == other.c and self._d == other.d)
89 | else:
90 | return False
91 |
92 | @classmethod
93 | def _conj2(cls, c, b):
94 | return CONJ2_TABLE[c << 1 | b]
95 |
96 | @classmethod
97 | def _conj3(cls, b, c, a):
98 | return CONJ3_TABLE[a << 3 | b << 2 | c]
99 |
100 | @classmethod
101 | def _cinv(cls, a, b, c):
102 | return CINV_TABLE[a << 3 | b << 2 | c]
103 |
104 | @classmethod
105 | def _tconj(cls, a, b):
106 | return TCONJ_TABLE[a << 1 | b]
107 |
108 | def __mul__(self, other):
109 | if isinstance(other, self.__class__):
110 | a1, b1, c1, d1 = self.__class__._conj3(self._b, self._c, other.a)
111 | c2, d2 = self.__class__._conj2(c1, other.b)
112 | new_a = self._a + a1
113 | new_b = b1 + other.b
114 | new_c = c2 + other.c
115 | new_d = d2 + d1 + self._d + other.d
116 | return self.__class__(new_a, new_b, new_c, new_d)
117 | else:
118 | return NotImplemented
119 |
120 | def inv(self):
121 | a1, b1, c1, d1 = self.__class__._cinv(self._a, self._b, self._c)
122 | return self.__class__(a1, b1, c1, d1 - self._d)
123 |
124 | def decompose_coset(self):
125 | if self._a == 0:
126 | return Axis.I, self
127 | elif self._a == 1:
128 | return Axis.H, CLIFFORD_H.inv() * self
129 | elif self._a == 2:
130 | return Axis.SH, CLIFFORD_SH.inv() * self
131 |
132 | def decompose_tconj(self):
133 | axis, c1, d1 = self.__class__._tconj(self._a, self._b)
134 | return axis, self.__class__(0, self._b, c1 + self._c, d1 + self._d)
135 |
136 | def to_gates(self):
137 | axis, c = self.decompose_coset()
138 | return ("" if axis == Axis.I else axis.name) + "X" * c.b + "S" * c.c + "W" * c.d
139 |
140 |
141 | class NormalForm():
142 | def __init__(self, syllables, c):
143 | self._syllables = syllables
144 | self._c = c
145 |
146 | @property
147 | def syllables(self):
148 | return self._syllables
149 |
150 | @property
151 | def c(self):
152 | return self._c
153 |
154 | @c.setter
155 | def c(self, c):
156 | self._c = c
157 |
158 | def __repr__(self):
159 | return f"NormalForm({repr(self._syllables)}, {repr(self._c)})"
160 |
161 | def _append_gate(self, g):
162 | if g in ["H", "S", "X", "W"]:
163 | self.c *= Clifford.from_str(g)
164 | elif g == "T":
165 | axis, new_c = self.c.decompose_tconj()
166 | if axis == Axis.I:
167 | if len(self._syllables) == 0:
168 | self._syllables.append(Syllable.T)
169 | elif self._syllables[-1] == Syllable.T:
170 | self._syllables[-1].pop()
171 | self.c = CLIFFORD_S * new_c
172 | elif self._syllables[-1] == Syllable.HT:
173 | self._syllables.pop()
174 | self.c = CLIFFORD_HS * new_c
175 | elif self._syllables[-1] == Syllable.SHT:
176 | self._syllables.pop()
177 | self.c = CLIFFORD_SHS * new_c
178 | elif axis == Axis.H:
179 | self._syllables.append(Syllable.HT)
180 | self.c = new_c
181 | elif axis == Axis.SH:
182 | self._syllables.append(Syllable.SHT)
183 | self.c = new_c
184 |
185 | @classmethod
186 | def from_gates(cls, gates):
187 | normal_form = NormalForm([], CLIFFORD_I)
188 | for g in gates:
189 | normal_form._append_gate(g)
190 | return normal_form
191 |
192 | def to_gates(self):
193 | gates = ""
194 | for syllable in self._syllables:
195 | if syllable != Syllable.I:
196 | gates += syllable.name
197 | gates += self._c.to_gates()
198 | return "I" if gates == "" else gates
199 |
200 |
201 | CLIFFORD_I = Clifford(0, 0, 0, 0)
202 | CLIFFORD_X = Clifford(0, 1, 0, 0)
203 | CLIFFORD_H = Clifford(1, 0, 1, 5)
204 | CLIFFORD_S = Clifford(0, 0, 1, 0)
205 | CLIFFORD_W = Clifford(0, 0, 0, 1)
206 | CLIFFORD_SH = CLIFFORD_S * CLIFFORD_H
207 | CLIFFORD_HS = CLIFFORD_H * CLIFFORD_S
208 | CLIFFORD_SHS = CLIFFORD_S * CLIFFORD_H * CLIFFORD_S
209 |
--------------------------------------------------------------------------------
/pygridsynth/odgp.py:
--------------------------------------------------------------------------------
1 | from .mymath import SQRT2, floor, ceil, pow_sqrt2, floorlog
2 | from .ring import ZRootTwo, DRootTwo, LAMBDA
3 |
4 |
5 | def _solve_ODGP_internal(I, J):
6 | if I.width < 0 or J.width < 0:
7 | return []
8 | elif I.width > 0 and J.width <= 0:
9 | sol = _solve_ODGP_internal(J, I)
10 | return [beta.conj_sq2 for beta in sol]
11 | else:
12 | (n, _) = (0, 0) if J.width <= 0 else floorlog(J.width, LAMBDA.to_real)
13 | if n == 0:
14 | sol = []
15 | a_min = ceil((I.l + J.l) / 2)
16 | a_max = floor((I.r + J.r) / 2)
17 | for a in range(a_min, a_max + 1):
18 | b_min = ceil(SQRT2() * (a - J.r) / 2)
19 | b_max = floor(SQRT2() * (a - J.l) / 2)
20 | for b in range(b_min, b_max + 1):
21 | sol.append(ZRootTwo(a, b))
22 | return sol
23 | else:
24 | lambda_n = LAMBDA ** n
25 | lambda_inv_n = LAMBDA ** -n
26 | lambda_conj_sq2_n = LAMBDA.conj_sq2 ** n
27 | sol = _solve_ODGP_internal(I * lambda_n.to_real, J * lambda_conj_sq2_n.to_real)
28 | sol = [beta * lambda_inv_n for beta in sol]
29 | return sol
30 |
31 |
32 | def solve_ODGP(I, J):
33 | if I.width < 0 or J.width < 0:
34 | return []
35 |
36 | a = floor((I.l + J.l) / 2)
37 | b = floor(SQRT2() * (I.l - J.l) / 4)
38 | alpha = ZRootTwo(a, b)
39 | sol = _solve_ODGP_internal(I - alpha.to_real, J - alpha.conj_sq2.to_real)
40 | sol = [beta + alpha for beta in sol]
41 | sol = [beta for beta in sol if I.within(beta.to_real) and J.within(beta.conj_sq2.to_real)]
42 | return sol
43 |
44 |
45 | def solve_ODGP_with_parity(I, J, beta):
46 | p = beta.parity
47 | sol = solve_ODGP((I - p) * SQRT2() / 2, (J - p) * (- SQRT2()) / 2)
48 | sol = [alpha * ZRootTwo(0, 1) + p for alpha in sol]
49 | return sol
50 |
51 |
52 | def solve_scaled_ODGP(I, J, k):
53 | scale = pow_sqrt2(k)
54 | sol = solve_ODGP(I * scale, -J * scale if k & 1 else J * scale)
55 | return [DRootTwo(alpha, k) for alpha in sol]
56 |
57 |
58 | def solve_scaled_ODGP_with_parity(I, J, k, beta):
59 | if k == 0:
60 | sol = solve_ODGP_with_parity(I, J, beta.renew_denomexp(0))
61 | return [DRootTwo.from_zroottwo(alpha) for alpha in sol]
62 | else:
63 | p = beta.renew_denomexp(k).parity
64 | offset = DRootTwo.from_int(0) if p == 0 else DRootTwo.power_of_inv_sqrt2(k)
65 | sol = solve_scaled_ODGP(I - offset.to_real, J - offset.conj_sq2.to_real, k - 1)
66 | return [alpha + offset for alpha in sol]
67 |
--------------------------------------------------------------------------------
/pygridsynth/region.py:
--------------------------------------------------------------------------------
1 | from abc import ABC, abstractmethod
2 | from functools import cached_property
3 | import numbers
4 | import mpmath
5 |
6 | from .mymath import sqrt
7 | from .grid_op import GridOp
8 |
9 |
10 | class Interval():
11 | def __init__(self, l, r):
12 | self.l = l
13 | self.r = r
14 |
15 | def __str__(self):
16 | return f"[{self.l}, {self.r}]"
17 |
18 | def __add__(self, other):
19 | if isinstance(other, numbers.Real):
20 | return self.__class__(self.l + other, self.r + other)
21 | elif isinstance(other, self.__class__):
22 | return self.__class__(self.l + other.l, self.r + other.r)
23 | else:
24 | return NotImplemented
25 |
26 | def __radd__(self, other):
27 | if isinstance(other, numbers.Real):
28 | return self + other
29 | elif isinstance(other, self.__class__):
30 | return self + other
31 | else:
32 | return NotImplemented
33 |
34 | def __sub__(self, other):
35 | return self + (-other)
36 |
37 | def __rsub__(self, other):
38 | return (-self) + other
39 |
40 | def __neg__(self):
41 | return self.__class__(- self.r, - self.l)
42 |
43 | def __mul__(self, other):
44 | if isinstance(other, numbers.Real):
45 | if other >= 0:
46 | return self.__class__(self.l * other, self.r * other)
47 | else:
48 | return self.__class__(self.r * other, self.l * other)
49 | else:
50 | return NotImplemented
51 |
52 | def __rmul__(self, other):
53 | return self * other
54 |
55 | def __truediv__(self, other):
56 | if isinstance(other, numbers.Real):
57 | if other > 0:
58 | return self.__class__(self.l / other, self.r / other)
59 | else:
60 | return self.__class__(self.r / other, self.l / other)
61 | else:
62 | return NotImplemented
63 |
64 | @cached_property
65 | def width(self):
66 | return self.r - self.l
67 |
68 | def fatten(self, eps):
69 | return Interval(self.l - eps, self.r + eps)
70 |
71 | def within(self, x):
72 | return self.l <= x <= self.r
73 |
74 |
75 | class Rectangle():
76 | def __init__(self, x_l, x_r, y_l, y_r):
77 | self.I_x = Interval(x_l, x_r)
78 | self.I_y = Interval(y_l, y_r)
79 |
80 | def __str__(self):
81 | return f"{self.I_x}×{self.I_y}"
82 |
83 | def __mul__(self, other):
84 | if isinstance(other, numbers.Real):
85 | if other >= 0:
86 | new_I_x = self.I_x * other
87 | new_I_y = self.I_y * other
88 | return self.__class__(new_I_x.l, new_I_x.r, new_I_y.l, new_I_y.r)
89 | else:
90 | new_I_x = self.I_x * other
91 | new_I_y = self.I_y * other
92 | return self.__class__(new_I_x.r, new_I_x.l, new_I_y.r, new_I_y.l)
93 | else:
94 | return NotImplemented
95 |
96 | def __rmul__(self, other):
97 | if isinstance(other, numbers.Real):
98 | return self * other
99 | else:
100 | return NotImplemented
101 |
102 | @cached_property
103 | def area(self):
104 | return self.I_x.width * self.I_y.width
105 |
106 | def plot(self, ax, color='black'):
107 | x = [self.I_x.l, self.I_x.l, self.I_x.r, self.I_x.r, self.I_x.l]
108 | y = [self.I_y.l, self.I_y.r, self.I_y.r, self.I_y.l, self.I_y.l]
109 | ax.plot(x, y, c=color)
110 |
111 |
112 | class Ellipse():
113 | def __init__(self, D, p):
114 | self.D = D
115 | self.p = p
116 |
117 | @property
118 | def px(self):
119 | return self.p[0]
120 |
121 | @px.setter
122 | def px(self, px):
123 | self.p[0] = px
124 |
125 | @property
126 | def py(self):
127 | return self.p[1]
128 |
129 | @py.setter
130 | def py(self, py):
131 | self.p[1] = py
132 |
133 | @property
134 | def a(self):
135 | return self.D[0, 0]
136 |
137 | @a.setter
138 | def a(self, a):
139 | self.D[0, 0] = a
140 |
141 | @property
142 | def b(self):
143 | return self.D[0, 1]
144 |
145 | @b.setter
146 | def b(self, b):
147 | self.D[0, 1] = b
148 | self.D[1, 0] = b
149 |
150 | @property
151 | def d(self):
152 | return self.D[1, 1]
153 |
154 | @d.setter
155 | def d(self, d):
156 | self.D[1, 1] = d
157 |
158 | def inside(self, v):
159 | x = v[0] - self.px
160 | y = v[1] - self.py
161 | tmp = self.a * x * x + 2 * self.b * x * y + self.d * y * y
162 | return tmp <= 1
163 |
164 | def bbox(self):
165 | sqrt_det = self.sqrt_det
166 | w = sqrt(self.d) / sqrt_det
167 | h = sqrt(self.a) / sqrt_det
168 | return Rectangle(self.px - w, self.px + w, self.py - h, self.py + h)
169 |
170 | def __mul__(self, other):
171 | if isinstance(other, numbers.Real):
172 | return self.__class__(self.D * (1 / other) ** 2, self.p * other)
173 | else:
174 | return NotImplemented
175 |
176 | def __rmul__(self, other):
177 | if isinstance(other, GridOp):
178 | M00 = other.inv.toMat[0, 0]
179 | M01 = other.inv.toMat[0, 1]
180 | M10 = other.inv.toMat[1, 0]
181 | M11 = other.inv.toMat[1, 1]
182 | a = self.a * M00 * M00 + 2 * self.b * M00 * M10 + self.d * M10 * M10
183 | b = self.a * M00 * M01 + self.b * (M00 * M11 + M01 * M10) + self.d * M10 * M11
184 | d = self.a * M01 * M01 + 2 * self.b * M11 * M01 + self.d * M11 * M11
185 | new_D = mpmath.matrix([[a, b], [b, d]])
186 |
187 | M00 = other.toMat[0, 0]
188 | M01 = other.toMat[0, 1]
189 | M10 = other.toMat[1, 0]
190 | M11 = other.toMat[1, 1]
191 | px = M00 * self.px + M01 * self.py
192 | py = M10 * self.px + M11 * self.py
193 | new_p = mpmath.matrix([px, py])
194 |
195 | return self.__class__(new_D, new_p)
196 | elif isinstance(other, numbers.Real):
197 | return self * other
198 | else:
199 | return NotImplemented
200 |
201 | def __truediv__(self, other):
202 | if isinstance(other, numbers.Real):
203 | return self.__class__(self.D * other ** 2, self.p / other)
204 | else:
205 | return NotImplemented
206 |
207 | @property
208 | def area(self):
209 | return mpmath.mp.pi / self.sqrt_det
210 |
211 | @property
212 | def sqrt_det(self):
213 | det = self.d * self.a - self.b ** 2
214 | return sqrt(det)
215 |
216 | def normalize(self):
217 | return self.__class__(self.D / self.sqrt_det, self.p * sqrt(self.sqrt_det))
218 |
219 | @property
220 | def skew(self):
221 | return self.b ** 2
222 |
223 | @property
224 | def bias(self):
225 | return self.d / self.a
226 |
227 | def plot(self, ax, n=5000):
228 | eig_val, eig_vec = mpmath.eigsy(self.D)
229 | vx = [self.px] * n
230 | vy = [self.py] * n
231 | for i in range(n):
232 | t = mpmath.mp.pi * 2 * i / n
233 | vx[i] += eig_vec[0, 0] * mpmath.cos(t) / sqrt(eig_val[0])
234 | vx[i] += eig_vec[0, 1] * mpmath.sin(t) / sqrt(eig_val[1])
235 | vy[i] += eig_vec[1, 0] * mpmath.cos(t) / sqrt(eig_val[0])
236 | vy[i] += eig_vec[1, 1] * mpmath.sin(t) / sqrt(eig_val[1])
237 | ax.plot(vx, vy, c='orangered')
238 |
239 |
240 | class ConvexSet(ABC):
241 | def __init__(self, ellipse):
242 | self._ellipse = ellipse
243 |
244 | @abstractmethod
245 | def inside(self, u):
246 | pass
247 |
248 | @property
249 | def ellipse(self):
250 | return self._ellipse
251 |
252 | @abstractmethod
253 | def intersect(self, u, v):
254 | pass
255 |
--------------------------------------------------------------------------------
/pygridsynth/ring.py:
--------------------------------------------------------------------------------
1 | import numbers
2 | from functools import cached_property, total_ordering
3 | import mpmath
4 |
5 | from .mymath import SQRT2, ntz, sign, floorsqrt, rounddiv, pow_sqrt2
6 |
7 |
8 | @total_ordering
9 | class ZRootTwo():
10 | def __init__(self, a, b):
11 | self._a = a
12 | self._b = b
13 |
14 | @property
15 | def a(self):
16 | return self._a
17 |
18 | @property
19 | def b(self):
20 | return self._b
21 |
22 | @cached_property
23 | def coef(self):
24 | return [self._a, self._b]
25 |
26 | def __repr__(self):
27 | return f"ZRootTwo({self._a}, {self._b})"
28 |
29 | def __str__(self):
30 | return f"{self._a}{self._b:+}√2"
31 |
32 | @classmethod
33 | def from_int(cls, x):
34 | return cls(x, 0)
35 |
36 | @classmethod
37 | def from_zomega(cls, x):
38 | if x.b == 0 and x.a == -x.c:
39 | return cls(x.d, x.c)
40 | else:
41 | raise ValueError
42 |
43 | def __eq__(self, other):
44 | if isinstance(other, numbers.Integral):
45 | return self == self.from_int(other)
46 | elif isinstance(other, self.__class__):
47 | return self._a == other.a and self._b == other.b
48 | else:
49 | return False
50 |
51 | def __lt__(self, other):
52 | if isinstance(other, numbers.Integral):
53 | return self < self.from_int(other)
54 | elif isinstance(other, self.__class__):
55 | if self._b < other.b:
56 | return self._a < other.a or (self._a - other.a) ** 2 < 2 * (self._b - other.b) ** 2
57 | else:
58 | return self._a < other.a and (self._a - other.a) ** 2 > 2 * (self._b - other.b) ** 2
59 | else:
60 | return False
61 |
62 | def __add__(self, other):
63 | if isinstance(other, numbers.Integral):
64 | return self + self.from_int(other)
65 | elif isinstance(other, self.__class__):
66 | return self.__class__(self._a + other.a, self._b + other.b)
67 | else:
68 | return NotImplemented
69 |
70 | def __radd__(self, other):
71 | if isinstance(other, numbers.Integral):
72 | return self + other
73 | elif isinstance(other, self.__class__):
74 | return self + other
75 | else:
76 | return NotImplemented
77 |
78 | def __sub__(self, other):
79 | return self + (- other)
80 |
81 | def __rsub__(self, other):
82 | return (-self) + other
83 |
84 | def __neg__(self):
85 | return self.__class__(-self._a, -self._b)
86 |
87 | def __mul__(self, other):
88 | if isinstance(other, numbers.Integral):
89 | return self * self.from_int(other)
90 | elif isinstance(other, self.__class__):
91 | new_a = self._a * other.a + 2 * self._b * other.b
92 | new_b = self._a * other.b + self._b * other.a
93 | return self.__class__(new_a, new_b)
94 | else:
95 | return NotImplemented
96 |
97 | def __rmul__(self, other):
98 | if isinstance(other, numbers.Integral):
99 | return self * other
100 | elif isinstance(other, self.__class__):
101 | return self * other
102 | else:
103 | return NotImplemented
104 |
105 | @cached_property
106 | def inv(self):
107 | if self.norm == 1:
108 | return self.conj_sq2
109 | elif self.norm == -1:
110 | return -self.conj_sq2
111 | else:
112 | raise ZeroDivisionError
113 |
114 | def __pow__(self, other):
115 | if isinstance(other, numbers.Integral):
116 | if other < 0:
117 | return self.inv ** -other
118 | else:
119 | new = self.__class__(1, 0)
120 | tmp = self
121 | while other > 0:
122 | if other & 1:
123 | new *= tmp
124 | tmp *= tmp
125 | other >>= 1
126 | return new
127 | else:
128 | return NotImplemented
129 |
130 | def sqrt(self):
131 | norm = self.norm
132 | if norm < 0 or self._a < 0:
133 | return None
134 | r = floorsqrt(norm)
135 | a1 = floorsqrt((self._a + r) // 2)
136 | b1 = floorsqrt((self._a - r) // 4)
137 | a2 = floorsqrt((self._a - r) // 2)
138 | b2 = floorsqrt((self._a + r) // 4)
139 | if sign(self._a) * sign(self._b) >= 0:
140 | w1 = ZRootTwo(a1, b1)
141 | w2 = ZRootTwo(a2, b2)
142 | else:
143 | w1 = ZRootTwo(a1, -b1)
144 | w2 = ZRootTwo(a2, -b2)
145 | if self == w1 * w1:
146 | return w1
147 | elif self == w2 * w2:
148 | return w2
149 | else:
150 | return None
151 |
152 | def __divmod__(self, other):
153 | if isinstance(other, numbers.Integral):
154 | return divmod(self, self.from_int(other))
155 | elif isinstance(other, self.__class__):
156 | p = self * other.conj_sq2
157 | k = other.norm
158 | q = self.__class__(rounddiv(p.a, k), rounddiv(p.b, k))
159 | r = self - other * q
160 | return q, r
161 | else:
162 | return NotImplemented
163 |
164 | def __rdivmod__(self, other):
165 | if isinstance(other, numbers.Integral):
166 | return divmod(self.from_int(other), self)
167 | elif isinstance(other, self.__class__):
168 | return divmod(other, self)
169 | else:
170 | return NotImplemented
171 |
172 | def __floordiv__(self, other):
173 | q, _ = divmod(self, other)
174 | return q
175 |
176 | def __rfloordiv__(self, other):
177 | q, _ = divmod(other, self)
178 | return q
179 |
180 | def __mod__(self, other):
181 | _, r = divmod(self, other)
182 | return r
183 |
184 | def __rmod__(self, other):
185 | _, r = divmod(other, self)
186 | return r
187 |
188 | @classmethod
189 | def sim(cls, a, b):
190 | return a % b == 0 and b % a == 0
191 |
192 | @classmethod
193 | def ext_gcd(cls, a, b):
194 | if isinstance(a, numbers.Integral):
195 | a = cls.from_int(a)
196 | if isinstance(b, numbers.Integral):
197 | b = cls.from_int(b)
198 | x = cls.from_int(1)
199 | y = cls.from_int(0)
200 | z = cls.from_int(0)
201 | w = cls.from_int(1)
202 | while b != 0:
203 | q, r = divmod(a, b)
204 | x, y = y, x - y * q
205 | z, w = w, z - w * q
206 | a, b = b, r
207 | return x, z, a
208 |
209 | @classmethod
210 | def gcd(cls, a, b):
211 | _, _, g = cls.ext_gcd(a, b)
212 | return g
213 |
214 | @cached_property
215 | def parity(self):
216 | return self._a & 1
217 |
218 | @cached_property
219 | def norm(self):
220 | return self._a ** 2 - 2 * self._b ** 2
221 |
222 | @cached_property
223 | def to_real(self):
224 | return self._a + SQRT2() * self._b
225 |
226 | @cached_property
227 | def conj_sq2(self):
228 | return self.__class__(self._a, -self._b)
229 |
230 |
231 | @total_ordering
232 | class DRootTwo():
233 | def __init__(self, alpha, k):
234 | self._alpha = alpha
235 | self._k = k
236 |
237 | @property
238 | def alpha(self):
239 | return self._alpha
240 |
241 | @property
242 | def k(self):
243 | return self._k
244 |
245 | def __repr__(self):
246 | return f"DRootTwo({self._alpha}, {self._k})"
247 |
248 | def __str__(self):
249 | return f"{self._alpha} / √2^{self._k}"
250 |
251 | @classmethod
252 | def from_int(cls, x):
253 | return cls(ZRootTwo.from_int(x), 0)
254 |
255 | @classmethod
256 | def from_zroottwo(cls, x):
257 | return cls(x, 0)
258 |
259 | @classmethod
260 | def from_zomega(cls, x):
261 | return cls(ZRootTwo.from_zomega(x), 0)
262 |
263 | @classmethod
264 | def fromDOmega(cls, x):
265 | return cls(ZRootTwo.from_zomega(x.u), x.k)
266 |
267 | def __eq__(self, other):
268 | if isinstance(other, numbers.Integral):
269 | return self == self.from_int(other)
270 | elif isinstance(other, ZRootTwo):
271 | return self == self.from_zroottwo(other)
272 | elif isinstance(other, self.__class__):
273 | if self._k < other.k:
274 | return self.renew_denomexp(other.k) == other
275 | elif self._k > other.k:
276 | return self == other.renew_denomexp(self._k)
277 | else:
278 | return self._alpha == other.alpha and self._k == other.k
279 | else:
280 | return False
281 |
282 | def __lt__(self, other):
283 | if isinstance(other, numbers.Integral):
284 | return self < self.from_int(other)
285 | elif isinstance(other, ZRootTwo):
286 | return self < self.from_zroottwo(other)
287 | elif isinstance(other, self.__class__):
288 | if self._k < other.k:
289 | return self.renew_denomexp(other.k) < other
290 | elif self._k > other.k:
291 | return self < other.renew_denomexp(self._k)
292 | else:
293 | return self._alpha < other.alpha
294 | else:
295 | return False
296 |
297 | def __add__(self, other):
298 | if isinstance(other, numbers.Integral):
299 | return self + self.from_int(other)
300 | elif isinstance(other, ZRootTwo):
301 | return self + self.from_zroottwo(other)
302 | elif isinstance(other, self.__class__):
303 | if self._k < other.k:
304 | return self.renew_denomexp(other.k) + other
305 | elif self._k > other.k:
306 | return self + other.renew_denomexp(self._k)
307 | else:
308 | return self.__class__(self._alpha + other.alpha, self._k)
309 | else:
310 | return NotImplemented
311 |
312 | def __radd__(self, other):
313 | if isinstance(other, numbers.Integral):
314 | return self + other
315 | elif isinstance(other, ZRootTwo):
316 | return self + other
317 | elif isinstance(other, self.__class__):
318 | return self + other
319 | else:
320 | return NotImplemented
321 |
322 | def __sub__(self, other):
323 | return self + (- other)
324 |
325 | def __rsub__(self, other):
326 | return (-self) + other
327 |
328 | def __neg__(self):
329 | return self.__class__(-self._alpha, self._k)
330 |
331 | def __mul__(self, other):
332 | if isinstance(other, numbers.Integral):
333 | return self * self.from_int(other)
334 | elif isinstance(other, ZRootTwo):
335 | return self * self.from_zroottwo(other)
336 | elif isinstance(other, self.__class__):
337 | return self.__class__(self._alpha * other.alpha, self._k + other.k)
338 | else:
339 | return NotImplemented
340 |
341 | def __rmul__(self, other):
342 | if isinstance(other, numbers.Integral):
343 | return self * other
344 | elif isinstance(other, ZRootTwo):
345 | return self * other
346 | elif isinstance(other, self.__class__):
347 | return self * other
348 | else:
349 | return NotImplemented
350 |
351 | def renew_denomexp(self, new_k):
352 | new_alpha = self.mul_by_sqrt2_power(new_k - self._k).alpha
353 | return self.__class__(new_alpha, new_k)
354 |
355 | def reduce_denomexp(self):
356 | k_a = self._k if self._alpha.a == 0 else ntz(self._alpha.a)
357 | k_b = self._k if self._alpha.b == 0 else ntz(self._alpha.b)
358 | new_k = self._k - k_a * 2 if k_a <= k_b else self._k - k_b * 2 - 1
359 | return self.renew_denomexp(0 if new_k < 0 else new_k)
360 |
361 | def mul_by_inv_sqrt2(self):
362 | if not (self._alpha.a & 1):
363 | new_alpha = ZRootTwo(self._alpha.b, self._alpha.a >> 1)
364 | else:
365 | raise ValueError
366 | return self.__class__(new_alpha, self._k)
367 |
368 | def mul_by_sqrt2_power(self, d):
369 | if d < 0:
370 | if d == -1:
371 | return self.mul_by_inv_sqrt2()
372 | d_div_2, d_mod_2 = (-d) >> 1, (-d) & 1
373 | if d_mod_2 == 0:
374 | bit = (1 << d_div_2) - 1
375 | if self._alpha.a & bit == 0 and self._alpha.b & bit == 0:
376 | new_alpha = ZRootTwo(self._alpha.a >> d_div_2, self._alpha.b >> d_div_2)
377 | else:
378 | raise ValueError
379 | else:
380 | bit = (1 << d_div_2) - 1
381 | bit2 = (1 << (d_div_2 + 1)) - 1
382 | if self._alpha.a & bit2 == 0 and self._alpha.b & bit == 0:
383 | new_alpha = ZRootTwo(self._alpha.b >> d_div_2, self._alpha.a >> (d_div_2 + 1))
384 | else:
385 | raise ValueError
386 | return self.__class__(new_alpha, self._k)
387 | else:
388 | d_div_2, d_mod_2 = d >> 1, d & 1
389 | new_alpha = self._alpha * (1 << d_div_2)
390 | if d_mod_2:
391 | new_alpha *= ZRootTwo(0, 1)
392 | return self.__class__(new_alpha, self._k)
393 |
394 | def mul_by_sqrt2_power_renewing_denomexp(self, d):
395 | if d > self._k:
396 | raise ValueError
397 | return self.__class__(self._alpha, self._k - d)
398 |
399 | @cached_property
400 | def parity(self):
401 | return self._alpha.parity
402 |
403 | @cached_property
404 | def scale(self):
405 | return pow_sqrt2(self._k)
406 |
407 | @cached_property
408 | def squared_scale(self):
409 | return 1 << self._k
410 |
411 | @cached_property
412 | def to_real(self):
413 | return self.alpha.to_real / self.scale
414 |
415 | @cached_property
416 | def conj_sq2(self):
417 | return (self.__class__(- self._alpha.conj_sq2, self._k) if self._k & 1
418 | else self.__class__(self._alpha.conj_sq2, self._k))
419 |
420 | @classmethod
421 | def power_of_inv_sqrt2(cls, k):
422 | return cls(ZRootTwo(1, 0), k)
423 |
424 |
425 | class ZOmega():
426 | def __init__(self, a, b, c, d):
427 | self._a = a
428 | self._b = b
429 | self._c = c
430 | self._d = d
431 |
432 | @property
433 | def a(self):
434 | return self._a
435 |
436 | @property
437 | def b(self):
438 | return self._b
439 |
440 | @property
441 | def c(self):
442 | return self._c
443 |
444 | @property
445 | def d(self):
446 | return self._d
447 |
448 | @cached_property
449 | def coef(self):
450 | return [self._d, self._c, self._b, self._a]
451 |
452 | def __repr__(self):
453 | return f"ZOmega({self._a}, {self._b}, {self._c}, {self._d})"
454 |
455 | def __str__(self):
456 | return f"{self._a}ω^3{self._b:+}ω^2{self._c:+}ω{self._d:+}"
457 |
458 | @classmethod
459 | def from_int(cls, x):
460 | return cls(0, 0, 0, x)
461 |
462 | @classmethod
463 | def from_zroottwo(cls, x):
464 | return cls(-x.b, 0, x.b, x.a)
465 |
466 | def __eq__(self, other):
467 | if isinstance(other, numbers.Integral):
468 | return self == self.from_int(other)
469 | elif isinstance(other, ZRootTwo):
470 | return self == self.from_zroottwo(other)
471 | elif isinstance(other, self.__class__):
472 | return (self._a == other.a and self._b == other.b
473 | and self._c == other.c and self._d == other.d)
474 | else:
475 | return False
476 |
477 | def __add__(self, other):
478 | if isinstance(other, numbers.Integral):
479 | return self + self.from_int(other)
480 | elif isinstance(other, ZRootTwo):
481 | return self + self.from_zroottwo(other)
482 | elif isinstance(other, self.__class__):
483 | return self.__class__(self._a + other.a, self._b + other.b,
484 | self._c + other.c, self._d + other.d)
485 | else:
486 | return NotImplemented
487 |
488 | def __radd__(self, other):
489 | if isinstance(other, numbers.Integral):
490 | return self + other
491 | elif isinstance(other, ZRootTwo):
492 | return self + other
493 | elif isinstance(other, self.__class__):
494 | return self + other
495 | else:
496 | return NotImplemented
497 |
498 | def __sub__(self, other):
499 | return self + (- other)
500 |
501 | def __rsub__(self, other):
502 | return (-self) + other
503 |
504 | def __neg__(self):
505 | return self.__class__(-self._a, -self._b, -self._c, -self._d)
506 |
507 | def __mul__(self, other):
508 | if isinstance(other, numbers.Integral):
509 | return self * self.from_int(other)
510 | elif isinstance(other, ZRootTwo):
511 | return self * self.from_zroottwo(other)
512 | elif isinstance(other, self.__class__):
513 | new_coef = [0] * 4
514 | for i in range(4):
515 | for j in range(4):
516 | if i + j < 4:
517 | new_coef[i + j] += self.coef[i] * other.coef[j]
518 | else:
519 | new_coef[i + j - 4] -= self.coef[i] * other.coef[j]
520 | return self.__class__(*reversed(new_coef))
521 | else:
522 | return NotImplemented
523 |
524 | def __rmul__(self, other):
525 | if isinstance(other, numbers.Integral):
526 | return self * other
527 | elif isinstance(other, ZRootTwo):
528 | return self * other
529 | elif isinstance(other, self.__class__):
530 | return self * other
531 | else:
532 | return NotImplemented
533 |
534 | @cached_property
535 | def inv(self):
536 | if self.norm == 1:
537 | return self.conj_sq2 * self.conj * self.conj.conj_sq2
538 | else:
539 | raise ZeroDivisionError
540 |
541 | def __pow__(self, other):
542 | if isinstance(other, int):
543 | if other < 0:
544 | return NotImplemented
545 | else:
546 | new = self.from_int(1)
547 | tmp = self
548 | while other > 0:
549 | if other & 1:
550 | new *= tmp
551 | tmp *= tmp
552 | other >>= 1
553 | return new
554 | else:
555 | return NotImplemented
556 |
557 | def __divmod__(self, other):
558 | if isinstance(other, numbers.Integral):
559 | return divmod(self, self.from_int(other))
560 | elif isinstance(other, ZRootTwo):
561 | return divmod(self, self.from_zroottwo(other))
562 | elif isinstance(other, self.__class__):
563 | p = self * other.conj * other.conj.conj_sq2 * other.conj_sq2
564 | k = other.norm
565 | q = self.__class__(rounddiv(p.a, k), rounddiv(p.b, k),
566 | rounddiv(p.c, k), rounddiv(p.d, k))
567 | r = self - other * q
568 | return q, r
569 | else:
570 | return NotImplemented
571 |
572 | def __rdivmod__(self, other):
573 | if isinstance(other, numbers.Integral):
574 | return divmod(self.from_int(other), self)
575 | elif isinstance(other, ZRootTwo):
576 | return divmod(self.from_zroottwo(other), self)
577 | elif isinstance(other, self.__class__):
578 | return divmod(other, self)
579 | else:
580 | return NotImplemented
581 |
582 | def __floordiv__(self, other):
583 | q, _ = divmod(self, other)
584 | return q
585 |
586 | def __rfloordiv__(self, other):
587 | q, _ = divmod(other, self)
588 | return q
589 |
590 | def __mod__(self, other):
591 | _, r = divmod(self, other)
592 | return r
593 |
594 | def __rmod__(self, other):
595 | _, r = divmod(other, self)
596 | return r
597 |
598 | @classmethod
599 | def sim(cls, a, b):
600 | return a % b == 0 and b % a == 0
601 |
602 | @classmethod
603 | def ext_gcd(cls, a, b):
604 | if isinstance(a, numbers.Integral):
605 | a = cls.from_int(a)
606 | elif isinstance(a, ZRootTwo):
607 | a = cls.from_zroottwo(a)
608 | if isinstance(b, numbers.Integral):
609 | b = cls.from_int(b)
610 | elif isinstance(b, ZRootTwo):
611 | b = cls.from_zroottwo(b)
612 | x = cls.from_int(1)
613 | y = cls.from_int(0)
614 | z = cls.from_int(0)
615 | w = cls.from_int(1)
616 | while b != 0:
617 | q, r = divmod(a, b)
618 | x, y = y, x - y * q
619 | z, w = w, z - w * q
620 | a, b = b, r
621 | return x, z, a
622 |
623 | @classmethod
624 | def gcd(cls, a, b):
625 | _, _, g = cls.ext_gcd(a, b)
626 | return g
627 |
628 | def mul_by_omega(self):
629 | return self.__class__(self._b, self._c, self._d, -self._a)
630 |
631 | def mul_by_omega_inv(self):
632 | return self.__class__(-self._d, self._a, self._b, self._c)
633 |
634 | def mul_by_omega_power(self, n):
635 | if n >= 8 or n < 0:
636 | n &= 0b111
637 | if n & 0b100:
638 | return (-self).mul_by_omega_power(n & 0b11)
639 | else:
640 | coef = self.coef
641 | new_coef = [0] * 4
642 | for i in range(n):
643 | new_coef[i] = -coef[i - n]
644 | for i in range(n, 4):
645 | new_coef[i] = coef[i - n]
646 | return self.__class__(*reversed(new_coef))
647 |
648 | @cached_property
649 | def residue(self):
650 | return (self._a & 1) << 3 | (self._b & 1) << 2 | (self._c & 1) << 1 | (self._d & 1)
651 |
652 | @cached_property
653 | def norm(self):
654 | return ((self._a ** 2 + self._b ** 2 + self._c ** 2 + self._d ** 2) ** 2
655 | - 2 * (self._a * self._b + self._b * self._c
656 | + self._c * self._d - self._d * self._a) ** 2)
657 |
658 | @cached_property
659 | def real(self):
660 | return self._d + SQRT2() * (self._c - self._a) / 2
661 |
662 | @cached_property
663 | def imag(self):
664 | return self._b + SQRT2() * (self._c + self._a) / 2
665 |
666 | @cached_property
667 | def to_complex(self):
668 | return self.real + 1.j * self.imag
669 |
670 | @cached_property
671 | def to_vector(self):
672 | return mpmath.matrix([self.real, self.imag])
673 |
674 | @cached_property
675 | def conj(self):
676 | return self.__class__(-self._c, -self._b, -self._a, self._d)
677 |
678 | @cached_property
679 | def conj_sq2(self):
680 | return self.__class__(-self._a, self._b, -self._c, self._d)
681 |
682 |
683 | class DOmega():
684 | def __init__(self, u, k):
685 | self._u = u
686 | self._k = k
687 |
688 | @property
689 | def u(self):
690 | return self._u
691 |
692 | @property
693 | def k(self):
694 | return self._k
695 |
696 | def __repr__(self):
697 | return f"DOmega({repr(self._u)}, {self._k})"
698 |
699 | def __str__(self):
700 | return f"{self._u} / √2^{self._k}"
701 |
702 | @classmethod
703 | def from_int(cls, x):
704 | return cls(ZOmega.from_int(x), 0)
705 |
706 | @classmethod
707 | def from_zroottwo(cls, x):
708 | return cls(ZOmega.from_zroottwo(x), 0)
709 |
710 | @classmethod
711 | def from_droottwo(cls, x):
712 | return cls(ZOmega.from_zroottwo(x.alpha), x.k)
713 |
714 | @classmethod
715 | def from_droottwo_vector(cls, x, y, k):
716 | return (cls.from_droottwo(x) + cls.from_droottwo(y) * ZOmega(0, 1, 0, 0)).renew_denomexp(k)
717 |
718 | @classmethod
719 | def from_zomega(cls, x):
720 | return cls(x, 0)
721 |
722 | def __eq__(self, other):
723 | if isinstance(other, numbers.Integral):
724 | return self == self.from_int(other)
725 | elif isinstance(other, ZRootTwo):
726 | return self == self.from_zroottwo(other)
727 | elif isinstance(other, ZOmega):
728 | return self == self.from_zomega(other)
729 | elif isinstance(other, self.__class__):
730 | if self._k < other.k:
731 | return self.renew_denomexp(other.k) == other
732 | elif self._k > other.k:
733 | return self == other.renew_denomexp(self._k)
734 | else:
735 | return self._u == other.u and self._k == other.k
736 | else:
737 | return False
738 |
739 | def __add__(self, other):
740 | if isinstance(other, numbers.Integral):
741 | return self + self.from_int(other)
742 | elif isinstance(other, ZRootTwo):
743 | return self + self.from_zroottwo(other)
744 | elif isinstance(other, ZOmega):
745 | return self + self.from_zomega(other)
746 | elif isinstance(other, self.__class__):
747 | if self._k < other.k:
748 | return self.renew_denomexp(other.k) + other
749 | elif self._k > other.k:
750 | return self + other.renew_denomexp(self._k)
751 | else:
752 | return self.__class__(self._u + other.u, self._k)
753 | else:
754 | return NotImplemented
755 |
756 | def __radd__(self, other):
757 | if isinstance(other, numbers.Integral):
758 | return self + other
759 | elif isinstance(other, ZRootTwo):
760 | return self + other
761 | elif isinstance(other, ZOmega):
762 | return self + other
763 | elif isinstance(other, self.__class__):
764 | return self + other
765 | else:
766 | return NotImplemented
767 |
768 | def __sub__(self, other):
769 | return self + (- other)
770 |
771 | def __rsub__(self, other):
772 | return (-self) + other
773 |
774 | def __neg__(self):
775 | return self.__class__(-self._u, self._k)
776 |
777 | def __mul__(self, other):
778 | if isinstance(other, numbers.Integral):
779 | return self * self.from_int(other)
780 | elif isinstance(other, ZRootTwo):
781 | return self * self.from_zroottwo(other)
782 | elif isinstance(other, ZOmega):
783 | return self * self.from_zomega(other)
784 | elif isinstance(other, self.__class__):
785 | return self.__class__(self._u * other.u, self._k + other.k)
786 | else:
787 | return NotImplemented
788 |
789 | def __rmul__(self, other):
790 | if isinstance(other, numbers.Integral):
791 | return self * other
792 | elif isinstance(other, ZRootTwo):
793 | return self * other
794 | elif isinstance(other, ZOmega):
795 | return self * other
796 | elif isinstance(other, self.__class__):
797 | return self * other
798 | else:
799 | return NotImplemented
800 |
801 | def renew_denomexp(self, new_k):
802 | new_u = self.mul_by_sqrt2_power(new_k - self._k).u
803 | return self.__class__(new_u, new_k)
804 |
805 | def reduce_denomexp(self):
806 | k_a = self._k if self._u.a == 0 else ntz(self._u.a)
807 | k_b = self._k if self._u.b == 0 else ntz(self._u.b)
808 | k_c = self._k if self._u.c == 0 else ntz(self._u.c)
809 | k_d = self._k if self._u.d == 0 else ntz(self._u.d)
810 | reduce_k = min(k_a, k_b, k_c, k_d)
811 | new_k = self._k - reduce_k * 2
812 | bit = (1 << (reduce_k + 1)) - 1
813 | if (self._u.c + self._u.a) & bit == 0 and (self._u.b + self._u.d) & bit == 0:
814 | new_k -= 1
815 | return self.renew_denomexp(0 if new_k < 0 else new_k)
816 |
817 | def mul_by_inv_sqrt2(self):
818 | if not ((self._u.b + self._u.d) & 1) and not ((self._u.c + self._u.a) & 1):
819 | new_u = ZOmega((self._u.b - self._u.d) >> 1,
820 | (self._u.c + self._u.a) >> 1,
821 | (self._u.b + self._u.d) >> 1,
822 | (self._u.c - self._u.a) >> 1)
823 | else:
824 | raise ValueError
825 | return self.__class__(new_u, self._k)
826 |
827 | def mul_by_sqrt2_power(self, d):
828 | if d < 0:
829 | if d == -1:
830 | return self.mul_by_inv_sqrt2()
831 | d_div_2, d_mod_2 = (-d) >> 1, (-d) & 1
832 | if d_mod_2 == 0:
833 | bit = (1 << d_div_2) - 1
834 | if (self._u.a & bit == 0 and self._u.b & bit == 0
835 | and self._u.c & bit == 0 and self._u.c & bit == 0):
836 | new_u = ZOmega(self._u.a >> d_div_2, self._u.b >> d_div_2,
837 | self._u.c >> d_div_2, self._u.d >> d_div_2)
838 | else:
839 | raise ValueError
840 | else:
841 | bit = (1 << (d_div_2 + 1)) - 1
842 | if ((self._u.b - self._u.d) & bit == 0
843 | and (self._u.c + self._u.a) & bit == 0
844 | and (self._u.b + self._u.d) & bit == 0
845 | and (self._u.c - self._u.a) & bit == 0):
846 | new_u = ZOmega((self._u.b - self._u.d) >> (d_div_2 + 1),
847 | (self._u.c + self._u.a) >> (d_div_2 + 1),
848 | (self._u.b + self._u.d) >> (d_div_2 + 1),
849 | (self._u.c - self._u.a) >> (d_div_2 + 1))
850 | else:
851 | raise ValueError
852 | return self.__class__(new_u, self._k)
853 | else:
854 | d_div_2, d_mod_2 = d >> 1, d & 1
855 | new_u = self._u * (1 << d_div_2)
856 | if d_mod_2:
857 | new_u *= ZOmega(-1, 0, 1, 0)
858 | return self.__class__(new_u, self._k)
859 |
860 | def mul_by_omega(self):
861 | return self.__class__(self._u.mul_by_omega(), self._k)
862 |
863 | def mul_by_omega_inv(self):
864 | return self.__class__(self._u.mul_by_omega_inv(), self._k)
865 |
866 | def mul_by_omega_power(self, n):
867 | return self.__class__(self._u.mul_by_omega_power(n), self._k)
868 |
869 | @cached_property
870 | def scale(self):
871 | return pow_sqrt2(self._k)
872 |
873 | @cached_property
874 | def squared_scale(self):
875 | return 1 << self._k
876 |
877 | @property
878 | def residue(self):
879 | return self._u.residue
880 |
881 | @cached_property
882 | def real(self):
883 | return self._u.real / self.scale
884 |
885 | @cached_property
886 | def imag(self):
887 | return self._u.imag / self.scale
888 |
889 | @cached_property
890 | def to_complex(self):
891 | return self.real + 1.j * self.imag
892 |
893 | @cached_property
894 | def to_vector(self):
895 | return mpmath.matrix([self.real, self.imag])
896 |
897 | @cached_property
898 | def conj(self):
899 | return self.__class__(self._u.conj, self._k)
900 |
901 | @cached_property
902 | def conj_sq2(self):
903 | return (self.__class__(- self._u.conj_sq2, self._k) if self._k & 1
904 | else self.__class__(self._u.conj_sq2, self._k))
905 |
906 |
907 | LAMBDA = ZRootTwo(1, 1)
908 | OMEGA = ZOmega(0, 0, 1, 0)
909 | OMEGA_POWER = [ZOmega(0, 0, 0, 1), ZOmega(0, 0, 1, 0), ZOmega(0, 1, 0, 0), ZOmega(1, 0, 0, 0),
910 | ZOmega(0, 0, 0, -1), ZOmega(0, 0, -1, 0), ZOmega(0, -1, 0, 0), ZOmega(-1, 0, 0, 0)]
911 |
--------------------------------------------------------------------------------
/pygridsynth/synthesis_of_cliffordT.py:
--------------------------------------------------------------------------------
1 | from .ring import OMEGA_POWER
2 | from .unitary import DOmegaUnitary
3 | from .normal_form import NormalForm
4 |
5 | BIT_SHIFT = [0, 0, 1, 0, 2, 0, 1, 3, 3, 3, 0, 2, 2, 1, 0, 0]
6 | BIT_COUNT = [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4]
7 |
8 |
9 | def _reduce_denomexp(unitary):
10 | T_POWER_and_H = ["H", "TH", "SH", "TSH"]
11 | residue_z = unitary.z.residue
12 | residue_w = unitary.w.residue
13 | residue_squared_z = (unitary.z.u * unitary.z.conj.u).residue
14 |
15 | m = BIT_SHIFT[residue_w] - BIT_SHIFT[residue_z]
16 | if m < 0:
17 | m += 4
18 | if residue_squared_z == 0b0000:
19 | unitary = unitary.mul_by_H_and_T_power_from_left(0).renew_denomexp(unitary.k - 1)
20 | return T_POWER_and_H[0], unitary
21 | elif residue_squared_z == 0b1010:
22 | unitary = unitary.mul_by_H_and_T_power_from_left(-m).renew_denomexp(unitary.k - 1)
23 | return T_POWER_and_H[m], unitary
24 | elif residue_squared_z == 0b0001:
25 | if BIT_COUNT[residue_z] == BIT_COUNT[residue_w]:
26 | unitary = unitary.mul_by_H_and_T_power_from_left(-m).renew_denomexp(unitary.k - 1)
27 | return T_POWER_and_H[m], unitary
28 | else:
29 | unitary = unitary.mul_by_H_and_T_power_from_left(-m)
30 | return T_POWER_and_H[m], unitary
31 |
32 |
33 | def decompose_domega_unitary(unitary):
34 | gates = ""
35 | while unitary.k > 0:
36 | g, unitary = _reduce_denomexp(unitary)
37 | gates += g
38 |
39 | if unitary.n & 1:
40 | gates += "T"
41 | unitary = unitary.mul_by_T_inv_from_left()
42 | if unitary.z == 0:
43 | gates += "X"
44 | unitary = unitary.mul_by_X_from_left()
45 | for m in range(8):
46 | if unitary.z == OMEGA_POWER[m]:
47 | m_W = m
48 | unitary = unitary.mul_by_W_power_from_left(-m_W)
49 | break
50 | m_S = unitary.n >> 1
51 | gates += "S" * m_S
52 | unitary = unitary.mul_by_S_power_from_left(-m_S)
53 | gates += "W" * m_W
54 |
55 | assert unitary == DOmegaUnitary.identity(), "decomposition failed..."
56 | gates = NormalForm.from_gates(gates).to_gates()
57 | return gates
58 |
--------------------------------------------------------------------------------
/pygridsynth/tdgp.py:
--------------------------------------------------------------------------------
1 | from .ring import DRootTwo, DOmega
2 | from .region import Interval
3 | from .odgp import solve_scaled_ODGP, solve_scaled_ODGP_with_parity
4 | from .myplot import plot_sol
5 |
6 |
7 | def solve_TDGP(setA, setB, opG, ellipseA_upright, ellipseB_upright, bboxA, bboxB, k,
8 | verbose=False, show_graph=False):
9 | sol_sufficient = []
10 | sol_x = solve_scaled_ODGP(bboxA.I_x, bboxB.I_x, k + 1)
11 | sol_y = solve_scaled_ODGP(bboxA.I_y.fatten(bboxA.I_y.width * 1e-4),
12 | bboxB.I_y.fatten(bboxB.I_y.width * 1e-4),
13 | k + 1)
14 | if len(sol_x) <= 0 or len(sol_y) <= 0:
15 | sol_sufficient = []
16 | else:
17 | alpha0 = sol_x[0]
18 | for beta in sol_y:
19 | dx = DRootTwo.power_of_inv_sqrt2(k)
20 | z0 = opG.inv * DOmega.from_droottwo_vector(alpha0, beta, k + 1)
21 | v = opG.inv * DOmega.from_droottwo_vector(dx, DRootTwo.from_int(0), k)
22 | t_A = setA.intersect(z0, v)
23 | t_B = setB.intersect(z0.conj_sq2, v.conj_sq2)
24 | if t_A is None or t_B is None:
25 | continue
26 |
27 | parity = (beta - alpha0).mul_by_sqrt2_power_renewing_denomexp(k)
28 | intA, intB = Interval(*t_A), Interval(*t_B)
29 | dtA = 10 / max(10, (1 << k) * intB.width)
30 | dtB = 10 / max(10, (1 << k) * intA.width)
31 | intA, intB = intA.fatten(dtA), intB.fatten(dtB)
32 | sol_t = solve_scaled_ODGP_with_parity(intA, intB, 1, parity)
33 | sol_x = [alpha * dx + alpha0 for alpha in sol_t]
34 | for alpha in sol_x:
35 | sol_sufficient.append(DOmega.from_droottwo_vector(alpha, beta, k))
36 | sol_transformed = [opG.inv * z for z in sol_sufficient]
37 | sol = [z for z in sol_transformed if setA.inside(z) and setB.inside(z.conj_sq2)]
38 |
39 | if verbose and len(sol_sufficient) > 0:
40 | print(f"{k=}")
41 | print(f"size of sol_sufficient: {len(sol_sufficient)}, size of sol: {len(sol)}")
42 | if show_graph and len(sol_sufficient) > 0:
43 | plot_sol([sol_transformed, sol], setA.ellipse, setB.ellipse, None, None,
44 | color_list=['limegreen', 'blue'], size_list=[5, 10])
45 |
46 | return sol
47 |
--------------------------------------------------------------------------------
/pygridsynth/to_upright.py:
--------------------------------------------------------------------------------
1 | from .mymath import log, floorsqrt
2 | from .ring import ZOmega, LAMBDA
3 | from .grid_op import EllipsePair, GridOp
4 | from .myplot import plot_sol
5 |
6 |
7 | def _reduction(ellipse_pair, opG_l, opG_r, new_opG):
8 | return new_opG * ellipse_pair, opG_l, new_opG * opG_r, False
9 |
10 |
11 | def _shift_ellipse_pair(ellipse_pair, n):
12 | lambda_n = LAMBDA ** n
13 | lambda_inv_n = LAMBDA ** -n
14 | ellipse_pair.A.a *= lambda_inv_n.to_real
15 | ellipse_pair.A.d *= lambda_n.to_real
16 | ellipse_pair.B.a *= lambda_n.to_real
17 | ellipse_pair.B.d *= lambda_inv_n.to_real
18 | if n & 1:
19 | ellipse_pair.B.b = -ellipse_pair.B.b
20 | return ellipse_pair
21 |
22 |
23 | def _step_lemma(ellipse_pair, opG_l, opG_r, verbose=False):
24 | A = ellipse_pair.A
25 | B = ellipse_pair.B
26 | if verbose:
27 | print("-----")
28 | print(f"skew: {ellipse_pair.skew}, bias: {ellipse_pair.bias}")
29 | print(f"bias(A): {A.bias}, bias(B): {B.bias}, "
30 | + "sign(A.b):" + ("+" if A.b >= 0 else "-")
31 | + ", sign(B.b):" + ("+" if B.b >= 0 else "-"))
32 | print("-----")
33 | if B.b < 0:
34 | if verbose:
35 | print("Z")
36 | OP_Z = GridOp(ZOmega(0, 0, 0, 1), ZOmega(0, -1, 0, 0))
37 | return _reduction(ellipse_pair, opG_l, opG_r, OP_Z)
38 | elif A.bias * B.bias < 1:
39 | if verbose:
40 | print("X")
41 | OP_X = GridOp(ZOmega(0, 1, 0, 0), ZOmega(0, 0, 0, 1))
42 | return _reduction(ellipse_pair, opG_l, opG_r, OP_X)
43 | elif ellipse_pair.bias > 33.971 or ellipse_pair.bias < 0.029437:
44 | n = round(log(ellipse_pair.bias) / log(LAMBDA.to_real) / 8)
45 | OP_S = GridOp(ZOmega(-1, 0, 1, 1), ZOmega(1, -1, 1, 0))
46 | if verbose:
47 | print(f"S ({n=})")
48 | return _reduction(ellipse_pair, opG_l, opG_r, OP_S ** n)
49 | elif ellipse_pair.skew <= 15:
50 | return ellipse_pair, opG_l, opG_r, True
51 | elif ellipse_pair.bias > 5.8285 or ellipse_pair.bias < 0.17157:
52 | n = round(log(ellipse_pair.bias) / log(LAMBDA.to_real) / 4)
53 | ellipse_pair = _shift_ellipse_pair(ellipse_pair, n)
54 | if verbose:
55 | print(f"sigma ({n=})")
56 | if n >= 0:
57 | OP_SIGMA_L = GridOp(ZOmega(-1, 0, 1, 1), ZOmega(0, 1, 0, 0)) ** n
58 | OP_SIGMA_R = GridOp(ZOmega(0, 0, 0, 1), ZOmega(1, -1, 1, 0)) ** n
59 | else:
60 | OP_SIGMA_L = GridOp(ZOmega(-1, 0, 1, -1), ZOmega(0, 1, 0, 0)) ** (-n)
61 | OP_SIGMA_R = GridOp(ZOmega(0, 0, 0, 1), ZOmega(1, 1, 1, 0)) ** (-n)
62 | return ellipse_pair, opG_l * OP_SIGMA_L, OP_SIGMA_R * opG_r, False
63 | elif 0.24410 <= A.bias <= 4.0968 and 0.24410 <= B.bias <= 4.0968:
64 | if verbose:
65 | print("R")
66 | OP_R = GridOp(ZOmega(0, 0, 1, 0), ZOmega(1, 0, 0, 0))
67 | return _reduction(ellipse_pair, opG_l, opG_r, OP_R)
68 | elif A.b >= 0 and A.bias <= 1.6969:
69 | if verbose:
70 | print("K")
71 | OP_K = GridOp(ZOmega(-1, -1, 0, 0), ZOmega(0, -1, 1, 0))
72 | return _reduction(ellipse_pair, opG_l, opG_r, OP_K)
73 | elif A.b >= 0 and B.bias <= 1.6969:
74 | if verbose:
75 | print("K_conj_sq2")
76 | OP_K_conj_sq2 = GridOp(ZOmega(1, -1, 0, 0), ZOmega(0, -1, -1, 0))
77 | return _reduction(ellipse_pair, opG_l, opG_r, OP_K_conj_sq2)
78 | elif A.b >= 0:
79 | n = max(1, floorsqrt(min(A.bias, B.bias) / 4))
80 | if verbose:
81 | print(f"A ({n=})")
82 | OP_A_n = GridOp(ZOmega(0, 0, 0, 1), ZOmega(0, 1, 0, 2 * n))
83 | return _reduction(ellipse_pair, opG_l, opG_r, OP_A_n)
84 | else:
85 | n = max(1, floorsqrt(min(A.bias, B.bias) / 2))
86 | if verbose:
87 | print(f"B ({n=})")
88 | OP_B_n = GridOp(ZOmega(0, 0, 0, 1), ZOmega(n, 1, -n, 0))
89 | return _reduction(ellipse_pair, opG_l, opG_r, OP_B_n)
90 |
91 |
92 | def _to_upright_ellipse_pair(ellipseA, ellipseB, verbose=False):
93 | ellipseA_normalized = ellipseA.normalize()
94 | ellipseB_normalized = ellipseB.normalize()
95 | ellipse_pair = EllipsePair(ellipseA_normalized, ellipseB_normalized)
96 | OP_I = GridOp(ZOmega(0, 0, 0, 1), ZOmega(0, 1, 0, 0))
97 | opG_l, opG_r = OP_I, OP_I
98 | while True:
99 | ellipse_pair, opG_l, opG_r, end = _step_lemma(ellipse_pair, opG_l, opG_r, verbose=verbose)
100 | if end:
101 | break
102 | return opG_l * opG_r
103 |
104 |
105 | def to_upright_set_pair(setA, setB, show_graph, verbose=False):
106 | opG = _to_upright_ellipse_pair(setA.ellipse, setB.ellipse, verbose=verbose)
107 | ellipse_pair = opG * EllipsePair(setA.ellipse, setB.ellipse)
108 | ellipseA_upright = ellipse_pair.A
109 | ellipseB_upright = ellipse_pair.B
110 | bboxA = ellipseA_upright.bbox()
111 | bboxB = ellipseB_upright.bbox()
112 | upA = ellipseA_upright.area / bboxA.area
113 | upB = ellipseB_upright.area / bboxB.area
114 | if verbose:
115 | print(f"{upA=}, {upB=}")
116 | if show_graph:
117 | plot_sol([], ellipseA_upright, ellipseB_upright, bboxA, bboxB)
118 | return opG, ellipseA_upright, ellipseB_upright, bboxA, bboxB
119 |
--------------------------------------------------------------------------------
/pygridsynth/unitary.py:
--------------------------------------------------------------------------------
1 | from functools import cached_property
2 | import mpmath
3 |
4 | from .ring import DOmega
5 |
6 |
7 | class DOmegaUnitary():
8 | def __init__(self, z, w, n, k=None):
9 | if n >= 8 or n < 0:
10 | n &= 0b111
11 | self._n = n
12 | if k is None:
13 | if z.k > w.k:
14 | w = w.renew_denomexp(z.k)
15 | elif z.k < w.k:
16 | z = z.renew_denomexp(w.k)
17 | else:
18 | z = z.renew_denomexp(k)
19 | w = w.renew_denomexp(k)
20 | self._z = z
21 | self._w = w
22 |
23 | @property
24 | def z(self):
25 | return self._z
26 |
27 | @property
28 | def w(self):
29 | return self._w
30 |
31 | @property
32 | def n(self):
33 | return self._n
34 |
35 | @property
36 | def k(self):
37 | return self._w.k
38 |
39 | @cached_property
40 | def to_matrix(self):
41 | return [[self._z, -self._w.conj.mul_by_omega_power(self._n)],
42 | [self._w, self._z.conj.mul_by_omega_power(self._n)]]
43 |
44 | @cached_property
45 | def to_complex_matrix(self):
46 | return mpmath.matrix([[self._z.to_complex, -self._w.conj.mul_by_omega_power(self._n).to_complex],
47 | [self._w.to_complex, self._z.conj.mul_by_omega_power(self._n).to_complex]])
48 |
49 | def __repr__(self):
50 | return f"DOmegaUnitary({repr(self._z)}, {repr(self._w)}, {self._n})"
51 |
52 | def __str__(self):
53 | return str(self.to_matrix)
54 |
55 | def __eq__(self, other):
56 | if isinstance(other, self.__class__):
57 | return self._z == other.z and self._w == other.w and self._n == other.n
58 | else:
59 | return False
60 |
61 | def mul_by_T_from_left(self):
62 | return self.__class__(self._z, self._w.mul_by_omega(), self._n + 1)
63 |
64 | def mul_by_T_inv_from_left(self):
65 | return self.__class__(self._z, self._w.mul_by_omega_inv(), self._n - 1)
66 |
67 | def mul_by_T_power_from_left(self, m):
68 | if m >= 8 or m < 0:
69 | m &= 0b111
70 | return self.__class__(self._z, self._w.mul_by_omega_power(m), self._n + m)
71 |
72 | def mul_by_S_from_left(self):
73 | return self.__class__(self._z, self._w.mul_by_omega_power(2), self._n + 2)
74 |
75 | def mul_by_S_power_from_left(self, m):
76 | if m >= 4 or m < 0:
77 | m &= 0b11
78 | return self.__class__(self._z, self._w.mul_by_omega_power(m << 1), self._n + (m << 1))
79 |
80 | def mul_by_H_from_left(self):
81 | new_z = (self._z + self._w).mul_by_inv_sqrt2()
82 | new_w = (self._z - self._w).mul_by_inv_sqrt2()
83 | return self.__class__(new_z, new_w, self._n + 4)
84 |
85 | def mul_by_H_and_T_power_from_left(self, m):
86 | return self.mul_by_T_power_from_left(m).mul_by_H_from_left()
87 |
88 | def mul_by_X_from_left(self):
89 | return self.__class__(self._w, self._z, self._n + 4)
90 |
91 | def mul_by_W_from_left(self):
92 | return self.__class__(self._z.mul_by_omega(), self._w.mul_by_omega(), self._n + 2)
93 |
94 | def mul_by_W_power_from_left(self, m):
95 | if m >= 8 or m < 0:
96 | m &= 0b111
97 | return self.__class__(self._z.mul_by_omega_power(m), self._w.mul_by_omega_power(m),
98 | self._n + (m << 1))
99 |
100 | def renew_denomexp(self, new_k):
101 | return self.__class__(self._z, self._w, self._n, new_k)
102 |
103 | def reduce_denomexp(self):
104 | new_z = self._z.reduce_denomexp()
105 | new_w = self._w.reduce_denomexp()
106 | return self.__class__(new_z, new_w, self._n)
107 |
108 | @classmethod
109 | def identity(cls):
110 | return cls(DOmega.from_int(1), DOmega.from_int(0), 0)
111 |
112 | @classmethod
113 | def from_gates(cls, gates):
114 | unitary = cls.identity()
115 | for g in reversed(gates):
116 | if g == "H":
117 | unitary = unitary.renew_denomexp(unitary.k + 1).mul_by_H_from_left()
118 | elif g == "T":
119 | unitary = unitary.mul_by_T_from_left()
120 | elif g == "S":
121 | unitary = unitary.mul_by_S_from_left()
122 | elif g == "X":
123 | unitary = unitary.mul_by_X_from_left()
124 | elif g == "W":
125 | unitary = unitary.mul_by_W_from_left()
126 | return unitary.reduce_denomexp()
127 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "pygridsynth"
3 | version = "1.1.0"
4 | authors = [{ name="Shuntaro Yamamoto", email="shun0923@g.ecc.u-tokyo.ac.jp" }, { name="Nobuyuki Yoshioka", email="nyoshioka@g.ecc.u-tokyo.ac.jp" }]
5 | description = "Python version of the gridsynth program that computes approximations of z-rotations over the Clifford+T gate set."
6 | readme = "README.md"
7 | license = {file = "LICENSE"}
8 | requires-python = ">=3.8"
9 | classifiers = [
10 | "Development Status :: 4 - Beta",
11 | "Programming Language :: Python :: 3",
12 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
13 | ]
14 |
15 | dependencies = [
16 | "mpmath",
17 | ]
18 |
19 | [tool.setuptools]
20 | packages = ["pygridsynth"]
21 |
22 | [project.scripts]
23 | pygridsynth = "pygridsynth:main"
24 |
25 | [project.urls]
26 | "Homepage" = "https://github.com/quantum-programming/clifford-T-decomp"
27 | "Bug Tracker" = "https://github.com/quantum-programming/clifford-T-decomp/issues"
28 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | mpmath
--------------------------------------------------------------------------------