Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_init(self):
"""Test initialization"""
mat4 = np.eye(4) / 2.0
chan = PTM(mat4)
assert_allclose(chan.data, mat4)
self.assertEqual(chan.dim, (2, 2))
mat16 = np.eye(16) / 4
chan = PTM(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
# Wrong input or output dims should raise exception
self.assertRaises(QiskitError, PTM, mat16, input_dims=2, output_dims=4)
# Non multi-qubit dimensions should raise exception
self.assertRaises(
QiskitError, PTM, np.eye(6) / 2, input_dims=3, output_dims=2)
def test_compose_except(self):
"""Test compose different dimension exception"""
self.assertRaises(QiskitError,
Choi(np.eye(4)).compose, Choi(np.eye(8)))
self.assertRaises(QiskitError, Choi(np.eye(4)).compose, 2)
def test_superop_to_operator(self):
"""Test SuperOp to Operator transformation."""
for mat, sop in zip(self.unitary_mat, self.unitary_sop):
chan1 = Operator(mat)
chan2 = Operator(SuperOp(sop))
self.assertTrue(
matrix_equal(chan2.data, chan1.data, ignore_phase=True))
self.assertRaises(QiskitError, Operator, SuperOp(self.depol_sop(0.5)))
chan = Choi(mat8, input_dims=4)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (4, 2))
chan = Choi(mat8, input_dims=2)
assert_allclose(chan.data, mat8)
self.assertEqual(chan.dim, (2, 4))
mat16 = np.eye(16) / 4
chan = Choi(mat16)
assert_allclose(chan.data, mat16)
self.assertEqual(chan.dim, (4, 4))
# Wrong input or output dims should raise exception
self.assertRaises(
QiskitError, Choi, mat8, input_dims=[4], output_dims=[4])
"""Return the preparation circuit on the given qubit
Args:
op: The name of the preparation operator
qubit: The qubit on which to apply the preparation operator
Raises:
QiskitError: In case no preparation data is present in the basis
or **qubit** is not Qubit
ValueError: if **op** is not a n name of a preparation operator
in the basis
Returns:
The preparation circuit
"""
# Error Checking
if self.preparation is False:
raise QiskitError("{} is not a preparation basis".format(
self._name))
if not isinstance(qubit, Qubit):
raise QiskitError('Input must be a qubit in a QuantumRegister')
if op not in self._preparation_labels:
msg = "Invalid {0} preparation operator label".format(self._name)
error = "'{}' not in {}".format(op, self._preparation_labels)
raise ValueError("{0}: {1}".format(msg, error))
return self._preparation_circuit(op, qubit)
if not isinstance(new_backend_result, list):
new_backend_result = [new_backend_result]
for result in new_backend_result:
self._result_list.append(result)
# update the number of trials *if* new ones
# added.
for qvcirc in result.results:
ntrials_circ = int(qvcirc.header.name.split('_')[-1])
if (ntrials_circ+1) > self._ntrials:
self._ntrials = ntrials_circ+1
if qvcirc.header.name not in self._heavy_output_prob_ideal:
raise QiskitError('Ideal distribution '
'must be loaded first')
if rerun_fit:
self.calc_data()
self.calc_statistics()
"""
# check controls
if isinstance(q_controls, QuantumRegister):
control_qubits = [qb for qb in q_controls]
elif isinstance(q_controls, list):
control_qubits = q_controls
else:
raise QiskitError('The mcry gate needs a list of qubits or a quantum '
'register for controls.')
# check target
if isinstance(q_target, Qubit):
target_qubit = q_target
else:
raise QiskitError('The mcry gate needs a single qubit as target.')
# check ancilla
if q_ancillae is None:
ancillary_qubits = []
elif isinstance(q_ancillae, QuantumRegister):
ancillary_qubits = [qb for qb in q_ancillae]
elif isinstance(q_ancillae, list):
ancillary_qubits = q_ancillae
else:
raise QiskitError('The mcry gate needs None or a list of qubits or a '
'quantum register for ancilla.')
all_qubits = control_qubits + [target_qubit] + ancillary_qubits
self._check_qargs(all_qubits)
self._check_dups(all_qubits)
if self.num_traps < 3:
QiskitError("ERROR: run the protocol with at least 3 traps")
allcounts = []
for ind, postp in enumerate(postp_list):
# Classical postprocessing
# check single shot and extract string
counts = results.get_counts(ind)
counts = QOTPCorrectCounts(counts, postp)
shots = 0
countstring = None
for countstring, val in counts.items():
shots += val
if shots != 1 or countstring is None:
QiskitError("ERROR: not single shot data")
allcounts.append(countstring)
for k, count in enumerate(allcounts):
if k != v_zero:
# Check if trap returns correct output
if count != '0' * len(count):
self.flag = 'rejected'
else:
output_target = count
if self.flag == 'accepted':
self.N_acc += 1
self.outputs.append(output_target)
# Check if there are already measurements in the circuit
for op in circuit:
if isinstance(op, Measure):
logger.warning('WARNING: circuit already contains measurements')
if isinstance(op, Reset):
logger.warning('WARNING: circuit contains resets')
# Load built-in circuit functions
if callable(meas_basis):
measurement = meas_basis
else:
measurement = default_basis(meas_basis)
if isinstance(measurement, TomographyBasis):
if measurement.measurement is not True:
raise QiskitError("Invalid measurement basis")
measurement = measurement.measurement_circuit
if callable(prep_basis):
preparation = prep_basis
else:
preparation = default_basis(prep_basis)
if isinstance(preparation, TomographyBasis):
if preparation.preparation is not True:
raise QiskitError("Invalid preparation basis")
preparation = preparation.preparation_circuit
# Check we have circuit functions defined
if measurement is None and meas_labels is not None:
raise ValueError("Measurement basis is not specified.")
if preparation is None and prep_labels is not None:
raise ValueError("Preparation basis is not specified.")
if isinstance(measured_qubits, (list, tuple)):
# Unroll list of registers
if isinstance((measured_qubits[0]), int):
measured_qubits = [circuit.qubits[i] for i in measured_qubits]
meas_qubits = _format_registers(*measured_qubits)
else:
meas_qubits = _format_registers(measured_qubits)
if isinstance(prepared_qubits, (list, tuple)):
# Unroll list of registers
if isinstance(prepared_qubits[0], int):
prepared_qubits = [circuit.qubits[i] for i in prepared_qubits]
prep_qubits = _format_registers(*prepared_qubits)
else:
prep_qubits = _format_registers(prepared_qubits)
if len(prep_qubits) != len(meas_qubits):
raise QiskitError(
"prepared_qubits and measured_qubits are different length.")
num_qubits = len(meas_qubits)
meas_qubit_registers = set(q.register for q in meas_qubits)
# Check qubits being measured are defined in circuit
for reg in meas_qubit_registers:
if reg not in circuit.qregs:
logger.warning('WARNING: circuit does not contain '
'measured QuantumRegister: %s', reg.name)
prep_qubit_registers = set(q.register for q in prep_qubits)
# Check qubits being measured are defined in circuit
for reg in prep_qubit_registers:
if reg not in circuit.qregs:
logger.warning('WARNING: circuit does not contain '
'prepared QuantumRegister: %s', reg.name)