def test_basis_change(simulator):
    for angle in list(uniform(0, 2 * pi, 5)):
        EX = simulate(ExpectationValue(U=gates.Rx(target=0, angle=angle), H=PX(0)), backend=simulator)
        EY = simulate(ExpectationValue(U=gates.Rx(target=0, angle=angle), H=PY(0)), backend=simulator)
        EZ = simulate(ExpectationValue(U=gates.Rx(target=0, angle=angle), H=PZ(0)), backend=simulator)

        EXX = simulate(ExpectationValue(U=gates.Rx(target=0, angle=angle) + change_basis(target=0, axis=0),
                                   H=PZ(0)), backend=simulator)
        EYY = simulate(ExpectationValue(U=gates.Rx(target=0, angle=angle) + change_basis(target=0, axis=1),
                                   H=PZ(0)), backend=simulator)
        EZZ = simulate(ExpectationValue(U=gates.Rx(target=0, angle=angle) + change_basis(target=0, axis=2),
                                   H=PZ(0)), backend=simulator)

        assert (isclose(EX, EXX, atol=1.e-4))
        assert (isclose(EY, EYY, atol=1.e-4))
        assert (isclose(EZ, EZZ, atol=1.e-4))

    for i, gate in enumerate([gates.Rx, gates.Ry, gates.Rz]):
        angle = uniform(0, 2 * pi)
        U1 = gate(target=0, angle=angle)
        U2 = change_basis(target=0, axis=i) + gates.Rz(target=0, angle=angle) + change_basis(target=0, axis=i,
                                                                                             daggered=True)
        wfn1 = simulate(U1, backend=simulator)
        wfn2 = simulate(U2, backend=simulator)
        assert (isclose(numpy.abs(wfn1.inner(wfn2)) ** 2, 1.0, atol=1.e-4))

        if simulator == "qiskit":
            return # initial state not yet supported
        wfn1 = simulate(U1, initial_state=1, backend=simulator)
        wfn2 = simulate(U2, initial_state=1, backend=simulator)
        assert (isclose(numpy.abs(wfn1.inner(wfn2)) ** 2, 1.0, atol=1.e-4))
示例#2
0
def test_convert_to_from_pyzx_optimizing_circuit(tequila_circuit, t_reduce):

    pyzx_circuit = convert_to_pyzx(tequila_circuit)

    pyzx_graph = pyzx_circuit.to_graph()

    if t_reduce:
        pyzx.teleport_reduce(pyzx_graph)
        pyzx_circuit_opt = pyzx.Circuit.from_graph(pyzx_graph)
    else:
        pyzx.full_reduce(pyzx_graph)
        pyzx_graph.normalize()
        pyzx_circuit_opt = pyzx.extract_circuit(pyzx_graph.copy())

    # compare_tensors returns True if pyzx_circuit and pyzx_circuit_opt
    # implement the same circuit (up to global phase)
    assert (pyzx.compare_tensors(pyzx_circuit, pyzx_circuit_opt))

    # verify_equality return True if full_reduce() is able to reduce the
    # composition of the circuits to the identity
    assert (pyzx_circuit.verify_equality(pyzx_circuit_opt))

    converted_circuit = convert_from_pyzx(pyzx_circuit_opt)

    wfn1 = simulate(tequila_circuit, backend="symbolic")
    wfn2 = simulate(converted_circuit, backend="symbolic")

    assert (numpy.isclose(wfn1.inner(wfn2), 1.0))
