Esempio n. 1
0
    def test_inner_product_inputs(self):
        """Makes sure that inner_product fails gracefully on bad inputs."""
        n_qubits = 5
        batch_size = 5
        symbol_names = ['alpha']
        qubits = cirq.GridQubit.rect(1, n_qubits)
        circuit_batch, resolver_batch = \
            util.random_symbol_circuit_resolver_batch(
                qubits, symbol_names, batch_size)

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

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

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'programs must be rank 1'):
            # Circuit tensor has too many dimensions.
            inner_product_op.inner_product(
                util.convert_to_tensor([circuit_batch]), symbol_names,
                symbol_values_array, util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'symbol_names must be rank 1.'):
            # symbol_names tensor has too many dimensions.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), np.array([symbol_names]),
                symbol_values_array, util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'symbol_values must be rank 2.'):
            # symbol_values_array tensor has too many dimensions.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                np.array([symbol_values_array]),
                util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'symbol_values must be rank 2.'):
            # symbol_values_array tensor has too few dimensions.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array[0], util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'other_programs must be rank 2.'):
            # other_programs tensor has too few dimensions.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array, util.convert_to_tensor(circuit_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'other_programs must be rank 2.'):
            # pauli_sums tensor has too many dimensions.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array,
                util.convert_to_tensor([[x] for x in other_batch]))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'Unparseable proto'):
            # circuit tensor has the right type but invalid values.
            inner_product_op.inner_product(['junk'] * batch_size, symbol_names,
                                           symbol_values_array,
                                           util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'Could not find symbol in parameter map'):
            # symbol_names tensor has the right type but invalid values.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), ['junk'],
                symbol_values_array, util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'not found in reference circuit'):
            # other_programs tensor has the right type but operates on
            # qubits that the reference ciruit doesn't have.
            new_qubits = [cirq.GridQubit(5, 5), cirq.GridQubit(9, 9)]
            new_circuits, _ = util.random_circuit_resolver_batch(
                new_qubits, batch_size)
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array,
                util.convert_to_tensor([[x] for x in new_circuits]))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    'not found in paired circuit'):
            # other_programs tensor has the right type but operates on
            # qubits that the reference ciruit doesn't have.
            new_qubits = cirq.GridQubit.rect(1, n_qubits - 1)
            new_circuits, _ = util.random_circuit_resolver_batch(
                new_qubits, batch_size)
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array,
                util.convert_to_tensor([[x] for x in new_circuits]))

        with self.assertRaisesRegex(TypeError, 'Cannot convert'):
            # circuits tensor has the wrong type.
            inner_product_op.inner_product([1.0] * batch_size, symbol_names,
                                           symbol_values_array,
                                           util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(TypeError, 'Cannot convert'):
            # symbol_names tensor has the wrong type.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), [0.1234],
                symbol_values_array, util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(tf.errors.UnimplementedError, ''):
            # symbol_values tensor has the wrong type.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                [['junk']] * batch_size, util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(TypeError, 'Cannot convert'):
            # other_programs tensor has the wrong type.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array, [[1.0]] * batch_size)

        with self.assertRaisesRegex(TypeError, 'missing'):
            # we are missing an argument.
            # pylint: disable=no-value-for-parameter
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array)
            # pylint: enable=no-value-for-parameter

        with self.assertRaisesRegex(TypeError, 'positional arguments'):
            # pylint: disable=too-many-function-args
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array, util.convert_to_tensor(other_batch), [])

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    expected_regex='do not match'):
            # batch programs has wrong batch size.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array,
                util.convert_to_tensor(other_batch[:int(batch_size * 0.5)]))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    expected_regex='do not match'):
            # batch programs has wrong batch size.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array[::int(batch_size * 0.5)],
                util.convert_to_tensor(other_batch))

        with self.assertRaisesRegex(
                tf.errors.InvalidArgumentError,
                expected_regex='Found symbols in other_programs'):
            # other_programs has symbols.
            inner_product_op.inner_product(
                util.convert_to_tensor(circuit_batch), symbol_names,
                symbol_values_array,
                util.convert_to_tensor([[x] for x in circuit_batch]))

        with self.assertRaisesRegex(tf.errors.InvalidArgumentError,
                                    expected_regex='cirq.Channel'):
            # attempting to use noisy circuit.
            noisy_circuit = cirq.Circuit(cirq.depolarize(0.3).on_each(*qubits))
            inner_product_op.inner_product(
                util.convert_to_tensor([noisy_circuit for _ in circuit_batch]),
                symbol_names, symbol_values_array,
                util.convert_to_tensor(other_batch))

        res = inner_product_op.inner_product(
            util.convert_to_tensor(circuit_batch), symbol_names,
            symbol_values_array.astype(np.float64),
            util.convert_to_tensor(other_batch))
        self.assertDTypeEqual(res, np.complex64)
