def test_controlled_by(): a, b, c = cirq.LineQubit.range(3) g = cirq.SingleQubitGate() # Ignores empty. assert g.controlled_by() is g # Combined. cg = g.controlled_by(a, b) assert isinstance(cg, cirq.ControlledGate) assert cg.sub_gate == g assert cg.control_qubits == (a, b) # Equality ignores ordering but cares about set and quantity. eq = cirq.testing.EqualsTester() eq.add_equality_group(g, g.controlled_by()) eq.add_equality_group(g.controlled_by(a, b), g.controlled_by(b, a), cirq.ControlledGate(g, [a, b]), g.controlled_by(a).controlled_by(b)) eq.add_equality_group(g.controlled_by(a)) eq.add_equality_group(g.controlled_by(b)) eq.add_equality_group(g.controlled_by(a, c)) eq.add_equality_group(cirq.ControlledGate(g, num_controls=1)) eq.add_equality_group(cirq.ControlledGate(g, num_controls=2))

def test_parameterizable(): a = cirq.Symbol('a') cz = cirq.ControlledGate(cirq.RotYGate(half_turns=1)) cza = cirq.ControlledGate(cirq.RotYGate(half_turns=a)) assert cza.is_parameterized() assert not cz.is_parameterized() assert cza.with_parameters_resolved_by(cirq.ParamResolver({'a': 1})) == cz

def test_circuit_diagram_info(): assert cirq.circuit_diagram_info(CY) == cirq.CircuitDiagramInfo( wire_symbols=('@', 'Y'), exponent=1) assert cirq.circuit_diagram_info(C0Y) == cirq.CircuitDiagramInfo( wire_symbols=('(0)', 'Y'), exponent=1) assert cirq.circuit_diagram_info(C2Y) == cirq.CircuitDiagramInfo( wire_symbols=('(2)', 'Y'), exponent=1) assert cirq.circuit_diagram_info(cirq.ControlledGate(cirq.Y**0.5) ) == cirq.CircuitDiagramInfo( wire_symbols=('@', 'Y'), exponent=0.5) assert cirq.circuit_diagram_info(cirq.ControlledGate(cirq.S) ) == cirq.CircuitDiagramInfo( wire_symbols=('@', 'S'), exponent=1) class UndiagrammableGate(cirq.SingleQubitGate): pass assert cirq.circuit_diagram_info(cirq.ControlledGate(UndiagrammableGate()), default=None) is None

def qft(qubits, tol=None, mea=False, initial=None, control=()): size = len(qubits) if tol == None: # Sets maximum distance of controlled gates to cover entire circuit if not given. tol = size if initial == None: # Sets array for qubit starting state to all 0's if not given. initial = zeros(size) for i in range( size): # Applies an X gate to all qubits starting in the state 1. if initial[i] == 1: yield cirq.ControlledGate(X, num_controls=len(control))(*control, qubits[i]) for i in range( size ): # Applies Hadamard and CPhase gates to each block of qubits. yield cirq.ControlledGate(H, num_controls=len(control))(*control, qubits[i]) for j in range(1, min(size - i, tol)): yield cirq.ControlledGate(CZP(exponent=1 / (2**(j))), num_controls=len(control))(*control, qubits[i], qubits[i + j]) for i in range( size // 2 ): # Applies swap gates to switch order of qubits at the end of the circuit. yield cirq.ControlledGate(SWAP, num_controls=len(control))( *control, qubits[i], qubits[size - i - 1]) for i in range( size ): # Adds measurement operators at the end of the circuit if mea is set to true. if mea: yield measure(qubits[i], key='q{}'.format(str(i)))

def test_text_diagrammable(): assert CY.text_diagram_wire_symbols() == ('@', 'Y') assert CY.text_diagram_exponent() == 1 assert cirq.ControlledGate(cirq.S).text_diagram_wire_symbols() == ('@', 'Z') assert cirq.ControlledGate(cirq.S).text_diagram_exponent() == 0.5

def test_eq(): eq = cirq.testing.EqualsTester() eq.add_equality_group(CY, cirq.ControlledGate(cirq.Y)) eq.add_equality_group(CCH) eq.add_equality_group(cirq.ControlledGate(cirq.H)) eq.add_equality_group(cirq.ControlledGate(cirq.X)) eq.add_equality_group(cirq.X)