示例#3
0
def test_mixed_power(
    simulator,
    value1=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0)),
    value2=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0))):
    angle1 = Variable(name="angle1")
    angle2 = Variable(name="angle2")
    variables = {angle1: value1, angle2: value2}
    qubit = 0
    control = 1
    H1 = paulis.X(qubit=qubit)
    U1 = gates.X(target=control) + gates.Ry(
        target=qubit, control=control, angle=angle1)
    e1 = ExpectationValue(U=U1, H=H1)
    H2 = paulis.Y(qubit=qubit)
    U2 = gates.X(target=control) + gates.Rx(
        target=qubit, control=control, angle=angle2)
    e2 = ExpectationValue(U=U2, H=H2)
    added = e1**e2
    val = simulate(added, variables=variables, backend=simulator)
    en1 = simulate(e1, variables=variables, backend=simulator)
    en2 = simulate(e2, variables=variables, backend=simulator)
    an1 = np.sin(angle1(variables=variables))
    an2 = -np.sin(angle2(variables=variables))
    assert np.isclose(val, en1**en2, atol=1.e-4)
    assert np.isclose(val, an1**an2, atol=1.e-4)
示例#4
0
def test_gradient_UX_HY_wfnsim(simulator, angle, controlled, silent=True):
    # same as before just with wavefunction simulation

    # case YX
    # U = cos(angle/2) + sin(-angle/2)*i*X
    # O = cos*sin*i*<0|YX|0> + sin*cos*(-i)<0|XY|0>
    #   = 0.5*sin(-angle)*i <0|[YX,XY]|0>
    #   = -sin(angle)

    angle_value = angle
    angle = Variable(name="angle")
    variables = {angle: angle_value}

    qubit = 0
    H = paulis.Y(qubit=qubit)
    if controlled:
        control = 1
        U = gates.X(target=control) + gates.Rx(
            target=qubit, control=control, angle=angle)
    else:
        U = gates.Rx(target=qubit, angle=angle)
    O = ExpectationValue(U=U, H=H)
    E = simulate(O, variables=variables, backend=simulator)
    dO = grad(objective=O, variable=angle)
    dE = simulate(dO, variables=variables)
    assert (numpy.isclose(E, -numpy.sin(angle(variables)), atol=0.0001))
    assert (numpy.isclose(dE, -numpy.cos(angle(variables)), atol=0.0001))
    if not silent:
        print("E         =", E)
        print("-sin(angle)=", -numpy.sin(angle(variables)))
        print("dE        =", dE)
        print("-cos(angle)=", -numpy.cos(angle(variables)))
示例#5
0
def test_endianness_simulators():
    tests = ["000111",
             "111000",
             "101010",
             "010101",
             "10010010001",
             "111100101000010"]

    for string in tests:
        binary = BitString.from_binary(binary=string)
        c = QCircuit()
        for i, v in enumerate(binary):
            if v == 1:
                c += gates.X(target=i)
            if v == 0:
                c += gates.Z(target=i)

        wfn_cirq = simulate(c, initial_state=0, backend="cirq")
        counts_cirq = simulate(c, samples=1, backend="cirq")
        counts_qiskit = simulate(c, samples=1, backend="qiskit")
        print("counts_cirq  =", type(counts_cirq))
        print("counts_qiskit=", type(counts_qiskit))
        print("counts_cirq  =", counts_cirq)
        print("counts_qiskit=", counts_qiskit)
        assert (counts_cirq.isclose(counts_qiskit))
        assert (wfn_cirq.state == counts_cirq.state)
示例#6
0
def test_akward_expression(
    simulator,
    value1=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0)),
    value2=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0))):
    angle1 = Variable(name="angle1")
    angle2 = Variable(name="angle2")
    variables = {angle1: value1, angle2: value2}

    prod = angle1 * angle2
    qubit = 0
    control = None
    H = paulis.Y(qubit=qubit)
    U = gates.Rx(target=qubit, control=control, angle=prod)
    Up = gates.Rx(target=qubit, control=control, angle=prod + np.pi / 2)
    Down = gates.Rx(target=qubit, control=control, angle=prod - np.pi / 2)
    e1 = ExpectationValue(U=U, H=H)
    en1 = simulate(e1, variables=variables, backend=simulator)
    uen = simulate(0.5 * ExpectationValue(Up, H),
                   variables=variables,
                   backend=simulator)
    den = simulate(-0.5 * ExpectationValue(Down, H),
                   variables=variables,
                   backend=simulator)
    an1 = -np.sin(prod(variables=variables))
    anval = prod(variables=variables)
    an2 = angle2(variables=variables)
    added = angle1 * e1
    dO = grad(added, 'angle1')
    dE = grad(e1, 'angle1')
    deval = simulate(dE, variables=variables, backend=simulator)
    doval = simulate(dO, variables=variables, backend=simulator)
    dtrue = angle1(variables=variables) * deval + en1
    assert np.isclose(en1, an1)
    assert np.isclose(deval, an2 * (uen + den), atol=1.e-4)
    assert np.isclose(doval, dtrue, atol=1.e-4)
