Beispiel #1
0
def test_dict_to_product_sweep():
    assert cirq.dict_to_product_sweep({'t': [0, 2, 3]}) == (
        cirq.Product(cirq.Points('t', [0, 2, 3]))
    )

    assert cirq.dict_to_product_sweep({'t': [0, 1], 's': [2, 3], 'r': 4}) == (
        cirq.Product(cirq.Points('t', [0, 1]), cirq.Points('s', [2, 3]), cirq.Points('r', [4]))
    )
Beispiel #2
0
    def __init__(self,
                 qubits: Sequence[cirq.Qid],
                 prerotations: Optional[Sequence[Tuple[float, float]]] = None):
        """Initializes the rotation protocol and matrix for system.

        Args:
            qubits: Qubits to do the tomography on.
            prerotations: Tuples of (phase_exponent, exponent) parameters for
                gates to apply to the qubits before measurement. The actual
                rotation applied will be
                    `cirq.PhasedXPowGate(
                        phase_exponent=phase_exponent, exponent=exponent)`
                If none, we use [(0, 0), (0, 0.5), (0.5, 0.5)], which
                corresponds to rotation gates [I, X**0.5, Y**0.5].
        """
        if prerotations is None:
            prerotations = [(0, 0), (0, 0.5), (0.5, 0.5)]
        self.num_qubits = len(qubits)

        phase_exp_vals, exp_vals = zip(*prerotations)

        ops: List[cirq.Operation] = []
        sweeps: List[cirq.Sweep] = []
        for i, qubit in enumerate(qubits):
            phase_exp = sympy.Symbol(f'phase_exp_{i}')
            exp = sympy.Symbol(f'exp_{i}')
            gate = cirq.PhasedXPowGate(phase_exponent=phase_exp, exponent=exp)
            ops.append(gate.on(qubit))
            sweeps.append(
                cirq.Points(phase_exp, phase_exp_vals) +
                cirq.Points(exp, exp_vals))

        self.rot_circuit = cirq.Circuit(ops)
        self.rot_sweep = cirq.Product(*sweeps)
        self.mat = self._make_state_tomography_matrix()
Beispiel #3
0
def sweep_from_proto(param_sweep: params_pb2.ParameterSweep) -> cirq.Sweep:
    if param_sweep.HasField('sweep') and len(param_sweep.sweep.factors) > 0:
        return cirq.Product(*[
            _sweep_from_param_sweep_zip_proto(f)
            for f in param_sweep.sweep.factors
        ])
    return cirq.UnitSweep
Beispiel #4
0
def _to_zip_product(sweep: cirq.Sweep) -> cirq.Product:
    """Converts sweep to a product of zips of single sweeps, if possible."""
    if not isinstance(sweep, cirq.Product):
        sweep = cirq.Product(sweep)
    if not all(isinstance(f, cirq.Zip) for f in sweep.factors):
        factors = [
            f if isinstance(f, cirq.Zip) else cirq.Zip(f)
            for f in sweep.factors
        ]
        sweep = cirq.Product(*factors)
    for factor in sweep.factors:
        for term in cast(cirq.Zip, factor).sweeps:
            if not isinstance(term, sweeps.SingleSweep):
                raise ValueError(
                    f'cannot convert to zip-product form: {sweep}')
    return sweep
Beispiel #5
0
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}')
Beispiel #6
0
def test_gen_param_sweep():
    s1 = {'parameter_key': 'foo', 'points': {'points': [1, 2, 3]}}
    s2 = {'parameter_key': 'bar', 'points': {'points': [4, 5]}}
    ps = {'sweep': {'factors': [{'sweeps': [s1]}, {'sweeps': [s2]}]}}
    out = cg.sweep_from_proto_dict(ps)
    assert out == cirq.Product(cirq.Zip(cirq.Points('foo', [1, 2, 3])),
                               cirq.Zip(cirq.Points('bar', [4, 5])))
Beispiel #7
0
def test_gen_param_sweep():
    ps = params_pb2.ParameterSweep(
        sweep=params_pb2.ProductSweep(
            factors=[
                params_pb2.ZipSweep(
                    sweeps=[
                        params_pb2.SingleSweep(
                            parameter_key='foo', points=params_pb2.Points(points=[1, 2, 3])
                        )
                    ]
                ),
                params_pb2.ZipSweep(
                    sweeps=[
                        params_pb2.SingleSweep(
                            parameter_key='bar', points=params_pb2.Points(points=[4, 5])
                        )
                    ]
                ),
            ]
        )
    )
    out = params.sweep_from_proto(ps)
    assert out == cirq.Product(
        cirq.Zip(cirq.Points('foo', [1, 2, 3])), cirq.Zip(cirq.Points('bar', [4, 5]))
    )
