def hhl_circuit(A, C, t, register_size, *input_prep_gates): """ Constructs the HHL circuit. Args: A: The input Hermitian matrix. C: Algorithm parameter, see above. t: Algorithm parameter, see above. register_size: The size of the eigenvalue register. memory_basis: The basis to measure the memory in, one of 'x', 'y', 'z'. input_prep_gates: A list of gates to be applied to |0> to generate the desired input state |b>. Returns: The HHL circuit. The ancilla measurement has key 'a' and the memory measurement is in key 'm'. There are two parameters in the circuit, `exponent` and `phase_exponent` corresponding to a possible rotation applied before the measurement on the memory with a `cirq.PhasedXPowGate`. """ ancilla = cirq.LineQubit(0) # to store eigenvalues of the matrix register = [cirq.LineQubit(i + 1) for i in range(register_size)] # to store input and output vectors memory = cirq.LineQubit(register_size + 1) c = cirq.Circuit() hs = HamiltonianSimulation(A, t) pe = PhaseEstimation(register_size + 1, hs) c.append([gate(memory) for gate in input_prep_gates]) c.append([ pe(*(register + [memory])), EigenRotation(register_size + 1, C, t)(*(register + [ancilla])), pe(*(register + [memory]))**-1, cirq.measure(ancilla, key='a') ]) c.append([ cirq.PhasedXPowGate( exponent=sympy.Symbol('exponent'), phase_exponent=sympy.Symbol('phase_exponent'))(memory), cirq.measure(memory, key='m') ]) return c
def test_phase_by(): g = cirq.PhasedXPowGate(phase_exponent=0.25) g2 = cirq.phase_by(g, 0.25, 0) assert g2 == cirq.PhasedXPowGate(phase_exponent=0.75) g = cirq.PhasedXPowGate(phase_exponent=0) g2 = cirq.phase_by(g, 0.125, 0) assert g2 == cirq.PhasedXPowGate(phase_exponent=0.25) g = cirq.PhasedXPowGate(phase_exponent=0.5) g2 = cirq.phase_by(g, 0.125, 0) assert g2 == cirq.PhasedXPowGate(phase_exponent=0.75)
def test_toggles_measurements(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') x = sympy.Symbol('x') # Single. assert_optimizes(before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(True, ))], )) assert_optimizes(before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(False, True))], )) assert_optimizes(before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=x).on(b)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(False, True))], ), eject_parameterized=True) # Multiple. assert_optimizes(before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(b)], [cirq.measure(a, b)], ), expected=quick_circuit( [], [], [cirq.measure(a, b, invert_mask=(True, True))], )) # Xmon. assert_optimizes(before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(a)], [cirq.measure(a, b, key='t')], ), expected=quick_circuit( [], [cirq.measure(a, b, invert_mask=(True, ), key='t')], ))
def decompose_swap_into_syc(a: cirq.Qid, b: cirq.Qid): """Decompose SWAP into sycamore gates using precomputed coefficients""" yield cirq.PhasedXPowGate(phase_exponent=0.44650378384076217, exponent=0.8817921214052824).on(a) yield cirq.PhasedXPowGate(phase_exponent=-0.7656774060816165, exponent=0.6628666504604785).on(b) yield google.SYC.on(a, b) yield cirq.PhasedXPowGate(phase_exponent=-0.6277589946716742, exponent=0.5659160932099687).on(a) yield google.SYC.on(a, b) yield cirq.PhasedXPowGate(phase_exponent=0.28890767199499257, exponent=0.4340839067900317).on(b) yield cirq.PhasedXPowGate(phase_exponent=-0.22592784059288928).on(a) yield google.SYC.on(a, b) yield cirq.PhasedXPowGate(phase_exponent=-0.4691261557936808, exponent=0.7728525693920243).on(a) yield cirq.PhasedXPowGate(phase_exponent=-0.8150261316932077, exponent=0.11820787859471782).on( b ) yield (cirq.Z ** -0.7384700844660306).on(b) yield (cirq.Z ** -0.7034535141382525).on(a)
def test_phased_x_pow_gate_test(self): """Test 1 PhasedXPowGate decomposition.""" t = sympy.Symbol('t') r = sympy.Symbol('r') q = cirq.GridQubit(0, 0) circuit = cirq.Circuit( cirq.PhasedXPowGate(phase_exponent=np.random.random() * r, exponent=np.random.random() * t).on(q)) inputs = util.convert_to_tensor([circuit]) outputs = tfq_ps_util_ops.tfq_ps_decompose(inputs) decomposed_programs = util.from_tensor(outputs) rand_resolver = {'t': np.random.random(), 'r': np.random.random()} self.assertAllClose(cirq.unitary( cirq.resolve_parameters(circuit, rand_resolver)), cirq.unitary( cirq.resolve_parameters(decomposed_programs[0], rand_resolver)), atol=1e-5)
def hhl_circuit(A, C, t, register_size, *input_prep_gates): """ HHL 회로를 구성합니다. Args: A: 에르미트 행렬. C: 알고리즘 매개변수, 위 설명 참고. t: 알고리즘 매개변수, 위 설명 참고. register_size: 고유값 레지스터의 크기. memory_basis: 'x', 'y', 'z' 중 하나로 메모리 큐비트를 측정할 기저. input_prep_gates: |0> 상태에 가할 게이트들의 리스트로 원하는 입력 상태 |b>에 해당. Returns: HHL 회로를 반환. 보조 큐비트 측정은 키값 'a'를, 메모리 큐비트의 측정은 키값 'm'을 갖습니다. 회로에는 두 가지 매개변수가 있습니다. `exponent`와 `phase_exponent`는 메모리에 대한 측정이 이루어지기 전에 `cirq.PhasedXPowGate`로 가해질 가능한 회전에 대응됩니다. """ ancilla = cirq.LineQubit(0) # 행렬의 고유값을 저장하기 위한 레지스터. register = [cirq.LineQubit(i + 1) for i in range(register_size)] # 입력과 출력 벡터를 저장하기 위한 메모리 큐비트. memory = cirq.LineQubit(register_size + 1) c = cirq.Circuit() hs = HamiltonianSimulation(A, t) pe = PhaseEstimation(register_size + 1, hs) c.append([gate(memory) for gate in input_prep_gates]) c.append([ pe(*(register + [memory])), EigenRotation(register_size + 1, C, t)(*(register + [ancilla])), pe(*(register + [memory]))**-1, cirq.measure(ancilla, key='a') ]) c.append([ cirq.PhasedXPowGate( exponent=sympy.Symbol('exponent'), phase_exponent=sympy.Symbol('phase_exponent'))(memory), cirq.measure(memory, key='m') ]) return c
def test_str_repr(): assert str(cirq.PhasedXPowGate(phase_exponent=0.25)) == 'PhasedX(0.25)' assert str(cirq.PhasedXPowGate(phase_exponent=0.25, exponent=0.5)) == 'PhasedX(0.25)^0.5' cirq.testing.assert_equivalent_repr(cirq.PhasedXPowGate(phase_exponent=0)) cirq.testing.assert_equivalent_repr( cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.3, global_shift=0.7)) cirq.testing.assert_equivalent_repr( cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.3)) assert repr( cirq.PhasedXPowGate( phase_exponent=0.25, exponent=4, global_shift=0.125) == 'cirq.PhasedXPowGate(phase_exponent=0.25, ' 'exponent=4, global_shift=0.125)') assert repr(cirq.PhasedXPowGate( phase_exponent=0.25)) == 'cirq.PhasedXPowGate(phase_exponent=0.25)'
def test_validate_operation_existing_qubits(): d = ion_device(3) d.validate_operation( cirq.GateOperation(cirq.XX, (cirq.LineQubit(0), cirq.LineQubit(1)))) d.validate_operation(cirq.Z(cirq.LineQubit(0))) d.validate_operation( cirq.PhasedXPowGate(phase_exponent=0.75, exponent=0.25, global_shift=0.1).on(cirq.LineQubit(1))) with pytest.raises(ValueError): d.validate_operation(cirq.CZ(cirq.LineQubit(0), cirq.LineQubit(-1))) with pytest.raises(ValueError): d.validate_operation(cirq.Z(cirq.LineQubit(-1))) with pytest.raises(ValueError): d.validate_operation(cirq.CZ(cirq.LineQubit(1), cirq.LineQubit(1))) with pytest.raises(ValueError): d.validate_operation(cirq.X(cirq.NamedQubit("q1")))
def test_zxz_qiskit(self): """Test the special gate ZXZ (from cirq PhasedXPowGate) for qiskit """ #random.seed(RNDSEED) beta = random.uniform(-1, 1) # rotation angles (in multiples of pi) gamma = random.uniform(-1, 1) # rotation angles (in multiples of pi) qubits = qiskit.QuantumRegister(1) circ = qiskit.QuantumCircuit(qubits) circ.rz(-beta * pi, qubits[0]) circ.rx(gamma * pi, qubits[0]) circ.rz(beta * pi, qubits[0]) z_circuit = Circuit(circ) u1 = z_circuit.to_unitary() circ2 = cirq.PhasedXPowGate(phase_exponent=beta, exponent=gamma) u2 = circ2._unitary_() self.assertTrue(compare_unitary(u1, u2, tol=1e-10))
def test_parameterize(resolve_fn, global_shift): parameterized_gate = cirq.PhasedXPowGate(exponent=sympy.Symbol('a'), phase_exponent=sympy.Symbol('b'), global_shift=global_shift) assert cirq.pow(parameterized_gate, 5) == cirq.PhasedXPowGate(exponent=sympy.Symbol('a') * 5, phase_exponent=sympy.Symbol('b'), global_shift=global_shift) assert cirq.unitary(parameterized_gate, default=None) is None assert cirq.is_parameterized(parameterized_gate) q = cirq.NamedQubit("q") parameterized_decomposed_circuit = cirq.Circuit( cirq.decompose(parameterized_gate(q))) for resolver in cirq.Linspace('a', 0, 2, 10) * cirq.Linspace( 'b', 0, 2, 10): resolved_gate = resolve_fn(parameterized_gate, resolver) assert resolved_gate == cirq.PhasedXPowGate( exponent=resolver.value_of('a'), phase_exponent=resolver.value_of('b'), global_shift=global_shift, ) np.testing.assert_allclose( cirq.unitary(resolved_gate(q)), cirq.unitary(resolve_fn(parameterized_decomposed_circuit, resolver)), atol=1e-8, ) unparameterized_gate = cirq.PhasedXPowGate(exponent=0.1, phase_exponent=0.2, global_shift=global_shift) assert not cirq.is_parameterized(unparameterized_gate) assert cirq.is_parameterized(unparameterized_gate**sympy.Symbol('a')) assert cirq.is_parameterized(unparameterized_gate**(sympy.Symbol('a') + 1)) resolver = {'a': 0.5j} with pytest.raises(ValueError, match='complex value'): resolve_fn( cirq.PhasedXPowGate(exponent=sympy.Symbol('a'), phase_exponent=0.2, global_shift=global_shift), resolver, ) with pytest.raises(ValueError, match='complex value'): resolve_fn( cirq.PhasedXPowGate(exponent=0.1, phase_exponent=sympy.Symbol('a'), global_shift=global_shift), resolver, )
def export_to_cirq(obj): """Imports a gate, operation or circuit from Cirq. Args: obj: the object to be exported to Cirq. Returns: the exported Cirq object (an instance of cirq.Circuit, cirq.GateOperation, or a subclass of cirq.Gate). Raises: TypeError: if export is not supported for the given type. ValueError: if the object cannot be exported successfully. """ if isinstance(obj, circuit.PhasedXGate): return cirq.PhasedXPowGate(exponent=obj.get_rotation_angle() / np.pi, phase_exponent=obj.get_phase_angle() / np.pi) elif isinstance(obj, circuit.RotZGate): return cirq.ZPowGate(exponent=obj.get_rotation_angle() / np.pi) elif isinstance(obj, circuit.ControlledZGate): return cirq.CZPowGate(exponent=1.0) elif isinstance(obj, circuit.MatrixGate): num_qubits = obj.get_num_qubits() operator = obj.get_operator() if num_qubits == 1: return cirq.SingleQubitMatrixGate(operator) elif num_qubits == 2: return cirq.TwoQubitMatrixGate(operator) else: raise ValueError('MatrixGate for %d qubits not supported (Cirq has' ' matrix gates only up to 2 qubits)' % num_qubits) elif isinstance(obj, circuit.Operation): return cirq.GateOperation( export_to_cirq(obj.get_gate()), [cirq.LineQubit(qubit) for qubit in obj.get_qubits()]) elif isinstance(obj, circuit.Circuit): return cirq.Circuit(export_to_cirq(operation) for operation in obj) else: raise TypeError('unknown type: %s' % type(obj).__name__)
def test_serialize_deserialize_phased_x_half_pi_gate(phase_exponent): proto = op_proto({ 'gate': { 'id': 'xy_half_pi' }, 'args': { 'axis_half_turns': { 'arg_value': { 'float_value': phase_exponent } } }, 'qubits': [{ 'id': '1_2' }], }) q = cirq.GridQubit(1, 2) op = cirq.PhasedXPowGate(exponent=0.5, phase_exponent=phase_exponent)(q) assert HALF_PI_GATE_SET.serialize_op(op) == proto assert HALF_PI_GATE_SET.deserialize_op(proto) == op
def test_phase_by(): g = cirq.PhasedXPowGate(phase_exponent=0.25) g2 = cirq.phase_by(g, 0.25, 0) assert g2 == cirq.PhasedXPowGate(phase_exponent=0.75) cirq.testing.assert_phase_by_is_consistent_with_unitary(g) g = cirq.PhasedXPowGate(phase_exponent=0) g2 = cirq.phase_by(g, 0.125, 0) assert g2 == cirq.PhasedXPowGate(phase_exponent=0.25) cirq.testing.assert_phase_by_is_consistent_with_unitary(g) g = cirq.PhasedXPowGate(phase_exponent=0.5) g2 = cirq.phase_by(g, 0.125, 0) assert g2 == cirq.PhasedXPowGate(phase_exponent=0.75) cirq.testing.assert_phase_by_is_consistent_with_unitary(g)
def test_deserialize_xy_parameterized(): serialized_op = op_proto({ 'gate': { 'id': 'xy' }, 'args': { 'axis_half_turns': { 'symbol': 'a' }, 'half_turns': { 'symbol': 'b' } }, 'qubits': [{ 'id': '1_2' }], }) q = cirq.GridQubit(1, 2) expected = cirq.PhasedXPowGate(exponent=sympy.Symbol('b'), phase_exponent=sympy.Symbol('a'))(q) assert SINGLE_QUBIT_GATE_SET.deserialize_op(serialized_op) == expected
def test_deserialize_exp_w_parameterized(): serialized_op = op_proto({ 'gate': { 'id': 'xy' }, 'args': { 'axis_half_turns': { 'symbol': 'x' }, 'half_turns': { 'symbol': 'y' } }, 'qubits': [{ 'id': '1_2' }], }) q = cirq.GridQubit(1, 2) expected = cirq.PhasedXPowGate(exponent=sympy.Symbol('y'), phase_exponent=sympy.Symbol('x'))(q) assert cg.XMON.deserialize_op(serialized_op) == expected
def test_convert_to_ion_gates(): q0 = cirq.GridQubit(0, 0) q1 = cirq.GridQubit(0, 1) op = cirq.CNOT(q0, q1) circuit = cirq.Circuit() with pytest.raises(TypeError): cirq.ion.ConvertToIonGates().convert_one(circuit) with pytest.raises(TypeError): cirq.ion.ConvertToIonGates().convert_one(NoUnitary().on(q0)) no_unitary_op = NoUnitary().on(q0) assert cirq.ion.ConvertToIonGates(ignore_failures=True).convert_one(no_unitary_op) == [ no_unitary_op ] rx = cirq.ion.ConvertToIonGates().convert_one(OtherX().on(q0)) rop = cirq.ion.ConvertToIonGates().convert_one(op) assert cirq.approx_eq(rx, [cirq.PhasedXPowGate(phase_exponent=1.0).on(cirq.GridQubit(0, 0))]) assert cirq.approx_eq( rop, [ cirq.ry(np.pi / 2).on(op.qubits[0]), cirq.ms(np.pi / 4).on(op.qubits[0], op.qubits[1]), cirq.rx(-1 * np.pi / 2).on(op.qubits[0]), cirq.rx(-1 * np.pi / 2).on(op.qubits[1]), cirq.ry(-1 * np.pi / 2).on(op.qubits[0]), ], ) rcnot = cirq.ion.ConvertToIonGates().convert_one(OtherCNOT().on(q0, q1)) assert cirq.approx_eq( [op for op in rcnot if len(op.qubits) > 1], [cirq.ms(-0.5 * np.pi / 2).on(q0, q1)], atol=1e-4, ) assert cirq.allclose_up_to_global_phase( cirq.unitary(cirq.Circuit(rcnot)), cirq.unitary(OtherCNOT().on(q0, q1)) )
def test_approx_eq(): assert cirq.approx_eq( cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.2, global_shift=0.3), cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.2, global_shift=0.3), atol=1e-4, ) assert not cirq.approx_eq( cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.2, global_shift=0.4), cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.2, global_shift=0.3), atol=1e-4, ) assert cirq.approx_eq( cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.2, global_shift=0.4), cirq.PhasedXPowGate(phase_exponent=0.1, exponent=0.2, global_shift=0.3), atol=0.2, )
def decompose_iswap_into_syc(a: cirq.Qid, b: cirq.Qid): """Decompose ISWAP into sycamore gates using precomputed coefficients""" yield cirq.PhasedXPowGate(phase_exponent=-0.27250925776964596, exponent=0.2893438375555899).on(a) yield google.SYC.on(a, b) yield cirq.PhasedXPowGate(phase_exponent=0.8487591858680898, exponent=0.9749387200813147).on(b), yield cirq.PhasedXPowGate(phase_exponent=-0.3582574564210601).on(a), yield google.SYC.on(a, b) yield cirq.PhasedXPowGate(phase_exponent=0.9675022326694225, exponent=0.6908986856555526).on(a), yield google.SYC.on(a, b), yield cirq.PhasedXPowGate(phase_exponent=0.9161706861686068, exponent=0.14818318325264102).on(b), yield cirq.PhasedXPowGate(phase_exponent=0.9408341606787907).on(a), yield (cirq.Z**-1.1551880579397293).on(b), yield (cirq.Z**0.31848343246696365).on(a),
def test_convert_to_ion_gates(): q0 = cirq.GridQubit(0, 0) q1 = cirq.GridQubit(0, 1) op = cirq.CNOT(q0, q1) circuit = cirq.Circuit() with pytest.raises(TypeError): cirq.ion.ConvertToIonGates().convert_one(circuit) with pytest.raises(TypeError): cirq.ion.ConvertToIonGates().convert_one(NoUnitary().on(q0)) no_unitary_op = NoUnitary().on(q0) assert cirq.ion.ConvertToIonGates( ignore_failures=True).convert_one(no_unitary_op) == [no_unitary_op] rx = cirq.ion.ConvertToIonGates().convert_one(OtherX().on(q0)) rop = cirq.ion.ConvertToIonGates().convert_one(op) rcnot = cirq.ion.ConvertToIonGates().convert_one(OtherCNOT().on(q0, q1)) assert rx == [(cirq.X**1.0).on(cirq.GridQubit(0, 0))] assert rop == [ cirq.Ry(np.pi / 2).on(op.qubits[0]), cirq.ion.MS(np.pi / 4).on(op.qubits[0], op.qubits[1]), cirq.ops.Rx(-1 * np.pi / 2).on(op.qubits[0]), cirq.ops.Rx(-1 * np.pi / 2).on(op.qubits[1]), cirq.ops.Ry(-1 * np.pi / 2).on(op.qubits[0]) ] assert rcnot == [ cirq.PhasedXPowGate(phase_exponent=-0.75, exponent=0.5).on(cirq.GridQubit(0, 0)), (cirq.X**-0.25).on(cirq.GridQubit(0, 1)), cirq.T.on(cirq.GridQubit(0, 0)), cirq.MS(-0.5 * np.pi / 2).on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1)), (cirq.Y**0.5).on(cirq.GridQubit(0, 0)), (cirq.X**-0.25).on(cirq.GridQubit(0, 1)), (cirq.Z**-0.75).on(cirq.GridQubit(0, 0)) ]
def simulate(sim_type: str, num_qubits: int, num_gates: int, num_prefix_qubits: int = 0, use_processes: bool = False) -> None: """"Runs the simulator.""" circuit = cirq.Circuit(device=test_device) for _ in range(num_gates): which = np.random.choice(['expz', 'expw', 'exp11']) if which == 'expw': q1 = cirq.GridQubit(0, np.random.randint(num_qubits)) circuit.append( cirq.PhasedXPowGate( phase_exponent=np.random.random(), exponent=np.random.random() ).on(q1)) elif which == 'expz': q1 = cirq.GridQubit(0, np.random.randint(num_qubits)) circuit.append( cirq.Z(q1)**np.random.random()) elif which == 'exp11': q1 = cirq.GridQubit(0, np.random.randint(num_qubits - 1)) q2 = cirq.GridQubit(0, q1.col + 1) circuit.append(cirq.CZ(q1, q2)**np.random.random()) circuit.append([ cirq.measure(cirq.GridQubit(0, np.random.randint(num_qubits)), key='meas') ]) if sim_type == _XMON: options = cg.XmonOptions(num_shards=2 ** num_prefix_qubits, use_processes=use_processes) cg.XmonSimulator(options).run(circuit) elif sim_type == _UNITARY: circuit.final_wavefunction(initial_state=0) elif sim_type == _DENSITY: cirq.DensityMatrixSimulator().run(circuit)
def test_serialize_xy_parameterized_axis_half_turns(): gate = cirq.PhasedXPowGate(exponent=0.25, phase_exponent=sympy.Symbol('a')) q = cirq.GridQubit(1, 2) expected = op_proto({ 'gate': { 'id': 'xy' }, 'args': { 'axis_half_turns': { 'symbol': 'a' }, 'half_turns': { 'arg_value': { 'float_value': 0.25 } }, }, 'qubits': [{ 'id': '1_2' }], }) assert SINGLE_QUBIT_GATE_SET.serialize_op(gate.on(q)) == expected
def test_serialize_exp_w_parameterized_axis_half_turns(): gate = cirq.PhasedXPowGate(exponent=0.25, phase_exponent=sympy.Symbol('x')) q = cirq.GridQubit(1, 2) expected = { 'gate': { 'id': 'xy' }, 'args': { 'axis_half_turns': { 'symbol': 'x' }, 'half_turns': { 'arg_value': { 'float_value': 0.25 } }, }, 'qubits': [{ 'id': '1_2' }] } assert cg.XMON.serialize_op_dict(gate.on(q)) == expected
def xmon_op_from_proto(proto: operations_pb2.Operation) -> cirq.Operation: """Convert the proto to the corresponding operation. See protos in api/google/v1 for specification of the protos. Args: proto: Operation proto. Returns: The operation. Raises: ValueError: If the proto has an operation that is invalid. """ param = _parameterized_value_from_proto qubit = _qubit_from_proto if proto.HasField('exp_w'): exp_w = proto.exp_w return cirq.PhasedXPowGate( exponent=param(exp_w.half_turns), phase_exponent=param(exp_w.axis_half_turns), ).on(qubit(exp_w.target)) if proto.HasField('exp_z'): exp_z = proto.exp_z return cirq.Z(qubit(exp_z.target))**param(exp_z.half_turns) if proto.HasField('exp_11'): exp_11 = proto.exp_11 return cirq.CZ(qubit(exp_11.target1), qubit(exp_11.target2))**param(exp_11.half_turns) if proto.HasField('measurement'): meas = proto.measurement return cirq.MeasurementGate(num_qubits=len(meas.targets), key=meas.key, invert_mask=tuple(meas.invert_mask)).on( *[qubit(q) for q in meas.targets]) raise ValueError(f'invalid operation: {proto}')
def simulate(sim_type: str, num_qubits: int, num_gates: int, run_repetitions: int = 1) -> None: """Runs the simulator.""" circuit = cirq.Circuit() for _ in range(num_gates): which = np.random.choice(['expz', 'expw', 'exp11']) if which == 'expw': q1 = cirq.GridQubit(0, np.random.randint(num_qubits)) circuit.append( cirq.PhasedXPowGate(phase_exponent=np.random.random(), exponent=np.random.random()).on(q1)) elif which == 'expz': q1 = cirq.GridQubit(0, np.random.randint(num_qubits)) circuit.append(cirq.Z(q1)**np.random.random()) elif which == 'exp11': q1 = cirq.GridQubit(0, np.random.randint(num_qubits - 1)) q2 = cirq.GridQubit(0, q1.col + 1) circuit.append(cirq.CZ(q1, q2)**np.random.random()) circuit.append([ cirq.measure(*[cirq.GridQubit(0, i) for i in range(num_qubits)], key='meas') ]) if sim_type == _DENSITY: for i in range(num_qubits): circuit.append(cirq.H(cirq.GridQubit(0, i))) circuit.append(cirq.measure(cirq.GridQubit(0, i), key=f"meas{i}.")) if sim_type == _UNITARY: circuit.final_state_vector(initial_state=0, ignore_terminal_measurements=True, dtype=np.complex64) elif sim_type == _DENSITY: cirq.DensityMatrixSimulator().run(circuit, repetitions=run_repetitions)
def test_zxz_pyquil(self): """Test the special gate ZXZ (from cirq PhasedXPowGate) for pyquil """ #random.seed(RNDSEED) beta = random.uniform(-1, 1) # rotation angles (in multiples of pi) gamma = random.uniform(-1, 1) # rotation angles (in multiples of pi) circ1 = pyquil.quil.Program(RZ(-beta * pi, 0), RX(gamma * pi, 0), RZ(beta * pi, 0)) cirq_gate = cirq.PhasedXPowGate(phase_exponent=beta, exponent=gamma) cirq_circuit = cirq.Circuit() q = cirq.LineQubit(0) cirq_circuit.append([cirq_gate(q)], strategy=cirq.circuits.InsertStrategy.EARLIEST) z_circuit = Circuit(cirq_circuit) circ2 = z_circuit.to_pyquil() # desired unitary u = np.array([[cos(gamma*pi/2),-sin(beta*pi)*sin(gamma*pi/2)-1j*cos(beta*pi)*sin(gamma*pi/2)],\ [sin(beta*pi)*sin(gamma*pi/2)-1j*cos(beta*pi)*sin(gamma*pi/2),cos(gamma*pi/2)]]) u1 = Circuit(circ1).to_unitary() u2 = Circuit(circ2).to_unitary() u3 = cirq_gate._unitary_() if compare_unitary(u1, u2, tol=1e-10) == False: print('u1={}'.format(u1)) print('u2={}'.format(u2)) if compare_unitary(u2, u3, tol=1e-10) == False: print('u2={}'.format(u2)) print('u3={}'.format(u3)) if compare_unitary(u3, u, tol=1e-10) == False: print('u2={}'.format(u2)) print('u3={}'.format(u3)) self.assertTrue(compare_unitary(u1, u2, tol=1e-10)) self.assertTrue(compare_unitary(u2, u3, tol=1e-10)) self.assertTrue(compare_unitary(u3, u, tol=1e-10))
def test_new_init(): g = cirq.PhasedXPowGate(phase_exponent=0.75, exponent=0.25, global_shift=0.1) assert g.phase_exponent == 0.75 assert g.exponent == 0.25 assert g._global_shift == 0.1 assert isinstance(cirq.PhasedXPowGate(phase_exponent=0), cirq.XPowGate) assert isinstance(cirq.PhasedXPowGate(phase_exponent=1), cirq.XPowGate) assert isinstance(cirq.PhasedXPowGate(phase_exponent=0.5), cirq.YPowGate) assert isinstance(cirq.PhasedXPowGate(phase_exponent=1.5), cirq.YPowGate) x = cirq.PhasedXPowGate(phase_exponent=0, exponent=0.1, global_shift=0.2) assert isinstance(x, cirq.XPowGate) assert x.exponent == 0.1 assert x._global_shift == 0.2 y = cirq.PhasedXPowGate(phase_exponent=0.5, exponent=0.1, global_shift=0.2) assert isinstance(y, cirq.YPowGate) assert y.exponent == 0.1 assert y._global_shift == 0.2
def test_deserialize_exp_w_parameterized(): with cirq.testing.assert_deprecated('SerializableGateSet', deadline='v0.16', count=1): serialized_op = op_proto({ 'gate': { 'id': 'xy' }, 'args': { 'axis_half_turns': { 'symbol': 'x' }, 'half_turns': { 'symbol': 'y' } }, 'qubits': [{ 'id': '1_2' }], }) q = cirq.GridQubit(1, 2) expected = cirq.PhasedXPowGate(exponent=sympy.Symbol('y'), phase_exponent=sympy.Symbol('x'))(q) assert cg.XMON.deserialize_op(serialized_op) == expected
def serialize(serializer: str, num_gates: int, nesting_depth: int) -> int: """Runs a round-trip of the serializer.""" circuit = cirq.Circuit() for _ in range(num_gates): which = np.random.choice(['expz', 'expw', 'exp11']) if which == 'expw': q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS)) circuit.append( cirq.PhasedXPowGate( phase_exponent=np.random.random(), exponent=np.random.random() ).on(q1) ) elif which == 'expz': q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS)) circuit.append(cirq.Z(q1) ** np.random.random()) elif which == 'exp11': q1 = cirq.GridQubit(0, np.random.randint(NUM_QUBITS - 1)) q2 = cirq.GridQubit(0, q1.col + 1) circuit.append(cirq.CZ(q1, q2) ** np.random.random()) cs = [circuit] for _ in range(1, nesting_depth): fc = cs[-1].freeze() cs.append(cirq.Circuit(fc.to_op(), fc.to_op())) test_circuit = cs[-1] if serializer == _JSON: json_data = cirq.to_json(test_circuit) assert json_data is not None data_size = len(json_data) cirq.read_json(json_text=json_data) elif serializer == _JSON_GZIP: gzip_data = cirq.to_json_gzip(test_circuit) assert gzip_data is not None data_size = len(gzip_data) cirq.read_json_gzip(gzip_raw=gzip_data) return data_size
def test_cancels_other_full_w(): q = cirq.NamedQubit('q') assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), expected=quick_circuit( [], [], )) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], ), expected=quick_circuit( [], [cirq.Z(q)**-0.25], )) assert_optimizes( before=quick_circuit( [cirq.X(q)], [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], ), expected=quick_circuit( [], [cirq.Z(q)**0.5], )) assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [cirq.X(q)], ), expected=quick_circuit( [], [cirq.Z(q)**-0.5], ))
def test_absorbs_z(): q = cirq.NamedQubit('q') # Full Z. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.Z(q)], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.625).on(q)], [], )) # Partial Z. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.375).on(q)], [], )) # Multiple Zs. assert_optimizes( before=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.125).on(q)], [cirq.S(q)], [cirq.T(q)**-1], ), expected=quick_circuit( [cirq.PhasedXPowGate(phase_exponent=0.25).on(q)], [], [], ))