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/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/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 resolve.
<issue>
remove usage of backports.shutil_get_terminal_size
This is for pre-3.3 Python.
Pretty easy it should only require deleting lines.
Maybe a few need to be dedented.
</issue>
<code>
[start of README.rst]
1 .. image:: https://codecov.io/github/ipython/ipython/coverage.svg?branch=master
2 :target: https://codecov.io/github/ipython/ipython?branch=master
3
4 .. image:: https://img.shields.io/pypi/dm/IPython.svg
5 :target: https://pypi.python.org/pypi/ipython
6
7 .. image:: https://img.shields.io/pypi/v/IPython.svg
8 :target: https://pypi.python.org/pypi/ipython
9
10 .. image:: https://img.shields.io/travis/ipython/ipython.svg
11 :target: https://travis-ci.org/ipython/ipython
12
13
14 ===========================================
15 IPython: Productive Interactive Computing
16 ===========================================
17
18 Overview
19 ========
20
21 Welcome to IPython. Our full documentation is available on `ipython.readthedocs.io
22 <https://ipython.readthedocs.io/en/stable/>`_ and contains information on how to install, use and
23 contribute to the project.
24
25 Officially, IPython requires Python version 3.3 and above.
26 IPython 5.x is the last IPython version to support Python 2.7.
27
28 The Notebook, Qt console and a number of other pieces are now parts of *Jupyter*.
29 See the `Jupyter installation docs <http://jupyter.readthedocs.io/en/latest/install.html>`__
30 if you want to use these.
31
32
33
34
35 Development and Instant running
36 ===============================
37
38 You can find the latest version of the development documentation on `readthedocs
39 <http://ipython.readthedocs.io/en/latest/>`_.
40
41 You can run IPython from this directory without even installing it system-wide
42 by typing at the terminal::
43
44 $ python -m IPython
45
46 Or see the `development installation docs
47 <http://ipython.readthedocs.io/en/latest/install/install.html#installing-the-development-version>`_
48 for the latest revision on read the docs.
49
50 Documentation and installation instructions for older version of IPython can be
51 found on the `IPython website <http://ipython.org/documentation.html>`_
52
53
54
55 IPython requires Python version 3 or above
56 ==========================================
57
58 Starting with version 6.0, IPython does not support Python 2.7, 3.0, 3.1, or
59 3.2.
60
61 For a version compatible with Python 2.7, please install the 5.x LTS Long Term
62 Support version.
63
64 If you are encountering this error message you are likely trying to install or
65 use IPython from source. You need to checkout the remote 5.x branch. If you are
66 using git the following should work:
67
68 $ git fetch origin
69 $ git checkout -b origin/5.x
70
71 If you encounter this error message with a regular install of IPython, then you
72 likely need to update your package manager, for example if you are using `pip`
73 check the version of pip with
74
75 $ pip --version
76
77 You will need to update pip to the version 8.2 or greater. If you are not using
78 pip, please inquiry with the maintainers of the package for your package
79 manager.
80
81 For more information see one of our blog posts:
82
83 http://blog.jupyter.org/2016/07/08/ipython-5-0-released/
84
85 As well as the following Pull-Request for discussion:
86
87 https://github.com/ipython/ipython/pull/9900
88
[end of README.rst]
[start of IPython/core/magics/basic.py]
1 """Implementation of basic magic functions."""
2
3
4 import argparse
5 import io
6 import sys
7 from pprint import pformat
8
9 from IPython.core import magic_arguments, page
10 from IPython.core.error import UsageError
11 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.utils.ipstruct import Struct
15 from warnings import warn
16 from logging import error
17
18
19 class MagicsDisplay(object):
20 def __init__(self, magics_manager):
21 self.magics_manager = magics_manager
22
23 def _lsmagic(self):
24 """The main implementation of the %lsmagic"""
25 mesc = magic_escapes['line']
26 cesc = magic_escapes['cell']
27 mman = self.magics_manager
28 magics = mman.lsmagic()
29 out = ['Available line magics:',
30 mesc + (' '+mesc).join(sorted(magics['line'])),
31 '',
32 'Available cell magics:',
33 cesc + (' '+cesc).join(sorted(magics['cell'])),
34 '',
35 mman.auto_status()]
36 return '\n'.join(out)
37
38 def _repr_pretty_(self, p, cycle):
39 p.text(self._lsmagic())
40
41 def __str__(self):
42 return self._lsmagic()
43
44 def _jsonable(self):
45 """turn magics dict into jsonable dict of the same structure
46
47 replaces object instances with their class names as strings
48 """
49 magic_dict = {}
50 mman = self.magics_manager
51 magics = mman.lsmagic()
52 for key, subdict in magics.items():
53 d = {}
54 magic_dict[key] = d
55 for name, obj in subdict.items():
56 try:
57 classname = obj.__self__.__class__.__name__
58 except AttributeError:
59 classname = 'Other'
60
61 d[name] = classname
62 return magic_dict
63
64 def _repr_json_(self):
65 return self._jsonable()
66
67
68 @magics_class
69 class BasicMagics(Magics):
70 """Magics that provide central IPython functionality.
71
72 These are various magics that don't fit into specific categories but that
73 are all part of the base 'IPython experience'."""
74
75 @magic_arguments.magic_arguments()
76 @magic_arguments.argument(
77 '-l', '--line', action='store_true',
78 help="""Create a line magic alias."""
79 )
80 @magic_arguments.argument(
81 '-c', '--cell', action='store_true',
82 help="""Create a cell magic alias."""
83 )
84 @magic_arguments.argument(
85 'name',
86 help="""Name of the magic to be created."""
87 )
88 @magic_arguments.argument(
89 'target',
90 help="""Name of the existing line or cell magic."""
91 )
92 @line_magic
93 def alias_magic(self, line=''):
94 """Create an alias for an existing line or cell magic.
95
96 Examples
97 --------
98 ::
99
100 In [1]: %alias_magic t timeit
101 Created `%t` as an alias for `%timeit`.
102 Created `%%t` as an alias for `%%timeit`.
103
104 In [2]: %t -n1 pass
105 1 loops, best of 3: 954 ns per loop
106
107 In [3]: %%t -n1
108 ...: pass
109 ...:
110 1 loops, best of 3: 954 ns per loop
111
112 In [4]: %alias_magic --cell whereami pwd
113 UsageError: Cell magic function `%%pwd` not found.
114 In [5]: %alias_magic --line whereami pwd
115 Created `%whereami` as an alias for `%pwd`.
116
117 In [6]: %whereami
118 Out[6]: u'/home/testuser'
119 """
120 args = magic_arguments.parse_argstring(self.alias_magic, line)
121 shell = self.shell
122 mman = self.shell.magics_manager
123 escs = ''.join(magic_escapes.values())
124
125 target = args.target.lstrip(escs)
126 name = args.name.lstrip(escs)
127
128 # Find the requested magics.
129 m_line = shell.find_magic(target, 'line')
130 m_cell = shell.find_magic(target, 'cell')
131 if args.line and m_line is None:
132 raise UsageError('Line magic function `%s%s` not found.' %
133 (magic_escapes['line'], target))
134 if args.cell and m_cell is None:
135 raise UsageError('Cell magic function `%s%s` not found.' %
136 (magic_escapes['cell'], target))
137
138 # If --line and --cell are not specified, default to the ones
139 # that are available.
140 if not args.line and not args.cell:
141 if not m_line and not m_cell:
142 raise UsageError(
143 'No line or cell magic with name `%s` found.' % target
144 )
145 args.line = bool(m_line)
146 args.cell = bool(m_cell)
147
148 if args.line:
149 mman.register_alias(name, target, 'line')
150 print('Created `%s%s` as an alias for `%s%s`.' % (
151 magic_escapes['line'], name,
152 magic_escapes['line'], target))
153
154 if args.cell:
155 mman.register_alias(name, target, 'cell')
156 print('Created `%s%s` as an alias for `%s%s`.' % (
157 magic_escapes['cell'], name,
158 magic_escapes['cell'], target))
159
160 @line_magic
161 def lsmagic(self, parameter_s=''):
162 """List currently available magic functions."""
163 return MagicsDisplay(self.shell.magics_manager)
164
165 def _magic_docs(self, brief=False, rest=False):
166 """Return docstrings from magic functions."""
167 mman = self.shell.magics_manager
168 docs = mman.lsmagic_docs(brief, missing='No documentation')
169
170 if rest:
171 format_string = '**%s%s**::\n\n%s\n\n'
172 else:
173 format_string = '%s%s:\n%s\n'
174
175 return ''.join(
176 [format_string % (magic_escapes['line'], fname,
177 indent(dedent(fndoc)))
178 for fname, fndoc in sorted(docs['line'].items())]
179 +
180 [format_string % (magic_escapes['cell'], fname,
181 indent(dedent(fndoc)))
182 for fname, fndoc in sorted(docs['cell'].items())]
183 )
184
185 @line_magic
186 def magic(self, parameter_s=''):
187 """Print information about the magic function system.
188
189 Supported formats: -latex, -brief, -rest
190 """
191
192 mode = ''
193 try:
194 mode = parameter_s.split()[0][1:]
195 except IndexError:
196 pass
197
198 brief = (mode == 'brief')
199 rest = (mode == 'rest')
200 magic_docs = self._magic_docs(brief, rest)
201
202 if mode == 'latex':
203 print(self.format_latex(magic_docs))
204 return
205 else:
206 magic_docs = format_screen(magic_docs)
207
208 out = ["""
209 IPython's 'magic' functions
210 ===========================
211
212 The magic function system provides a series of functions which allow you to
213 control the behavior of IPython itself, plus a lot of system-type
214 features. There are two kinds of magics, line-oriented and cell-oriented.
215
216 Line magics are prefixed with the % character and work much like OS
217 command-line calls: they get as an argument the rest of the line, where
218 arguments are passed without parentheses or quotes. For example, this will
219 time the given statement::
220
221 %timeit range(1000)
222
223 Cell magics are prefixed with a double %%, and they are functions that get as
224 an argument not only the rest of the line, but also the lines below it in a
225 separate argument. These magics are called with two arguments: the rest of the
226 call line and the body of the cell, consisting of the lines below the first.
227 For example::
228
229 %%timeit x = numpy.random.randn((100, 100))
230 numpy.linalg.svd(x)
231
232 will time the execution of the numpy svd routine, running the assignment of x
233 as part of the setup phase, which is not timed.
234
235 In a line-oriented client (the terminal or Qt console IPython), starting a new
236 input with %% will automatically enter cell mode, and IPython will continue
237 reading input until a blank line is given. In the notebook, simply type the
238 whole cell as one entity, but keep in mind that the %% escape can only be at
239 the very start of the cell.
240
241 NOTE: If you have 'automagic' enabled (via the command line option or with the
242 %automagic function), you don't need to type in the % explicitly for line
243 magics; cell magics always require an explicit '%%' escape. By default,
244 IPython ships with automagic on, so you should only rarely need the % escape.
245
246 Example: typing '%cd mydir' (without the quotes) changes your working directory
247 to 'mydir', if it exists.
248
249 For a list of the available magic functions, use %lsmagic. For a description
250 of any of them, type %magic_name?, e.g. '%cd?'.
251
252 Currently the magic system has the following functions:""",
253 magic_docs,
254 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
255 str(self.lsmagic()),
256 ]
257 page.page('\n'.join(out))
258
259
260 @line_magic
261 def page(self, parameter_s=''):
262 """Pretty print the object and display it through a pager.
263
264 %page [options] OBJECT
265
266 If no object is given, use _ (last output).
267
268 Options:
269
270 -r: page str(object), don't pretty-print it."""
271
272 # After a function contributed by Olivier Aubert, slightly modified.
273
274 # Process options/args
275 opts, args = self.parse_options(parameter_s, 'r')
276 raw = 'r' in opts
277
278 oname = args and args or '_'
279 info = self.shell._ofind(oname)
280 if info['found']:
281 txt = (raw and str or pformat)( info['obj'] )
282 page.page(txt)
283 else:
284 print('Object `%s` not found' % oname)
285
286 @line_magic
287 def profile(self, parameter_s=''):
288 """Print your currently active IPython profile.
289
290 See Also
291 --------
292 prun : run code using the Python profiler
293 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
294 """
295 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
296 from IPython.core.application import BaseIPythonApplication
297 if BaseIPythonApplication.initialized():
298 print(BaseIPythonApplication.instance().profile)
299 else:
300 error("profile is an application-level value, but you don't appear to be in an IPython application")
301
302 @line_magic
303 def pprint(self, parameter_s=''):
304 """Toggle pretty printing on/off."""
305 ptformatter = self.shell.display_formatter.formatters['text/plain']
306 ptformatter.pprint = bool(1 - ptformatter.pprint)
307 print('Pretty printing has been turned',
308 ['OFF','ON'][ptformatter.pprint])
309
310 @line_magic
311 def colors(self, parameter_s=''):
312 """Switch color scheme for prompts, info system and exception handlers.
313
314 Currently implemented schemes: NoColor, Linux, LightBG.
315
316 Color scheme names are not case-sensitive.
317
318 Examples
319 --------
320 To get a plain black and white terminal::
321
322 %colors nocolor
323 """
324 def color_switch_err(name):
325 warn('Error changing %s color schemes.\n%s' %
326 (name, sys.exc_info()[1]), stacklevel=2)
327
328
329 new_scheme = parameter_s.strip()
330 if not new_scheme:
331 raise UsageError(
332 "%colors: you must specify a color scheme. See '%colors?'")
333 # local shortcut
334 shell = self.shell
335
336 # Set shell colour scheme
337 try:
338 shell.colors = new_scheme
339 shell.refresh_style()
340 except:
341 color_switch_err('shell')
342
343 # Set exception colors
344 try:
345 shell.InteractiveTB.set_colors(scheme = new_scheme)
346 shell.SyntaxTB.set_colors(scheme = new_scheme)
347 except:
348 color_switch_err('exception')
349
350 # Set info (for 'object?') colors
351 if shell.color_info:
352 try:
353 shell.inspector.set_active_scheme(new_scheme)
354 except:
355 color_switch_err('object inspector')
356 else:
357 shell.inspector.set_active_scheme('NoColor')
358
359 @line_magic
360 def xmode(self, parameter_s=''):
361 """Switch modes for the exception handlers.
362
363 Valid modes: Plain, Context and Verbose.
364
365 If called without arguments, acts as a toggle."""
366
367 def xmode_switch_err(name):
368 warn('Error changing %s exception modes.\n%s' %
369 (name,sys.exc_info()[1]))
370
371 shell = self.shell
372 new_mode = parameter_s.strip().capitalize()
373 try:
374 shell.InteractiveTB.set_mode(mode=new_mode)
375 print('Exception reporting mode:',shell.InteractiveTB.mode)
376 except:
377 xmode_switch_err('user')
378
379 @line_magic
380 def quickref(self,arg):
381 """ Show a quick reference sheet """
382 from IPython.core.usage import quick_reference
383 qr = quick_reference + self._magic_docs(brief=True)
384 page.page(qr)
385
386 @line_magic
387 def doctest_mode(self, parameter_s=''):
388 """Toggle doctest mode on and off.
389
390 This mode is intended to make IPython behave as much as possible like a
391 plain Python shell, from the perspective of how its prompts, exceptions
392 and output look. This makes it easy to copy and paste parts of a
393 session into doctests. It does so by:
394
395 - Changing the prompts to the classic ``>>>`` ones.
396 - Changing the exception reporting mode to 'Plain'.
397 - Disabling pretty-printing of output.
398
399 Note that IPython also supports the pasting of code snippets that have
400 leading '>>>' and '...' prompts in them. This means that you can paste
401 doctests from files or docstrings (even if they have leading
402 whitespace), and the code will execute correctly. You can then use
403 '%history -t' to see the translated history; this will give you the
404 input after removal of all the leading prompts and whitespace, which
405 can be pasted back into an editor.
406
407 With these features, you can switch into this mode easily whenever you
408 need to do testing and changes to doctests, without having to leave
409 your existing IPython session.
410 """
411
412 # Shorthands
413 shell = self.shell
414 meta = shell.meta
415 disp_formatter = self.shell.display_formatter
416 ptformatter = disp_formatter.formatters['text/plain']
417 # dstore is a data store kept in the instance metadata bag to track any
418 # changes we make, so we can undo them later.
419 dstore = meta.setdefault('doctest_mode',Struct())
420 save_dstore = dstore.setdefault
421
422 # save a few values we'll need to recover later
423 mode = save_dstore('mode',False)
424 save_dstore('rc_pprint',ptformatter.pprint)
425 save_dstore('xmode',shell.InteractiveTB.mode)
426 save_dstore('rc_separate_out',shell.separate_out)
427 save_dstore('rc_separate_out2',shell.separate_out2)
428 save_dstore('rc_separate_in',shell.separate_in)
429 save_dstore('rc_active_types',disp_formatter.active_types)
430
431 if not mode:
432 # turn on
433
434 # Prompt separators like plain python
435 shell.separate_in = ''
436 shell.separate_out = ''
437 shell.separate_out2 = ''
438
439
440 ptformatter.pprint = False
441 disp_formatter.active_types = ['text/plain']
442
443 shell.magic('xmode Plain')
444 else:
445 # turn off
446 shell.separate_in = dstore.rc_separate_in
447
448 shell.separate_out = dstore.rc_separate_out
449 shell.separate_out2 = dstore.rc_separate_out2
450
451 ptformatter.pprint = dstore.rc_pprint
452 disp_formatter.active_types = dstore.rc_active_types
453
454 shell.magic('xmode ' + dstore.xmode)
455
456 # mode here is the state before we switch; switch_doctest_mode takes
457 # the mode we're switching to.
458 shell.switch_doctest_mode(not mode)
459
460 # Store new mode and inform
461 dstore.mode = bool(not mode)
462 mode_label = ['OFF','ON'][dstore.mode]
463 print('Doctest mode is:', mode_label)
464
465 @line_magic
466 def gui(self, parameter_s=''):
467 """Enable or disable IPython GUI event loop integration.
468
469 %gui [GUINAME]
470
471 This magic replaces IPython's threaded shells that were activated
472 using the (pylab/wthread/etc.) command line flags. GUI toolkits
473 can now be enabled at runtime and keyboard
474 interrupts should work without any problems. The following toolkits
475 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
476
477 %gui wx # enable wxPython event loop integration
478 %gui qt4|qt # enable PyQt4 event loop integration
479 %gui qt5 # enable PyQt5 event loop integration
480 %gui gtk # enable PyGTK event loop integration
481 %gui gtk3 # enable Gtk3 event loop integration
482 %gui tk # enable Tk event loop integration
483 %gui osx # enable Cocoa event loop integration
484 # (requires %matplotlib 1.1)
485 %gui # disable all event loop integration
486
487 WARNING: after any of these has been called you can simply create
488 an application object, but DO NOT start the event loop yourself, as
489 we have already handled that.
490 """
491 opts, arg = self.parse_options(parameter_s, '')
492 if arg=='': arg = None
493 try:
494 return self.shell.enable_gui(arg)
495 except Exception as e:
496 # print simple error message, rather than traceback if we can't
497 # hook up the GUI
498 error(str(e))
499
500 @skip_doctest
501 @line_magic
502 def precision(self, s=''):
503 """Set floating point precision for pretty printing.
504
505 Can set either integer precision or a format string.
506
507 If numpy has been imported and precision is an int,
508 numpy display precision will also be set, via ``numpy.set_printoptions``.
509
510 If no argument is given, defaults will be restored.
511
512 Examples
513 --------
514 ::
515
516 In [1]: from math import pi
517
518 In [2]: %precision 3
519 Out[2]: u'%.3f'
520
521 In [3]: pi
522 Out[3]: 3.142
523
524 In [4]: %precision %i
525 Out[4]: u'%i'
526
527 In [5]: pi
528 Out[5]: 3
529
530 In [6]: %precision %e
531 Out[6]: u'%e'
532
533 In [7]: pi**10
534 Out[7]: 9.364805e+04
535
536 In [8]: %precision
537 Out[8]: u'%r'
538
539 In [9]: pi**10
540 Out[9]: 93648.047476082982
541 """
542 ptformatter = self.shell.display_formatter.formatters['text/plain']
543 ptformatter.float_precision = s
544 return ptformatter.float_format
545
546 @magic_arguments.magic_arguments()
547 @magic_arguments.argument(
548 '-e', '--export', action='store_true', default=False,
549 help=argparse.SUPPRESS
550 )
551 @magic_arguments.argument(
552 'filename', type=str,
553 help='Notebook name or filename'
554 )
555 @line_magic
556 def notebook(self, s):
557 """Export and convert IPython notebooks.
558
559 This function can export the current IPython history to a notebook file.
560 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
561
562 The -e or --export flag is deprecated in IPython 5.2, and will be
563 removed in the future.
564 """
565 args = magic_arguments.parse_argstring(self.notebook, s)
566
567 from nbformat import write, v4
568
569 cells = []
570 hist = list(self.shell.history_manager.get_range())
571 if(len(hist)<=1):
572 raise ValueError('History is empty, cannot export')
573 for session, execution_count, source in hist[:-1]:
574 cells.append(v4.new_code_cell(
575 execution_count=execution_count,
576 source=source
577 ))
578 nb = v4.new_notebook(cells=cells)
579 with io.open(args.filename, 'w', encoding='utf-8') as f:
580 write(nb, f, version=4)
581
[end of IPython/core/magics/basic.py]
[start of IPython/utils/tokenize2.py]
1 """Patched version of standard library tokenize, to deal with various bugs.
2
3 Based on Python 3.2 code.
4
5 Patches:
6
7 - Gareth Rees' patch for Python issue #12691 (untokenizing)
8 - Except we don't encode the output of untokenize
9 - Python 2 compatible syntax, so that it can be byte-compiled at installation
10 - Newlines in comments and blank lines should be either NL or NEWLINE, depending
11 on whether they are in a multi-line statement. Filed as Python issue #17061.
12 - Export generate_tokens & TokenError
13 - u and rb literals are allowed under Python 3.3 and above.
14
15 ------------------------------------------------------------------------------
16 Tokenization help for Python programs.
17
18 tokenize(readline) is a generator that breaks a stream of bytes into
19 Python tokens. It decodes the bytes according to PEP-0263 for
20 determining source file encoding.
21
22 It accepts a readline-like method which is called repeatedly to get the
23 next line of input (or b"" for EOF). It generates 5-tuples with these
24 members:
25
26 the token type (see token.py)
27 the token (a string)
28 the starting (row, column) indices of the token (a 2-tuple of ints)
29 the ending (row, column) indices of the token (a 2-tuple of ints)
30 the original line (string)
31
32 It is designed to match the working of the Python tokenizer exactly, except
33 that it produces COMMENT tokens for comments and gives type OP for all
34 operators. Additionally, all token lists start with an ENCODING token
35 which tells you which encoding was used to decode the bytes stream.
36 """
37
38 __author__ = 'Ka-Ping Yee <ping@lfw.org>'
39 __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
40 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
41 'Michael Foord')
42 import builtins
43 import re
44 import sys
45 from token import *
46 from codecs import lookup, BOM_UTF8
47 import collections
48 from io import TextIOWrapper
49 cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
50
51 import token
52 __all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
53 "NL", "untokenize", "ENCODING", "TokenInfo"]
54 del token
55
56 __all__ += ["generate_tokens", "TokenError"]
57
58 COMMENT = N_TOKENS
59 tok_name[COMMENT] = 'COMMENT'
60 NL = N_TOKENS + 1
61 tok_name[NL] = 'NL'
62 ENCODING = N_TOKENS + 2
63 tok_name[ENCODING] = 'ENCODING'
64 N_TOKENS += 3
65
66 class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
67 def __repr__(self):
68 annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
69 return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
70 self._replace(type=annotated_type))
71
72 def group(*choices): return '(' + '|'.join(choices) + ')'
73 def any(*choices): return group(*choices) + '*'
74 def maybe(*choices): return group(*choices) + '?'
75
76 # Note: we use unicode matching for names ("\w") but ascii matching for
77 # number literals.
78 Whitespace = r'[ \f\t]*'
79 Comment = r'#[^\r\n]*'
80 Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
81 Name = r'\w+'
82
83 Hexnumber = r'0[xX][0-9a-fA-F]+'
84 Binnumber = r'0[bB][01]+'
85 Octnumber = r'0[oO][0-7]+'
86 Decnumber = r'(?:0+|[1-9][0-9]*)'
87 Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
88 Exponent = r'[eE][-+]?[0-9]+'
89 Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
90 Expfloat = r'[0-9]+' + Exponent
91 Floatnumber = group(Pointfloat, Expfloat)
92 Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
93 Number = group(Imagnumber, Floatnumber, Intnumber)
94
95 if sys.version_info.minor >= 3:
96 StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
97 else:
98 StringPrefix = r'(?:[bB]?[rR]?)?'
99
100 # Tail end of ' string.
101 Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
102 # Tail end of " string.
103 Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
104 # Tail end of ''' string.
105 Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
106 # Tail end of """ string.
107 Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
108 Triple = group(StringPrefix + "'''", StringPrefix + '"""')
109 # Single-line ' or " string.
110 String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
111 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
112
113 # Because of leftmost-then-longest match semantics, be sure to put the
114 # longest operators first (e.g., if = came before ==, == would get
115 # recognized as two instances of =).
116 Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
117 r"//=?", r"->",
118 r"[+\-*/%&|^=<>]=?",
119 r"~")
120
121 Bracket = '[][(){}]'
122 Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
123 Funny = group(Operator, Bracket, Special)
124
125 PlainToken = group(Number, Funny, String, Name)
126 Token = Ignore + PlainToken
127
128 # First (or only) line of ' or " string.
129 ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
130 group("'", r'\\\r?\n'),
131 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
132 group('"', r'\\\r?\n'))
133 PseudoExtras = group(r'\\\r?\n', Comment, Triple)
134 PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
135
136 def _compile(expr):
137 return re.compile(expr, re.UNICODE)
138
139 tokenprog, pseudoprog, single3prog, double3prog = map(
140 _compile, (Token, PseudoToken, Single3, Double3))
141 endprogs = {"'": _compile(Single), '"': _compile(Double),
142 "'''": single3prog, '"""': double3prog,
143 "r'''": single3prog, 'r"""': double3prog,
144 "b'''": single3prog, 'b"""': double3prog,
145 "R'''": single3prog, 'R"""': double3prog,
146 "B'''": single3prog, 'B"""': double3prog,
147 "br'''": single3prog, 'br"""': double3prog,
148 "bR'''": single3prog, 'bR"""': double3prog,
149 "Br'''": single3prog, 'Br"""': double3prog,
150 "BR'''": single3prog, 'BR"""': double3prog,
151 'r': None, 'R': None, 'b': None, 'B': None}
152
153 triple_quoted = {}
154 for t in ("'''", '"""',
155 "r'''", 'r"""', "R'''", 'R"""',
156 "b'''", 'b"""', "B'''", 'B"""',
157 "br'''", 'br"""', "Br'''", 'Br"""',
158 "bR'''", 'bR"""', "BR'''", 'BR"""'):
159 triple_quoted[t] = t
160 single_quoted = {}
161 for t in ("'", '"',
162 "r'", 'r"', "R'", 'R"',
163 "b'", 'b"', "B'", 'B"',
164 "br'", 'br"', "Br'", 'Br"',
165 "bR'", 'bR"', "BR'", 'BR"' ):
166 single_quoted[t] = t
167
168 if sys.version_info.minor >= 3:
169 # Python 3.3
170 for _prefix in ['rb', 'rB', 'Rb', 'RB', 'u', 'U']:
171 _t2 = _prefix+'"""'
172 endprogs[_t2] = double3prog
173 triple_quoted[_t2] = _t2
174 _t1 = _prefix + "'''"
175 endprogs[_t1] = single3prog
176 triple_quoted[_t1] = _t1
177 single_quoted[_prefix+'"'] = _prefix+'"'
178 single_quoted[_prefix+"'"] = _prefix+"'"
179 del _prefix, _t2, _t1
180 endprogs['u'] = None
181 endprogs['U'] = None
182
183 del _compile
184
185 tabsize = 8
186
187 class TokenError(Exception): pass
188
189 class StopTokenizing(Exception): pass
190
191
192 class Untokenizer:
193
194 def __init__(self):
195 self.tokens = []
196 self.prev_row = 1
197 self.prev_col = 0
198 self.encoding = 'utf-8'
199
200 def add_whitespace(self, tok_type, start):
201 row, col = start
202 assert row >= self.prev_row
203 col_offset = col - self.prev_col
204 if col_offset > 0:
205 self.tokens.append(" " * col_offset)
206 elif row > self.prev_row and tok_type not in (NEWLINE, NL, ENDMARKER):
207 # Line was backslash-continued.
208 self.tokens.append(" ")
209
210 def untokenize(self, tokens):
211 iterable = iter(tokens)
212 for t in iterable:
213 if len(t) == 2:
214 self.compat(t, iterable)
215 break
216 tok_type, token, start, end = t[:4]
217 if tok_type == ENCODING:
218 self.encoding = token
219 continue
220 self.add_whitespace(tok_type, start)
221 self.tokens.append(token)
222 self.prev_row, self.prev_col = end
223 if tok_type in (NEWLINE, NL):
224 self.prev_row += 1
225 self.prev_col = 0
226 return "".join(self.tokens)
227
228 def compat(self, token, iterable):
229 # This import is here to avoid problems when the itertools
230 # module is not built yet and tokenize is imported.
231 from itertools import chain
232 startline = False
233 prevstring = False
234 indents = []
235 toks_append = self.tokens.append
236
237 for tok in chain([token], iterable):
238 toknum, tokval = tok[:2]
239 if toknum == ENCODING:
240 self.encoding = tokval
241 continue
242
243 if toknum in (NAME, NUMBER):
244 tokval += ' '
245
246 # Insert a space between two consecutive strings
247 if toknum == STRING:
248 if prevstring:
249 tokval = ' ' + tokval
250 prevstring = True
251 else:
252 prevstring = False
253
254 if toknum == INDENT:
255 indents.append(tokval)
256 continue
257 elif toknum == DEDENT:
258 indents.pop()
259 continue
260 elif toknum in (NEWLINE, NL):
261 startline = True
262 elif startline and indents:
263 toks_append(indents[-1])
264 startline = False
265 toks_append(tokval)
266
267
268 def untokenize(tokens):
269 """
270 Convert ``tokens`` (an iterable) back into Python source code. Return
271 a bytes object, encoded using the encoding specified by the last
272 ENCODING token in ``tokens``, or UTF-8 if no ENCODING token is found.
273
274 The result is guaranteed to tokenize back to match the input so that
275 the conversion is lossless and round-trips are assured. The
276 guarantee applies only to the token type and token string as the
277 spacing between tokens (column positions) may change.
278
279 :func:`untokenize` has two modes. If the input tokens are sequences
280 of length 2 (``type``, ``string``) then spaces are added as necessary to
281 preserve the round-trip property.
282
283 If the input tokens are sequences of length 4 or more (``type``,
284 ``string``, ``start``, ``end``), as returned by :func:`tokenize`, then
285 spaces are added so that each token appears in the result at the
286 position indicated by ``start`` and ``end``, if possible.
287 """
288 return Untokenizer().untokenize(tokens)
289
290
291 def _get_normal_name(orig_enc):
292 """Imitates get_normal_name in tokenizer.c."""
293 # Only care about the first 12 characters.
294 enc = orig_enc[:12].lower().replace("_", "-")
295 if enc == "utf-8" or enc.startswith("utf-8-"):
296 return "utf-8"
297 if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
298 enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
299 return "iso-8859-1"
300 return orig_enc
301
302 def detect_encoding(readline):
303 """
304 The detect_encoding() function is used to detect the encoding that should
305 be used to decode a Python source file. It requires one argment, readline,
306 in the same way as the tokenize() generator.
307
308 It will call readline a maximum of twice, and return the encoding used
309 (as a string) and a list of any lines (left as bytes) it has read in.
310
311 It detects the encoding from the presence of a utf-8 bom or an encoding
312 cookie as specified in pep-0263. If both a bom and a cookie are present,
313 but disagree, a SyntaxError will be raised. If the encoding cookie is an
314 invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
315 'utf-8-sig' is returned.
316
317 If no encoding is specified, then the default of 'utf-8' will be returned.
318 """
319 bom_found = False
320 encoding = None
321 default = 'utf-8'
322 def read_or_stop():
323 try:
324 return readline()
325 except StopIteration:
326 return b''
327
328 def find_cookie(line):
329 try:
330 # Decode as UTF-8. Either the line is an encoding declaration,
331 # in which case it should be pure ASCII, or it must be UTF-8
332 # per default encoding.
333 line_string = line.decode('utf-8')
334 except UnicodeDecodeError:
335 raise SyntaxError("invalid or missing encoding declaration")
336
337 matches = cookie_re.findall(line_string)
338 if not matches:
339 return None
340 encoding = _get_normal_name(matches[0])
341 try:
342 codec = lookup(encoding)
343 except LookupError:
344 # This behaviour mimics the Python interpreter
345 raise SyntaxError("unknown encoding: " + encoding)
346
347 if bom_found:
348 if encoding != 'utf-8':
349 # This behaviour mimics the Python interpreter
350 raise SyntaxError('encoding problem: utf-8')
351 encoding += '-sig'
352 return encoding
353
354 first = read_or_stop()
355 if first.startswith(BOM_UTF8):
356 bom_found = True
357 first = first[3:]
358 default = 'utf-8-sig'
359 if not first:
360 return default, []
361
362 encoding = find_cookie(first)
363 if encoding:
364 return encoding, [first]
365
366 second = read_or_stop()
367 if not second:
368 return default, [first]
369
370 encoding = find_cookie(second)
371 if encoding:
372 return encoding, [first, second]
373
374 return default, [first, second]
375
376
377 def open(filename):
378 """Open a file in read only mode using the encoding detected by
379 detect_encoding().
380 """
381 buffer = builtins.open(filename, 'rb')
382 encoding, lines = detect_encoding(buffer.readline)
383 buffer.seek(0)
384 text = TextIOWrapper(buffer, encoding, line_buffering=True)
385 text.mode = 'r'
386 return text
387
388
389 def tokenize(readline):
390 """
391 The tokenize() generator requires one argment, readline, which
392 must be a callable object which provides the same interface as the
393 readline() method of built-in file objects. Each call to the function
394 should return one line of input as bytes. Alternately, readline
395 can be a callable function terminating with StopIteration:
396 readline = open(myfile, 'rb').__next__ # Example of alternate readline
397
398 The generator produces 5-tuples with these members: the token type; the
399 token string; a 2-tuple (srow, scol) of ints specifying the row and
400 column where the token begins in the source; a 2-tuple (erow, ecol) of
401 ints specifying the row and column where the token ends in the source;
402 and the line on which the token was found. The line passed is the
403 logical line; continuation lines are included.
404
405 The first token sequence will always be an ENCODING token
406 which tells you which encoding was used to decode the bytes stream.
407 """
408 # This import is here to avoid problems when the itertools module is not
409 # built yet and tokenize is imported.
410 from itertools import chain, repeat
411 encoding, consumed = detect_encoding(readline)
412 rl_gen = iter(readline, b"")
413 empty = repeat(b"")
414 return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
415
416
417 def _tokenize(readline, encoding):
418 lnum = parenlev = continued = 0
419 numchars = '0123456789'
420 contstr, needcont = '', 0
421 contline = None
422 indents = [0]
423
424 if encoding is not None:
425 if encoding == "utf-8-sig":
426 # BOM will already have been stripped.
427 encoding = "utf-8"
428 yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
429 while True: # loop over lines in stream
430 try:
431 line = readline()
432 except StopIteration:
433 line = b''
434
435 if encoding is not None:
436 line = line.decode(encoding)
437 lnum += 1
438 pos, max = 0, len(line)
439
440 if contstr: # continued string
441 if not line:
442 raise TokenError("EOF in multi-line string", strstart)
443 endmatch = endprog.match(line)
444 if endmatch:
445 pos = end = endmatch.end(0)
446 yield TokenInfo(STRING, contstr + line[:end],
447 strstart, (lnum, end), contline + line)
448 contstr, needcont = '', 0
449 contline = None
450 elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
451 yield TokenInfo(ERRORTOKEN, contstr + line,
452 strstart, (lnum, len(line)), contline)
453 contstr = ''
454 contline = None
455 continue
456 else:
457 contstr = contstr + line
458 contline = contline + line
459 continue
460
461 elif parenlev == 0 and not continued: # new statement
462 if not line: break
463 column = 0
464 while pos < max: # measure leading whitespace
465 if line[pos] == ' ':
466 column += 1
467 elif line[pos] == '\t':
468 column = (column//tabsize + 1)*tabsize
469 elif line[pos] == '\f':
470 column = 0
471 else:
472 break
473 pos += 1
474 if pos == max:
475 break
476
477 if line[pos] in '#\r\n': # skip comments or blank lines
478 if line[pos] == '#':
479 comment_token = line[pos:].rstrip('\r\n')
480 nl_pos = pos + len(comment_token)
481 yield TokenInfo(COMMENT, comment_token,
482 (lnum, pos), (lnum, pos + len(comment_token)), line)
483 yield TokenInfo(NEWLINE, line[nl_pos:],
484 (lnum, nl_pos), (lnum, len(line)), line)
485 else:
486 yield TokenInfo(NEWLINE, line[pos:],
487 (lnum, pos), (lnum, len(line)), line)
488 continue
489
490 if column > indents[-1]: # count indents or dedents
491 indents.append(column)
492 yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
493 while column < indents[-1]:
494 if column not in indents:
495 raise IndentationError(
496 "unindent does not match any outer indentation level",
497 ("<tokenize>", lnum, pos, line))
498 indents = indents[:-1]
499 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
500
501 else: # continued statement
502 if not line:
503 raise TokenError("EOF in multi-line statement", (lnum, 0))
504 continued = 0
505
506 while pos < max:
507 pseudomatch = pseudoprog.match(line, pos)
508 if pseudomatch: # scan for tokens
509 start, end = pseudomatch.span(1)
510 spos, epos, pos = (lnum, start), (lnum, end), end
511 token, initial = line[start:end], line[start]
512
513 if (initial in numchars or # ordinary number
514 (initial == '.' and token != '.' and token != '...')):
515 yield TokenInfo(NUMBER, token, spos, epos, line)
516 elif initial in '\r\n':
517 yield TokenInfo(NL if parenlev > 0 else NEWLINE,
518 token, spos, epos, line)
519 elif initial == '#':
520 assert not token.endswith("\n")
521 yield TokenInfo(COMMENT, token, spos, epos, line)
522 elif token in triple_quoted:
523 endprog = endprogs[token]
524 endmatch = endprog.match(line, pos)
525 if endmatch: # all on one line
526 pos = endmatch.end(0)
527 token = line[start:pos]
528 yield TokenInfo(STRING, token, spos, (lnum, pos), line)
529 else:
530 strstart = (lnum, start) # multiple lines
531 contstr = line[start:]
532 contline = line
533 break
534 elif initial in single_quoted or \
535 token[:2] in single_quoted or \
536 token[:3] in single_quoted:
537 if token[-1] == '\n': # continued string
538 strstart = (lnum, start)
539 endprog = (endprogs[initial] or endprogs[token[1]] or
540 endprogs[token[2]])
541 contstr, needcont = line[start:], 1
542 contline = line
543 break
544 else: # ordinary string
545 yield TokenInfo(STRING, token, spos, epos, line)
546 elif initial.isidentifier(): # ordinary name
547 yield TokenInfo(NAME, token, spos, epos, line)
548 elif initial == '\\': # continued stmt
549 continued = 1
550 else:
551 if initial in '([{':
552 parenlev += 1
553 elif initial in ')]}':
554 parenlev -= 1
555 yield TokenInfo(OP, token, spos, epos, line)
556 else:
557 yield TokenInfo(ERRORTOKEN, line[pos],
558 (lnum, pos), (lnum, pos+1), line)
559 pos += 1
560
561 for indent in indents[1:]: # pop remaining indent levels
562 yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
563 yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
564
565
566 # An undocumented, backwards compatible, API for all the places in the standard
567 # library that expect to be able to use tokenize with strings
568 def generate_tokens(readline):
569 return _tokenize(readline, None)
570
571 if __name__ == "__main__":
572 # Quick sanity check
573 s = b'''def parseline(self, line):
574 """Parse the line into a command name and a string containing
575 the arguments. Returns a tuple containing (command, args, line).
576 'command' and 'args' may be None if the line couldn't be parsed.
577 """
578 line = line.strip()
579 if not line:
580 return None, None, line
581 elif line[0] == '?':
582 line = 'help ' + line[1:]
583 elif line[0] == '!':
584 if hasattr(self, 'do_shell'):
585 line = 'shell ' + line[1:]
586 else:
587 return None, None, line
588 i, n = 0, len(line)
589 while i < n and line[i] in self.identchars: i = i+1
590 cmd, arg = line[:i], line[i:].strip()
591 return cmd, arg, line
592 '''
593 for tok in tokenize(iter(s.splitlines()).__next__):
594 print(tok)
595
[end of IPython/utils/tokenize2.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>
| ipython/ipython | 78ec96d7ca0147f0655d5260f2ab0c61d94e4279 | remove usage of backports.shutil_get_terminal_size
This is for pre-3.3 Python.
Pretty easy it should only require deleting lines.
Maybe a few need to be dedented.
| 2017-01-28T05:22:06Z | <patch>
diff --git a/IPython/utils/terminal.py b/IPython/utils/terminal.py
--- a/IPython/utils/terminal.py
+++ b/IPython/utils/terminal.py
@@ -15,11 +15,7 @@
import os
import sys
import warnings
-try:
- from shutil import get_terminal_size as _get_terminal_size
-except ImportError:
- # use backport on Python 2
- from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
+from shutil import get_terminal_size as _get_terminal_size
from . import py3compat
</patch> | [] | [] | ||||
Qiskit__qiskit-1295 | You will be provided with a partial code base and an issue statement explaining a problem to resolve.
<issue>
credentials failed for qiskit ver 0.6.1
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.7.0
- **Operating system**:MAC OSX 10.13.6
### What is the current behavior?
After I acquired fresh token from https://quantumexperience.ng.bluemix.net/qx/account/advanced
IBMQ.load_accounts() fails.
### Steps to reproduce the problem
```
from qiskit import IBMQ
myToken='b6abe11442c9a...'
IBMQ.save_account(myToken)
IBMQ.load_accounts()
```
Results with
```
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/site-packages/qiskit/backends/ibmq/ibmqsingleprovider.py", line 71, in _authenticate
credentials.verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 478, in __init__
self.req = _Request(token, config=config, verify=verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 253, in __init__
ntlm_credentials=self.ntlm_credentials)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 95, in __init__
self.obtain_token(config=self.config)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 159, in obtain_token
raise CredentialsError('error during login: %s' % error_message)
IBMQuantumExperience.IBMQuantumExperience.CredentialsError: error during login: Wrong user or password, check your credentials.
```
### What is the expected behavior?
Would be better if IBMQ.load_accounts() accepted me. All worked well w/ ver 0.5.
### Suggested solutions
</issue>
<code>
[start of README.md]
1 # Qiskit Terra
2
3 [![PyPI](https://img.shields.io/pypi/v/qiskit.svg)](https://pypi.python.org/pypi/qiskit)
4 [![Build Status](https://travis-ci.org/Qiskit/qiskit-terra.svg?branch=master)](https://travis-ci.org/Qiskit/qiskit-terra)
5 [![Build Status IBM Q](https://travis-matrix-badges.herokuapp.com/repos/Qiskit/qiskit-terra/branches/master/8)](https://travis-ci.org/Qiskit/qiskit-terra)
6
7 **Qiskit** is a software development kit for
8 developing quantum computing applications and working with NISQ (Noisy-Intermediate Scale Quantum) computers.
9
10 Qiskit is made up elements that each work together to enable quantum computing. This element is **Terra**
11 and is the foundation on which the rest of Qiskit is built (see this [post](https://medium.com/qiskit/qiskit-and-its-fundamental-elements-bcd7ead80492) for an overview).
12
13
14 ## Installation
15
16
17 We encourage installing Qiskit via the PIP tool (a python package manager):
18
19 ```bash
20 pip install qiskit
21 ```
22
23 PIP will handle all dependencies automatically for us and you will always install the latest (and well-tested) version.
24
25 At least [Python 3.5 or later](https://www.python.org/downloads/) is needed for using Qiskit. In
26 addition, [Jupyter Notebook](https://jupyter.readthedocs.io/en/latest/install.html) is recommended
27 for interacting with the tutorials.
28 For this reason we recommend installing the [Anaconda 3](https://www.continuum.io/downloads)
29 python distribution, as it comes with all of these dependencies pre-installed.
30
31 See [installing](doc/install.rst) Qiskit for detailed instructions, how to build from source and using environments.
32
33
34 ## Creating your first quantum program
35
36 Now that Qiskit is installed, it's time to begin working with Terra.
37
38 We are ready to try out a quantum circuit example, which is simulated locally using
39 the Qiskt Aer element. This is a simple example that makes an entangled state.
40
41 ```
42 $ python
43 ```
44
45 ```python
46 >>> from qiskit import *
47 >>> q = QuantumRegister(2)
48 >>> c = ClassicalRegister(2)
49 >>> qc = QuantumCircuit(q, c)
50 >>> qc.h(q[0])
51 >>> qc.cx(q[0], q[1])
52 >>> qc.measure(q, c)
53 >>> backend_sim = Aer.get_backend('qasm_simulator')
54 >>> result = execute(qc, backend_sim).result()
55 >>> print(result.get_counts(qc))
56 ```
57
58 In this case, the output will be:
59
60 ```python
61 {'counts': {'00': 513, '11': 511}}
62 ```
63
64 A script is available [here](examples/python/hello_quantum.py), where we also show how to
65 run the same program on a real quantum computer via IBMQ.
66
67 ### Executing your code on a real quantum chip
68
69 You can also use Qiskit to execute your code on a
70 **real quantum chip**.
71 In order to do so, you need to configure Qiskit for using the credentials in
72 your IBM Q account:
73
74 #### Configure your IBMQ credentials
75
76 1. Create an _[IBM Q](https://quantumexperience.ng.bluemix.net) > Account_ if you haven't already done so.
77
78 2. Get an API token from the IBM Q website under _My Account > Advanced > API Token_.
79
80 3. Take your token from step 2, here called `MY_API_TOKEN`, and run:
81
82 ```python
83 >>> from qiskit import IBMQ
84 >>> IBMQ.save_account('MY_API_TOKEN')
85 ```
86
87 4. If you have access to the IBM Q Network features, you also need to pass the
88 url listed on your IBM Q account page to `save_account`.
89
90 After calling `IBMQ.save_account()`, your credentials will be stored on disk.
91 Once they are stored, at any point in the future you can load and use them
92 in your program simply via:
93
94 ```python
95 >>> from qiskit import IBMQ
96 >>> IBMQ.load_accounts()
97 ```
98
99 For those who do not want to save there credentials to disk please use
100
101 ```python
102 >>> from qiskit import IBMQ
103 >>> IBMQ.enable_account('MY_API_TOKEN')
104 ```
105
106 and the token will only be active for the session. For examples using Terra with real
107 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
108 the levels.
109
110 ## Contribution guidelines
111
112 If you'd like to contribute to Qiskit, please take a look at our
113 [contribution guidelines](.github/CONTRIBUTING.rst). This project adheres to Qiskit's [code of conduct](.github/CODE_OF_CONDUCT.rst). By participating, you are expect to uphold to this code.
114
115 We use [GitHub issues](https://github.com/Qiskit/qiskit-terra/issues) for tracking requests and bugs.
116 Please use our [slack](https://qiskit.slack.com) for discussion. To join our Slack community use the [link](https://join.slack.com/t/qiskit/shared_invite/enQtNDc2NjUzMjE4Mzc0LTMwZmE0YTM4ZThiNGJmODkzN2Y2NTNlMDIwYWNjYzA2ZmM1YTRlZGQ3OGM0NjcwMjZkZGE0MTA4MGQ1ZTVmYzk). To ask questions to [Stack Overflow](https://stackoverflow.com/questions/tagged/qiskit).
117
118
119
120 ### Next Steps
121
122 Now you're set up and ready to check out some of the other examples from our
123 [Qiskit Tutorial](https://github.com/Qiskit/qiskit-tutorial) repository.
124
125
126 ## Authors
127
128 Qiskit Terra is the work of [many people](https://github.com/Qiskit/qiskit-terra/graphs/contributors) who contribute
129 to the project at different levels.
130
131 ## License
132
133 [Apache License 2.0](LICENSE.txt)
[end of README.md]
[start of qiskit/backends/ibmq/api/ibmqconnector.py]
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018, IBM.
4 #
5 # This source code is licensed under the Apache License, Version 2.0 found in
6 # the LICENSE.txt file in the root directory of this source tree.
7
8 """IBM Q API connector."""
9
10 import json
11 import logging
12 import re
13 import time
14
15 import requests
16 from requests_ntlm import HttpNtlmAuth
17
18 logger = logging.getLogger(__name__)
19 CLIENT_APPLICATION = 'qiskit-api-py'
20
21
22 def get_job_url(config, hub, group, project):
23 """
24 Util method to get job url
25 """
26 if (config is not None) and ('hub' in config) and (hub is None):
27 hub = config["hub"]
28 if (config is not None) and ('group' in config) and (group is None):
29 group = config["group"]
30 if (config is not None) and ('project' in config) and (project is None):
31 project = config["project"]
32 if (hub is not None) and (group is not None) and (project is not None):
33 return '/Network/{}/Groups/{}/Projects/{}/jobs'.format(hub, group, project)
34 return '/Jobs'
35
36
37 def get_backend_stats_url(config, hub, backend_type):
38 """
39 Util method to get backend stats url
40 """
41 if (config is not None) and ('hub' in config) and (hub is None):
42 hub = config["hub"]
43 if hub is not None:
44 return '/Network/{}/devices/{}'.format(hub, backend_type)
45 return '/Backends/{}'.format(backend_type)
46
47
48 def get_backend_url(config, hub, group, project):
49 """
50 Util method to get backend url
51 """
52 if (config is not None) and ('hub' in config) and (hub is None):
53 hub = config["hub"]
54 if (config is not None) and ('group' in config) and (group is None):
55 group = config["group"]
56 if (config is not None) and ('project' in config) and (project is None):
57 project = config["project"]
58 if (hub is not None) and (group is not None) and (project is not None):
59 return '/Network/{}/Groups/{}/Projects/{}/devices'.format(hub, group, project)
60 return '/Backends'
61
62
63 class _Credentials(object):
64 """
65 The Credential class to manage the tokens
66 """
67 config_base = {'url': 'https://quantumexperience.ng.bluemix.net/api'}
68
69 def __init__(self, token, config=None, verify=True, proxy_urls=None,
70 ntlm_credentials=None):
71 self.token_unique = token
72 self.verify = verify
73 self.config = config
74 self.proxy_urls = proxy_urls
75 self.ntlm_credentials = ntlm_credentials
76
77 # Set the extra arguments to requests (proxy and auth).
78 self.extra_args = {}
79 if self.proxy_urls:
80 self.extra_args['proxies'] = self.proxy_urls
81 if self.ntlm_credentials:
82 self.extra_args['auth'] = HttpNtlmAuth(
83 self.ntlm_credentials['username'],
84 self.ntlm_credentials['password'])
85
86 if not verify:
87 # pylint: disable=import-error
88 import requests.packages.urllib3 as urllib3
89 urllib3.disable_warnings()
90 print('-- Ignoring SSL errors. This is not recommended --')
91 if self.config and ("url" not in self.config):
92 self.config["url"] = self.config_base["url"]
93 elif not self.config:
94 self.config = self.config_base
95
96 self.data_credentials = {}
97 if token:
98 self.obtain_token(config=self.config)
99 else:
100 access_token = self.config.get('access_token', None)
101 if access_token:
102 user_id = self.config.get('user_id', None)
103 if access_token:
104 self.set_token(access_token)
105 if user_id:
106 self.set_user_id(user_id)
107 else:
108 self.obtain_token(config=self.config)
109
110 def obtain_token(self, config=None):
111 """Obtain the token to access to QX Platform.
112
113 Raises:
114 CredentialsError: when token is invalid or the user has not
115 accepted the license.
116 ApiError: when the response from the server couldn't be parsed.
117 """
118 client_application = CLIENT_APPLICATION
119 if self.config and ("client_application" in self.config):
120 client_application += ':' + self.config["client_application"]
121 headers = {'x-qx-client-application': client_application}
122
123 if self.token_unique:
124 try:
125 response = requests.post(str(self.config.get('url') +
126 "/users/loginWithToken"),
127 data={'apiToken': self.token_unique},
128 verify=self.verify,
129 headers=headers,
130 **self.extra_args)
131 except requests.RequestException as ex:
132 raise ApiError('error during login: %s' % str(ex))
133 elif config and ("email" in config) and ("password" in config):
134 email = config.get('email', None)
135 password = config.get('password', None)
136 credentials = {
137 'email': email,
138 'password': password
139 }
140 try:
141 response = requests.post(str(self.config.get('url') +
142 "/users/login"),
143 data=credentials,
144 verify=self.verify,
145 headers=headers,
146 **self.extra_args)
147 except requests.RequestException as ex:
148 raise ApiError('error during login: %s' % str(ex))
149 else:
150 raise CredentialsError('invalid token')
151
152 if response.status_code == 401:
153 error_message = None
154 try:
155 # For 401: ACCEPT_LICENSE_REQUIRED, a detailed message is
156 # present in the response and passed to the exception.
157 error_message = response.json()['error']['message']
158 except Exception: # pylint: disable=broad-except
159 pass
160
161 if error_message:
162 raise CredentialsError('error during login: %s' % error_message)
163 else:
164 raise CredentialsError('invalid token')
165 try:
166 response.raise_for_status()
167 self.data_credentials = response.json()
168 except (requests.HTTPError, ValueError) as ex:
169 raise ApiError('error during login: %s' % str(ex))
170
171 if self.get_token() is None:
172 raise CredentialsError('invalid token')
173
174 def get_token(self):
175 """
176 Get Authenticated Token to connect with QX Platform
177 """
178 return self.data_credentials.get('id', None)
179
180 def get_user_id(self):
181 """
182 Get User Id in QX Platform
183 """
184 return self.data_credentials.get('userId', None)
185
186 def get_config(self):
187 """
188 Get Configuration setted to connect with QX Platform
189 """
190 return self.config
191
192 def set_token(self, access_token):
193 """
194 Set Access Token to connect with QX Platform API
195 """
196 self.data_credentials['id'] = access_token
197
198 def set_user_id(self, user_id):
199 """
200 Set Access Token to connect with QX Platform API
201 """
202 self.data_credentials['userId'] = user_id
203
204
205 class _Request(object):
206 """
207 The Request class to manage the methods
208 """
209 def __init__(self, token, config=None, verify=True, retries=5,
210 timeout_interval=1.0):
211 self.verify = verify
212 self.client_application = CLIENT_APPLICATION
213 self.config = config
214 self.errors_not_retry = [401, 403, 413]
215
216 # Set the proxy information, if present, from the configuration,
217 # with the following format:
218 # config = {
219 # 'proxies': {
220 # # If using 'urls', assume basic auth or no auth.
221 # 'urls': {
222 # 'http': 'http://user:password@1.2.3.4:5678',
223 # 'https': 'http://user:password@1.2.3.4:5678',
224 # }
225 # # If using 'ntlm', assume NTLM authentication.
226 # 'username_ntlm': 'domain\\username',
227 # 'password_ntlm': 'password'
228 # }
229 # }
230
231 # Set the basic proxy settings, if present.
232 self.proxy_urls = None
233 self.ntlm_credentials = None
234 if config and 'proxies' in config:
235 if 'urls' in config['proxies']:
236 self.proxy_urls = self.config['proxies']['urls']
237 if 'username_ntlm' and 'password_ntlm' in config['proxies']:
238 self.ntlm_credentials = {
239 'username': self.config['proxies']['username_ntlm'],
240 'password': self.config['proxies']['password_ntlm']
241 }
242
243 # Set the extra arguments to requests (proxy and auth).
244 self.extra_args = {}
245 if self.proxy_urls:
246 self.extra_args['proxies'] = self.proxy_urls
247 if self.ntlm_credentials:
248 self.extra_args['auth'] = HttpNtlmAuth(
249 self.ntlm_credentials['username'],
250 self.ntlm_credentials['password'])
251
252 if self.config and ("client_application" in self.config):
253 self.client_application += ':' + self.config["client_application"]
254 self.credential = _Credentials(token, self.config, verify,
255 proxy_urls=self.proxy_urls,
256 ntlm_credentials=self.ntlm_credentials)
257
258 if not isinstance(retries, int):
259 raise TypeError('post retries must be positive integer')
260 self.retries = retries
261 self.timeout_interval = timeout_interval
262 self.result = None
263 self._max_qubit_error_re = re.compile(
264 r".*registers exceed the number of qubits, "
265 r"it can\'t be greater than (\d+).*")
266
267 def check_token(self, respond):
268 """
269 Check is the user's token is valid
270 """
271 if respond.status_code == 401:
272 self.credential.obtain_token(config=self.config)
273 return False
274 return True
275
276 def post(self, path, params='', data=None):
277 """
278 POST Method Wrapper of the REST API
279 """
280 self.result = None
281 data = data or {}
282 headers = {'Content-Type': 'application/json',
283 'x-qx-client-application': self.client_application}
284 url = str(self.credential.config['url'] + path + '?access_token=' +
285 self.credential.get_token() + params)
286 retries = self.retries
287 while retries > 0:
288 respond = requests.post(url, data=data, headers=headers,
289 verify=self.verify, **self.extra_args)
290 if not self.check_token(respond):
291 respond = requests.post(url, data=data, headers=headers,
292 verify=self.verify,
293 **self.extra_args)
294
295 if self._response_good(respond):
296 if self.result:
297 return self.result
298 elif retries < 2:
299 return respond.json()
300 else:
301 retries -= 1
302 else:
303 retries -= 1
304 time.sleep(self.timeout_interval)
305
306 # timed out
307 raise ApiError(usr_msg='Failed to get proper ' +
308 'response from backend.')
309
310 def put(self, path, params='', data=None):
311 """
312 PUT Method Wrapper of the REST API
313 """
314 self.result = None
315 data = data or {}
316 headers = {'Content-Type': 'application/json',
317 'x-qx-client-application': self.client_application}
318 url = str(self.credential.config['url'] + path + '?access_token=' +
319 self.credential.get_token() + params)
320 retries = self.retries
321 while retries > 0:
322 respond = requests.put(url, data=data, headers=headers,
323 verify=self.verify, **self.extra_args)
324 if not self.check_token(respond):
325 respond = requests.put(url, data=data, headers=headers,
326 verify=self.verify,
327 **self.extra_args)
328 if self._response_good(respond):
329 if self.result:
330 return self.result
331 elif retries < 2:
332 return respond.json()
333 else:
334 retries -= 1
335 else:
336 retries -= 1
337 time.sleep(self.timeout_interval)
338 # timed out
339 raise ApiError(usr_msg='Failed to get proper ' +
340 'response from backend.')
341
342 def get(self, path, params='', with_token=True):
343 """
344 GET Method Wrapper of the REST API
345 """
346 self.result = None
347 access_token = ''
348 if with_token:
349 access_token = self.credential.get_token() or ''
350 if access_token:
351 access_token = '?access_token=' + str(access_token)
352 url = self.credential.config['url'] + path + access_token + params
353 retries = self.retries
354 headers = {'x-qx-client-application': self.client_application}
355 while retries > 0: # Repeat until no error
356 respond = requests.get(url, verify=self.verify, headers=headers,
357 **self.extra_args)
358 if not self.check_token(respond):
359 respond = requests.get(url, verify=self.verify,
360 headers=headers, **self.extra_args)
361 if self._response_good(respond):
362 if self.result:
363 return self.result
364 elif retries < 2:
365 return respond.json()
366 else:
367 retries -= 1
368 else:
369 retries -= 1
370 time.sleep(self.timeout_interval)
371 # timed out
372 raise ApiError(usr_msg='Failed to get proper ' +
373 'response from backend.')
374
375 def _response_good(self, respond):
376 """check response
377
378 Args:
379 respond (requests.Response): HTTP response.
380
381 Returns:
382 bool: True if the response is good, else False.
383
384 Raises:
385 ApiError: response isn't formatted properly.
386 """
387 if respond.status_code != requests.codes.ok:
388 logger.warning('Got a %s code response to %s: %s',
389 respond.status_code,
390 respond.url,
391 respond.text)
392 if respond.status_code in self.errors_not_retry:
393 raise ApiError(usr_msg='Got a {} code response to {}: {}'.format(
394 respond.status_code,
395 respond.url,
396 respond.text))
397 else:
398 return self._parse_response(respond)
399 try:
400 if str(respond.headers['content-type']).startswith("text/html;"):
401 self.result = respond.text
402 return True
403 else:
404 self.result = respond.json()
405 except (json.JSONDecodeError, ValueError):
406 usr_msg = 'device server returned unexpected http response'
407 dev_msg = usr_msg + ': ' + respond.text
408 raise ApiError(usr_msg=usr_msg, dev_msg=dev_msg)
409 if not isinstance(self.result, (list, dict)):
410 msg = ('JSON not a list or dict: url: {0},'
411 'status: {1}, reason: {2}, text: {3}')
412 raise ApiError(
413 usr_msg=msg.format(respond.url,
414 respond.status_code,
415 respond.reason, respond.text))
416 if ('error' not in self.result or
417 ('status' not in self.result['error'] or
418 self.result['error']['status'] != 400)):
419 return True
420
421 logger.warning("Got a 400 code JSON response to %s", respond.url)
422 return False
423
424 def _parse_response(self, respond):
425 """parse text of response for HTTP errors
426
427 This parses the text of the response to decide whether to
428 retry request or raise exception. At the moment this only
429 detects an exception condition.
430
431 Args:
432 respond (Response): requests.Response object
433
434 Returns:
435 bool: False if the request should be retried, True
436 if not.
437
438 Raises:
439 RegisterSizeError: if invalid device register size.
440 """
441 # convert error messages into exceptions
442 mobj = self._max_qubit_error_re.match(respond.text)
443 if mobj:
444 raise RegisterSizeError(
445 'device register size must be <= {}'.format(mobj.group(1)))
446 return True
447
448
449 class IBMQConnector(object):
450 """
451 The Connector Class to do request to QX Platform
452 """
453 __names_backend_ibmqxv2 = ['ibmqx5qv2', 'ibmqx2', 'qx5qv2', 'qx5q', 'real']
454 __names_backend_ibmqxv3 = ['ibmqx3']
455 __names_backend_simulator = ['simulator', 'sim_trivial_2',
456 'ibmqx_qasm_simulator', 'ibmq_qasm_simulator']
457
458 def __init__(self, token=None, config=None, verify=True):
459 """ If verify is set to false, ignore SSL certificate errors """
460 self.config = config
461
462 if self.config and ('url' in self.config):
463 url_parsed = self.config['url'].split('/api')
464 if len(url_parsed) == 2:
465 hub = group = project = None
466 project_parse = url_parsed[1].split('/Projects/')
467 if len(project_parse) == 2:
468 project = project_parse[1]
469 group_parse = project_parse[0].split('/Groups/')
470 if len(group_parse) == 2:
471 group = group_parse[1]
472 hub_parse = group_parse[0].split('/Hubs/')
473 if len(hub_parse) == 2:
474 hub = hub_parse[1]
475 if hub and group and project:
476 self.config['project'] = project
477 self.config['group'] = group
478 self.config['hub'] = hub
479 self.config['url'] = url_parsed[0] + '/api'
480
481 self.req = _Request(token, config=config, verify=verify)
482
483 def _check_backend(self, backend, endpoint):
484 """
485 Check if the name of a backend is valid to run in QX Platform
486 """
487 # First check against hacks for old backend names
488 original_backend = backend
489 backend = backend.lower()
490 if endpoint == 'experiment':
491 if backend in self.__names_backend_ibmqxv2:
492 return 'real'
493 elif backend in self.__names_backend_ibmqxv3:
494 return 'ibmqx3'
495 elif backend in self.__names_backend_simulator:
496 return 'sim_trivial_2'
497
498 # Check for new-style backends
499 backends = self.available_backends()
500 for backend_ in backends:
501 if backend_['name'] == original_backend:
502 return original_backend
503 # backend unrecognized
504 return None
505
506 def check_credentials(self):
507 """
508 Check if the user has permission in QX platform
509 """
510 return bool(self.req.credential.get_token())
511
512 def run_job(self, job, backend='simulator', shots=1,
513 max_credits=None, seed=None, hub=None, group=None,
514 project=None, hpc=None, access_token=None, user_id=None):
515 """
516 Execute a job
517 """
518 if access_token:
519 self.req.credential.set_token(access_token)
520 if user_id:
521 self.req.credential.set_user_id(user_id)
522 if not self.check_credentials():
523 return {"error": "Not credentials valid"}
524
525 backend_type = self._check_backend(backend, 'job')
526
527 if not backend_type:
528 raise BadBackendError(backend)
529
530 if isinstance(job, (list, tuple)):
531 qasms = job
532 for qasm in qasms:
533 qasm['qasm'] = qasm['qasm'].replace('IBMQASM 2.0;', '')
534 qasm['qasm'] = qasm['qasm'].replace('OPENQASM 2.0;', '')
535
536 data = {'qasms': qasms,
537 'shots': shots,
538 'backend': {}}
539
540 if max_credits:
541 data['maxCredits'] = max_credits
542
543 if seed and len(str(seed)) < 11 and str(seed).isdigit():
544 data['seed'] = seed
545 elif seed:
546 return {"error": "Not seed allowed. Max 10 digits."}
547
548 data['backend']['name'] = backend_type
549 elif isinstance(job, dict):
550 q_obj = job
551 data = {'qObject': q_obj,
552 'backend': {}}
553
554 data['backend']['name'] = backend_type
555 else:
556 return {"error": "Not a valid data to send"}
557
558 if hpc:
559 data['hpc'] = hpc
560
561 url = get_job_url(self.config, hub, group, project)
562
563 job = self.req.post(url, data=json.dumps(data))
564
565 return job
566
567 def get_job(self, id_job, hub=None, group=None, project=None,
568 access_token=None, user_id=None):
569 """
570 Get the information about a job, by its id
571 """
572 if access_token:
573 self.req.credential.set_token(access_token)
574 if user_id:
575 self.req.credential.set_user_id(user_id)
576 if not self.check_credentials():
577 respond = {}
578 respond["status"] = 'Error'
579 respond["error"] = "Not credentials valid"
580 return respond
581 if not id_job:
582 respond = {}
583 respond["status"] = 'Error'
584 respond["error"] = "Job ID not specified"
585 return respond
586
587 url = get_job_url(self.config, hub, group, project)
588
589 url += '/' + id_job
590
591 job = self.req.get(url)
592
593 if 'qasms' in job:
594 for qasm in job['qasms']:
595 if ('result' in qasm) and ('data' in qasm['result']):
596 qasm['data'] = qasm['result']['data']
597 del qasm['result']['data']
598 for key in qasm['result']:
599 qasm['data'][key] = qasm['result'][key]
600 del qasm['result']
601
602 return job
603
604 def get_jobs(self, limit=10, skip=0, backend=None, only_completed=False,
605 filter=None, hub=None, group=None, project=None,
606 access_token=None, user_id=None):
607 """
608 Get the information about the user jobs
609 """
610 # pylint: disable=redefined-builtin
611
612 if access_token:
613 self.req.credential.set_token(access_token)
614 if user_id:
615 self.req.credential.set_user_id(user_id)
616 if not self.check_credentials():
617 return {"error": "Not credentials valid"}
618
619 url = get_job_url(self.config, hub, group, project)
620 url_filter = '&filter='
621 query = {
622 "order": "creationDate DESC",
623 "limit": limit,
624 "skip": skip,
625 "where": {}
626 }
627 if filter is not None:
628 query['where'] = filter
629 else:
630 if backend is not None:
631 query['where']['backend.name'] = backend
632 if only_completed:
633 query['where']['status'] = 'COMPLETED'
634
635 url_filter = url_filter + json.dumps(query)
636 jobs = self.req.get(url, url_filter)
637 return jobs
638
639 def get_status_job(self, id_job, hub=None, group=None, project=None,
640 access_token=None, user_id=None):
641 """
642 Get the status about a job, by its id
643 """
644 if access_token:
645 self.req.credential.set_token(access_token)
646 if user_id:
647 self.req.credential.set_user_id(user_id)
648 if not self.check_credentials():
649 respond = {}
650 respond["status"] = 'Error'
651 respond["error"] = "Not credentials valid"
652 return respond
653 if not id_job:
654 respond = {}
655 respond["status"] = 'Error'
656 respond["error"] = "Job ID not specified"
657 return respond
658
659 url = get_job_url(self.config, hub, group, project)
660
661 url += '/' + id_job + '/status'
662
663 status = self.req.get(url)
664
665 return status
666
667 def get_status_jobs(self, limit=10, skip=0, backend=None, filter=None,
668 hub=None, group=None, project=None, access_token=None,
669 user_id=None):
670 """
671 Get the information about the user jobs
672 """
673 # pylint: disable=redefined-builtin
674
675 if access_token:
676 self.req.credential.set_token(access_token)
677 if user_id:
678 self.req.credential.set_user_id(user_id)
679 if not self.check_credentials():
680 return {"error": "Not credentials valid"}
681
682 url = get_job_url(self.config, hub, group, project)
683 url_filter = '&filter='
684 query = {
685 "order": "creationDate DESC",
686 "limit": limit,
687 "skip": skip,
688 "where": {}
689 }
690 if filter is not None:
691 query['where'] = filter
692 else:
693 if backend is not None:
694 query['where']['backend.name'] = backend
695
696 url += '/status'
697
698 url_filter = url_filter + json.dumps(query)
699
700 jobs = self.req.get(url, url_filter)
701
702 return jobs
703
704 def cancel_job(self, id_job, hub=None, group=None, project=None,
705 access_token=None, user_id=None):
706 """
707 Cancel the information about a job, by its id
708 """
709 if access_token:
710 self.req.credential.set_token(access_token)
711 if user_id:
712 self.req.credential.set_user_id(user_id)
713 if not self.check_credentials():
714 respond = {}
715 respond["status"] = 'Error'
716 respond["error"] = "Not credentials valid"
717 return respond
718 if not id_job:
719 respond = {}
720 respond["status"] = 'Error'
721 respond["error"] = "Job ID not specified"
722 return respond
723
724 url = get_job_url(self.config, hub, group, project)
725
726 url += '/{}/cancel'.format(id_job)
727
728 res = self.req.post(url)
729
730 return res
731
732 def backend_status(self, backend='ibmqx4', access_token=None, user_id=None):
733 """
734 Get the status of a chip
735 """
736 if access_token:
737 self.req.credential.set_token(access_token)
738 if user_id:
739 self.req.credential.set_user_id(user_id)
740 backend_type = self._check_backend(backend, 'status')
741 if not backend_type:
742 raise BadBackendError(backend)
743
744 status = self.req.get('/Backends/' + backend_type + '/queue/status',
745 with_token=False)
746
747 ret = {}
748 if 'state' in status:
749 ret['available'] = bool(status['state'])
750 if 'busy' in status:
751 ret['busy'] = bool(status['busy'])
752 if 'lengthQueue' in status:
753 ret['pending_jobs'] = status['lengthQueue']
754
755 ret['backend'] = backend_type
756
757 return ret
758
759 def backend_calibration(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
760 """
761 Get the calibration of a real chip
762 """
763 if access_token:
764 self.req.credential.set_token(access_token)
765 if user_id:
766 self.req.credential.set_user_id(user_id)
767 if not self.check_credentials():
768 raise CredentialsError('credentials invalid')
769
770 backend_type = self._check_backend(backend, 'calibration')
771
772 if not backend_type:
773 raise BadBackendError(backend)
774
775 if backend_type in self.__names_backend_simulator:
776 ret = {}
777 return ret
778
779 url = get_backend_stats_url(self.config, hub, backend_type)
780
781 ret = self.req.get(url + '/calibration')
782 if not bool(ret):
783 ret = {}
784 else:
785 ret["backend"] = backend_type
786 return ret
787
788 def backend_parameters(self, backend='ibmqx4', hub=None, access_token=None, user_id=None):
789 """
790 Get the parameters of calibration of a real chip
791 """
792 if access_token:
793 self.req.credential.set_token(access_token)
794 if user_id:
795 self.req.credential.set_user_id(user_id)
796 if not self.check_credentials():
797 raise CredentialsError('credentials invalid')
798
799 backend_type = self._check_backend(backend, 'calibration')
800
801 if not backend_type:
802 raise BadBackendError(backend)
803
804 if backend_type in self.__names_backend_simulator:
805 ret = {}
806 return ret
807
808 url = get_backend_stats_url(self.config, hub, backend_type)
809
810 ret = self.req.get(url + '/parameters')
811 if not bool(ret):
812 ret = {}
813 else:
814 ret["backend"] = backend_type
815 return ret
816
817 def available_backends(self, hub=None, group=None, project=None,
818 access_token=None, user_id=None):
819 """
820 Get the backends available to use in the QX Platform
821 """
822 if access_token:
823 self.req.credential.set_token(access_token)
824 if user_id:
825 self.req.credential.set_user_id(user_id)
826 if not self.check_credentials():
827 raise CredentialsError('credentials invalid')
828 else:
829
830 url = get_backend_url(self.config, hub, group, project)
831
832 ret = self.req.get(url)
833 if (ret is not None) and (isinstance(ret, dict)):
834 return []
835 return [backend for backend in ret
836 if backend.get('status') == 'on']
837
838 def api_version(self):
839 """
840 Get the API Version of the QX Platform
841 """
842 return self.req.get('/version')
843
844
845 class ApiError(Exception):
846 """
847 IBMQConnector API error handling base class.
848 """
849 def __init__(self, usr_msg=None, dev_msg=None):
850 """
851 Args:
852 usr_msg (str): Short user facing message describing error.
853 dev_msg (str or None): More detailed message to assist
854 developer with resolving issue.
855 """
856 Exception.__init__(self, usr_msg)
857 self.usr_msg = usr_msg
858 self.dev_msg = dev_msg
859
860 def __repr__(self):
861 return repr(self.dev_msg)
862
863 def __str__(self):
864 return str(self.usr_msg)
865
866
867 class BadBackendError(ApiError):
868 """
869 Unavailable backend error.
870 """
871 def __init__(self, backend):
872 """
873 Args:
874 backend (str): name of backend.
875 """
876 usr_msg = ('Could not find backend "{0}" available.').format(backend)
877 dev_msg = ('Backend "{0}" does not exist. Please use '
878 'available_backends to see options').format(backend)
879 ApiError.__init__(self, usr_msg=usr_msg,
880 dev_msg=dev_msg)
881
882
883 class CredentialsError(ApiError):
884 """Exception associated with bad server credentials."""
885 pass
886
887
888 class RegisterSizeError(ApiError):
889 """Exception due to exceeding the maximum number of allowed qubits."""
890 pass
891
[end of qiskit/backends/ibmq/api/ibmqconnector.py]
[start of qiskit/backends/ibmq/ibmqprovider.py]
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2018, IBM.
4 #
5 # This source code is licensed under the Apache License, Version 2.0 found in
6 # the LICENSE.txt file in the root directory of this source tree.
7
8 """Provider for remote IBMQ backends with admin features."""
9
10 import warnings
11 from collections import OrderedDict
12
13 from qiskit.backends import BaseProvider
14
15 from .credentials._configrc import remove_credentials
16 from .credentials import (Credentials,
17 read_credentials_from_qiskitrc, store_credentials, discover_credentials)
18 from .ibmqaccounterror import IBMQAccountError
19 from .ibmqsingleprovider import IBMQSingleProvider
20
21 QE_URL = 'https://quantumexperience.ng.bluemix.net/api'
22
23
24 class IBMQProvider(BaseProvider):
25 """Provider for remote IBMQ backends with admin features.
26
27 This class is the entry point for handling backends from IBMQ, allowing
28 using different accounts.
29 """
30 def __init__(self):
31 super().__init__()
32
33 # dict[credentials_unique_id: IBMQSingleProvider]
34 # This attribute stores a reference to the different accounts. The
35 # keys are tuples (hub, group, project), as the convention is that
36 # that tuple uniquely identifies a set of credentials.
37 self._accounts = OrderedDict()
38
39 def backends(self, name=None, filters=None, **kwargs):
40 """Return all backends accessible via IBMQ provider, subject to optional filtering.
41
42 Args:
43 name (str): backend name to filter by
44 filters (callable): more complex filters, such as lambda functions
45 e.g. IBMQ.backends(filters=lambda b: b.configuration['n_qubits'] > 5)
46 kwargs: simple filters specifying a true/false criteria in the
47 backend configuration or backend status or provider credentials
48 e.g. IBMQ.backends(n_qubits=5, operational=True, hub='internal')
49
50 Returns:
51 list[IBMQBackend]: list of backends available that match the filter
52
53 Raises:
54 IBMQAccountError: if no account matched the filter.
55 """
56 # pylint: disable=arguments-differ
57
58 # Special handling of the credentials filters: match and prune from kwargs
59 credentials_filter = {}
60 for key in ['token', 'url', 'hub', 'group', 'project', 'proxies', 'verify']:
61 if key in kwargs:
62 credentials_filter[key] = kwargs.pop(key)
63 providers = [provider for provider in self._accounts.values() if
64 self._credentials_match_filter(provider.credentials,
65 credentials_filter)]
66
67 # Special handling of the `name` parameter, to support alias resolution.
68 if name:
69 aliases = self.aliased_backend_names()
70 aliases.update(self.deprecated_backend_names())
71 name = aliases.get(name, name)
72
73 # Aggregate the list of filtered backends.
74 backends = []
75 for provider in providers:
76 backends = backends + provider.backends(
77 name=name, filters=filters, **kwargs)
78
79 return backends
80
81 @staticmethod
82 def deprecated_backend_names():
83 """Returns deprecated backend names."""
84 return {
85 'ibmqx_qasm_simulator': 'ibmq_qasm_simulator',
86 'ibmqx_hpc_qasm_simulator': 'ibmq_qasm_simulator',
87 'real': 'ibmqx1'
88 }
89
90 @staticmethod
91 def aliased_backend_names():
92 """Returns aliased backend names."""
93 return {
94 'ibmq_5_yorktown': 'ibmqx2',
95 'ibmq_5_tenerife': 'ibmqx4',
96 'ibmq_16_rueschlikon': 'ibmqx5',
97 'ibmq_20_austin': 'QS1_1'
98 }
99
100 def enable_account(self, token, url=QE_URL, **kwargs):
101 """Authenticate a new IBMQ account and add for use during this session.
102
103 Login into Quantum Experience or IBMQ using the provided credentials,
104 adding the account to the current session. The account is not stored
105 in disk.
106
107 Args:
108 token (str): Quantum Experience or IBM Q API token.
109 url (str): URL for Quantum Experience or IBM Q (for IBM Q,
110 including the hub, group and project in the URL).
111 **kwargs (dict):
112 * proxies (dict): Proxy configuration for the API.
113 * verify (bool): If False, ignores SSL certificates errors
114 """
115 credentials = Credentials(token, url, **kwargs)
116
117 self._append_account(credentials)
118
119 def save_account(self, token, url=QE_URL, **kwargs):
120 """Save the account to disk for future use.
121
122 Login into Quantum Experience or IBMQ using the provided credentials,
123 adding the account to the current session. The account is stored in
124 disk for future use.
125
126 Args:
127 token (str): Quantum Experience or IBM Q API token.
128 url (str): URL for Quantum Experience or IBM Q (for IBM Q,
129 including the hub, group and project in the URL).
130 **kwargs (dict):
131 * proxies (dict): Proxy configuration for the API.
132 * verify (bool): If False, ignores SSL certificates errors
133 """
134 credentials = Credentials(token, url, **kwargs)
135
136 # Check if duplicated credentials are already stored. By convention,
137 # we assume (hub, group, project) is always unique.
138 stored_credentials = read_credentials_from_qiskitrc()
139
140 if credentials.unique_id() in stored_credentials.keys():
141 warnings.warn('Credentials are already stored.')
142 else:
143 store_credentials(credentials)
144
145 def active_accounts(self):
146 """List all accounts currently in the session.
147
148 Returns:
149 list[dict]: a list with information about the accounts currently
150 in the session.
151 """
152 information = []
153 for provider in self._accounts.values():
154 information.append({
155 'token': provider.credentials.token,
156 'url': provider.credentials.url,
157 })
158
159 return information
160
161 def stored_accounts(self):
162 """List all accounts stored to disk.
163
164 Returns:
165 list[dict]: a list with information about the accounts stored
166 on disk.
167 """
168 information = []
169 stored_creds = read_credentials_from_qiskitrc()
170 for creds in stored_creds:
171 information.append({
172 'token': stored_creds[creds].token,
173 'url': stored_creds[creds].url
174 })
175
176 return information
177
178 def load_accounts(self, **kwargs):
179 """Load IBMQ accounts found in the system into current session,
180 subject to optional filtering.
181
182 Automatically load the accounts found in the system. This method
183 looks for credentials in the following locations, in order, and
184 returns as soon as credentials are found:
185
186 1. in the `Qconfig.py` file in the current working directory.
187 2. in the environment variables.
188 3. in the `qiskitrc` configuration file
189
190 Raises:
191 IBMQAccountError: if no credentials are found.
192 """
193 for credentials in discover_credentials().values():
194 if self._credentials_match_filter(credentials, kwargs):
195 self._append_account(credentials)
196
197 if not self._accounts:
198 raise IBMQAccountError('No IBMQ credentials found on disk.')
199
200 def disable_accounts(self, **kwargs):
201 """Disable accounts in the current session, subject to optional filtering.
202
203 The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
204 If no filter is passed, all accounts in the current session will be disabled.
205
206 Raises:
207 IBMQAccountError: if no account matched the filter.
208 """
209 disabled = False
210
211 # Try to remove from session.
212 current_creds = self._accounts.copy()
213 for creds in current_creds:
214 credentials = Credentials(current_creds[creds].credentials.token,
215 current_creds[creds].credentials.url)
216 if self._credentials_match_filter(credentials, kwargs):
217 del self._accounts[credentials.unique_id()]
218 disabled = True
219
220 if not disabled:
221 raise IBMQAccountError('No matching account to disable in current session.')
222
223 def delete_accounts(self, **kwargs):
224 """Delete saved accounts from disk, subject to optional filtering.
225
226 The filter kwargs can be `token`, `url`, `hub`, `group`, `project`.
227 If no filter is passed, all accounts will be deleted from disk.
228
229 Raises:
230 IBMQAccountError: if no account matched the filter.
231 """
232 deleted = False
233
234 # Try to delete from disk.
235 stored_creds = read_credentials_from_qiskitrc()
236 for creds in stored_creds:
237 credentials = Credentials(stored_creds[creds].token,
238 stored_creds[creds].url)
239 if self._credentials_match_filter(credentials, kwargs):
240 remove_credentials(credentials)
241 deleted = True
242
243 if not deleted:
244 raise IBMQAccountError('No matching account to delete from disk.')
245
246 def _append_account(self, credentials):
247 """Append an account with the specified credentials to the session.
248
249 Args:
250 credentials (Credentials): set of credentials.
251
252 Returns:
253 IBMQSingleProvider: new single-account provider.
254 """
255 # Check if duplicated credentials are already in use. By convention,
256 # we assume (hub, group, project) is always unique.
257 if credentials.unique_id() in self._accounts.keys():
258 warnings.warn('Credentials are already in use.')
259
260 single_provider = IBMQSingleProvider(credentials, self)
261 self._accounts[credentials.unique_id()] = single_provider
262
263 return single_provider
264
265 def _credentials_match_filter(self, credentials, filter_dict):
266 """Return True if the credentials match a filter.
267
268 These filters apply on properties of a Credentials object:
269 token, url, hub, group, project, proxies, verify
270 Any other filter has no effect.
271
272 Args:
273 credentials (Credentials): IBMQ credentials object
274 filter_dict (dict): dictionary of filter conditions
275
276 Returns:
277 bool: True if the credentials meet all the filter conditions
278 """
279 return all(getattr(credentials, key_, None) == value_ for
280 key_, value_ in filter_dict.items())
281
[end of qiskit/backends/ibmq/ibmqprovider.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 | 77dc51b93e7312bbff8f5acf7d8242232bd6624f | credentials failed for qiskit ver 0.6.1
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->
### Informations
- **Qiskit Terra version**: 0.6.1
- **Python version**: 3.7.0
- **Operating system**:MAC OSX 10.13.6
### What is the current behavior?
After I acquired fresh token from https://quantumexperience.ng.bluemix.net/qx/account/advanced
IBMQ.load_accounts() fails.
### Steps to reproduce the problem
```
from qiskit import IBMQ
myToken='b6abe11442c9a...'
IBMQ.save_account(myToken)
IBMQ.load_accounts()
```
Results with
```
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/site-packages/qiskit/backends/ibmq/ibmqsingleprovider.py", line 71, in _authenticate
credentials.verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 478, in __init__
self.req = _Request(token, config=config, verify=verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 253, in __init__
ntlm_credentials=self.ntlm_credentials)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 95, in __init__
self.obtain_token(config=self.config)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 159, in obtain_token
raise CredentialsError('error during login: %s' % error_message)
IBMQuantumExperience.IBMQuantumExperience.CredentialsError: error during login: Wrong user or password, check your credentials.
```
### What is the expected behavior?
Would be better if IBMQ.load_accounts() accepted me. All worked well w/ ver 0.5.
### Suggested solutions
| Can you try enable_account or regenerating the token. Your code should work. If you type `IBMQ.stored_accounts()` do you see the account.
@pacomf I can confirm this has happened to me today as well.
I cant reproduce the bug, i regenerate my APIToken and it works fine using qiskit terra... is it still happening? Can you send me more details?
It happened for about 5 hours on the weekend. However, @nonhermitian could run at the same time and then it started working again.
Mmmm, maybe an issue with the API... we will investigate it
I will add that, when it happened to me, I could log into some accounts and not others.
Hi @jaygambetta,
your tip helped. IBMQ.stored_accounts() has returned some old token, not the new one.
Looks like IBMQ.save_account(myToken) is unable to replace token if it exist - I leave it to you to decide if it is a bug or a feature.
My hack around it is to execute first: IBMQ.delete_accounts()
to clear my old token. So this sequence always works:
`
IBMQ.delete_accounts()
myToken='b6abe11442c9a...'
IBMQ.save_account(myToken)
IBMQ.load_accounts()
`
I can move on, closing thus ticket.
Thanks for help
Jan
Let's leave this open and investigate whether there's a bug with `IBMQ.save_account()` re-writing old tokens.
@diego-plan9 can you please have a look?
Yes - thanks @balewski for the information, which is spot on - currently, `IBMQ.save_account()` will just print a warning and do nothing else if old credentials are present:
https://github.com/Qiskit/qiskit-terra/blob/master/qiskit/backends/ibmq/ibmqprovider.py#L140-L143
> Looks like IBMQ.save_account(myToken) is unable to replace token if it exist - I leave it to you to decide if it is a bug or a feature.
Actually ... I can't decide if it is a bug or a feature either! :thinking: In the original draft implementation, the `.save_account()` (`.add_account()` by that time) method was [raising an Exception](https://github.com/Qiskit/qiskit-terra/blob/746245e29c5cadc44dc37851b19a4150b4e86cd8/qiskit/backends/ibmq/ibmqprovider.py#L111) in the case of trying to store a duplicate account. This was later changed to a warning, I'm unsure if by design and as a hard requisite from Jupyter-users needs, or also related to the slight tuning of the method functionality (ie. not authenticating during the call, just storing in disk). So I'm actually de-assigning myself, as probably the rest of the team has a more fresh view of the design decisions related to #1000.
I think we have several options:
* consider that not overwriting and raising a warning is indeed the desired behavior: the main drawback is that the warning might be easy to miss (and was probably the source of confusion in this issue).
* tune the method a bit in order to accept an `overwrite=True` optional parameter or a similar approach: the `credentials` module already has the needed parts in place, the main drawback would be that we touch a bit the public API.
* be a bit more restrictive and promote the warning back to an exception: it might affect users running the method twice and already used to not raising a warning (ie. maybe notebook users).
One way or the other, I think we need to make sure that the flow for updating an existing stored token is a bit smoother than the delete-save workaround proposed by @balewski, as it seems a relatively common use case.
From external user perspective:
It happens rather often that the ibmq_16_melbourne or even sometimes ibmqx4 does not accept the job, throws some 'general error', despite your web-page says both hardwares are operational.
Then, it is natural to (wrongly?) guess perhaps my token is invalid.
Then, I'd ask for a new token and try to use it - hoping it will help.
For such train of though the natural solution is assume 'user knows what he wants'. If user wants to replace the token by calling save_account(), just replace it. You can issue a warning that there was an old token (still valid), but why not just replace token each time user calls IBMQ.save_account(myToken) ?
Would this have any negative effect on your end?
Thanks
Jan
I think save_account should not raise an exception. Overwriting is not bad behavior. Similar to overwriting a key in a dict or something. Should just work.
@ajavadia is there an update.
Hi,
there is some inconsistency between the devices status you show here:
https://quantumexperience.ng.bluemix.net/qx/account/advanced
and actual avaliability.
At this moment, both ibmqx4 and ibmq_16_melbourne are reported to work.
However,. when I try to submit my circuit using Qiskit ver: 0.6.1 I get the error below for either.
Got a 400 code response to https://quantumexperience.ng.bluemix.net/api/Jobs?access_token=VCgYWnMUUBaYeT5gSmGO14cX93Foo4rccsLUVvIjf3bwYEZNjxlDcRmPArS2wZ25: {"error":{"status":400,"message":"Generic error","code":"GENERIC_ERROR"}}
Note, my token is correct, because I can submit the circuit to your simulator
'backend': 'ibmq_qasm_simulator',
'jobId2': '1814808',
'startTime': '2018-11-09 17:53:28'}
Can you have a look ?
Thanks
Jan | 2018-11-19T08:27:15Z | <patch>
diff --git a/qiskit/backends/ibmq/credentials/_configrc.py b/qiskit/backends/ibmq/credentials/_configrc.py
--- a/qiskit/backends/ibmq/credentials/_configrc.py
+++ b/qiskit/backends/ibmq/credentials/_configrc.py
@@ -9,6 +9,7 @@
Utilities for reading and writing credentials from and to configuration files.
"""
+import warnings
import os
from ast import literal_eval
from collections import OrderedDict
@@ -116,15 +117,17 @@ def store_credentials(credentials, overwrite=False, filename=None):
location is used (`HOME/.qiskit/qiskitrc`).
Raises:
- QISKitError: If credentials already exists and overwrite=False; or if
- the account_name could not be assigned.
+ QISKitError: if the account_name could not be assigned.
"""
# Read the current providers stored in the configuration file.
filename = filename or DEFAULT_QISKITRC_FILE
stored_credentials = read_credentials_from_qiskitrc(filename)
+ # Check if duplicated credentials are already stored. By convention,
+ # we assume (hub, group, project) is always unique.
if credentials.unique_id() in stored_credentials and not overwrite:
- raise QISKitError('Credentials already present and overwrite=False')
+ warnings.warn('Credentials already present. Set overwrite=True to overwrite.')
+ return
# Append and write the credentials to file.
stored_credentials[credentials.unique_id()] = credentials
diff --git a/qiskit/backends/ibmq/credentials/credentials.py b/qiskit/backends/ibmq/credentials/credentials.py
--- a/qiskit/backends/ibmq/credentials/credentials.py
+++ b/qiskit/backends/ibmq/credentials/credentials.py
@@ -22,7 +22,7 @@ class Credentials(object):
"""IBM Q account credentials.
Note that, by convention, two credentials that have the same hub, group
- and token (regardless of other attributes) are considered equivalent.
+ and project (regardless of other attributes) are considered equivalent.
The `unique_id()` returns the unique identifier.
"""
diff --git a/qiskit/backends/ibmq/ibmqprovider.py b/qiskit/backends/ibmq/ibmqprovider.py
--- a/qiskit/backends/ibmq/ibmqprovider.py
+++ b/qiskit/backends/ibmq/ibmqprovider.py
@@ -116,7 +116,7 @@ def enable_account(self, token, url=QE_URL, **kwargs):
self._append_account(credentials)
- def save_account(self, token, url=QE_URL, **kwargs):
+ def save_account(self, token, url=QE_URL, overwrite=False, **kwargs):
"""Save the account to disk for future use.
Login into Quantum Experience or IBMQ using the provided credentials,
@@ -127,20 +127,13 @@ def save_account(self, token, url=QE_URL, **kwargs):
token (str): Quantum Experience or IBM Q API token.
url (str): URL for Quantum Experience or IBM Q (for IBM Q,
including the hub, group and project in the URL).
+ overwrite (bool): overwrite existing credentials.
**kwargs (dict):
* proxies (dict): Proxy configuration for the API.
* verify (bool): If False, ignores SSL certificates errors
"""
credentials = Credentials(token, url, **kwargs)
-
- # Check if duplicated credentials are already stored. By convention,
- # we assume (hub, group, project) is always unique.
- stored_credentials = read_credentials_from_qiskitrc()
-
- if credentials.unique_id() in stored_credentials.keys():
- warnings.warn('Credentials are already stored.')
- else:
- store_credentials(credentials)
+ store_credentials(credentials, overwrite=overwrite)
def active_accounts(self):
"""List all accounts currently in the session.
</patch> | [] | [] | |||
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_13K"
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_13K
includes a formatting of each instance using Pyserini's BM25 retrieval as described in the paper. The code context size limit is 13,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.
- Downloads last month
- 224