示例#7
0
def test_import_qasm_with_custom_gates():

    openqasmcode = "OPENQASM 2.0;\n" \
                   "include \"qelib1.inc\";\n" \
                   "gate mycustom a,b,c\n" \
                   "{\n" \
                   "cx c,b;\n" \
                   "cx c,a;\n" \
                   "}\n" \
                   "qreg q1[3];\n" \
                   "qreg q2[4];\n" \
                   "creg c[3];\n" \
                   "y q1[1];\n" \
                   "z q2[2];\n" \
                   "mycustom q1[0],q2[0],q1[2];\n" \
                   "h q2[1];\n" \
                   "mycustom q2[3],q1[1],q2[2];\n" \
                   "y q2[1];\n"

    imported_circuit = import_open_qasm(qasm_code=openqasmcode)

    # openqasm   -> tequila qbits
    # qreg q1[3] -> 0, 1, 2
    # qreg q2[4] -> 3, 4, 5, 6

    tequila_circuit = Y(target=1) + Z(target=5) + \
                      CX(target=3, control=2) + CX(target=3, control=0) + \
                      H(target=4) + \
                      CX(target=1, control=5) + CX(target=6, control=5) + \
                      Y(target=4)

    wfn1 = simulate(tequila_circuit, backend="symbolic")
    wfn2 = simulate(imported_circuit, backend="symbolic")

    assert (numpy.isclose(wfn1.inner(wfn2), 1.0))
示例#8
0
def test_gradient_deep_H(simulator, power, controls):
    if controls > 2 and simulator == "qiskit":
        # does not work yet
        return
    qubit = 0
    angle = Variable(name="angle")
    variables = {angle: power}
    control = [i for i in range(1, controls + 1)]
    H = paulis.X(qubit=qubit)

    U = gates.X(target=control) + gates.H(
        target=qubit, control=control, power=angle)

    O = ExpectationValue(U=U, H=H)
    E = simulate(O, variables=variables, backend=simulator)
    assert (numpy.isclose(E,
                          -numpy.cos(angle(variables) * (numpy.pi)) / 2 + 0.5,
                          atol=1.e-4))
    dO = grad(objective=O, variable=angle)
    dE = simulate(dO, variables=variables, backend=simulator)

    assert (numpy.isclose(dE,
                          numpy.pi * numpy.sin(angle(variables) * (numpy.pi)) /
                          2,
                          atol=1.e-4))
示例#9
0
def test_export_import_qasm_trotterized_gate(zx_calculus, string1, string2,
                                             angles, steps):

    variables = {
        "ang1": angles[0]
    } if string2 is None else {
        "ang1": angles[0],
        "ang2": angles[1]
    }

    g1 = QubitHamiltonian.from_string(string1)
    g2 = None if string2 is None else QubitHamiltonian.from_string(string2)
    tequila_circuit = Trotterized(
        generators=[g1] if string2 is None else [g1, g2],
        angles=["ang1"] if string2 is None else ["ang1", "ang2"],
        steps=steps)

    qasm_code = export_open_qasm(tequila_circuit,
                                 variables=variables,
                                 zx_calculus=zx_calculus)
    imported_circuit = import_open_qasm(qasm_code=qasm_code)

    wfn1 = simulate(tequila_circuit, backend="symbolic", variables=variables)
    wfn2 = simulate(imported_circuit, backend="symbolic")

    assert (numpy.isclose(wfn1.inner(wfn2), 1.0))
