Example #1
0
def test_xeb_parse_result_failure():
    gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0)
    request = XEBPhasedFSimCalibrationRequest(
        gate=gate,
        pairs=(),
        options=XEBPhasedFSimCalibrationOptions(
            fsim_options=XEBPhasedFSimCharacterizationOptions(
                characterize_theta=False,
                characterize_zeta=False,
                characterize_chi=False,
                characterize_gamma=False,
                characterize_phi=True,
            )),
    )

    result = cirq_google.CalibrationResult(
        code=cirq_google.api.v2.calibration_pb2.ERROR_CALIBRATION_FAILED,
        error_message="Test message",
        token=None,
        valid_until=None,
        metrics=cirq_google.Calibration(),
    )

    with pytest.raises(PhasedFSimCalibrationError, match='Test message'):
        request.parse_result(result)
Example #2
0
def test_xeb_parse_result():
    q_00, q_01, q_02, q_03 = [cirq.GridQubit(0, index) for index in range(4)]
    gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0)
    request = XEBPhasedFSimCalibrationRequest(
        gate=gate,
        pairs=((q_00, q_01), (q_02, q_03)),
        options=XEBPhasedFSimCalibrationOptions(
            fsim_options=XEBPhasedFSimCharacterizationOptions(
                characterize_theta=False,
                characterize_zeta=False,
                characterize_chi=False,
                characterize_gamma=False,
                characterize_phi=True,
            )),
    )

    result = _load_xeb_results_textproto()
    assert request.parse_result(result) == PhasedFSimCalibrationResult(
        parameters={
            (q_00, q_01): PhasedFSimCharacterization(phi=0.0,
                                                     theta=-0.7853981),
            (q_02, q_03): PhasedFSimCharacterization(phi=0.0,
                                                     theta=-0.7853981),
        },
        gate=gate,
        options=request.options,
    )
Example #3
0
def test_xeb_to_calibration_layer():
    q_00, q_01, q_02, q_03 = [cirq.GridQubit(0, index) for index in range(4)]
    gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0)
    request = XEBPhasedFSimCalibrationRequest(
        gate=gate,
        pairs=((q_00, q_01), (q_02, q_03)),
        options=XEBPhasedFSimCalibrationOptions(
            n_library_circuits=22,
            fsim_options=XEBPhasedFSimCharacterizationOptions(
                characterize_theta=True,
                characterize_zeta=True,
                characterize_chi=False,
                characterize_gamma=False,
                characterize_phi=True,
            ),
        ),
    )
    layer = request.to_calibration_layer()
    assert layer == cirq_google.CalibrationLayer(
        calibration_type='xeb_phased_fsim_characterization',
        program=cirq.Circuit([gate.on(q_00, q_01),
                              gate.on(q_02, q_03)]),
        args={
            'n_library_circuits': 22,
            'n_combinations': 10,
            'cycle_depths': '5_25_50_100_200_300',
            'fatol': 5e-3,
            'xatol': 5e-3,
            'characterize_theta': True,
            'characterize_zeta': True,
            'characterize_chi': False,
            'characterize_gamma': False,
            'characterize_phi': True,
            'theta_default': 0.0,
            'zeta_default': 0.0,
            'chi_default': 0.0,
            'gamma_default': 0.0,
            'phi_default': 0.0,
        },
    )

    # Serialize to proto
    calibration = v2.calibration_pb2.FocusedCalibration()
    new_layer = calibration.layers.add()
    new_layer.calibration_type = layer.calibration_type
    for arg in layer.args:
        arg_to_proto(layer.args[arg], out=new_layer.args[arg])
    cirq_google.SQRT_ISWAP_GATESET.serialize(layer.program,
                                             msg=new_layer.layer)
    with open(
            os.path.dirname(__file__) +
            '/test_data/xeb_calibration_layer.textproto') as f:
        desired_textproto = f.read()

    layer_str = str(new_layer)
    # Fix precision issues
    layer_str = re.sub(r'0.004999\d+', '0.005', layer_str)
    assert layer_str == desired_textproto
