Esempio n. 1
0
def test_try_convert_sqrt_iswap_to_fsim_converts_correctly():
    expected = cirq.FSimGate(theta=np.pi / 4, phi=0)
    expected_unitary = cirq.unitary(expected)

    fsim = cirq.FSimGate(theta=np.pi / 4, phi=0)
    assert np.allclose(cirq.unitary(fsim), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(fsim) == expected
    assert try_convert_sqrt_iswap_to_fsim(cirq.FSimGate(theta=np.pi / 4, phi=0.1)) is None
    assert try_convert_sqrt_iswap_to_fsim(cirq.FSimGate(theta=np.pi / 3, phi=0)) is None

    phased_fsim = cirq.PhasedFSimGate(theta=np.pi / 4, phi=0)
    assert np.allclose(cirq.unitary(phased_fsim), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(phased_fsim) == expected
    assert (
        try_convert_sqrt_iswap_to_fsim(cirq.PhasedFSimGate(theta=np.pi / 4, zeta=0.1, phi=0))
        is None
    )

    iswap_pow = cirq.ISwapPowGate(exponent=-0.5)
    assert np.allclose(cirq.unitary(iswap_pow), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(iswap_pow) == expected
    assert try_convert_sqrt_iswap_to_fsim(cirq.ISwapPowGate(exponent=-0.4)) is None

    phased_iswap_pow = cirq.PhasedISwapPowGate(exponent=0.5, phase_exponent=-0.5)
    assert np.allclose(cirq.unitary(phased_iswap_pow), expected_unitary)
    assert try_convert_sqrt_iswap_to_fsim(phased_iswap_pow) == expected
    assert (
        try_convert_sqrt_iswap_to_fsim(cirq.PhasedISwapPowGate(exponent=-0.5, phase_exponent=0.1))
        is None
    )

    assert try_convert_sqrt_iswap_to_fsim(cirq.CZ) is None
Esempio n. 2
0
def test_from_characterizations_sqrt_iswap_simulates_correctly() -> None:
    parameters_ab = cirq.google.PhasedFSimCharacterization(theta=0.6,
                                                           zeta=0.5,
                                                           chi=0.4,
                                                           gamma=0.3,
                                                           phi=0.2)
    parameters_bc = cirq.google.PhasedFSimCharacterization(theta=0.8,
                                                           zeta=-0.5,
                                                           chi=-0.4,
                                                           gamma=-0.3,
                                                           phi=-0.2)
    parameters_cd = cirq.google.PhasedFSimCharacterization(theta=0.1,
                                                           zeta=0.2,
                                                           chi=0.3,
                                                           gamma=0.4,
                                                           phi=0.5)

    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit([
        [cirq.X(a), cirq.Y(c)],
        [
            cirq.FSimGate(np.pi / 4, 0.0).on(a, b),
            cirq.FSimGate(np.pi / 4, 0.0).on(c, d)
        ],
        [cirq.FSimGate(np.pi / 4, 0.0).on(c, b)],
    ])
    expected_circuit = cirq.Circuit([
        [cirq.X(a), cirq.X(c)],
        [
            cirq.PhasedFSimGate(**parameters_ab.asdict()).on(a, b),
            cirq.PhasedFSimGate(**parameters_cd.asdict()).on(c, d),
        ],
        [cirq.PhasedFSimGate(**parameters_bc.asdict()).on(b, c)],
    ])

    engine_simulator = PhasedFSimEngineSimulator.create_from_characterizations_sqrt_iswap(
        characterizations=[
            cirq.google.PhasedFSimCalibrationResult(
                gate=cirq.FSimGate(np.pi / 4, 0.0),
                parameters={
                    (a, b): parameters_ab,
                    (c, d): parameters_cd
                },
                options=ALL_ANGLES_FLOQUET_PHASED_FSIM_CHARACTERIZATION,
            ),
            cirq.google.PhasedFSimCalibrationResult(
                gate=cirq.FSimGate(np.pi / 4, 0.0),
                parameters={
                    (c, b): parameters_bc.parameters_for_qubits_swapped()
                },
                options=ALL_ANGLES_FLOQUET_PHASED_FSIM_CHARACTERIZATION,
            ),
        ])

    actual = engine_simulator.final_state_vector(circuit)
    expected = cirq.final_state_vector(expected_circuit)

    assert cirq.allclose_up_to_global_phase(actual, expected)
Esempio n. 3
0
def test_from_dictionary_sqrt_iswap_simulates_correctly() -> None:
    parameters_ab = cirq.google.PhasedFSimCharacterization(theta=0.6,
                                                           zeta=0.5,
                                                           chi=0.4,
                                                           gamma=0.3,
                                                           phi=0.2)
    parameters_bc = cirq.google.PhasedFSimCharacterization(theta=0.8,
                                                           zeta=-0.5,
                                                           chi=-0.4,
                                                           gamma=-0.3,
                                                           phi=-0.2)
    parameters_cd_dict = {
        'theta': 0.1,
        'zeta': 0.2,
        'chi': 0.3,
        'gamma': 0.4,
        'phi': 0.5
    }

    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit([
        [cirq.X(a), cirq.Y(c)],
        [
            cirq.FSimGate(np.pi / 4, 0.0).on(a, b),
            cirq.FSimGate(np.pi / 4, 0.0).on(d, c)
        ],
        [cirq.FSimGate(np.pi / 4, 0.0).on(b, c)],
        [
            cirq.FSimGate(np.pi / 4, 0.0).on(a, b),
            cirq.FSimGate(np.pi / 4, 0.0).on(c, d)
        ],
    ])
    expected_circuit = cirq.Circuit([
        [cirq.X(a), cirq.X(c)],
        [
            cirq.PhasedFSimGate(**parameters_ab.asdict()).on(a, b),
            cirq.PhasedFSimGate(**parameters_cd_dict).on(c, d),
        ],
        [cirq.PhasedFSimGate(**parameters_bc.asdict()).on(b, c)],
        [
            cirq.PhasedFSimGate(**parameters_ab.asdict()).on(a, b),
            cirq.PhasedFSimGate(**parameters_cd_dict).on(c, d),
        ],
    ])

    engine_simulator = PhasedFSimEngineSimulator.create_from_dictionary_sqrt_iswap(
        parameters={
            (a, b): parameters_ab,
            (b, c): parameters_bc,
            (c, d): parameters_cd_dict
        })

    actual = engine_simulator.final_state_vector(circuit)
    expected = cirq.final_state_vector(expected_circuit)

    assert cirq.allclose_up_to_global_phase(actual, expected)
Esempio n. 4
0
def test_phased_fsim_circuit():
    a, b = cirq.LineQubit.range(2)
    c = cirq.Circuit(
        cirq.PhasedFSimGate(np.pi / 2, np.pi, np.pi / 2, 0,
                            -np.pi / 4).on(a, b),
        cirq.PhasedFSimGate(-np.pi, np.pi / 2, np.pi / 10, np.pi / 5,
                            3 * np.pi / 10).on(a, b),
    )
    cirq.testing.assert_has_diagram(
        c,
        """
0: ───PhFSim(0.5π, π, 0.5π, 0, -0.25π)───PhFSim(-π, 0.5π, 0.1π, 0.2π, 0.3π)───
      │                                  │
1: ───PhFSim(0.5π, π, 0.5π, 0, -0.25π)───PhFSim(-π, 0.5π, 0.1π, 0.2π, 0.3π)───
    """,
    )
    # pylint: disable=line-too-long
    cirq.testing.assert_has_diagram(
        c,
        """
0: ---PhFSim(0.5pi, pi, 0.5pi, 0, -0.25pi)---PhFSim(-pi, 0.5pi, 0.1pi, 0.2pi, 0.3pi)---
      |                                      |
1: ---PhFSim(0.5pi, pi, 0.5pi, 0, -0.25pi)---PhFSim(-pi, 0.5pi, 0.1pi, 0.2pi, 0.3pi)---
        """,
        use_unicode_characters=False,
    )
    cirq.testing.assert_has_diagram(
        c,
        """
0: ---PhFSim(1.5707963267948966, pi, 1.5707963267948966, 0, -0.7853981633974483)---PhFSim(-pi, 1.5707963267948966, 0.3141592653589793, 0.6283185307179586, 0.9424777960769379)---
      |                                                                            |
1: ---PhFSim(1.5707963267948966, pi, 1.5707963267948966, 0, -0.7853981633974483)---PhFSim(-pi, 1.5707963267948966, 0.3141592653589793, 0.6283185307179586, 0.9424777960769379)---
""",
        use_unicode_characters=False,
        precision=None,
    )
    # pylint: enable=line-too-long
    c = cirq.Circuit(
        cirq.PhasedFSimGate(
            sympy.Symbol('a') + sympy.Symbol('b'),
            0,
            sympy.Symbol('c'),
            sympy.Symbol('d'),
            sympy.Symbol('a') - sympy.Symbol('b'),
        ).on(a, b))
    cirq.testing.assert_has_diagram(
        c,
        """
0: ───PhFSim(a + b, 0, c, d, a - b)───
      │
1: ───PhFSim(a + b, 0, c, d, a - b)───
    """,
    )
Esempio n. 5
0
def test_phased_fsim_init():
    f = cirq.PhasedFSimGate(1, 2, 3, 4, 5)
    assert f.theta == 1
    assert f.zeta == 2
    assert f.chi == 3
    assert f.gamma == 4 - 2 * np.pi
    assert f.phi == 5 - 2 * np.pi

    f2 = cirq.PhasedFSimGate(theta=1, zeta=2, chi=3, gamma=4, phi=5)
    assert f2.theta == 1
    assert f2.zeta == 2
    assert f2.chi == 3
    assert f2.gamma == 4 - 2 * np.pi
    assert f2.phi == 5 - 2 * np.pi
Esempio n. 6
0
def test_with_random_gaussian_sqrt_iswap_simulates_correctly() -> None:
    engine_simulator = PhasedFSimEngineSimulator.create_with_random_gaussian_sqrt_iswap(
        mean=SQRT_ISWAP_PARAMETERS,
        sigma=PhasedFSimCharacterization(theta=0.02,
                                         zeta=0.05,
                                         chi=0.05,
                                         gamma=None,
                                         phi=0.02),
    )

    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit([
        [cirq.X(a), cirq.Y(c)],
        [
            cirq.FSimGate(np.pi / 4, 0.0).on(a, b),
            cirq.FSimGate(np.pi / 4, 0.0).on(c, d)
        ],
        [cirq.FSimGate(np.pi / 4, 0.0).on(b, c)],
        [
            cirq.FSimGate(np.pi / 4, 0.0).on(b, a),
            cirq.FSimGate(np.pi / 4, 0.0).on(d, c)
        ],
    ])

    calibrations = engine_simulator.get_calibrations([
        _create_sqrt_iswap_request([(a, b), (c, d)]),
        _create_sqrt_iswap_request([(b, c)])
    ])
    parameters = collections.ChainMap(*(calibration.parameters
                                        for calibration in calibrations))

    expected_circuit = cirq.Circuit([
        [cirq.X(a), cirq.X(c)],
        [
            cirq.PhasedFSimGate(**parameters[(a, b)].asdict()).on(a, b),
            cirq.PhasedFSimGate(**parameters[(c, d)].asdict()).on(c, d),
        ],
        [cirq.PhasedFSimGate(**parameters[(b, c)].asdict()).on(b, c)],
        [
            cirq.PhasedFSimGate(**parameters[(a, b)].asdict()).on(a, b),
            cirq.PhasedFSimGate(**parameters[(c, d)].asdict()).on(c, d),
        ],
    ])

    actual = engine_simulator.final_state_vector(circuit)
    expected = cirq.final_state_vector(expected_circuit)

    assert cirq.allclose_up_to_global_phase(actual, expected)
Esempio n. 7
0
def test_phase_calibrated_fsim_gate_compensated(phase_exponent: float):
    a, b = cirq.LineQubit.range(2)
    ideal_gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0)
    characterized_gate = cirq.PhasedFSimGate(theta=ideal_gate.theta,
                                             zeta=0.1,
                                             chi=0.2,
                                             gamma=0.3,
                                             phi=ideal_gate.phi)
    parameters = PhasedFSimCharacterization(
        theta=ideal_gate.theta,
        zeta=characterized_gate.zeta,
        chi=characterized_gate.chi,
        gamma=characterized_gate.gamma,
        phi=ideal_gate.phi,
    )

    calibrated = PhaseCalibratedFSimGate(ideal_gate,
                                         phase_exponent=phase_exponent)

    # Passing characterized_gate as engine_gate simulates the hardware execution.
    operations = calibrated.with_zeta_chi_gamma_compensated(
        (a, b), parameters, engine_gate=characterized_gate)

    cirq.testing.assert_allclose_up_to_global_phase(
        cirq.unitary(cirq.Circuit(operations)),
        cirq.unitary(
            cirq.Circuit([
                [cirq.Z(a)**-phase_exponent,
                 cirq.Z(b)**phase_exponent],
                ideal_gate.on(a, b),
                [cirq.Z(a)**phase_exponent,
                 cirq.Z(b)**-phase_exponent],
            ])),
        atol=1e-8,
    )
def test_with_params_opid_with_gate():
    # Test gate-based opid with_params.
    q0, q1 = cirq.LineQubit.range(2)
    props = sample_noise_properties([q0, q1], [(q0, q1), (q1, q0)])
    expected_vals = {
        'gate_pauli_errors': 0.096,
        'fsim_errors': cirq.PhasedFSimGate(0.0971, 0.0972, 0.0973, 0.0974,
                                           0.0975),
    }
    props_v2 = props.with_params(
        gate_pauli_errors={
            cirq.PhasedXZGate: expected_vals['gate_pauli_errors']
        },
        fsim_errors={cirq.CZPowGate: expected_vals['fsim_errors']},
    )
    assert props_v2 != props
    gpe_op_id_0 = cirq.OpIdentifier(cirq.PhasedXZGate, q0)
    gpe_op_id_1 = cirq.OpIdentifier(cirq.PhasedXZGate, q1)
    assert props_v2.gate_pauli_errors[gpe_op_id_0] == expected_vals[
        'gate_pauli_errors']
    assert props_v2.gate_pauli_errors[gpe_op_id_1] == expected_vals[
        'gate_pauli_errors']

    fsim_op_id_0 = cirq.OpIdentifier(cirq.CZPowGate, q0, q1)
    fsim_op_id_1 = cirq.OpIdentifier(cirq.CZPowGate, q1, q0)
    assert props_v2.fsim_errors[fsim_op_id_0] == expected_vals['fsim_errors']
    assert props_v2.fsim_errors[fsim_op_id_1] == expected_vals['fsim_errors']
Esempio n. 9
0
def test_phase_corrected_fsim_operations_with_phase_exponent(
        theta: float, zeta: float, chi: float, gamma: float,
        phi: float) -> None:
    a, b = cirq.LineQubit.range(2)

    phase_exponent = 0.5

    # Theta is negated to match the phase exponent of 0.5.
    expected_gate = cirq.PhasedFSimGate(theta=-theta,
                                        zeta=-zeta,
                                        chi=-chi,
                                        gamma=-gamma,
                                        phi=phi)
    expected = cirq.unitary(expected_gate)

    corrected = workflow.FSimPhaseCorrections.from_characterization(
        (a, b),
        PhaseCalibratedFSimGate(cirq.FSimGate(theta=theta, phi=phi),
                                phase_exponent),
        cirq_google.PhasedFSimCharacterization(theta=theta,
                                               zeta=zeta,
                                               chi=chi,
                                               gamma=gamma,
                                               phi=phi),
        characterization_index=5,
    )
    actual = cirq.unitary(corrected.as_circuit())

    assert cirq.equal_up_to_global_phase(actual, expected)
    assert corrected.moment_to_calibration == [None, 5, None]
Esempio n. 10
0
def sample_noise_properties(
    system_qubits: List[cirq.Qid], qubit_pairs: List[Tuple[cirq.Qid, cirq.Qid]]
):
    # Known false positive: https://github.com/PyCQA/pylint/issues/5857
    return GoogleNoiseProperties(  # pylint: disable=unexpected-keyword-arg
        gate_times_ns=DEFAULT_GATE_NS,
        t1_ns={q: 1e5 for q in system_qubits},
        tphi_ns={q: 2e5 for q in system_qubits},
        readout_errors={q: np.array([SINGLE_QUBIT_ERROR, TWO_QUBIT_ERROR]) for q in system_qubits},
        gate_pauli_errors={
            **{
                OpIdentifier(g, q): 0.001
                for g in GoogleNoiseProperties.single_qubit_gates()
                for q in system_qubits
            },
            **{
                OpIdentifier(g, q0, q1): 0.01
                for g in GoogleNoiseProperties.symmetric_two_qubit_gates()
                for q0, q1 in qubit_pairs
            },
        },
        fsim_errors={
            OpIdentifier(g, q0, q1): cirq.PhasedFSimGate(0.01, 0.03, 0.04, 0.05, 0.02)
            for g in GoogleNoiseProperties.symmetric_two_qubit_gates()
            for q0, q1 in qubit_pairs
        },
    )
Esempio n. 11
0
def test_fsim_phase_corrections(theta: float, zeta: float, chi: float,
                                gamma: float, phi: float) -> None:
    a, b = cirq.LineQubit.range(2)

    expected_gate = cirq.PhasedFSimGate(theta=theta,
                                        zeta=-zeta,
                                        chi=-chi,
                                        gamma=-gamma,
                                        phi=phi)
    expected = cirq.unitary(expected_gate)

    corrected = workflow.FSimPhaseCorrections.from_characterization(
        (a, b),
        cirq.FSimGate(theta=theta, phi=phi),
        cirq.google.PhasedFSimCharacterization(theta=theta,
                                               zeta=zeta,
                                               chi=chi,
                                               gamma=gamma,
                                               phi=phi),
        5,
    )
    actual = cirq.unitary(corrected.as_circuit())

    assert cirq.equal_up_to_global_phase(actual, expected)
    assert corrected.moment_to_calibration == [None, 5, None]
Esempio n. 12
0
def test_phase_calibrated_fsim_gate_as_characterized_phased_fsim_gate(
        phase_exponent: float):
    a, b = cirq.LineQubit.range(2)
    ideal_gate = cirq.FSimGate(theta=np.pi / 4, phi=0.0)
    characterized_gate = cirq.PhasedFSimGate(theta=ideal_gate.theta,
                                             zeta=0.1,
                                             chi=0.2,
                                             gamma=0.3,
                                             phi=ideal_gate.phi)
    parameters = PhasedFSimCharacterization(
        theta=ideal_gate.theta,
        zeta=characterized_gate.zeta,
        chi=characterized_gate.chi,
        gamma=characterized_gate.gamma,
        phi=ideal_gate.phi,
    )

    calibrated = PhaseCalibratedFSimGate(ideal_gate,
                                         phase_exponent=phase_exponent)
    phased_gate = calibrated.as_characterized_phased_fsim_gate(parameters).on(
        a, b)

    assert np.allclose(
        cirq.unitary(phased_gate),
        cirq.unitary(
            cirq.Circuit([
                [cirq.Z(a)**-phase_exponent,
                 cirq.Z(b)**phase_exponent],
                characterized_gate.on(a, b),
                [cirq.Z(a)**phase_exponent,
                 cirq.Z(b)**-phase_exponent],
            ])),
    )
Esempio n. 13
0
def test_with_params_target():
    # Test targeted-value with_params.
    q0, q1 = cirq.LineQubit.range(2)
    props = sample_noise_properties([q0, q1], [(q0, q1), (q1, q0)])
    expected_vals = {
        'gate_times_ns': {cirq.ZPowGate: 91},
        't1_ns': {q0: 92},
        'tphi_ns': {q1: 93},
        'readout_errors': {q0: [0.094, 0.095]},
        'gate_pauli_errors': {cirq.OpIdentifier(cirq.PhasedXZGate, q1): 0.096},
        'fsim_errors': {
            cirq.OpIdentifier(cirq.CZPowGate, q0, q1): cirq.PhasedFSimGate(
                0.0971, 0.0972, 0.0973, 0.0974, 0.0975
            )
        },
    }
    props_v2 = props.with_params(
        gate_times_ns=expected_vals['gate_times_ns'],
        t1_ns=expected_vals['t1_ns'],
        tphi_ns=expected_vals['tphi_ns'],
        readout_errors=expected_vals['readout_errors'],
        gate_pauli_errors=expected_vals['gate_pauli_errors'],
        fsim_errors=expected_vals['fsim_errors'],
    )
    assert props_v2 != props
    for field_name, expected in expected_vals.items():
        target_dict = getattr(props_v2, field_name)
        for key, val in expected.items():
            if isinstance(target_dict[key], np.ndarray):
                assert np.allclose(target_dict[key], val)
            else:
                assert target_dict[key] == val
Esempio n. 14
0
def test_phased_fsim_consistent(theta, zeta, chi, gamma, phi):
    gate = cirq.PhasedFSimGate(theta=theta,
                               zeta=zeta,
                               chi=chi,
                               gamma=gamma,
                               phi=phi)
    cirq.testing.assert_implements_consistent_protocols(gate)
Esempio n. 15
0
def test_from_dictionary_sqrt_iswap_ideal_when_missing_simulates_correctly(
) -> None:
    parameters_ab = cirq.google.PhasedFSimCharacterization(theta=0.6,
                                                           zeta=0.5,
                                                           chi=0.4,
                                                           gamma=0.3,
                                                           phi=0.2)
    parameters_bc = cirq.google.PhasedFSimCharacterization(theta=0.8,
                                                           zeta=-0.5,
                                                           chi=-0.4)

    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit([
        [cirq.X(a), cirq.Y(c)],
        [
            cirq.FSimGate(np.pi / 4, 0.0).on(a, b),
            cirq.FSimGate(np.pi / 4, 0.0).on(c, d)
        ],
        [cirq.FSimGate(np.pi / 4, 0.0).on(b, c)],
    ])
    expected_circuit = cirq.Circuit([
        [cirq.X(a), cirq.X(c)],
        [
            cirq.PhasedFSimGate(**parameters_ab.asdict()).on(a, b),
            cirq.PhasedFSimGate(**SQRT_ISWAP_PARAMETERS.asdict()).on(c, d),
        ],
        [
            cirq.PhasedFSimGate(
                **parameters_bc.merge_with(SQRT_ISWAP_PARAMETERS).asdict()).on(
                    b, c)
        ],
    ])

    engine_simulator = PhasedFSimEngineSimulator.create_from_dictionary_sqrt_iswap(
        parameters={
            (a, b): parameters_ab,
            (b, c): parameters_bc
        },
        ideal_when_missing_parameter=True,
        ideal_when_missing_gate=True,
    )

    actual = engine_simulator.final_state_vector(circuit)
    expected = cirq.final_state_vector(expected_circuit)

    assert cirq.allclose_up_to_global_phase(actual, expected)
Esempio n. 16
0
def test_phased_fsim_repr():
    f = cirq.PhasedFSimGate(
        sympy.Symbol('a'),
        sympy.Symbol('b'),
        sympy.Symbol('c'),
        sympy.Symbol('d'),
        sympy.Symbol('e'),
    )
    cirq.testing.assert_equivalent_repr(f)
Esempio n. 17
0
def test_phased_fsim_json_dict():
    assert cirq.PhasedFSimGate(
        theta=0.12, zeta=0.34, chi=0.56, gamma=0.78, phi=0.9
    )._json_dict_() == {
        'theta': 0.12,
        'zeta': 0.34,
        'chi': 0.56,
        'gamma': 0.78,
        'phi': 0.9,
    }
Esempio n. 18
0
def test_create_from_dictionary_simulates_correctly():
    parameters_ab_1 = {'theta': 0.6, 'zeta': 0.5, 'chi': 0.4, 'gamma': 0.3, 'phi': 0.2}
    parameters_ab_2 = {'theta': 0.1, 'zeta': 0.2, 'chi': 0.3, 'gamma': 0.4, 'phi': 0.5}
    parameters_bc = {'theta': 0.8, 'zeta': -0.5, 'chi': -0.4, 'gamma': -0.3, 'phi': -0.2}
    parameters_cd = {'theta': 0.1, 'zeta': 0.2, 'chi': 0.3, 'gamma': 0.4, 'phi': 0.5}

    a, b, c, d = cirq.LineQubit.range(4)
    circuit = cirq.Circuit(
        [
            [cirq.X(a), cirq.Y(b), cirq.Z(c), cirq.H(d)],
            [SQRT_ISWAP_INV_GATE.on(a, b), SQRT_ISWAP_INV_GATE.on(d, c)],
            [SQRT_ISWAP_INV_GATE.on(b, c)],
            [cirq_google.SYC.on(a, b), SQRT_ISWAP_INV_GATE.on(c, d)],
        ]
    )
    expected_circuit = cirq.Circuit(
        [
            [cirq.X(a), cirq.Y(b), cirq.Z(c), cirq.H(d)],
            [
                cirq.PhasedFSimGate(**parameters_ab_1).on(a, b),
                cirq.PhasedFSimGate(**parameters_cd).on(c, d),
            ],
            [cirq.PhasedFSimGate(**parameters_bc).on(b, c)],
            [
                cirq.PhasedFSimGate(**parameters_ab_2).on(a, b),
                cirq.PhasedFSimGate(**parameters_cd).on(c, d),
            ],
        ]
    )

    engine_simulator = PhasedFSimEngineSimulator.create_from_dictionary(
        parameters={
            (a, b): {SQRT_ISWAP_INV_GATE: parameters_ab_1, cirq_google.SYC: parameters_ab_2},
            (b, c): {SQRT_ISWAP_INV_GATE: parameters_bc},
            (c, d): {SQRT_ISWAP_INV_GATE: parameters_cd},
        }
    )

    actual = engine_simulator.final_state_vector(circuit)
    expected = cirq.final_state_vector(expected_circuit)

    assert cirq.allclose_up_to_global_phase(actual, expected)
Esempio n. 19
0
 def _convert_to_phased_fsim(
         self, g: POSSIBLE_FSIM_GATES) -> Optional[cirq.PhasedFSimGate]:
     if isinstance(g, cirq.PhasedFSimGate):
         return g
     chi = 0
     if isinstance(g, cirq.PhasedISwapPowGate):
         chi = g.phase_exponent * 2 * np.pi
         g = g._iswap
     fsim = self._convert_to_fsim(g)
     return None if fsim is None else cirq.PhasedFSimGate(
         fsim.theta, 0, chi, 0, fsim.phi)
Esempio n. 20
0
def test_phased_fsim_resolve():
    f = cirq.PhasedFSimGate(sympy.Symbol('a'), sympy.Symbol('b'),
                            sympy.Symbol('c'), sympy.Symbol('d'),
                            sympy.Symbol('e'))
    assert cirq.is_parameterized(f)

    f = cirq.resolve_parameters(f, {'a': 1})
    assert f == cirq.PhasedFSimGate(1, sympy.Symbol('b'), sympy.Symbol('c'),
                                    sympy.Symbol('d'), sympy.Symbol('e'))
    assert cirq.is_parameterized(f)

    f = cirq.resolve_parameters(f, {'b': 2})
    assert f == cirq.PhasedFSimGate(1, 2, sympy.Symbol('c'), sympy.Symbol('d'),
                                    sympy.Symbol('e'))
    assert cirq.is_parameterized(f)

    f = cirq.resolve_parameters(f, {'c': 3})
    assert f == cirq.PhasedFSimGate(1, 2, 3, sympy.Symbol('d'),
                                    sympy.Symbol('e'))
    assert cirq.is_parameterized(f)

    f = cirq.resolve_parameters(f, {'d': 4})
    assert f == cirq.PhasedFSimGate(1, 2, 3, 4, sympy.Symbol('e'))
    assert cirq.is_parameterized(f)

    f = cirq.resolve_parameters(f, {'e': 5})
    assert f == cirq.PhasedFSimGate(1, 2, 3, 4, 5)
    assert not cirq.is_parameterized(f)
Esempio n. 21
0
def test_try_convert_syc_or_sqrt_iswap_to_fsim():
    def check_converts(gate: cirq.Gate):
        result = try_convert_syc_or_sqrt_iswap_to_fsim(gate)
        assert np.allclose(cirq.unitary(gate), cirq.unitary(result))

    def check_none(gate: cirq.Gate):
        assert try_convert_syc_or_sqrt_iswap_to_fsim(gate) is None

    check_converts(cirq_google.ops.SYC)
    check_converts(cirq.FSimGate(np.pi / 2, np.pi / 6))
    check_none(cirq.FSimGate(0, np.pi))
    check_converts(cirq.FSimGate(np.pi / 4, 0.0))
    check_none(cirq.FSimGate(0.2, 0.3))
    check_converts(cirq.ISwapPowGate(exponent=0.5))
    check_converts(cirq.ISwapPowGate(exponent=-0.5))
    check_none(cirq.ISwapPowGate(exponent=0.3))
    check_converts(cirq.PhasedFSimGate(theta=np.pi / 4, phi=0.0, chi=0.7))
    check_none(cirq.PhasedFSimGate(theta=0.3, phi=0.4))
    check_converts(cirq.PhasedISwapPowGate(exponent=0.5, phase_exponent=0.75))
    check_none(cirq.PhasedISwapPowGate(exponent=0.4, phase_exponent=0.75))
    check_none(cirq.ops.CZPowGate(exponent=1.0))
    check_none(cirq.CX)
Esempio n. 22
0
def test_gate_translators_are_consistent():
    def check(gate):
        result1 = try_convert_gate_to_fsim(gate)
        result2 = try_convert_sqrt_iswap_to_fsim(gate)
        assert result1 == result2
        assert result1 is not None

    check(cirq.FSimGate(theta=np.pi / 4, phi=0))
    check(cirq.FSimGate(theta=-np.pi / 4, phi=0))
    check(cirq.FSimGate(theta=7 * np.pi / 4, phi=0))
    check(cirq.PhasedFSimGate(theta=np.pi / 4, phi=0))
    check(cirq.ISwapPowGate(exponent=0.5))
    check(cirq.ISwapPowGate(exponent=-0.5))
    check(cirq.PhasedISwapPowGate(exponent=0.5, phase_exponent=-0.5))
Esempio n. 23
0
def test_supertype_match():
    # Verifies that ops in gate_pauli_errors which only appear as their
    # supertypes in fsim_errors are properly accounted for.
    q0, q1 = cirq.LineQubit.range(2)
    op_id = OpIdentifier(cirq_google.SycamoreGate, q0, q1)
    test_props = sample_noise_properties([q0, q1], [(q0, q1), (q1, q0)])
    expected_err = test_props._depolarizing_error[op_id]

    props = sample_noise_properties([q0, q1], [(q0, q1), (q1, q0)])
    props.fsim_errors = {
        k: cirq.PhasedFSimGate(0.5, 0.4, 0.3, 0.2, 0.1)
        for k in [OpIdentifier(cirq.FSimGate, q0, q1), OpIdentifier(cirq.FSimGate, q1, q0)]
    }
    assert props._depolarizing_error[op_id] != expected_err
def test_with_params_fill():
    # Test single-value with_params.
    q0, q1 = cirq.LineQubit.range(2)
    props = sample_noise_properties([q0, q1], [(q0, q1), (q1, q0)])
    expected_vals = {
        'gate_times_ns': 91,
        't1_ns': 92,
        'tphi_ns': 93,
        'readout_errors': [0.094, 0.095],
        'gate_pauli_errors': 0.096,
        'fsim_errors': cirq.PhasedFSimGate(0.0971, 0.0972, 0.0973, 0.0974,
                                           0.0975),
    }
    props_v2 = props.with_params(
        gate_times_ns=expected_vals['gate_times_ns'],
        t1_ns=expected_vals['t1_ns'],
        tphi_ns=expected_vals['tphi_ns'],
        readout_errors=expected_vals['readout_errors'],
        gate_pauli_errors=expected_vals['gate_pauli_errors'],
        fsim_errors=expected_vals['fsim_errors'],
    )
    assert props_v2 != props
    for key in props.gate_times_ns:
        assert key in props_v2.gate_times_ns
        assert props_v2.gate_times_ns[key] == expected_vals['gate_times_ns']
    for key in props.t1_ns:
        assert key in props_v2.t1_ns
        assert props_v2.t1_ns[key] == expected_vals['t1_ns']
    for key in props.tphi_ns:
        assert key in props_v2.tphi_ns
        assert props_v2.tphi_ns[key] == expected_vals['tphi_ns']
    for key in props.readout_errors:
        assert key in props_v2.readout_errors
        assert np.allclose(props_v2.readout_errors[key],
                           expected_vals['readout_errors'])
    for key in props.gate_pauli_errors:
        assert key in props_v2.gate_pauli_errors
        assert props_v2.gate_pauli_errors[key] == expected_vals[
            'gate_pauli_errors']
    for key in props.fsim_errors:
        assert key in props_v2.fsim_errors
        assert props_v2.fsim_errors[key] == expected_vals['fsim_errors']
Esempio n. 25
0
    def as_characterized_phased_fsim_gate(
            self,
            parameters: PhasedFSimCharacterization) -> cirq.PhasedFSimGate:
        """Creates a PhasedFSimGate which represents the characterized engine_gate but includes
        deviations in unitary parameters.

        Args:
            parameters: The results of characterization of the engine gate.

        Returns:
            Instance of PhasedFSimGate that executes a gate according to the characterized
            parameters of the engine_gate.
        """
        return cirq.PhasedFSimGate(
            theta=parameters.theta,
            zeta=parameters.zeta,
            chi=parameters.chi - 2 * np.pi * self.phase_exponent,
            gamma=parameters.gamma,
            phi=parameters.phi,
        )
Esempio n. 26
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)
Esempio n. 27
0
def test_phased_setters_deprecated():
    gate = cirq.PhasedFSimGate(0.1, 0.1, 0.1, 0.1, 0.1)
    assert gate.theta == 0.1
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.theta = 0.2
        assert gate.theta == 0.2
    assert gate.zeta == 0.1
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.zeta = 0.2
        assert gate.zeta == 0.2
    assert gate.chi == 0.1
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.chi = 0.2
        assert gate.chi == 0.2
    assert gate.gamma == 0.1
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.gamma = 0.2
        assert gate.gamma == 0.2
    assert gate.phi == 0.1
    with cirq.testing.assert_deprecated('mutators', deadline='v0.15'):
        gate.phi = 0.2
        assert gate.phi == 0.2
Esempio n. 28
0
def test_phased_fsim_vs_fsim(theta, phi):
    g1 = cirq.FSimGate(theta, phi)
    g2 = cirq.PhasedFSimGate(theta, 0, 0, 0, phi)
    assert np.allclose(cirq.unitary(g1), cirq.unitary(g2))
    )
    cirq.testing.assert_circuits_with_terminal_measurements_are_equivalent(c_orig, c_new, atol=1e-6)
    assert all(
        (
            all_gates_of_type(m, cirq.Gateset(cirq.PhasedXZGate))
            or all_gates_of_type(m, cirq.Gateset(cirq.SQRT_ISWAP_INV))
        )
        for m in c_new
    )


