instance_id
stringlengths
13
37
text
stringlengths
3.08k
667k
repo
stringlengths
8
30
base_commit
stringlengths
40
40
problem_statement
stringlengths
10
256k
hints_text
stringlengths
0
908k
created_at
stringlengths
20
20
patch
stringlengths
18
101M
test_patch
stringclasses
1 value
version
stringclasses
1 value
FAIL_TO_PASS
stringclasses
1 value
PASS_TO_PASS
stringclasses
1 value
environment_setup_commit
stringclasses
1 value
Qiskit__qiskit-4465
You will be provided with a partial code base and an issue statement explaining a problem to resolve. <issue> `initialize` and `Statevector` don't play nicely <!-- ⚠️ If you do not respect this template, your issue will be closed --> <!-- ⚠️ Make sure to browse the opened and closed issues --> ### Informations - **Qiskit Aer version**: 0.5.1 - **Python version**: 3.7.3 - **Operating system**: OSX ### What is the current behavior? Using `initialize` in a circuit and then running with `Statevector` results in the error "Cannot apply Instruction: reset" ### Steps to reproduce the problem ``` import qiskit as qk import qiskit.quantum_info as qi from numpy import sqrt n = 2 ket0 = [1/sqrt(2),0,0,1/sqrt(2)] qc = qk.QuantumCircuit(n) qc.initialize(ket0,range(n)) ket_qi = qi.Statevector.from_instruction(qc) ``` </issue> <code> [start of README.md] 1 # Qiskit Terra 2 3 [![License](https://img.shields.io/github/license/Qiskit/qiskit-terra.svg?style=popout-square)](https://opensource.org/licenses/Apache-2.0)[![Build Status](https://img.shields.io/travis/com/Qiskit/qiskit-terra/master.svg?style=popout-square)](https://travis-ci.com/Qiskit/qiskit-terra)[![](https://img.shields.io/github/release/Qiskit/qiskit-terra.svg?style=popout-square)](https://github.com/Qiskit/qiskit-terra/releases)[![](https://img.shields.io/pypi/dm/qiskit-terra.svg?style=popout-square)](https://pypi.org/project/qiskit-terra/)[![Coverage Status](https://coveralls.io/repos/github/Qiskit/qiskit-terra/badge.svg?branch=master)](https://coveralls.io/github/Qiskit/qiskit-terra?branch=master) 4 5 **Qiskit** is an open-source framework for working with noisy quantum computers at the level of pulses, circuits, and algorithms. 6 7 Qiskit is made up of elements that work together to enable quantum computing. This element is **Terra** and is the foundation on which the rest of Qiskit is built. 8 9 ## Installation 10 11 We encourage installing Qiskit via the pip tool (a python package manager), which installs all Qiskit elements, including Terra. 12 13 ```bash 14 pip install qiskit 15 ``` 16 17 PIP will handle all dependencies automatically and you will always install the latest (and well-tested) version. 18 19 To install from source, follow the instructions in the [documentation](https://qiskit.org/documentation/contributing_to_qiskit.html#install-terra-from-source). 20 21 ## Creating Your First Quantum Program in Qiskit Terra 22 23 Now that Qiskit is installed, it's time to begin working with Terra. 24 25 We are ready to try out a quantum circuit example, which is simulated locally using 26 the Qiskit BasicAer element. This is a simple example that makes an entangled state. 27 28 ``` 29 $ python 30 ``` 31 32 ```python 33 >>> from qiskit import * 34 >>> qc = QuantumCircuit(2, 2) 35 >>> qc.h(0) 36 >>> qc.cx(0, 1) 37 >>> qc.measure([0,1], [0,1]) 38 >>> backend_sim = BasicAer.get_backend('qasm_simulator') 39 >>> result = backend_sim.run(assemble(qc)).result() 40 >>> print(result.get_counts(qc)) 41 ``` 42 43 In this case, the output will be: 44 45 ```python 46 {'00': 513, '11': 511} 47 ``` 48 49 A script is available [here](examples/python/ibmq/hello_quantum.py), where we also show how to 50 run the same program on a real quantum computer via IBMQ. 51 52 ### Executing your code on a real quantum chip 53 54 You can also use Qiskit to execute your code on a 55 **real quantum chip**. 56 In order to do so, you need to configure Qiskit for using the credentials in 57 your IBM Q account: 58 59 #### Configure your IBMQ credentials 60 61 1. Create an _[IBM Q](https://quantum-computing.ibm.com) > Account_ if you haven't already done so. 62 63 2. Get an API token from the IBM Q website under _My Account > API Token_ and the URL for the account. 64 65 3. Take your token and url from step 2, here called `MY_API_TOKEN`, `MY_URL`, and run: 66 67 ```python 68 >>> from qiskit import IBMQ 69 >>> IBMQ.save_account('MY_API_TOKEN', 'MY_URL') 70 ``` 71 72 After calling `IBMQ.save_account()`, your credentials will be stored on disk. 73 Once they are stored, at any point in the future you can load and use them 74 in your program simply via: 75 76 ```python 77 >>> from qiskit import IBMQ 78 >>> IBMQ.load_account() 79 ``` 80 81 Those who do not want to save their credentials to disk should use instead: 82 83 ```python 84 >>> from qiskit import IBMQ 85 >>> IBMQ.enable_account('MY_API_TOKEN') 86 ``` 87 88 and the token will only be active for the session. For examples using Terra with real 89 devices we have provided a set of examples in **examples/python** and we suggest starting with [using_qiskit_terra_level_0.py](examples/python/using_qiskit_terra_level_0.py) and working up in 90 the levels. 91 92 ## Contribution Guidelines 93 94 If you'd like to contribute to Qiskit Terra, please take a look at our 95 [contribution guidelines](CONTRIBUTING.md). This project adheres to Qiskit's [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. 96 97 We use [GitHub issues](https://github.com/Qiskit/qiskit-terra/issues) for tracking requests and bugs. Please 98 [join the Qiskit Slack community](https://join.slack.com/t/qiskit/shared_invite/zt-e4sscbg2-p8NHTezPVkC3r8nV6BIUVw) 99 and use our [Qiskit Slack channel](https://qiskit.slack.com) for discussion and simple questions. 100 For questions that are more suited for a forum we use the Qiskit tag in the [Stack Exchange](https://quantumcomputing.stackexchange.com/questions/tagged/qiskit). 101 102 ## Next Steps 103 104 Now you're set up and ready to check out some of the other examples from our 105 [Qiskit Tutorials](https://github.com/Qiskit/qiskit-tutorials) repository. 106 107 ## Authors and Citation 108 109 Qiskit Terra is the work of [many people](https://github.com/Qiskit/qiskit-terra/graphs/contributors) who contribute 110 to the project at different levels. If you use Qiskit, please cite as per the included [BibTeX file](https://github.com/Qiskit/qiskit/blob/master/Qiskit.bib). 111 112 ## Changelog and Release Notes 113 114 The changelog for a particular release is dynamically generated and gets 115 written to the release page on Github for each release. For example, you can 116 find the page for the `0.9.0` release here: 117 118 https://github.com/Qiskit/qiskit-terra/releases/tag/0.9.0 119 120 The changelog for the current release can be found in the releases tab: 121 ![](https://img.shields.io/github/release/Qiskit/qiskit-terra.svg?style=popout-square) 122 The changelog provides a quick overview of noteable changes for a given 123 release. 124 125 Additionally, as part of each release detailed release notes are written to 126 document in detail what has changed as part of a release. This includes any 127 documentation on potential breaking changes on upgrade and new features. 128 For example, You can find the release notes for the `0.9.0` release in the 129 Qiskit documentation here: 130 131 https://qiskit.org/documentation/release_notes.html#terra-0-9 132 133 ## License 134 135 [Apache License 2.0](LICENSE.txt) 136 [end of README.md] [start of qiskit/circuit/__init__.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 """ 16 ======================================== 17 Quantum Circuits (:mod:`qiskit.circuit`) 18 ======================================== 19 20 .. currentmodule:: qiskit.circuit 21 22 Overview 23 ======== 24 25 The fundamental element of quantum computing is the **quantum circuit**. 26 A quantum circuit is a computational routine consisting of coherent quantum 27 operations on quantum data, such as qubits. It is an ordered sequence of quantum 28 gates, measurements and resets, which may be conditioned on real-time classical 29 computation. A set of quantum gates is said to be universal if any unitary 30 transformation of the quantum data can be efficiently approximated arbitrarily well 31 as as sequence of gates in the set. Any quantum program can be represented by a 32 sequence of quantum circuits and classical near-time computation. 33 34 In Qiskit, this core element is represented by the :class:`QuantumCircuit` class. 35 Below is an example of a quantum circuit that makes a three-qubit GHZ state 36 defined as: 37 38 .. math:: 39 40 |\\psi\\rangle = \\left(|000\\rangle+|111\\rangle\\right)/\\sqrt{2} 41 42 43 .. jupyter-execute:: 44 45 from qiskit import QuantumCircuit 46 # Create a circuit with a register of three qubits 47 circ = QuantumCircuit(3) 48 # H gate on qubit 0, putting this qubit in a superposition of |0> + |1>. 49 circ.h(0) 50 # A CX (CNOT) gate on control qubit 0 and target qubit 1 generating a Bell state. 51 circ.cx(0, 1) 52 # CX (CNOT) gate on control qubit 0 and target qubit 2 resulting in a GHZ state. 53 circ.cx(0, 2) 54 # Draw the circuit 55 circ.draw() 56 57 58 Supplementary Information 59 ========================= 60 61 .. container:: toggle 62 63 .. container:: header 64 65 **Quantum Circuit Properties** 66 67 When constructing quantum circuits, there are several properties that help quantify 68 the "size" of the circuits, and their ability to be run on a noisy quantum device. 69 Some of these, like number of qubits, are straightforward to understand, while others 70 like depth and number of tensor components require a bit more explanation. Here we will 71 explain all of these properties, and, in preparation for understanding how circuits change 72 when run on actual devices, highlight the conditions under which they change. 73 74 Consider the following circuit: 75 76 .. jupyter-execute:: 77 78 from qiskit import QuantumCircuit 79 qc = QuantumCircuit(12) 80 for idx in range(5): 81 qc.h(idx) 82 qc.cx(idx, idx+5) 83 84 qc.cx(1, 7) 85 qc.x(8) 86 qc.cx(1, 9) 87 qc.x(7) 88 qc.cx(1, 11) 89 qc.swap(6, 11) 90 qc.swap(6, 9) 91 qc.swap(6, 10) 92 qc.x(6) 93 qc.draw() 94 95 From the plot, it is easy to see that this circuit has 12 qubits, and a collection of 96 Hadamard, CNOT, X, and SWAP gates. But how to quantify this programmatically? Because we 97 can do single-qubit gates on all the qubits simultaneously, the number of qubits in this 98 circuit is equal to the **width** of the circuit: 99 100 .. jupyter-execute:: 101 102 qc.width() 103 104 105 We can also just get the number of qubits directly: 106 107 .. jupyter-execute:: 108 109 qc.num_qubits 110 111 112 .. important:: 113 114 For a quantum circuit composed from just qubits, the circuit width is equal 115 to the number of qubits. This is the definition used in quantum computing. However, 116 for more complicated circuits with classical registers, and classically controlled gates, 117 this equivalence breaks down. As such, from now on we will not refer to the number of 118 qubits in a quantum circuit as the width. 119 120 121 It is also straightforward to get the number and type of the gates in a circuit using 122 :meth:`QuantumCircuit.count_ops`: 123 124 .. jupyter-execute:: 125 126 qc.count_ops() 127 128 129 We can also get just the raw count of operations by computing the circuits 130 :meth:`QuantumCircuit.size`: 131 132 .. jupyter-execute:: 133 134 qc.size() 135 136 137 A particularly important circuit property is known as the circuit **depth**. The depth 138 of a quantum circuit is a measure of how many "layers" of quantum gates, executed in 139 parallel, it takes to complete the computation defined by the circuit. Because quantum 140 gates take time to implement, the depth of a circuit roughly corresponds to the amount of 141 time it takes the quantum computer to execute the circuit. Thus, the depth of a circuit 142 is one important quantity used to measure if a quantum circuit can be run on a device. 143 144 The depth of a quantum circuit has a mathematical definition as the longest path in a 145 directed acyclic graph (DAG). However, such a definition is a bit hard to grasp, even for 146 experts. Fortunately, the depth of a circuit can be easily understood by anyone familiar 147 with playing `Tetris <https://en.wikipedia.org/wiki/Tetris>`_. Lets see how to compute this 148 graphically: 149 150 .. image:: /source_images/depth.gif 151 152 153 .. raw:: html 154 155 <br><br> 156 157 158 We can verify our graphical result using :meth:`QuantumCircuit.depth`: 159 160 .. jupyter-execute:: 161 162 qc.depth() 163 164 165 .. raw:: html 166 167 <br> 168 169 Quantum Circuit API 170 =================== 171 172 Quantum Circuit Construction 173 ---------------------------- 174 175 .. autosummary:: 176 :toctree: ../stubs/ 177 178 QuantumCircuit 179 QuantumRegister 180 Qubit 181 ClassicalRegister 182 Clbit 183 184 Gates and Instructions 185 ---------------------- 186 187 .. autosummary:: 188 :toctree: ../stubs/ 189 190 Gate 191 ControlledGate 192 Measure 193 Reset 194 Instruction 195 InstructionSet 196 EquivalenceLibrary 197 198 Parametric Quantum Circuits 199 --------------------------- 200 201 .. autosummary:: 202 :toctree: ../stubs/ 203 204 Parameter 205 ParameterVector 206 ParameterExpression 207 208 Random Circuits 209 --------------- 210 211 .. autosummary:: 212 :toctree: ../stubs/ 213 214 random.random_circuit 215 """ 216 from .quantumcircuit import QuantumCircuit 217 from .classicalregister import ClassicalRegister, Clbit 218 from .quantumregister import QuantumRegister, Qubit 219 from .gate import Gate 220 # pylint: disable=cyclic-import 221 from .controlledgate import ControlledGate 222 from .instruction import Instruction 223 from .instructionset import InstructionSet 224 from .barrier import Barrier 225 from .measure import Measure 226 from .reset import Reset 227 from .parameter import Parameter 228 from .parametervector import ParameterVector 229 from .parameterexpression import ParameterExpression 230 from .equivalence import EquivalenceLibrary 231 [end of qiskit/circuit/__init__.py] [start of qiskit/providers/basicaer/qasm_simulator.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 # pylint: disable=arguments-differ 16 17 """Contains a (slow) Python simulator. 18 19 It simulates a qasm quantum circuit (an experiment) that has been compiled 20 to run on the simulator. It is exponential in the number of qubits. 21 22 The simulator is run using 23 24 .. code-block:: python 25 26 QasmSimulatorPy().run(qobj) 27 28 Where the input is a Qobj object and the output is a BasicAerJob object, which can 29 later be queried for the Result object. The result will contain a 'memory' data 30 field, which is a result of measurements for each shot. 31 """ 32 33 import uuid 34 import time 35 import logging 36 37 from math import log2 38 from collections import Counter 39 import numpy as np 40 41 from qiskit.util import local_hardware_info 42 from qiskit.providers.models import QasmBackendConfiguration 43 from qiskit.result import Result 44 from qiskit.providers import BaseBackend 45 from qiskit.providers.basicaer.basicaerjob import BasicAerJob 46 from .exceptions import BasicAerError 47 from .basicaertools import single_gate_matrix 48 from .basicaertools import cx_gate_matrix 49 from .basicaertools import einsum_vecmul_index 50 51 logger = logging.getLogger(__name__) 52 53 54 class QasmSimulatorPy(BaseBackend): 55 """Python implementation of a qasm simulator.""" 56 57 MAX_QUBITS_MEMORY = int(log2(local_hardware_info()['memory'] * (1024 ** 3) / 16)) 58 59 DEFAULT_CONFIGURATION = { 60 'backend_name': 'qasm_simulator', 61 'backend_version': '2.0.0', 62 'n_qubits': min(24, MAX_QUBITS_MEMORY), 63 'url': 'https://github.com/Qiskit/qiskit-terra', 64 'simulator': True, 65 'local': True, 66 'conditional': True, 67 'open_pulse': False, 68 'memory': True, 69 'max_shots': 65536, 70 'coupling_map': None, 71 'description': 'A python simulator for qasm experiments', 72 'basis_gates': ['u1', 'u2', 'u3', 'cx', 'id', 'unitary'], 73 'gates': [ 74 { 75 'name': 'u1', 76 'parameters': ['lambda'], 77 'qasm_def': 'gate u1(lambda) q { U(0,0,lambda) q; }' 78 }, 79 { 80 'name': 'u2', 81 'parameters': ['phi', 'lambda'], 82 'qasm_def': 'gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }' 83 }, 84 { 85 'name': 'u3', 86 'parameters': ['theta', 'phi', 'lambda'], 87 'qasm_def': 'gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }' 88 }, 89 { 90 'name': 'cx', 91 'parameters': ['c', 't'], 92 'qasm_def': 'gate cx c,t { CX c,t; }' 93 }, 94 { 95 'name': 'id', 96 'parameters': ['a'], 97 'qasm_def': 'gate id a { U(0,0,0) a; }' 98 }, 99 { 100 'name': 'unitary', 101 'parameters': ['matrix'], 102 'qasm_def': 'unitary(matrix) q1, q2,...' 103 } 104 ] 105 } 106 107 DEFAULT_OPTIONS = { 108 "initial_statevector": None, 109 "chop_threshold": 1e-15 110 } 111 112 # Class level variable to return the final state at the end of simulation 113 # This should be set to True for the statevector simulator 114 SHOW_FINAL_STATE = False 115 116 def __init__(self, configuration=None, provider=None): 117 super().__init__(configuration=( 118 configuration or QasmBackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION)), 119 provider=provider) 120 121 # Define attributes in __init__. 122 self._local_random = np.random.RandomState() 123 self._classical_memory = 0 124 self._classical_register = 0 125 self._statevector = 0 126 self._number_of_cmembits = 0 127 self._number_of_qubits = 0 128 self._shots = 0 129 self._memory = False 130 self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"] 131 self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"] 132 self._qobj_config = None 133 # TEMP 134 self._sample_measure = False 135 136 def _add_unitary(self, gate, qubits): 137 """Apply an N-qubit unitary matrix. 138 139 Args: 140 gate (matrix_like): an N-qubit unitary matrix 141 qubits (list): the list of N-qubits. 142 """ 143 # Get the number of qubits 144 num_qubits = len(qubits) 145 # Compute einsum index string for 1-qubit matrix multiplication 146 indexes = einsum_vecmul_index(qubits, self._number_of_qubits) 147 # Convert to complex rank-2N tensor 148 gate_tensor = np.reshape(np.array(gate, dtype=complex), 149 num_qubits * [2, 2]) 150 # Apply matrix multiplication 151 self._statevector = np.einsum(indexes, gate_tensor, self._statevector, 152 dtype=complex, casting='no') 153 154 def _get_measure_outcome(self, qubit): 155 """Simulate the outcome of measurement of a qubit. 156 157 Args: 158 qubit (int): the qubit to measure 159 160 Return: 161 tuple: pair (outcome, probability) where outcome is '0' or '1' and 162 probability is the probability of the returned outcome. 163 """ 164 # Axis for numpy.sum to compute probabilities 165 axis = list(range(self._number_of_qubits)) 166 axis.remove(self._number_of_qubits - 1 - qubit) 167 probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis)) 168 # Compute einsum index string for 1-qubit matrix multiplication 169 random_number = self._local_random.rand() 170 if random_number < probabilities[0]: 171 return '0', probabilities[0] 172 # Else outcome was '1' 173 return '1', probabilities[1] 174 175 def _add_sample_measure(self, measure_params, num_samples): 176 """Generate memory samples from current statevector. 177 178 Args: 179 measure_params (list): List of (qubit, cmembit) values for 180 measure instructions to sample. 181 num_samples (int): The number of memory samples to generate. 182 183 Returns: 184 list: A list of memory values in hex format. 185 """ 186 # Get unique qubits that are actually measured and sort in 187 # ascending order 188 measured_qubits = sorted(list({qubit for qubit, cmembit in measure_params})) 189 num_measured = len(measured_qubits) 190 # We use the axis kwarg for numpy.sum to compute probabilities 191 # this sums over all non-measured qubits to return a vector 192 # of measure probabilities for the measured qubits 193 axis = list(range(self._number_of_qubits)) 194 for qubit in reversed(measured_qubits): 195 # Remove from largest qubit to smallest so list position is correct 196 # with respect to position from end of the list 197 axis.remove(self._number_of_qubits - 1 - qubit) 198 probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2, 199 axis=tuple(axis)), 200 2 ** num_measured) 201 # Generate samples on measured qubits as ints with qubit 202 # position in the bit-string for each int given by the qubit 203 # position in the sorted measured_qubits list 204 samples = self._local_random.choice(range(2 ** num_measured), 205 num_samples, p=probabilities) 206 # Convert the ints to bitstrings 207 memory = [] 208 for sample in samples: 209 classical_memory = self._classical_memory 210 for qubit, cmembit in measure_params: 211 pos = measured_qubits.index(qubit) 212 qubit_outcome = int((sample & (1 << pos)) >> pos) 213 membit = 1 << cmembit 214 classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit) 215 value = bin(classical_memory)[2:] 216 memory.append(hex(int(value, 2))) 217 return memory 218 219 def _add_qasm_measure(self, qubit, cmembit, cregbit=None): 220 """Apply a measure instruction to a qubit. 221 222 Args: 223 qubit (int): qubit is the qubit measured. 224 cmembit (int): is the classical memory bit to store outcome in. 225 cregbit (int, optional): is the classical register bit to store outcome in. 226 """ 227 # get measure outcome 228 outcome, probability = self._get_measure_outcome(qubit) 229 # update classical state 230 membit = 1 << cmembit 231 self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit) 232 233 if cregbit is not None: 234 regbit = 1 << cregbit 235 self._classical_register = \ 236 (self._classical_register & (~regbit)) | (int(outcome) << cregbit) 237 238 # update quantum state 239 if outcome == '0': 240 update_diag = [[1 / np.sqrt(probability), 0], [0, 0]] 241 else: 242 update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]] 243 # update classical state 244 self._add_unitary(update_diag, [qubit]) 245 246 def _add_qasm_reset(self, qubit): 247 """Apply a reset instruction to a qubit. 248 249 Args: 250 qubit (int): the qubit being rest 251 252 This is done by doing a simulating a measurement 253 outcome and projecting onto the outcome state while 254 renormalizing. 255 """ 256 # get measure outcome 257 outcome, probability = self._get_measure_outcome(qubit) 258 # update quantum state 259 if outcome == '0': 260 update = [[1 / np.sqrt(probability), 0], [0, 0]] 261 self._add_unitary(update, [qubit]) 262 else: 263 update = [[0, 1 / np.sqrt(probability)], [0, 0]] 264 self._add_unitary(update, [qubit]) 265 266 def _validate_initial_statevector(self): 267 """Validate an initial statevector""" 268 # If initial statevector isn't set we don't need to validate 269 if self._initial_statevector is None: 270 return 271 # Check statevector is correct length for number of qubits 272 length = len(self._initial_statevector) 273 required_dim = 2 ** self._number_of_qubits 274 if length != required_dim: 275 raise BasicAerError('initial statevector is incorrect length: ' + 276 '{} != {}'.format(length, required_dim)) 277 278 def _set_options(self, qobj_config=None, backend_options=None): 279 """Set the backend options for all experiments in a qobj""" 280 # Reset default options 281 self._initial_statevector = self.DEFAULT_OPTIONS["initial_statevector"] 282 self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"] 283 if backend_options is None: 284 backend_options = {} 285 286 # Check for custom initial statevector in backend_options first, 287 # then config second 288 if 'initial_statevector' in backend_options: 289 self._initial_statevector = np.array(backend_options['initial_statevector'], 290 dtype=complex) 291 elif hasattr(qobj_config, 'initial_statevector'): 292 self._initial_statevector = np.array(qobj_config.initial_statevector, 293 dtype=complex) 294 if self._initial_statevector is not None: 295 # Check the initial statevector is normalized 296 norm = np.linalg.norm(self._initial_statevector) 297 if round(norm, 12) != 1: 298 raise BasicAerError('initial statevector is not normalized: ' + 299 'norm {} != 1'.format(norm)) 300 # Check for custom chop threshold 301 # Replace with custom options 302 if 'chop_threshold' in backend_options: 303 self._chop_threshold = backend_options['chop_threshold'] 304 elif hasattr(qobj_config, 'chop_threshold'): 305 self._chop_threshold = qobj_config.chop_threshold 306 307 def _initialize_statevector(self): 308 """Set the initial statevector for simulation""" 309 if self._initial_statevector is None: 310 # Set to default state of all qubits in |0> 311 self._statevector = np.zeros(2 ** self._number_of_qubits, 312 dtype=complex) 313 self._statevector[0] = 1 314 else: 315 self._statevector = self._initial_statevector.copy() 316 # Reshape to rank-N tensor 317 self._statevector = np.reshape(self._statevector, 318 self._number_of_qubits * [2]) 319 320 def _get_statevector(self): 321 """Return the current statevector""" 322 vec = np.reshape(self._statevector, 2 ** self._number_of_qubits) 323 vec[abs(vec) < self._chop_threshold] = 0.0 324 return vec 325 326 def _validate_measure_sampling(self, experiment): 327 """Determine if measure sampling is allowed for an experiment 328 329 Args: 330 experiment (QobjExperiment): a qobj experiment. 331 """ 332 # If shots=1 we should disable measure sampling. 333 # This is also required for statevector simulator to return the 334 # correct final statevector without silently dropping final measurements. 335 if self._shots <= 1: 336 self._sample_measure = False 337 return 338 339 # Check for config flag 340 if hasattr(experiment.config, 'allows_measure_sampling'): 341 self._sample_measure = experiment.config.allows_measure_sampling 342 # If flag isn't found do a simple test to see if a circuit contains 343 # no reset instructions, and no gates instructions after 344 # the first measure. 345 else: 346 measure_flag = False 347 for instruction in experiment.instructions: 348 # If circuit contains reset operations we cannot sample 349 if instruction.name == "reset": 350 self._sample_measure = False 351 return 352 # If circuit contains a measure option then we can 353 # sample only if all following operations are measures 354 if measure_flag: 355 # If we find a non-measure instruction 356 # we cannot do measure sampling 357 if instruction.name not in ["measure", "barrier", "id", "u0"]: 358 self._sample_measure = False 359 return 360 elif instruction.name == "measure": 361 measure_flag = True 362 # If we made it to the end of the circuit without returning 363 # measure sampling is allowed 364 self._sample_measure = True 365 366 def run(self, qobj, backend_options=None): 367 """Run qobj asynchronously. 368 369 Args: 370 qobj (Qobj): payload of the experiment 371 backend_options (dict): backend options 372 373 Returns: 374 BasicAerJob: derived from BaseJob 375 376 Additional Information: 377 backend_options: Is a dict of options for the backend. It may contain 378 * "initial_statevector": vector_like 379 380 The "initial_statevector" option specifies a custom initial 381 initial statevector for the simulator to be used instead of the all 382 zero state. This size of this vector must be correct for the number 383 of qubits in all experiments in the qobj. 384 385 Example:: 386 387 backend_options = { 388 "initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2), 389 } 390 """ 391 self._set_options(qobj_config=qobj.config, 392 backend_options=backend_options) 393 job_id = str(uuid.uuid4()) 394 job = BasicAerJob(self, job_id, self._run_job, qobj) 395 job.submit() 396 return job 397 398 def _run_job(self, job_id, qobj): 399 """Run experiments in qobj 400 401 Args: 402 job_id (str): unique id for the job. 403 qobj (Qobj): job description 404 405 Returns: 406 Result: Result object 407 """ 408 self._validate(qobj) 409 result_list = [] 410 self._shots = qobj.config.shots 411 self._memory = getattr(qobj.config, 'memory', False) 412 self._qobj_config = qobj.config 413 start = time.time() 414 for experiment in qobj.experiments: 415 result_list.append(self.run_experiment(experiment)) 416 end = time.time() 417 result = {'backend_name': self.name(), 418 'backend_version': self._configuration.backend_version, 419 'qobj_id': qobj.qobj_id, 420 'job_id': job_id, 421 'results': result_list, 422 'status': 'COMPLETED', 423 'success': True, 424 'time_taken': (end - start), 425 'header': qobj.header.to_dict()} 426 427 return Result.from_dict(result) 428 429 def run_experiment(self, experiment): 430 """Run an experiment (circuit) and return a single experiment result. 431 432 Args: 433 experiment (QobjExperiment): experiment from qobj experiments list 434 435 Returns: 436 dict: A result dictionary which looks something like:: 437 438 { 439 "name": name of this experiment (obtained from qobj.experiment header) 440 "seed": random seed used for simulation 441 "shots": number of shots used in the simulation 442 "data": 443 { 444 "counts": {'0x9: 5, ...}, 445 "memory": ['0x9', '0xF', '0x1D', ..., '0x9'] 446 }, 447 "status": status string for the simulation 448 "success": boolean 449 "time_taken": simulation time of this single experiment 450 } 451 Raises: 452 BasicAerError: if an error occurred. 453 """ 454 start = time.time() 455 self._number_of_qubits = experiment.config.n_qubits 456 self._number_of_cmembits = experiment.config.memory_slots 457 self._statevector = 0 458 self._classical_memory = 0 459 self._classical_register = 0 460 self._sample_measure = False 461 # Validate the dimension of initial statevector if set 462 self._validate_initial_statevector() 463 # Get the seed looking in circuit, qobj, and then random. 464 if hasattr(experiment.config, 'seed_simulator'): 465 seed_simulator = experiment.config.seed_simulator 466 elif hasattr(self._qobj_config, 'seed_simulator'): 467 seed_simulator = self._qobj_config.seed_simulator 468 else: 469 # For compatibility on Windows force dyte to be int32 470 # and set the maximum value to be (2 ** 31) - 1 471 seed_simulator = np.random.randint(2147483647, dtype='int32') 472 473 self._local_random.seed(seed=seed_simulator) 474 # Check if measure sampling is supported for current circuit 475 self._validate_measure_sampling(experiment) 476 477 # List of final counts for all shots 478 memory = [] 479 # Check if we can sample measurements, if so we only perform 1 shot 480 # and sample all outcomes from the final state vector 481 if self._sample_measure: 482 shots = 1 483 # Store (qubit, cmembit) pairs for all measure ops in circuit to 484 # be sampled 485 measure_sample_ops = [] 486 else: 487 shots = self._shots 488 for _ in range(shots): 489 self._initialize_statevector() 490 # Initialize classical memory to all 0 491 self._classical_memory = 0 492 self._classical_register = 0 493 for operation in experiment.instructions: 494 conditional = getattr(operation, 'conditional', None) 495 if isinstance(conditional, int): 496 conditional_bit_set = (self._classical_register >> conditional) & 1 497 if not conditional_bit_set: 498 continue 499 elif conditional is not None: 500 mask = int(operation.conditional.mask, 16) 501 if mask > 0: 502 value = self._classical_memory & mask 503 while (mask & 0x1) == 0: 504 mask >>= 1 505 value >>= 1 506 if value != int(operation.conditional.val, 16): 507 continue 508 509 # Check if single gate 510 if operation.name == 'unitary': 511 qubits = operation.qubits 512 gate = operation.params[0] 513 self._add_unitary(gate, qubits) 514 elif operation.name in ('U', 'u1', 'u2', 'u3'): 515 params = getattr(operation, 'params', None) 516 qubit = operation.qubits[0] 517 gate = single_gate_matrix(operation.name, params) 518 self._add_unitary(gate, [qubit]) 519 # Check if CX gate 520 elif operation.name in ('id', 'u0'): 521 pass 522 elif operation.name in ('CX', 'cx'): 523 qubit0 = operation.qubits[0] 524 qubit1 = operation.qubits[1] 525 gate = cx_gate_matrix() 526 self._add_unitary(gate, [qubit0, qubit1]) 527 # Check if reset 528 elif operation.name == 'reset': 529 qubit = operation.qubits[0] 530 self._add_qasm_reset(qubit) 531 # Check if barrier 532 elif operation.name == 'barrier': 533 pass 534 # Check if measure 535 elif operation.name == 'measure': 536 qubit = operation.qubits[0] 537 cmembit = operation.memory[0] 538 cregbit = operation.register[0] if hasattr(operation, 'register') else None 539 540 if self._sample_measure: 541 # If sampling measurements record the qubit and cmembit 542 # for this measurement for later sampling 543 measure_sample_ops.append((qubit, cmembit)) 544 else: 545 # If not sampling perform measurement as normal 546 self._add_qasm_measure(qubit, cmembit, cregbit) 547 elif operation.name == 'bfunc': 548 mask = int(operation.mask, 16) 549 relation = operation.relation 550 val = int(operation.val, 16) 551 552 cregbit = operation.register 553 cmembit = operation.memory if hasattr(operation, 'memory') else None 554 555 compared = (self._classical_register & mask) - val 556 557 if relation == '==': 558 outcome = (compared == 0) 559 elif relation == '!=': 560 outcome = (compared != 0) 561 elif relation == '<': 562 outcome = (compared < 0) 563 elif relation == '<=': 564 outcome = (compared <= 0) 565 elif relation == '>': 566 outcome = (compared > 0) 567 elif relation == '>=': 568 outcome = (compared >= 0) 569 else: 570 raise BasicAerError('Invalid boolean function relation.') 571 572 # Store outcome in register and optionally memory slot 573 regbit = 1 << cregbit 574 self._classical_register = \ 575 (self._classical_register & (~regbit)) | (int(outcome) << cregbit) 576 if cmembit is not None: 577 membit = 1 << cmembit 578 self._classical_memory = \ 579 (self._classical_memory & (~membit)) | (int(outcome) << cmembit) 580 else: 581 backend = self.name() 582 err_msg = '{0} encountered unrecognized operation "{1}"' 583 raise BasicAerError(err_msg.format(backend, operation.name)) 584 585 # Add final creg data to memory list 586 if self._number_of_cmembits > 0: 587 if self._sample_measure: 588 # If sampling we generate all shot samples from the final statevector 589 memory = self._add_sample_measure(measure_sample_ops, self._shots) 590 else: 591 # Turn classical_memory (int) into bit string and pad zero for unused cmembits 592 outcome = bin(self._classical_memory)[2:] 593 memory.append(hex(int(outcome, 2))) 594 595 # Add data 596 data = {'counts': dict(Counter(memory))} 597 # Optionally add memory list 598 if self._memory: 599 data['memory'] = memory 600 # Optionally add final statevector 601 if self.SHOW_FINAL_STATE: 602 data['statevector'] = self._get_statevector() 603 # Remove empty counts and memory for statevector simulator 604 if not data['counts']: 605 data.pop('counts') 606 if 'memory' in data and not data['memory']: 607 data.pop('memory') 608 end = time.time() 609 return {'name': experiment.header.name, 610 'seed_simulator': seed_simulator, 611 'shots': self._shots, 612 'data': data, 613 'status': 'DONE', 614 'success': True, 615 'time_taken': (end - start), 616 'header': experiment.header.to_dict()} 617 618 def _validate(self, qobj): 619 """Semantic validations of the qobj which cannot be done via schemas.""" 620 n_qubits = qobj.config.n_qubits 621 max_qubits = self.configuration().n_qubits 622 if n_qubits > max_qubits: 623 raise BasicAerError('Number of qubits {} '.format(n_qubits) + 624 'is greater than maximum ({}) '.format(max_qubits) + 625 'for "{}".'.format(self.name())) 626 for experiment in qobj.experiments: 627 name = experiment.header.name 628 if experiment.config.memory_slots == 0: 629 logger.warning('No classical registers in circuit "%s", ' 630 'counts will be empty.', name) 631 elif 'measure' not in [op.name for op in experiment.instructions]: 632 logger.warning('No measurements in circuit "%s", ' 633 'classical register will remain all zeros.', name) 634 [end of qiskit/providers/basicaer/qasm_simulator.py] [start of qiskit/providers/basicaer/unitary_simulator.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 # pylint: disable=arguments-differ 16 17 """Contains a Python simulator that returns the unitary of the circuit. 18 19 It simulates a unitary of a quantum circuit that has been compiled to run on 20 the simulator. It is exponential in the number of qubits. 21 22 .. code-block:: python 23 24 UnitarySimulator().run(qobj) 25 26 Where the input is a Qobj object and the output is a BasicAerJob object, which can 27 later be queried for the Result object. The result will contain a 'unitary' 28 data field, which is a 2**n x 2**n complex numpy array representing the 29 circuit's unitary matrix. 30 """ 31 import logging 32 import uuid 33 import time 34 from math import log2, sqrt 35 import numpy as np 36 from qiskit.util import local_hardware_info 37 from qiskit.providers.models import QasmBackendConfiguration 38 from qiskit.providers import BaseBackend 39 from qiskit.providers.basicaer.basicaerjob import BasicAerJob 40 from qiskit.result import Result 41 from .exceptions import BasicAerError 42 from .basicaertools import single_gate_matrix 43 from .basicaertools import cx_gate_matrix 44 from .basicaertools import einsum_matmul_index 45 46 logger = logging.getLogger(__name__) 47 48 49 # TODO add ["status"] = 'DONE', 'ERROR' especially for empty circuit error 50 # does not show up 51 52 53 class UnitarySimulatorPy(BaseBackend): 54 """Python implementation of a unitary simulator.""" 55 56 MAX_QUBITS_MEMORY = int(log2(sqrt(local_hardware_info()['memory'] * (1024 ** 3) / 16))) 57 58 DEFAULT_CONFIGURATION = { 59 'backend_name': 'unitary_simulator', 60 'backend_version': '1.0.0', 61 'n_qubits': min(24, MAX_QUBITS_MEMORY), 62 'url': 'https://github.com/Qiskit/qiskit-terra', 63 'simulator': True, 64 'local': True, 65 'conditional': False, 66 'open_pulse': False, 67 'memory': False, 68 'max_shots': 65536, 69 'coupling_map': None, 70 'description': 'A python simulator for unitary matrix corresponding to a circuit', 71 'basis_gates': ['u1', 'u2', 'u3', 'cx', 'id', 'unitary'], 72 'gates': [ 73 { 74 'name': 'u1', 75 'parameters': ['lambda'], 76 'qasm_def': 'gate u1(lambda) q { U(0,0,lambda) q; }' 77 }, 78 { 79 'name': 'u2', 80 'parameters': ['phi', 'lambda'], 81 'qasm_def': 'gate u2(phi,lambda) q { U(pi/2,phi,lambda) q; }' 82 }, 83 { 84 'name': 'u3', 85 'parameters': ['theta', 'phi', 'lambda'], 86 'qasm_def': 'gate u3(theta,phi,lambda) q { U(theta,phi,lambda) q; }' 87 }, 88 { 89 'name': 'cx', 90 'parameters': ['c', 't'], 91 'qasm_def': 'gate cx c,t { CX c,t; }' 92 }, 93 { 94 'name': 'id', 95 'parameters': ['a'], 96 'qasm_def': 'gate id a { U(0,0,0) a; }' 97 }, 98 { 99 'name': 'unitary', 100 'parameters': ['matrix'], 101 'qasm_def': 'unitary(matrix) q1, q2,...' 102 } 103 ] 104 } 105 106 DEFAULT_OPTIONS = { 107 "initial_unitary": None, 108 "chop_threshold": 1e-15 109 } 110 111 def __init__(self, configuration=None, provider=None): 112 super().__init__(configuration=( 113 configuration or QasmBackendConfiguration.from_dict(self.DEFAULT_CONFIGURATION)), 114 provider=provider) 115 116 # Define attributes inside __init__. 117 self._unitary = None 118 self._number_of_qubits = 0 119 self._initial_unitary = None 120 self._chop_threshold = 1e-15 121 122 def _add_unitary(self, gate, qubits): 123 """Apply an N-qubit unitary matrix. 124 125 Args: 126 gate (matrix_like): an N-qubit unitary matrix 127 qubits (list): the list of N-qubits. 128 """ 129 # Get the number of qubits 130 num_qubits = len(qubits) 131 # Compute einsum index string for 1-qubit matrix multiplication 132 indexes = einsum_matmul_index(qubits, self._number_of_qubits) 133 # Convert to complex rank-2N tensor 134 gate_tensor = np.reshape(np.array(gate, dtype=complex), 135 num_qubits * [2, 2]) 136 # Apply matrix multiplication 137 self._unitary = np.einsum(indexes, gate_tensor, self._unitary, 138 dtype=complex, casting='no') 139 140 def _validate_initial_unitary(self): 141 """Validate an initial unitary matrix""" 142 # If initial unitary isn't set we don't need to validate 143 if self._initial_unitary is None: 144 return 145 # Check unitary is correct length for number of qubits 146 shape = np.shape(self._initial_unitary) 147 required_shape = (2 ** self._number_of_qubits, 148 2 ** self._number_of_qubits) 149 if shape != required_shape: 150 raise BasicAerError('initial unitary is incorrect shape: ' + 151 '{} != 2 ** {}'.format(shape, required_shape)) 152 153 def _set_options(self, qobj_config=None, backend_options=None): 154 """Set the backend options for all experiments in a qobj""" 155 # Reset default options 156 self._initial_unitary = self.DEFAULT_OPTIONS["initial_unitary"] 157 self._chop_threshold = self.DEFAULT_OPTIONS["chop_threshold"] 158 if backend_options is None: 159 backend_options = {} 160 161 # Check for custom initial statevector in backend_options first, 162 # then config second 163 if 'initial_unitary' in backend_options: 164 self._initial_unitary = np.array(backend_options['initial_unitary'], 165 dtype=complex) 166 elif hasattr(qobj_config, 'initial_unitary'): 167 self._initial_unitary = np.array(qobj_config.initial_unitary, 168 dtype=complex) 169 if self._initial_unitary is not None: 170 # Check the initial unitary is actually unitary 171 shape = np.shape(self._initial_unitary) 172 if len(shape) != 2 or shape[0] != shape[1]: 173 raise BasicAerError("initial unitary is not a square matrix") 174 iden = np.eye(len(self._initial_unitary)) 175 u_dagger_u = np.dot(self._initial_unitary.T.conj(), 176 self._initial_unitary) 177 norm = np.linalg.norm(u_dagger_u - iden) 178 if round(norm, 10) != 0: 179 raise BasicAerError("initial unitary is not unitary") 180 # Check the initial statevector is normalized 181 182 # Check for custom chop threshold 183 # Replace with custom options 184 if 'chop_threshold' in backend_options: 185 self._chop_threshold = backend_options['chop_threshold'] 186 elif hasattr(qobj_config, 'chop_threshold'): 187 self._chop_threshold = qobj_config.chop_threshold 188 189 def _initialize_unitary(self): 190 """Set the initial unitary for simulation""" 191 self._validate_initial_unitary() 192 if self._initial_unitary is None: 193 # Set to identity matrix 194 self._unitary = np.eye(2 ** self._number_of_qubits, 195 dtype=complex) 196 else: 197 self._unitary = self._initial_unitary.copy() 198 # Reshape to rank-N tensor 199 self._unitary = np.reshape(self._unitary, 200 self._number_of_qubits * [2, 2]) 201 202 def _get_unitary(self): 203 """Return the current unitary""" 204 unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits]) 205 unitary[abs(unitary) < self._chop_threshold] = 0.0 206 return unitary 207 208 def run(self, qobj, backend_options=None): 209 """Run qobj asynchronously. 210 211 Args: 212 qobj (Qobj): payload of the experiment 213 backend_options (dict): backend options 214 215 Returns: 216 BasicAerJob: derived from BaseJob 217 218 Additional Information:: 219 220 backend_options: Is a dict of options for the backend. It may contain 221 * "initial_unitary": matrix_like 222 * "chop_threshold": double 223 224 The "initial_unitary" option specifies a custom initial unitary 225 matrix for the simulator to be used instead of the identity 226 matrix. This size of this matrix must be correct for the number 227 of qubits inall experiments in the qobj. 228 229 The "chop_threshold" option specifies a truncation value for 230 setting small values to zero in the output unitary. The default 231 value is 1e-15. 232 233 Example:: 234 235 backend_options = { 236 "initial_unitary": np.array([[1, 0, 0, 0], 237 [0, 0, 0, 1], 238 [0, 0, 1, 0], 239 [0, 1, 0, 0]]) 240 "chop_threshold": 1e-15 241 } 242 """ 243 self._set_options(qobj_config=qobj.config, 244 backend_options=backend_options) 245 job_id = str(uuid.uuid4()) 246 job = BasicAerJob(self, job_id, self._run_job, qobj) 247 job.submit() 248 return job 249 250 def _run_job(self, job_id, qobj): 251 """Run experiments in qobj. 252 253 Args: 254 job_id (str): unique id for the job. 255 qobj (Qobj): job description 256 257 Returns: 258 Result: Result object 259 """ 260 self._validate(qobj) 261 result_list = [] 262 start = time.time() 263 for experiment in qobj.experiments: 264 result_list.append(self.run_experiment(experiment)) 265 end = time.time() 266 result = {'backend_name': self.name(), 267 'backend_version': self._configuration.backend_version, 268 'qobj_id': qobj.qobj_id, 269 'job_id': job_id, 270 'results': result_list, 271 'status': 'COMPLETED', 272 'success': True, 273 'time_taken': (end - start), 274 'header': qobj.header.to_dict()} 275 276 return Result.from_dict(result) 277 278 def run_experiment(self, experiment): 279 """Run an experiment (circuit) and return a single experiment result. 280 281 Args: 282 experiment (QobjExperiment): experiment from qobj experiments list 283 284 Returns: 285 dict: A result dictionary which looks something like:: 286 287 { 288 "name": name of this experiment (obtained from qobj.experiment header) 289 "seed": random seed used for simulation 290 "shots": number of shots used in the simulation 291 "data": 292 { 293 "unitary": [[[0.0, 0.0], [1.0, 0.0]], 294 [[1.0, 0.0], [0.0, 0.0]]] 295 }, 296 "status": status string for the simulation 297 "success": boolean 298 "time taken": simulation time of this single experiment 299 } 300 301 Raises: 302 BasicAerError: if the number of qubits in the circuit is greater than 24. 303 Note that the practical qubit limit is much lower than 24. 304 """ 305 start = time.time() 306 self._number_of_qubits = experiment.header.n_qubits 307 308 # Validate the dimension of initial unitary if set 309 self._validate_initial_unitary() 310 self._initialize_unitary() 311 312 for operation in experiment.instructions: 313 if operation.name == 'unitary': 314 qubits = operation.qubits 315 gate = operation.params[0] 316 self._add_unitary(gate, qubits) 317 # Check if single gate 318 elif operation.name in ('U', 'u1', 'u2', 'u3'): 319 params = getattr(operation, 'params', None) 320 qubit = operation.qubits[0] 321 gate = single_gate_matrix(operation.name, params) 322 self._add_unitary(gate, [qubit]) 323 elif operation.name in ('id', 'u0'): 324 pass 325 # Check if CX gate 326 elif operation.name in ('CX', 'cx'): 327 qubit0 = operation.qubits[0] 328 qubit1 = operation.qubits[1] 329 gate = cx_gate_matrix() 330 self._add_unitary(gate, [qubit0, qubit1]) 331 # Check if barrier 332 elif operation.name == 'barrier': 333 pass 334 else: 335 backend = self.name() 336 err_msg = '{0} encountered unrecognized operation "{1}"' 337 raise BasicAerError(err_msg.format(backend, operation.name)) 338 # Add final state to data 339 data = {'unitary': self._get_unitary()} 340 end = time.time() 341 return {'name': experiment.header.name, 342 'shots': 1, 343 'data': data, 344 'status': 'DONE', 345 'success': True, 346 'time_taken': (end - start), 347 'header': experiment.header.to_dict()} 348 349 def _validate(self, qobj): 350 """Semantic validations of the qobj which cannot be done via schemas. 351 Some of these may later move to backend schemas. 352 1. No shots 353 2. No measurements in the middle 354 """ 355 n_qubits = qobj.config.n_qubits 356 max_qubits = self.configuration().n_qubits 357 if n_qubits > max_qubits: 358 raise BasicAerError('Number of qubits {} '.format(n_qubits) + 359 'is greater than maximum ({}) '.format(max_qubits) + 360 'for "{}".'.format(self.name())) 361 if hasattr(qobj.config, 'shots') and qobj.config.shots != 1: 362 logger.info('"%s" only supports 1 shot. Setting shots=1.', 363 self.name()) 364 qobj.config.shots = 1 365 for experiment in qobj.experiments: 366 name = experiment.header.name 367 if getattr(experiment.config, 'shots', 1) != 1: 368 logger.info('"%s" only supports 1 shot. ' 369 'Setting shots=1 for circuit "%s".', 370 self.name(), name) 371 experiment.config.shots = 1 372 for operation in experiment.instructions: 373 if operation.name in ['measure', 'reset']: 374 raise BasicAerError('Unsupported "%s" instruction "%s" ' + 375 'in circuit "%s" ', self.name(), 376 operation.name, name) 377 [end of qiskit/providers/basicaer/unitary_simulator.py] [start of qiskit/quantum_info/operators/operator.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017, 2019. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 """ 16 Matrix Operator class. 17 """ 18 19 import copy 20 import re 21 from numbers import Number 22 23 import numpy as np 24 25 from qiskit.circuit.quantumcircuit import QuantumCircuit 26 from qiskit.circuit.instruction import Instruction 27 from qiskit.circuit.library.standard_gates import IGate, XGate, YGate, ZGate, HGate, SGate, TGate 28 from qiskit.exceptions import QiskitError 29 from qiskit.quantum_info.operators.predicates import is_unitary_matrix, matrix_equal 30 from qiskit.quantum_info.operators.base_operator import BaseOperator 31 32 33 class Operator(BaseOperator): 34 r"""Matrix operator class 35 36 This represents a matrix operator :math:`M` that will 37 :meth:`~Statevector.evolve` a :class:`Statevector` :math:`|\psi\rangle` 38 by matrix-vector multiplication 39 40 .. math:: 41 42 |\psi\rangle \mapsto M|\psi\rangle, 43 44 and will :meth:`~DensityMatrix.evolve` a :class:`DensityMatrix` :math:`\rho` 45 by left and right multiplication 46 47 .. math:: 48 49 \rho \mapsto M \rho M^\dagger. 50 """ 51 52 def __init__(self, data, input_dims=None, output_dims=None): 53 """Initialize an operator object. 54 55 Args: 56 data (QuantumCircuit or 57 Instruction or 58 BaseOperator or 59 matrix): data to initialize operator. 60 input_dims (tuple): the input subsystem dimensions. 61 [Default: None] 62 output_dims (tuple): the output subsystem dimensions. 63 [Default: None] 64 65 Raises: 66 QiskitError: if input data cannot be initialized as an operator. 67 68 Additional Information: 69 If the input or output dimensions are None, they will be 70 automatically determined from the input data. If the input data is 71 a Numpy array of shape (2**N, 2**N) qubit systems will be used. If 72 the input operator is not an N-qubit operator, it will assign a 73 single subsystem with dimension specified by the shape of the input. 74 """ 75 if isinstance(data, (list, np.ndarray)): 76 # Default initialization from list or numpy array matrix 77 self._data = np.asarray(data, dtype=complex) 78 elif isinstance(data, (QuantumCircuit, Instruction)): 79 # If the input is a Terra QuantumCircuit or Instruction we 80 # perform a simulation to construct the unitary operator. 81 # This will only work if the circuit or instruction can be 82 # defined in terms of unitary gate instructions which have a 83 # 'to_matrix' method defined. Any other instructions such as 84 # conditional gates, measure, or reset will cause an 85 # exception to be raised. 86 self._data = self._init_instruction(data).data 87 elif hasattr(data, 'to_operator'): 88 # If the data object has a 'to_operator' attribute this is given 89 # higher preference than the 'to_matrix' method for initializing 90 # an Operator object. 91 data = data.to_operator() 92 self._data = data.data 93 if input_dims is None: 94 input_dims = data._input_dims 95 if output_dims is None: 96 output_dims = data._output_dims 97 elif hasattr(data, 'to_matrix'): 98 # If no 'to_operator' attribute exists we next look for a 99 # 'to_matrix' attribute to a matrix that will be cast into 100 # a complex numpy matrix. 101 self._array = np.asarray(data.to_matrix(), dtype=complex) 102 else: 103 raise QiskitError("Invalid input data format for Operator") 104 # Determine input and output dimensions 105 dout, din = self._data.shape 106 output_dims = self._automatic_dims(output_dims, dout) 107 input_dims = self._automatic_dims(input_dims, din) 108 super().__init__(input_dims, output_dims) 109 110 def __repr__(self): 111 prefix = 'Operator(' 112 pad = len(prefix) * ' ' 113 return '{}{},\n{}input_dims={}, output_dims={})'.format( 114 prefix, np.array2string( 115 self.data, separator=', ', prefix=prefix), 116 pad, self._input_dims, self._output_dims) 117 118 def __eq__(self, other): 119 """Test if two Operators are equal.""" 120 if not super().__eq__(other): 121 return False 122 return np.allclose( 123 self.data, other.data, rtol=self.rtol, atol=self.atol) 124 125 @property 126 def data(self): 127 """Return data.""" 128 return self._data 129 130 @classmethod 131 def from_label(cls, label): 132 """Return a tensor product of single-qubit operators. 133 134 Args: 135 label (string): single-qubit operator string. 136 137 Returns: 138 Operator: The N-qubit operator. 139 140 Raises: 141 QiskitError: if the label contains invalid characters, or the 142 length of the label is larger than an explicitly 143 specified num_qubits. 144 145 Additional Information: 146 The labels correspond to the single-qubit matrices: 147 'I': [[1, 0], [0, 1]] 148 'X': [[0, 1], [1, 0]] 149 'Y': [[0, -1j], [1j, 0]] 150 'Z': [[1, 0], [0, -1]] 151 'H': [[1, 1], [1, -1]] / sqrt(2) 152 'S': [[1, 0], [0 , 1j]] 153 'T': [[1, 0], [0, (1+1j) / sqrt(2)]] 154 '0': [[1, 0], [0, 0]] 155 '1': [[0, 0], [0, 1]] 156 '+': [[0.5, 0.5], [0.5 , 0.5]] 157 '-': [[0.5, -0.5], [-0.5 , 0.5]] 158 'r': [[0.5, -0.5j], [0.5j , 0.5]] 159 'l': [[0.5, 0.5j], [-0.5j , 0.5]] 160 """ 161 # Check label is valid 162 label_mats = { 163 'I': IGate().to_matrix(), 164 'X': XGate().to_matrix(), 165 'Y': YGate().to_matrix(), 166 'Z': ZGate().to_matrix(), 167 'H': HGate().to_matrix(), 168 'S': SGate().to_matrix(), 169 'T': TGate().to_matrix(), 170 '0': np.array([[1, 0], [0, 0]], dtype=complex), 171 '1': np.array([[0, 0], [0, 1]], dtype=complex), 172 '+': np.array([[0.5, 0.5], [0.5, 0.5]], dtype=complex), 173 '-': np.array([[0.5, -0.5], [-0.5, 0.5]], dtype=complex), 174 'r': np.array([[0.5, -0.5j], [0.5j, 0.5]], dtype=complex), 175 'l': np.array([[0.5, 0.5j], [-0.5j, 0.5]], dtype=complex), 176 } 177 if re.match(r'^[IXYZHST01rl\-+]+$', label) is None: 178 raise QiskitError('Label contains invalid characters.') 179 # Initialize an identity matrix and apply each gate 180 num_qubits = len(label) 181 op = Operator(np.eye(2 ** num_qubits, dtype=complex)) 182 for qubit, char in enumerate(reversed(label)): 183 if char != 'I': 184 op = op.compose(label_mats[char], qargs=[qubit]) 185 return op 186 187 def is_unitary(self, atol=None, rtol=None): 188 """Return True if operator is a unitary matrix.""" 189 if atol is None: 190 atol = self.atol 191 if rtol is None: 192 rtol = self.rtol 193 return is_unitary_matrix(self._data, rtol=rtol, atol=atol) 194 195 def to_operator(self): 196 """Convert operator to matrix operator class""" 197 return self 198 199 def to_instruction(self): 200 """Convert to a UnitaryGate instruction.""" 201 # pylint: disable=cyclic-import 202 from qiskit.extensions.unitary import UnitaryGate 203 return UnitaryGate(self.data) 204 205 def conjugate(self): 206 """Return the conjugate of the operator.""" 207 # Make a shallow copy and update array 208 ret = copy.copy(self) 209 ret._data = np.conj(self._data) 210 return ret 211 212 def transpose(self): 213 """Return the transpose of the operator.""" 214 # Make a shallow copy and update array 215 ret = copy.copy(self) 216 ret._data = np.transpose(self._data) 217 # Swap input and output dimensions 218 ret._set_dims(self._output_dims, self._input_dims) 219 return ret 220 221 def compose(self, other, qargs=None, front=False): 222 """Return the composed operator. 223 224 Args: 225 other (Operator): an operator object. 226 qargs (list or None): a list of subsystem positions to apply 227 other on. If None apply on all 228 subsystems [default: None]. 229 front (bool): If True compose using right operator multiplication, 230 instead of left multiplication [default: False]. 231 232 Returns: 233 Operator: The operator self @ other. 234 235 Raise: 236 QiskitError: if operators have incompatible dimensions for 237 composition. 238 239 Additional Information: 240 Composition (``@``) is defined as `left` matrix multiplication for 241 matrix operators. That is that ``A @ B`` is equal to ``B * A``. 242 Setting ``front=True`` returns `right` matrix multiplication 243 ``A * B`` and is equivalent to the :meth:`dot` method. 244 """ 245 if qargs is None: 246 qargs = getattr(other, 'qargs', None) 247 if not isinstance(other, Operator): 248 other = Operator(other) 249 # Validate dimensions are compatible and return the composed 250 # operator dimensions 251 input_dims, output_dims = self._get_compose_dims( 252 other, qargs, front) 253 254 # Full composition of operators 255 if qargs is None: 256 if front: 257 # Composition self * other 258 data = np.dot(self._data, other.data) 259 else: 260 # Composition other * self 261 data = np.dot(other.data, self._data) 262 return Operator(data, input_dims, output_dims) 263 264 # Compose with other on subsystem 265 if front: 266 num_indices = len(self._input_dims) 267 shift = len(self._output_dims) 268 right_mul = True 269 else: 270 num_indices = len(self._output_dims) 271 shift = 0 272 right_mul = False 273 274 # Reshape current matrix 275 # Note that we must reverse the subsystem dimension order as 276 # qubit 0 corresponds to the right-most position in the tensor 277 # product, which is the last tensor wire index. 278 tensor = np.reshape(self.data, self._shape) 279 mat = np.reshape(other.data, other._shape) 280 indices = [num_indices - 1 - qubit for qubit in qargs] 281 final_shape = [np.product(output_dims), np.product(input_dims)] 282 data = np.reshape( 283 Operator._einsum_matmul(tensor, mat, indices, shift, right_mul), 284 final_shape) 285 return Operator(data, input_dims, output_dims) 286 287 def dot(self, other, qargs=None): 288 """Return the right multiplied operator self * other. 289 290 Args: 291 other (Operator): an operator object. 292 qargs (list or None): a list of subsystem positions to apply 293 other on. If None apply on all 294 subsystems [default: None]. 295 296 Returns: 297 Operator: The operator self * other. 298 299 Raises: 300 QiskitError: if other cannot be converted to an Operator or has 301 incompatible dimensions. 302 """ 303 return super().dot(other, qargs=qargs) 304 305 def power(self, n): 306 """Return the matrix power of the operator. 307 308 Args: 309 n (int): the power to raise the matrix to. 310 311 Returns: 312 BaseOperator: the n-times composed operator. 313 314 Raises: 315 QiskitError: if the input and output dimensions of the operator 316 are not equal, or the power is not a positive integer. 317 """ 318 if not isinstance(n, int): 319 raise QiskitError("Can only take integer powers of Operator.") 320 if self.input_dims() != self.output_dims(): 321 raise QiskitError("Can only power with input_dims = output_dims.") 322 # Override base class power so we can implement more efficiently 323 # using Numpy.matrix_power 324 ret = copy.copy(self) 325 ret._data = np.linalg.matrix_power(self.data, n) 326 return ret 327 328 def tensor(self, other): 329 """Return the tensor product operator self βŠ— other. 330 331 Args: 332 other (Operator): a operator subclass object. 333 334 Returns: 335 Operator: the tensor product operator self βŠ— other. 336 337 Raises: 338 QiskitError: if other cannot be converted to an operator. 339 """ 340 if not isinstance(other, Operator): 341 other = Operator(other) 342 input_dims = other.input_dims() + self.input_dims() 343 output_dims = other.output_dims() + self.output_dims() 344 data = np.kron(self._data, other._data) 345 return Operator(data, input_dims, output_dims) 346 347 def expand(self, other): 348 """Return the tensor product operator other βŠ— self. 349 350 Args: 351 other (Operator): an operator object. 352 353 Returns: 354 Operator: the tensor product operator other βŠ— self. 355 356 Raises: 357 QiskitError: if other cannot be converted to an operator. 358 """ 359 if not isinstance(other, Operator): 360 other = Operator(other) 361 input_dims = self.input_dims() + other.input_dims() 362 output_dims = self.output_dims() + other.output_dims() 363 data = np.kron(other._data, self._data) 364 return Operator(data, input_dims, output_dims) 365 366 def _add(self, other, qargs=None): 367 """Return the operator self + other. 368 369 If ``qargs`` are specified the other operator will be added 370 assuming it is identity on all other subsystems. 371 372 Args: 373 other (Operator): an operator object. 374 qargs (None or list): optional subsystems to add on 375 (Default: None) 376 377 Returns: 378 Operator: the operator self + other. 379 380 Raises: 381 QiskitError: if other is not an operator, or has incompatible 382 dimensions. 383 """ 384 # pylint: disable=import-outside-toplevel, cyclic-import 385 from qiskit.quantum_info.operators.scalar_op import ScalarOp 386 387 if qargs is None: 388 qargs = getattr(other, 'qargs', None) 389 390 if not isinstance(other, Operator): 391 other = Operator(other) 392 393 self._validate_add_dims(other, qargs) 394 other = ScalarOp._pad_with_identity(self, other, qargs) 395 396 ret = copy.copy(self) 397 ret._data = self.data + other.data 398 return ret 399 400 def _multiply(self, other): 401 """Return the operator self * other. 402 403 Args: 404 other (complex): a complex number. 405 406 Returns: 407 Operator: the operator other * self. 408 409 Raises: 410 QiskitError: if other is not a valid complex number. 411 """ 412 if not isinstance(other, Number): 413 raise QiskitError("other is not a number") 414 ret = copy.copy(self) 415 ret._data = other * self._data 416 return ret 417 418 def equiv(self, other, rtol=None, atol=None): 419 """Return True if operators are equivalent up to global phase. 420 421 Args: 422 other (Operator): an operator object. 423 rtol (float): relative tolerance value for comparison. 424 atol (float): absolute tolerance value for comparison. 425 426 Returns: 427 bool: True if operators are equivalent up to global phase. 428 """ 429 if not isinstance(other, Operator): 430 try: 431 other = Operator(other) 432 except QiskitError: 433 return False 434 if self.dim != other.dim: 435 return False 436 if atol is None: 437 atol = self.atol 438 if rtol is None: 439 rtol = self.rtol 440 return matrix_equal(self.data, other.data, ignore_phase=True, 441 rtol=rtol, atol=atol) 442 443 @property 444 def _shape(self): 445 """Return the tensor shape of the matrix operator""" 446 return tuple(reversed(self.output_dims())) + tuple( 447 reversed(self.input_dims())) 448 449 @classmethod 450 def _einsum_matmul(cls, tensor, mat, indices, shift=0, right_mul=False): 451 """Perform a contraction using Numpy.einsum 452 453 Args: 454 tensor (np.array): a vector or matrix reshaped to a rank-N tensor. 455 mat (np.array): a matrix reshaped to a rank-2M tensor. 456 indices (list): tensor indices to contract with mat. 457 shift (int): shift for indices of tensor to contract [Default: 0]. 458 right_mul (bool): if True right multiply tensor by mat 459 (else left multiply) [Default: False]. 460 461 Returns: 462 Numpy.ndarray: the matrix multiplied rank-N tensor. 463 464 Raises: 465 QiskitError: if mat is not an even rank tensor. 466 """ 467 rank = tensor.ndim 468 rank_mat = mat.ndim 469 if rank_mat % 2 != 0: 470 raise QiskitError( 471 "Contracted matrix must have an even number of indices.") 472 # Get einsum indices for tensor 473 indices_tensor = list(range(rank)) 474 for j, index in enumerate(indices): 475 indices_tensor[index + shift] = rank + j 476 # Get einsum indices for mat 477 mat_contract = list(reversed(range(rank, rank + len(indices)))) 478 mat_free = [index + shift for index in reversed(indices)] 479 if right_mul: 480 indices_mat = mat_contract + mat_free 481 else: 482 indices_mat = mat_free + mat_contract 483 return np.einsum(tensor, indices_tensor, mat, indices_mat) 484 485 @classmethod 486 def _init_instruction(cls, instruction): 487 """Convert a QuantumCircuit or Instruction to an Operator.""" 488 # Convert circuit to an instruction 489 if isinstance(instruction, QuantumCircuit): 490 instruction = instruction.to_instruction() 491 # Initialize an identity operator of the correct size of the circuit 492 op = Operator(np.eye(2 ** instruction.num_qubits)) 493 op._append_instruction(instruction) 494 return op 495 496 @classmethod 497 def _instruction_to_matrix(cls, obj): 498 """Return Operator for instruction if defined or None otherwise.""" 499 if not isinstance(obj, Instruction): 500 raise QiskitError('Input is not an instruction.') 501 mat = None 502 if hasattr(obj, 'to_matrix'): 503 # If instruction is a gate first we see if it has a 504 # `to_matrix` definition and if so use that. 505 try: 506 mat = obj.to_matrix() 507 except QiskitError: 508 pass 509 return mat 510 511 def _append_instruction(self, obj, qargs=None): 512 """Update the current Operator by apply an instruction.""" 513 mat = self._instruction_to_matrix(obj) 514 if mat is not None: 515 # Perform the composition and inplace update the current state 516 # of the operator 517 op = self.compose(mat, qargs=qargs) 518 self._data = op.data 519 else: 520 # If the instruction doesn't have a matrix defined we use its 521 # circuit decomposition definition if it exists, otherwise we 522 # cannot compose this gate and raise an error. 523 if obj.definition is None: 524 raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) 525 for instr, qregs, cregs in obj.definition: 526 if cregs: 527 raise QiskitError( 528 'Cannot apply instruction with classical registers: {}'.format( 529 instr.name)) 530 # Get the integer position of the flat register 531 if qargs is None: 532 new_qargs = [tup.index for tup in qregs] 533 else: 534 new_qargs = [qargs[tup.index] for tup in qregs] 535 self._append_instruction(instr, qargs=new_qargs) 536 [end of qiskit/quantum_info/operators/operator.py] [start of qiskit/quantum_info/states/densitymatrix.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017, 2019. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 """ 16 DensityMatrix quantum state class. 17 """ 18 19 import warnings 20 from numbers import Number 21 import numpy as np 22 23 from qiskit.circuit.quantumcircuit import QuantumCircuit 24 from qiskit.circuit.instruction import Instruction 25 from qiskit.exceptions import QiskitError 26 from qiskit.quantum_info.states.quantum_state import QuantumState 27 from qiskit.quantum_info.operators.operator import Operator 28 from qiskit.quantum_info.operators.scalar_op import ScalarOp 29 from qiskit.quantum_info.operators.predicates import is_hermitian_matrix 30 from qiskit.quantum_info.operators.predicates import is_positive_semidefinite_matrix 31 from qiskit.quantum_info.operators.channel.quantum_channel import QuantumChannel 32 from qiskit.quantum_info.operators.channel.superop import SuperOp 33 from qiskit.quantum_info.states.statevector import Statevector 34 35 36 class DensityMatrix(QuantumState): 37 """DensityMatrix class""" 38 39 def __init__(self, data, dims=None): 40 """Initialize a density matrix object. 41 42 Args: 43 data (matrix_like or vector_like): a density matrix or 44 statevector. If a vector the density matrix is constructed 45 as the projector of that vector. 46 dims (int or tuple or list): Optional. The subsystem dimension 47 of the state (See additional information). 48 49 Raises: 50 QiskitError: if input data is not valid. 51 52 Additional Information: 53 The ``dims`` kwarg can be None, an integer, or an iterable of 54 integers. 55 56 * ``Iterable`` -- the subsystem dimensions are the values in the list 57 with the total number of subsystems given by the length of the list. 58 59 * ``Int`` or ``None`` -- the leading dimension of the input matrix 60 specifies the total dimension of the density matrix. If it is a 61 power of two the state will be initialized as an N-qubit state. 62 If it is not a power of two the state will have a single 63 d-dimensional subsystem. 64 """ 65 if isinstance(data, (list, np.ndarray)): 66 # Finally we check if the input is a raw matrix in either a 67 # python list or numpy array format. 68 self._data = np.asarray(data, dtype=complex) 69 elif hasattr(data, 'to_operator'): 70 # If the data object has a 'to_operator' attribute this is given 71 # higher preference than the 'to_matrix' method for initializing 72 # an Operator object. 73 op = data.to_operator() 74 self._data = op.data 75 if dims is None: 76 dims = op._output_dims 77 elif hasattr(data, 'to_matrix'): 78 # If no 'to_operator' attribute exists we next look for a 79 # 'to_matrix' attribute to a matrix that will be cast into 80 # a complex numpy matrix. 81 self._data = np.asarray(data.to_matrix(), dtype=complex) 82 else: 83 raise QiskitError("Invalid input data format for DensityMatrix") 84 # Convert statevector into a density matrix 85 ndim = self._data.ndim 86 shape = self._data.shape 87 if ndim == 2 and shape[0] == shape[1]: 88 pass # We good 89 elif ndim == 1: 90 self._data = np.outer(self._data, np.conj(self._data)) 91 elif ndim == 2 and shape[1] == 1: 92 self._data = np.reshape(self._data, shape[0]) 93 shape = self._data.shape 94 else: 95 raise QiskitError( 96 "Invalid DensityMatrix input: not a square matrix.") 97 super().__init__(self._automatic_dims(dims, shape[0])) 98 99 def __eq__(self, other): 100 return super().__eq__(other) and np.allclose( 101 self._data, other._data, rtol=self.rtol, atol=self.atol) 102 103 def __repr__(self): 104 prefix = 'DensityMatrix(' 105 pad = len(prefix) * ' ' 106 return '{}{},\n{}dims={})'.format( 107 prefix, np.array2string( 108 self._data, separator=', ', prefix=prefix), 109 pad, self._dims) 110 111 @property 112 def data(self): 113 """Return data.""" 114 return self._data 115 116 def is_valid(self, atol=None, rtol=None): 117 """Return True if trace 1 and positive semidefinite.""" 118 if atol is None: 119 atol = self.atol 120 if rtol is None: 121 rtol = self.rtol 122 # Check trace == 1 123 if not np.allclose(self.trace(), 1, rtol=rtol, atol=atol): 124 return False 125 # Check Hermitian 126 if not is_hermitian_matrix(self.data, rtol=rtol, atol=atol): 127 return False 128 # Check positive semidefinite 129 return is_positive_semidefinite_matrix(self.data, rtol=rtol, atol=atol) 130 131 def to_operator(self): 132 """Convert to Operator""" 133 dims = self.dims() 134 return Operator(self.data, input_dims=dims, output_dims=dims) 135 136 def conjugate(self): 137 """Return the conjugate of the density matrix.""" 138 return DensityMatrix(np.conj(self.data), dims=self.dims()) 139 140 def trace(self): 141 """Return the trace of the density matrix.""" 142 return np.trace(self.data) 143 144 def purity(self): 145 """Return the purity of the quantum state.""" 146 # For a valid statevector the purity is always 1, however if we simply 147 # have an arbitrary vector (not correctly normalized) then the 148 # purity is equivalent to the trace squared: 149 # P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2 150 return np.trace(np.dot(self.data, self.data)) 151 152 def tensor(self, other): 153 """Return the tensor product state self βŠ— other. 154 155 Args: 156 other (DensityMatrix): a quantum state object. 157 158 Returns: 159 DensityMatrix: the tensor product operator self βŠ— other. 160 161 Raises: 162 QiskitError: if other is not a quantum state. 163 """ 164 if not isinstance(other, DensityMatrix): 165 other = DensityMatrix(other) 166 dims = other.dims() + self.dims() 167 data = np.kron(self._data, other._data) 168 return DensityMatrix(data, dims) 169 170 def expand(self, other): 171 """Return the tensor product state other βŠ— self. 172 173 Args: 174 other (DensityMatrix): a quantum state object. 175 176 Returns: 177 DensityMatrix: the tensor product state other βŠ— self. 178 179 Raises: 180 QiskitError: if other is not a quantum state. 181 """ 182 if not isinstance(other, DensityMatrix): 183 other = DensityMatrix(other) 184 dims = self.dims() + other.dims() 185 data = np.kron(other._data, self._data) 186 return DensityMatrix(data, dims) 187 188 def _add(self, other): 189 """Return the linear combination self + other. 190 191 Args: 192 other (DensityMatrix): a quantum state object. 193 194 Returns: 195 DensityMatrix: the linear combination self + other. 196 197 Raises: 198 QiskitError: if other is not a quantum state, or has 199 incompatible dimensions. 200 """ 201 if not isinstance(other, DensityMatrix): 202 other = DensityMatrix(other) 203 if self.dim != other.dim: 204 raise QiskitError("other DensityMatrix has different dimensions.") 205 return DensityMatrix(self.data + other.data, self.dims()) 206 207 def _multiply(self, other): 208 """Return the scalar multiplied state other * self. 209 210 Args: 211 other (complex): a complex number. 212 213 Returns: 214 DensityMatrix: the scalar multiplied state other * self. 215 216 Raises: 217 QiskitError: if other is not a valid complex number. 218 """ 219 if not isinstance(other, Number): 220 raise QiskitError("other is not a number") 221 return DensityMatrix(other * self.data, self.dims()) 222 223 def evolve(self, other, qargs=None): 224 """Evolve a quantum state by an operator. 225 226 Args: 227 other (Operator or QuantumChannel 228 or Instruction or Circuit): The operator to evolve by. 229 qargs (list): a list of QuantumState subsystem positions to apply 230 the operator on. 231 232 Returns: 233 QuantumState: the output quantum state. 234 235 Raises: 236 QiskitError: if the operator dimension does not match the 237 specified QuantumState subsystem dimensions. 238 """ 239 if qargs is None: 240 qargs = getattr(other, 'qargs', None) 241 242 # Evolution by a circuit or instruction 243 if isinstance(other, (QuantumCircuit, Instruction)): 244 return self._evolve_instruction(other, qargs=qargs) 245 246 # Evolution by a QuantumChannel 247 if hasattr(other, 'to_quantumchannel'): 248 return other.to_quantumchannel()._evolve(self, qargs=qargs) 249 if isinstance(other, QuantumChannel): 250 return other._evolve(self, qargs=qargs) 251 252 # Unitary evolution by an Operator 253 if not isinstance(other, Operator): 254 other = Operator(other) 255 return self._evolve_operator(other, qargs=qargs) 256 257 def probabilities(self, qargs=None, decimals=None): 258 """Return the subsystem measurement probability vector. 259 260 Measurement probabilities are with respect to measurement in the 261 computation (diagonal) basis. 262 263 Args: 264 qargs (None or list): subsystems to return probabilities for, 265 if None return for all subsystems (Default: None). 266 decimals (None or int): the number of decimal places to round 267 values. If None no rounding is done (Default: None). 268 269 Returns: 270 np.array: The Numpy vector array of probabilities. 271 272 Examples: 273 274 Consider a 2-qubit product state :math:`\\rho=\\rho_1\\otimes\\rho_0` 275 with :math:`\\rho_1=|+\\rangle\\!\\langle+|`, 276 :math:`\\rho_0=|0\\rangle\\!\\langle0|`. 277 278 .. jupyter-execute:: 279 280 from qiskit.quantum_info import DensityMatrix 281 282 rho = DensityMatrix.from_label('+0') 283 284 # Probabilities for measuring both qubits 285 probs = rho.probabilities() 286 print('probs: {}'.format(probs)) 287 288 # Probabilities for measuring only qubit-0 289 probs_qubit_0 = rho.probabilities([0]) 290 print('Qubit-0 probs: {}'.format(probs_qubit_0)) 291 292 # Probabilities for measuring only qubit-1 293 probs_qubit_1 = rho.probabilities([1]) 294 print('Qubit-1 probs: {}'.format(probs_qubit_1)) 295 296 We can also permute the order of qubits in the ``qargs`` list 297 to change the qubit position in the probabilities output 298 299 .. jupyter-execute:: 300 301 from qiskit.quantum_info import DensityMatrix 302 303 rho = DensityMatrix.from_label('+0') 304 305 # Probabilities for measuring both qubits 306 probs = rho.probabilities([0, 1]) 307 print('probs: {}'.format(probs)) 308 309 # Probabilities for measuring both qubits 310 # but swapping qubits 0 and 1 in output 311 probs_swapped = rho.probabilities([1, 0]) 312 print('Swapped probs: {}'.format(probs_swapped)) 313 """ 314 probs = self._subsystem_probabilities( 315 np.abs(self.data.diagonal()), self._dims, qargs=qargs) 316 if decimals is not None: 317 probs = probs.round(decimals=decimals) 318 return probs 319 320 def reset(self, qargs=None): 321 """Reset state or subsystems to the 0-state. 322 323 Args: 324 qargs (list or None): subsystems to reset, if None all 325 subsystems will be reset to their 0-state 326 (Default: None). 327 328 Returns: 329 DensityMatrix: the reset state. 330 331 Additional Information: 332 If all subsystems are reset this will return the ground state 333 on all subsystems. If only a some subsystems are reset this 334 function will perform evolution by the reset 335 :class:`~qiskit.quantum_info.SuperOp` of the reset subsystems. 336 """ 337 if qargs is None: 338 # Resetting all qubits does not require sampling or RNG 339 state = np.zeros(2 * (self._dim, ), dtype=complex) 340 state[0, 0] = 1 341 return DensityMatrix(state, dims=self._dims) 342 343 # Reset by evolving by reset SuperOp 344 dims = self.dims(qargs) 345 reset_superop = SuperOp(ScalarOp(dims, coeff=0)) 346 reset_superop.data[0] = Operator(ScalarOp(dims)).data.ravel() 347 return self.evolve(reset_superop, qargs=qargs) 348 349 @classmethod 350 def from_label(cls, label): 351 r"""Return a tensor product of Pauli X,Y,Z eigenstates. 352 353 .. list-table:: Single-qubit state labels 354 :header-rows: 1 355 356 * - Label 357 - Statevector 358 * - ``"0"`` 359 - :math:`\begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}` 360 * - ``"1"`` 361 - :math:`\begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}` 362 * - ``"+"`` 363 - :math:`\frac{1}{2}\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}` 364 * - ``"-"`` 365 - :math:`\frac{1}{2}\begin{pmatrix} 1 & -1 \\ -1 & 1 \end{pmatrix}` 366 * - ``"r"`` 367 - :math:`\frac{1}{2}\begin{pmatrix} 1 & -i \\ i & 1 \end{pmatrix}` 368 * - ``"l"`` 369 - :math:`\frac{1}{2}\begin{pmatrix} 1 & i \\ -i & 1 \end{pmatrix}` 370 371 Args: 372 label (string): a eigenstate string ket label (see table for 373 allowed values). 374 375 Returns: 376 Statevector: The N-qubit basis state density matrix. 377 378 Raises: 379 QiskitError: if the label contains invalid characters, or the length 380 of the label is larger than an explicitly specified num_qubits. 381 """ 382 return DensityMatrix(Statevector.from_label(label)) 383 384 @staticmethod 385 def from_int(i, dims): 386 """Return a computational basis state density matrix. 387 388 Args: 389 i (int): the basis state element. 390 dims (int or tuple or list): The subsystem dimensions of the statevector 391 (See additional information). 392 393 Returns: 394 DensityMatrix: The computational basis state :math:`|i\\rangle\\!\\langle i|`. 395 396 Additional Information: 397 The ``dims`` kwarg can be an integer or an iterable of integers. 398 399 * ``Iterable`` -- the subsystem dimensions are the values in the list 400 with the total number of subsystems given by the length of the list. 401 402 * ``Int`` -- the integer specifies the total dimension of the 403 state. If it is a power of two the state will be initialized 404 as an N-qubit state. If it is not a power of two the state 405 will have a single d-dimensional subsystem. 406 """ 407 size = np.product(dims) 408 state = np.zeros((size, size), dtype=complex) 409 state[i, i] = 1.0 410 return DensityMatrix(state, dims=dims) 411 412 @classmethod 413 def from_instruction(cls, instruction): 414 """Return the output density matrix of an instruction. 415 416 The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of 417 the same number of qubits as the input instruction or circuit, evolved 418 by the input instruction, and the output statevector returned. 419 420 Args: 421 instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit 422 423 Returns: 424 DensityMatrix: the final density matrix. 425 426 Raises: 427 QiskitError: if the instruction contains invalid instructions for 428 density matrix simulation. 429 """ 430 # Convert circuit to an instruction 431 if isinstance(instruction, QuantumCircuit): 432 instruction = instruction.to_instruction() 433 # Initialize an the statevector in the all |0> state 434 num_qubits = instruction.num_qubits 435 init = np.zeros((2**num_qubits, 2**num_qubits), dtype=complex) 436 init[0, 0] = 1 437 vec = DensityMatrix(init, dims=num_qubits * (2, )) 438 vec._append_instruction(instruction) 439 return vec 440 441 def to_dict(self, decimals=None): 442 r"""Convert the density matrix to dictionary form. 443 444 This dictionary representation uses a Ket-like notation where the 445 dictionary keys are qudit strings for the subsystem basis vectors. 446 If any subsystem has a dimension greater than 10 comma delimiters are 447 inserted between integers so that subsystems can be distinguished. 448 449 Args: 450 decimals (None or int): the number of decimal places to round 451 values. If None no rounding is done 452 (Default: None). 453 454 Returns: 455 dict: the dictionary form of the DensityMatrix. 456 457 Examples: 458 459 The ket-form of a 2-qubit density matrix 460 :math:`rho = |-\rangle\!\langle -|\otimes |0\rangle\!\langle 0|` 461 462 .. jupyter-execute:: 463 464 from qiskit.quantum_info import DensityMatrix 465 466 rho = DensityMatrix.from_label('-0') 467 print(rho.to_dict()) 468 469 For non-qubit subsystems the integer range can go from 0 to 9. For 470 example in a qutrit system 471 472 .. jupyter-execute:: 473 474 import numpy as np 475 from qiskit.quantum_info import DensityMatrix 476 477 mat = np.zeros((9, 9)) 478 mat[0, 0] = 0.25 479 mat[3, 3] = 0.25 480 mat[6, 6] = 0.25 481 mat[-1, -1] = 0.25 482 rho = DensityMatrix(mat, dims=(3, 3)) 483 print(rho.to_dict()) 484 485 For large subsystem dimensions delimeters are required. The 486 following example is for a 20-dimensional system consisting of 487 a qubit and 10-dimensional qudit. 488 489 .. jupyter-execute:: 490 491 import numpy as np 492 from qiskit.quantum_info import DensityMatrix 493 494 mat = np.zeros((2 * 10, 2 * 10)) 495 mat[0, 0] = 0.5 496 mat[-1, -1] = 0.5 497 rho = DensityMatrix(mat, dims=(2, 10)) 498 print(rho.to_dict()) 499 """ 500 return self._matrix_to_dict(self.data, 501 self._dims, 502 decimals=decimals, 503 string_labels=True) 504 505 @property 506 def _shape(self): 507 """Return the tensor shape of the matrix operator""" 508 return 2 * tuple(reversed(self.dims())) 509 510 def _evolve_operator(self, other, qargs=None): 511 """Evolve density matrix by an operator""" 512 if qargs is None: 513 # Evolution on full matrix 514 if self._dim != other._input_dim: 515 raise QiskitError( 516 "Operator input dimension is not equal to density matrix dimension." 517 ) 518 op_mat = other.data 519 mat = np.dot(op_mat, self.data).dot(op_mat.T.conj()) 520 return DensityMatrix(mat, dims=other._output_dims) 521 # Otherwise we are applying an operator only to subsystems 522 # Check dimensions of subsystems match the operator 523 if self.dims(qargs) != other.input_dims(): 524 raise QiskitError( 525 "Operator input dimensions are not equal to statevector subsystem dimensions." 526 ) 527 # Reshape statevector and operator 528 tensor = np.reshape(self.data, self._shape) 529 # Construct list of tensor indices of statevector to be contracted 530 num_indices = len(self.dims()) 531 indices = [num_indices - 1 - qubit for qubit in qargs] 532 # Left multiple by mat 533 mat = np.reshape(other.data, other._shape) 534 tensor = Operator._einsum_matmul(tensor, mat, indices) 535 # Right multiply by mat ** dagger 536 adj = other.adjoint() 537 mat_adj = np.reshape(adj.data, adj._shape) 538 tensor = Operator._einsum_matmul(tensor, mat_adj, indices, num_indices, 539 True) 540 # Replace evolved dimensions 541 new_dims = list(self.dims()) 542 for i, qubit in enumerate(qargs): 543 new_dims[qubit] = other._output_dims[i] 544 new_dim = np.product(new_dims) 545 return DensityMatrix(np.reshape(tensor, (new_dim, new_dim)), 546 dims=new_dims) 547 548 def _append_instruction(self, other, qargs=None): 549 """Update the current Statevector by applying an instruction.""" 550 551 # Try evolving by a matrix operator (unitary-like evolution) 552 mat = Operator._instruction_to_matrix(other) 553 if mat is not None: 554 self._data = self._evolve_operator(Operator(mat), qargs=qargs).data 555 return 556 # Otherwise try evolving by a Superoperator 557 chan = SuperOp._instruction_to_superop(other) 558 if chan is not None: 559 # Evolve current state by the superoperator 560 self._data = chan._evolve(self, qargs=qargs).data 561 return 562 # If the instruction doesn't have a matrix defined we use its 563 # circuit decomposition definition if it exists, otherwise we 564 # cannot compose this gate and raise an error. 565 if other.definition is None: 566 raise QiskitError('Cannot apply Instruction: {}'.format( 567 other.name)) 568 for instr, qregs, cregs in other.definition: 569 if cregs: 570 raise QiskitError( 571 'Cannot apply instruction with classical registers: {}'. 572 format(instr.name)) 573 # Get the integer position of the flat register 574 if qargs is None: 575 new_qargs = [tup.index for tup in qregs] 576 else: 577 new_qargs = [qargs[tup.index] for tup in qregs] 578 self._append_instruction(instr, qargs=new_qargs) 579 580 def _evolve_instruction(self, obj, qargs=None): 581 """Return a new statevector by applying an instruction.""" 582 if isinstance(obj, QuantumCircuit): 583 obj = obj.to_instruction() 584 vec = DensityMatrix(self.data, dims=self._dims) 585 vec._append_instruction(obj, qargs=qargs) 586 return vec 587 588 def to_statevector(self, atol=None, rtol=None): 589 """Return a statevector from a pure density matrix. 590 591 Args: 592 atol (float): Absolute tolerance for checking operation validity. 593 rtol (float): Relative tolerance for checking operation validity. 594 595 Returns: 596 Statevector: The pure density matrix's corresponding statevector. 597 Corresponds to the eigenvector of the only non-zero eigenvalue. 598 599 Raises: 600 QiskitError: if the state is not pure. 601 """ 602 if atol is None: 603 atol = self.atol 604 if rtol is None: 605 rtol = self.rtol 606 607 if not is_hermitian_matrix(self._data, atol=atol, rtol=rtol): 608 raise QiskitError("Not a valid density matrix (non-hermitian).") 609 610 evals, evecs = np.linalg.eig(self._data) 611 612 nonzero_evals = evals[abs(evals) > atol] 613 if len(nonzero_evals) != 1 or not np.isclose(nonzero_evals[0], 1, 614 atol=atol, rtol=rtol): 615 raise QiskitError("Density matrix is not a pure state") 616 617 psi = evecs[:, np.argmax(evals)] # eigenvectors returned in columns. 618 return Statevector(psi) 619 620 def to_counts(self): 621 """Returns the density matrix as a counts dict of probabilities. 622 623 DEPRECATED: use :meth:`probabilities_dict` instead. 624 625 Returns: 626 dict: Counts of probabilities. 627 """ 628 warnings.warn( 629 'The `Statevector.to_counts` method is deprecated as of 0.13.0,' 630 ' and will be removed no earlier than 3 months after that ' 631 'release date. You should use the `Statevector.probabilities_dict`' 632 ' method instead.', DeprecationWarning, stacklevel=2) 633 return self.probabilities_dict() 634 [end of qiskit/quantum_info/states/densitymatrix.py] [start of qiskit/quantum_info/states/statevector.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017, 2019. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 """ 16 Statevector quantum state class. 17 """ 18 19 import re 20 import warnings 21 from numbers import Number 22 23 import numpy as np 24 25 from qiskit.circuit.quantumcircuit import QuantumCircuit 26 from qiskit.circuit.instruction import Instruction 27 from qiskit.exceptions import QiskitError 28 from qiskit.quantum_info.states.quantum_state import QuantumState 29 from qiskit.quantum_info.operators.operator import Operator 30 from qiskit.quantum_info.operators.predicates import matrix_equal 31 32 33 class Statevector(QuantumState): 34 """Statevector class""" 35 36 def __init__(self, data, dims=None): 37 """Initialize a statevector object. 38 39 Args: 40 data (vector_like): a complex statevector. 41 dims (int or tuple or list): Optional. The subsystem dimension of 42 the state (See additional information). 43 44 Raises: 45 QiskitError: if input data is not valid. 46 47 Additional Information: 48 The ``dims`` kwarg can be None, an integer, or an iterable of 49 integers. 50 51 * ``Iterable`` -- the subsystem dimensions are the values in the list 52 with the total number of subsystems given by the length of the list. 53 54 * ``Int`` or ``None`` -- the length of the input vector 55 specifies the total dimension of the density matrix. If it is a 56 power of two the state will be initialized as an N-qubit state. 57 If it is not a power of two the state will have a single 58 d-dimensional subsystem. 59 """ 60 if isinstance(data, (list, np.ndarray)): 61 # Finally we check if the input is a raw vector in either a 62 # python list or numpy array format. 63 self._data = np.asarray(data, dtype=complex) 64 elif isinstance(data, Statevector): 65 self._data = data._data 66 if dims is None: 67 dims = data._dims 68 elif isinstance(data, Operator): 69 # We allow conversion of column-vector operators to Statevectors 70 input_dim, output_dim = data.dim 71 if input_dim != 1: 72 raise QiskitError("Input Operator is not a column-vector.") 73 self._data = np.ravel(data.data) 74 else: 75 raise QiskitError("Invalid input data format for Statevector") 76 # Check that the input is a numpy vector or column-vector numpy 77 # matrix. If it is a column-vector matrix reshape to a vector. 78 ndim = self._data.ndim 79 shape = self._data.shape 80 if ndim != 1: 81 if ndim == 2 and shape[1] == 1: 82 self._data = np.reshape(self._data, shape[0]) 83 elif ndim != 2 or shape[1] != 1: 84 raise QiskitError("Invalid input: not a vector or column-vector.") 85 super().__init__(self._automatic_dims(dims, shape[0])) 86 87 def __eq__(self, other): 88 return super().__eq__(other) and np.allclose( 89 self._data, other._data, rtol=self.rtol, atol=self.atol) 90 91 def __repr__(self): 92 prefix = 'Statevector(' 93 pad = len(prefix) * ' ' 94 return '{}{},\n{}dims={})'.format( 95 prefix, np.array2string( 96 self.data, separator=', ', prefix=prefix), 97 pad, self._dims) 98 99 @property 100 def data(self): 101 """Return data.""" 102 return self._data 103 104 def is_valid(self, atol=None, rtol=None): 105 """Return True if a Statevector has norm 1.""" 106 if atol is None: 107 atol = self.atol 108 if rtol is None: 109 rtol = self.rtol 110 norm = np.linalg.norm(self.data) 111 return np.allclose(norm, 1, rtol=rtol, atol=atol) 112 113 def to_operator(self): 114 """Convert state to a rank-1 projector operator""" 115 mat = np.outer(self.data, np.conj(self.data)) 116 return Operator(mat, input_dims=self.dims(), output_dims=self.dims()) 117 118 def conjugate(self): 119 """Return the conjugate of the operator.""" 120 return Statevector(np.conj(self.data), dims=self.dims()) 121 122 def trace(self): 123 """Return the trace of the quantum state as a density matrix.""" 124 return np.sum(np.abs(self.data) ** 2) 125 126 def purity(self): 127 """Return the purity of the quantum state.""" 128 # For a valid statevector the purity is always 1, however if we simply 129 # have an arbitrary vector (not correctly normalized) then the 130 # purity is equivalent to the trace squared: 131 # P(|psi>) = Tr[|psi><psi|psi><psi|] = |<psi|psi>|^2 132 return self.trace() ** 2 133 134 def tensor(self, other): 135 """Return the tensor product state self βŠ— other. 136 137 Args: 138 other (Statevector): a quantum state object. 139 140 Returns: 141 Statevector: the tensor product operator self βŠ— other. 142 143 Raises: 144 QiskitError: if other is not a quantum state. 145 """ 146 if not isinstance(other, Statevector): 147 other = Statevector(other) 148 dims = other.dims() + self.dims() 149 data = np.kron(self._data, other._data) 150 return Statevector(data, dims) 151 152 def expand(self, other): 153 """Return the tensor product state other βŠ— self. 154 155 Args: 156 other (Statevector): a quantum state object. 157 158 Returns: 159 Statevector: the tensor product state other βŠ— self. 160 161 Raises: 162 QiskitError: if other is not a quantum state. 163 """ 164 if not isinstance(other, Statevector): 165 other = Statevector(other) 166 dims = self.dims() + other.dims() 167 data = np.kron(other._data, self._data) 168 return Statevector(data, dims) 169 170 def _add(self, other): 171 """Return the linear combination self + other. 172 173 Args: 174 other (Statevector): a quantum state object. 175 176 Returns: 177 Statevector: the linear combination self + other. 178 179 Raises: 180 QiskitError: if other is not a quantum state, or has 181 incompatible dimensions. 182 """ 183 if not isinstance(other, Statevector): 184 other = Statevector(other) 185 if self.dim != other.dim: 186 raise QiskitError("other Statevector has different dimensions.") 187 return Statevector(self.data + other.data, self.dims()) 188 189 def _multiply(self, other): 190 """Return the scalar multiplied state self * other. 191 192 Args: 193 other (complex): a complex number. 194 195 Returns: 196 Statevector: the scalar multiplied state other * self. 197 198 Raises: 199 QiskitError: if other is not a valid complex number. 200 """ 201 if not isinstance(other, Number): 202 raise QiskitError("other is not a number") 203 return Statevector(other * self.data, self.dims()) 204 205 def evolve(self, other, qargs=None): 206 """Evolve a quantum state by the operator. 207 208 Args: 209 other (Operator): The operator to evolve by. 210 qargs (list): a list of Statevector subsystem positions to apply 211 the operator on. 212 213 Returns: 214 Statevector: the output quantum state. 215 216 Raises: 217 QiskitError: if the operator dimension does not match the 218 specified Statevector subsystem dimensions. 219 """ 220 if qargs is None: 221 qargs = getattr(other, 'qargs', None) 222 223 # Evolution by a circuit or instruction 224 if isinstance(other, (QuantumCircuit, Instruction)): 225 return self._evolve_instruction(other, qargs=qargs) 226 # Evolution by an Operator 227 if not isinstance(other, Operator): 228 other = Operator(other) 229 if qargs is None: 230 # Evolution on full statevector 231 if self._dim != other._input_dim: 232 raise QiskitError( 233 "Operator input dimension is not equal to statevector dimension." 234 ) 235 return Statevector(np.dot(other.data, self.data), dims=other.output_dims()) 236 # Otherwise we are applying an operator only to subsystems 237 # Check dimensions of subsystems match the operator 238 if self.dims(qargs) != other.input_dims(): 239 raise QiskitError( 240 "Operator input dimensions are not equal to statevector subsystem dimensions." 241 ) 242 # Reshape statevector and operator 243 tensor = np.reshape(self.data, self._shape) 244 mat = np.reshape(other.data, other._shape) 245 # Construct list of tensor indices of statevector to be contracted 246 num_indices = len(self.dims()) 247 indices = [num_indices - 1 - qubit for qubit in qargs] 248 tensor = Operator._einsum_matmul(tensor, mat, indices) 249 new_dims = list(self.dims()) 250 for i, qubit in enumerate(qargs): 251 new_dims[qubit] = other._output_dims[i] 252 # Replace evolved dimensions 253 return Statevector(np.reshape(tensor, np.product(new_dims)), dims=new_dims) 254 255 def equiv(self, other, rtol=None, atol=None): 256 """Return True if statevectors are equivalent up to global phase. 257 258 Args: 259 other (Statevector): a statevector object. 260 rtol (float): relative tolerance value for comparison. 261 atol (float): absolute tolerance value for comparison. 262 263 Returns: 264 bool: True if statevectors are equivalent up to global phase. 265 """ 266 if not isinstance(other, Statevector): 267 try: 268 other = Statevector(other) 269 except QiskitError: 270 return False 271 if self.dim != other.dim: 272 return False 273 if atol is None: 274 atol = self.atol 275 if rtol is None: 276 rtol = self.rtol 277 return matrix_equal(self.data, other.data, ignore_phase=True, 278 rtol=rtol, atol=atol) 279 280 def probabilities(self, qargs=None, decimals=None): 281 """Return the subsystem measurement probability vector. 282 283 Measurement probabilities are with respect to measurement in the 284 computation (diagonal) basis. 285 286 Args: 287 qargs (None or list): subsystems to return probabilities for, 288 if None return for all subsystems (Default: None). 289 decimals (None or int): the number of decimal places to round 290 values. If None no rounding is done (Default: None). 291 292 Returns: 293 np.array: The Numpy vector array of probabilities. 294 295 Examples: 296 297 Consider a 2-qubit product state 298 :math:`|\\psi\\rangle=|+\\rangle\\otimes|0\\rangle`. 299 300 .. jupyter-execute:: 301 302 from qiskit.quantum_info import Statevector 303 304 psi = Statevector.from_label('+0') 305 306 # Probabilities for measuring both qubits 307 probs = psi.probabilities() 308 print('probs: {}'.format(probs)) 309 310 # Probabilities for measuring only qubit-0 311 probs_qubit_0 = psi.probabilities([0]) 312 print('Qubit-0 probs: {}'.format(probs_qubit_0)) 313 314 # Probabilities for measuring only qubit-1 315 probs_qubit_1 = psi.probabilities([1]) 316 print('Qubit-1 probs: {}'.format(probs_qubit_1)) 317 318 We can also permute the order of qubits in the ``qargs`` list 319 to change the qubit position in the probabilities output 320 321 .. jupyter-execute:: 322 323 from qiskit.quantum_info import Statevector 324 325 psi = Statevector.from_label('+0') 326 327 # Probabilities for measuring both qubits 328 probs = psi.probabilities([0, 1]) 329 print('probs: {}'.format(probs)) 330 331 # Probabilities for measuring both qubits 332 # but swapping qubits 0 and 1 in output 333 probs_swapped = psi.probabilities([1, 0]) 334 print('Swapped probs: {}'.format(probs_swapped)) 335 """ 336 probs = self._subsystem_probabilities( 337 np.abs(self.data) ** 2, self._dims, qargs=qargs) 338 if decimals is not None: 339 probs = probs.round(decimals=decimals) 340 return probs 341 342 def reset(self, qargs=None): 343 """Reset state or subsystems to the 0-state. 344 345 Args: 346 qargs (list or None): subsystems to reset, if None all 347 subsystems will be reset to their 0-state 348 (Default: None). 349 350 Returns: 351 Statevector: the reset state. 352 353 Additional Information: 354 If all subsystems are reset this will return the ground state 355 on all subsystems. If only a some subsystems are reset this 356 function will perform a measurement on those subsystems and 357 evolve the subsystems so that the collapsed post-measurement 358 states are rotated to the 0-state. The RNG seed for this 359 sampling can be set using the :meth:`seed` method. 360 """ 361 if qargs is None: 362 # Resetting all qubits does not require sampling or RNG 363 state = np.zeros(self._dim, dtype=complex) 364 state[0] = 1 365 return Statevector(state, dims=self._dims) 366 367 # Sample a single measurement outcome 368 dims = self.dims(qargs) 369 probs = self.probabilities(qargs) 370 sample = self._rng.choice(len(probs), p=probs, size=1) 371 372 # Convert to projector for state update 373 proj = np.zeros(len(probs), dtype=complex) 374 proj[sample] = 1 / np.sqrt(probs[sample]) 375 376 # Rotate outcome to 0 377 reset = np.eye(len(probs)) 378 reset[0, 0] = 0 379 reset[sample, sample] = 0 380 reset[0, sample] = 1 381 382 # compose with reset projection 383 reset = np.dot(reset, np.diag(proj)) 384 return self.evolve( 385 Operator(reset, input_dims=dims, output_dims=dims), 386 qargs=qargs) 387 388 def to_counts(self): 389 """Returns the statevector as a counts dict 390 of probabilities. 391 392 DEPRECATED: use :meth:`probabilities_dict` instead. 393 394 Returns: 395 dict: Counts of probabilities. 396 """ 397 warnings.warn( 398 'The `Statevector.to_counts` method is deprecated as of 0.13.0,' 399 ' and will be removed no earlier than 3 months after that ' 400 'release date. You should use the `Statevector.probabilities_dict`' 401 ' method instead.', DeprecationWarning, stacklevel=2) 402 return self.probabilities_dict() 403 404 @classmethod 405 def from_label(cls, label): 406 """Return a tensor product of Pauli X,Y,Z eigenstates. 407 408 .. list-table:: Single-qubit state labels 409 :header-rows: 1 410 411 * - Label 412 - Statevector 413 * - ``"0"`` 414 - :math:`[1, 0]` 415 * - ``"1"`` 416 - :math:`[0, 1]` 417 * - ``"+"`` 418 - :math:`[1 / \\sqrt{2}, 1 / \\sqrt{2}]` 419 * - ``"-"`` 420 - :math:`[1 / \\sqrt{2}, -1 / \\sqrt{2}]` 421 * - ``"r"`` 422 - :math:`[1 / \\sqrt{2}, i / \\sqrt{2}]` 423 * - ``"l"`` 424 - :math:`[1 / \\sqrt{2}, -i / \\sqrt{2}]` 425 426 Args: 427 label (string): a eigenstate string ket label (see table for 428 allowed values). 429 430 Returns: 431 Statevector: The N-qubit basis state density matrix. 432 433 Raises: 434 QiskitError: if the label contains invalid characters, or the 435 length of the label is larger than an explicitly 436 specified num_qubits. 437 """ 438 # Check label is valid 439 if re.match(r'^[01rl\-+]+$', label) is None: 440 raise QiskitError('Label contains invalid characters.') 441 # We can prepare Z-eigenstates by converting the computational 442 # basis bit-string to an integer and preparing that unit vector 443 # However, for X-basis states, we will prepare a Z-eigenstate first 444 # then apply Hadamard gates to rotate 0 and 1s to + and -. 445 z_label = label 446 xy_states = False 447 if re.match('^[01]+$', label) is None: 448 # We have X or Y eigenstates so replace +,r with 0 and 449 # -,l with 1 and prepare the corresponding Z state 450 xy_states = True 451 z_label = z_label.replace('+', '0') 452 z_label = z_label.replace('r', '0') 453 z_label = z_label.replace('-', '1') 454 z_label = z_label.replace('l', '1') 455 # Initialize Z eigenstate vector 456 num_qubits = len(label) 457 data = np.zeros(1 << num_qubits, dtype=complex) 458 pos = int(z_label, 2) 459 data[pos] = 1 460 state = Statevector(data) 461 if xy_states: 462 # Apply hadamards to all qubits in X eigenstates 463 x_mat = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2) 464 # Apply S.H to qubits in Y eigenstates 465 y_mat = np.dot(np.diag([1, 1j]), x_mat) 466 for qubit, char in enumerate(reversed(label)): 467 if char in ['+', '-']: 468 state = state.evolve(x_mat, qargs=[qubit]) 469 elif char in ['r', 'l']: 470 state = state.evolve(y_mat, qargs=[qubit]) 471 return state 472 473 @staticmethod 474 def from_int(i, dims): 475 """Return a computational basis statevector. 476 477 Args: 478 i (int): the basis state element. 479 dims (int or tuple or list): The subsystem dimensions of the statevector 480 (See additional information). 481 482 Returns: 483 Statevector: The computational basis state :math:`|i\\rangle`. 484 485 Additional Information: 486 The ``dims`` kwarg can be an integer or an iterable of integers. 487 488 * ``Iterable`` -- the subsystem dimensions are the values in the list 489 with the total number of subsystems given by the length of the list. 490 491 * ``Int`` -- the integer specifies the total dimension of the 492 state. If it is a power of two the state will be initialized 493 as an N-qubit state. If it is not a power of two the state 494 will have a single d-dimensional subsystem. 495 """ 496 size = np.product(dims) 497 state = np.zeros(size, dtype=complex) 498 state[i] = 1.0 499 return Statevector(state, dims=dims) 500 501 @classmethod 502 def from_instruction(cls, instruction): 503 """Return the output statevector of an instruction. 504 505 The statevector is initialized in the state :math:`|{0,\\ldots,0}\\rangle` of the 506 same number of qubits as the input instruction or circuit, evolved 507 by the input instruction, and the output statevector returned. 508 509 Args: 510 instruction (qiskit.circuit.Instruction or QuantumCircuit): instruction or circuit 511 512 Returns: 513 Statevector: The final statevector. 514 515 Raises: 516 QiskitError: if the instruction contains invalid instructions for 517 the statevector simulation. 518 """ 519 # Convert circuit to an instruction 520 if isinstance(instruction, QuantumCircuit): 521 instruction = instruction.to_instruction() 522 # Initialize an the statevector in the all |0> state 523 init = np.zeros(2 ** instruction.num_qubits, dtype=complex) 524 init[0] = 1.0 525 vec = Statevector(init, dims=instruction.num_qubits * (2,)) 526 vec._append_instruction(instruction) 527 return vec 528 529 def to_dict(self, decimals=None): 530 r"""Convert the statevector to dictionary form. 531 532 This dictionary representation uses a Ket-like notation where the 533 dictionary keys are qudit strings for the subsystem basis vectors. 534 If any subsystem has a dimension greater than 10 comma delimiters are 535 inserted between integers so that subsystems can be distinguished. 536 537 Args: 538 decimals (None or int): the number of decimal places to round 539 values. If None no rounding is done 540 (Default: None). 541 542 Returns: 543 dict: the dictionary form of the Statevector. 544 545 Example: 546 547 The ket-form of a 2-qubit statevector 548 :math:`|\psi\rangle = |-\rangle\otimes |0\rangle` 549 550 .. jupyter-execute:: 551 552 from qiskit.quantum_info import Statevector 553 554 psi = Statevector.from_label('-0') 555 print(psi.to_dict()) 556 557 For non-qubit subsystems the integer range can go from 0 to 9. For 558 example in a qutrit system 559 560 .. jupyter-execute:: 561 562 import numpy as np 563 from qiskit.quantum_info import Statevector 564 565 vec = np.zeros(9) 566 vec[0] = 1 / np.sqrt(2) 567 vec[-1] = 1 / np.sqrt(2) 568 psi = Statevector(vec, dims=(3, 3)) 569 print(psi.to_dict()) 570 571 For large subsystem dimensions delimeters are required. The 572 following example is for a 20-dimensional system consisting of 573 a qubit and 10-dimensional qudit. 574 575 .. jupyter-execute:: 576 577 import numpy as np 578 from qiskit.quantum_info import Statevector 579 580 vec = np.zeros(2 * 10) 581 vec[0] = 1 / np.sqrt(2) 582 vec[-1] = 1 / np.sqrt(2) 583 psi = Statevector(vec, dims=(2, 10)) 584 print(psi.to_dict()) 585 """ 586 return self._vector_to_dict(self.data, 587 self._dims, 588 decimals=decimals, 589 string_labels=True) 590 591 @property 592 def _shape(self): 593 """Return the tensor shape of the matrix operator""" 594 return tuple(reversed(self.dims())) 595 596 def _append_instruction(self, obj, qargs=None): 597 """Update the current Statevector by applying an instruction.""" 598 mat = Operator._instruction_to_matrix(obj) 599 if mat is not None: 600 # Perform the composition and inplace update the current state 601 # of the operator 602 state = self.evolve(mat, qargs=qargs) 603 self._data = state.data 604 else: 605 # If the instruction doesn't have a matrix defined we use its 606 # circuit decomposition definition if it exists, otherwise we 607 # cannot compose this gate and raise an error. 608 if obj.definition is None: 609 raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) 610 for instr, qregs, cregs in obj.definition: 611 if cregs: 612 raise QiskitError( 613 'Cannot apply instruction with classical registers: {}'.format( 614 instr.name)) 615 # Get the integer position of the flat register 616 if qargs is None: 617 new_qargs = [tup.index for tup in qregs] 618 else: 619 new_qargs = [qargs[tup.index] for tup in qregs] 620 self._append_instruction(instr, qargs=new_qargs) 621 622 def _evolve_instruction(self, obj, qargs=None): 623 """Return a new statevector by applying an instruction.""" 624 if isinstance(obj, QuantumCircuit): 625 obj = obj.to_instruction() 626 vec = Statevector(self.data, dims=self.dims()) 627 vec._append_instruction(obj, qargs=qargs) 628 return vec 629 [end of qiskit/quantum_info/states/statevector.py] [start of qiskit/transpiler/__init__.py] 1 # -*- coding: utf-8 -*- 2 3 # This code is part of Qiskit. 4 # 5 # (C) Copyright IBM 2017, 2018. 6 # 7 # This code is licensed under the Apache License, Version 2.0. You may 8 # obtain a copy of this license in the LICENSE.txt file in the root directory 9 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 10 # 11 # Any modifications or derivative works of this code must retain this 12 # copyright notice, and modified files need to carry a notice indicating 13 # that they have been altered from the originals. 14 15 """ 16 ===================================== 17 Transpiler (:mod:`qiskit.transpiler`) 18 ===================================== 19 20 .. currentmodule:: qiskit.transpiler 21 22 Overview 23 ======== 24 Transpilation is the process of rewriting a given input circuit to match 25 the topoplogy of a specific quantum device, and/or to optimize the circuit 26 for execution on present day noisy quantum systems. 27 28 Most circuits must undergo a series of transformations that make them compatible with 29 a given target device, and optimize them to reduce the effects of noise on the 30 resulting outcomes. Rewriting quantum circuits to match hardware constraints and 31 optimizing for performance can be far from trivial. The flow of logic in the rewriting 32 tool chain need not be linear, and can often have iterative sub-loops, conditional 33 branches, and other complex behaviors. That being said, the basic building blocks 34 follow the structure given below: 35 36 .. image:: /source_images/transpiling_core_steps.png 37 38 .. raw:: html 39 40 <br> 41 42 Qiskit has four pre-built transpilation pipelines available here: 43 :mod:`qiskit.transpiler.preset_passmanagers`. Unless the reader is familiar with 44 quantum circuit optimization methods and their usage, it is best to use one of 45 these ready-made routines. 46 47 48 Supplementary Information 49 ========================= 50 51 .. container:: toggle 52 53 .. container:: header 54 55 **Basis Gates** 56 57 When writing a quantum circuit you are free to use any quantum gate (unitary operator) that 58 you like, along with a collection of non-gate operations such as qubit measurements and 59 reset operations. However, when running a circuit on a real quantum device one no longer 60 has this flexibility. Due to limitations in, for example, the physical interactions 61 between qubits, difficulty in implementing multi-qubit gates, control electronics etc, 62 a quantum computing device can only natively support a handful of quantum gates and non-gate 63 operations. In the present case of IBM Q devices, the native gate set can be found by querying 64 the devices themselves, and looking for the corresponding attribute in their configuration: 65 66 .. jupyter-execute:: 67 :hide-code: 68 :hide-output: 69 70 from qiskit.test.mock import FakeVigo 71 backend = FakeVigo() 72 73 .. jupyter-execute:: 74 75 backend.configuration().basis_gates 76 77 78 Every quantum circuit run on an IBM Q device must be expressed using only these basis gates. 79 For example, suppose one wants to run a simple phase estimation circuit: 80 81 .. jupyter-execute:: 82 83 import numpy as np 84 from qiskit import QuantumCircuit 85 qc = QuantumCircuit(2, 1) 86 87 qc.h(0) 88 qc.x(1) 89 qc.cu1(np.pi/4, 0, 1) 90 qc.h(0) 91 qc.measure([0], [0]) 92 qc.draw(output='mpl') 93 94 We have :math:`H`, :math:`X`, and controlled-:math:`U_{1}` gates, all of which are 95 not in our devices basis gate set, and must be expanded. This expansion is taken 96 care of for us in the :func:`qiskit.execute` function. However, we can 97 decompose the circuit to show what it would look like in the native gate set of 98 the IBM Quantum devices: 99 100 .. jupyter-execute:: 101 102 qc_basis = qc.decompose() 103 qc_basis.draw(output='mpl') 104 105 106 A few things to highlight. First, the circuit has gotten longer with respect to the 107 initial one. This can be verified by checking the depth of the circuits: 108 109 .. jupyter-execute:: 110 111 print('Original depth:', qc.depth(), 'Decomposed Depth:', qc_basis.depth()) 112 113 Second, although we had a single controlled gate, the fact that it was not in the basis 114 set means that, when expanded, it requires more than a single `cx` gate to implement. 115 All said, unrolling to the basis set of gates leads to an increase in the depth of a 116 quantum circuit and the number of gates. 117 118 It is important to highlight two special cases: 119 120 1. A SWAP gate is not a native gate on the IBM Q devices, and must be decomposed into 121 three CNOT gates: 122 123 .. jupyter-execute:: 124 125 swap_circ = QuantumCircuit(2) 126 swap_circ.swap(0, 1) 127 swap_circ.decompose().draw(output='mpl') 128 129 As a product of three CNOT gates, SWAP gates are expensive operations to perform on a 130 noisy quantum devices. However, such operations are usually necessary for embedding a 131 circuit into the limited entangling gate connectivities of actual devices. Thus, 132 minimizing the number of SWAP gates in a circuit is a primary goal in the 133 transpilation process. 134 135 136 2. A Toffoli, or controlled-controlled-not gate (`ccx`), is a three-qubit gate. Given 137 that our basis gate set includes only single- and two-qubit gates, it is obvious that 138 this gate must be decomposed. This decomposition is quite costly: 139 140 .. jupyter-execute:: 141 142 ccx_circ = QuantumCircuit(3) 143 ccx_circ.ccx(0, 1, 2) 144 ccx_circ.decompose().draw(output='mpl') 145 146 For every Toffoli gate in a quantum circuit, the IBM Quantum hardware may execute up to 147 six CNOT gates, and a handful of single-qubit gates. From this example, it should be 148 clear that any algorithm that makes use of multiple Toffoli gates will end up as a 149 circuit with large depth and will therefore be appreciably affected by noise and gate 150 errors. 151 152 153 .. raw:: html 154 155 <br> 156 157 .. container:: toggle 158 159 .. container:: header 160 161 **Initial Layout** 162 163 Quantum circuits are abstract entities whose qubits are "virtual" representations of actual 164 qubits used in computations. We need to be able to map these virtual qubits in a one-to-one 165 manner to the "physical" qubits in an actual quantum device. 166 167 .. image:: /source_images/mapping.png 168 169 .. raw:: html 170 171 <br><br> 172 173 By default, qiskit will do this mapping for you. The choice of mapping depends on the 174 properties of the circuit, the particular device you are targeting, and the optimization 175 level that is chosen. The basic mapping strategies are the following: 176 177 - **Trivial layout**: Map virtual qubits to the same numbered physical qubit on the device, 178 i.e. `[0,1,2,3,4]` -> `[0,1,2,3,4]` (default in `optimization_level=0` and 179 `optimization_level=1`). 180 181 - **Dense layout**: Find the sub-graph of the device with same number of qubits as the circuit 182 with the greatest connectivity (default in `optimization_level=2` and `optimization_level=3`). 183 184 185 The choice of initial layout is extremely important when: 186 187 1. Computing the number of SWAP operations needed to map the input circuit onto the device 188 topology. 189 190 2. Taking into account the noise properties of the device. 191 192 193 The choice of `initial_layout` can mean the difference between getting a result, 194 and getting nothing but noise. 195 196 Lets see what layouts are automatically picked at various optimization levels. The modified 197 circuits returned by :func:`qiskit.compiler.transpile` have this initial layout information 198 in them, and we can view this layout selection graphically using 199 :func:`qiskit.visualization.plot_circuit_layout`: 200 201 .. jupyter-execute:: 202 203 from qiskit import QuantumCircuit, transpile 204 from qiskit.visualization import plot_circuit_layout 205 from qiskit.test.mock import FakeVigo 206 backend = FakeVigo() 207 208 ghz = QuantumCircuit(3, 3) 209 ghz.h(0) 210 ghz.cx(0,range(1,3)) 211 ghz.barrier() 212 ghz.measure(range(3), range(3)) 213 ghz.draw(output='mpl') 214 215 216 - **Layout Using Optimization Level 0** 217 218 .. jupyter-execute:: 219 220 new_circ_lv0 = transpile(ghz, backend=backend, optimization_level=0) 221 plot_circuit_layout(new_circ_lv0, backend) 222 223 224 - **Layout Using Optimization Level 3** 225 226 .. jupyter-execute:: 227 228 new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) 229 plot_circuit_layout(new_circ_lv3, backend) 230 231 232 It is completely possible to specify your own initial layout. To do so we can 233 pass a list of integers to :func:`qiskit.compiler.transpile` via the `initial_layout` 234 keyword argument, where the index labels the virtual qubit in the circuit and the 235 corresponding value is the label for the physical qubit to map onto: 236 237 .. jupyter-execute:: 238 239 # Virtual -> physical 240 # 0 -> 3 241 # 1 -> 4 242 # 2 -> 2 243 244 my_ghz = transpile(ghz, backend, initial_layout=[3, 4, 2]) 245 plot_circuit_layout(my_ghz, backend) 246 247 .. raw:: html 248 249 <br> 250 251 252 .. container:: toggle 253 254 .. container:: header 255 256 **Mapping Circuits to Hardware Topology** 257 258 In order to implement a CNOT gate between qubits in a quantum circuit that are not directly 259 connected on a quantum device one or more SWAP gates must be inserted into the circuit to 260 move the qubit states around until they are adjacent on the device gate map. Each SWAP 261 gate is decomposed into three CNOT gates on the IBM Quantum devices, and represents an 262 expensive and noisy operation to perform. Thus, finding the minimum number of SWAP gates 263 needed to map a circuit onto a given device, is an important step (if not the most important) 264 in the whole execution process. 265 266 However, as with many important things in life, finding the optimal SWAP mapping is hard. 267 In fact it is in a class of problems called NP-Hard, and is thus prohibitively expensive 268 to compute for all but the smallest quantum devices and input circuits. To get around this, 269 by default Qiskit uses a stochastic heuristic algorithm called 270 :class:`Qiskit.transpiler.passes.StochasticSwap` to compute a good, but not necessarily minimal 271 SWAP count. The use of a stochastic method means the circuits generated by 272 :func:`Qiskit.compiler.transpile` (or :func:`Qiskit.execute` that calls `transpile` internally) 273 are not guaranteed to be the same over repeated runs. Indeed, running the same circuit 274 repeatedly will in general result in a distribution of circuit depths and gate counts at the 275 output. 276 277 In order to highlight this, we run a GHZ circuit 100 times, using a "bad" (disconnected) 278 `initial_layout`: 279 280 .. jupyter-execute:: 281 282 import matplotlib.pyplot as plt 283 from qiskit import QuantumCircuit, transpile 284 from qiskit.test.mock import FakeBoeblingen 285 backend = FakeBoeblingen() 286 287 ghz = QuantumCircuit(5) 288 ghz.h(0) 289 ghz.cx(0,range(1,5)) 290 ghz.draw(output='mpl') 291 292 293 .. jupyter-execute:: 294 295 depths = [] 296 for _ in range(100): 297 depths.append(transpile(ghz, 298 backend, 299 initial_layout=[7, 0, 4, 15, 19], 300 ).depth()) 301 302 plt.figure(figsize=(8, 6)) 303 plt.hist(depths, bins=list(range(14,36)), align='left', color='#AC557C') 304 plt.xlabel('Depth', fontsize=14) 305 plt.ylabel('Counts', fontsize=14); 306 307 308 This distribution is quite wide, signaling the difficultly the SWAP mapper is having 309 in computing the best mapping. Most circuits will have a distribution of depths, 310 perhaps not as wide as this one, due to the stochastic nature of the default SWAP 311 mapper. Of course, we want the best circuit we can get, especially in cases where 312 the depth is critical to success or failure. In cases like this, it is best to 313 :func:`transpile` a circuit several times, e.g. 10, and take the one with the 314 lowest depth. The :func:`transpile` function will automatically run in parallel 315 mode, making this procedure relatively speedy in most cases. 316 317 .. raw:: html 318 319 <br> 320 321 322 .. container:: toggle 323 324 .. container:: header 325 326 **Gate Optimization** 327 328 Decomposing quantum circuits into the basis gate set of the IBM Quantum devices, 329 and the addition of SWAP gates needed to match hardware topology, conspire to 330 increase the depth and gate count of quantum circuits. Fortunately many routines 331 for optimizing circuits by combining or eliminating gates exist. In some cases 332 these methods are so effective the output circuits have lower depth than the inputs. 333 In other cases, not much can be done, and the computation may be difficult to 334 perform on noisy devices. Different gate optimizations are turned on with 335 different `optimization_level` values. Below we show the benefits gained from 336 setting the optimization level higher: 337 338 .. important:: 339 340 The output from :func:`transpile` varies due to the stochastic swap mapper. 341 So the numbers below will likely change each time you run the code. 342 343 344 .. jupyter-execute:: 345 346 import matplotlib.pyplot as plt 347 from qiskit import QuantumCircuit, transpile 348 from qiskit.test.mock import FakeBoeblingen 349 backend = FakeBoeblingen() 350 351 ghz = QuantumCircuit(5) 352 ghz.h(0) 353 ghz.cx(0,range(1,5)) 354 ghz.draw(output='mpl') 355 356 357 .. jupyter-execute:: 358 359 for kk in range(4): 360 circ = transpile(ghz, backend, optimization_level=kk) 361 print('Optimization Level {}'.format(kk)) 362 print('Depth:', circ.depth()) 363 print('Gate counts:', circ.count_ops()) 364 print() 365 366 367 .. raw:: html 368 369 <br> 370 371 372 Transpiler API 373 ============== 374 375 Pass Manager Construction 376 ------------------------- 377 378 .. autosummary:: 379 :toctree: ../stubs/ 380 381 PassManager 382 PassManagerConfig 383 PropertySet 384 FlowController 385 386 Layout and Topology 387 ------------------- 388 389 .. autosummary:: 390 :toctree: ../stubs/ 391 392 Layout 393 CouplingMap 394 395 Fenced Objects 396 -------------- 397 398 .. autosummary:: 399 :toctree: ../stubs/ 400 401 FencedDAGCircuit 402 FencedPropertySet 403 404 Exceptions 405 ---------- 406 407 .. autosummary:: 408 :toctree: ../stubs/ 409 410 TranspilerError 411 TranspilerAccessError 412 """ 413 414 from .runningpassmanager import FlowController 415 from .passmanager import PassManager 416 from .passmanager_config import PassManagerConfig 417 from .propertyset import PropertySet 418 from .exceptions import TranspilerError, TranspilerAccessError 419 from .fencedobjs import FencedDAGCircuit, FencedPropertySet 420 from .basepasses import AnalysisPass, TransformationPass 421 from .coupling import CouplingMap 422 from .layout import Layout 423 [end of qiskit/transpiler/__init__.py] [start of qiskit/visualization/transition_visualization.py] 1 # This code is part of Qiskit. 2 # 3 # (C) Copyright IBM 2017, 2018. 4 # 5 # This code is licensed under the Apache License, Version 2.0. You may 6 # obtain a copy of this license in the LICENSE.txt file in the root directory 7 # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. 8 # 9 # Any modifications or derivative works of this code must retain this 10 # copyright notice, and modified files need to carry a notice indicating 11 # that they have been altered from the originals. 12 13 """ 14 Visualization function for animation of state transitions by applying gates to single qubit. 15 """ 16 import sys 17 from math import sin, cos, acos, sqrt 18 import numpy as np 19 20 try: 21 import matplotlib 22 from matplotlib import pyplot as plt 23 from matplotlib import animation 24 from mpl_toolkits.mplot3d import Axes3D 25 from qiskit.visualization.bloch import Bloch 26 from qiskit.visualization.exceptions import VisualizationError 27 HAS_MATPLOTLIB = True 28 except ImportError: 29 HAS_MATPLOTLIB = False 30 31 try: 32 from IPython.display import HTML 33 HAS_IPYTHON = True 34 except ImportError: 35 HAS_IPYTHON = False 36 37 38 def _normalize(v, tolerance=0.00001): 39 """Makes sure magnitude of the vector is 1 with given tolerance""" 40 41 mag2 = sum(n * n for n in v) 42 if abs(mag2 - 1.0) > tolerance: 43 mag = sqrt(mag2) 44 v = tuple(n / mag for n in v) 45 return np.array(v) 46 47 48 class _Quaternion: 49 """For calculating vectors on unit sphere""" 50 def __init__(self): 51 self._val = None 52 53 @staticmethod 54 def from_axisangle(theta, v): 55 """Create quaternion from axis""" 56 v = _normalize(v) 57 58 new_quaternion = _Quaternion() 59 new_quaternion._axisangle_to_q(theta, v) 60 return new_quaternion 61 62 @staticmethod 63 def from_value(value): 64 """Create quaternion from vector""" 65 new_quaternion = _Quaternion() 66 new_quaternion._val = value 67 return new_quaternion 68 69 def _axisangle_to_q(self, theta, v): 70 """Convert axis and angle to quaternion""" 71 x = v[0] 72 y = v[1] 73 z = v[2] 74 75 w = cos(theta/2.) 76 x = x * sin(theta/2.) 77 y = y * sin(theta/2.) 78 z = z * sin(theta/2.) 79 80 self._val = np.array([w, x, y, z]) 81 82 def __mul__(self, b): 83 """Multiplication of quaternion with quaternion or vector""" 84 85 if isinstance(b, _Quaternion): 86 return self._multiply_with_quaternion(b) 87 elif isinstance(b, (list, tuple, np.ndarray)): 88 if len(b) != 3: 89 raise Exception("Input vector has invalid length {0}".format(len(b))) 90 return self._multiply_with_vector(b) 91 else: 92 raise Exception("Multiplication with unknown type {0}".format(type(b))) 93 94 def _multiply_with_quaternion(self, q_2): 95 """Multiplication of quaternion with quaternion""" 96 w_1, x_1, y_1, z_1 = self._val 97 w_2, x_2, y_2, z_2 = q_2._val 98 w = w_1 * w_2 - x_1 * x_2 - y_1 * y_2 - z_1 * z_2 99 x = w_1 * x_2 + x_1 * w_2 + y_1 * z_2 - z_1 * y_2 100 y = w_1 * y_2 + y_1 * w_2 + z_1 * x_2 - x_1 * z_2 101 z = w_1 * z_2 + z_1 * w_2 + x_1 * y_2 - y_1 * x_2 102 103 result = _Quaternion.from_value(np.array((w, x, y, z))) 104 return result 105 106 def _multiply_with_vector(self, v): 107 """Multiplication of quaternion with vector""" 108 q_2 = _Quaternion.from_value(np.append((0.0), v)) 109 return (self * q_2 * self.get_conjugate())._val[1:] 110 111 def get_conjugate(self): 112 """Conjugation of quaternion""" 113 w, x, y, z = self._val 114 result = _Quaternion.from_value(np.array((w, -x, -y, -z))) 115 return result 116 117 def __repr__(self): 118 theta, v = self.get_axisangle() 119 return "(({0}; {1}, {2}, {3}))".format(theta, v[0], v[1], v[2]) 120 121 def get_axisangle(self): 122 """Returns angle and vector of quaternion""" 123 w, v = self._val[0], self._val[1:] 124 theta = acos(w) * 2.0 125 126 return theta, _normalize(v) 127 128 def tolist(self): 129 """Converts quaternion to a list""" 130 return self._val.tolist() 131 132 def vector_norm(self): 133 """Calculates norm of quaternion""" 134 _, v = self.get_axisangle() 135 return np.linalg.norm(v) 136 137 138 def visualize_transition(circuit, 139 trace=False, 140 saveas=None, 141 fpg=100, 142 spg=2): 143 """ 144 Creates animation showing transitions between states of a single 145 qubit by applying quantum gates. 146 147 Args: 148 circuit (QuantumCircuit): Qiskit single-qubit QuantumCircuit. Gates supported are 149 h,x, y, z, rx, ry, rz, s, sdg, t, tdg and u1. 150 trace (bool): Controls whether to display tracing vectors - history of 10 past vectors 151 at each step of the animation. 152 saveas (str): User can choose to save the animation as a video to their filesystem. 153 This argument is a string of path with filename and extension (e.g. "movie.mp4" to 154 save the video in current working directory). 155 fpg (int): Frames per gate. Finer control over animation smoothness and computiational 156 needs to render the animation. Works well for tkinter GUI as it is, for jupyter GUI 157 it might be preferable to choose fpg between 5-30. 158 spg (int): Seconds per gate. How many seconds should animation of individual gate 159 transitions take. 160 161 Returns: 162 IPython.core.display.HTML: 163 If arg jupyter is set to True. Otherwise opens tkinter GUI and returns 164 after the GUI is closed. 165 166 Raises: 167 ImportError: Must have Matplotlib (and/or IPython) installed. 168 VisualizationError: Given gate(s) are not supported. 169 170 """ 171 jupyter = False 172 if ('ipykernel' in sys.modules) and ('spyder' not in sys.modules): 173 jupyter = True 174 175 if not HAS_MATPLOTLIB: 176 raise ImportError("Must have Matplotlib installed.") 177 if not HAS_IPYTHON and jupyter is True: 178 raise ImportError("Must have IPython installed.") 179 if len(circuit.qubits) != 1: 180 raise VisualizationError("Only one qubit circuits are supported") 181 182 frames_per_gate = fpg 183 time_between_frames = (spg*1000)/fpg 184 185 # quaternions of gates which don't take parameters 186 gates = dict() 187 gates['x'] = ('x', _Quaternion.from_axisangle(np.pi / frames_per_gate, [1, 0, 0]), '#1abc9c') 188 gates['y'] = ('y', _Quaternion.from_axisangle(np.pi / frames_per_gate, [0, 1, 0]), '#2ecc71') 189 gates['z'] = ('z', _Quaternion.from_axisangle(np.pi / frames_per_gate, [0, 0, 1]), '#3498db') 190 gates['s'] = ('s', _Quaternion.from_axisangle(np.pi / 2 / frames_per_gate, 191 [0, 0, 1]), '#9b59b6') 192 gates['sdg'] = ('sdg', _Quaternion.from_axisangle(-np.pi / 2 / frames_per_gate, [0, 0, 1]), 193 '#8e44ad') 194 gates['h'] = ('h', _Quaternion.from_axisangle(np.pi / frames_per_gate, _normalize([1, 0, 1])), 195 '#34495e') 196 gates['t'] = ('t', _Quaternion.from_axisangle(np.pi / 4 / frames_per_gate, [0, 0, 1]), 197 '#e74c3c') 198 gates['tdg'] = ('tdg', _Quaternion.from_axisangle(-np.pi / 4 / frames_per_gate, [0, 0, 1]), 199 '#c0392b') 200 201 implemented_gates = ['h', 'x', 'y', 'z', 'rx', 'ry', 'rz', 's', 'sdg', 't', 'tdg', 'u1'] 202 simple_gates = ['h', 'x', 'y', 'z', 's', 'sdg', 't', 'tdg'] 203 list_of_circuit_gates = [] 204 205 for gate in circuit._data: 206 if gate[0].name not in implemented_gates: 207 raise VisualizationError("Gate {0} is not supported".format(gate[0].name)) 208 if gate[0].name in simple_gates: 209 list_of_circuit_gates.append(gates[gate[0].name]) 210 else: 211 theta = gate[0].params[0] 212 rad = np.deg2rad(theta) 213 if gate[0].name == 'rx': 214 quaternion = _Quaternion.from_axisangle(rad / frames_per_gate, [1, 0, 0]) 215 list_of_circuit_gates.append(('rx:'+str(theta), quaternion, '#16a085')) 216 elif gate[0].name == 'ry': 217 quaternion = _Quaternion.from_axisangle(rad / frames_per_gate, [0, 1, 0]) 218 list_of_circuit_gates.append(('ry:'+str(theta), quaternion, '#27ae60')) 219 elif gate[0].name == 'rz': 220 quaternion = _Quaternion.from_axisangle(rad / frames_per_gate, [0, 0, 1]) 221 list_of_circuit_gates.append(('rz:'+str(theta), quaternion, '#2980b9')) 222 elif gate[0].name == 'u1': 223 quaternion = _Quaternion.from_axisangle(rad / frames_per_gate, [0, 0, 1]) 224 list_of_circuit_gates.append(('u1:'+str(theta), quaternion, '#f1c40f')) 225 226 if len(list_of_circuit_gates) == 0: 227 raise VisualizationError("Nothing to visualize.") 228 229 starting_pos = _normalize(np.array([0, 0, 1])) 230 231 fig = plt.figure(figsize=(5, 5)) 232 _ax = Axes3D(fig) 233 _ax.set_xlim(-10, 10) 234 _ax.set_ylim(-10, 10) 235 sphere = Bloch(axes=_ax) 236 237 class Namespace: 238 """Helper class serving as scope container""" 239 def __init__(self): 240 self.new_vec = [] 241 self.last_gate = -2 242 self.colors = [] 243 self.pnts = [] 244 245 namespace = Namespace() 246 namespace.new_vec = starting_pos 247 248 def animate(i): 249 sphere.clear() 250 251 # starting gate count from -1 which is the initial vector 252 gate_counter = (i-1) // frames_per_gate 253 if gate_counter != namespace.last_gate: 254 namespace.pnts.append([[], [], []]) 255 namespace.colors.append(list_of_circuit_gates[gate_counter][2]) 256 257 # starts with default vector [0,0,1] 258 if i == 0: 259 sphere.add_vectors(namespace.new_vec) 260 namespace.pnts[0][0].append(namespace.new_vec[0]) 261 namespace.pnts[0][1].append(namespace.new_vec[1]) 262 namespace.pnts[0][2].append(namespace.new_vec[2]) 263 namespace.colors[0] = 'r' 264 sphere.make_sphere() 265 return _ax 266 267 namespace.new_vec = list_of_circuit_gates[gate_counter][1] * namespace.new_vec 268 269 namespace.pnts[gate_counter+1][0].append(namespace.new_vec[0]) 270 namespace.pnts[gate_counter+1][1].append(namespace.new_vec[1]) 271 namespace.pnts[gate_counter+1][2].append(namespace.new_vec[2]) 272 273 sphere.add_vectors(namespace.new_vec) 274 if trace: 275 # sphere.add_vectors(namespace.points) 276 for point_set in namespace.pnts: 277 sphere.add_points([point_set[0], point_set[1], point_set[2]]) 278 279 sphere.vector_color = [list_of_circuit_gates[gate_counter][2]] 280 sphere.point_color = namespace.colors 281 sphere.point_marker = 'o' 282 283 annotation_text = list_of_circuit_gates[gate_counter][0] 284 annotationvector = [1.4, -0.45, 1.7] 285 sphere.add_annotation(annotationvector, 286 annotation_text, 287 color=list_of_circuit_gates[gate_counter][2], 288 fontsize=30, 289 horizontalalignment='left') 290 291 sphere.make_sphere() 292 293 namespace.last_gate = gate_counter 294 return _ax 295 296 def init(): 297 sphere.vector_color = ['r'] 298 return _ax 299 300 ani = animation.FuncAnimation(fig, 301 animate, 302 range(frames_per_gate * len(list_of_circuit_gates)+1), 303 init_func=init, 304 blit=False, 305 repeat=False, 306 interval=time_between_frames) 307 308 if saveas: 309 ani.save(saveas, fps=30) 310 if jupyter: 311 # This is necessary to overcome matplotlib memory limit 312 matplotlib.rcParams['animation.embed_limit'] = 50 313 return HTML(ani.to_jshtml()) 314 plt.show() 315 plt.close(fig) 316 return None 317 [end of qiskit/visualization/transition_visualization.py] </code> I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format. <patch> --- a/file.py +++ b/file.py @@ -1,27 +1,35 @@ def euclidean(a, b): - while b: - a, b = b, a % b - return a + if b == 0: + return a + return euclidean(b, a % b) def bresenham(x0, y0, x1, y1): points = [] dx = abs(x1 - x0) dy = abs(y1 - y0) - sx = 1 if x0 < x1 else -1 - sy = 1 if y0 < y1 else -1 - err = dx - dy + x, y = x0, y0 + sx = -1 if x0 > x1 else 1 + sy = -1 if y0 > y1 else 1 - while True: - points.append((x0, y0)) - if x0 == x1 and y0 == y1: - break - e2 = 2 * err - if e2 > -dy: + if dx > dy: + err = dx / 2.0 + while x != x1: + points.append((x, y)) err -= dy - x0 += sx - if e2 < dx: - err += dx - y0 += sy + if err < 0: + y += sy + err += dx + x += sx + else: + err = dy / 2.0 + while y != y1: + points.append((x, y)) + err -= dx + if err < 0: + x += sx + err += dy + y += sy + points.append((x, y)) return points </patch>
Qiskit/qiskit
aae6eab589915d948f89d1b131019282560df61a
`initialize` and `Statevector` don't play nicely <!-- ⚠️ If you do not respect this template, your issue will be closed --> <!-- ⚠️ Make sure to browse the opened and closed issues --> ### Informations - **Qiskit Aer version**: 0.5.1 - **Python version**: 3.7.3 - **Operating system**: OSX ### What is the current behavior? Using `initialize` in a circuit and then running with `Statevector` results in the error "Cannot apply Instruction: reset" ### Steps to reproduce the problem ``` import qiskit as qk import qiskit.quantum_info as qi from numpy import sqrt n = 2 ket0 = [1/sqrt(2),0,0,1/sqrt(2)] qc = qk.QuantumCircuit(n) qc.initialize(ket0,range(n)) ket_qi = qi.Statevector.from_instruction(qc) ```
Funny cause the circuit has no resets: ``` β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”Β» q_0: ─|0>─────────────────────────────── X β”œβ”€ U3(-pi/2,0,0) β”œβ”€ X β”œΒ» β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β””β”€β”¬β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”¬β”€β”˜Β» q_1: ─|0>── U3(pi/2,0,0) β”œβ”€ U3(0,0,0) β”œβ”€β”€β– β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β– β”€β”€Β» β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Β» Β« β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”β”Œβ”€β”€β”€β”β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” Β«q_0: ─ U3(pi/2,0,0) β”œβ”€ X β”œβ”€ U3(0,0,0) β”œβ”€ X β”œβ”€ U3(0,0,0) β”œ Β« β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”¬β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜β””β”€β”¬β”€β”˜β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ Β«q_1: ──────────────────■─────────────────■─────────────── Β« ``` That circuit has a lot of things I don't like, but at least it has no resets. @nonhermitian That circuit *does* have resets, notice the two |0> |0> at the start? The definition of initialize has reset instructions on all qubits that are removed by the transpiler if it is the first instruction in a circuit. This is so you can "initialize" subsets of qubits at any stage of a circuit. I'm transferring this to Qiskit Terra. In the future please post issues related to the Quantum info module in Terra, not Aer. That is not just the initial state of the qubits? That is what used to be there. It is hard to tell the difference here. So that means that initialize is no longer a unitary operation like it was before? I guess I missed that as well. A reset method was added to the Statevector class last release, so the simulation could be updated to work with initialize via adding support of reset to the the from_instruction method. @nonhermitian I think this was changed recently in the draw function. Now circuits are drawn without any initial states, so any time you see them they refer to reset instructions. Yeah, it is just that the original text drawing is very close to the reset instructions so it is hard for the user to understand.
2020-05-15T16:51:32Z
<patch> diff --git a/qiskit/quantum_info/states/densitymatrix.py b/qiskit/quantum_info/states/densitymatrix.py --- a/qiskit/quantum_info/states/densitymatrix.py +++ b/qiskit/quantum_info/states/densitymatrix.py @@ -547,12 +547,22 @@ def _evolve_operator(self, other, qargs=None): def _append_instruction(self, other, qargs=None): """Update the current Statevector by applying an instruction.""" + from qiskit.circuit.reset import Reset + from qiskit.circuit.barrier import Barrier # Try evolving by a matrix operator (unitary-like evolution) mat = Operator._instruction_to_matrix(other) if mat is not None: self._data = self._evolve_operator(Operator(mat), qargs=qargs).data return + + # Special instruction types + if isinstance(other, Reset): + self._data = self.reset(qargs)._data + return + if isinstance(other, Barrier): + return + # Otherwise try evolving by a Superoperator chan = SuperOp._instruction_to_superop(other) if chan is not None: diff --git a/qiskit/quantum_info/states/statevector.py b/qiskit/quantum_info/states/statevector.py --- a/qiskit/quantum_info/states/statevector.py +++ b/qiskit/quantum_info/states/statevector.py @@ -595,29 +595,40 @@ def _shape(self): def _append_instruction(self, obj, qargs=None): """Update the current Statevector by applying an instruction.""" + from qiskit.circuit.reset import Reset + from qiskit.circuit.barrier import Barrier + mat = Operator._instruction_to_matrix(obj) if mat is not None: # Perform the composition and inplace update the current state # of the operator - state = self.evolve(mat, qargs=qargs) - self._data = state.data - else: - # If the instruction doesn't have a matrix defined we use its - # circuit decomposition definition if it exists, otherwise we - # cannot compose this gate and raise an error. - if obj.definition is None: - raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) - for instr, qregs, cregs in obj.definition: - if cregs: - raise QiskitError( - 'Cannot apply instruction with classical registers: {}'.format( - instr.name)) - # Get the integer position of the flat register - if qargs is None: - new_qargs = [tup.index for tup in qregs] - else: - new_qargs = [qargs[tup.index] for tup in qregs] - self._append_instruction(instr, qargs=new_qargs) + self._data = self.evolve(mat, qargs=qargs).data + return + + # Special instruction types + if isinstance(obj, Reset): + self._data = self.reset(qargs)._data + return + if isinstance(obj, Barrier): + return + + # If the instruction doesn't have a matrix defined we use its + # circuit decomposition definition if it exists, otherwise we + # cannot compose this gate and raise an error. + if obj.definition is None: + raise QiskitError('Cannot apply Instruction: {}'.format(obj.name)) + + for instr, qregs, cregs in obj.definition: + if cregs: + raise QiskitError( + 'Cannot apply instruction with classical registers: {}'.format( + instr.name)) + # Get the integer position of the flat register + if qargs is None: + new_qargs = [tup.index for tup in qregs] + else: + new_qargs = [qargs[tup.index] for tup in qregs] + self._append_instruction(instr, qargs=new_qargs) def _evolve_instruction(self, obj, qargs=None): """Return a new statevector by applying an instruction.""" </patch>
[]
[]
ipython__ipython-10213
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
ipython/ipython
78ec96d7ca0147f0655d5260f2ab0c61d94e4279
"remove usage of backports.shutil_get_terminal_size\nThis is for pre-3.3 Python.\r\n\r\nPretty easy (...TRUNCATED)
2017-01-28T05:22:06Z
"<patch>\ndiff --git a/IPython/utils/terminal.py b/IPython/utils/terminal.py\n--- a/IPython/utils/te(...TRUNCATED)
[]
[]
Qiskit__qiskit-1295
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
Qiskit/qiskit
77dc51b93e7312bbff8f5acf7d8242232bd6624f
"credentials failed for qiskit ver 0.6.1\n<!-- ⚠️ If you do not respect this template, your issu(...TRUNCATED)
"Can you try enable_account or regenerating the token. Your code should work. If you type `IBMQ.stor(...TRUNCATED)
2018-11-19T08:27:15Z
"<patch>\ndiff --git a/qiskit/backends/ibmq/credentials/_configrc.py b/qiskit/backends/ibmq/credenti(...TRUNCATED)
[]
[]
docker__compose-6410
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
docker/compose
14e7a11b3c96f0ea818c8c28d84a1aff7967e579
"Upgrade `events` to use the new API fields\nIn API version 1.22 the events structure was updated to(...TRUNCATED)
"This upgrade may also allow us to handle image events. Since we won't need to inspect every event, (...TRUNCATED)
2018-12-11T01:55:02Z
"<patch>\ndiff --git a/compose/cli/log_printer.py b/compose/cli/log_printer.py\n--- a/compose/cli/lo(...TRUNCATED)
[]
[]
ytdl-org__youtube-dl-1591
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
ytdl-org/youtube-dl
b4cdc245cf0af0672207a5090cb6eb6c29606cdb
"Opus audio conversion failure\nWhen trying to extract and convert audio from a youtube video into a(...TRUNCATED)
"I had the same issue and after an hour-long debug session with a friend of mine we found out that t(...TRUNCATED)
2013-10-12T11:32:27Z
"<patch>\ndiff --git a/youtube_dl/PostProcessor.py b/youtube_dl/PostProcessor.py\n--- a/youtube_dl/P(...TRUNCATED)
[]
[]
numpy__numpy-13703
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
numpy/numpy
40ada70d9efc903097b2ff3f968c23a7e2f14296
"Dtype.base attribute not documented\ndtype instances have a `base` attribute that, I think, is mean(...TRUNCATED)
"I've found myself using `.subdtype` instead, which contains the same info\nI think base also means (...TRUNCATED)
2019-06-03T20:15:13Z
"<patch>\ndiff --git a/numpy/core/_add_newdocs.py b/numpy/core/_add_newdocs.py\n--- a/numpy/core/_ad(...TRUNCATED)
[]
[]
wagtail__wagtail-7855
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
wagtail/wagtail
4550bba562286992b27e667b071451e6886fbf44
"Use html_url in alias_of API serialisation\nAs per https://github.com/wagtail/wagtail/pull/7669#iss(...TRUNCATED)
2022-01-13T15:50:23Z
"<patch>\ndiff --git a/wagtail/api/v2/serializers.py b/wagtail/api/v2/serializers.py\n--- a/wagtail/(...TRUNCATED)
[]
[]
pandas-dev__pandas-27237
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
pandas-dev/pandas
f683473a156f032a64a1d7edcebde21c42a8702d
"Add key to sorting functions\nMany python functions (sorting, max/min) accept a key argument, perh(...TRUNCATED)
"Here's a specific use case that came up on [StackOverflow](http://stackoverflow.com/questions/29580(...TRUNCATED)
2019-07-04T23:04:26Z
"<patch>\ndiff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst\n--- a/do(...TRUNCATED)
[]
[]
conan-io__conan-3187
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
conan-io/conan
c3baafb780b6e5498f8bd460426901d9d5ab10e1
"Using \"?\" in a tools.get() URL will fail, while using it in a tools.download() will succeed.\nTo (...TRUNCATED)
"Verified: ``tools.get()`` uses the last part of the URL as the name of the file to be saved.\r\n\r\(...TRUNCATED)
2018-07-10T10:30:23Z
"<patch>\ndiff --git a/conans/client/tools/net.py b/conans/client/tools/net.py\n--- a/conans/client/(...TRUNCATED)
[]
[]
googleapis__google-cloud-python-3348
"You will be provided with a partial code base and an issue statement explaining a problem to resolv(...TRUNCATED)
googleapis/google-cloud-python
520637c245d461db8ee45ba466d763036b82ea42
Error reporting system tests needed Follow up to #3263.
2017-05-01T22:40:28Z
"<patch>\ndiff --git a/error_reporting/nox.py b/error_reporting/nox.py\n--- a/error_reporting/nox.py(...TRUNCATED)
[]
[]