Esempio n. 2
0
    c.append(cirq.measure(*input_qubit, key='result'))

    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 =2820

    circuit = circuit.with_noise(cirq.depolarize(p=0.01))
    simulator = cirq.Simulator()
    result = simulator.run(circuit, repetitions=circuit_sample_count)

    frequencies = result.histogram(key='result', fold_func=bitstring)
    writefile = open("../data/startCirq_noisy223.csv","w+")

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

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


    writefile.close()
Esempio n. 3
0
def test_depolarizing_mixture():
    d = cirq.depolarize(0.3)
    assert_mixtures_equal(cirq.mixture(d),
                          ((0.7, np.eye(2)), (0.1, X), (0.1, Y), (0.1, Z)))
    assert cirq.has_mixture_channel(d)
Esempio n. 4
0
def trial(length=2, steps=1, repetitions=1000, maxiter=2):

    h, jr, jc = random_instance(length)
    print('transverse fields: {}'.format(h))
    print('row j fields: {}'.format(jr))
    print('column j fields: {}'.format(jc))
    # prints something like
    # transverse fields: [[-1, 1, -1], [1, -1, -1], [-1, 1, -1]]
    # row j fields: [[1, 1, -1], [1, -1, 1]]
    # column j fields: [[1, -1], [-1, 1], [-1, 1]]

    # define qubits on the grid.
    # [cirq.GridQubit(i, j) for i in range(length) for j in range(length)]
    qubits = cirq.LineQubit.range(length * length)
    print(qubits)
    # prints
    # [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(0, 2), cirq.GridQubit(1, 0), cirq.GridQubit(1, 1), cirq.GridQubit(1, 2), cirq.GridQubit(2, 0), cirq.GridQubit(2, 1), cirq.GridQubit(2, 2)]

    cirq_circuit = cirq.Circuit()
    alpha = sympy.Symbol('alpha')
    beta = sympy.Symbol('beta')
    gamma = sympy.Symbol('gamma')
    for _ in range(steps):
        cirq_circuit.append(one_step(h, jr, jc, alpha, beta, gamma))

    # noise = cirq.ConstantQubitNoiseModel(cirq.asymmetric_depolarize(0.005,0.005,0.005)) # mixture: size four noise not implemented
    noise = cirq.ConstantQubitNoiseModel(
        cirq.depolarize(0.005))  # mixture: size four noise not implemented
    # noise = cirq.ConstantQubitNoiseModel(cirq.phase_flip(0.01)) # mixture: works well
    # noise = cirq.ConstantQubitNoiseModel(cirq.bit_flip(0.01)) # mixture: works well

    cirq_circuit = cirq.Circuit(
        cirq.NoiseModel.from_noise_model_like(noise).noisy_moments(
            cirq_circuit, sorted(cirq_circuit.all_qubits())))
    meas_circuit = cirq.Circuit(cirq_circuit, cirq.measure(*qubits, key='x'))
    print(meas_circuit)

    # Initialize simulators
    dm_sim = cirq.DensityMatrixSimulator()
    # kc_sim = cirq.KnowledgeCompilationSimulator(cirq_circuit, initial_state=0)
    kc_smp = cirq.KnowledgeCompilationSimulator(meas_circuit, initial_state=0)

    # eval_iter = 0
    def f(x):
        param_resolver = cirq.ParamResolver({
            'alpha': x[0],
            'beta': x[1],
            'gamma': x[2]
        })

        # VALIDATE DENSITY MATRIX SIMULATION

        # dm_sim_start = time.time()
        # dm_sim_result = dm_sim.simulate(cirq_circuit, param_resolver=param_resolver)
        # dm_sim_time = time.time() - dm_sim_start

        # kc_sim_start = time.time()
        # kc_sim_result = kc_sim.simulate(cirq_circuit, param_resolver=param_resolver)
        # kc_sim_time = time.time() - kc_sim_start

        # print("dm_sim_result.final_density_matrix=")
        # print(dm_sim_result.final_density_matrix)
        # print("kc_sim_result.final_density_matrix=")
        # print(kc_sim_result.final_density_matrix)

        # np.testing.assert_almost_equal(
        #     dm_sim_result.final_density_matrix,
        #     kc_sim_result.final_density_matrix,
        #     decimal=6
        # )

        # VALIDATE SAMPLING HISTOGRAMS

        # Sample bitstrings from circuit
        if length * length <= cirq_max:
            dm_smp_start = time.time()
            dm_smp_result = dm_sim.run(meas_circuit,
                                       param_resolver=param_resolver,
                                       repetitions=repetitions)
            dm_smp_time = time.time() - dm_smp_start
            dm_smp_time_dict[length * length].append(dm_smp_time)

            # Process histogram
            dm_bitstrings = dm_smp_result.measurements['x']
            dm_histogram = defaultdict(int)
            for bitstring in dm_bitstrings:
                integer = 0
                for pos, bit in enumerate(reversed(bitstring)):
                    integer += bit << pos
                dm_histogram[integer] += 1

            # Process bitstrings
            dm_value = obj_func(dm_smp_result, h, jr, jc)
            print('Objective value is {}.'.format(dm_value))

        # Sample bitstrings from circuit
        kc_smp_start = time.time()
        kc_smp_result = kc_smp.run(meas_circuit,
                                   param_resolver=param_resolver,
                                   repetitions=repetitions)
        kc_smp_time = time.time() - kc_smp_start
        kc_smp_time_dict[length * length].append(kc_smp_time)

        # Process histogram
        kc_bitstrings = kc_smp_result.measurements['x']
        kc_histogram = defaultdict(int)
        for bitstring in kc_bitstrings:
            integer = 0
            for pos, bit in enumerate(reversed(bitstring)):
                integer += bit << pos
            kc_histogram[integer] += 1

        # Process bitstrings
        kc_value = obj_func(kc_smp_result, h, jr, jc)
        print('Objective value is {}.'.format(kc_value))

        # nonlocal eval_iter
        # PRINT HISTOGRAMS
        # print ('eval_iter,index,bitstring,bitstring_bin,dm_probability,dm_samples,kc_samples')
        # probabilities = np.zeros(1<<(length*length))
        # for bitstring, probability in enumerate(cirq.sim.density_matrix_utils._probs(
        #     dm_sim_result.final_density_matrix,
        #     [index for index in range(length*length)],
        #     cirq.protocols.qid_shape(qubits)
        # )):
        #     probabilities[bitstring]=probability
        # sorted_bitstrings = np.argsort(probabilities)
        # for index, bitstring in enumerate(sorted_bitstrings):
        #     print (str(eval_iter)+','+str(index)+','+str(bitstring)+','+format(bitstring,'b').zfill(length*length)+','+str(probabilities[bitstring])+','+"{:.6e}".format(dm_histogram[bitstring]/repetitions)+','+"{:.6e}".format(kc_histogram[bitstring]/repetitions))

        if length * length <= cirq_max:
            print('dm_value=' + str(dm_value) + ' kc_value=' + str(kc_value))
            # print ( 'dm_sim_time='+str(dm_sim_time)+' kc_sim_time='+str(kc_sim_time) )
            print('dm_smp_time=' + str(dm_smp_time) + ' kc_smp_time=' +
                  str(kc_smp_time))
        print(
            '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        # eval_iter += 1
        return kc_value

    # Pick an initial guess
    x0 = np.random.uniform(0.0, 1.0, size=3)

    # Optimize f
    print('Optimizing objective function ...')
    scipy.optimize.minimize(f,
                            x0,
                            method='Nelder-Mead',
                            options={'maxiter': maxiter})
Esempio n. 5
0
def test_depolarizing_channel_text_diagram():
    assert (cirq.circuit_diagram_info(
        cirq.depolarize(0.3)) == cirq.CircuitDiagramInfo(
            wire_symbols=('D(0.3)', )))
Esempio n. 6
0
def test_depolarizing_channel():
    d = cirq.depolarize(0.3)
    np.testing.assert_almost_equal(cirq.channel(d),
                                   (np.sqrt(0.7) * np.eye(2), np.sqrt(0.1) * X,
                                    np.sqrt(0.1) * Y, np.sqrt(0.1) * Z))
    assert cirq.has_channel(d)
Esempio n. 7
0
def test_depolarizing_channel_invalid_probability():
    with pytest.raises(ValueError, match='was less than 0'):
        cirq.depolarize(-0.1)
    with pytest.raises(ValueError, match='was greater than 1'):
        cirq.depolarize(1.1)
Esempio n. 8
0
def test_depolarizing_channel_str():
    assert str(cirq.depolarize(0.3)) == 'depolarize(p=0.3)'
Esempio n. 9
0
def test_apply_unitaries():
    a, b, c = cirq.LineQubit.range(3)

    result = cirq.apply_unitaries(unitary_values=[
        cirq.H(a), cirq.CNOT(a, b),
        cirq.H(c).controlled_by(b)
    ],
                                  qubits=[a, b, c])
    np.testing.assert_allclose(result.reshape(8), [
        np.sqrt(0.5),
        0,
        0,
        0,
        0,
        0,
        0.5,
        0.5,
    ],
                               atol=1e-8)

    # Different order.
    result = cirq.apply_unitaries(unitary_values=[
        cirq.H(a), cirq.CNOT(a, b),
        cirq.H(c).controlled_by(b)
    ],
                                  qubits=[a, c, b])
    np.testing.assert_allclose(result.reshape(8), [
        np.sqrt(0.5),
        0,
        0,
        0,
        0,
        0.5,
        0,
        0.5,
    ],
                               atol=1e-8)

    # Explicit arguments.
    result = cirq.apply_unitaries(
        unitary_values=[
            cirq.H(a), cirq.CNOT(a, b),
            cirq.H(c).controlled_by(b)
        ],
        qubits=[a, b, c],
        args=cirq.ApplyUnitaryArgs.default(num_qubits=3))
    np.testing.assert_allclose(result.reshape(8), [
        np.sqrt(0.5),
        0,
        0,
        0,
        0,
        0,
        0.5,
        0.5,
    ],
                               atol=1e-8)

    # Empty.
    result = cirq.apply_unitaries(unitary_values=[], qubits=[])
    np.testing.assert_allclose(result, [1])
    result = cirq.apply_unitaries(unitary_values=[], qubits=[], default=None)
    np.testing.assert_allclose(result, [1])

    # Non-unitary operation.
    with pytest.raises(TypeError, match='non-unitary'):
        _ = cirq.apply_unitaries(unitary_values=[cirq.depolarize(0.5).on(a)],
                                 qubits=[a])
    assert cirq.apply_unitaries(unitary_values=[cirq.depolarize(0.5).on(a)],
                                qubits=[a],
                                default=None) is None
    assert cirq.apply_unitaries(unitary_values=[cirq.depolarize(0.5).on(a)],
                                qubits=[a],
                                default=1) == 1

    # Inconsistent arguments.
    with pytest.raises(ValueError, match='len'):
        _ = cirq.apply_unitaries(unitary_values=[],
                                 qubits=[],
                                 args=cirq.ApplyUnitaryArgs.default(1))
Esempio n. 10
0
def test_depolarizing_channel_invalid_probability():
    with pytest.raises(ValueError,
                       match=re.escape('p(I) was greater than 1.')):
        cirq.depolarize(-0.1)
    with pytest.raises(ValueError, match=re.escape('p(I) was less than 0.')):
        cirq.depolarize(1.1)
Esempio n. 11
0
def test_depolarizing_channel_str_two_qubits():
    assert str(cirq.depolarize(0.3,
                               n_qubits=2)) == 'depolarize(p=0.3,n_qubits=2)'