Beispiel #8
0
def test_bad_args():
    with pytest.raises(ValueError, match='repetitions <= 0'):
        _ = cirq.experiments.t2_decay(sampler=cirq.Simulator(),
                                      qubit=cirq.GridQubit(0, 0),
                                      num_points=4,
                                      repetitions=0,
                                      max_delay=cirq.Duration(micros=1))

    with pytest.raises(ValueError, match='max_delay < min_delay'):
        _ = cirq.experiments.t2_decay(sampler=cirq.Simulator(),
                                      qubit=cirq.GridQubit(0, 0),
                                      num_points=4,
                                      repetitions=10,
                                      min_delay=cirq.Duration(micros=1),
                                      max_delay=cirq.Duration(micros=0))

    with pytest.raises(ValueError, match='min_delay < 0'):
        _ = cirq.experiments.t2_decay(sampler=cirq.Simulator(),
                                      qubit=cirq.GridQubit(0, 0),
                                      num_points=4,
                                      repetitions=10,
                                      max_delay=cirq.Duration(micros=1),
                                      min_delay=cirq.Duration(micros=-1))

    with pytest.raises(ValueError, match='not supported'):
        _ = cirq.experiments.t2_decay(sampler=cirq.Simulator(),
                                      qubit=cirq.GridQubit(0, 0),
                                      num_points=4,
                                      repetitions=100,
                                      max_delay=cirq.Duration(micros=1),
                                      experiment_type=t2.ExperimentType.CPMG)
    with pytest.raises(ValueError, match='delay_ns'):
        _ = cirq.experiments.t2_decay(sampler=cirq.Simulator(),
                                      qubit=cirq.GridQubit(0, 0),
                                      num_points=4,
                                      repetitions=10,
                                      max_delay=cirq.Duration(micros=10),
                                      min_delay=cirq.Duration(micros=1),
                                      delay_sweep=cirq.Linspace(
                                          sympy.Symbol('t'),
                                          start=10,
                                          stop=2000,
                                          length=10))
    sweep1 = cirq.Linspace(sympy.Symbol('delay_ns'),
                           start=10,
                           stop=100,
                           length=10)
    sweep2 = cirq.Linspace(sympy.Symbol('t'), start=20, stop=200, length=10)
    product = cirq.Product(sweep1, sweep2)
    with pytest.raises(ValueError, match='delay_ns'):
        _ = cirq.experiments.t2_decay(sampler=cirq.Simulator(),
                                      qubit=cirq.GridQubit(0, 0),
                                      num_points=4,
                                      repetitions=10,
                                      max_delay=cirq.Duration(micros=10),
                                      min_delay=cirq.Duration(micros=1),
                                      delay_sweep=product)
Beispiel #9
0
    return [empty_sweep, empty_product, empty_zip, full_sweep]


@pytest.mark.parametrize('param_sweep', example_sweeps())
def test_param_sweep_size_versus_gen(param_sweep):
    sweep = cg.sweep_from_proto_dict(param_sweep)
    print(sweep)
    predicted_size = len(sweep)
    out = list(sweep)
    assert len(out) == predicted_size


@pytest.mark.parametrize('sweep,expected', [
    (cirq.UnitSweep, cirq.UnitSweep),
    (cirq.Linspace('a', 0, 10,
                   25), cirq.Product(cirq.Zip(cirq.Linspace('a', 0, 10, 25)))),
    (cirq.Points(
        'a', [1, 2, 3]), cirq.Product(cirq.Zip(cirq.Points('a', [1, 2, 3])))),
    (
        cirq.Zip(cirq.Linspace('a', 0, 1, 5), cirq.Points('b', [1, 2, 3])),
        cirq.Product(
            cirq.Zip(cirq.Linspace('a', 0, 1, 5), cirq.Points('b',
                                                              [1, 2, 3]))),
    ),
    (
        cirq.Product(cirq.Linspace('a', 0, 1, 5), cirq.Points('b', [1, 2, 3])),
        cirq.Product(cirq.Zip(cirq.Linspace('a', 0, 1, 5)),
                     cirq.Zip(cirq.Points('b', [1, 2, 3]))),
    ),
    (
        cirq.Product(