circuit += cirq.rz(params[i * 2 + 1]).on(qubits[i]) return circuit def model_circuit(qubits, depth): cir = cirq.Circuit() num_params = depth * 2 * len(qubits) params = sympy.symbols("q0:%d" % num_params) for i in range(depth): cir = layer( cir, qubits, params[i * 2 * len(qubits):i * 2 * len(qubits) + 2 * len(qubits)]) return cir qs = [cirq.GridQubit(0, i) for i in range(6)] d = 5 X_train_en, X_test_en, y_train_en, y_test_en = encode(blob_data, blob_labels, qs) c = model_circuit(qs, d) print(c) readout_operators = [cirq.Z(i) for i in qs] inputs = tf.keras.Input(shape=(), dtype=tf.dtypes.string) layer1 = tfq.layers.PQC(c, readout_operators, differentiator=tfq.differentiators.Adjoint())(inputs) vqc = tf.keras.models.Model(inputs=inputs, outputs=layer1) vqc.compile( loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(lr=0.01),
def demo(input_parameters): result, circuit = simulate_and_measure(*input_parameters) print("Circuit:") print(circuit) print("") print("Results:") print(result) print(result.histogram(key=input_parameters[2])) qregister = [cirq.LineQubit(0), cirq.LineQubit(1)] input_parameters = [qregister, 10, "m"] demo(input_parameters) qregister = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)] input_parameters = [qregister, 10, "m"] demo(input_parameters) # Besides, the index of each qubit is only used for the indication of qubit ID. # No matter what the index is, it does not impact the final measurement. qregister = [cirq.LineQubit(2), cirq.LineQubit(3)] input_parameters = [qregister, 10, "m"] demo(input_parameters) qregister = [cirq.GridQubit(1, 1), cirq.GridQubit(1, 2)] input_parameters = [qregister, 10, "m"] demo(input_parameters) # let's try a different measurement method qregister = [cirq.LineQubit(0), cirq.LineQubit(1)]
c.append(cirq.SWAP.on(input_qubit[1],input_qubit[0])) # number=28 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=34 c.append(cirq.SWAP.on(input_qubit[3],input_qubit[0])) # number=35 # circuit end 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 =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq3105.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile)
def test_complex_pad(self): """Test trickier padding.""" bit = cirq.GridQubit(0, 0) bit2 = cirq.GridQubit(0, 1) circuit = cirq.Circuit( cirq.X(bit)**sympy.Symbol('alpha'), cirq.Y(bit)**sympy.Symbol('alpha'), cirq.Z(bit)**sympy.Symbol('alpha'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) circuit2 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('beta'), cirq.Y(bit)**sympy.Symbol('beta'), cirq.Z(bit)**sympy.Symbol('beta'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) circuit3 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('alpha'), cirq.Y(bit)**sympy.Symbol('alpha'), cirq.Z(bit)**sympy.Symbol('alpha'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) inputs = util.convert_to_tensor([circuit, circuit2, circuit3]) symbols = tf.convert_to_tensor(['alpha', 'beta', 'gamma']) new = tf.convert_to_tensor(['new', 'old', 'nothing']) res = tfq_ps_util_ops.tfq_ps_symbol_replace(inputs, symbols, new) output = util.from_tensor(res) correct_000 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('new'), cirq.Y(bit)**sympy.Symbol('alpha'), cirq.Z(bit)**sympy.Symbol('alpha'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) correct_001 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('alpha'), cirq.Y(bit)**sympy.Symbol('new'), cirq.Z(bit)**sympy.Symbol('alpha'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) correct_002 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('alpha'), cirq.Y(bit)**sympy.Symbol('alpha'), cirq.Z(bit)**sympy.Symbol('new'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) correct_003 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('alpha'), cirq.Y(bit)**sympy.Symbol('alpha'), cirq.Z(bit)**sympy.Symbol('alpha'), cirq.XX(bit, bit2)**sympy.Symbol('new')) self.assertEqual(correct_000, output[0][0][0]) self.assertEqual(correct_001, output[0][0][1]) self.assertEqual(correct_002, output[0][0][2]) self.assertEqual(correct_003, output[0][0][3]) self.assertEqual(correct_000, output[2][0][0]) self.assertEqual(correct_001, output[2][0][1]) self.assertEqual(correct_002, output[2][0][2]) self.assertEqual(correct_003, output[2][0][3]) correct_110 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('old'), cirq.Y(bit)**sympy.Symbol('beta'), cirq.Z(bit)**sympy.Symbol('beta'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) correct_111 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('beta'), cirq.Y(bit)**sympy.Symbol('old'), cirq.Z(bit)**sympy.Symbol('beta'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) correct_112 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('beta'), cirq.Y(bit)**sympy.Symbol('beta'), cirq.Z(bit)**sympy.Symbol('old'), cirq.XX(bit, bit2)**sympy.Symbol('alpha')) correct_113 = cirq.Circuit() self.assertEqual(correct_110, output[1][1][0]) self.assertEqual(correct_111, output[1][1][1]) self.assertEqual(correct_112, output[1][1][2]) self.assertEqual(correct_113, output[1][1][3]) correct_100 = cirq.Circuit( cirq.X(bit)**sympy.Symbol('beta'), cirq.Y(bit)**sympy.Symbol('beta'), cirq.Z(bit)**sympy.Symbol('beta'), cirq.XX(bit, bit2)**sympy.Symbol('new')) correct_101 = cirq.Circuit() correct_102 = cirq.Circuit() correct_103 = cirq.Circuit() self.assertEqual(correct_100, output[1][0][0]) self.assertEqual(correct_101, output[1][0][1]) self.assertEqual(correct_102, output[1][0][2]) self.assertEqual(correct_103, output[1][0][3]) correct_220 = cirq.Circuit() correct_221 = cirq.Circuit() correct_222 = cirq.Circuit() correct_223 = cirq.Circuit() self.assertEqual(correct_220, output[2][2][0]) self.assertEqual(correct_221, output[2][2][1]) self.assertEqual(correct_222, output[2][2][2]) self.assertEqual(correct_223, output[2][2][3]) correct = cirq.Circuit() for i in range(3): for j in range(3): for k in range(3): if i != j and (not (i == 2 and j == 0)) \ and (not (i == 1 and j == 0)): self.assertEqual(correct, output[i][j][k])
def test_noisy_expectation_inputs(self): """Make sure noisy expectation op 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, include_channels=True) symbol_values_array = np.array( [[resolver[symbol] for symbol in symbol_names] for resolver in resolver_batch]) pauli_sums = util.random_pauli_sums(qubits, 3, batch_size) num_samples = [[10]] * batch_size with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'programs must be rank 1'): # Circuit tensor has too many dimensions. noisy_expectation_op.expectation( util.convert_to_tensor([circuit_batch]), symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_names must be rank 1.'): # symbol_names tensor has too many dimensions. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), np.array([symbol_names]), symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_values must be rank 2.'): # symbol_values_array tensor has too many dimensions. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, np.array([symbol_values_array]), util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'symbol_values must be rank 2.'): # symbol_values_array tensor has too few dimensions. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array[0], util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'pauli_sums must be rank 2.'): # pauli_sums tensor has too few dimensions. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, util.convert_to_tensor(list(pauli_sums)), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'pauli_sums must be rank 2.'): # pauli_sums tensor has too many dimensions. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, [util.convert_to_tensor([[x] for x in pauli_sums])], num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'num_samples must be rank 2'): # num_samples tensor has the wrong shape. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), [num_samples]) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'num_samples must be rank 2'): # num_samples tensor has the wrong shape. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples[0]) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'Unparseable proto'): # circuit tensor has the right type but invalid values. noisy_expectation_op.expectation( ['junk'] * batch_size, symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'Could not find symbol in parameter map'): # symbol_names tensor has the right type but invalid values. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), ['junk'], symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'qubits not found in circuit'): # pauli_sums tensor has the right type but invalid values. new_qubits = [cirq.GridQubit(5, 5), cirq.GridQubit(9, 9)] new_pauli_sums = util.random_pauli_sums(new_qubits, 2, batch_size) noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in new_pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'Unparseable proto'): # pauli_sums tensor has the right type but invalid values 2. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, [['junk']] * batch_size, num_samples) with self.assertRaisesRegex(TypeError, 'Cannot convert'): # circuits tensor has the wrong type. noisy_expectation_op.expectation( [1.0] * batch_size, symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(TypeError, 'Cannot convert'): # symbol_names tensor has the wrong type. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), [0.1234], symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.UnimplementedError, ''): # symbol_values tensor has the wrong type. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, [['junk']] * batch_size, util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(TypeError, 'Cannot convert'): # pauli_sums tensor has the wrong type. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, [[1.0]] * batch_size, num_samples) with self.assertRaisesRegex(TypeError, 'missing'): # we are missing an argument. # pylint: disable=no-value-for-parameter noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, num_samples) # pylint: enable=no-value-for-parameter with self.assertRaisesRegex(TypeError, 'positional arguments'): # pylint: disable=too-many-function-args noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), [], num_samples) # pylint: enable=too-many-function-args with self.assertRaisesRegex(tf.errors.InvalidArgumentError, expected_regex='do not match'): # wrong op size. noisy_expectation_op.expectation( util.convert_to_tensor([cirq.Circuit()]), symbol_names, symbol_values_array.astype(np.float64), util.convert_to_tensor([[x] for x in pauli_sums]), num_samples) with self.assertRaisesRegex(tf.errors.InvalidArgumentError, 'greater than 0'): # pylint: disable=too-many-function-args noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array, util.convert_to_tensor([[x] for x in pauli_sums]), [[-1]] * batch_size) # pylint: enable=too-many-function-args with self.assertRaisesRegex(tf.errors.InvalidArgumentError, expected_regex='do not match'): # wrong symbol_values size. noisy_expectation_op.expectation( util.convert_to_tensor(circuit_batch), symbol_names, symbol_values_array[:int(batch_size * 0.5)], util.convert_to_tensor([[x] for x in pauli_sums]), num_samples)
def rot_x_layer(length, half_turns): """Yields X rotations by half_turns on a square grid of given length.""" rot = cirq.XPowGate(exponent=half_turns) for i in range(length): for j in range(length): yield rot(cirq.GridQubit(i, j))
def test_static_cases(self): """Run inputs through in complex cases.""" bit = cirq.GridQubit(0, 0) symbol = sympy.Symbol('alpha') test_pstring = cirq.Z(bit) test_psum = cirq.PauliSum.from_pauli_strings([test_pstring]) symb_circuit = cirq.Circuit(cirq.H(bit)**symbol) reg_circuit = cirq.Circuit(cirq.H(bit)) # Passing a 2d operators input requires a 1d circuit input. sampled_expectation.SampledExpectation()( [reg_circuit, reg_circuit], operators=[[test_psum, test_psum], [test_psum, test_psum]], repetitions=1) # Passing 2d operators along with other inputs. sampled_expectation.SampledExpectation()( [symb_circuit, symb_circuit], symbol_names=[symbol], operators=[[test_psum, test_psum], [test_psum, test_psum]], repetitions=1) sampled_expectation.SampledExpectation()( [symb_circuit, symb_circuit], symbol_names=[symbol], symbol_values=[[0.5], [0.8]], operators=[[test_psum, test_psum], [test_psum, test_psum]], repetitions=1) # Ensure tiling up of circuits works as expected. sampled_expectation.SampledExpectation()(reg_circuit, operators=test_psum, repetitions=1) sampled_expectation.SampledExpectation()( reg_circuit, operators=[test_psum, test_psum], repetitions=1) # Ensure tiling up of symbol_values works as expected. sampled_expectation.SampledExpectation()(symb_circuit, symbol_names=[symbol], symbol_values=[[0.5], [0.8]], operators=test_psum, repetitions=1) sampled_expectation.SampledExpectation()(symb_circuit, symbol_names=[symbol], symbol_values=[[0.5]], operators=test_psum, repetitions=1) # Test multiple operators with integer valued repetition. sampled_expectation.SampledExpectation()( symb_circuit, symbol_names=[symbol], symbol_values=[[0.5]], operators=[-1.0 * cirq.Z(bit), cirq.X(bit) + 2.0 * cirq.Z(bit)], repetitions=1) sampled_expectation.SampledExpectation()( symb_circuit, symbol_names=[symbol], symbol_values=[[0.5]], operators=[-1.0 * cirq.Z(bit), cirq.X(bit) + 2.0 * cirq.Z(bit)], repetitions=[5, 1])
def test_get_circuit_v2(get_program): circuit = cirq.Circuit( cirq.X(cirq.GridQubit(5, 2))**0.5, cirq.measure(cirq.GridQubit(5, 2), key='result')) program_proto = Merge( """language { gate_set: "xmon" } circuit { scheduling_strategy: MOMENT_BY_MOMENT moments { operations { gate { id: "xy" } args { key: "axis_half_turns" value { arg_value { float_value: 0.0 } } } args { key: "half_turns" value { arg_value { float_value: 0.5 } } } qubits { id: "5_2" } } } moments { operations { gate { id: "meas" } args { key: "invert_mask" value { arg_value { bool_values { } } } } args { key: "key" value { arg_value { string_value: "result" } } } qubits { id: "5_2" } } } } """, v2.program_pb2.Program()) program = cg.EngineProgram('a', 'b', EngineContext()) get_program.return_value = qtypes.QuantumProgram( code=_to_any(program_proto)) assert program.get_circuit() == circuit get_program.assert_called_once_with('a', 'b', True)
def test_get_circuit_batch(get_program): circuit = cirq.Circuit( cirq.X(cirq.GridQubit(5, 2))**0.5, cirq.measure(cirq.GridQubit(5, 2), key='result')) program_proto = Merge( """programs { language { gate_set: "xmon" } circuit { scheduling_strategy: MOMENT_BY_MOMENT moments { operations { gate { id: "xy" } args { key: "axis_half_turns" value { arg_value { float_value: 0.0 } } } args { key: "half_turns" value { arg_value { float_value: 0.5 } } } qubits { id: "5_2" } } } moments { operations { gate { id: "meas" } args { key: "invert_mask" value { arg_value { bool_values { } } } } args { key: "key" value { arg_value { string_value: "result" } } } qubits { id: "5_2" } } } } } """, v2.batch_pb2.BatchProgram()) program = cg.EngineProgram('a', 'b', EngineContext()) get_program.return_value = qtypes.QuantumProgram( code=_to_any(program_proto)) with pytest.raises(ValueError, match='A program number must be specified'): program.get_circuit() with pytest.raises(ValueError, match='Only 1 in the batch but index 1 was specified'): program.get_circuit(1) assert program.get_circuit(0) == circuit get_program.assert_called_once_with('a', 'b', True)
import cirq import numpy as np QUBIT_ORDER = [ cirq.GridQubit(3, 3), cirq.GridQubit(3, 4), cirq.GridQubit(3, 5), cirq.GridQubit(3, 6), cirq.GridQubit(4, 3), cirq.GridQubit(4, 4), cirq.GridQubit(4, 5), cirq.GridQubit(4, 6), cirq.GridQubit(5, 3), cirq.GridQubit(5, 4), cirq.GridQubit(5, 5), cirq.GridQubit(5, 6), ] CIRCUIT = cirq.Circuit( [ cirq.Moment( operations=[ (cirq.Y ** 0.5).on(cirq.GridQubit(3, 3)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on( cirq.GridQubit(3, 4) ), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on( cirq.GridQubit(3, 5) ), (cirq.Y ** 0.5).on(cirq.GridQubit(3, 6)), cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5).on(
def pyquil2cirq(qprog): """Convert a pyquil Program to a cirq Circuit. Currently supports only common single- and two-qubit gates. Args: qprog (pyquil.quil.Program): the program to be converted. Returns: circuit (cirq.Cirquit): the converted circuit""" # A map between gate names used by pyquil and cirq gate objects op_map = { "X": cirq.X, "Y": cirq.Y, "Z": cirq.Z, "T": cirq.T, "H": cirq.H, "S": cirq.S, "RX": cirq.XPowGate, "RY": cirq.YPowGate, "RZ": cirq.ZPowGate, "CNOT": cirq.CNOT, "SWAP": cirq.SWAP, "CZ": cirq.CZ, "CPHASE": cirq.ops.common_gates.CZPowGate, } # Create the qubits. The row of each grid qubit is equal to the index # of the corresponding pyquil qubit. qubits = [cirq.GridQubit(i, 0) for i in qprog.get_qubits()] # A map between the row of the qubit and the index in the qubits array qubit_map = {} for i in range(len(qubits)): qubit_map[qubits[i].row] = i circuit = cirq.Circuit() for gate in qprog: if not op_map.get(gate.name): raise ValueError("Gate {} not yet supported".format(gate.name)) # Find the cirq qubits that this gate acts on target_qubits = [qubits[qubit_map[q.index]] for q in gate.qubits] # Create the cirq gate if len(gate.params) == 0: cirq_gate = op_map[gate.name](*target_qubits) elif len(gate.params) == 1: cirq_gate = op_map[gate.name](exponent=gate.params[0] / np.pi)( *target_qubits ) else: raise ValueError( "Gates with more than one parameter not yet supported: {}".format(gate) ) # Append the gate to the circuit circuit.append(cirq_gate, strategy=cirq.circuits.InsertStrategy.EARLIEST) return circuit
def test_row_and_col(): d = square_device(2, 3) assert d.col(-1) == [] assert d.col(0) == [ cirq.GridQubit(0, 0), cirq.GridQubit(1, 0), cirq.GridQubit(2, 0) ] assert d.col(1) == [ cirq.GridQubit(0, 1), cirq.GridQubit(1, 1), cirq.GridQubit(2, 1) ] assert d.col(2) == [] assert d.col(5000) == [] assert d.row(-1) == [] assert d.row(0) == [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)] assert d.row(1) == [cirq.GridQubit(1, 0), cirq.GridQubit(1, 1)] assert d.row(2) == [cirq.GridQubit(2, 0), cirq.GridQubit(2, 1)] assert d.row(3) == [] b = cg.Bristlecone assert b.col(0) == [cirq.GridQubit(5, 0)] assert b.row(0) == [cirq.GridQubit(0, 5), cirq.GridQubit(0, 6)] assert b.col(1) == [ cirq.GridQubit(4, 1), cirq.GridQubit(5, 1), cirq.GridQubit(6, 1) ]
def test_validate_measurement_non_adjacent_qubits_ok(): d = square_device(3, 3) d.validate_operation( cirq.GateOperation(cirq.MeasurementGate(2), (cirq.GridQubit(0, 0), cirq.GridQubit(2, 0))))
def set_qubits(qubit_count): """Add the specified number of input qubits.""" input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] return input_qubits
def test_proto_with_waitgate(): # Deprecations: cirq_google.SerializableDevice, cirq_google.SerializableGateSet, # common serializers, and # cirq_google.devices.known_devices.create_device_proto_from_diagram with cirq.testing.assert_deprecated( 'Use cirq_google.GridDevice', 'SerializableGateSet', 'CircuitSerializer', 'no longer be available', deadline='v0.16', count=7, ): wait_gateset = cirq_google.SerializableGateSet( gate_set_name='wait_gateset', serializers=[cgc.WAIT_GATE_SERIALIZER], deserializers=[cgc.WAIT_GATE_DESERIALIZER], ) wait_proto = cirq_google.devices.known_devices.create_device_proto_from_diagram( "aa\naa", [wait_gateset]) wait_device = cirq_google.SerializableDevice.from_proto( proto=wait_proto, gate_sets=[wait_gateset]) q0 = cirq.GridQubit(1, 1) wait_op = cirq.wait(q0, nanos=25) wait_device.validate_operation(wait_op) assert (str(wait_proto) == """\ valid_gate_sets { name: "wait_gateset" valid_gates { id: "wait" number_of_qubits: 1 valid_args { name: "nanos" type: FLOAT } } } valid_qubits: "0_0" valid_qubits: "0_1" valid_qubits: "1_0" valid_qubits: "1_1" valid_targets { name: "meas_targets" target_ordering: SUBSET_PERMUTATION } valid_targets { name: "2_qubit_targets" target_ordering: SYMMETRIC targets { ids: "0_0" ids: "0_1" } targets { ids: "0_0" ids: "1_0" } targets { ids: "0_1" ids: "1_1" } targets { ids: "1_0" ids: "1_1" } } """)
def test_avoids_infinite_cycle_when_matrix_available(): q = cirq.GridQubit(0, 0) c = cirq.Circuit.from_ops(OtherX().on(q), OtherOtherX().on(q)) cirq.google.ConvertToXmonGates().optimize_circuit(c) assert c.to_text_diagram() == '(0, 0): ───X───X───'
if jc_ij == -1: yield cirq.X(cirq.GridQubit(i, j)) yield cirq.X(cirq.GridQubit(i, j + 1)) def one_step(h, jr, jc, x_half_turns, h_half_turns, j_half_turns): length = len(h) yield rot_x_layer(length, x_half_turns) yield rot_z_layer(h, h_half_turns) yield rot_11_layer(jr, jc, j_half_turns) # define the length of the grid. length = 3 # define qubits on the grid. qubits = [cirq.GridQubit(i, j) for i in range(length) for j in range(length)] # J and h in the Hamiltonian definition # For J use two lists, one for the row links - jr and one for the column links - jc h, jr, jc = random_instance(3) simulator = cirq.Simulator() circuit = cirq.Circuit() circuit.append(one_step(h, jr, jc, 0.1, 0.2, 0.3)) circuit.append(cirq.measure(*qubits, key='x')) print(circuit) # repeat for 100 times and histogram of the counts of the measurement results results = simulator.run(circuit, repetitions=100) print("results - ") print(results.histogram(key='x'))
''' The bit-flip code and the sign-flip code (you can find a description of both here) are two very simple circuits able to detect and fix the bit-flip and the sign-flip errors, respectively. Build the following simple circuit to prepare the Bell state: Now add, right before the CNOT gate and for each of the two qubits, an arbitrary “error gate”. By error gate we mean that with a certain probability (that you can decide but must be non-zero for all the choices) you have a 1 qubit unitary which can be either the identity, or the X gate (bit-flip error) or the Z gate (sign-flip error). Encode each of the two qubits with a sign-flip or a bit-flip code, in such a way that all the possible choices for the error gates described in 2), occurring on the logical qubits, can be detected and fixed. Motivate your choice. This is the most non-trivial part of the problem, so do it with a lot of care! Test your solution by making many measurements over the final state and testing that the results are in line with the expectations. ''' qubits = [cirq.GridQubit(0, i) for i in range(2)] sim = cirq.Simulator() def bitstring(bits): return ''.join(str(int(b)) for b in bits) bell_state = cirq.Circuit() bell_state.append(cirq.H(qubits[0])) bell_state.append(cirq.CNOT(qubits[0], qubits[1])) bell_state.append(cirq.measure(*qubits, key='result')) result = sim.run(bell_state, repetitions=100) frequencies = result.histogram(key='result', fold_func=bitstring) print(frequencies)
def rot_11_layer(jr, jc, half_turns): """Yields rotations about |11> conditioned on the jr and jc fields.""" gate = cirq.CZPowGate(exponent=half_turns) for i, jr_row in enumerate(jr): for j, jr_ij in enumerate(jr_row): if jr_ij == -1: yield cirq.X(cirq.GridQubit(i, j)) yield cirq.X(cirq.GridQubit(i + 1, j)) yield gate(cirq.GridQubit(i, j), cirq.GridQubit(i + 1, j)) if jr_ij == -1: yield cirq.X(cirq.GridQubit(i, j)) yield cirq.X(cirq.GridQubit(i + 1, j)) for i, jc_row in enumerate(jc): for j, jc_ij in enumerate(jc_row): if jc_ij == -1: yield cirq.X(cirq.GridQubit(i, j)) yield cirq.X(cirq.GridQubit(i, j + 1)) yield gate(cirq.GridQubit(i, j), cirq.GridQubit(i, j + 1)) if jc_ij == -1: yield cirq.X(cirq.GridQubit(i, j)) yield cirq.X(cirq.GridQubit(i, j + 1))
def test_sample_outputs_simple(self): """Test the simplest call where nothing but circuits are provided.""" state_calc = state.State() circuit = cirq.Circuit(cirq.H(cirq.GridQubit(0, 0))) output = state_calc([circuit, circuit]) self.assertShapeEqual(np.empty((2, 2)), output.to_tensor())
def test_decompose_with_complex_circuit(self): """Test decompose with complex circuit.""" names = ['CLAE', 'HRYV', 'IRKB', 'LKRV', 'PJOU', 'CJKX', 'NASW'] # Test circuit has a Moment with 1) FSimGate & PhasedXPowGate, # 2) PhasedXPowGate & ISwapPowGate and 3) FSimGate & ISwapPowGate. # Be careful, they are not decomposed if not parameterized. circuit_batch = [ cirq.Circuit([ cirq.Moment(operations=[ cirq.FSimGate(theta=0.10338130973488413 * sympy.Symbol('CLAE'), phi=0.10338130973488413 * sympy.Symbol('IRKB')). on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)), cirq.PhasedXPowGate(phase_exponent=1.0, exponent=0.86426029696045281 * sympy.Symbol('HRYV')).on( cirq.GridQubit(0, 1)), ]), cirq.Moment(operations=[ cirq.Y.on(cirq.GridQubit(0, 3)), cirq.Z.on(cirq.GridQubit(0, 0)), cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)), ]), cirq.Moment(operations=[ (cirq.CNOT**(0.92874230274398684 * sympy.Symbol('IRKB')) ).on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)), ]), cirq.Moment(operations=[ cirq.PhasedXPowGate(phase_exponent=sympy.Symbol('PJOU'), exponent=0.2081415255258906 * sympy.Symbol('LKRV')).on( cirq.GridQubit(0, 2)), (cirq.ISWAP**(0.32860954996781722 * sympy.Symbol('PJOU')) ).on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 3)), ]), cirq.Moment(operations=[ cirq.PhasedXPowGate(phase_exponent=sympy.Symbol( 'CJKX')).on(cirq.GridQubit(0, 1)), cirq.ZZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)), (cirq.X**(0.6826594585474709 * sympy.Symbol('HRYV'))).on(cirq.GridQubit(0, 2)), ]), cirq.Moment(operations=[ (cirq.ZZ**(0.18781276022427218 * sympy.Symbol('PJOU')) ).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)), ]), cirq.Moment(operations=[ cirq.Y.on(cirq.GridQubit(0, 0)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=0.13793763138552417 * sympy.Symbol('CJKX'), phi=0.13793763138552417 * sympy.Symbol('PJOU')). on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)), (cirq.ISWAP**(0.028165738453673095 * sympy.Symbol('NASW')) ).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=0.74356520426349459 * sympy.Symbol('CJKX'), phi=0.74356520426349459 * sympy.Symbol('NASW')). on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 0)), ]), cirq.Moment(operations=[ cirq.CNOT.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)), cirq.SWAP.on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 1)), ]), cirq.Moment(operations=[ cirq.H.on(cirq.GridQubit(0, 3)), cirq.H.on(cirq.GridQubit(0, 2)), cirq.CNOT.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 0)), ]), cirq.Moment(operations=[ cirq.CNOT.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)), cirq.YY.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)), ]), cirq.Moment(operations=[ cirq.CZ.on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 0)), cirq.CNOT.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 3)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)), cirq.CNOT.on(cirq.GridQubit(0, 3), cirq.GridQubit(0, 1)), ]), cirq.Moment(operations=[ cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 3)), cirq.SWAP.on(cirq.GridQubit(0, 2), cirq.GridQubit(0, 1)), ]), cirq.Moment(operations=[ cirq.Y.on(cirq.GridQubit(0, 0)), cirq.PhasedXPowGate( phase_exponent=1.0).on(cirq.GridQubit(0, 2)), cirq.FSimGate(theta=1, phi=1).on(cirq.GridQubit(0, 1), cirq.GridQubit(0, 3)), ]), ]) ] # Decompose programs. inputs = util.convert_to_tensor(circuit_batch) outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs) decomposed_programs = util.from_tensor(outputs) self.assertEqual(len(decomposed_programs), len(circuit_batch)) # Original programs has parameterized ISP, PXP, FSIM, but this result # has no such gates at all. All parameterized gates have at most two # eigenvalues. There are still ISwap and PhasedX(1.0) because they are # not parameterized, which doesn't affect ParameterShift differentiation # at all. for program in decomposed_programs: for moment in program: for gate_op in moment: # Consider parameterized gates only if cirq.is_parameterized(gate_op.gate): # Check I. The gate should have _eigen_components. self.assertTrue( hasattr(gate_op.gate, '_eigen_components')) # Check II. The gate should have two eigen values. self.assertEqual(len(gate_op.gate._eigen_components()), 2, gate_op.gate) # Now all programs don't have ISWAP & PhasedXPowGate because ISWAP has # 3 eigenvalues and PhasedXPowGate doesn't have _eigen_components. # Check if two programs are identical. rand_resolver = {name: np.random.random() for name in names} self.assertAllClose(cirq.unitary( cirq.resolve_parameters(circuit_batch[0], rand_resolver)), cirq.unitary( cirq.resolve_parameters( decomposed_programs[0], rand_resolver)), atol=1e-5)
def test_quantum_runtime_configuration_sampler(rt_config): sampler = rt_config.processor_record.get_sampler() result = sampler.run(cirq.Circuit(cirq.measure(cirq.GridQubit(5, 3), key='z'))) assert isinstance(result, cirq.Result)
import time import numpy as np import pytest from google.protobuf import any_pb2 from google.protobuf.text_format import Merge import cirq import cirq_google import cirq_google as cg from cirq_google.api import v1, v2 from cirq_google.engine.engine import EngineContext from cirq_google.engine.client.quantum_v1alpha1 import types as qtypes _CIRCUIT = cirq.Circuit( cirq.X(cirq.GridQubit(5, 2))**0.5, cirq.measure(cirq.GridQubit(5, 2), key='result')) _CIRCUIT2 = cirq.FrozenCircuit( cirq.Y(cirq.GridQubit(5, 2))**0.5, cirq.measure(cirq.GridQubit(5, 2), key='result')) def _to_any(proto): any_proto = qtypes.any_pb2.Any() any_proto.Pack(proto) return any_proto def _to_timestamp(json_string): timestamp_proto = qtypes.timestamp_pb2.Timestamp()
def rot_x_layer(lenght, half_turns): rot = cirq.XPowGate(exponent=half_turns) for i in range(lenght): for j in range(lenght): yield rot(cirq.GridQubit(i, j))
def default_circuit(): return cirq.FrozenCircuit( cirq.X(cirq.GridQubit(1, 1))**sympy.Symbol('k'), cirq.X(cirq.GridQubit(1, 2)).with_tags(DEFAULT_TOKEN), cirq.measure(cirq.GridQubit(1, 1), key='m'), )
def rot_11_layer(jc, jr, half_turns): rot1 = cirq.CZPowGate(exponent=half_turns) for i, r in enumerate(jr): for j, jr_ij in enumerate(r): if jr_ij < 0: yield (cirq.X(cirq.GridQubit(i, j))) yield (cirq.X(cirq.GridQubit(i + 1, j))) yield (rot1(cirq.GridQubit(i, j), cirq.GridQubit(i + 1, j))) yield (cirq.CZ(cirq.GridQubit(i, j), cirq.GridQubit(i + 1, j))) #change 1 yield (cirq.CZ(cirq.GridQubit(i, j), cirq.GridQubit(i + 1, j))) #chang 2 if jr_ij < 0: yield (cirq.X(cirq.GridQubit(i, j))) yield (cirq.X(cirq.GridQubit(i + 1, j))) for i, c in enumerate(jc): for j, jc_ij in enumerate(c): if jc_ij < 0: yield (cirq.X(cirq.GridQubit(i, j))) yield (cirq.X(cirq.GridQubit(i, j + 1))) yield (rot1(cirq.GridQubit(i, j), cirq.GridQubit(i, j + 1))) yield (cirq.CZ(cirq.GridQubit(i, j), cirq.GridQubit(i, j + 1))) #change 3 yield (cirq.CZ(cirq.GridQubit(i, j), cirq.GridQubit(i, j + 1))) #chang 4 if jc_ij < 0: yield (cirq.X(cirq.GridQubit(i, j))) yield (cirq.X(cirq.GridQubit(i, j + 1)))
}, }, 'qubits': [{ 'id': '1_2' }], }) assert _single_qubit_gate_set().serialize_op(op) == expected deserialized_op = _single_qubit_gate_set().deserialize_op(expected) cirq.testing.assert_allclose_up_to_global_phase( cirq.unitary(deserialized_op), cirq.unitary(op), atol=1e-7) @pytest.mark.parametrize( ('qubits', 'qubit_ids', 'key', 'invert_mask'), [ ([cirq.GridQubit(1, 1)], ['1_1'], 'a', ()), ([cirq.GridQubit(1, 2)], ['1_2'], 'b', (True, )), ([cirq.GridQubit(1, 1), cirq.GridQubit(1, 2)], ['1_1', '1_2'], 'a', (True, False)), ], ) def test_serialize_deserialize_meas(qubits, qubit_ids, key, invert_mask): op = cirq.measure(*qubits, key=key, invert_mask=invert_mask) proto = op_proto({ 'gate': { 'id': 'meas' }, 'qubits': [{ 'id': id } for id in qubit_ids], 'args': {
import tensorflow as tf import tensorflow_quantum as tfq import cirq import sympy import numpy as np # visualization tools#%matplotlib inline import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from cirq.contrib.svg import SVGCircuit qubit = cirq.GridQubit(0, 0) # Define some circuits. circuit1 = cirq.Circuit(cirq.X(qubit)) circuit2 = cirq.Circuit(cirq.H(qubit)) # Convert to a tensor. input_circuit_tensor = tfq.convert_to_tensor([circuit1, circuit2]) # Define a circuit that we want to append y_circuit = cirq.Circuit(cirq.Y(qubit)) # Instantiate our layer y_appender = tfq.layers.AddCircuit() # Run our circuit tensor through the layer and save the output.
def test_tagged_operation_forwards_protocols(): """The results of all protocols applied to an operation with a tag should be equivalent to the result without tags. """ q1 = cirq.GridQubit(1, 1) q2 = cirq.GridQubit(1, 2) h = cirq.H(q1) tag = 'tag1' tagged_h = cirq.H(q1).with_tags(tag) np.testing.assert_equal(cirq.unitary(tagged_h), cirq.unitary(h)) assert cirq.has_unitary(tagged_h) assert cirq.decompose(tagged_h) == cirq.decompose(h) assert cirq.pauli_expansion(tagged_h) == cirq.pauli_expansion(h) assert cirq.equal_up_to_global_phase(h, tagged_h) assert np.isclose(cirq.channel(h), cirq.channel(tagged_h)).all() assert (cirq.measurement_key(cirq.measure( q1, key='blah').with_tags(tag)) == 'blah') parameterized_op = cirq.XPowGate( exponent=sympy.Symbol('t'))(q1).with_tags(tag) assert cirq.is_parameterized(parameterized_op) resolver = cirq.study.ParamResolver({'t': 0.25}) assert (cirq.resolve_parameters( parameterized_op, resolver) == cirq.XPowGate(exponent=0.25)(q1).with_tags(tag)) y = cirq.Y(q1) tagged_y = cirq.Y(q1).with_tags(tag) assert tagged_y**0.5 == cirq.YPowGate(exponent=0.5)(q1) assert tagged_y * 2 == (y * 2) assert (3 * tagged_y == (3 * y)) assert cirq.phase_by(y, 0.125, 0) == cirq.phase_by(tagged_y, 0.125, 0) controlled_y = tagged_y.controlled_by(q2) assert controlled_y.qubits == ( q2, q1, ) assert isinstance(controlled_y, cirq.Operation) assert not isinstance(controlled_y, cirq.TaggedOperation) clifford_x = cirq.SingleQubitCliffordGate.X(q1) tagged_x = cirq.SingleQubitCliffordGate.X(q1).with_tags(tag) assert cirq.commutes(clifford_x, clifford_x) assert cirq.commutes(tagged_x, clifford_x) assert cirq.commutes(clifford_x, tagged_x) assert cirq.commutes(tagged_x, tagged_x) assert (cirq.trace_distance_bound(y**0.001) == cirq.trace_distance_bound( (y**0.001).with_tags(tag))) flip = cirq.bit_flip(0.5)(q1) tagged_flip = cirq.bit_flip(0.5)(q1).with_tags(tag) assert cirq.has_mixture(tagged_flip) assert cirq.has_channel(tagged_flip) flip_mixture = cirq.mixture(flip) tagged_mixture = cirq.mixture(tagged_flip) assert len(tagged_mixture) == 2 assert len(tagged_mixture[0]) == 2 assert len(tagged_mixture[1]) == 2 assert tagged_mixture[0][0] == flip_mixture[0][0] assert np.isclose(tagged_mixture[0][1], flip_mixture[0][1]).all() assert tagged_mixture[1][0] == flip_mixture[1][0] assert np.isclose(tagged_mixture[1][1], flip_mixture[1][1]).all() qubit_map = {q1: 'q1'} qasm_args = cirq.QasmArgs(qubit_id_map=qubit_map) assert (cirq.qasm(h, args=qasm_args) == cirq.qasm(tagged_h, args=qasm_args)) cirq.testing.assert_has_consistent_apply_unitary(tagged_h)
def test_foxtail_qubits(): expected_qubits = [] for i in range(0, 2): for j in range(0, 11): expected_qubits.append(cirq.GridQubit(i, j)) assert set(expected_qubits) == cirq.google.Foxtail.qubits