Example #4
0
def test_run_calibration(monkeypatch):
    monkeypatch.setattr('cirq.experiments.xeb_fitting.scipy.optimize.minimize', _minimize_patch)
    monkeypatch.setattr(
        'cirq_google.calibration.xeb_wrapper.xebf.benchmark_2q_xeb_fidelities', _benchmark_patch
    )
    qubit_indices = [
        (0, 5),
        (0, 6),
        (1, 6),
        (2, 6),
    ]
    qubits = [cirq.GridQubit(*idx) for idx in qubit_indices]
    sampler = cirq.ZerosSampler()

    circuits = [
        random_rotations_between_grid_interaction_layers_circuit(
            qubits,
            depth=depth,
            two_qubit_op_factory=lambda a, b, _: SQRT_ISWAP.on(a, b),
            pattern=cirq.experiments.GRID_ALIGNED_PATTERN,
            seed=10,
        )
        for depth in [5, 10]
    ]

    options = LocalXEBPhasedFSimCalibrationOptions(
        fsim_options=XEBPhasedFSimCharacterizationOptions(
            characterize_zeta=True,
            characterize_gamma=True,
            characterize_chi=True,
            characterize_theta=False,
            characterize_phi=False,
            theta_default=np.pi / 4,
        ),
        n_processes=1,
    )

    characterization_requests = []
    for circuit in circuits:
        _, characterization_requests = cg.prepare_characterization_for_moments(
            circuit, options=options, initial=characterization_requests
        )
    assert len(characterization_requests) == 2
    for cr in characterization_requests:
        assert isinstance(cr, LocalXEBPhasedFSimCalibrationRequest)

    characterizations = [
        run_local_xeb_calibration(request, sampler) for request in characterization_requests
    ]

    final_params = dict()
    for c in characterizations:
        final_params.update(c.parameters)
    assert len(final_params) == 3  # pairs
Example #5
0
def test_options_with_defaults_from_gate():
    options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.ISWAP ** 0.5)
    np.testing.assert_allclose(options.theta_default, -np.pi / 4)
    options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.ISWAP ** -0.5)
    np.testing.assert_allclose(options.theta_default, np.pi / 4)

    options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(
        cirq.FSimGate(0.1, 0.2)
    )
    assert options.theta_default == 0.1
    assert options.phi_default == 0.2

    options = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(
        cirq.PhasedFSimGate(0.1)
    )
    assert options.theta_default == 0.1
    assert options.phi_default == 0.0
    assert options.zeta_default == 0.0

    with pytest.raises(ValueError):
        _ = XEBPhasedFSimCharacterizationOptions().with_defaults_from_gate(cirq.CZ)
Example #6
0
def test_options_defaults_set():
    o1 = XEBPhasedFSimCharacterizationOptions(
        characterize_zeta=True,
        characterize_chi=True,
        characterize_gamma=True,
        characterize_theta=False,
        characterize_phi=False,
    )
    assert o1.defaults_set() is False
    with pytest.raises(ValueError):
        o1.get_initial_simplex_and_names()

    o2 = XEBPhasedFSimCharacterizationOptions(
        characterize_zeta=True,
        characterize_chi=True,
        characterize_gamma=True,
        characterize_theta=False,
        characterize_phi=False,
        zeta_default=0.1,
        chi_default=0.2,
        gamma_default=0.3,
    )
    with pytest.raises(ValueError):
        _ = o2.defaults_set()

    o3 = XEBPhasedFSimCharacterizationOptions(
        characterize_zeta=True,
        characterize_chi=True,
        characterize_gamma=True,
        characterize_theta=False,
        characterize_phi=False,
        zeta_default=0.1,
        chi_default=0.2,
        gamma_default=0.3,
        theta_default=0.0,
        phi_default=0.0,
    )
    assert o3.defaults_set() is True
Example #7
0
        final_simplex=None,
    )


def _benchmark_patch(*args, **kwargs):
    return pd.DataFrame()


