-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Implement circuit_to_latex_using_qcircuit #295
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
226c9ae
Refactor AsciiDiagrammableGate into TextDiagrammableGate
Strilanc 369c6b8
lint
Strilanc 544bf4f
Merge branch 'master' of github.com:quantumlib/cirq into qcircuit
Strilanc 7264a65
Merge branch 'master' of github.com:quantumlib/cirq into qcircuit2
Strilanc db8ad21
Implement circuit_to_latex_using_qcircuit
Strilanc fff72f1
types
Strilanc 641638a
escape
Strilanc 765d779
Merge branch 'master' of github.com:quantumlib/cirq into qcircuit2
Strilanc de733c0
Merge branch 'master' into qcircuit2
Strilanc File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,3 +19,4 @@ | |
| """ | ||
|
|
||
| from cirq.contrib import jobs | ||
| from cirq.contrib.qcircuit_diagram import circuit_to_latex_using_qcircuit | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| # Copyright 2018 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # https://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import Any, Callable, Optional | ||
|
|
||
| from cirq import abc, circuits, extension, ops | ||
| from cirq.contrib.qcircuit_diagrammable_gate import ( | ||
| QCircuitDiagrammableGate, | ||
| fallback_qcircuit_extensions, | ||
| ) | ||
|
|
||
|
|
||
| class _QCircuitQubit(ops.QubitId): | ||
| def __init__(self, sub: ops.QubitId) -> None: | ||
| self.sub = sub | ||
|
|
||
| def __str__(self): | ||
| # TODO: If qubit name ends with digits, turn them into subscripts. | ||
| return '\\lstick{\\text{' + str(self.sub) + '}}&' | ||
|
|
||
| def __eq__(self, other): | ||
| if not isinstance(other, _QCircuitQubit): | ||
| return NotImplemented | ||
| return self.sub == other.sub | ||
|
|
||
| def __ne__(self, other): | ||
| return not self == other | ||
|
|
||
| def __hash__(self): | ||
| return hash((_QCircuitQubit, self.sub)) | ||
|
|
||
|
|
||
| class _QCircuitGate(ops.TextDiagrammableGate, metaclass=abc.ABCMeta): | ||
| def __init__(self, sub: QCircuitDiagrammableGate) -> None: | ||
| self.sub = sub | ||
|
|
||
| def text_diagram_exponent(self): | ||
| return 1 | ||
|
|
||
| def text_diagram_wire_symbols(self, | ||
| qubit_count: Optional[int] = None, | ||
| use_unicode_characters: bool = True): | ||
| return self.sub.qcircuit_wire_symbols(qubit_count) | ||
|
|
||
|
|
||
| def _render(diagram: circuits.TextDiagramDrawer) -> str: | ||
| w = diagram.width() | ||
| h = diagram.height() | ||
|
|
||
| qwx = {(x, y + 1) | ||
| for x, y1, y2 in diagram.vertical_lines | ||
| for y in range(y1, y2)} | ||
|
|
||
| qw = {(x, y) | ||
| for y, x1, x2 in diagram.horizontal_lines | ||
| for x in range(x1, x2)} | ||
|
|
||
| rows = [] | ||
| for y in range(h): | ||
| row = [] | ||
| for x in range(w): | ||
| cell = [] | ||
| key = (x, y) | ||
| v = diagram.entries.get(key) | ||
| if v is not None: | ||
| cell.append(' ' + v + ' ') | ||
| if key in qw: | ||
| cell.append('\\qw ') | ||
| if key in qwx: | ||
| cell.append('\\qwx ') | ||
| row.append(''.join(cell)) | ||
| rows.append('&'.join(row) + '\qw') | ||
|
|
||
| grid = '\\\\\n'.join(rows) | ||
|
|
||
| output = '\Qcircuit @R=1em @C=0.75em { \\\\ \n' + grid + ' \\\\ \n \\\\ }' | ||
|
|
||
| return output | ||
|
|
||
|
|
||
| def _wrap_operation(op: ops.Operation, | ||
| ext: extension.Extensions) -> ops.Operation: | ||
| new_qubits = [_QCircuitQubit(e) for e in op.qubits] | ||
| new_gate = ext.try_cast(op.gate, QCircuitDiagrammableGate) | ||
| if new_gate is None: | ||
| new_gate = fallback_qcircuit_extensions.cast(op.gate, | ||
| QCircuitDiagrammableGate) | ||
| return ops.Operation(_QCircuitGate(new_gate), new_qubits) | ||
|
|
||
|
|
||
| def _wrap_moment(moment: circuits.Moment, | ||
| ext: extension.Extensions) -> circuits.Moment: | ||
| return circuits.Moment(_wrap_operation(op, ext) | ||
| for op in moment.operations) | ||
|
|
||
|
|
||
| def _wrap_circuit(circuit: circuits.Circuit, | ||
| ext: extension.Extensions) -> circuits.Circuit: | ||
| return circuits.Circuit(_wrap_moment(moment, ext) | ||
| for moment in circuit.moments) | ||
|
|
||
|
|
||
| def circuit_to_latex_using_qcircuit( | ||
| circuit: circuits.Circuit, | ||
| ext: extension.Extensions = None, | ||
| qubit_order_key: Callable[[ops.QubitId], Any] = None) -> str: | ||
| """Returns a QCircuit-based latex diagram of the given circuit. | ||
|
|
||
| Args: | ||
| circuit: The circuit to represent in latex. | ||
| ext: Extensions used when attempting to cast gates into | ||
| QCircuitDiagrammableGate instances (before falling back to the | ||
| default wrapping methods). | ||
| qubit_order_key: Determines the order of qubit wires in the diagram. | ||
|
|
||
| Returns: | ||
| Latex code for the diagram. | ||
| """ | ||
| if ext is None: | ||
| ext = extension.Extensions() | ||
| qcircuit = _wrap_circuit(circuit, ext) | ||
| diagram = qcircuit.to_text_diagram_drawer( | ||
| ext, | ||
| qubit_name_suffix='', | ||
| qubit_order_key=(None | ||
| if qubit_order_key is None | ||
| else lambda e: qubit_order_key(e.sub))) | ||
| return _render(diagram) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| # Copyright 2018 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # https://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import Optional | ||
|
|
||
| import cirq | ||
| from cirq import Extensions, ops | ||
| from cirq import abc | ||
|
|
||
|
|
||
| class QCircuitDiagrammableGate(ops.Gate, metaclass=abc.ABCMeta): | ||
| @abc.abstractmethod | ||
| def qcircuit_wire_symbols(self, qubit_count: Optional[int] = None): | ||
| pass | ||
|
|
||
|
|
||
| def _escape_text_for_latex(text): | ||
| escaped = (text | ||
| .replace('\\', '\\textbackslash{}') | ||
| .replace('^', '\\textasciicircum{}') | ||
| .replace('~', '\\textasciitilde{}') | ||
| .replace('_', '\\_') | ||
| .replace('{', '\\{') | ||
| .replace('}', '\\}') | ||
| .replace('$', '\\$') | ||
| .replace('%', '\\%') | ||
| .replace('&', '\\&') | ||
| .replace('#', '\\#')) | ||
| return '\\text{' + escaped + '}' | ||
|
|
||
|
|
||
| class _HardcodedQCircuitSymbolsGate(QCircuitDiagrammableGate): | ||
| def __init__(self, *symbols) -> None: | ||
| self.symbols = symbols | ||
|
|
||
| def qcircuit_wire_symbols(self, qubit_count=None): | ||
| return self.symbols | ||
|
|
||
|
|
||
| class _WrappedSymbolsQCircuitGate(QCircuitDiagrammableGate): | ||
| def __init__(self, sub: ops.TextDiagrammableGate) -> None: | ||
| self.sub = sub | ||
|
|
||
| def qcircuit_wire_symbols(self, qubit_count=None): | ||
| s = self.sub.text_diagram_wire_symbols() | ||
| s = [_escape_text_for_latex(e) for e in s] | ||
| e = self.sub.text_diagram_exponent() | ||
| if e != 1: | ||
| s[0] += '^{' + str(e) + '}' | ||
| return tuple('\\gate{' + e + '}' for e in s) | ||
|
|
||
|
|
||
| class _FallbackQCircuitSymbolsGate(QCircuitDiagrammableGate): | ||
| def __init__(self, sub: ops.Gate) -> None: | ||
| self.sub = sub | ||
|
|
||
| def qcircuit_wire_symbols(self, qubit_count=None): | ||
| name = str(self.sub) | ||
| if qubit_count is None: | ||
| qubit_count = 1 | ||
| return tuple(_escape_text_for_latex('{}:{}'.format(name, i)) | ||
| for i in range(qubit_count)) | ||
|
|
||
|
|
||
| fallback_qcircuit_extensions = Extensions() | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| ops.TextDiagrammableGate, | ||
| _WrappedSymbolsQCircuitGate) | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| ops.RotXGate, | ||
| lambda gate: | ||
| _HardcodedQCircuitSymbolsGate('\\targ') | ||
| if gate.half_turns == 1 | ||
| else None) | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| ops.MeasurementGate, | ||
| lambda gate: _HardcodedQCircuitSymbolsGate('\\meter')) | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| cirq.google.ExpWGate, | ||
| lambda gate: | ||
| _HardcodedQCircuitSymbolsGate('\\targ') | ||
| if gate.half_turns == 1 and gate.axis_half_turns == 0 | ||
| else None) | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| ops.Rot11Gate, | ||
| lambda gate: | ||
| _HardcodedQCircuitSymbolsGate('\\control', '\\control') | ||
| if gate.half_turns == 1 | ||
| else None) | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| ops.CNotGate, | ||
| lambda gate: _HardcodedQCircuitSymbolsGate('\\control', '\\targ')) | ||
| fallback_qcircuit_extensions.add_cast( | ||
| QCircuitDiagrammableGate, | ||
| ops.Gate, | ||
| _FallbackQCircuitSymbolsGate) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # Copyright 2018 Google LLC | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # https://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from cirq import ops, Circuit | ||
| from cirq.contrib import circuit_to_latex_using_qcircuit | ||
|
|
||
|
|
||
| def test_teleportation_diagram(): | ||
| ali = ops.NamedQubit('alice') | ||
| car = ops.NamedQubit('carrier') | ||
| bob = ops.NamedQubit('bob') | ||
|
|
||
| circuit = Circuit.from_ops( | ||
| ops.H(car), | ||
| ops.CNOT(car, bob), | ||
| ops.X(ali)**0.5, | ||
| ops.CNOT(ali, car), | ||
| ops.H(ali), | ||
| [ops.MeasurementGate()(ali), ops.MeasurementGate()(car)], | ||
| ops.CNOT(car, bob), | ||
| ops.CZ(ali, bob)) | ||
|
|
||
| diagram = circuit_to_latex_using_qcircuit( | ||
| circuit, | ||
| qubit_order_key=[ali, car, bob].index) | ||
| assert diagram.strip() == """ | ||
| \\Qcircuit @R=1em @C=0.75em { \\\\ | ||
| \\lstick{\\text{alice}}& \\qw &\\qw & \\gate{\\text{X}^{0.5}} \\qw & \\control \\qw & \\gate{\\text{H}} \\qw & \\meter \\qw &\\qw & \\control \\qw &\\qw\\\\ | ||
| \\lstick{\\text{carrier}}& \\qw & \\gate{\\text{H}} \\qw & \\control \\qw & \\targ \\qw \\qwx &\\qw & \\meter \\qw & \\control \\qw &\\qw \\qwx &\\qw\\\\ | ||
| \\lstick{\\text{bob}}& \\qw &\\qw & \\targ \\qw \\qwx &\\qw &\\qw &\\qw & \\targ \\qw \\qwx & \\control \\qw \\qwx &\\qw \\\\ | ||
| \\\\ } | ||
| """.strip() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I might just do circuit_to_latex. If we want to support something other than qcircuit we could pass some sort of type in to this to distiguish
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I also think that could be nice; but I'll wait until we have other supported formats before amalgamating.