How to use the projectq.ops.X function in projectq

To help you get started, we’ve selected a few projectq examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github QuTech-Delft / quantuminspire / docs / example_projectq_grover.py View on Github external
Returns:
        solution (list): Solution bit-string.
    """
    x = eng.allocate_qureg(n)

    # start in uniform superposition
    All(H) | x

    # number of iterations we have to run:
    num_it = int(math.pi / 4. * math.sqrt(1 << n))

    # prepare the oracle output qubit (the one that is flipped to indicate the
    # solution. start in state 1/sqrt(2) * (|0> - |1>) s.t. a bit-flip turns
    # into a (-1)-phase.
    oracle_out = eng.allocate_qubit()
    X | oracle_out
    H | oracle_out

    # run num_it iterations
    with Loop(eng, num_it):
        # oracle adds a (-1)-phase to the solution
        oracle(eng, x, oracle_out)

        # reflection across uniform superposition
        with Compute(eng):
            All(H) | x
            All(X) | x

        with Control(eng, x[0:-1]):
            Z | x[-1]

        Uncompute(eng)
github Huawei-HiQ / HiQsimulator / examples / exactgrover_mpi.py View on Github external
All(H) | x

    # number of iterations we have to run:
    num_it = int(math.pi/4.*math.sqrt(1 << n))
    
    #phi is the parameter of modified oracle
    #varphi is the parameter of reflection across uniform superposition
    theta=math.asin(math.sqrt(1/(1 << n)))
    phi=math.acos(-math.cos(2*theta)/(math.sin(2*theta)*math.tan((2*num_it+1)*theta)))
    varphi=math.atan(1/(math.sin(2*theta)*math.sin(phi)*math.tan((2*num_it+1)*theta)))*2

    # prepare the oracle output qubit (the one that is flipped to indicate the
    # solution. start in state 1/sqrt(2) * (|0> - |1>) s.t. a bit-flip turns
    # into a (-1)-phase.
    oracle_out = eng.allocate_qubit()
    X | oracle_out
    H | oracle_out

    # run num_it iterations
    with Loop(eng, num_it):
        # oracle adds a (-1)-phase to the solution
        oracle(eng, x, oracle_out)

        # reflection across uniform superposition
        with Compute(eng):
            All(H) | x
            All(X) | x

        with Control(eng, x[0:-1]):
            Z | x[-1]

        Uncompute(eng)
github Huawei-HiQ / HiQsimulator / examples / BV_algorithm_constant_mpi.py View on Github external
def run_BV_algorithm(eng, n, oracle):
    """
    Args:
        eng (MainEngine): the Main engine on which we run the BV algorithm
        n (int): number of qubits
        oracle (function): oracle used by the BV algorithm
    """
    x = eng.allocate_qureg(n)
    
    # start in uniform superposition
    All(H) | x
    
    oracle_out = eng.allocate_qubit()
    X | oracle_out
    H | oracle_out
    
    oracle(eng, x, oracle_out)
    
    All(H) | x
    
    All(Measure) | x
    Measure | oracle_out

    eng.flush()
    
    return [int(qubit) for qubit in x]
github Huawei-HiQ / HiQsimulator / examples / shor_mpi.py View on Github external
Runs the quantum subroutine of Shor's algorithm for factoring.

    Args:
        eng (MainEngine): Main compiler engine to use.
        N (int): Number to factor.
        a (int): Relative prime to use as a base for a^x mod N.
        verbose (bool): If True, display intermediate measurement results.

    Returns:
        r (float): Potential period of a.
    """
    n = int(math.ceil(math.log(N, 2)))

    x = eng.allocate_qureg(n)

    X | x[0]

    measurements = [0] * (2 * n)  # will hold the 2n measurement results

    ctrl_qubit = eng.allocate_qubit()

    for k in range(2 * n):
        current_a = pow(a, 1 << (2 * n - 1 - k), N)
        # one iteration of 1-qubit QPE
        H | ctrl_qubit
        
        with Control(eng, ctrl_qubit):
            MultiplyByConstantModN(current_a, N) | x

        # perform inverse QFT --> Rotations conditioned on previous outcomes
        for i in range(k):
            if measurements[i]:
github Huawei-HiQ / HiQsimulator / examples / phase_estimation_mpi.py View on Github external
epsilon = 0.1   # the estimation algorithm successs with probability 1 - epsilon 
    n_accuracy = 3  # the estimation algorithm estimates with 3 bits accuracy
    n = _bits_required_to_achieve_accuracy(n_accuracy, epsilon)
    
    ## we create a unitary U = R(cmath.pi*3/4) \ox R(cmath.pi*3/4)
    U = BasicGate() 
    theta = math.pi*3/4
    U.matrix = np.matrix([[1, 0, 0, 0], 
                          [0, cmath.exp(1j*theta), 0, 0], 
                          [0, 0, cmath.exp(1j*theta), 0], 
                          [0, 0, 0, cmath.exp(1j*2*theta)]])

    state = eng.allocate_qureg(m+n)

    # prepare the input state to be |psi>=|01>
    X | state[1]
    
    run_phase_estimation(eng, U, state, m, n)
    
    # we have to post-process the state that stores the estimated phase
    OFFSET = m
    Tensor(Measure) | state[OFFSET:]
    Tensor(Measure) | state[:OFFSET]
    eng.flush()
    
    outcome = "" # used to store the binary string of the estimated phase
    value = 0    # used to store the decimal value of the estimated phase
    for k in range(n_accuracy):
        bit = int(state[OFFSET+n-1-k])
        outcome = outcome + str(bit)
        value = value + bit/(1 << (k+1))