示例#10
0
def test_endianness_simulators():
    tests = [
        "000111", "111000", "101010", "010101", "10010010001",
        "111100101000010"
    ]

    for string in tests:
        number = int(string, 2)
        binary = BitString.from_binary(binary=string)
        c = QCircuit()
        for i, v in enumerate(binary):
            if v == 1:
                c += gates.X(target=i)

        c += gates.Measurement(target=[x for x in range(len(string))])

        wfn_cirq = simulate(c, initial_state=0, backend="cirq")
        counts_cirq = simulate(c, samples=1, backend="cirq")
        counts_qiskit = simulate(c, samples=1, backend="qiskit")
        print("counts_cirq  =", type(counts_cirq))
        print("counts_qiskit=", type(counts_qiskit))
        print("counts_cirq  =", counts_cirq)
        print("counts_qiskit=", counts_qiskit)
        assert (counts_cirq == counts_qiskit)
        assert (wfn_cirq.state == counts_cirq.state)
示例#11
0
def test_gradient_H(simulator, power, controlled):
    qubit = 0
    control = 1
    angle = Variable(name="angle")
    variables = {angle: power}

    H = paulis.X(qubit=qubit)
    if not controlled:
        U = gates.H(target=qubit, power=angle)
    else:
        U = gates.X(target=control) + gates.H(
            target=qubit, control=control, power=angle)

    O = ExpectationValue(U=U, H=H)
    E = simulate(O, variables=variables, backend=simulator)
    assert (numpy.isclose(E,
                          -numpy.cos(angle(variables) * (numpy.pi)) / 2 + 0.5,
                          atol=1.e-4))
    dO = grad(objective=O, variable=angle)
    dE = simulate(dO, variables=variables, backend=simulator)

    assert (numpy.isclose(dE,
                          numpy.pi * numpy.sin(angle(variables) * (numpy.pi)) /
                          2,
                          atol=1.e-4))
示例#12
0
def test_gradient_UY_HX(simulator, angle_value, controlled, silent=True):
    # case X Y
    # U = cos(angle/2) + sin(-angle/2)*i*Y
    # <0|Ud H U |0> = cos^2(angle/2)*<0|X|0>
    # + sin^2(-angle/2) <0|YXY|0>
    # + cos(angle/2)*sin(angle/2)*i<0|XY|0>
    # + sin(-angle/2)*cos(angle/2)*(-i) <0|YX|0>
    # = cos^2*0 + sin^2*0 + cos*sin*i(<0|[XY,YX]|0>)
    # = 0.5*sin(-angle)*i <0|[XY,YX]|0> = -0.5*sin(angle)*i * 2 i <0|Z|0>
    # = sin(angle)

    angle = Variable(name="angle")
    variables = {angle: angle_value}

    qubit = 0
    H = paulis.X(qubit=qubit)
    if controlled:
        control = 1
        U = gates.X(target=control) + gates.Ry(
            target=qubit, control=control, angle=angle)
    else:
        U = gates.X(target=qubit) + gates.X(target=qubit) + gates.Ry(
            target=qubit, angle=angle)
    O = ExpectationValue(U=U, H=H)
    E = simulate(O, variables=variables, backend=simulator)
    print("O={type}".format(type=type(O)))
    dO = grad(objective=O, variable=angle)
    dE = simulate(dO, variables=variables, backend=simulator)
    assert (numpy.isclose(E, numpy.sin(angle(variables)), atol=1.e-4))
    assert (numpy.isclose(dE, numpy.cos(angle(variables)), atol=1.e-4))
    if not silent:
        print("E         =", E)
        print("sin(angle)=", numpy.sin(angle()))
        print("dE        =", dE)
        print("cos(angle)=", numpy.cos(angle()))
