def test_run_mixture(dtype): q0 = cirq.LineQubit(0) simulator = cirq.Simulator(dtype=dtype) circuit = cirq.Circuit(cirq.bit_flip(0.5)(q0), cirq.measure(q0)) result = simulator.run(circuit, repetitions=100) assert 20 < sum(result.measurements['0'])[0] < 80
import cirq as cq circuit = cq.Circuit() (q0, q1) = cq.LineQubit.range(2) circuit.append([cq.H(q0), cq.CNOT(q0, q1)]) circuit.append([cq.measure(q0), cq.measure(q1)]) sim = cq.Simulator() results = sim.run(circuit, repetitions=10) print(circuit) print(results)
return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 4 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count, input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count = 2000 circuit = circuit.with_noise(cirq.depolarize(p=0.01)) simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq_noisy460.csv", "w+") print(format(frequencies), file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit, file=writefile) writefile.close()
def test_run_empty_circuit(dtype): simulator = cirq.Simulator(dtype=dtype) with pytest.raises(ValueError, match="no measurements"): simulator.run(cirq.Circuit())
def run_experiment( parameters: FermiHubbardParameters, steps: Iterable[int], sampler: cirq.Sampler = cirq.Simulator(), *, repetitions: int = 20000, name: Optional[str] = None, processor: Optional[str] = None, keep_raw_result: bool = False, threads: int = 4, pre_run_func: Optional[Callable[[int, cirq.Circuit], None]] = None, post_run_func: Optional[Callable[[int, cirq.Result], None]] = None ) -> FermiHubbardExperiment: """Executes Fermi-Hubbard experiment. Args: parameters: Fermi-Hubbard problem description. steps: Array of Trotter step counts that should be simulated. sampler: Sampler used to run the circuits. This can be either a simulation sampler or sampler with capability of running on quantum hardware. repetitions: Number of repetitions for each circuit executed. name: Name which is passed to returned container. processor: Processor name which is passed to returned container. keep_raw_result: When true, the raw bitstring measurements for each run will be stored within the results object. threads: Number of threads used for execution. When set to 0, no multithreading routines are used. pre_run_func: Optional callable which is called before each circuit is scheduled for execution. post_run_func: Optional callable which is called after each circuit completes. Returns: Instance of FermiHubbardExperiment with experiment results. """ def run_step(step: int) -> ExperimentRun: initial, trotter, measurement = create_circuits(parameters, step) circuit = initial + trotter + measurement if pre_run_func: pre_run_func(step, circuit) trial = sampler.run(circuit, repetitions=repetitions) end_time = time.time() if post_run_func: post_run_func(step, trial) result = extract_result(parameters.up_particles, parameters.down_particles, trial, post_select=False) result_post_selected = extract_result(parameters.up_particles, parameters.down_particles, trial, post_select=True) return ExperimentRun(trotter_steps=step, end_timestamp_sec=end_time, result=result, result_post_selected=result_post_selected, result_raw=trial if keep_raw_result else None) if threads: with ThreadPoolExecutor(max_workers=threads) as executor: runs = tuple(executor.map(run_step, steps)) else: runs = tuple(run_step(step) for step in steps) return FermiHubbardExperiment(parameters=parameters, runs=runs, processor=processor, name=name)
def test_simulate_sweep_parameters_not_resolved(): a = cirq.LineQubit(0) simulator = cirq.Simulator() circuit = cirq.Circuit(cirq.XPowGate(exponent=sympy.Symbol('a'))(a), cirq.measure(a)) with pytest.raises(ValueError, match='symbols were not specified'): _ = simulator.simulate_sweep(circuit, cirq.ParamResolver({}))
def state_sim(self, num_MC, rgen=np.random, dtype=np.complex64): vals = self.schwarmafier.gen_noise_instances(self.circ, num_MC, rgen, self.SPAM) sim = cirq.Simulator(dtype=dtype) resolvers = [cirq.ParamResolver({str(h):row[i] for i,h in enumerate(self.syms)}) for row in vals] return np.array([s.final_state_vector for s in sim.simulate_sweep(self.noisy_circuit, resolvers)])
def test_run_empty_circuit(dtype): simulator = cirq.Simulator(dtype=dtype) result = simulator.run(cirq.Circuit()) assert len(result.measurements) == 0
def test_simulates_composite(): c = cirq.Circuit.from_ops(MultiHTestGate().on(*cirq.LineQubit.range(2))) expected = np.array([0.5] * 4) np.testing.assert_allclose(c.apply_unitary_effect_to_state(), expected) np.testing.assert_allclose(cirq.Simulator().simulate(c).state_vector(), expected)
expand B 12 expand B 13 expand B 14 expand B 15 merge A B """ # Simulate circuit qubits = utils.GetGridQubits(StringIO(grid_test)) circuit = utils.GetCircuit(StringIO(circuit_test), qubits) circuit_no_h_and_sparse = utils.GetCircuit( StringIO(circuit_no_h_and_sparse_test), qubits) auto_ordering = auto_order.circuit_to_ordering(circuit, qubit_names=sorted(qubits)) results = cirq.Simulator().simulate(circuit) results_no_h_and_sparse = cirq.Simulator().simulate(circuit_no_h_and_sparse) @pytest.mark.parametrize('m', ['1kB', '10B', '1', 1 << 10, 10, 1, '1kMB']) @pytest.mark.xfail def test_memory_limit(m): # Get configuration as a string final_conf = '0' * len(qubits) options = { 'circuit': circuit_test.split('\n'), 'ordering': ordering_test.split('\n'), 'grid': grid_test.split('\n'), 'final_state': final_conf,
def measure_circuit(self,circuit,parameters={}, betas= None,gammas=None,key='m',n_trials=100): ''' This function resolves the input parameters and carries out the measurements of the circuits. All symbolic parameters are resolved into values for calculation. Keyword arguments: A - the penalty scaling coefficient D - the investment constraint T - the normalized cost incurred if an asset is traded mu - the normalized average asset returns vector sigma - the normalized asset returns covariance matrix y - the previous portfolio position lam - the asset manager control parameter betas - the vector representing the angles for the mixer gammas - the vector representing the angles for the cost function unitarity matrix key - the key that is used for specifying what to measure in the circuit simulation. n_trials - the number of times to run the circuit and collect the results ''' # Retrieve the input parameters lam = parameters['lam'] A = parameters['A'] D = parameters['D'] mu = parameters['mu'] sigma = parameters['sigma'] T = parameters['T'] y = parameters['y'] resolved_params ={} # The cirq simulator object simulator = cirq.Simulator() # This parameters only exists for the QAOA cicuit with soft constraints try: if(A is not None): resolved_params[self.A] = A except: pass if(D is not None): resolved_params[self.D] = D if(lam is not None): resolved_params[self.lam] = lam if(T is not None): resolved_params[self.T] = T if(y is not None): for k in range(self.N_portfolio): resolved_params[self.y[k]] = y[k] if(mu is not None): for k in range(self.N_portfolio): resolved_params[self.mu[k]] = mu[k] if(betas is not None): for k in range(len(betas)): resolved_params[self.betas[k]] = betas[k] if(gammas is not None): for k in range(len(gammas)): resolved_params[self.gammas[k]] = gammas[k] if(sigma is not None): for k1 in range(self.N_portfolio): for k2 in range(self.N_portfolio): resolved_params[self.sigma[k1][k2]] = sigma[k1,k2] # Resolve all of the symbolic parameters in the circuit resolver = cirq.ParamResolver(resolved_params) # Carry out the n_trial measurements results = simulator.run(circuit,resolver,repetitions=n_trials) # Extract the bitstrings that were measured bitstrings = results.measurements[key] return bitstrings
class ControlledPQCTest(tf.test.TestCase, parameterized.TestCase): """Tests for the ControlledPQC layer.""" def test_controlled_pqc_instantiate(self): """Basic creation test.""" symbol = sympy.Symbol('alpha') bit = cirq.GridQubit(0, 0) learnable_flip = cirq.Circuit(cirq.X(bit)**symbol) controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit)) controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit), repetitions=500) def test_controlled_pqc_backend_error(self): """Test that invalid backends error properly.""" symbol = sympy.Symbol('alpha') bit = cirq.GridQubit(0, 0) learnable_flip = cirq.Circuit(cirq.X(bit)**symbol) class MyState(cirq.SimulatesFinalState): """My state simulator.""" def simulate_sweep(self): """do nothing.""" return class MySample(cirq.Sampler): """My state simulator.""" def run_sweep(self): """do nothing.""" return with self.assertRaisesRegex(TypeError, expected_regex="cirq.SimulatesFinalState"): controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit), backend='junk') with self.assertRaisesRegex(TypeError, expected_regex="cirq.SimulatesFinalState"): controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit), repetitions=None, backend=MySample) with self.assertRaisesRegex(TypeError, expected_regex="cirq.Sampler"): controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit), repetitions=500, backend=MyState) def test_controlled_pqc_model_circuit_error(self): """Test that invalid circuits error properly.""" bit = cirq.GridQubit(0, 0) no_symbols = cirq.Circuit(cirq.X(bit)) with self.assertRaisesRegex(TypeError, expected_regex="cirq.Circuit"): controlled_pqc.ControlledPQC('junk', cirq.Z(bit)) with self.assertRaisesRegex(ValueError, expected_regex="no sympy.Symbols"): controlled_pqc.ControlledPQC(no_symbols, cirq.Z(bit)) def test_controlled_pqc_operators_error(self): """Test that invalid operators error properly.""" symbol = sympy.Symbol('alpha') bit = cirq.GridQubit(0, 0) learnable_flip = cirq.Circuit(cirq.X(bit)**symbol) with self.assertRaisesRegex( TypeError, expected_regex="cirq.PauliSum or cirq.PauliString"): controlled_pqc.ControlledPQC(learnable_flip, 'junk') with self.assertRaisesRegex(TypeError, expected_regex="Each element"): controlled_pqc.ControlledPQC(learnable_flip, [[cirq.Z(bit)]]) with self.assertRaisesRegex(TypeError, expected_regex="Each element"): controlled_pqc.ControlledPQC(learnable_flip, [cirq.Z(bit), 'bad']) def test_controlled_pqc_repetitions_error(self): """Test that invalid repetitions error properly.""" symbol = sympy.Symbol('alpha') bit = cirq.GridQubit(0, 0) learnable_flip = cirq.Circuit(cirq.X(bit)**symbol) with self.assertRaisesRegex(ValueError, expected_regex="greater than zero."): controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit), repetitions=-100) with self.assertRaisesRegex(TypeError, expected_regex="positive integer value"): controlled_pqc.ControlledPQC(learnable_flip, cirq.Z(bit), repetitions='junk') @parameterized.parameters( list( util.kwargs_cartesian_product(repetitions=[None, 5000], backend=[None, cirq.Simulator()]))) def test_controlled_pqc_simple_learn(self, backend, repetitions): """Test a simple learning scenario using analytic and sample expectation on many backends.""" bit = cirq.GridQubit(0, 0) circuit = \ cirq.Circuit(cirq.Rx(sympy.Symbol('theta'))(bit)) inputs = tf.keras.Input(shape=(1, ), dtype=tf.dtypes.float32) quantum_datum = tf.keras.Input(shape=(), dtype=tf.dtypes.string) l1 = tf.keras.layers.Dense(10)(inputs) l2 = tf.keras.layers.Dense(1)(l1) outputs = controlled_pqc.ControlledPQC(circuit, cirq.Z(bit), repetitions=repetitions, backend=backend)( [quantum_datum, l2]) model = tf.keras.Model(inputs=[quantum_datum, inputs], outputs=outputs) data_in = np.array([[1], [0]], dtype=np.float32) data_out = np.array([[1], [-1]], dtype=np.float32) model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.05), loss=tf.keras.losses.mean_squared_error) data_circuits = util.convert_to_tensor( [cirq.Circuit(cirq.X(bit)), cirq.Circuit()]) history = model.fit(x=[data_circuits, data_in], y=data_out, epochs=30) self.assertAllClose(history.history['loss'][-1], 0, atol=1e-1)
class StateTest(parameterized.TestCase, tf.test.TestCase): """Basic tests for the State layer.""" def test_state_create(self): """Test that State layers can be created.""" state.State() state.State(backend=cirq.Simulator()) with self.assertRaisesRegex(TypeError, expected_regex="junk is invalid"): state.State('junk') def test_state_invalid_type_inputs(self): """Test that state rejects bad inputs.""" state_calc = state.State() with self.assertRaisesRegex(TypeError, expected_regex="circuits cannot be parsed"): state_calc('junk_circuit') with self.assertRaisesRegex( TypeError, expected_regex="symbol_values cannot be parsed"): state_calc(cirq.Circuit(), symbol_values='junk') with self.assertRaisesRegex( TypeError, expected_regex="symbol_names cannot be parsed"): state_calc(cirq.Circuit(), symbol_values=[], symbol_names='junk') with self.assertRaisesRegex(TypeError, expected_regex="Cannot convert"): state_calc(cirq.Circuit(), symbol_values=[['bad']], symbol_names=['name']) with self.assertRaisesRegex(TypeError, expected_regex="must be a string."): state_calc(cirq.Circuit(), symbol_values=[[0.5]], symbol_names=[0.33333]) with self.assertRaisesRegex(ValueError, expected_regex="must be unique."): state_calc(cirq.Circuit(), symbol_values=[[0.5]], symbol_names=['duplicate', 'duplicate']) def test_state_invalid_shape_inputs(self): """Test that state rejects bad input shapes.""" state_calc = state.State() with self.assertRaisesRegex(TypeError, expected_regex="string or sympy.Symbol"): state_calc(cirq.Circuit(), symbol_values=[[0.5]], symbol_names=[[]]) with self.assertRaisesRegex(Exception, expected_regex="rank 1"): state_calc(cirq.Circuit(), symbol_values=[0.5], symbol_names=['name']) with self.assertRaisesRegex(Exception, expected_regex="rank 2"): state_calc([[cirq.Circuit()]], symbol_values=[[0.5]], symbol_names=['name']) @parameterized.parameters([{ 'backend': None }, { 'backend': cirq.Simulator() }, { 'backend': cirq.DensityMatrixSimulator() }]) def test_state_invalid_combinations(self, backend): """Test with valid type inputs and valid value, but incorrect combo.""" state_calc = state.State(backend) symbol = sympy.Symbol('alpha') circuit = cirq.Circuit(cirq.H(cirq.GridQubit(0, 0))**symbol) with self.assertRaisesRegex(Exception, expected_regex=""): # no value provided. state_calc([circuit, circuit], symbol_names=[symbol], repetitions=5) with self.assertRaisesRegex(Exception, expected_regex=""): # no name provided. state_calc([circuit, circuit], symbol_names=[], symbol_values=[[2.0], [3.0]]) with self.assertRaisesRegex(Exception, expected_regex=""): # deceptive, but the circuit shouldn't be in a list. otherwise fine. state_calc([circuit], symbol_names=['alpha'], symbol_values=[[2.0], [3.0]]) with self.assertRaisesRegex(Exception, expected_regex=""): # wrong symbol name. state_calc([circuit], symbol_names=['alphaaaa'], symbol_values=[[2.0], [3.0]]) with self.assertRaisesRegex(Exception, expected_regex=""): # too many symbol values provided. state_calc(circuit, symbol_names=['alpha'], symbol_values=[[2.0, 4.0], [3.0, 5.0]]) def test_state_basic_inputs(self): """Test that state ingests inputs correctly in simple settings.""" state_calc = state.State() state_calc(cirq.Circuit()) state_calc([cirq.Circuit()]) state_calc(cirq.Circuit(), symbol_names=['name'], symbol_values=[[0.5]]) state_calc(cirq.Circuit(), symbol_names=[sympy.Symbol('name')], symbol_values=[[0.5]]) def test_sample_outputs_simple(self): """Test the simplest call where nothing but circuits are provided.""" state_calc = state.State() circuit = cirq.Circuit(cirq.H(cirq.GridQubit(0, 0))) output = state_calc([circuit, circuit]) self.assertShapeEqual(np.empty((2, 2)), output.to_tensor()) @parameterized.parameters([ { 'backend_output': (None, WF_OUTPUT) }, { 'backend_output': (cirq.sim.sparse_simulator.Simulator(), WF_OUTPUT) }, { 'backend_output': (cirq.sim.density_matrix_simulator.DensityMatrixSimulator(), DM_OUTPUT) }, ]) def test_state_output(self, backend_output): """Check that any output type is as expected. This layer only allows for 2 different outputs, depending on whether a wavefuntion or density matrix simulator is used. Therefore any pre or post processing done inside the layers should not cause output from the layer to structurally deviate from what is expected. """ backend = backend_output[0] output = backend_output[1] state_executor = state.State(backend=backend) bits = cirq.GridQubit.rect(1, 2) circuit = cirq.Circuit() circuit.append(cirq.H.on(bits[0])) circuit.append(cirq.CNOT(bits[0], bits[1])) programs = util.convert_to_tensor([circuit, circuit]) layer_output = state_executor(programs).to_list() self.assertAllClose(layer_output, [output, output]) def test_state_one_circuit(self): """Test that State behaves when a single layer is specified.""" state_calc = state.State() state_calc(cirq.Circuit(), symbol_values=tf.zeros((5, 0), dtype=tf.dtypes.float32))
def main(repetitions=10, maxiter=50, use_boolean_hamiltonian_gate=False): # Set problem parameters n = 6 p = 2 # Generate a random 3-regular graph on n nodes graph = networkx.random_regular_graph(3, n) # Make qubits qubits = cirq.LineQubit.range(n) # Print an example circuit betas = np.random.uniform(-np.pi, np.pi, size=p) gammas = np.random.uniform(-np.pi, np.pi, size=p) circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph, use_boolean_hamiltonian_gate) print('Example QAOA circuit:') print(circuit.to_text_diagram(transpose=True)) # Create variables to store the largest cut and cut value found largest_cut_found = None largest_cut_value_found = 0 # Initialize simulator simulator = cirq.Simulator() # Define objective function (we'll use the negative expected cut value) def f(x): # Create circuit betas = x[:p] gammas = x[p:] circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph, use_boolean_hamiltonian_gate) # Sample bitstrings from circuit result = simulator.run(circuit, repetitions=repetitions) bitstrings = result.measurements['m'] # Process bitstrings nonlocal largest_cut_found nonlocal largest_cut_value_found values = cut_values(bitstrings, graph) max_value_index = np.argmax(values) max_value = values[max_value_index] if max_value > largest_cut_value_found: largest_cut_value_found = max_value largest_cut_found = bitstrings[max_value_index] mean = np.mean(values) return -mean # Pick an initial guess x0 = np.random.uniform(-np.pi, np.pi, size=2 * p) # Optimize f print('Optimizing objective function ...') scipy.optimize.minimize(f, x0, method='Nelder-Mead', options={'maxiter': maxiter}) # Compute best possible cut value via brute force search all_bitstrings = np.array(list(itertools.product(range(2), repeat=n))) all_values = cut_values(all_bitstrings, graph) max_cut_value = np.max(all_values) # Print the results print(f'The largest cut value found was {largest_cut_value_found}.') print(f'The largest possible cut has size {max_cut_value}.') print( f'The approximation ratio achieved is {largest_cut_value_found / max_cut_value}.' )
def test_measure_at_end_invert_mask(): simulator = cirq.Simulator() a = cirq.NamedQubit('a') circuit = cirq.Circuit(cirq.measure(a, key='a', invert_mask=(True,))) result = simulator.run(circuit, repetitions=4) np.testing.assert_equal(result.measurements['a'], np.array([[1]] * 4))
def PlotThreeBodyContact(u, v, t, theta, phi, t_start, t_end, t_sweep_size, n_measurements, n_trotter, method, preparation_method, n_ancilla=0): ''' Funtion to plot the three body contact density. Parameters ---------- u : float One the parameters in the Hamiltonian, see report for description. v : float One the parameters in the Hamiltonian, see report for description. t : float One the parameters in the Hamiltonian, see report for description. theta : float Angle to initialize the ansatz with. phi : float Angle to initialize the ansatz with. t_start : int Time point where the sweep starts. t_end : int Time point where the sweep ends. t_sweep_size : int Number of steps plotted between the start and end time. n_measurements : int How many times the simulator runs the system to calculate the expectation values with. n_trotter : int Number of trotter steps used in the time evoltution. method : string Choose the method used to calculate the time evoltuion. Options are: 'gates', 'exact' and 'trotter exact', denoting timeevolution by a circuit, full matrix exponential and trotterized matrix exponential respectively. preparation_method: string Choose the method used to initialize the approximated ground state. Options are: 'ansatz' and 'qpe'. Make sure a non zero value for n_ancilla is chosen when using qpe. n_ancilla: int, optional Defaults to zero, only used when preparation_method = 'qpe', choose non zero value when using qpe. Raises ------ MethodError When a method string is chosen that doesn't match one of the options an error is raised. Returns ------- None. ''' results_array = [] t_sweep = np.linspace(t_start, t_end, t_sweep_size) for i in range(0, t_sweep_size): qubits = [ c.LineQubit(0), c.LineQubit(1), c.LineQubit(2), c.LineQubit(3) ] circ = c.Circuit() if preparation_method == 'ansatz': circ.append(SP.StatePreparation(theta, phi)(*qubits)) elif preparation_method == 'qpe': circ.append( SP.QPEStatePreparation(theta, phi, qubits, n_ancilla, u, v, t, 1.0)) else: raise MethodError("Invalid time evolution method.") for j in range(0, n_trotter): if method == 'gates': circ.append( TE.TrotterizedEvolutionGate(u, v, t, t_sweep[i] / n_trotter)(*qubits)) elif method == 'exact': circ.append( TE.ExactEvolution(u, v, t, t_sweep[i] / n_trotter)(*qubits)) elif method == 'trotterexact': circ.append( TE.ExactEvolutionTrotterOne(u, v, t, t_sweep[i] / n_trotter)(*qubits)) else: raise MethodError("Invalid time evolution method.") circ.append(c.measure(*qubits, key='Zmeasurements')) simulator = c.Simulator() result = simulator.run(circ, repetitions=n_measurements) if preparation_method == 'ansatz': results_array.append( result.histogram(key='Zmeasurements')[0] / n_measurements) elif preparation_method == 'qpe': ancilla_histogram = result.histogram(key='ancilla') ancilla_values = result.data["ancilla"].values indices = np.array(np.where(ancilla_values == 788))[0] filtered_results = result.data["Zmeasurements"].values[indices] binned_results = np.bincount(filtered_results) results_array.append(binned_results[0] / len(filtered_results)) else: raise MethodError("Invalid time evolution method.") plt.plot(t_sweep, results_array, '.') plt.xlabel(r'$t$') plt.ylabel(r'$C_3 (t)$') plt.savefig('ThreeBodyContact.pdf') plt.show()
def test_measure_at_end_invert_mask_partial(): simulator = cirq.Simulator() a, _, c = cirq.LineQubit.range(3) circuit = cirq.Circuit(cirq.measure(a, c, key='ac', invert_mask=(True,))) result = simulator.run(circuit, repetitions=4) np.testing.assert_equal(result.measurements['ac'], np.array([[1, 0]] * 4))
'Sycamore23': QuantumProcessor( name='Sycamore23', device_obj=cg_devices.Sycamore23, processor_id='rainbow', is_simulator=False, _get_sampler_func=lambda x, gs: EngineSampler( processor_id=x.processor_id, gateset=gs), ), 'Syc23-noiseless': QuantumProcessor( name='Syc23-noiseless', device_obj=cg_devices.Sycamore23, processor_id=None, is_simulator=True, _get_sampler_func=lambda x, gs: cirq.Simulator(), ), 'Syc23-simulator': QuantumProcessor(name='Syc23-simulator', device_obj=cg_devices.Sycamore23, processor_id=None, is_simulator=True, _get_sampler_func=lambda x, gs: cirq. DensityMatrixSimulator(noise=cirq.ConstantQubitNoiseModel( qubit_noise_gate=cirq.DepolarizingChannel(0.005)))), 'Syc23-zeros': QuantumProcessor(name='Syc23-zeros', device_obj=cg_devices.Sycamore23, processor_id=None, is_simulator=True, _get_sampler_func=lambda x, gs: ZerosSampler())
def test_random_seed_terminal_measurements_deterministic(): a = cirq.NamedQubit('a') circuit = cirq.Circuit(cirq.X(a) ** 0.5, cirq.measure(a, key='a')) sim = cirq.Simulator(seed=1234) result1 = sim.run(circuit, repetitions=30) result2 = sim.run(circuit, repetitions=30) assert np.all( result1.measurements['a'] == [ [0], [1], [0], [1], [1], [0], [0], [1], [1], [1], [0], [1], [1], [1], [0], [1], [1], [0], [1], [1], [0], [1], [0], [0], [1], [1], [0], [1], [0], [1], ] ) assert np.all( result2.measurements['a'] == [ [1], [0], [1], [0], [1], [1], [0], [1], [0], [1], [0], [0], [0], [1], [1], [1], [0], [1], [0], [1], [0], [1], [1], [0], [1], [1], [1], [1], [1], [1], ] )
def run_tests(N): """run_tests: just a whole bunch of tests. :param N: number of iterations to run """ for _ in range(N): q = np.random.randn(2, 2)+1j*np.random.randn(2, 2) assert np.allclose(get_env_off_left_site(np.prod(put_env_on_left_site(q, ret_n=True))), q) assert np.allclose(get_env_off_right_site(np.prod(put_env_on_right_site(q, ret_n=True))), q) U = put_env_on_left_site(q) V = put_env_on_right_site(q) assert np.allclose(V.conj().T@V, np.eye(U.shape[0])) assert np.allclose(U.conj().T@U, np.eye(U.shape[0])) A = iMPS().random(2, 2).left_canonicalise()[0] B = iMPS().random(2, 2).left_canonicalise()[0]#np.tensordot(expm(-1j*Z*dt), A, [1, 0]) U = Environment(tensor_to_unitary(A), 'U') U_ = Environment(tensor_to_unitary(B), 'U\'') x, r = Map(merge(A, A), merge(B, B)).right_fixed_point() x_, l = Map(merge(A, A), merge(B, B)).left_fixed_point() L = put_env_on_right_site(l) R = put_env_on_left_site(r) assert np.allclose(get_env_off_left_site(put_env_on_left_site(r)), r) assert np.allclose(get_env_off_right_site(put_env_on_right_site(l)), l) U = put_env_on_left_site(r) V = put_env_on_right_site(l) assert np.allclose(V.conj().T@V, np.eye(U.shape[0])) assert np.allclose(U.conj().T@U, np.eye(U.shape[0])) A = iMPS().random(2, 2).left_canonicalise()[0] B = iMPS().random(2, 2).left_canonicalise()[0]#np.tensordot(expm(-1j*Z*dt), A, [1, 0]) E = Map(A, B) x, r = E.right_fixed_point() x_, l = E.left_fixed_point() U = Environment(tensor_to_unitary(A), 'U') U_ = Environment(tensor_to_unitary(B), 'U\'') R = Environment(put_env_on_left_site(r), 'R') L = Environment(put_env_on_right_site(l.conj().T), 'L') qbs = cirq.LineQubit.range(4) for g in zip([cirq.I, cirq.X, cirq.Y, cirq.Z], [I, X, Y, Z]): C = cirq.Circuit.from_ops([cirq.H(qbs[1]), cirq.CNOT(*qbs[1:3]), R(*qbs[2:]), g[0](qbs[1]), cirq.CNOT(*qbs[1:3]), cirq.H(qbs[1])]) s = cirq.Simulator() assert np.allclose(2*s.simulate(C).final_state[0]-np.trace(g[1]@r), 0, 1e-6, 1e-6) # r is the matrix on the 1st qubit qbs = cirq.LineQubit.range(4) for g in zip([cirq.I, cirq.X, cirq.Y, cirq.Z], [I, X, Y, Z]): C = cirq.Circuit.from_ops([cirq.H(qbs[1]), cirq.CNOT(*qbs[1:3]), U(*qbs[0:2]), R(*qbs[2:]), g[0](qbs[0]), cirq.inverse(U_)(*qbs[0:2]), cirq.CNOT(*qbs[1:3]), cirq.H(qbs[1])]) s = cirq.Simulator() assert np.allclose(2*s.simulate(C).final_state[0]-x*np.trace(g[1]@r), 0, 1e-6, 1e-6) qbs = cirq.LineQubit.range(5) for g in zip([cirq.I, cirq.X, cirq.Y, cirq.Z], [I, X, Y, Z]): C = cirq.Circuit.from_ops([cirq.H(qbs[2]), cirq.CNOT(*qbs[2:4]), U(*qbs[1:3]), U(*qbs[0:2]), R(*qbs[3:]), g[0](qbs[0]), cirq.inverse(U_)(*qbs[0:2]), cirq.inverse(U_)(*qbs[1:3]), cirq.CNOT(*qbs[2:4]), cirq.H(qbs[2])]) s = cirq.Simulator() #print(C.to_text_diagram(transpose=True)) #raise Exception assert np.allclose(2*s.simulate(C).final_state[0]-x**2*np.trace(g[1]@r), 0, 1e-6, 1e-6) qbs = cirq.LineQubit.range(3) for g in zip([cirq.I, cirq.X, cirq.Y, cirq.Z], [I, X, Y, Z]): C = cirq.Circuit.from_ops([cirq.H(qbs[1]), cirq.CNOT(*qbs[1:3]), L(*qbs[:2]), g[0](qbs[2]), cirq.CNOT(*qbs[1:3]), cirq.H(qbs[1])]) s = cirq.Simulator() assert np.allclose(2*s.simulate(C).final_state[0]-np.trace(g[1]@l.conj()), 0, 1e-6, 1e-6) # r is the matrix on the 1st qubit qbs = cirq.LineQubit.range(4) for g in zip([cirq.I, cirq.X, cirq.Y, cirq.Z], [I, X, Y, Z]): C = cirq.Circuit.from_ops([cirq.H(qbs[2]), cirq.CNOT(*qbs[2:4]), U(*qbs[1:3]), L(*qbs[:2]), g[0](qbs[3]), cirq.inverse(U_)(*qbs[1:3]), cirq.CNOT(*qbs[2:4]), cirq.H(qbs[2])]) s = cirq.Simulator() #print(C.to_text_diagram(transpose=True)) #raise Exception assert np.allclose(2*s.simulate(C).final_state[0]-x*np.trace(g[1]@l.conj()), 0, 1e-6, 1e-6) qbs = cirq.LineQubit.range(5) for g in zip([cirq.I, cirq.X, cirq.Y, cirq.Z], [I, X, Y, Z]): C = cirq.Circuit.from_ops([cirq.H(qbs[3]), cirq.CNOT(*qbs[3:5]), U(*qbs[2:4]), U(*qbs[1:3]), L(*qbs[0:2]), g[0](qbs[4]), cirq.inverse(U_)(*qbs[1:3]), cirq.inverse(U_)(*qbs[2:4]), cirq.CNOT(*qbs[3:5]), cirq.H(qbs[3])]) s = cirq.Simulator() assert np.allclose(2*s.simulate(C).final_state[0]-x**2*np.trace(g[1]@l.conj()), 0, 1e-6, 1e-6) qbs = cirq.LineQubit.range(6) C = cirq.Circuit.from_ops([cirq.H(qbs[3]), cirq.CNOT(*qbs[3:5]), U(*qbs[2:4]), U(*qbs[1:3]), L(*qbs[0:2]), R(*qbs[4:]), cirq.inverse(U_)(*qbs[1:3]), cirq.inverse(U_)(*qbs[2:4]), cirq.CNOT(*qbs[3:5]), cirq.H(qbs[3])]) s = cirq.Simulator() assert np.allclose(2*s.simulate(C).final_state[0], x**2*np.trace(l.conj().T@r))
def test_invalid_dtype(): with pytest.raises(ValueError, match='complex'): cirq.Simulator(dtype=np.int32)
def test_run_repetitions_terminal_measurement_stochastic(): q = cirq.LineQubit(0) c = cirq.Circuit(cirq.H(q), cirq.measure(q, key='q')) results = cirq.Simulator().run(c, repetitions=10000) assert 1000 <= sum(v[0] for v in results.measurements['q']) < 9000
def test_simulates_composite(): c = cirq.Circuit.from_ops(MultiHTestGate().on(*cirq.LineQubit.range(2))) expected = np.array([0.5] * 4) np.testing.assert_allclose(c.final_wavefunction(), expected) np.testing.assert_allclose(cirq.Simulator().simulate(c).state_vector(), expected)
def test_run_mixture(dtype: Type[np.number], split: bool): q0 = cirq.LineQubit(0) simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) circuit = cirq.Circuit(cirq.bit_flip(0.5)(q0), cirq.measure(q0)) result = simulator.run(circuit, repetitions=100) assert 20 < sum(result.measurements['0'])[0] < 80 # type: ignore
def run_circuit(player, light1, light0): results_dict = {} # define qubits for circuit q0, q1, q2 = [cirq.GridQubit(i, 0) for i in range(3)] # define quantum circuit circuit = cirq.Circuit() # define quantuum simulator simulator = cirq.Simulator() # if any of the values are one add an X gate at beginning of circuit for that bit if player == 1: circuit.append(X(q2)) if light1 == 1: circuit.append(X(q1)) if light0 == 1: circuit.append(X(q0)) # main circuit construction # H ->Hadamard gate # CNOT -> Feynman gate # X -> Pauli X gate (inverter) # CCX -> CCNOT gate circuit.append(H(q0)) circuit.append(CNOT(q2, q1)) circuit.append(X(q1)) circuit.append(H(q2)) circuit.append(CNOT(q2, q0)) circuit.append(CCX(q2, q0, q1)) circuit.append(X(q1)) circuit.append(cirq.measure(q0, key='x')) circuit.append(cirq.measure(q1, key='y')) # get results from 1000 runs of circuit results = simulator.run(circuit, repetitions=1000) # gets counts for each possible output counts = results.multi_measurement_histogram(keys=['y', 'x']) # place count values from circuit simlation into dictionary results_dict = counter_to_dict(counts) # obtain 1 letter value that corresponds to 1 selected output value out of 1000 possiblities letter_choice = parse_counts(results_dict) # translate the letter value into a mood value choice = determine_state(letter_choice) # print statements that can be set with boolean if print_circuit == True: print(circuit) if print_counts == True: print(counts) if print_stats == True: get_stats() if print_mood == True: print("Robot Mood = " + str(choice)) # return the choice of the robot return choice
def test_run_empty_circuit(dtype: Type[np.number], split: bool): simulator = cirq.Simulator(dtype=dtype, split_untangled_states=split) with pytest.raises(ValueError, match="no measurements"): simulator.run(cirq.Circuit())
def main( # repetitions=16384, maxiter=8 ): # Set problem parameters n = 8 p = 1 # Generate a random 3-regular graph on n nodes graph = networkx.random_regular_graph(3, n) # Make qubits qubits = cirq.LineQubit.range(n) # Print an example circuit betas = np.random.uniform(-np.pi, np.pi, size=p) gammas = np.random.uniform(-np.pi, np.pi, size=p) circuit_no_meas = qaoa_max_cut_circuit_no_meas(qubits, p, graph) print('Example QAOA circuit:') print(circuit_no_meas.to_text_diagram(transpose=True)) # noise = cirq.ConstantQubitNoiseModel(cirq.generalized_amplitude_damp(0.05,0.05)) # noise = cirq.ConstantQubitNoiseModel(cirq.amplitude_damp(0.25)) # noise = cirq.ConstantQubitNoiseModel(cirq.phase_damp(0.25)) # noise = cirq.ConstantQubitNoiseModel(cirq.asymmetric_depolarize(0.05,0.05,0.05)) # asymmetric depolarizing noise = cirq.ConstantQubitNoiseModel(cirq.depolarize(0.005)) # symmetric depolarizing # noise = cirq.ConstantQubitNoiseModel(cirq.phase_flip(0.25)) # mixture # noise = cirq.ConstantQubitNoiseModel(cirq.bit_flip(0.03125)) # mixture circuit_no_meas = cirq.Circuit(cirq.NoiseModel.from_noise_model_like(noise).noisy_moments(circuit_no_meas, sorted(circuit_no_meas.all_qubits()))) circuit = cirq.Circuit( circuit_no_meas, cirq.measure(*qubits, key='m') ) cirq.optimizers.ExpandComposite().optimize_circuit(circuit) # seems to actually increase BN size # Initialize simulator kc_simulator = cirq.KnowledgeCompilationSimulator( circuit, initial_state=0, intermediate=False ) dm_simulator = cirq.Simulator() # Create variables to store the largest cut and cut value found kc_largest_cut_found = None kc_largest_cut_value_found = 0 dm_largest_cut_found = None dm_largest_cut_value_found = 0 # Define objective function (we'll use the negative expected cut value) iter = 0 def f(x): # Create circuit betas = x[:p] betas_dict = { 'beta'+str(index):betas[index] for index in range(p) } gammas = x[p:] gammas_dict = { 'gamma'+str(index):gammas[index] for index in range(p) } param_resolver = cirq.ParamResolver({**betas_dict,**gammas_dict}) # kc_chisqs = {} # dm_chisqs = {} kc_power_divergences = {} dm_power_divergences = {} ks_2samps = {} for rep_pow in range(12): repetitions = 1<<rep_pow # VALIDATE STATE VECTOR SIMULATION # kc_sim_result = kc_simulator.simulate(circuit_no_meas, param_resolver=param_resolver) dm_sim_result = dm_simulator.simulate(circuit_no_meas, param_resolver=param_resolver) # print("kc_sim_result.final_density_matrix") # print(kc_sim_result.final_density_matrix) # print("dm_sim_result.final_density_matrix") # print(dm_sim_result.final_density_matrix) # np.testing.assert_almost_equal( # kc_sim_result.final_density_matrix, # dm_sim_result.final_density_matrix, # decimal=5 # ) # VALIDATE SAMPLING HISTOGRAMS # Sample bitstrings from circuit kc_smp_start = time.time() kc_smp_result = kc_simulator.run(circuit, param_resolver=param_resolver, repetitions=repetitions) kc_smp_time = time.time() - kc_smp_start kc_bitstrings = kc_smp_result.measurements['m'] # Process histogram kc_histogram = np.zeros(1<<n) kc_integers = [] for bitstring in kc_bitstrings: integer = 0 for pos, bit in enumerate(bitstring): integer += bit<<pos kc_histogram[integer] += 1 kc_integers.append(integer) # Process bitstrings nonlocal kc_largest_cut_found nonlocal kc_largest_cut_value_found kc_values = cut_values(kc_bitstrings, graph) kc_max_value_index = np.argmax(kc_values) kc_max_value = kc_values[kc_max_value_index] if kc_max_value > kc_largest_cut_value_found: kc_largest_cut_value_found = kc_max_value kc_largest_cut_found = kc_bitstrings[kc_max_value_index] kc_mean = np.mean(kc_values) # Sample bitstrings from circuit dm_smp_start = time.time() dm_smp_result = dm_simulator.run(circuit, param_resolver=param_resolver, repetitions=repetitions) dm_smp_time = time.time() - dm_smp_start dm_bitstrings = dm_smp_result.measurements['m'] # Process histogram dm_histogram = np.zeros(1<<n) dm_integers = [] for bitstring in dm_bitstrings: integer = 0 for pos, bit in enumerate(bitstring): integer += bit<<pos dm_histogram[integer] += 1 dm_integers.append(integer) # Process bitstrings nonlocal dm_largest_cut_found nonlocal dm_largest_cut_value_found dm_values = cut_values(dm_bitstrings, graph) dm_max_value_index = np.argmax(dm_values) dm_max_value = dm_values[dm_max_value_index] if dm_max_value > dm_largest_cut_value_found: dm_largest_cut_value_found = dm_max_value dm_largest_cut_found = dm_bitstrings[dm_max_value_index] dm_mean = np.mean(dm_values) nonlocal iter # PRINT HISTOGRAMS exact_histogram = np.zeros(1<<n) for index, amplitude in enumerate(dm_sim_result.state_vector()): probability = abs(amplitude) * abs(amplitude) exact_histogram[index] = probability * repetitions # print ('iter='+str(iter)+' bitstring='+str(index)+' kc_probability='+str(kc_histogram[index]/repetitions)+' dm_probability='+str(dm_histogram[index]/repetitions)+' probability='+str(probability)) # exact_probabilities = cirq.sim.density_matrix_utils._probs( # dm_sim_result.final_density_matrix, # [index for index in range(n)], # cirq.protocols.qid_shape(qubits) # ) # for index, probability in enumerate(exact_probabilities): # exact_histogram[index] = probability * repetitions # print ('iter='+str(iter)+' bitstring='+str(index)+' kc_probability='+str(kc_histogram[index]/repetitions)+' dm_probability='+str(dm_histogram[index]/repetitions)+' probability='+str(probability)) # kc_chisq, _ = scipy.stats.chisquare( f_obs=kc_histogram, f_exp=exact_histogram ) # dm_chisq, _ = scipy.stats.chisquare( f_obs=dm_histogram, f_exp=exact_histogram ) # kc_power_divergence, _ = scipy.stats.power_divergence( f_obs=kc_histogram, f_exp=exact_histogram, lambda_="pearson" ) # dm_power_divergence, _ = scipy.stats.power_divergence( f_obs=dm_histogram, f_exp=exact_histogram, lambda_="pearson" ) kc_power_divergence, _ = scipy.stats.power_divergence( f_obs=kc_histogram, f_exp=exact_histogram, lambda_="log-likelihood" ) dm_power_divergence, _ = scipy.stats.power_divergence( f_obs=dm_histogram, f_exp=exact_histogram, lambda_="log-likelihood" ) ks_2samp, _ = scipy.stats.ks_2samp( data1=kc_integers, data2=dm_integers ) # kc_chisqs[repetitions]=kc_chisq # dm_chisqs[repetitions]=dm_chisq # kc_power_divergences[repetitions]=kc_power_divergence # dm_power_divergences[repetitions]=dm_power_divergence kc_power_divergences[repetitions]=kc_power_divergence / 2 / repetitions dm_power_divergences[repetitions]=dm_power_divergence / 2 / repetitions ks_2samps[repetitions]=ks_2samp print ( 'repetitions='+str(repetitions)+ # ' kc_chisq='+str(kc_chisq)+ # ' dm_chisq='+str(dm_chisq)+ # ' kc_power_divergence='+str(kc_power_divergence)+ # ' dm_power_divergence='+str(dm_power_divergence)+ ' kc_power_divergence='+str(kc_power_divergence / 2 / repetitions)+ ' dm_power_divergence='+str(dm_power_divergence / 2 / repetitions)+ ' ks_2samp='+str(ks_2samp) ) # print ('kc_mean='+str(kc_mean)+' dm_mean='+str(dm_mean)) # print ( 'kc_smp_time=' + str(kc_smp_time) + ' dm_smp_time=' + str(dm_smp_time) ) # print ('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~') iter += 1 return -dm_mean # Pick an initial guess x0 = np.random.uniform(-np.pi, np.pi, size=2 * p) # Optimize f print('Optimizing objective function ...') scipy.optimize.minimize(f, x0, method='Nelder-Mead', options={'maxiter': maxiter}) # Compute best possible cut value via brute force search all_bitstrings = np.array(list(itertools.product(range(2), repeat=n))) all_values = cut_values(all_bitstrings, graph) max_cut_value = np.max(all_values) # Print the results print('The largest cut value found was {}.'.format(dm_largest_cut_value_found)) print('The largest possible cut has size {}.'.format(max_cut_value)) print('The approximation ratio achieved is {}.'.format( dm_largest_cut_value_found / max_cut_value))
def test_works_on_pauli_string(): a, b = cirq.LineQubit.range(2) c = cirq.Circuit(cirq.X(a) * cirq.X(b)) sim = cirq.Simulator() result = sim.simulate(c).state_vector() np.testing.assert_allclose(result.reshape(4), np.array([0, 0, 0, 1]), atol=1e-8)
def test_expectation_instantiate(self): """Test that Expectation instantiates correctly.""" expectation.Expectation() expectation.Expectation(backend=cirq.Simulator()) expectation.Expectation( differentiator=linear_combination.ForwardDifference())
def create_from_dictionary_sqrt_iswap( cls, parameters: PhasedFsimDictParameters, *, simulator: Optional[cirq.Simulator] = None, ideal_when_missing_gate: bool = False, ideal_when_missing_parameter: bool = False, ) -> 'PhasedFSimEngineSimulator': """Creates PhasedFSimEngineSimulator with fixed drifts. Args: parameters: Parameters to use for each gate. All keys must be stored in canonical order, when the first qubit is not greater than the second one. simulator: Simulator object to use. When None, a new instance of cirq.Simulator() will be created. ideal_when_missing_gate: When set and parameters for some gate for a given pair of qubits are not specified in the parameters dictionary then the FSimGate(theta=π/4, phi=0) gate parameters will be used. When not set and this situation occurs, ValueError is thrown during simulation. ideal_when_missing_parameter: When set and some parameter for some gate for a given pair of qubits is specified then the matching parameter of FSimGate(theta=π/4, phi=0) gate will be used. When not set and this situation occurs, ValueError is thrown during simulation. Returns: New PhasedFSimEngineSimulator instance. """ def sample_gate( a: cirq.Qid, b: cirq.Qid, gate: cirq.FSimGate ) -> PhasedFSimCharacterization: assert isinstance(gate, cirq.FSimGate), f'Expected FSimGate, got {gate}' assert np.isclose(gate.theta, np.pi / 4) and np.isclose( gate.phi, 0.0 ), f'Expected ISWAP ** -0.5 like gate, got {gate}' if (a, b) in parameters: pair_parameters = parameters[(a, b)] if not isinstance(pair_parameters, PhasedFSimCharacterization): pair_parameters = PhasedFSimCharacterization(**pair_parameters) elif (b, a) in parameters: pair_parameters = parameters[(b, a)] if not isinstance(pair_parameters, PhasedFSimCharacterization): pair_parameters = PhasedFSimCharacterization(**pair_parameters) pair_parameters = pair_parameters.parameters_for_qubits_swapped() elif ideal_when_missing_gate: pair_parameters = SQRT_ISWAP_INV_PARAMETERS else: raise ValueError(f'Missing parameters for pair {(a, b)}') if pair_parameters.any_none(): if not ideal_when_missing_parameter: raise ValueError( f'Missing parameter value for pair {(a, b)}, ' f'parameters={pair_parameters}' ) pair_parameters = pair_parameters.merge_with(SQRT_ISWAP_INV_PARAMETERS) return pair_parameters for a, b in parameters: if a > b: raise ValueError( f'All qubit pairs must be given in canonical order where the first qubit is ' f'less than the second, got {a} > {b}' ) if simulator is None: simulator = cirq.Simulator() return cls( simulator, drift_generator=sample_gate, gates_translator=try_convert_sqrt_iswap_to_fsim )