Exemplo n.º 1
0
    def test_correctness_without_symbols(self, n_qubits, batch_size,
                                         inner_dim_size):
        """Test that inner_product works with symbols."""
        qubits = cirq.GridQubit.rect(1, n_qubits)
        circuit_batch, _ = \
            util.random_circuit_resolver_batch(
                qubits, batch_size)

        other_batch = [
            util.random_circuit_resolver_batch(qubits, inner_dim_size)[0]
            for i in range(batch_size)
        ]

        programs = util.convert_to_tensor(circuit_batch)
        other_programs = util.convert_to_tensor(other_batch)
        symbol_names = tf.convert_to_tensor([], dtype=tf.dtypes.string)
        symbol_values = tf.convert_to_tensor([[] for _ in range(batch_size)])

        out = inner_product_op.inner_product(programs, symbol_names,
                                             symbol_values, other_programs)

        out_arr = np.empty((batch_size, inner_dim_size), dtype=np.complex64)
        for i in range(batch_size):
            final_wf = cirq.final_wavefunction(circuit_batch[i])
            for j in range(inner_dim_size):
                internal_wf = cirq.final_wavefunction(other_batch[i][j])
                out_arr[i][j] = np.vdot(final_wf, internal_wf)

        self.assertAllClose(out, out_arr)
Exemplo n.º 2
0
def test_final_wavefunction_seed():
    a = cirq.LineQubit(0)
    np.testing.assert_allclose(cirq.final_wavefunction(
        [cirq.X(a)**0.5, cirq.measure(a)], seed=123), [0, 0.707107 - 0.707107j],
                               atol=1e-4)
    np.testing.assert_allclose(cirq.final_wavefunction(
        [cirq.X(a)**0.5, cirq.measure(a)], seed=124), [0.707107 + 0.707107j, 0],
                               atol=1e-4)
Exemplo n.º 3
0
def test_final_wavefunction_param_resolver():
    s = sympy.Symbol('s')

    with pytest.raises(ValueError, match='not unitary'):
        _ = cirq.final_wavefunction(cirq.X**s)

    np.testing.assert_allclose(
        cirq.final_wavefunction(cirq.X**s, param_resolver={s: 0.5}),
        [0.5 + 0.5j, 0.5 - 0.5j])
Exemplo n.º 4
0
def test_final_wavefunction_qubit_order():
    a, b = cirq.LineQubit.range(2)

    np.testing.assert_allclose(
        cirq.final_wavefunction([cirq.X(a), cirq.X(b)**0.5],
                                qubit_order=[a, b]),
        [0, 0, 0.5 + 0.5j, 0.5 - 0.5j])

    np.testing.assert_allclose(
        cirq.final_wavefunction([cirq.X(a), cirq.X(b)**0.5],
                                qubit_order=[b, a]),
        [0, 0.5 + 0.5j, 0, 0.5 - 0.5j])
Exemplo n.º 5
0
def test_final_wavefunction_initial_state():
    np.testing.assert_allclose(cirq.final_wavefunction(cirq.X, initial_state=0),
                               [0, 1],
                               atol=1e-8)

    np.testing.assert_allclose(cirq.final_wavefunction(cirq.X, initial_state=1),
                               [1, 0],
                               atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(cirq.X,
                                initial_state=[np.sqrt(0.5),
                                               1j * np.sqrt(0.5)]),
        [1j * np.sqrt(0.5), np.sqrt(0.5)],
        atol=1e-8)
Exemplo n.º 6
0
def test_deprecated():
    a = cirq.LineQubit(0)
    with cirq.testing.assert_logs('final_wavefunction',
                                  'final_state_vector',
                                  'deprecated',
                                  count=2):
        _ = cirq.final_wavefunction([cirq.H(a)])
def test_xeb_fidelity(depolarization, estimator):
    prng_state = np.random.get_state()
    np.random.seed(0)

    fs = []
    for _ in range(10):
        qubits = cirq.LineQubit.range(5)
        circuit = make_random_quantum_circuit(qubits, depth=12)
        bitstrings = sample_noisy_bitstrings(circuit,
                                             qubits,
                                             depolarization,
                                             repetitions=5000)

        f = cirq.xeb_fidelity(circuit, bitstrings, qubits, estimator=estimator)
        amplitudes = cirq.final_wavefunction(circuit)
        f2 = cirq.xeb_fidelity(circuit,
                               bitstrings,
                               qubits,
                               amplitudes=amplitudes,
                               estimator=estimator)
        assert np.abs(f - f2) < 1e-6

        fs.append(f)

    estimated_fidelity = np.mean(fs)
    expected_fidelity = 1 - depolarization
    assert np.isclose(estimated_fidelity, expected_fidelity, atol=0.04)

    np.random.set_state(prng_state)