github ProjectQ-Framework / ProjectQ / projectq / backends / _circuits / _to_latex.py View on Github external
def _x_gate(self, lines, ctrl_lines):
        """
        Return the TikZ code for a NOT-gate.

        Args:
            lines (list): List of length 1 denoting the target qubit of
                the NOT / X gate.
            ctrl_lines (list): List of qubit lines which act as controls.

        """
        assert (len(lines) == 1)  # NOT gate only acts on 1 qubit
        line = lines[0]
        delta_pos = self._gate_offset(X)
        gate_width = self._gate_width(X)
        op = self._op(line)
        gate_str = ("\n\\node[xstyle] ({op}) at ({pos},-{line}) {{}};\n\\draw"
                    "[edgestyle] ({op}.north)--({op}.south);\n\\draw"
                    "[edgestyle] ({op}.west)--({op}.east);").format(
                        op=op, line=line, pos=self.pos[line])

        if len(ctrl_lines) > 0:
            for ctrl in ctrl_lines:
                gate_str += self._phase(ctrl, self.pos[line])
                gate_str += self._line(ctrl, line)

        all_lines = ctrl_lines + [line]
        new_pos = self.pos[line] + delta_pos + gate_width
        for i in all_lines:
            self.op_count[i] += 1
        for i in range(min(all_lines), max(all_lines) + 1):
github QuantumBFS / Yao.jl / benchmark / projectq / bench.py View on Github external
def xyz(self):
        tl = []
        for nsite, num_bench in zip(NL, [1000, 1000, 1000, 100, 10, 5]):
            print('========== N: %d ============'%nsite)
            for func in [bG(ops.X), bG(ops.Y), bG(ops.Z)]:
                tl.append(qbenchmark(func, nsite, num_bench)*1e6)
        np.savetxt('xyz-report.dat', tl)
github GiggleLiu / QAOA / qaoa / qcircuit.py View on Github external
def _refresh(self):
        qureg = self.qureg
        ops.Measure | qureg
        for z, q in zip(self.z0, qureg):
            if int(q) != z:
                ops.X | q
        qureg.engine.flush()
        ops.Measure | qureg
github XanaduAI / pennylane / openqml-pq / openqml_pq / projectq.py View on Github external
Rx = Gate('Rx', 1, 1, pq.ops.Rx) #(angle) RotationX gate class
Ry = Gate('Ry', 1, 1, pq.ops.Ry) #(angle) RotationY gate class
Rz = Gate('Rz', 1, 1, pq.ops.Rz) #(angle) RotationZ gate class
R = Gate('R', 1, 1, pq.ops.R) #(angle) Phase-shift gate (equivalent to Rz up to a global phase)
#pq.ops.AllGate , which is the same as pq.ops.Tensor, is a meta gate that acts on all qubits
#pq.ops.QFTGate #This gate acts on all qubits
#pq.ops.QubitOperator #A sum of terms acting on qubits, e.g., 0.5 * ‘X0 X5’ + 0.3 * ‘Z1 Z2’
CRz = Gate('CRz', 2, 1, pq.ops.CRz) #(angle) Shortcut for C(Rz(angle), n=1).
CNOT = Gate('CNOT', 2, 0, CNOTClass)
CZ = Gate('CZ', 2, 0, CZClass)
#Toffoli = Gate('Toffoli', 3, 0, ToffoliClass)
#pq.ops.TimeEvolution #Gate for time evolution under a Hamiltonian (QubitOperator object).
AllZ = Gate('AllZ', 1, 0, AllZClass) #todo: 1 should be replaced by a way to specify "all"

# measurements
MeasureX = Observable('X', 1, 0, pq.ops.X)
MeasureY = Observable('Y', 1, 0, pq.ops.Y)
MeasureZ = Observable('Z', 1, 0, pq.ops.Z)
MeasureAllZ = Observable('AllZ', 1, 0, AllZClass) #todo: 1 should be replaced by a way to specify "all"


classical_demo = [
    Command(X,  [0], []),
    Command(Swap, [0, 1], []),
]

demo = [
    Command(Rx,  [0], [ParRef(0)]),
    Command(Rx,  [1], [ParRef(1)]),
    Command(CNOT, [0, 1], []),
]