def test_control(): g = cirq.SingleQubitGate() # Ignores empty. assert g.controlled() == cirq.ControlledGate(g) # Combined. cg = g.controlled() assert isinstance(cg, cirq.ControlledGate) assert cg.sub_gate == g assert cg.num_controls() == 1 # Equality ignores ordering but cares about set and quantity. eq = cirq.testing.EqualsTester() eq.add_equality_group(g) eq.add_equality_group(g.controlled(), g.controlled(control_values=[1]), g.controlled(control_qid_shape=(2, )), cirq.ControlledGate(g, num_controls=1)) eq.add_equality_group(cirq.ControlledGate(g, num_controls=2), g.controlled(control_values=[1, 1]), g.controlled(control_qid_shape=[2, 2]), g.controlled(num_controls=2), g.controlled().controlled()) eq.add_equality_group( cirq.ControlledGate(g, control_values=[0, 1]), g.controlled(control_values=[0, 1]), g.controlled(control_values=[0]).controlled(control_values=[1])) eq.add_equality_group( cirq.ControlledGate(g, control_qid_shape=[4, 3]), g.controlled(control_qid_shape=[4, 3]), g.controlled(control_qid_shape=[4]).controlled(control_qid_shape=[3]))

def test_controlled_gate(): a, b, c, d = cirq.LineQubit.range(4) circuit = cirq.Circuit( cirq.ControlledGate(cirq.ControlledGate(cirq.CZ)).on(a, d, c, b)) assert_links_to( circuit, """ http://algassert.com/quirk#circuit={"cols":[["•","Z","•", "•"]]} """, escape_url=False, ) # Doesn't merge. circuit = cirq.Circuit( cirq.ControlledGate(cirq.X).on(a, b), cirq.ControlledGate(cirq.Z).on(c, d)) assert_links_to( circuit, """ http://algassert.com/quirk#circuit={"cols":[["•","X"],[1,1,"•", "Z"]]} """, escape_url=False, ) # Unknown sub-gate. circuit = cirq.Circuit(cirq.ControlledGate(MysteryGate()).on(a, b)) assert_links_to( circuit, """ http://algassert.com/quirk#circuit={"cols":[["UNKNOWN","UNKNOWN"]]} """, escape_url=False, prefer_unknown_gate_to_failure=True, )

def test_pow_inverse(): assert cirq.inverse(CRestricted, None) is None assert cirq.inverse(SCRestricted, None) is None assert cirq.pow(CRestricted, 1.5, None) is None assert cirq.pow(SCRestricted, 1.5, None) is None assert cirq.pow(CY, 1.5) == cirq.ControlledGate(cirq.Y**1.5) assert cirq.inverse(CY) == CY**-1 == CY assert cirq.inverse(SCY) == SCY**-1 == SCY assert cirq.inverse(C0Restricted, None) is None assert cirq.inverse(SC0Restricted, None) is None assert cirq.pow(C0Restricted, 1.5, None) is None assert cirq.pow(SC0Restricted, 1.5, None) is None assert cirq.pow(C0Y, 1.5) == cirq.ControlledGate(cirq.Y**1.5, control_values=[0]) assert cirq.inverse(C0Y) == C0Y**-1 == C0Y assert cirq.inverse(SC0Y) == SC0Y**-1 == SC0Y assert cirq.inverse(C2Restricted, None) is None assert cirq.inverse(SC2Restricted, None) is None assert cirq.pow(C2Restricted, 1.5, None) is None assert cirq.pow(SC2Restricted, 1.5, None) is None assert cirq.pow(C2Y, 1.5) == cirq.ControlledGate(cirq.Y**1.5, control_values=[2], control_qid_shape=(3,)) assert cirq.inverse(C2Y) == C2Y**-1 == C2Y assert cirq.inverse(SC2Y) == SC2Y**-1 == SC2Y

