Skip to content

Commit f267b01

Browse files
doc: integration in pytest
+ sphinx gen OK + doc examples improved/fixed
1 parent 0ce1e7e commit f267b01

11 files changed

+199
-144
lines changed

docs/examples.rst

+1-2
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,4 @@ On this page, you will find a few notebooks we provide as examples for various
1212
notebooks/2_Execution_Bell_circuit
1313
notebooks/3_Expectation_value_of_observables
1414
notebooks/4_Quantum_Fourier_Transform
15-
notebooks/5_Variational_Quantum_Algorithms
16-
notebooks/6_Pauli_string_observable
15+
notebooks/5_Variational_Quantum_Algorithms

docs/notebooks/6_Pauli_string_observable.nblink

-3
This file was deleted.

mpqp/core/circuit.py

+25-24
Original file line numberDiff line numberDiff line change
@@ -70,13 +70,13 @@ class QCircuit:
7070
7171
Example:
7272
>>> circuit = QCircuit(2)
73-
>>> circuit.pretty_print() # doctest: +NORMALIZE_WHITESPACE
73+
>>> circuit.pretty_print() # doctest: +NORMALIZE_WHITESPACE
7474
QCircuit : Size (Qubits,Cbits) = (2, 0), Nb instructions = 0
7575
q_0:
7676
q_1:
7777
>>> circuit = QCircuit(5, nb_cbits=2, label="Circuit 1")
7878
>>> circuit.add(Rx(1.23, 3))
79-
>>> circuit.pretty_print() # doctest: +NORMALIZE_WHITESPACE
79+
>>> circuit.pretty_print() # doctest: +NORMALIZE_WHITESPACE
8080
QCircuit Circuit 1: Size (Qubits,Cbits) = (5, 2), Nb instructions = 1
8181
q_0: ────────────
8282
q_1: ────────────
@@ -137,7 +137,7 @@ def add(self, instruction: Instruction | Iterable[Instruction]):
137137
>>> circuit = QCircuit(2)
138138
>>> circuit.add(X(0))
139139
>>> circuit.add([CNOT(0, 1), BasisMeasure([0, 1], shots=100)])
140-
>>> circuit.pretty_print() # doctest: +NORMALIZE_WHITESPACE
140+
>>> circuit.pretty_print() # doctest: +NORMALIZE_WHITESPACE
141141
QCircuit : Size (Qubits,Cbits) = (2, 2), Nb instructions = 3
142142
┌───┐ ┌─┐
143143
q_0: ┤ X ├──■──┤M├───
@@ -202,7 +202,7 @@ def append(self, other: QCircuit, qubits_offset: int = 0) -> None:
202202
>>> c1 = QCircuit([CNOT(0,1),CNOT(1,2)])
203203
>>> c2 = QCircuit([X(1),CNOT(1,2)])
204204
>>> c1.append(c2)
205-
>>> print(c1) # doctest: +NORMALIZE_WHITESPACE
205+
>>> print(c1) # doctest: +NORMALIZE_WHITESPACE
206206
q_0: ──■─────────────────
207207
┌─┴─┐ ┌───┐
208208
q_1: ┤ X ├──■──┤ X ├──■──
@@ -260,7 +260,7 @@ def tensor(self, other: QCircuit) -> QCircuit:
260260
Example:
261261
>>> c1 = QCircuit([CNOT(0,1),CNOT(1,2)])
262262
>>> c2 = QCircuit([X(1),CNOT(1,2)])
263-
>>> print(c1.tensor(c2)) # doctest: +NORMALIZE_WHITESPACE
263+
>>> print(c1.tensor(c2)) # doctest: +NORMALIZE_WHITESPACE
264264
q_0: ──■───────
265265
┌─┴─┐
266266
q_1: ┤ X ├──■──
@@ -304,7 +304,7 @@ def display(self, output: str = "mpl"):
304304
┌──────┐
305305
q: ┤ P(θ) ├
306306
└──────┘
307-
>>> print(circ.display("latex_source")) # doctest: +NORMALIZE_WHITESPACE
307+
>>> print(circ.display("latex_source")) # doctest: +NORMALIZE_WHITESPACE
308308
\documentclass[border=2px]{standalone}
309309
\usepackage[braket, qm]{qcircuit}
310310
\usepackage{graphicx}
@@ -476,26 +476,26 @@ def inverse(self) -> QCircuit:
476476
477477
Examples:
478478
>>> c1 = QCircuit([H(0), CNOT(0,1)])
479-
>>> print(c1) # doctest: +NORMALIZE_WHITESPACE
479+
>>> print(c1) # doctest: +NORMALIZE_WHITESPACE
480480
┌───┐
481481
q_0: ┤ H ├──■──
482482
└───┘┌─┴─┐
483483
q_1: ─────┤ X ├
484484
└───┘
485-
>>> print(c1.inverse()) # doctest: +NORMALIZE_WHITESPACE
485+
>>> print(c1.inverse()) # doctest: +NORMALIZE_WHITESPACE
486486
┌───┐
487487
q_0: ──■──┤ H ├
488488
┌─┴─┐└───┘
489489
q_1: ┤ X ├─────
490490
└───┘
491491
>>> c2 = QCircuit([S(0), CZ(0,1), H(1), Ry(4.56, 1)])
492-
>>> print(c2) # doctest: +NORMALIZE_WHITESPACE
492+
>>> print(c2) # doctest: +NORMALIZE_WHITESPACE
493493
┌───┐
494494
q_0: ┤ S ├─■──────────────────
495495
└───┘ │ ┌───┐┌──────────┐
496496
q_1: ──────■─┤ H ├┤ Ry(4.56) ├
497497
└───┘└──────────┘
498-
>>> print(c2.inverse()) # doctest: +NORMALIZE_WHITESPACE
498+
>>> print(c2.inverse()) # doctest: +NORMALIZE_WHITESPACE
499499
┌───┐
500500
q_0: ──────────────────■─┤ S ├
501501
┌──────────┐┌───┐ │ └───┘
@@ -544,7 +544,7 @@ def initializer(cls, state: npt.NDArray[np.complex64]) -> QCircuit:
544544
545545
Examples:
546546
>>> qc = QCircuit.initializer(np.array([1, 0, 0 ,1])/np.sqrt(2))
547-
>>> print(qc) # doctest: +NORMALIZE_WHITESPACE
547+
>>> print(qc) # doctest: +NORMALIZE_WHITESPACE
548548
┌───┐
549549
q_0: ┤ H ├──■──
550550
└───┘┌─┴─┐
@@ -600,8 +600,9 @@ def get_measurements(self) -> list[Measure]:
600600
... BasisMeasure([0, 1], shots=1000),
601601
... ExpectationMeasure([1], Observable(np.identity(2)), shots=1000)
602602
... ])
603-
>>> circuit.get_measurements()
604-
[BasisMeasure([0, 1], shots=1000), ExpectationMeasure([1], Observable(array([[1.+0.j, 0.+0.j], [0.+0.j, 1.+0.j]], dtype=complex64)), shots=1000)]
603+
>>> circuit.get_measurements() # doctest: +NORMALIZE_WHITESPACE
604+
[BasisMeasure([0, 1], shots=1000),
605+
ExpectationMeasure([1], Observable(array([[1.+0.j, 0.+0.j], [0.+0.j, 1.+0.j]], dtype=complex64)), shots=1000)]
605606
606607
"""
607608
return [inst for inst in self.instructions if isinstance(inst, Measure)]
@@ -614,15 +615,15 @@ def without_measurements(self) -> QCircuit:
614615
615616
Example:
616617
>>> circuit = QCircuit([X(0), CNOT(0, 1), BasisMeasure([0, 1], shots=100)])
617-
>>> print(circuit) # doctest: +NORMALIZE_WHITESPACE
618+
>>> print(circuit) # doctest: +NORMALIZE_WHITESPACE
618619
┌───┐ ┌─┐
619620
q_0: ┤ X ├──■──┤M├───
620621
└───┘┌─┴─┐└╥┘┌─┐
621622
q_1: ─────┤ X ├─╫─┤M├
622623
└───┘ ║ └╥┘
623624
c: 2/═══════════╩══╩═
624625
0 1
625-
>>> print(circuit.without_measurements()) # doctest: +NORMALIZE_WHITESPACE
626+
>>> print(circuit.without_measurements()) # doctest: +NORMALIZE_WHITESPACE
626627
┌───┐
627628
q_0: ┤ X ├──■──
628629
└───┘┌─┴─┐
@@ -760,13 +761,13 @@ def to_other_language(
760761
from cirq.transformers.optimize_for_target_gateset import (
761762
optimize_for_target_gateset,
762763
)
763-
from cirq_google.engine.virtual_engine_factory import (
764-
create_device_from_processor_id,
765-
)
766764
from cirq.transformers.routing.route_circuit_cqc import RouteCQC
767765
from cirq.transformers.target_gatesets.sqrt_iswap_gateset import (
768766
SqrtIswapTargetGateset,
769767
)
768+
from cirq_google.engine.virtual_engine_factory import (
769+
create_device_from_processor_id,
770+
)
770771

771772
device = create_device_from_processor_id(cirq_proc_id)
772773
if device.metadata is None:
@@ -798,7 +799,7 @@ def to_qasm2(self) -> str:
798799
799800
Example:
800801
>>> circuit = QCircuit([X(0), CNOT(0, 1), BasisMeasure([0, 1], shots=100)])
801-
>>> print(circuit.to_qasm2()) # doctest: +NORMALIZE_WHITESPACE
802+
>>> print(circuit.to_qasm2()) # doctest: +NORMALIZE_WHITESPACE
802803
OPENQASM 2.0;
803804
include "qelib1.inc";
804805
qreg q[2];
@@ -830,7 +831,7 @@ def to_qasm3(self) -> str:
830831
831832
Example:
832833
>>> circuit = QCircuit([X(0), CNOT(0, 1), BasisMeasure([0, 1], shots=100)])
833-
>>> print(circuit.to_qasm3()) # doctest: +NORMALIZE_WHITESPACE
834+
>>> print(circuit.to_qasm3()) # doctest: +NORMALIZE_WHITESPACE
834835
OPENQASM 3.0;
835836
include "stdgates.inc";
836837
qubit[2] q;
@@ -869,7 +870,7 @@ def subs(
869870
... [Rx(theta, 0), CNOT(1,0), CNOT(1,2), X(2), Rk(2,1), H(0), CRk(k, 0, 1),
870871
... BasisMeasure(list(range(3)), shots=1000)]
871872
... )
872-
>>> print(c) # doctest: +NORMALIZE_WHITESPACE
873+
>>> print(c) # doctest: +NORMALIZE_WHITESPACE
873874
┌───────┐┌───┐┌───┐ ┌─┐
874875
q_0: ┤ Rx(θ) ├┤ X ├┤ H ├────────────■─────────────────┤M├───
875876
└───────┘└─┬─┘└───┘┌─────────┐ │P(2**(1 - k)*pi) └╥┘┌─┐
@@ -879,7 +880,7 @@ def subs(
879880
└───┘ └───┘ └╥┘ ║ ║
880881
c: 3/═══════════════════════════════════════╩══════════╩══╩═
881882
2 0 1
882-
>>> print(c.subs({theta: np.pi, k: 1})) # doctest: +NORMALIZE_WHITESPACE
883+
>>> print(c.subs({theta: np.pi, k: 1})) # doctest: +NORMALIZE_WHITESPACE
883884
┌───────┐┌───┐┌───┐ ┌─┐
884885
q_0: ┤ Rx(π) ├┤ X ├┤ H ├───────────■─────┤M├───
885886
└───────┘└─┬─┘└───┘┌────────┐ │P(π) └╥┘┌─┐
@@ -903,7 +904,7 @@ def pretty_print(self):
903904
904905
Example:
905906
>>> c = QCircuit([H(0), CNOT(0,1)])
906-
>>> c.pretty_print() # doctest: +NORMALIZE_WHITESPACE
907+
>>> c.pretty_print() # doctest: +NORMALIZE_WHITESPACE
907908
QCircuit : Size (Qubits,Cbits) = (2, 0), Nb instructions = 2
908909
┌───┐
909910
q_0: ┤ H ├──■──
@@ -943,7 +944,7 @@ def variables(self) -> set[Basic]:
943944
... Rx(theta, 0), CNOT(1,0), CNOT(1,2), X(2), Rk(2,1),
944945
... H(0), CRk(k, 0, 1), ExpectationMeasure([1], obs)
945946
... ])
946-
>>> circ.variables() # doctest: +SKIP
947+
>>> circ.variables() # doctest: +SKIP
947948
{θ, k}
948949
949950
"""