示例#13
0
def test_gradient_PHASE_HY(simulator, angle_value, controlled, silent=False):
    angle = Variable(name="angle")
    variables = {angle: angle_value}

    qubit = 0
    H = paulis.Y(qubit=qubit)
    if controlled:
        control = 1
        U = gates.X(target=control) + gates.H(target=qubit) + gates.Phase(
            target=qubit, control=control, phi=angle) + gates.H(target=qubit)
    else:
        U = gates.H(target=qubit) + gates.Phase(
            target=qubit, phi=angle) + gates.H(target=qubit)

    O = ExpectationValue(U=U, H=H)
    E = simulate(O, variables=variables, backend=simulator)
    dO = grad(objective=O, variable='angle')
    dE = simulate(dO, variables=variables)
    assert (numpy.isclose(E, -numpy.sin(angle(variables)), atol=1.e-4))
    assert (numpy.isclose(dE, -numpy.cos(angle(variables)), atol=1.e-4))
    if not silent:
        print("E         =", E)
        print("-sin(angle)=", -numpy.sin(angle(variables)))
        print("dE        =", dE)
        print("-cos(angle)=", -numpy.cos(angle(variables)))
示例#14
0
def test_convert_to_from_pyzx_simple(tequila_circuit):

    pyzx_circuit = convert_to_pyzx(tequila_circuit)
    converted_circuit = convert_from_pyzx(pyzx_circuit)

    wfn1 = simulate(tequila_circuit, backend="symbolic")
    wfn2 = simulate(converted_circuit, backend="symbolic")

    assert (numpy.isclose(wfn1.inner(wfn2), 1.0))
def test_exponential_pauli_wfn(simulator, angle, axis, control):
    U1 = gates.RotationGate(axis=axis, angle=angle, target=0, control=control)
    U2 = gates.ExpPauli(paulistring=axis + "(0)", angle=angle, control=control)

    wfn1 = simulate(U1, backend=simulator)
    wfn2 = simulate(U2, backend=simulator)
    wfn3 = simulate(U2, backend=None)

    assert (isclose(numpy.abs(wfn1.inner(wfn2))**2, 1.0, atol=1.e-4))
    assert (isclose(numpy.abs(wfn2.inner(wfn3))**2, 1.0, atol=1.e-4))
示例#16
0
def test_controls(target, control, gate):
    c0 = gates.X(target=control) + gate(target=target, control=None)
    c1 = gates.X(target=control) + gate(target=target, control=control)
    wfn0 = simulate(c0, initial_state=0, backend="symbolic")
    wfn1 = simulate(c1, initial_state=0, backend="symbolic")
    assert (wfn0.isclose(wfn1))

    c0 = gates.QCircuit()
    c1 = gate(target=target, control=control)
    wfn0 = simulate(c0, initial_state=0)
    wfn1 = simulate(c1, initial_state=0)
    assert (wfn0.isclose(wfn1))
def test_controlled_rotations(simulator):
    angles = uniform(0, 2 * pi, 5)
    gs = [gates.Rx, gates.Ry, gates.Rz]
    for angle in angles:
        for gate in gs:
            qubit = randint(0, 1)
            control = randint(2, 3)
            U = gates.X(target=control) + gate(target=qubit, control=control, angle=angle)
            RCU = compile_controlled_rotation(gate=U)
            wfn1 = simulate(U, initial_state=0, backend=simulator)
            wfn2 = simulate(RCU, initial_state=0, backend=simulator)
            assert (isclose(numpy.abs(wfn1.inner(wfn2)) ** 2, 1.0, atol=1.e-4))
