unitaryfund / mitiq

Mitiq is an open source toolkit for implementing error mitigation techniques on most current intermediate-scale quantum computers.
https://mitiq.readthedocs.io
GNU General Public License v3.0
358 stars 157 forks source link

Using a CZPowGate produces an error with CDR #1062

Closed amirebrahimi closed 2 years ago

amirebrahimi commented 2 years ago

Pre-Report Checklist

Issue Description

Using a CZPowGate produces an error with CDR.

How to Reproduce

Code Snippet

import warnings
warnings.filterwarnings("ignore")

import cirq
import numpy as np
from cirq import CZPowGate
from mitiq import cdr, Observable, PauliString
from mitiq.interface.mitiq_cirq import compute_density_matrix
from cirq.circuits import InsertStrategy

#Create cirucit
circuit1 = cirq.Circuit()

t=1 #Number of qubits in the control register
n=1 #Number of qubits in the target register

#Create t control qubits
control = [cirq.LineQubit(i) for i in range(t) ]

#Create n target qubits
target = [cirq.LineQubit(i) for i in range(t,t+n) ]

crk = CZPowGate(exponent = -2/2**(2))
circuit1.append(crk(control[0], target[0]),strategy = InsertStrategy.NEW)

print(circuit1)

obs1 = Observable(PauliString("ZZ"))

def simulate(circuit: cirq.Circuit) -> np.ndarray:
    return compute_density_matrix(circuit, noise_level=(0.0,))

cdr.execute_with_cdr(
    circuit1,
    compute_density_matrix,
    observable=obs1,
    simulator=simulate,
).real

Error Output

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-ca147fd1cc89> in <module>
     31     return compute_density_matrix(circuit, noise_level=(0.0,))
     32 