@pytest.mark.parametrize(
    ['fsim_options', 'x0_should_be'],
    [
        (
            XEBPhasedFSimCharacterizationOptions(
                characterize_zeta=True,
                characterize_gamma=True,
                characterize_chi=True,
                characterize_theta=False,
                characterize_phi=False,
            ),
            [0.0, 0.0, 0.0],
        ),
        (XEBPhasedFSimCharacterizationOptions(),
         [np.pi / 4, 0.0, 0.0, 0.0, 0.0]),
        (
            XEBPhasedFSimCharacterizationOptions(
                characterize_zeta=True,
                characterize_chi=True,
                characterize_gamma=True,
                characterize_theta=False,
                characterize_phi=False,
                theta_default=99,
Example #8
0
class XEBPhasedFSimCalibrationOptions(PhasedFSimCalibrationOptions):
    """Options for configuring a PhasedFSim calibration using XEB.

    XEB uses the fidelity of random circuits to characterize PhasedFSim gates. The parameters
    of the gate are varied by a classical optimizer to maximize the observed fidelities.

    Args:
        n_library_circuits: The number of distinct, two-qubit random circuits to use in our
            library of random circuits. This should be the same order of magnitude as
            `n_combinations`.
        n_combinations: We take each library circuit and randomly assign it to qubit pairs.
            This parameter controls the number of random combinations of the two-qubit random
            circuits we execute. Higher values increase the precision of estimates but linearly
            increase experimental runtime.
        cycle_depths: We run the random circuits at these cycle depths to fit an exponential
            decay in the fidelity.
        fatol: The absolute convergence tolerance for the objective function evaluation in
            the Nelder-Mead optimization. This controls the runtime of the classical
            characterization optimization loop.
        xatol: The absolute convergence tolerance for the parameter estimates in
            the Nelder-Mead optimization. This controls the runtime of the classical
            characterization optimization loop.
        fsim_options: An instance of `XEBPhasedFSimCharacterizationOptions` that controls aspects
            of the PhasedFSim characterization like initial guesses and which angles to
            characterize.
    """

    n_library_circuits: int = 20
    n_combinations: int = 10
    cycle_depths: Tuple[int, ...] = _DEFAULT_XEB_CYCLE_DEPTHS
    fatol: Optional[float] = 5e-3
    xatol: Optional[float] = 5e-3

    fsim_options: XEBPhasedFSimCharacterizationOptions = XEBPhasedFSimCharacterizationOptions(
    )

    def to_args(self) -> Dict[str, Any]:
        """Convert this dataclass to an `args` dictionary suitable for sending to the Quantum
        Engine calibration API."""
        args: Dict[str, Any] = {
            'n_library_circuits': self.n_library_circuits,
            'n_combinations': self.n_combinations,
            'cycle_depths': '_'.join(f'{cd:d}' for cd in self.cycle_depths),
        }
        if self.fatol is not None:
            args['fatol'] = self.fatol
        if self.xatol is not None:
            args['xatol'] = self.xatol

        fsim_options = dataclasses.asdict(self.fsim_options)
        fsim_options = {k: v for k, v in fsim_options.items() if v is not None}
        args.update(fsim_options)
        return args

    def create_phased_fsim_request(
        self,
        pairs: Tuple[Tuple[cirq.Qid, cirq.Qid], ...],
        gate: cirq.Gate,
    ) -> 'XEBPhasedFSimCalibrationRequest':
        return XEBPhasedFSimCalibrationRequest(pairs=pairs,
                                               gate=gate,
                                               options=self)

    @classmethod
    def _from_json_dict_(cls, **kwargs):
        del kwargs['cirq_type']
        kwargs['cycle_depths'] = tuple(kwargs['cycle_depths'])
        return cls(**kwargs)
Example #9
0
"""Floquet PhasedFSimCalibrationOptions options with all angles characterization requests set to
True."""
ALL_ANGLES_FLOQUET_PHASED_FSIM_CHARACTERIZATION = FloquetPhasedFSimCalibrationOptions(
    characterize_theta=True,
    characterize_zeta=True,
    characterize_chi=True,
    characterize_gamma=True,
    characterize_phi=True,
)
"""XEB PhasedFSimCalibrationOptions options with all angles characterization requests set to
True."""
ALL_ANGLES_XEB_PHASED_FSIM_CHARACTERIZATION = XEBPhasedFSimCalibrationOptions(
    fsim_options=XEBPhasedFSimCharacterizationOptions(
        characterize_theta=True,
        characterize_zeta=True,
        characterize_chi=True,
        characterize_gamma=True,
        characterize_phi=True,
    ))
"""PhasedFSimCalibrationOptions with all but chi angle characterization requests set to True."""
WITHOUT_CHI_FLOQUET_PHASED_FSIM_CHARACTERIZATION = FloquetPhasedFSimCalibrationOptions(
    characterize_theta=True,
    characterize_zeta=True,
    characterize_chi=False,
    characterize_gamma=True,
    characterize_phi=True,
)
"""PhasedFSimCalibrationOptions with theta, zeta and gamma angles characterization requests set to
True.

Those are the most efficient options that can be used to cancel out the errors by adding the