def test_consistency_with_qasm_output_and_qiskit(): qubits = [cirq.NamedQubit('q_{}'.format(i)) for i in range(4)] a, b, c, d = qubits circuit1 = cirq.Circuit( cirq.rx(np.pi / 2).on(a), cirq.ry(np.pi / 2).on(b), cirq.rz(np.pi / 2).on(b), cirq.X.on(a), cirq.Y.on(b), cirq.Z.on(c), cirq.H.on(d), cirq.S.on(a), cirq.T.on(b), cirq.S.on(c) ** -1, cirq.T.on(d) ** -1, cirq.X.on(d) ** 0.125, cirq.TOFFOLI.on(a, b, c), cirq.CSWAP.on(d, a, b), cirq.SWAP.on(c, d), cirq.CX.on(a, b), cirq.ControlledGate(cirq.Y).on(c, d), cirq.CZ.on(a, b), cirq.ControlledGate(cirq.H).on(b, c), cirq.IdentityGate(1).on(c), cirq.circuits.qasm_output.QasmUGate(1.0, 2.0, 3.0).on(d), ) qasm = cirq.qasm(circuit1) circuit2 = circuit_from_qasm(qasm) cirq_unitary = cirq.unitary(circuit2) ct.assert_allclose_up_to_global_phase(cirq_unitary, cirq.unitary(circuit1), atol=1e-8) cq.assert_qiskit_parsed_qasm_consistent_with_unitary(qasm, cirq_unitary)

def test_parameterizable(): a = cirq.Symbol('a') cz = cirq.ControlledGate(cirq.RotYGate(half_turns=1)) cza = cirq.ControlledGate(cirq.RotYGate(half_turns=a)) assert cirq.is_parameterized(cza) assert not cirq.is_parameterized(cz) assert cirq.resolve_parameters(cza, cirq.ParamResolver({'a': 1})) == cz

def test_parameterizable(): a = sympy.Symbol('a') cy = cirq.ControlledGate(cirq.Y) cya = cirq.ControlledGate(cirq.YPowGate(exponent=a)) assert cirq.is_parameterized(cya) assert not cirq.is_parameterized(cy) assert cirq.resolve_parameters(cya, cirq.ParamResolver({'a': 1})) == cy

def test_init(): ext = cirq.Extensions() gate = cirq.ControlledGate(cirq.Z, ext) assert gate.default_extensions is ext assert gate.sub_gate is cirq.Z assert cirq.ControlledGate(cirq.X).default_extensions is None

def QNPU2B(l_old,l_new,n): ctrl,q0,q1 = [cirq.GridQubit(0, 0), cirq.GridQubit(0, 1), cirq.GridQubit(0, 2)] U1=cirq.ControlledGate(U(l_old)) U2=cirq.ControlledGate(cirq.inverse(U(l_new))) circuit = cirq.Circuit(cirq.H(ctrl), cirq.S(ctrl),U1.on(ctrl,q0,q1), cirq.CNOT(ctrl,q1), cirq.TOFFOLI(ctrl,q1,q0), U2.on(ctrl,q0,q1), cirq.H(ctrl), cirq.measure(ctrl,key='c'), strategy=cirq.InsertStrategy.EARLIEST) simulator = cirq.Simulator() result=simulator.run(circuit, repetitions=n) m=result.histogram(key='c') for i,j in m.items(): if i==0: term=2*(j/n)-1 elif i==1: term=1-2*(j/n) return term

def test_repr(): assert repr(cirq.ControlledGate( cirq.Z)) == 'cirq.ControlledGate(sub_gate=cirq.Z)' assert (repr(cirq.ControlledGate( cirq.Z, [cirq.LineQubit(0)])) == "cirq.ControlledGate(sub_gate=cirq.Z, " "control_qubits=(cirq.LineQubit(0),), " "num_controls=1)")

def test_repr(): cirq.testing.assert_equivalent_repr(cirq.ControlledGate(cirq.Z)) cirq.testing.assert_equivalent_repr( cirq.ControlledGate(cirq.Z, num_controls=1)) cirq.testing.assert_equivalent_repr( cirq.ControlledGate(cirq.Z, num_controls=2)) cirq.testing.assert_equivalent_repr(C0C1H) cirq.testing.assert_equivalent_repr(C2C2H)

def test_repr(): cirq.testing.assert_equivalent_repr(cirq.ControlledGate(cirq.Z)) cirq.testing.assert_equivalent_repr( cirq.ControlledGate(cirq.Z, num_controls=1)) cirq.testing.assert_equivalent_repr( cirq.ControlledGate(cirq.Z, num_controls=2)) cirq.testing.assert_equivalent_repr( cirq.ControlledGate(cirq.Y, control_qubits=[cirq.LineQubit(1)]))

def test_extrapolatable_effect(): a = cirq.NamedQubit('a') b = cirq.NamedQubit('b') assert cirq.ControlledGate(cirq.Z)**0.5 == cirq.ControlledGate(cirq.Z**0.5) assert (cirq.ControlledGate(cirq.Z).on(a, b)**0.5 == cirq.ControlledGate( cirq.Z**0.5).on(a, b))

