instance_id
stringlengths
13
37
text
stringlengths
3.08k
667k
repo
stringclasses
35 values
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/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] </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_27K"

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_27K includes a formatting of each instance using Pyserini's BM25 retrieval as described in the paper. The code context size limit is 27,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
73