---> 33 cdr.execute_with_cdr(
     34     circuit1,
     35     compute_density_matrix,

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/mitiq/cdr/cdr.py in execute_with_cdr(circuit, executor, observable, simulator, num_training_circuits, fraction_non_clifford, fit_function, num_fit_parameters, scale_factors, scale_noise, **kwargs)
    131 
    132     # Generate training circuits.
--> 133     training_circuits = generate_training_circuits(
    134         circuit,
    135         num_training_circuits,

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/mitiq/interface/conversions.py in qprogram_modifier(circuit, *args, **kwargs)
    204         mitiq_circuit, input_circuit_type = convert_to_mitiq(circuit)
    205 
--> 206         modified_circuits: Iterable[Circuit] = cirq_circuit_modifier(
    207             mitiq_circuit, *args, **kwargs
    208         )

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/mitiq/cdr/clifford_training_data.py in generate_training_circuits(circuit, num_training_circuits, fraction_non_clifford, method_select, method_replace, random_state, **kwargs)
     96     near_clifford_circuits = []
     97     for _ in range(num_training_circuits):
---> 98         new_ops = _map_to_near_clifford(
     99             non_clifford_ops,
    100             fraction_non_clifford,

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/mitiq/cdr/clifford_training_data.py in _map_to_near_clifford(non_clifford_ops, fraction_non_clifford, method_select, method_replace, random_state, **kwargs)
    175 
    176     # Replace selected operations.
--> 177     clifford_ops: Sequence[cirq.ops.Operation] = _replace(
    178         [non_clifford_ops[i] for i in indices_of_selected_ops],
    179         method_replace,

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/mitiq/cdr/clifford_training_data.py in _replace(non_clifford_ops, method, sigma, random_state)
    298 
    299     # TODO: Write function to replace the angles in a list of operations?
--> 300     return [
    301         cirq.ops.rz(a).on(*q)
    302         for (a, q) in zip(

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/mitiq/cdr/clifford_training_data.py in <listcomp>(.0)
    299     # TODO: Write function to replace the angles in a list of operations?
    300     return [
--> 301         cirq.ops.rz(a).on(*q)
    302         for (a, q) in zip(
    303             clifford_angles, [op.qubits for op in non_clifford_ops],

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/cirq/ops/raw_types.py in on(self, *qubits)
    211         from cirq.ops import gate_operation
    212 
--> 213         return gate_operation.GateOperation(self, list(qubits))
    214 
    215     def wrap_in_linear_combination(

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/cirq/ops/gate_operation.py in __init__(self, gate, qubits)
     58             qubits: The qubits to operate on.
     59         """
---> 60         gate.validate_args(qubits)
     61         self._gate = gate
     62         self._qubits = tuple(qubits)

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/cirq/ops/raw_types.py in validate_args(self, qubits)
    200             ValueError: The gate can't be applied to the qubits.
    201         """
--> 202         _validate_qid_shape(self, qubits)
    203 
    204     def on(self, *qubits: Qid) -> 'Operation':

~/miniconda3/envs/mitiq/lib/python3.9/site-packages/cirq/ops/raw_types.py in _validate_qid_shape(val, qubits)
    784     qid_shape = protocols.qid_shape(val)
    785     if len(qubits) != len(qid_shape):
--> 786         raise ValueError(
    787             'Wrong number of qubits for <{!r}>. '
    788             'Expected {} qubits but got <{!r}>.'.format(val, len(qid_shape), qubits)

ValueError: Wrong number of qubits for <cirq.rz(np.pi*1.5)>. Expected 1 qubits but got <[cirq.LineQubit(0), cirq.LineQubit(1)]>.

Environment Context

Use the about() function to summarize information on operating system, python version and dependencies.

Mitiq: A Python toolkit for implementing error mitigation on quantum computers
==============================================================================
Authored by: Mitiq team, 2020 & later (https://github.com/unitaryfund/mitiq)

Mitiq Version:  0.11.1

Core Dependencies
-----------------
Cirq Version:   0.10.0
NumPy Version:  1.20.1
SciPy Version:  1.7.3

Optional Dependencies
---------------------
PyQuil Version: Not installed
Qiskit Version: 0.29.0
Braket Version: Not installed

Python Version: 3.9.2
Platform Info:  Linux (x86_64)

Additional Python Environment Details (pip freeze or conda list):

# packages in environment at /home/amir/miniconda3/envs/mitiq:
#
# Name                    Version                   Build  Channel
_libgcc_mutex             0.1                        main
anyio                     2.2.0            py39hf3d152e_0    conda-forge
argon2-cffi               20.1.0           py39hbd71b63_2    conda-forge
async_generator           1.10                       py_0    conda-forge
attrs                     20.3.0             pyhd3deb0d_0    conda-forge
babel                     2.9.0              pyhd3deb0d_0    conda-forge
backcall                  0.2.0              pyh9f0ad1d_0    conda-forge
backports                 1.0                        py_2    conda-forge
backports.functools_lru_cache 1.6.3              pyhd8ed1ab_0    conda-forge
bleach                    3.3.0              pyh44b312d_0    conda-forge
brotlipy                  0.7.0           py39h38d8fee_1001    conda-forge
ca-certificates           2020.12.5            ha878542_0    conda-forge
cachetools                4.2.4                    pypi_0    pypi
certifi                   2020.12.5        py39hf3d152e_1    conda-forge
cffi                      1.14.5           py39h261ae71_0
chardet                   4.0.0            py39hf3d152e_1    conda-forge
cirq                      0.10.0                   pypi_0    pypi
cryptography              3.4.7            py39hbca0aa6_0    conda-forge
cycler                    0.10.0                   pypi_0    pypi
decorator                 5.0.6              pyhd8ed1ab_0    conda-forge
defusedxml                0.7.1              pyhd8ed1ab_0    conda-forge
dill                      0.3.3                    pypi_0    pypi
dlx                       1.0.4                    pypi_0    pypi
docplex                   2.21.207                 pypi_0    pypi
entrypoints               0.3             pyhd8ed1ab_1003    conda-forge
fastdtw                   0.3.4                    pypi_0    pypi
fastjsonschema            2.15.0                   pypi_0    pypi
google-api-core           1.31.4                   pypi_0    pypi
google-auth               1.35.0                   pypi_0    pypi
googleapis-common-protos  1.54.0                   pypi_0    pypi
grpcio                    1.42.0                   pypi_0    pypi
h5py                      3.1.0                    pypi_0    pypi
idna                      2.10               pyh9f0ad1d_0    conda-forge
importlib-metadata        3.10.0           py39hf3d152e_0    conda-forge
inflection                0.5.1                    pypi_0    pypi
ipykernel                 5.5.3            py39hef51801_0    conda-forge
ipython                   7.22.0           py39hef51801_0    conda-forge
ipython_genutils          0.2.0                      py_1    conda-forge
ipywidgets                7.6.3                    pypi_0    pypi
jedi                      0.18.0           py39hf3d152e_2    conda-forge
jinja2                    2.11.3             pyh44b312d_0    conda-forge
joblib                    1.0.1                    pypi_0    pypi
json5                     0.9.5              pyh9f0ad1d_0    conda-forge
jsonschema                3.2.0              pyhd8ed1ab_3    conda-forge
jupyter-packaging         0.7.12             pyhd8ed1ab_0    conda-forge
jupyter_client            6.1.12             pyhd8ed1ab_0    conda-forge
jupyter_core              4.7.1            py39hf3d152e_0    conda-forge
jupyter_server            1.6.0            py39hf3d152e_0    conda-forge
jupyterlab                3.0.13             pyhd8ed1ab_0    conda-forge
jupyterlab-widgets        1.0.0                    pypi_0    pypi
jupyterlab_pygments       0.1.2              pyh9f0ad1d_0    conda-forge
jupyterlab_server         2.4.0              pyhd8ed1ab_0    conda-forge
kiwisolver                1.3.1                    pypi_0    pypi
ld_impl_linux-64          2.33.1               h53a641e_7
libffi                    3.3                  he6710b0_2
libgcc-ng                 9.1.0                hdf63c60_0
libsodium                 1.0.18               h36c2ea0_1    conda-forge
libstdcxx-ng              9.1.0                hdf63c60_0
lxml                      4.6.3                    pypi_0    pypi
markupsafe                1.1.1            py39h38d8fee_2    conda-forge
matplotlib                3.4.1                    pypi_0    pypi
mistune                   0.8.4           py39hbd71b63_1002    conda-forge
mitiq                     0.11.1                   pypi_0    pypi
more-itertools            8.7.0                    pypi_0    pypi
mpmath                    1.2.1                    pypi_0    pypi
multitasking              0.0.9                    pypi_0    pypi
nbclassic                 0.2.7              pyhd8ed1ab_0    conda-forge
nbclient                  0.5.3              pyhd8ed1ab_0    conda-forge
nbconvert                 6.0.7            py39hf3d152e_3    conda-forge
nbformat                  5.1.3              pyhd8ed1ab_0    conda-forge
ncurses                   6.2                  he6710b0_1
nest-asyncio              1.5.1              pyhd8ed1ab_0    conda-forge
networkx                  2.6.3                    pypi_0    pypi
notebook                  6.3.0            py39hf3d152e_0    conda-forge
ntlm-auth                 1.5.0                    pypi_0    pypi
numpy                     1.20.1                   pypi_0    pypi
openssl                   1.1.1k               h27cfd23_0
packaging                 20.9               pyh44b312d_0    conda-forge
pandas                    1.2.3                    pypi_0    pypi
pandoc                    2.12                 h7f98852_0    conda-forge
pandocfilters             1.4.2                      py_1    conda-forge
parso                     0.8.2              pyhd8ed1ab_0    conda-forge
pexpect                   4.8.0              pyh9f0ad1d_2    conda-forge
pickleshare               0.7.5                   py_1003    conda-forge
pillow                    8.2.0                    pypi_0    pypi
pip                       21.0.1           py39h06a4308_0
ply                       3.11                     pypi_0    pypi
prometheus_client         0.10.1             pyhd8ed1ab_0    conda-forge
prompt-toolkit            3.0.18             pyha770c72_0    conda-forge
protobuf                  3.13.0                   pypi_0    pypi
psutil                    5.8.0                    pypi_0    pypi
ptyprocess                0.7.0              pyhd3deb0d_0    conda-forge
pulsemaker                0.1.1b0                   dev_0    <develop>
pyasn1                    0.4.8                    pypi_0    pypi
pyasn1-modules            0.2.8                    pypi_0    pypi
pybind11                  2.6.2                    pypi_0    pypi
pycparser                 2.20               pyh9f0ad1d_2    conda-forge
pydot                     1.4.2                    pypi_0    pypi
pygments                  2.8.1              pyhd8ed1ab_0    conda-forge
pylatexenc                2.10                     pypi_0    pypi
pyopenssl                 20.0.1             pyhd8ed1ab_0    conda-forge
pyparsing                 2.4.7              pyh9f0ad1d_0    conda-forge
pyrsistent                0.17.3           py39hbd71b63_1    conda-forge
pysocks                   1.7.1            py39hf3d152e_3    conda-forge
python                    3.9.2                hdb3f193_0
python-constraint         1.4.0                    pypi_0    pypi
python-dateutil           2.8.1                      py_0    conda-forge
python_abi                3.9                      1_cp39    conda-forge
pytz                      2021.1             pyhd8ed1ab_0    conda-forge
pyzmq                     19.0.2           py39hb69f2a1_2    conda-forge
qiskit                    0.29.0                   pypi_0    pypi
qiskit-aer                0.8.2                    pypi_0    pypi
qiskit-aqua               0.9.4                    pypi_0    pypi
qiskit-ibmq-provider      0.16.0                   pypi_0    pypi
qiskit-ignis              0.6.0                    pypi_0    pypi
qiskit-terra              0.18.1                   pypi_0    pypi
qonduit                   0.1.2b2                   dev_0    <develop>
quandl                    3.6.0                    pypi_0    pypi
readline                  8.1                  h27cfd23_0
requests                  2.25.1             pyhd3deb0d_0    conda-forge
requests-ntlm             1.1.0                    pypi_0    pypi
retworkx                  0.9.0                    pypi_0    pypi
rsa                       4.8                      pypi_0    pypi
scikit-learn              0.24.1                   pypi_0    pypi
scipy                     1.7.3                    pypi_0    pypi
seaborn                   0.11.1                   pypi_0    pypi
send2trash                1.5.0                      py_0    conda-forge
setuptools                52.0.0           py39h06a4308_0
six                       1.15.0             pyh9f0ad1d_0    conda-forge
sniffio                   1.2.0            py39hf3d152e_1    conda-forge
sortedcontainers          2.4.0                    pypi_0    pypi
sqlite                    3.35.4               hdfb4753_0
symengine                 0.7.2                    pypi_0    pypi
sympy                     1.7.1                    pypi_0    pypi
terminado                 0.9.4            py39hf3d152e_0    conda-forge
testpath                  0.4.4                      py_0    conda-forge
threadpoolctl             2.1.0                    pypi_0    pypi
tk                        8.6.10               hbc83047_0
tornado                   6.1              py39hbd71b63_0    conda-forge
tqdm                      4.62.3                   pypi_0    pypi
traitlets                 5.0.5                      py_0    conda-forge
tweedledum                1.1.0                    pypi_0    pypi
typing-extensions         4.0.1                    pypi_0    pypi
tzdata                    2020f                h52ac0ba_0
urllib3                   1.26.4             pyhd8ed1ab_0    conda-forge
wcwidth                   0.2.5              pyh9f0ad1d_2    conda-forge
webencodings              0.5.1                      py_1    conda-forge
websocket-client          1.2.1                    pypi_0    pypi
websockets                8.1                      pypi_0    pypi
wheel                     0.36.2             pyhd3eb1b0_0
widgetsnbextension        3.5.1                    pypi_0    pypi
xz                        5.2.5                h7b6447c_0
yfinance                  0.1.55                   pypi_0    pypi
zeromq                    4.3.4                h2531618_0
zipp                      3.4.1              pyhd8ed1ab_0    conda-forge
zlib                      1.2.11               h7b6447c_3
github-actions[bot] commented 2 years ago

Hello @amirebrahimi, thank you for your interest in Mitiq! If this is a bug report, please provide screenshots and/or minimum viable code to reproduce your issue, so we can do our best to help get it fixed. If you have any questions in the meantime, you can also ask us on the Unitary Fund Discord.

rmlarose commented 2 years ago

Thanks @amirebrahimi. This is not a bug because, from the docstring of execute_with_cdr:

https://github.com/unitaryfund/mitiq/blob/5559568047cd86cb3d163050d1aca99539ab392e/mitiq/cdr/cdr.py#L53-L55

(The circuit in this example contains a CZPowGate.)

However, this is an important matter of usability. The long-term goal is support for any gates (e.g., by compiling the input circuit) so this example will work. In the short-term, I suggest we make the error message clearer here by checking if the circuit is compiled to the right gateset.

To use CDR with circuits that contain CZPowGates, you will need to compile the gates into {Rz, sqrt(X), CNOT}.

rmlarose commented 2 years ago

I also noticed the docstring for execute_with_cdr does not appear at https://mitiq.readthedocs.io/en/stable/apidoc.html#module-mitiq.cdr.clifford_training_data. This should also be fixed.

amirebrahimi commented 2 years ago

Thanks for the clarification. Feel free to close this or use it as an issue for creating a clearer error message / fixing docs.

github-actions[bot] commented 2 years ago

This issue had no activity for 4 months, and will be closed in 2 weeks unless there is new activity. Cheers!