def test_pow_inverse(): assert cirq.inverse(CRestricted, None) is None assert cirq.inverse(SCRestricted, None) is None assert cirq.pow(CRestricted, 1.5, None) is None assert cirq.pow(SCRestricted, 1.5, None) is None assert cirq.pow(CY, 1.5) == cirq.ControlledGate(cirq.Y**1.5) assert cirq.pow(SCY, 1.5) == cirq.ControlledGate(cirq.Y**1.5) assert cirq.inverse(CY) == CY**-1 == CY assert cirq.inverse(SCY) == SCY**-1 == SCY

def test_parameterizable_via_extension(): ext = cirq.Extensions() ext.add_cast(cirq.ParameterizableEffect, RestrictedGate, lambda _: cirq.S) without_ext = cirq.ControlledGate(RestrictedGate()) with_ext = cirq.ControlledGate(RestrictedGate(), ext) with pytest.raises(TypeError): _ = without_ext.is_parameterized() assert not with_ext.is_parameterized()

def test_parameterizable(): a = sympy.Symbol('a') cz = cirq.ControlledGate(cirq.Y) cza = cirq.ControlledGate(cirq.YPowGate(exponent=a)) scza = cirq.ControlledGate(cirq.YPowGate(exponent=a), [q]) assert cirq.is_parameterized(cza) assert cirq.is_parameterized(scza) assert not cirq.is_parameterized(cz) assert cirq.resolve_parameters(cza, cirq.ParamResolver({'a': 1})) == cz assert cirq.resolve_parameters(scza, cirq.ParamResolver({'a': 1})) == cz

def test_text_diagrammable_via_extension(): ext = cirq.Extensions() ext.add_cast(cirq.TextDiagrammableGate, RestrictedGate, lambda _: cirq.S) without_ext = cirq.ControlledGate(RestrictedGate()) with_ext = cirq.ControlledGate(RestrictedGate(), ext) with pytest.raises(TypeError): _ = without_ext.text_diagram_exponent() assert with_ext.text_diagram_exponent() == 0.5

def test_str(): assert str(cirq.ControlledGate(cirq.X)) == 'CX' assert str(cirq.ControlledGate(cirq.Z)) == 'CZ' assert str(cirq.ControlledGate(cirq.S)) == 'CS' assert str(cirq.ControlledGate(cirq.S, [q])) == 'CS' assert str(cirq.ControlledGate(cirq.Z**0.125)) == 'CZ**0.125' assert str(cirq.ControlledGate(cirq.ControlledGate(cirq.S))) == 'CCS' assert str(cirq.ControlledGate(cirq.ControlledGate(cirq.S, [q]), [q])) == 'CCS' assert str(cirq.ControlledGate(cirq.S, [q, q], 2)) == 'CCS'

def test_reversible_via_extension(): ext = cirq.Extensions() ext.add_cast(cirq.ReversibleEffect, RestrictedGate, lambda _: cirq.S) without_ext = cirq.ControlledGate(RestrictedGate()) with_ext = cirq.ControlledGate(RestrictedGate(), ext) with pytest.raises(TypeError): _ = without_ext.inverse() assert with_ext.inverse() == cirq.ControlledGate(cirq.S.inverse())

def test_bounded_effect_via_extension(): ext = cirq.Extensions() ext.add_cast(cirq.BoundedEffect, RestrictedGate, lambda _: cirq.Y) without_ext = cirq.ControlledGate(RestrictedGate()) with_ext = cirq.ControlledGate(RestrictedGate(), ext) with pytest.raises(TypeError): _ = without_ext.trace_distance_bound() assert with_ext.trace_distance_bound() < 100

def test_eq(): eq = cirq.testing.EqualsTester() eq.add_equality_group(CY, cirq.ControlledGate(cirq.Y)) eq.add_equality_group(CCH) eq.add_equality_group(cirq.ControlledGate(cirq.H)) eq.add_equality_group(cirq.ControlledGate(cirq.X)) eq.add_equality_group(cirq.X) eq.add_equality_group( cirq.ControlledGate(cirq.H, control_values=[1, (0, 2)], control_qid_shape=[2, 3]), cirq.ControlledGate(cirq.H, control_values=[(2, 0), 1], control_qid_shape=[3, 2]), ) eq.add_equality_group( cirq.ControlledGate(cirq.H, control_values=[1, 0], control_qid_shape=[2, 3]), cirq.ControlledGate(cirq.H, control_values=[0, 1], control_qid_shape=[3, 2]), ) eq.add_equality_group( cirq.ControlledGate(cirq.H, control_values=[1, 0]), cirq.ControlledGate(cirq.H, control_values=[0, 1]), )

