def test_density_matrix_snapshot_ideal(self): seed = 500 op = qi.random_unitary(8, seed=seed) circ = QuantumCircuit(3) circ.append(op, [0, 1, 2]) method = self.BACKEND_OPTS.get('method', 'automatic') label = 'density_matrix' snap_qargs = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0], [0, 1], [1, 0], [0, 2], [2, 0], [1, 2], [2, 1], [0], [1], [2]] evolve_qargs = [[0, 1, 2], [0, 2, 1], [1, 0, 2], [2, 0, 1], [1, 2, 0], [2, 1, 0], [0, 1, 2], [1, 0, 2], [0, 2, 1], [1, 2, 0], [2, 0, 1], [2, 1, 0], [0, 1, 2], [1, 0, 2], [2, 1, 0]] for squbits, equbits in zip(snap_qargs, evolve_qargs): with self.subTest(msg='qubits={}'.format(squbits)): num_qubits = len(squbits) tmp = circ.copy() tmp.append(Snapshot(label, 'density_matrix', num_qubits), squbits) result = execute(tmp, self.SIMULATOR, backend_options=self.BACKEND_OPTS).result() if method not in QasmSnapshotDensityMatrixTests.SUPPORTED_QASM_METHODS: self.assertFalse(result.success) else: self.assertSuccess(result) snapshots = result.data(0)['snapshots']['density_matrix'] value = qi.DensityMatrix(snapshots[label][0]['value']) target = qi.DensityMatrix.from_label(3 * '0').evolve( circ, equbits) if num_qubits == 2: target = qi.partial_trace(target, [2]) elif num_qubits == 1: target = qi.partial_trace(target, [1, 2]) self.assertEqual(value, target)
def snapshot_probabilities(self, label, qubits=None, variance=False, params=None): """Take a snapshot of the internal simulator representation. Works on specified qubits or the full register, and prevents reordering (like barrier). Args: label (str): a snapshot label to report the result qubits (list or None): the qubits to apply snapshot to [Default: None] variance (bool): set snapshot_type to 'probabilities' or ' probabilities_with_variance' [Default: False] params (list or None): the parameters for snapshot_type [Default: None] Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ snapshot_register = Snapshot.define_snapshot_register(self, label, qubits) return self.append( SnapshotProbabilites(label, num_qubits=len(snapshot_register), variance=variance, params=params), snapshot_register)
def snapshot_statevector(self, label): """Take a statevector snapshot of the simulator state. Args: label (str): a snapshot label to report the result. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. Additional Information: This snapshot is always performed on all qubits in a circuit. The number of qubits parameter specifies the size of the instruction as a barrier and should be set to the number of qubits in the circuit. """ # Statevector snapshot acts as a barrier across all qubits in the # circuit snapshot_register = Snapshot.define_snapshot_register(self, label) return self.append( SnapshotStatevector(label, num_qubits=len(snapshot_register)), snapshot_register)
def snapshot_expectation_value(self, label, op, qubits, single_shot=False, variance=False): """Take a snapshot of expectation value <O> of an Operator. Args: label (str): a snapshot label to report the result op (Operator): operator to snapshot qubits (list): the qubits to snapshot. single_shot (bool): return list for each shot rather than average [Default: False] variance (bool): compute variance of probabilities [Default: False] Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. """ snapshot_register = Snapshot.define_snapshot_register(self, label, qubits) return self.append( SnapshotExpectationValue(label, op, single_shot=single_shot, variance=variance), snapshot_register)
def hobo_qubo_mixer_measurement(hamildict, noise_model, angles, diag_vals, ps_end=False, mid_measure=None): n = int(np.max(hamildict[:, 1])) qr = QuantumRegister(n**2) main_circuit = QuantumCircuit(qr) times = len(angles) qubo_theta = angles[0:int(times / 2)] mixer_phi = angles[int(times / 2):] main_circuit += hadamards_position(n, qr) # Merging circuits for theta, phi in zip(qubo_theta, mixer_phi): main_circuit += hobo2qubo(n, qr) + qubo_circuit_simplified( hamildict, qr, theta) + hobo2qubo(n, qr).inverse() main_circuit += make_mixer(n, qr, phi) if mid_measure == 'no-ps': main_circuit += kraus_gates(qr, n, False) elif mid_measure == 'ps': main_circuit += kraus_gates(qr, n, True) else: pass if ps_end == 'end': main_circuit += kraus_gates(qr, n, True) main_circuit += hobo2qubo(n, qr) # Swap all for i in range(int(n**2 / 2)): main_circuit.swap(i, n**2 - 1 - i) #Preparation of Density-Matrix: backend = QasmSimulator(method='density_matrix', noise_model=noise_model, basis_gates=['cx', 'u1', 'u2', 'u3', 'kraus']) main_circuit.append(Snapshot('ss', 'density_matrix', n**2), qr) job = execute(main_circuit, backend=backend) result = job.result().results[0].to_dict( )['data']['snapshots']['density_matrix']['ss'][0]['value'] dm = np.asmatrix(result) #finds probability prob = np.trace(dm.real) #find mean energy mean_energy = np.real(np.sum(np.diag(dm) * diag_vals)) / prob max_energy = max(diag_vals) min_energy = min(diag_vals) energy = (mean_energy - min_energy) / (max_energy - min_energy) return energy, prob
def test_unitary_snap(self): """Test Unitary matrix snaps on a random circuit""" backend = UnitarySimulator() backend_opts = {} circ = QuantumCircuit(4) circ.append(qi.random_unitary(2**4), [0, 1, 2, 3]) circ.append(Snapshot("final", "unitary", 4), [0, 1, 2, 3]) qobj = assemble(circ, backend=backend) aer_input = backend._format_qobj(qobj, self.BACKEND_OPTS, None) aer_output = backend._controller(aer_input) self.assertIsInstance(aer_output, dict) self.assertTrue(aer_output['success']) snaps = aer_output['results'][0]['data']['snapshots']['unitary'][ 'final'] self.assertTrue(all([isinstance(arr, np.ndarray) for arr in snaps]))
def test_unitary_snap(self): """Test Unitary matrix snaps on a random circuit""" backend = UnitarySimulator() target = qi.random_unitary(2 ** 4, seed=111) circ = QuantumCircuit(4) circ.append(target, [0, 1, 2, 3]) circ.append(Snapshot("final", "unitary", 4), [0, 1, 2, 3]) qobj = assemble(circ, backend=backend, shots=1) job = backend.run(qobj) result = job.result() self.assertSuccess(result) snaps = result.data(0)['snapshots']['unitary']['final'] for arr in snaps: self.assertTrue(isinstance(arr, np.ndarray)) self.assertEqual(qi.Operator(arr), target)
def snapshot_expectation_value(self, label, op, qubits=None, params=None): """Take a snapshot of expectation value <M> of some Operator M. Works on all qubits, and prevents reordering (like barrier). Args: label (str): a snapshot label to report the result op (Operator): operator to snapshot qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ snapshot_register = Snapshot.define_snapshot_register(self, label, qubits) return self.append(SnapshotExpectationValue(label, op, params=params), snapshot_register)
def snapshot_stabilizer(self, label, qubits=None, params=None): """Take a snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). Args: label (str): a snapshot label to report the result qubits (list or None): the qubits to apply snapshot to [Default: None]. params (list or None): the parameters for snapshot_type [Default: None]. Returns: QuantumCircuit: with attached command Raises: ExtensionError: malformed command """ snapshot_register = Snapshot.define_snapshot_register(self, label, qubits) return self.append( SnapshotStabilizer(label, num_qubits=len(snapshot_register), params=params), snapshot_register)
def snapshot_density_matrix(self, label, qubits=None): """Take a density matrix snapshot of simulator state. Args: label (str): a snapshot label to report the result qubits (list or None): the qubits to apply snapshot to. If None all qubits will be snapshot [Default: None]. Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. """ snapshot_register = Snapshot.define_snapshot_register(self, label, qubits) return self.append( SnapshotDensityMatrix(label, num_qubits=len(snapshot_register)), snapshot_register)
def snapshot_probabilities(self, label, qubits, variance=False): """Take a probability snapshot of the simulator state. Args: label (str): a snapshot label to report the result qubits (list): the qubits to snapshot. variance (bool): compute variance of probabilities [Default: False] Returns: QuantumCircuit: with attached instruction. Raises: ExtensionError: if snapshot is invalid. """ snapshot_register = Snapshot.define_snapshot_register(self, label, qubits) return self.append( SnapshotProbabilities(label, num_qubits=len(snapshot_register), variance=variance), snapshot_register)