Exemplo n.º 8
0
def test_with_registers():
    circuit = quirk_url_to_circuit(
        'https://algassert.com/quirk#circuit={"cols":'
        '['
        '[{"id":"setA","arg":3}],'
        '["+=AB3",1,1,"inputB2"]'
        ']}')
    op = cast(cirq.ArithmeticOperation, circuit[0].operations[0])

    with pytest.raises(ValueError, match='number of registers'):
        _ = op.with_registers()

    with pytest.raises(ValueError, match='first register.*mutable target'):
        _ = op.with_registers(1, 2, 3)

    op2 = op.with_registers([], 5, 5)
    np.testing.assert_allclose(cirq.unitary(cirq.Circuit(op2)),
                               np.array([[1]]),
                               atol=1e-8)

    op2 = op.with_registers([*cirq.LineQubit.range(3)], 5, 5)
    np.testing.assert_allclose(cirq.final_wavefunction(cirq.Circuit(op2),
                                                       initial_state=0),
                               cirq.one_hot(index=25 % 8,
                                            shape=8,
                                            dtype=np.complex64),
                               atol=1e-8)
Exemplo n.º 9
0
def test_final_wavefunction_different_program_types():
    a, b = cirq.LineQubit.range(2)

    np.testing.assert_allclose(cirq.final_wavefunction(cirq.X), [0, 1],
                               atol=1e-8)

    ops = [cirq.H(a), cirq.CNOT(a, b)]

    np.testing.assert_allclose(
        cirq.final_wavefunction(ops),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(cirq.Circuit(ops)),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)
Exemplo n.º 10
0
def test_final_wavefunction_dtype_insensitive_to_initial_state():
    assert cirq.final_wavefunction(cirq.X, ).dtype == np.complex64

    assert cirq.final_wavefunction(cirq.X,
                                   initial_state=0).dtype == np.complex64

    assert cirq.final_wavefunction(cirq.X,
                                   initial_state=[np.sqrt(0.5),
                                                  np.sqrt(0.5)
                                                  ]).dtype == np.complex64

    assert cirq.final_wavefunction(cirq.X,
                                   initial_state=np.array(
                                       [np.sqrt(0.5),
                                        np.sqrt(0.5)])).dtype == np.complex64

    for t in [np.int32, np.float32, np.float64, np.complex64]:
        assert cirq.final_wavefunction(
            cirq.X, initial_state=np.array([1, 0],
                                           dtype=t)).dtype == np.complex64

        assert cirq.final_wavefunction(
            cirq.X,
            initial_state=np.array([1, 0], dtype=t),
            dtype=np.complex128).dtype == np.complex128
def test_reshape_referencing():
    class Op1(cirq.ArithmeticOperation):
        def apply(self, *register_values: int):
            return register_values[0] + 1

        def registers(self):
            return [cirq.LineQubit.range(2)[::-1]]

        def with_registers(self, *new_registers):
            raise NotImplementedError()

    state = np.ones(4, dtype=np.complex64) / 2
    output = cirq.final_wavefunction(cirq.Circuit(Op1()), initial_state=state)
    np.testing.assert_allclose(state, output)
Exemplo n.º 12
0
    def test_correctness_with_symbols(self, n_qubits, batch_size,
                                      inner_dim_size):
        """Test that inner_product works with symbols."""
        symbol_names = ['alpha', 'beta', 'gamma']
        qubits = cirq.GridQubit.rect(1, n_qubits)
        circuit_batch, resolver_batch = \
            util.random_symbol_circuit_resolver_batch(
                qubits, symbol_names, batch_size)

        other_batch = [
            util.random_circuit_resolver_batch(qubits, inner_dim_size)[0]
            for i in range(batch_size)
        ]

        symbol_values_array = np.array(
            [[resolver[symbol] for symbol in symbol_names]
             for resolver in resolver_batch])

        programs = util.convert_to_tensor(circuit_batch)
        other_programs = util.convert_to_tensor(other_batch)
        symbol_names = tf.convert_to_tensor(symbol_names,
                                            dtype=tf.dtypes.string)
        symbol_values = tf.convert_to_tensor(symbol_values_array)

        out = inner_product_op.inner_product(programs, symbol_names,
                                             symbol_values, other_programs)

        out_arr = np.empty((batch_size, inner_dim_size), dtype=np.complex64)
        for i in range(batch_size):
            final_circuit = cirq.resolve_parameters(circuit_batch[i],
                                                    resolver_batch[i])
            final_wf = cirq.final_wavefunction(final_circuit)
            for j in range(inner_dim_size):
                internal_wf = cirq.final_wavefunction(other_batch[i][j])
                out_arr[i][j] = np.vdot(final_wf, internal_wf)

        self.assertAllClose(out, out_arr)
