def test_parameterize(resolve_fn, global_shift): parameterized_gate = cirq.PhasedXPowGate(exponent=sympy.Symbol('a'), phase_exponent=sympy.Symbol('b'), global_shift=global_shift) assert cirq.pow(parameterized_gate, 5) == cirq.PhasedXPowGate(exponent=sympy.Symbol('a') * 5, phase_exponent=sympy.Symbol('b'), global_shift=global_shift) assert cirq.unitary(parameterized_gate, default=None) is None assert cirq.is_parameterized(parameterized_gate) q = cirq.NamedQubit("q") parameterized_decomposed_circuit = cirq.Circuit( cirq.decompose(parameterized_gate(q))) for resolver in cirq.Linspace('a', 0, 2, 10) * cirq.Linspace( 'b', 0, 2, 10): resolved_gate = resolve_fn(parameterized_gate, resolver) assert resolved_gate == cirq.PhasedXPowGate( exponent=resolver.value_of('a'), phase_exponent=resolver.value_of('b'), global_shift=global_shift, ) np.testing.assert_allclose( cirq.unitary(resolved_gate(q)), cirq.unitary(resolve_fn(parameterized_decomposed_circuit, resolver)), atol=1e-8, ) unparameterized_gate = cirq.PhasedXPowGate(exponent=0.1, phase_exponent=0.2, global_shift=global_shift) assert not cirq.is_parameterized(unparameterized_gate) assert cirq.is_parameterized(unparameterized_gate**sympy.Symbol('a')) assert cirq.is_parameterized(unparameterized_gate**(sympy.Symbol('a') + 1))
def test_estimate_run_batch_time(): qubits = cirq.GridQubit.rect(4, 5) circuit = cirq.testing.random_circuit(qubits[:19], n_moments=40, op_density=1.0) circuit2 = cirq.testing.random_circuit(qubits[:19], n_moments=40, op_density=1.0) circuit3 = cirq.testing.random_circuit(qubits, n_moments=40, op_density=1.0) sweeps_10 = cirq.Linspace('t', 0, 1, 10) sweeps_20 = cirq.Linspace('t', 0, 1, 20) sweeps_30 = cirq.Linspace('t', 0, 1, 30) sweeps_40 = cirq.Linspace('t', 0, 1, 40) # 2 batches with same qubits is the same time as a combined sweep sweep_runtime = runtime_estimator.estimate_run_sweep_time(circuit, sweeps_30, repetitions=1000) batch_runtime = runtime_estimator.estimate_run_batch_time( [circuit, circuit2], [sweeps_10, sweeps_20], repetitions=1000 ) assert sweep_runtime == batch_runtime # 2 batches with same qubits and 1 batch with different qubits # Should be equal to combining the first two batches three_batches = runtime_estimator.estimate_run_batch_time( [circuit, circuit2, circuit3], [sweeps_10, sweeps_20, sweeps_10], repetitions=1000 ) two_batches = runtime_estimator.estimate_run_batch_time( [circuit, circuit3], [sweeps_30, sweeps_10], repetitions=1000 ) assert three_batches == two_batches # The last batch cannot be combined since it has different qubits sweep_runtime = runtime_estimator.estimate_run_sweep_time(circuit, sweeps_40, repetitions=1000) assert three_batches > sweep_runtime
def test_estimate_run_batch_time_average_depths(): qubits = cirq.GridQubit.rect(4, 5) circuit_depth_20 = cirq.testing.random_circuit(qubits, n_moments=20, op_density=1.0) circuit_depth_30 = cirq.testing.random_circuit(qubits, n_moments=30, op_density=1.0) circuit_depth_40 = cirq.testing.random_circuit(qubits, n_moments=40, op_density=1.0) sweeps_10 = cirq.Linspace('t', 0, 1, 10) sweeps_20 = cirq.Linspace('t', 0, 1, 20) depth_20_and_40 = runtime_estimator.estimate_run_batch_time( [circuit_depth_20, circuit_depth_40], [sweeps_10, sweeps_10], repetitions=1000) depth_30 = runtime_estimator.estimate_run_sweep_time(circuit_depth_30, sweeps_20, repetitions=1000) depth_40 = runtime_estimator.estimate_run_sweep_time(circuit_depth_40, sweeps_20, repetitions=1000) assert depth_20_and_40 == depth_30 assert depth_20_and_40 < depth_40
def test_sample_sweep(): q = cirq.NamedQubit('q') c = cirq.Circuit.from_ops(cirq.X(q), cirq.Y(q)**sympy.Symbol('t'), cirq.measure(q)) # Unitary. results = cirq.sample_sweep(c, cirq.Linspace('t', 0, 1, 2), repetitions=3) assert len(results) == 2 assert results[0].histogram(key=q) == collections.Counter({1: 3}) assert results[1].histogram(key=q) == collections.Counter({0: 3}) # Overdamped. c = cirq.Circuit.from_ops(cirq.X(q), cirq.amplitude_damp(1).on(q), cirq.Y(q)**sympy.Symbol('t'), cirq.measure(q)) results = cirq.sample_sweep(c, cirq.Linspace('t', 0, 1, 2), repetitions=3) assert len(results) == 2 assert results[0].histogram(key=q) == collections.Counter({0: 3}) assert results[1].histogram(key=q) == collections.Counter({1: 3}) # Overdamped everywhere. c = cirq.Circuit.from_ops(cirq.X(q), cirq.Y(q)**sympy.Symbol('t'), cirq.measure(q)) results = cirq.sample_sweep(c, cirq.Linspace('t', 0, 1, 2), noise=cirq.ConstantQubitNoiseModel( cirq.amplitude_damp(1)), repetitions=3) assert len(results) == 2 assert results[0].histogram(key=q) == collections.Counter({0: 3}) assert results[1].histogram(key=q) == collections.Counter({0: 3})
def test_reps_and_sweeps(): job = NothingJob( job_id='test', processor_id='grill', parent_program=None, repetitions=100, sweeps=[cirq.Linspace('t', 0, 10, 0.1)], ) assert job.get_repetitions_and_sweeps() == (100, [ cirq.Linspace('t', 0, 10, 0.1) ])
def test_repr(): cirq.testing.assert_equivalent_repr( cirq.study.sweeps.Product(cirq.UnitSweep), setup_code='import cirq\nfrom collections import OrderedDict') cirq.testing.assert_equivalent_repr( cirq.study.sweeps.Zip(cirq.UnitSweep), setup_code='import cirq\nfrom collections import OrderedDict') cirq.testing.assert_equivalent_repr( cirq.ListSweep(cirq.Linspace('a', start=0, stop=3, length=4)), setup_code='import cirq\nfrom collections import OrderedDict') cirq.testing.assert_equivalent_repr(cirq.Points('zero&pi', [0, 3.14159])) cirq.testing.assert_equivalent_repr(cirq.Linspace('I/10', 0, 1, 10))
def test_parameterized_decompose(): angles = sympy.symbols('x0, x1, x2, x3') parameterized_op = cirq.TwoQubitDiagonalGate(angles).on( *cirq.LineQubit.range(2)) decomposed_circuit = cirq.Circuit(cirq.decompose(parameterized_op)) for resolver in (cirq.Linspace('x0', -2, 2, 3) * cirq.Linspace('x1', -2, 2, 3) * cirq.Linspace('x2', -2, 2, 3) * cirq.Linspace('x3', -2, 2, 3)): np.testing.assert_allclose( cirq.unitary(cirq.resolve_parameters(parameterized_op, resolver)), cirq.unitary(cirq.resolve_parameters(decomposed_circuit, resolver)), )
def test_equality(): et = cirq.testing.EqualsTester() et.add_equality_group(cirq.UnitSweep, cirq.UnitSweep) # Simple sweeps with the same key are equal to themselves, but different # from each other even if they happen to contain the same points. et.make_equality_group(lambda: cirq.Linspace('a', 0, 10, 11)) et.make_equality_group(lambda: cirq.Linspace('b', 0, 10, 11)) et.make_equality_group(lambda: cirq.Points('a', list(range(11)))) et.make_equality_group(lambda: cirq.Points('b', list(range(11)))) # Product and Zip sweeps can also be equated. et.make_equality_group(lambda: cirq.Linspace('a', 0, 5, 6) * cirq.Linspace('b', 10, 15, 6)) et.make_equality_group(lambda: cirq.Linspace('a', 0, 5, 6) + cirq.Linspace('b', 10, 15, 6)) et.make_equality_group( lambda: cirq.Points('a', [1, 2]) * (cirq.Linspace('b', 0, 5, 6) + cirq.Linspace('c', 10, 15, 6)) ) # ListSweep et.make_equality_group( lambda: cirq.ListSweep([{'var': 1}, {'var': -1}]), lambda: cirq.ListSweep(({'var': 1}, {'var': -1})), lambda: cirq.ListSweep(r for r in ({'var': 1}, {'var': -1})), ) et.make_equality_group(lambda: cirq.ListSweep([{'var': -1}, {'var': 1}])) et.make_equality_group(lambda: cirq.ListSweep([{'var': 1}])) et.make_equality_group(lambda: cirq.ListSweep([{'x': 1}, {'x': -1}]))
def test_run_circuit_sweeps(): circuit = cirq.Circuit.from_ops( cirq.X(Q1)**sympy.Symbol('a'), cirq.measure(Q1, key='m'), device=test_device, ) sweep = cirq.Linspace('a', 0, 5, 6) sweep2 = cirq.Linspace('a', 6, 10, 5) simulator = cg.XmonSimulator() for i, result in enumerate( simulator.run_sweep(circuit, [sweep, sweep2], repetitions=1)): assert result.params['a'] == i np.testing.assert_equal(result.measurements['m'], [[i % 2 != 0]])
def test_sampler_sample_sweep(): a = cirq.LineQubit(0) t = sympy.Symbol('t') sampler = cirq.Simulator() circuit = cirq.Circuit(cirq.X(a)**t, cirq.measure(a, key='out')) results = sampler.sample(circuit, repetitions=3, params=cirq.Linspace('t', 0, 2, 3)) pd.testing.assert_frame_equal( results, pd.DataFrame( columns=['t', 'out'], index=[0, 1, 2] * 3, data=[ [0.0, 0], [0.0, 0], [0.0, 0], [1.0, 1], [1.0, 1], [1.0, 1], [2.0, 0], [2.0, 0], [2.0, 0], ], ), )
def test_transform_sweep(): qubit = cirq.LineQubit(0) a = sympy.Symbol('a') circuit = cirq.Circuit.from_ops( cirq.X(qubit)**(a / 4), cirq.X(qubit)**(1 + a / 2), ) sweep = cirq.Linspace(a, start=0, stop=3, length=4) _, new_sweep = cirq.flatten_with_sweep(circuit, sweep) assert isinstance(new_sweep, cirq.Sweep) resolvers = list(new_sweep) expected_resolvers = [ cirq.ParamResolver({ '<a/4>': 0.0, '<a/2 + 1>': 1.0, }), cirq.ParamResolver({ '<a/4>': 0.25, '<a/2 + 1>': 1.5, }), cirq.ParamResolver({ '<a/4>': 0.5, '<a/2 + 1>': 2, }), cirq.ParamResolver({ '<a/4>': 0.75, '<a/2 + 1>': 2.5, }) ] assert resolvers == expected_resolvers
def sweep_from_proto(msg: run_context_pb2.Sweep) -> cirq.Sweep: """Creates a Sweep from a v2 protobuf message.""" which = msg.WhichOneof('sweep') if which is None: return cirq.UnitSweep if which == 'sweep_function': factors = [sweep_from_proto(m) for m in msg.sweep_function.sweeps] func_type = msg.sweep_function.function_type if func_type == run_context_pb2.SweepFunction.PRODUCT: return cirq.Product(*factors) if func_type == run_context_pb2.SweepFunction.ZIP: return cirq.Zip(*factors) raise ValueError(f'invalid sweep function type: {func_type}') if which == 'single_sweep': key = msg.single_sweep.parameter_key if msg.single_sweep.WhichOneof('sweep') == 'linspace': return cirq.Linspace( key=key, start=msg.single_sweep.linspace.first_point, stop=msg.single_sweep.linspace.last_point, length=msg.single_sweep.linspace.num_points, ) if msg.single_sweep.WhichOneof('sweep') == 'points': return cirq.Points(key=key, points=msg.single_sweep.points.points) raise ValueError(f'single sweep type not set: {msg}') # coverage: ignore raise ValueError(f'sweep type not set: {msg}')
def test_batch_run_context_to_proto(pass_out: bool) -> None: msg = v2.batch_pb2.BatchRunContext() if pass_out else None out = v2.batch_run_context_to_proto([], out=msg) if pass_out: assert out is msg assert len(out.run_contexts) == 0 msg = v2.batch_pb2.BatchRunContext() if pass_out else None out = v2.batch_run_context_to_proto([(None, 10)], out=msg) if pass_out: assert out is msg assert len(out.run_contexts) == 1 sweep_message = out.run_contexts[0].parameter_sweeps[0] assert v2.sweep_from_proto(sweep_message.sweep) == cirq.UnitSweep assert sweep_message.repetitions == 10 sweep = cirq.Linspace('a', 0, 1, 21) msg = v2.batch_pb2.BatchRunContext() if pass_out else None out = v2.batch_run_context_to_proto([(None, 10), (sweep, 100)], out=msg) if pass_out: assert out is msg assert len(out.run_contexts) == 2 sweep_message0 = out.run_contexts[0].parameter_sweeps[0] assert v2.sweep_from_proto(sweep_message0.sweep) == cirq.UnitSweep assert sweep_message0.repetitions == 10 sweep_message1 = out.run_contexts[1].parameter_sweeps[0] assert v2.sweep_from_proto(sweep_message1.sweep) == sweep assert sweep_message1.repetitions == 100
def test_linspace(): sweep = cirq.Linspace('a', 0.34, 9.16, 7) assert len(sweep) == 7 params = list(sweep.param_tuples()) assert len(params) == 7 assert params[0] == (('a', 0.34), ) assert params[-1] == (('a', 9.16), )
def test_run_sweep_with_parameter_sweep(adonis_sampler_without_settings): client = mock(IQMClient) run_id = uuid.uuid4() run_result = RunResult(status=RunStatus.READY, measurements=[{ 'some stuff': [[0]] }, { 'some stuff': [[1]] }], message=None) when(client).submit_circuits(ANY, ANY, ANY).thenReturn(run_id) when(client).wait_for_results(run_id).thenReturn(run_result) qubit_1 = cirq.NamedQubit('QB1') qubit_2 = cirq.NamedQubit('QB2') circuit_sweep = cirq.Circuit( cirq.X(qubit_1)**sympy.Symbol('t'), cirq.measure(qubit_1, qubit_2, key='result')) sweep_length = 2 param_sweep = cirq.Linspace('t', start=0, stop=1, length=sweep_length) adonis_sampler_without_settings._client = client results = adonis_sampler_without_settings.run_sweep(circuit_sweep, param_sweep, repetitions=123) assert len(results) == sweep_length assert all(isinstance(result, cirq.Result) for result in results)
def test_aqt_sampler_error_handling(): for e_return in [ EngineError(), EngineErrorSecond(), EngineNoStatus(), EngineNoStatus2(), EngineNoid(), ]: with mock.patch('cirq_aqt.aqt_sampler.put', return_value=e_return, side_effect=e_return.update) as _mock_method: theta = sympy.Symbol('theta') num_points = 1 max_angle = np.pi repetitions = 10 sampler = AQTSampler(remote_host="http://localhost:5000", access_token='testkey') _, qubits = get_aqt_device(1) circuit = cirq.Circuit(cirq.X(qubits[0])**theta) sweep = cirq.Linspace(key='theta', start=0.1, stop=max_angle / np.pi, length=num_points) with pytest.raises(RuntimeError): _results = sampler.run_sweep(circuit, params=sweep, repetitions=repetitions)
def test_aqt_sampler_sim(): theta = sympy.Symbol('theta') num_points = 10 max_angle = np.pi repetitions = 1000 num_qubits = 4 _, qubits = get_aqt_device(num_qubits) sampler = AQTSamplerLocalSimulator() sampler.simulate_ideal = True circuit = cirq.Circuit( cirq.X(qubits[3])**theta, cirq.X(qubits[0]), cirq.X(qubits[0]), cirq.X(qubits[1]), cirq.X(qubits[1]), cirq.X(qubits[2]), cirq.X(qubits[2]), ) circuit.append( cirq.PhasedXPowGate(phase_exponent=0.5, exponent=-0.5).on(qubits[0])) circuit.append( cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.5).on(qubits[0])) sweep = cirq.Linspace(key='theta', start=0.1, stop=max_angle / np.pi, length=num_points) results = sampler.run_sweep(circuit, params=sweep, repetitions=repetitions) excited_state_probs = np.zeros(num_points) for i in range(num_points): excited_state_probs[i] = np.mean(results[i].measurements['m']) assert excited_state_probs[-1] == 0.25
def test_aqt_sampler(): put_call_args0 = { 'access_token': 'testkey', 'id': '2131da', } e_return = EngineReturn() with mock.patch('cirq_aqt.aqt_sampler.put', return_value=e_return, side_effect=e_return.update) as mock_method: theta = sympy.Symbol('theta') num_points = 1 max_angle = np.pi repetitions = 10 sampler = AQTSampler(remote_host="http://localhost:5000", access_token='testkey') _, qubits = get_aqt_device(1) circuit = cirq.Circuit(cirq.X(qubits[0])**theta) sweep = cirq.Linspace(key='theta', start=0.1, stop=max_angle / np.pi, length=num_points) results = sampler.run_sweep(circuit, params=sweep, repetitions=repetitions) excited_state_probs = np.zeros(num_points) for i in range(num_points): excited_state_probs[i] = np.mean(results[i].measurements['m']) callargs = mock_method.call_args[1]['data'] for keys in put_call_args0: assert callargs[keys] == put_call_args0[keys] assert mock_method.call_count == 3
def test_gen_sweep_linspace(): sweep = params_pb2.SingleSweep(parameter_key='foo', linspace=params_pb2.Linspace(first_point=0, last_point=10, num_points=11)) out = params._sweep_from_single_param_sweep_proto(sweep) assert out == cirq.Linspace('foo', 0, 10, 11)
def _create_rep_rate_circuit( parameterized: bool, gate: cirq.Gate, qubits: List[cirq.Qid], depth: int, num_sweeps: Optional[int]) -> Tuple[cirq.Circuit, cirq.Sweep]: """Creates a testing circuit based on parameters. The circuit will be of alternating single and two qubit layers using the qubits specified and a number of moments specified by depth. This function will also create a sweep if parameterized is true, by parameterized all single qubit layers with random values for angles. """ c = cirq.Circuit() symbol_count = 0 for layer in range(depth): if layer % 2: moment, symbol_count = _sq_layer(qubits, parameterized, symbol_count) c.append(moment) else: c.append(_entangling_layer(gate, qubits)) c.append(cirq.Moment(cirq.measure(*qubits))) if not parameterized: return (c, None) sweeps = cirq.Zip(*[ cirq.Linspace('s_%d' % i, start=0, stop=1, length=num_sweeps) for i in range(symbol_count) ]) return (c, sweeps)
def test_estimate_run_sweep_time(depth, width, sweeps, reps, expected): """Test various run times. Values taken from Weber November 2021.""" qubits = cirq.GridQubit.rect(8, 8) circuit = cirq.testing.random_circuit(qubits[:depth], n_moments=width, op_density=1.0) params = cirq.Linspace('t', 0, 1, sweeps) runtime = runtime_estimator.estimate_run_sweep_time(circuit, params, repetitions=reps) _assert_about_equal(runtime, expected)
def test_linspace_sympy_symbol(): a = sympy.Symbol('a') sweep = cirq.Linspace(a, 0.34, 9.16, 7) assert len(sweep) == 7 params = list(sweep.param_tuples()) assert len(params) == 7 assert params[0] == (('a', 0.34), ) assert params[-1] == (('a', 9.16), )
def parametric_circuit_with_params() -> Tuple[cirq.Circuit, cirq.Linspace]: q = cirq.GridQubit(1, 1) circuit = cirq.Circuit( cirq.X(q)**sympy.Symbol('t'), cirq.measure(q, key='m')) # Sweep exponent from zero (off) to one (on) and back to two (off) param_sweep = cirq.Linspace('t', start=0, stop=2, length=5) return circuit, param_sweep
def test_sweep_with_flattened_sweep(): q = cirq.GridQubit(0, 0) circuit = cirq.Circuit.from_ops( cirq.PhasedXPowGate(exponent=sympy.Symbol('t') / 4 + 0.5, phase_exponent=sympy.Symbol('t') / 2 + 0.1, global_shift=0.0)(q), cirq.measure(q, key='m')) param_sweep1 = cirq.Linspace('t', start=0, stop=1, length=20) (_, param_sweep2) = cirq.flatten_with_sweep(circuit, param_sweep1) assert v2.sweep_to_proto(param_sweep2) is not None
def test_sweep_to_proto_linspace(): proto = v2.sweep_to_proto(cirq.Linspace('foo', 0, 1, 20)) assert isinstance(proto, v2.run_context_pb2.Sweep) assert proto.HasField('single_sweep') assert proto.single_sweep.parameter_key == 'foo' assert proto.single_sweep.WhichOneof('sweep') == 'linspace' assert proto.single_sweep.linspace.first_point == 0 assert proto.single_sweep.linspace.last_point == 1 assert proto.single_sweep.linspace.num_points == 20
def test_transformed_sweep_equality(): a = sympy.Symbol('a') sweep = cirq.Linspace('a', start=0, stop=3, length=4) expr_map = cirq.ExpressionMap({a / 4: 'x0', 1 - a / 4: 'x1'}) sweep2 = cirq.Linspace(a, start=0, stop=3, length=4) expr_map2 = cirq.ExpressionMap({a / 4: 'x0', 1 - a / 4: 'x1'}) sweep3 = cirq.Linspace(a, start=0, stop=3, length=20) expr_map3 = cirq.ExpressionMap({a / 20: 'x0', 1 - a / 20: 'x1'}) et = cirq.testing.EqualsTester() et.make_equality_group(lambda: expr_map.transform_sweep(sweep), lambda: expr_map.transform_sweep(sweep2), lambda: expr_map2.transform_sweep(sweep2)) et.add_equality_group(expr_map.transform_sweep(sweep3)) et.add_equality_group(expr_map3.transform_sweep(sweep)) et.add_equality_group(expr_map3.transform_sweep(sweep3))
def test_sample_sweep_seed(): q = cirq.NamedQubit('q') circuit = cirq.Circuit.from_ops(cirq.X(q)**0.5, cirq.measure(q)) results = cirq.sample_sweep(circuit, cirq.Linspace('t', 0, 1, 3), repetitions=2, seed=1234) assert np.all(results[0].measurements['q'] == [[False], [True]]) assert np.all(results[1].measurements['q'] == [[False], [True]]) assert np.all(results[2].measurements['q'] == [[True], [False]])
def test_repr(): cirq.testing.assert_equivalent_repr( cirq.study.sweeps.Product(cirq.UnitSweep), setup_code='import cirq\nfrom collections import OrderedDict') cirq.testing.assert_equivalent_repr( cirq.study.sweeps.Zip(cirq.UnitSweep), setup_code='import cirq\nfrom collections import OrderedDict') cirq.testing.assert_equivalent_repr( cirq.ListSweep(cirq.Linspace('a', start=0, stop=3, length=4)), setup_code='import cirq\nfrom collections import OrderedDict')