示例#18
0
def test_export_import_qasm_h_ch_gate(zx_calculus, target1, control1, target2,
                                      control2):

    tequila_circuit = H(target=target1, control=control1) + H(target=target2,
                                                              control=control2)

    qasm_code = export_open_qasm(tequila_circuit, zx_calculus=zx_calculus)
    imported_circuit = import_open_qasm(qasm_code=qasm_code)

    wfn1 = simulate(tequila_circuit, backend="symbolic")
    wfn2 = simulate(imported_circuit, backend="symbolic")

    assert (numpy.isclose(wfn1.inner(wfn2), 1.0))
示例#19
0
def test_l_addition(simulator, value=(numpy.random.randint(0, 1000) / 1000.0 * (numpy.pi / 2.0))):
    angle1 = Variable(name="angle1")
    variables = {angle1: value}
    qubit = 0
    control = 1
    H1 = paulis.X(qubit=qubit)
    U1 = gates.X(target=control) + gates.Ry(target=qubit, control=control, angle=angle1)
    e1 = ExpectationValue(U=U1, H=H1)
    added = e1 + 1
    val = simulate(added, variables=variables, backend=simulator)
    en1 = simulate(e1, variables=variables, backend=simulator) + 1.
    an1 = np.sin(angle1(variables=variables)) + 1.
    assert np.isclose(val, en1, atol=1.e-4)
    assert np.isclose(val, an1, atol=1.e-4)
示例#20
0
def test_r_power(simulator, value=numpy.random.uniform(0.1, 1.9*numpy.pi, 1)[0]):
    angle1 = Variable(name="angle1")
    variables = {angle1: value}
    qubit = 0
    control = 1
    H1 = paulis.X(qubit=qubit)
    U1 = gates.X(target=control) + gates.Ry(target=qubit, control=control, angle=angle1)
    e1 = ExpectationValue(U=U1, H=H1)
    added = 2 ** e1
    val = simulate(added, variables=variables, backend=simulator)
    en1 = 2 ** simulate(e1, variables=variables, backend=simulator)
    an1 = 2. ** np.sin(angle1(variables=variables))
    assert np.isclose(val, en1, atol=1.e-4)
    assert np.isclose(val, an1, atol=1.e-4)
示例#21
0
def test_l_division(simulator, value=numpy.random.uniform(0.0, 2.0*numpy.pi, 1)[0]):
    angle1 = Variable(name="angle1")
    variables = {angle1: value}
    qubit = 0
    control = 1
    H1 = paulis.X(qubit=qubit)
    U1 = gates.X(target=control) + gates.Ry(target=qubit, control=control, angle=angle1)
    e1 = ExpectationValue(U=U1, H=H1)
    added = e1 / 2
    val = simulate(added, variables=variables, backend=simulator)
    en1 = simulate(e1, variables=variables, backend=simulator) / 2
    an1 = np.sin(value) / 2.
    assert np.isclose(val, en1, atol=1.e-4)
    assert np.isclose(val, an1, atol=1.e-4)
示例#22
0
    def fill_grads_values(self, grads_values, var, variables, objectives_grad):
        """
        Inserts into "grads_values" the gradient values per objective in objectives_grad[var], where var is the name
        of the variable.

        Parameters
        ----------
        grads_values
            List in which we insert the gradient values (No returns)
        var
            Variable over which we are calculating the gradient values
        variables
            Dict mapping all variables to their current values
        objectives_grad
            List of ExpectationValueImpls that will be simulated to calculate the gradient value of a given variable
        """
        var_results = []
        grads_wrt_var = objectives_grad[var]
        if not isinstance(grads_wrt_var, List):
            grads_wrt_var = [grads_wrt_var]
        for obj in grads_wrt_var:
            var_results.append(
                simulate(objective=obj,
                         variables=variables,
                         backend=self.compile_args["backend"],
                         samples=self.samples))
        grads_values.append(var_results)