Exemplo n.º 13
0
def test_final_wavefunction_different_program_types():
    a, b = cirq.LineQubit.range(2)

    np.testing.assert_allclose(cirq.final_wavefunction(cirq.X), [0, 1],
                               atol=1e-8)

    ops = [cirq.H(a), cirq.CNOT(a, b)]

    np.testing.assert_allclose(
        cirq.final_wavefunction(ops),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(cirq.Circuit.from_ops(ops)),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)

    np.testing.assert_allclose(
        cirq.final_wavefunction(
            cirq.moment_by_moment_schedule(cirq.UNCONSTRAINED_DEVICE,
                                           cirq.Circuit.from_ops(ops))),
        [np.sqrt(0.5), 0, 0, np.sqrt(0.5)],
        atol=1e-8)
Exemplo n.º 14
0
def _sparse_computational_basis_map(inputs: Sequence[int],
                                    circuit: cirq.Circuit) -> Dict[int, int]:
    # Pick a unique amplitude for each computational basis input state.
    amps = [
        np.exp(1j * i / len(inputs)) / len(inputs)**0.5
        for i in range(len(inputs))
    ]

    # Permute the amplitudes using the circuit.
    input_state = np.zeros(1 << len(circuit.all_qubits()), dtype=np.complex128)
    for k, amp in zip(inputs, amps):
        input_state[k] = amp
    output_state = cirq.final_wavefunction(circuit, initial_state=input_state)

    # Find where each amplitude went.
    actual_map = {}
    for k, amp in zip(inputs, amps):
        for i, amp2 in enumerate(output_state):
            if abs(amp2 - amp) < 1e-5:
                actual_map[k] = i

    return actual_map
Exemplo n.º 15
0
    return c

def bitstring(bits):
    return ''.join(str(int(b)) for b in bits)

if __name__ == '__main__':
    qubit_count = 4

    input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)]
    circuit = make_circuit(qubit_count,input_qubits)
    circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap')

    circuit_sample_count =4040

    info = cirq.final_wavefunction(circuit)

    qubits = round(log2(len(info)))
    frequencies = {
        np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3)
        for i in range(2 ** qubits)
    }
    writefile = open("../data/startCirq_Class818.csv","w+")

    print(format(frequencies),file=writefile)
    print("results end", file=writefile)

    print(circuit.__len__(), file=writefile)
    print(circuit,file=writefile)

Exemplo n.º 16
0
def assert_url_to_circuit_returns(
        json_text: str,
        circuit: 'cirq.Circuit' = None,
        *,
        unitary: Optional[np.ndarray] = None,
        diagram: Optional[str] = None,
        output_amplitudes_from_quirk: Optional[List[Dict[str, float]]] = None,
        maps: Optional[Dict[int, int]] = None):
    """
    Args:
        json_text: The part of the quirk URL after "#circuit=".
        circuit: The optional expected circuit. If specified and not
            equal to the parsed circuit, an assertion fails.
        unitary: The optional expected unitary of the circuit. If specified
            and the parsed circuit has a different unitary, an assertion fails.
        diagram: The optional expected circuit diagram. If specified and the
            parsed circuit has a different diagram, an assertion fails.
        output_amplitudes_from_quirk: Optional data copied from Quirk's "export
            simulation data" function, for comparison to Cirq's simulator
            results. If specified and the output from the simulation differs
            from this data (after accounting for differences in endian-ness),
            an assertion fails.
        maps: Optional dictionary of test computational basis input states and
            the output computational basis state that they should be mapped to.
            If any state is mapped to the wrong thing, an assertion fails. Note
            that the states are specified using Quirk's little endian
            convention, meaning that the last bit of a binary literal will refer
            to the last qubit's value instead of vice versa.
    """
    parsed = quirk_url_to_circuit(
        f'https://algassert.com/quirk#circuit={json_text}')

    if diagram is not None:
        cirq.testing.assert_has_diagram(parsed, diagram)

    if circuit is not None:
        cirq.testing.assert_same_circuits(parsed, circuit)

    if unitary is not None:
        np.testing.assert_allclose(cirq.unitary(parsed), unitary, atol=1e-8)

    if output_amplitudes_from_quirk is not None:
        expected = np.array([
            float(e['r']) + 1j * float(e['i'])
            for e in output_amplitudes_from_quirk
        ])

        np.testing.assert_allclose(
            cirq.final_wavefunction(
                parsed,
                # Match Quirk's endian-ness for comparison purposes.
                qubit_order=sorted(parsed.all_qubits(), reverse=True),
            ),
            expected,
            atol=1e-8)

    if maps:
        keys = sorted(maps.keys())
        actual_map = _sparse_computational_basis_map(keys, parsed)
        for k in keys:
            assert actual_map.get(k) == maps[k], (
                f'{_bin_dec(k)} was mapped to '
                f'{_bin_dec(actual_map.get(k))} '
                f'instead of {_bin_dec(maps[k])}.')