def test_text_diagrammable_via_extension(): ext = cirq.Extensions() ext.add_cast(cirq.TextDiagrammable, RestrictedGate, lambda _: cirq.Y**0.5) without_ext = cirq.ControlledGate(RestrictedGate()) with_ext = cirq.ControlledGate(RestrictedGate(), ext) args = cirq.TextDiagramInfoArgs.UNINFORMED_DEFAULT with pytest.raises(TypeError): _ = without_ext.text_diagram_info(args) assert with_ext.text_diagram_info(args) == cirq.TextDiagramInfo( wire_symbols=('@', 'Y'), exponent=0.5)

def test_text_diagram_info(): assert CY.text_diagram_info( cirq.TextDiagramInfoArgs.UNINFORMED_DEFAULT) == cirq.TextDiagramInfo( wire_symbols=('@', 'Y'), exponent=1) assert cirq.ControlledGate(cirq.Y**0.5).text_diagram_info( cirq.TextDiagramInfoArgs.UNINFORMED_DEFAULT) == cirq.TextDiagramInfo( wire_symbols=('@', 'Y'), exponent=0.5) assert cirq.ControlledGate(cirq.S).text_diagram_info( cirq.TextDiagramInfoArgs.UNINFORMED_DEFAULT) == cirq.TextDiagramInfo( wire_symbols=('@', 'S'), exponent=1)

def test_parameterizable(resolve_fn): a = sympy.Symbol('a') cy = cirq.ControlledGate(cirq.Y) cya = cirq.ControlledGate(cirq.YPowGate(exponent=a)) assert cirq.is_parameterized(cya) assert not cirq.is_parameterized(cy) assert resolve_fn(cya, cirq.ParamResolver({'a': 1})) == cy cchan = cirq.ControlledGate( cirq.RandomGateChannel(sub_gate=cirq.PhaseDampingChannel(0.1), probability=a)) with pytest.raises(ValueError, match='Cannot control channel'): resolve_fn(cchan, cirq.ParamResolver({'a': 0.1}))

def test_specialized_control(input_gate, specialized_output): # Single qubit control on the input gate gives the specialized output assert input_gate.controlled() == specialized_output assert input_gate.controlled(num_controls=1) == specialized_output assert input_gate.controlled(control_values=((1,),)) == specialized_output assert input_gate.controlled(control_qid_shape=(2,)) == specialized_output assert np.allclose( cirq.unitary(specialized_output), cirq.unitary(cirq.ControlledGate(input_gate, num_controls=1))) # For multi-qudit controls, if the last control is a qubit with control # value 1, construct the specialized output leaving the rest of the # controls as they are. assert input_gate.controlled().controlled( ) == specialized_output.controlled(num_controls=1) assert input_gate.controlled( num_controls=2) == specialized_output.controlled(num_controls=1) assert input_gate.controlled( control_values=((0,), (0,), (1,))) == specialized_output.controlled( num_controls=2, control_values=((0,), (0,))) assert input_gate.controlled( control_qid_shape=(3, 3, 2)) == specialized_output.controlled( num_controls=2, control_qid_shape=(3, 3)) assert input_gate.controlled(control_qid_shape=(2,)).controlled( control_qid_shape=(3,)).controlled( control_qid_shape=(4,)) == specialized_output.controlled( num_controls=2, control_qid_shape=(3, 4)) # When a control_value 1 qubit is not acting first, results in a regular # ControlledGate on the input gate instance. assert input_gate.controlled(num_controls=1, control_qid_shape=(3,)) == cirq.ControlledGate( input_gate, num_controls=1, control_qid_shape=(3,)) assert input_gate.controlled(control_values=((0,), (1,), (0,))) == cirq.ControlledGate( input_gate, num_controls=3, control_values=((0,), (1,), (0,))) assert input_gate.controlled(control_qid_shape=(3, 2, 3)) == cirq.ControlledGate( input_gate, num_controls=3, control_qid_shape=(3, 2, 3)) assert input_gate.controlled(control_qid_shape=(3,)).controlled( control_qid_shape=(2,)).controlled( control_qid_shape=(4,)) == cirq.ControlledGate( input_gate, num_controls=3, control_qid_shape=(3, 2, 4))