示例#23
0
def test_total_type_jumble(simulator,value1=(numpy.random.randint(10, 1000) / 1000.0 * (numpy.pi / 2.0)),
                value2=(numpy.random.randint(10, 1000) / 1000.0 * (numpy.pi / 2.0))):
    a = Variable('a')
    b = Variable('b')
    values = {a: value1, b: value2}
    H1 = tq.paulis.X(0)
    H2 = tq.paulis.Y(0)
    U1= tq.gates.Ry(angle=a,target=0)
    U2= tq.gates.Rx(angle=b,target=0)
    e1=ExpectationValue(U1,H1)
    e2=ExpectationValue(U2,H2)
    stacked= tq.objective.vectorize([e1, e2])
    stacked = stacked*a*e2
    out=simulate(stacked,variables=values,backend=simulator)
    v1=out[0]
    v2=out[1]
    appendage =  a(values) * -np.sin(b(values))
    an1= np.sin(a(values)) *  appendage
    an2= -np.sin(b(values)) * appendage
    assert np.isclose(v1+v2,an1+an2)
    # not gonna contract, lets make gradient do some real work
    ga=grad(stacked,a)
    gb=grad(stacked,b)
    la=[tq.simulate(x,variables=values) for x in ga]
    print(la)
    lb=[tq.simulate(x,variables=values) for x in gb]
    print(lb)
    tota=np.sum(np.array(la))
    totb=np.sum(np.array(lb))
    gan1= np.cos(a(values)) * appendage + (np.sin(a(values)) * -np.sin(b(values))) - (np.sin(b(values)) * -np.sin(b(values)))
    gan2= np.sin(a(values)) * a(values) * -np.cos(b(values)) + 2 * (-np.cos(b(values)) * appendage)
    assert np.isclose(tota+totb,gan1+gan2)
示例#24
0
def test_paulistring_sampling(backend, case):
    print(case)
    H = QubitHamiltonian.from_paulistrings(PauliString.from_string(case[0]))
    U = gates.X(target=1) + gates.X(target=3) + gates.X(target=5)
    E = ExpectationValue(H=H, U=U)
    result = simulate(E,backend=backend, samples=1)
    assert isclose(result, case[1], 1.e-4)
示例#25
0
def test_hadamard(qubit, init):
    gate = gates.H(target=qubit)
    iwfn = QubitWaveFunction.from_int(i=init, n_qubits=qubit + 1)
    wfn = simulate(gate, initial_state=init)
    test = 1.0 / numpy.sqrt(2) * (iwfn.apply_qubitoperator(paulis.Z(qubit)) +
                                  iwfn.apply_qubitoperator(paulis.X(qubit)))
    assert (wfn.isclose(test))
示例#26
0
def test_compilation(backend):
    U = gates.X(target=[0, 1, 2, 3, 4, 5])
    for i in range(10):
        U += gates.Ry(angle=(i, ), target=numpy.random.randint(0, 5, 1)[0])
    U += gates.CZ(0, 1) + gates.CNOT(1, 2) + gates.CZ(2, 3) + gates.CNOT(
        3, 4) + gates.CZ(5, 6)
    H = paulis.X(0) + paulis.X(1) + paulis.X(2) + paulis.X(3) + paulis.X(
        4) + paulis.X(5)
    H += paulis.Z(0) + paulis.Z(1) + paulis.Z(2) + paulis.Z(3) + paulis.Z(
        4) + paulis.Z(5)
    E = ExpectationValue(H=H, U=U)

    randvals = numpy.random.uniform(0.0, 2.0, 10)
    variables = {(i, ): randvals[i] for i in range(10)}
    e0 = simulate(E, variables=variables, backend=backend)

    E2 = E * E
    for i in range(99):
        E2 += E * E

    compiled = tq.compile(E2, variables=variables, backend=backend)
    e2 = compiled(variables=variables)
    assert (E2.count_expectationvalues(unique=True) == 1)
    assert (compiled.count_expectationvalues(unique=True) == 1)
    assert numpy.isclose(100 * e0**2, e2)