@pytest.mark.parametrize(
    'gate',
    [
        cirq.CNotPowGate(exponent=sympy.Symbol('t')),
        cirq.PhasedFSimGate(theta=sympy.Symbol('t'), chi=sympy.Symbol('t'), phi=sympy.Symbol('t')),
    ],
)
@pytest.mark.parametrize('use_sqrt_iswap_inv', [True, False])
def test_two_qubit_gates_with_symbols(gate: cirq.Gate, use_sqrt_iswap_inv: bool):
    # Note that even though these gates are not natively supported by
    # `cirq.parameterized_2q_op_to_sqrt_iswap_operations`, the transformation succeeds because
    # `cirq.optimize_for_target_gateset` also relies on `cirq.decompose` as a fallback.

    c_orig = cirq.Circuit(gate(*cirq.LineQubit.range(2)))
    c_new = cirq.optimize_for_target_gateset(
        c_orig,
        gateset=cirq.SqrtIswapTargetGateset(
            use_sqrt_iswap_inv=use_sqrt_iswap_inv,
            additional_gates=[cirq.XPowGate, cirq.YPowGate, cirq.ZPowGate],
        ),
def test_noise_properties_from_calibration():
    qubits = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(1, 0)]
    pauli_error = [0.001, 0.002, 0.003]
    incoherent_error = [0.0001, 0.0002, 0.0003]
    p00_error = [0.004, 0.005, 0.006]
    p11_error = [0.007, 0.008, 0.009]
    t1_micros = [10, 20, 30]
    syc_pauli = [0.01, 0.02]
    iswap_pauli = [0.03, 0.04]
    syc_angles = [
        cirq.PhasedFSimGate(theta=0.011, phi=-0.021),
        cirq.PhasedFSimGate(theta=-0.012, phi=0.022),
    ]
    iswap_angles = [
        cirq.PhasedFSimGate(theta=-0.013, phi=0.023),
        cirq.PhasedFSimGate(theta=0.014, phi=-0.024),
    ]

    _CALIBRATION_DATA = Merge(
        f"""
    timestamp_ms: 1579214873,
    metrics: [{{
        name: 'single_qubit_rb_pauli_error_per_gate',
        targets: ['0_0'],
        values: [{{
            double_val: {pauli_error[0]}
        }}]
    }}, {{
        name: 'single_qubit_rb_pauli_error_per_gate',
        targets: ['0_1'],
        values: [{{
            double_val:{pauli_error[1]}
        }}]
    }}, {{
        name: 'single_qubit_rb_pauli_error_per_gate',
        targets: ['1_0'],
        values: [{{
            double_val:{pauli_error[2]}
        }}]
    }}, {{
        name: 'single_qubit_rb_incoherent_error_per_gate',
        targets: ['0_0'],
        values: [{{
            double_val: {incoherent_error[0]}
        }}]
    }}, {{
        name: 'single_qubit_rb_incoherent_error_per_gate',
        targets: ['0_1'],
        values: [{{
            double_val:{incoherent_error[1]}
        }}]
    }}, {{
        name: 'single_qubit_rb_incoherent_error_per_gate',
        targets: ['1_0'],
        values: [{{
            double_val:{incoherent_error[2]}
        }}]
    }}, {{
        name: 'single_qubit_p00_error',
        targets: ['0_0'],
        values: [{{
            double_val: {p00_error[0]}
        }}]
    }}, {{
        name: 'single_qubit_p00_error',
        targets: ['0_1'],
        values: [{{
            double_val: {p00_error[1]}
        }}]
    }}, {{
        name: 'single_qubit_p00_error',
        targets: ['1_0'],
        values: [{{
            double_val: {p00_error[2]}
        }}]
    }}, {{
        name: 'single_qubit_p11_error',
        targets: ['0_0'],
        values: [{{
            double_val: {p11_error[0]}
        }}]
    }}, {{
        name: 'single_qubit_p11_error',
        targets: ['0_1'],
        values: [{{
            double_val: {p11_error[1]}
        }}]
    }}, {{
        name: 'single_qubit_p11_error',
        targets: ['1_0'],
        values: [{{
            double_val: {p11_error[2]}
        }}]
    }}, {{
        name: 'single_qubit_idle_t1_micros',
        targets: ['0_0'],
        values: [{{
            double_val: {t1_micros[0]}
        }}]
    }}, {{
        name: 'single_qubit_idle_t1_micros',
        targets: ['0_1'],
        values: [{{
            double_val: {t1_micros[1]}
        }}]
    }}, {{
        name: 'single_qubit_idle_t1_micros',
        targets: ['1_0'],
        values: [{{
            double_val: {t1_micros[2]}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sycamore_gate_xeb_pauli_error_per_cycle',
        targets: ['0_0', '0_1'],
        values: [{{
            double_val: {syc_pauli[0]}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sycamore_gate_xeb_pauli_error_per_cycle',
        targets: ['0_0', '1_0'],
        values: [{{
            double_val: {syc_pauli[1]}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sqrt_iswap_gate_xeb_pauli_error_per_cycle',
        targets: ['0_0', '0_1'],
        values: [{{
            double_val: {iswap_pauli[0]}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sqrt_iswap_gate_xeb_pauli_error_per_cycle',
        targets: ['0_0', '1_0'],
        values: [{{
            double_val: {iswap_pauli[1]}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sycamore_gate_xeb_entangler_theta_error_per_cycle',
        targets: ['0_0', '0_1'],
        values: [{{
            double_val: {syc_angles[0].theta}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sycamore_gate_xeb_entangler_theta_error_per_cycle',
        targets: ['0_0', '1_0'],
        values: [{{
            double_val: {syc_angles[1].theta}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sqrt_iswap_gate_xeb_entangler_theta_error_per_cycle',
        targets: ['0_0', '0_1'],
        values: [{{
            double_val: {iswap_angles[0].theta}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sqrt_iswap_gate_xeb_entangler_theta_error_per_cycle',
        targets: ['0_0', '1_0'],
        values: [{{
            double_val: {iswap_angles[1].theta}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sycamore_gate_xeb_entangler_phi_error_per_cycle',
        targets: ['0_0', '0_1'],
        values: [{{
            double_val: {syc_angles[0].phi}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sycamore_gate_xeb_entangler_phi_error_per_cycle',
        targets: ['0_0', '1_0'],
        values: [{{
            double_val: {syc_angles[1].phi}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sqrt_iswap_gate_xeb_entangler_phi_error_per_cycle',
        targets: ['0_0', '0_1'],
        values: [{{
            double_val: {iswap_angles[0].phi}
        }}]
    }}, {{
        name: 'two_qubit_parallel_sqrt_iswap_gate_xeb_entangler_phi_error_per_cycle',
        targets: ['0_0', '1_0'],
        values: [{{
            double_val: {iswap_angles[1].phi}
        }}]
    }}]
""",
        cirq_google.api.v2.metrics_pb2.MetricsSnapshot(),
    )

    # Create NoiseProperties object from Calibration
    calibration = cirq_google.Calibration(_CALIBRATION_DATA)
    prop = cirq_google.noise_properties_from_calibration(calibration)

    for i, q in enumerate(qubits):
        assert np.isclose(
            prop.gate_pauli_errors[OpIdentifier(cirq.PhasedXZGate, q)],
            pauli_error[i])
        assert np.allclose(prop.readout_errors[q],
                           np.array([p00_error[i], p11_error[i]]))
        assert np.isclose(prop.t1_ns[q], t1_micros[i] * 1000)
        microwave_time_ns = 25.0
        tphi_err = incoherent_error[i] - microwave_time_ns / (3 *
                                                              prop.t1_ns[q])
        if tphi_err > 0:
            tphi_ns = microwave_time_ns / (3 * tphi_err)
        else:
            tphi_ns = 1e10
        assert prop.tphi_ns[q] == tphi_ns

    qubit_pairs = [(qubits[0], qubits[1]), (qubits[0], qubits[2])]
    for i, qs in enumerate(qubit_pairs):
        for gate, values in [
            (cirq_google.SycamoreGate, syc_pauli),
            (cirq.ISwapPowGate, iswap_pauli),
        ]:
            assert np.isclose(prop.gate_pauli_errors[OpIdentifier(gate, *qs)],
                              values[i])
            assert np.isclose(
                prop.gate_pauli_errors[OpIdentifier(gate, *qs[::-1])],
                values[i])
            assert np.isclose(prop.gate_pauli_errors[OpIdentifier(gate, *qs)],
                              values[i])
            assert np.isclose(
                prop.gate_pauli_errors[OpIdentifier(gate, *qs[::-1])],
                values[i])

        for gate, values in [
            (cirq_google.SycamoreGate, syc_angles),
            (cirq.ISwapPowGate, iswap_angles),
        ]:
            assert prop.fsim_errors[OpIdentifier(gate, *qs)] == values[i]
            assert prop.fsim_errors[OpIdentifier(gate, *qs[::-1])] == values[i]
            assert prop.fsim_errors[OpIdentifier(gate, *qs)] == values[i]
            assert prop.fsim_errors[OpIdentifier(gate, *qs[::-1])] == values[i]