Dataset Card for "SWE-bench_bm25_40K"

Dataset Summary

SWE-bench is a dataset that tests systems’ ability to solve GitHub issues automatically. The dataset collects 2,294 Issue-Pull Request pairs from 12 popular Python. Evaluation is performed by unit test verification using post-PR behavior as the reference solution.

The dataset was released as part of SWE-bench: Can Language Models Resolve Real-World GitHub Issues?

This dataset SWE-bench_bm25_40K includes a formatting of each instance using Pyserini's BM25 retrieval as described in the paper. The code context size limit is 40,000 cl100k_base tokens from the tiktoken tokenization package used for OpenAI models. The text column can be used directly with LMs to generate patch files. Models are instructed to generate patch formatted file using the following template:

<patch>
diff
--- a/path/to/file.py
--- b/path/to/file.py
@@ -1,3 +1,3 @@
 This is a test file.
-It contains several lines.
+It has been modified.
 This is the third line.
</patch>

This format can be used directly with the SWE-bench inference scripts. Please refer to these scripts for more details on inference.

Supported Tasks and Leaderboards

SWE-bench proposes a new task: issue resolution provided a full repository and GitHub issue. The leaderboard can be found at www.swebench.com

Languages

The text of the dataset is primarily English, but we make no effort to filter or otherwise clean based on language type.

Dataset Structure

Data Instances

An example of a SWE-bench datum is as follows:

instance_id: (str) - A formatted instance identifier, usually as repo_owner__repo_name-PR-number.
text: (str) - The input text including instructions, the "Oracle" retrieved file, and an example of the patch format for output.
patch: (str) - The gold patch, the patch generated by the PR (minus test-related code), that resolved the issue.
repo: (str) - The repository owner/name identifier from GitHub.
base_commit: (str) - The commit hash of the repository representing the HEAD of the repository before the solution PR is applied.
hints_text: (str) - Comments made on the issue prior to the creation of the solution PR’s first commit creation date.
created_at: (str) - The creation date of the pull request.
test_patch: (str) - A test-file patch that was contributed by the solution PR.
problem_statement: (str) - The issue title and body.
version: (str) - Installation version to use for running evaluation.
environment_setup_commit: (str) - commit hash to use for environment setup and installation.
FAIL_TO_PASS: (str) - A json list of strings that represent the set of tests resolved by the PR and tied to the issue resolution.
PASS_TO_PASS: (str) - A json list of strings that represent tests that should pass before and after the PR application.

More Information needed

Downloads last month
5
Edit dataset card