示例#27
0
def test_basic_gates():
    I = sympy.I
    cos = sympy.cos
    sin = sympy.sin
    exp = sympy.exp
    BS = QubitWaveFunction.from_int
    angle = sympy.pi
    gates = [
        X(0),
        Y(0),
        Z(0),
        Rx(target=0, angle=angle),
        Ry(target=0, angle=angle),
        Rz(target=0, angle=angle),
        H(0)
    ]
    results = [
        BS(1), I * BS(1),
        BS(0),
        cos(-angle / 2) * BS(0) + I * sin(-angle / 2) * BS(1),
        cos(-angle / 2) * BS(0) + I * sin(-angle / 2) * I * BS(1),
        exp(-I * angle / 2) * BS(0), 1 / sympy.sqrt(2) * (BS(0) + BS(1))
    ]
    for i, g in enumerate(gates):
        wfn = simulate(g, backend="symbolic", variables={angle: sympy.pi})
        assert (wfn == strip_sympy_zeros(results[i]))
示例#28
0
def test_unitary_gate_u1(gate, angle):
    """
    Test some equivalences for u1 gate
    """
    c_u1 = u1(lambd=angle,
              target=gate.gates[0].target,
              control=None
              if len(gate.gates[0].control) == 0 else gate.gates[0].control)

    if len(gate.gates[0].control) > 0:
        c_u1 = X(target=gate.gates[0].control) + c_u1
        gate = X(target=gate.gates[0].control) + gate

    wfn1 = simulate(c_u1, backend="symbolic")
    wfn2 = simulate(gate, backend="symbolic")

    assert (numpy.isclose(wfn1.inner(wfn2), 1.0))
示例#29
0
def test_heterogeneous_operations_l(simulator, op, value1=(numpy.random.randint(1, 1000) / 1000.0 * (numpy.pi / 2.0)),
                                    value2=(numpy.random.randint(1, 1000) / 1000.0 * (numpy.pi / 2.0))):
    angle1 = Variable(name="angle1")
    angle2 = Variable(name="angle2")
    variables = {angle1: value1, angle2: value2}
    qubit = 0
    control = 1
    H2 = paulis.X(qubit=qubit)
    U2 = gates.X(target=control) + gates.Ry(target=qubit, control=control, angle=angle2)
    e2 = ExpectationValue(U=U2, H=H2)
    added = Objective(args=[angle1, e2.args[0]], transformation=op)
    val = simulate(added, variables=variables, backend=simulator)
    en2 = simulate(e2, variables=variables, backend=simulator)
    an1 = angle1(variables=variables)
    an2 = np.sin(angle2(variables=variables))
    assert np.isclose(val, float(op(an1, en2)), atol=1.e-4)
    assert np.isclose(en2, an2, atol=1.e-4)
示例#30
0
def test_heterogeneous_operations_r(simulator, op, value1=(numpy.random.randint(1, 999) / 1000.0 * (numpy.pi / 2.0)),
                                    value2=(numpy.random.randint(1, 999) / 1000.0 * (numpy.pi / 2.0))):
    angle1 = Variable(name="angle1")
    angle2 = Variable(name="angle2")
    variables = {angle1: value1, angle2: value2}
    qubit = 0
    control = 1
    H1 = paulis.Y(qubit=qubit)
    U1 = gates.X(target=control) + gates.Rx(target=qubit, control=control, angle=angle1)
    e1 = ExpectationValue(U=U1, H=H1)
    added = Objective(args=[e1.args[0], angle2], transformation=op)
    val = simulate(added, variables=variables, backend=simulator)
    en1 = simulate(e1, variables=variables, backend=simulator)
    an1 = -np.sin(angle1(variables=variables))
    an2 = angle2(variables=variables)
    assert np.isclose(val, float(op(en1, an2)), atol=1.e-4)
    assert np.isclose(en1, an1, atol=1.e-4)