def test_save_statevector_conditional(self, method, device): """Test conditional save statevector instruction""" backend = self.backend(method=method, device=device) # Stabilizer test circuit # Add save to circuit label = 'state' circ = QuantumCircuit(2) circ.h(0) circ.sdg(0) circ.cx(0, 1) circ.measure_all() circ.save_statevector(label=label, conditional=True) # Target statevector target = {'0x0': qi.Statevector([1, 0, 0, 0]), '0x3': qi.Statevector([0, 0, 0, -1j])} # Run result = backend.run(transpile( circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) for key, vec in simdata[label].items(): self.assertIn(key, target) self.assertEqual(qi.Statevector(vec), target[key])
def test_save_statevector(self, method, device): """Test save statevector instruction""" backend = self.backend(method=method, device=device) # Stabilizer test circuit circ = QuantumCircuit(3) circ.h(0) circ.sdg(0) circ.cx(0, 1) circ.cx(0, 2) # Target statevector target = qi.Statevector(circ) # Add save to circuit label = 'state' circ.save_statevector(label=label) # Run result = backend.run(transpile( circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) value = qi.Statevector(simdata[label]) self.assertEqual(value, target)
def test_save_statevector(self): """Test save statevector for instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state', 'extended_stabilizer' ] # Stabilizer test circuit circ = QuantumCircuit(3) circ.h(0) circ.sdg(0) circ.cx(0, 1) circ.cx(0, 2) # Target statevector target = qi.Statevector(circ) # Add save to circuit save_key = 'sv' circ.save_statevector(save_key) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) value = qi.Statevector(result.data(0)[save_key]) self.assertAlmostEqual(value, target)
def test_save_statevector_pershot(self, method, device): """Test pershot save statevector instruction""" backend = self.backend(method=method, device=device) # Stabilizer test circuit circ = QuantumCircuit(1) circ.x(0) circ.reset(0) circ.h(0) circ.sdg(0) # Target statevector target = qi.Statevector(circ) # Add save label = 'state' circ.save_statevector(label=label, pershot=True) # Run shots = 10 result = backend.run(transpile( circ, backend, optimization_level=0), shots=shots).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) value = simdata[label] self.assertEqual(len(value), shots) for vec in value: self.assertEqual(qi.Statevector(vec), target)
def test_exp_circuits_measurement_qubits(self, meas_qubits): """Test subset state tomography generation""" # Subsystem unitaries seed = 1111 nq = 3 ops = [qi.random_unitary(2, seed=seed + i) for i in range(nq)] # Preparation circuit circ = QuantumCircuit(nq) for i, op in enumerate(ops): circ.append(op, [i]) num_meas = len(meas_qubits) exp = StateTomography(circ, measurement_qubits=meas_qubits) tomo_circuits = exp.circuits() # Check correct number of circuits are generated self.assertEqual(len(tomo_circuits), 3**num_meas) # Check circuit metadata is correct for circ in tomo_circuits: meta = circ.metadata clbits = meta.get("clbits") self.assertEqual(clbits, list(range(num_meas)), msg="metadata clbits is incorrect") # Check analysis target is correct target_state = exp.analysis.options.target target_circ = QuantumCircuit(num_meas) for i, qubit in enumerate(meas_qubits): target_circ.append(ops[qubit], [i]) fid = qi.state_fidelity(target_state, qi.Statevector(target_circ)) self.assertGreater(fid, 0.99, msg="target_state is incorrect")
def test_save_amplitudes(self, params): """Test save_amplitudes instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state' ] # Stabilizer test circuit circ = QFT(3) # Target statevector target = qi.Statevector(circ).data[params] # Add save to circuit save_key = 'amps' circ.save_amplitudes(save_key, params) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) value = result.data(0)[save_key] self.assertTrue(np.allclose(value, target))
def statevector_simulator(self, output, threshold=1e-10, precision='double'): qc_copy = copy.deepcopy(self.qc) qc_copy.remove_final_measurements() simulator = StatevectorSimulator( precision=precision ) # When the size of quantum circuit is large, "single" is better. job = execute(qc_copy, simulator) result = job.result() statevector = result.get_statevector() final_result = quantum_info.Statevector(statevector) if output == 'statevector': return final_result if output == 'probabilities_distribution': dic = final_result.probabilities_dict() for key in list(dic.keys()): if dic[key] < threshold: # Cut off a floating point numerical error dic.pop(key) return dic
def test_save_expval_var_nonstabilizer_pauli(self, pauli): """Test Pauli expval_var for non-stabilizer circuit""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'extended_stabilizer' ] SEED = 7382 # Stabilizer test circuit state_circ = QuantumVolume(2, 1, seed=SEED) oper = qi.Operator(qi.Pauli(pauli)) state = qi.Statevector(state_circ) expval = state.expectation_value(oper).real variance = state.expectation_value(oper**2).real - expval**2 target = [expval, variance] # Snapshot circuit opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') circ = transpile(state_circ, basis_gates=['u1', 'u2', 'u3', 'cx', 'swap']) circ.save_expectation_value_variance(oper, [0, 1], label='expval') qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertTrue(allclose(value, target))
def test_qst_teleport(self): """Test subset state tomography generation""" # NOTE: This test breaks transpiler. I think it is a bug with # conditionals in Terra. # Teleport qubit 0 -> 2 backend = AerSimulator(seed_simulator=9000) exp = StateTomography(teleport_circuit(), measurement_qubits=[2]) expdata = exp.run(backend) self.assertExperimentDone(expdata) results = expdata.analysis_results() # Check result f_threshold = 0.95 # Check state is density matrix state = filter_results(results, "state").value self.assertTrue(isinstance(state, qi.DensityMatrix), msg="fitted state is not a density matrix") # Manually check fidelity fid = qi.state_fidelity(state, qi.Statevector([1, 0]), validate=False) self.assertGreater(fid, f_threshold, msg="fitted state fidelity is low")
def test_save_probabilities_dict(self, qubits): """Test save probabilities dict instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'stabilizer' ] circ = QuantumCircuit(3) circ.x(0) circ.h(1) circ.cx(1, 2) # Target probabilities state = qi.Statevector(circ) target = state.probabilities_dict(qubits) # Snapshot circuit label = 'probs' opts = self.BACKEND_OPTS.copy() circ = transpile(circ, self.SIMULATOR) circ.save_probabilities_dict(qubits, label) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = Counts(result.data(0)[label], memory_slots=len(qubits)) self.assertDictAlmostEqual(value, target)
def test_save_expval_nonstabilizer_pauli(self, pauli): """Test Pauli expval for non-stabilizer circuit""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state' ] SEED = 7382 # Stabilizer test circuit state_circ = QuantumVolume(2, 1, seed=SEED) oper = qi.Pauli(pauli) state = qi.Statevector(state_circ) target = state.expectation_value(oper).real.round(10) # Snapshot circuit opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') circ = transpile(state_circ, basis_gates=['u1', 'u2', 'u3', 'cx', 'swap']) circ.save_expectation_value('expval', oper, [0, 1]) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertAlmostEqual(value, target)
def test_save_expval_nonstabilizer_hermitian(self, qubits): """Test expval for non-stabilizer circuit and Hermitian operator""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state' ] SEED = 8124 # Stabilizer test circuit state = QuantumVolume(3, 1, seed=SEED) oper = qi.random_hermitian(4, traceless=True, seed=SEED) target = qi.Statevector(state).expectation_value(oper, qubits).real # Snapshot circuit opts = self.BACKEND_OPTS.copy() circ = transpile(state, self.SIMULATOR) circ.save_expectation_value('expval', oper, qubits) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertAlmostEqual(value, target)
def test_save_amplitudes_squared_nonclifford(self, params): """Test save_amplitudes_squared instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state' ] # Stabilizer test circuit circ = QFT(3) # Target statevector target = np.abs(qi.Statevector(circ).data[params]) ** 2 # Add save to circuit label = 'amps' circ.save_amplitudes_squared(params, label=label) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(label, data) value = result.data(0)[label] self.assertTrue(np.allclose(value, target))
def test_save_expval_stabilizer_hermitian(self, qubits): """Test expval for stabilizer circuit and Hermitian operator""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'stabilizer' ] SEED = 7123 # Stabilizer test circuit state_circ = qi.random_clifford(3, seed=SEED).to_circuit() oper = qi.random_hermitian(4, traceless=True, seed=SEED) state = qi.Statevector(state_circ) target = state.expectation_value(oper, qubits).real # Snapshot circuit opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') circ = transpile(state_circ, basis_gates=[ 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'cx', 'cz', 'swap']) circ.save_expectation_value('expval', oper, qubits) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertAlmostEqual(value, target)
def test_save_probabilities(self, qubits): """Test save probabilities instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'stabilizer' ] circ = QuantumCircuit(3) circ.x(0) circ.h(1) circ.cx(1, 2) # Target probabilities state = qi.Statevector(circ) target = state.probabilities(qubits) # Snapshot circuit key = 'probs' opts = self.BACKEND_OPTS.copy() circ = transpile(circ, self.SIMULATOR) circ.save_probabilities(key, qubits) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)[key] self.assertTrue(np.allclose(value, target))
def _target_quantum_state( cls, circuit: QuantumCircuit, measurement_qubits: Optional[Sequence[int]] = None): """Return the state tomography target""" # Check if circuit contains measure instructions # If so we cannot return target state circuit_ops = circuit.count_ops() if "measure" in circuit_ops: return None perm_circ = cls._permute_circuit(circuit, measurement_qubits=measurement_qubits) try: if "reset" in circuit_ops or "kraus" in circuit_ops or "superop" in circuit_ops: state = qi.DensityMatrix(perm_circ) else: state = qi.Statevector(perm_circ) except QiskitError: # Circuit couldn't be simulated return None total_qubits = circuit.num_qubits if measurement_qubits: num_meas = len(measurement_qubits) else: num_meas = total_qubits if num_meas == total_qubits: return state # Trace out non-measurement qubits tr_qargs = range(num_meas, total_qubits) return qi.partial_trace(state, tr_qargs)
def test_set_statevector(self, num_qubits): """Test SetStatevector for instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state' ] seed = 100 save_label = 'state' target = qi.random_statevector(2 ** num_qubits, seed=seed) circ = QuantumCircuit(num_qubits) circ.set_statevector(target) circ.save_statevector(label=save_label) # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_label, data) value = qi.Statevector(result.data(0)[save_label]) self.assertAlmostEqual(value, target)
def _test_save_amplitudes(self, circuit, params, amp_squared, **options): """Test save_amplitudes instruction""" backend = self.backend(**options) # Stabilizer test circuit circ = circuit.copy() # Target statevector target = qi.Statevector(circ).data[params] if amp_squared: target = np.abs(target) ** 2 # Add save to circuit label = 'amps' if amp_squared: circ.save_amplitudes_squared(params, label=label) else: circ.save_amplitudes(params, label=label) # Run result = backend.run(transpile( circ, backend, optimization_level=0), shots=1).result() self.assertTrue(result.success) simdata = result.data(0) self.assertIn(label, simdata) value = simdata[label] self.assertTrue(np.allclose(value, target))
def test_save_expval_stabilizer_pauli(self, pauli): """Test Pauli expval for stabilizer circuit""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'stabilizer' ] SEED = 5832 # Stabilizer test circuit state = qi.random_clifford(2, seed=SEED).to_circuit() oper = qi.Pauli(pauli) target = qi.Statevector(state).expectation_value(oper).real.round(10) # Snapshot circuit opts = self.BACKEND_OPTS.copy() circ = transpile(state, self.SIMULATOR) circ.save_expectation_value('expval', oper, [0, 1]) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertAlmostEqual(value, target)
def test_save_expval_var_stabilizer_pauli(self, pauli): """Test Pauli expval_var for stabilizer circuit""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state', 'stabilizer' ] SEED = 5832 # Stabilizer test circuit state_circ = qi.random_clifford(2, seed=SEED).to_circuit() oper = qi.Pauli(pauli) state = qi.Statevector(state_circ) expval = state.expectation_value(oper).real variance = state.expectation_value(oper ** 2).real - expval ** 2 target = [expval, variance] # Snapshot circuit opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') circ = transpile(state_circ, basis_gates=[ 'id', 'x', 'y', 'z', 'h', 's', 'sdg', 'cx', 'cz', 'swap']) circ.save_expectation_value_variance('expval', oper, [0, 1]) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertTrue(allclose(value, target))
def test_save_expval_var_nonstabilizer_hermitian(self, qubits): """Test expval_var for non-stabilizer circuit and Hermitian operator""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'density_matrix', 'density_matrix_gpu', 'density_matrix_thrust', 'matrix_product_state' ] SEED = 8124 # Stabilizer test circuit state_circ = QuantumVolume(3, 1, seed=SEED) oper = qi.random_hermitian(4, traceless=True, seed=SEED) state = qi.Statevector(state_circ) expval = state.expectation_value(oper, qubits).real variance = state.expectation_value(oper ** 2, qubits).real - expval ** 2 target = [expval, variance] # Snapshot circuit opts = self.BACKEND_OPTS.copy() method = opts.get('method', 'automatic') circ = transpile(state_circ, basis_gates=['u1', 'u2', 'u3', 'cx', 'swap']) circ.save_expectation_value_variance('expval', oper, qubits) qobj = assemble(circ) result = self.SIMULATOR.run(qobj, **opts).result() if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) value = result.data(0)['expval'] self.assertTrue(allclose(value, target))
def get_uniform(*args, **kwargs): QAOA = QuantumCircuit(len(config.V), len(config.V)) QAOA.h(range(len(config.V))) simulate = execute(QAOA, backend=config.backend) QAOA_results = simulate.result() # Evaluate the data from the simulator statevector = QAOA_results.get_statevector(decimals=3) vec = quantum_info.Statevector(statevector) return vec.to_dict().keys()
def trace_to_density_op(state: qk.DictStateFn, trace_over: List[int]) -> qkinfo.DensityMatrix: """ Take a state comprised on n qubits and get the trace of the system over the subsystems specified by a list of indices. Makes no assumption about the separability of the traced subsystems and gives a density matrix as a result. """ input_statevector = qkinfo.Statevector(state.to_matrix()) return qkinfo.partial_trace(input_statevector, trace_over)
def _test_gate(self, gate, gates_dict, **options): """Test standard gates.""" backend = self.backend(**options) gate_cls, num_angles, has_ctrl_qubits = gates_dict[gate] circuits = self.gate_circuits(gate_cls, num_angles=num_angles, has_ctrl_qubits=has_ctrl_qubits, rng=self.RNG) label = 'final' method = backend.options.method for circuit in circuits: if method == 'density_matrix': target = qi.DensityMatrix(circuit) circuit.save_density_matrix(label=label) state_fn = qi.DensityMatrix fidelity_fn = qi.state_fidelity elif method == 'stabilizer': target = qi.Clifford(circuit) circuit.save_stabilizer(label=label) state_fn = qi.Clifford.from_dict fidelity_fn = qi.process_fidelity elif method == 'unitary': target = qi.Operator(circuit) circuit.save_unitary(label=label) state_fn = qi.Operator fidelity_fn = qi.process_fidelity elif method == 'superop': target = qi.SuperOp(circuit) circuit.save_superop(label=label) state_fn = qi.SuperOp fidelity_fn = qi.process_fidelity else: target = qi.Statevector(circuit) circuit.save_statevector(label=label) state_fn = qi.Statevector fidelity_fn = qi.state_fidelity result = backend.run(transpile(circuit, backend, optimization_level=0), shots=1).result() # Check results success = getattr(result, 'success', False) self.assertTrue(success) data = result.data(0) self.assertIn(label, data) value = state_fn(data[label]) fidelity = fidelity_fn(target, value) self.assertGreater(fidelity, 0.9999)
def trace_dict_state(state: qk.DictStateFn, trace_over: List[int]) -> qk.DictStateFn: """ Take a state comprised on n qubits and get the trace of the system over the subsystems specified by a list of indices. Assumes state is separable as a DictStateFn can only represent pure states. """ input_statevector = qkinfo.Statevector(state.to_matrix()) traced_statevector = qkinfo.partial_trace(input_statevector, trace_over).to_statevector() return qk.DictStateFn(traced_statevector.to_dict())
def test_save_statevector_pershot_conditional(self): """Test pershot conditional save statevector instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state', 'extended_stabilizer' ] # Stabilizer test circuit circ = QuantumCircuit(1) circ.x(0) circ.reset(0) circ.h(0) circ.sdg(0) # Target statevector target = qi.Statevector(circ) # Add save save_key = 'sv' circ.save_statevector(save_key, pershot=True, conditional=True) circ.measure_all() # Run shots = 10 opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR, shots=shots) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) value = result.data(0)[save_key] self.assertIn('0x0', value) self.assertEqual(len(value['0x0']), shots) for vec in value['0x0']: self.assertAlmostEqual(qi.Statevector(vec), target)
def Qiskit_QAOA(beta, gamma, norm=False): if norm == True: graph = G_norm else: graph = G # preapre the quantum and classical resisters QAOA = QuantumCircuit(len(V), len(V)) # apply the layer of Hadamard gates to all qubits QAOA.h(range(len(V))) QAOA.barrier() for a in range(p): # apply the Ising type gates with angle gamma along the edges in E for edge in E: k = edge[0] l = edge[1] w = gamma[a] * graph[k][l]['weight'] #w = gamma[a]*G_norm[k][l]['weight'] #sigma = 1.0 #t_w = G[k][l]['weight']**2/(2.0* sigma**2) #w = gamma[a]* np.exp(-t_w) QAOA.cu1(-2 * w, k, l) QAOA.u1(w, k) QAOA.u1(w, l) # then apply the single qubit X - rotations with angle beta to all qubits QAOA.barrier() QAOA.rx(2 * beta[a], range(len(V))) # Finally measure the result in the computational basis QAOA.barrier() if backend.name() == "qasm_simulator": QAOA.measure(range(len(V)), range(len(V))) # run on local simulator simulate = execute(QAOA, backend=backend, shots=shots) QAOA_results = simulate.result() # Evaluate the data from the simulator counts = QAOA_results.get_counts() return counts elif backend.name() == "statevector_simulator": # run on local simulator simulate = execute(QAOA, backend=backend) QAOA_results = simulate.result() # Evaluate the data from the simulator statevector = QAOA_results.get_statevector(decimals=3) vec = quantum_info.Statevector(statevector) return vec.probabilities_dict(decimals=3) else: raise TypeError("Incorrect backend.")
def _target_quantum_channel( cls, circuit: QuantumCircuit, measurement_qubits: Optional[Sequence[int]] = None, preparation_qubits: Optional[Sequence[int]] = None, ): """Return the process tomography target""" # Check if circuit contains measure instructions # If so we cannot return target state circuit_ops = circuit.count_ops() if "measure" in circuit_ops: return None perm_circ = cls._permute_circuit(circuit, measurement_qubits=measurement_qubits, preparation_qubits=preparation_qubits) try: if "reset" in circuit_ops or "kraus" in circuit_ops or "superop" in circuit_ops: channel = qi.Choi(perm_circ) else: channel = qi.Operator(perm_circ) except QiskitError: # Circuit couldn't be simulated return None total_qubits = circuit.num_qubits if measurement_qubits: num_meas = len(measurement_qubits) else: num_meas = total_qubits if preparation_qubits: num_prep = len(preparation_qubits) else: num_prep = total_qubits if num_prep == total_qubits and num_meas == total_qubits: return channel # Trace out non-measurement subsystems tr_qargs = [] if preparation_qubits: tr_qargs += list(range(num_prep, total_qubits)) if measurement_qubits: tr_qargs += list(range(total_qubits + num_meas, 2 * total_qubits)) chan_state = qi.Statevector(np.ravel(channel, order="F")) chan_state = qi.partial_trace(chan_state, tr_qargs) / 2**(total_qubits - num_meas) channel = qi.Choi(chan_state.data, input_dims=[2] * num_prep, output_dims=[2] * num_meas) return channel
def test_mixed_batch_exp(self): """Test batch state and process tomography experiment""" # Subsystem unitaries state_op = qi.random_unitary(2, seed=321) chan_op = qi.random_unitary(2, seed=123) state_target = qi.Statevector(state_op.to_instruction()) chan_target = qi.Choi(chan_op.to_instruction()) state_exp = StateTomography(state_op) chan_exp = ProcessTomography(chan_op) batch_exp = BatchExperiment([state_exp, chan_exp]) # Run batch experiments backend = AerSimulator(seed_simulator=9000) par_data = batch_exp.run(backend) self.assertExperimentDone(par_data) f_threshold = 0.95 # Check state tomo results state_results = par_data.child_data(0).analysis_results() state = filter_results(state_results, "state").value # Check fit state fidelity state_fid = filter_results(state_results, "state_fidelity").value self.assertGreater(state_fid, f_threshold, msg="fit fidelity is low") # Manually check fidelity target_fid = qi.state_fidelity(state, state_target, validate=False) self.assertAlmostEqual(state_fid, target_fid, places=6, msg="result fidelity is incorrect") # Check process tomo results chan_results = par_data.child_data(1).analysis_results() chan = filter_results(chan_results, "state").value # Check fit process fidelity chan_fid = filter_results(chan_results, "process_fidelity").value self.assertGreater(chan_fid, f_threshold, msg="fit fidelity is low") # Manually check fidelity target_fid = qi.process_fidelity(chan, chan_target, require_cp=False, require_tp=False) self.assertAlmostEqual(chan_fid, target_fid, places=6, msg="result fidelity is incorrect")
def test_save_statevector_conditional(self): """Test conditional save statevector instruction""" SUPPORTED_METHODS = [ 'automatic', 'statevector', 'statevector_gpu', 'statevector_thrust', 'matrix_product_state', 'extended_stabilizer' ] # Stabilizer test circuit save_key = 'sv' circ = QuantumCircuit(2) circ.h(0) circ.sdg(0) circ.cx(0, 1) circ.measure_all() circ.save_statevector(save_key, conditional=True) # Target statevector target = { '0x0': qi.Statevector([1, 0, 0, 0]), '0x3': qi.Statevector([0, 0, 0, -1j]) } # Run opts = self.BACKEND_OPTS.copy() qobj = assemble(circ, self.SIMULATOR, shots=10) result = self.SIMULATOR.run(qobj, **opts).result() method = opts.get('method', 'automatic') if method not in SUPPORTED_METHODS: self.assertFalse(result.success) else: self.assertTrue(result.success) data = result.data(0) self.assertIn(save_key, data) for key, vec in data[save_key].items(): self.assertIn(key, target) self.assertAlmostEqual(qi.Statevector(vec), target[key])