def to_sweeps(sweepable: Sweepable) -> List[Sweep]: """Converts a Sweepable to a list of Sweeps.""" if sweepable is None: return [UnitSweep] if isinstance(sweepable, ParamResolver): return [_resolver_to_sweep(sweepable)] if isinstance(sweepable, Sweep): return [sweepable] if isinstance(sweepable, dict): # change dictionary of lists to list of dictionaries # of single values using Cartesian product. newsweepable = {} for key, value in sweepable.items(): if isinstance(value, Iterable): newsweepable[key] = value else: newsweepable[key] = [value] expandsweepable = [ dict(zip(newsweepable.keys(), v)) for v in itertools.product(*newsweepable.values()) ] return [ _resolver_to_sweep(ParamResolver(cast(Dict, dictitem))) for dictitem in expandsweepable ] if isinstance(sweepable, Iterable) and not isinstance(sweepable, str): return [ sweep for item in sweepable for sweep in to_sweeps( cast(Union[Dict[str, float], ParamResolver, Sweep], item)) ] raise TypeError(f'Unrecognized sweepable type: {type(sweepable)}.\n' f'sweepable: {sweepable}')
def to_resolvers(sweepable: Sweepable) -> Iterator[ParamResolver]: """Convert a Sweepable to a list of ParamResolvers.""" if sweepable is None: yield ParamResolver({}) elif isinstance(sweepable, ParamResolver): yield sweepable elif isinstance(sweepable, Sweep): yield from sweepable elif isinstance(sweepable, dict): yield ParamResolver(cast(Dict, sweepable)) elif isinstance(sweepable, Iterable) and not isinstance(sweepable, str): for item in cast(Iterable, sweepable): yield from to_resolvers(item) else: raise TypeError(f'Unrecognized sweepable type: {type(sweepable)}.\n' f'sweepable: {sweepable}')
def test_param_resolver_exp_w_axis_half_turns(): exp_w = ExpWGate(half_turns=1.0, axis_half_turns=Symbol('a')) circuit = Circuit() circuit.append(exp_w(Q1)) resolver = ParamResolver({'a': 0.5}) result = compute_gate(circuit, resolver) np.testing.assert_almost_equal(result, np.array([[0, -1], [1, 0]]))
def test_param_resolver_exp_w_multiple_params(): exp_w = ExpWGate(half_turns=Symbol('a'), axis_half_turns=Symbol('b')) circuit = Circuit() circuit.append(exp_w(Q1)) resolver = ParamResolver({'a': -0.5, 'b': 0.5}) result = compute_gate(circuit, resolver) amp = 1.0 / math.sqrt(2) np.testing.assert_almost_equal(result, np.array([[amp, amp], [-amp, amp]]))
def test_param_resolver_param_dict(): exp_w = ExpWGate(half_turns=Symbol('a'), axis_half_turns=0.0) circuit = Circuit() circuit.append(exp_w(Q1)) resolver = ParamResolver({'a': 0.5}) simulator = xmon_simulator.XmonSimulator() result = simulator.run(circuit, resolver) assert result.params.param_dict == {'a': 0.5}
def test_param_resolver_exp_11_half_turns(): exp_11 = Exp11Gate(half_turns=Symbol('a')) circuit = Circuit() circuit.append(exp_11(Q1, Q2)) resolver = ParamResolver({'a': 0.5}) result = compute_gate(circuit, resolver, num_qubits=2) # Slight hack: doesn't depend on order of qubits. np.testing.assert_almost_equal( result, np.diag([1, 1, 1, cmath.exp(1j * math.pi * 0.5)]))
def test_param_resolver_exp_z_half_turns(): exp_z = ExpZGate(half_turns=Symbol('a')) circuit = Circuit() circuit.append(exp_z(Q1)) resolver = ParamResolver({'a': -0.5}) result = compute_gate(circuit, resolver) np.testing.assert_almost_equal( result, np.array([[cmath.exp(1j * math.pi * 0.25), 0], [0, cmath.exp(-1j * math.pi * 0.25)]]))
def test_simulator_simulate_trial_result_repr(): v = xmon_simulator.XmonSimulateTrialResult( params=ParamResolver({'a': 2}), measurements={'m': np.array([1, 2])}, final_state=np.array([0, 1, 0, 0])) assert repr(v) == ("XmonSimulateTrialResult(" "params=ParamResolver({'a': 2}), " "measurements={'m': array([1, 2])}, " "final_state=array([0, 1, 0, 0]))")
def to_sweeps(sweepable: Sweepable) -> List[Sweep]: """Converts a Sweepable to a list of Sweeps.""" if isinstance(sweepable, ParamResolver): return [_resolver_to_sweep(sweepable)] if isinstance(sweepable, Sweep): return [sweepable] if isinstance(sweepable, dict): return [_resolver_to_sweep(ParamResolver(cast(Dict, sweepable)))] if isinstance(sweepable, Iterable) and not isinstance(sweepable, str): return [ sweep for item in sweepable for sweep in to_sweeps( cast(Union[Dict[str, float], ParamResolver, Sweep], item)) ] raise TypeError('Unrecognized sweepable type: {type(sweepable)}.\n' 'sweepable: {sweepable}')
def to_resolvers(sweepable: Sweepable) -> List[ParamResolver]: """Convert a Sweepable to a list of ParamResolvers.""" if isinstance(sweepable, ParamResolver): return [sweepable] if isinstance(sweepable, Sweep): return list(sweepable) if isinstance(sweepable, dict): return [ParamResolver(cast(Dict, sweepable))] if isinstance(sweepable, Iterable) and not isinstance(sweepable, str): return [ resolver for item in sweepable for resolver in to_resolvers( cast(Union[Dict[str, float], ParamResolver, Sweep], item)) ] raise TypeError('Unrecognized sweepable type: {type(sweepable)}.\n' 'sweepable: {sweepable}')
def test_circuit_param_and_reps(): sim = xmon_simulator.XmonSimulator() circuit = bit_flip_circuit(Symbol('a'), Symbol('b')) resolvers = [ ParamResolver({ 'a': b1, 'b': b2 }) for b1 in range(2) for b2 in range(2) ] all_trials = sim.run_sweep(circuit, params=resolvers, repetitions=3) assert len(all_trials) == 4 for result in all_trials: assert result.repetitions == 3 expect_a = result.params['a'] == 1 expect_b = result.params['b'] == 1 np.testing.assert_equal(result.measurements['q1'], [[expect_a]] * 3) np.testing.assert_equal(result.measurements['q2'], [[expect_b]] * 3) # All parameters explored. assert (set(itertools.product([0, 1], [0, 1])) == {(r.params['a'], r.params['b']) for r in all_trials})