mpqp/execution/devices.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,8 @@ def get_region(self) -> str:
182182
Examples:
183183
>>> AWSDevice.BRAKET_IONQ_HARMONY.get_region()
184184
'us-east-1'
185-
>>> AWSDevice.BRAKET_SV1_SIMULATOR.get_region()
186-
''
185+
>>> AWSDevice.BRAKET_SV1_SIMULATOR.get_region() == get_env_variable("AWS_DEFAULT_REGION")
186+
True
187187
>>> AWSDevice.BRAKET_RIGETTI_ASPEN_M_3.get_region()
188188
'us-west-1'
189189

mpqp/execution/remote_handler.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def get_remote_result(
4343
State: 000, Index: 0, Count: 1017, Probability: 0.5085
4444
State: 100, Index: 4, Count: 983, Probability: 0.4915
4545
Error: 0.011181519941139355
46-
>>> print(remote_result_from_id(
46+
>>> print(get_remote_result(
4747
... 'cm80pb1054sir2ck9i3g',
4848
... IBMDevice.IBMQ_QASM_SIMULATOR,
4949
... ))

mpqp/execution/result.py

+8-11
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
import math
2525
from numbers import Complex
26-
from typing import Any, Optional
26+
from typing import Optional
2727

2828
import numpy as np
2929
import numpy.typing as npt
@@ -49,7 +49,7 @@ class StateVector:
4949
>>> state_vector = StateVector(np.array([1, 1, 1, -1])/2, 2)
5050
>>> state_vector.probabilities
5151
array([0.25, 0.25, 0.25, 0.25])
52-
>>> print(state_vector) # doctest: +NORMALIZE_WHITESPACE
52+
>>> print(state_vector)
5353
State vector: [0.5, 0.5, 0.5, -0.5]
5454
Probabilities: [0.25, 0.25, 0.25, 0.25]
5555
Number of qubits: 2
@@ -84,8 +84,7 @@ def amplitudes(self):
8484
def __str__(self):
8585
return f""" State vector: {clean_array(self.vector)}
8686
Probabilities: {clean_array(self.probabilities)}
87-
Number of qubits: {self.nb_qubits}
88-
"""
87+
Number of qubits: {self.nb_qubits}"""
8988

9089

9190
@typechecked
@@ -378,17 +377,15 @@ def __str__(self):
378377
Probabilities: {clean_array(self.probabilities)}
379378
Samples:
380379
{samples_str}
381-
Error: {self.error}
382-
"""
380+
Error: {self.error}"""
383381

384382
if self.job.job_type == JobType.STATE_VECTOR:
385383
return header + "\n" + str(self.state_vector)
386384

387385
if self.job.job_type == JobType.OBSERVABLE:
388386
return f"""{header}
389387
Expectation value: {self.expectation_value}
390-
Error/Variance: {self.error}
391-
"""
388+
Error/Variance: {self.error}"""
392389

393390
raise NotImplementedError(
394391
f"Job type {self.job.job_type} not implemented for __str__ method"
@@ -426,7 +423,7 @@ class BatchResult:
426423
... 2048
427424
... )
428425
>>> batch_result = BatchResult([result1, result2, result3])
429-
>>> print(batch_result) # doctest: +NORMALIZE_WHITESPACE
426+
>>> print(batch_result)
430427
BatchResult: 3 results
431428
Result: ATOSDevice, MYQLM_PYLINALG
432429
State vector: [0.5, 0.5, 0.5, -0.5]
@@ -442,7 +439,7 @@ class BatchResult:
442439
Result: ATOSDevice, MYQLM_PYLINALG
443440
Expectation value: -3.09834
444441
Error/Variance: 0.021
445-
>>> print(batch_result[0]) # doctest: +NORMALIZE_WHITESPACE
442+
>>> print(batch_result[0])
446443
Result: ATOSDevice, MYQLM_PYLINALG
447444
State vector: [0.5, 0.5, 0.5, -0.5]
448445
Probabilities: [0.25, 0.25, 0.25, 0.25]
@@ -456,7 +453,7 @@ def __init__(self, results: list[Result]):
456453

457454
def __str__(self):
458455
header = f"BatchResult: {len(self.results)} results\n"
459-
body = "".join(map(str, self.results))
456+
body = "\n".join(map(str, self.results))
460457
return header + body
461458

462459
def __repr__(self):

mpqp/tools/generics.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def find(iterable: Iterable[T], oracle: Callable[[T], bool]) -> T:
100100
raise ValueError("No objects satisfies the given oracle")
101101

102102

103-
def clean_array(array): # type: ignore
103+
def clean_array(array: list[complex] | npt.NDArray[np.complex64 | np.float32]):
104104
"""Cleans and formats elements of an array.
105105
This function rounds the real parts of complex numbers in the array to 7 decimal places
106106
and formats them as integers if they are whole numbers. It returns a string representation
@@ -165,6 +165,6 @@ def clean_matrix(matrix: Matrix):
165165
[1, 2, 3]]
166166
167167
"""
168+
# TODO: add an option to align cols
168169
cleaned_matrix = [clean_array(row) for row in matrix]
169-
return "[" +",\n ".join(cleaned_matrix) +"]"
170-
170+
return "[" + ",\n ".join(cleaned_matrix) + "]"

0 commit comments

Comments
 (0)