How to use the projectq.ops.Measure 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 Huawei-HiQ / HiQsimulator / examples / grover_mpi.py View on Github external
# 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)

        All(Ph(math.pi / n)) | x

    All(Measure) | x
    Measure | oracle_out

    eng.flush()
    # return result
    return [int(qubit) for qubit in x]
github ProjectQ-Framework / ProjectQ / projectq / backends / _circuits / _to_latex.py View on Github external
add_str = self._x_gate(lines, ctrl_lines)
                # and make the target qubit quantum if one of the controls is
                if not self.is_quantum[lines[0]]:
                    if sum([self.is_quantum[i] for i in ctrl_lines]) > 0:
                        self.is_quantum[lines[0]] = True
            elif gate == Z and len(ctrl_lines) > 0:
                add_str = self._cz_gate(lines + ctrl_lines)
            elif gate == Swap:
                add_str = self._swap_gate(lines, ctrl_lines)
            elif gate == SqrtSwap:
                add_str = self._sqrtswap_gate(lines,
                                              ctrl_lines,
                                              daggered=False)
            elif gate == get_inverse(SqrtSwap):
                add_str = self._sqrtswap_gate(lines, ctrl_lines, daggered=True)
            elif gate == Measure:
                # draw measurement gate
                for l in lines:
                    op = self._op(l)
                    width = self._gate_width(Measure)
                    height = self._gate_height(Measure)
                    shift0 = .07 * height
                    shift1 = .36 * height
                    shift2 = .1 * width
                    add_str += ("\n\\node[measure,edgestyle] ({op}) at ({pos}"
                                ",-{line}) {{}};\n\\draw[edgestyle] ([yshift="
                                "-{shift1}cm,xshift={shift2}cm]{op}.west) to "
                                "[out=60,in=180] ([yshift={shift0}cm]{op}."
                                "center) to [out=0, in=120] ([yshift=-{shift1}"
                                "cm,xshift=-{shift2}cm]{op}.east);\n"
                                "\\draw[edgestyle] ([yshift=-{shift1}cm]{op}."
                                "center) to ([yshift=-{shift2}cm,xshift=-"
github Qiskit / qiskit-terra / qiskit / backends / local / qasm_simulator_projectq.py View on Github external
H | qubit
                elif operation['name'] == 's':
                    qubit = qureg[operation['qubits'][0]]
                    S | qubit
                elif operation['name'] in ['CX', 'cx']:
                    qubit0 = qureg[operation['qubits'][0]]
                    qubit1 = qureg[operation['qubits'][1]]
                    CX | (qubit0, qubit1)
                elif operation['name'] in ['id', 'u0']:
                    pass
                # Check if measure
                elif operation['name'] == 'measure':
                    qubit_index = operation['qubits'][0]
                    qubit = qureg[qubit_index]
                    clbit = operation['clbits'][0]
                    Measure | qubit
                    bit = 1 << clbit
                    self._classical_state = (
                        self._classical_state & (~bit)) | (int(qubit)
                                                           << clbit)
                    # check whether we already measured this qubit
                    if operation['qubits'][0] in unmeasured_qubits:
                        unmeasured_qubits.remove(operation['qubits'][0])
                # Check if reset
                elif operation['name'] == 'reset':
                    qubit = operation['qubits'][0]
                    raise SimulatorError('Reset operation not yet implemented '
                                         'for ProjectQ C++ backend')
                elif operation['name'] == 'barrier':
                    pass
                else:
                    backend = self._configuration['name']
github ProjectQ-Framework / ProjectQ / examples / grover.py View on Github external
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)

    All(Measure) | x
    Measure | oracle_out

    eng.flush()
    # return result
    return [int(qubit) for qubit in x]
github XanaduAI / pennylane / openqml-pq / openqml_pq / projectq.py View on Github external
def _deallocate(self):
        """Deallocate all qubits to make ProjectQ happy

        See also: https://github.com/ProjectQ-Framework/ProjectQ/issues/2

        Drawback: This is probably rather resource intensive.
        """
        if self.eng is not None and self.backend == 'Simulator' or self.backend == 'IBMBackend':
            pq.ops.All(pq.ops.Measure) | self.reg #avoid an unfriendly error message: https://github.com/ProjectQ-Framework/ProjectQ/issues/2
github Huawei-HiQ / HiQsimulator / examples / SymMatrixSolver_mpi.py View on Github external
x=i
        for j in range(n):
            if 2**(n-j-1)>x:
                state[j]=0
            else:
                state[j]=1
                x-=2**(n-j-1)
        # Change the list of states to string format
        StrState=''
        for k in range(n):
            StrState+=str(int(state[k]))
        #print (state)
        #print (StrState)
        Statest[i]=np.real(eng.backend.get_amplitude(
                                        StrState+'1',Qubits))
    Measure | Qubits
    return States0,Statest
github ProjectQ-Framework / ProjectQ / examples / shor.py View on Github external
if measurements[i]:
                R(-math.pi/(1 << (k - i))) | ctrl_qubit
        H | ctrl_qubit

        # and measure
        Measure | ctrl_qubit
        eng.flush()
        measurements[k] = int(ctrl_qubit)
        if measurements[k]:
            X | ctrl_qubit

        if verbose:
            print("\033[95m{}\033[0m".format(measurements[k]), end="")
            sys.stdout.flush()

    All(Measure) | x
    # turn the measured values into a number in [0,1)
    y = sum([(measurements[2 * n - 1 - i]*1. / (1 << (i + 1)))
             for i in range(2 * n)])

    # continued fraction expansion to get denominator (the period?)
    r = Fraction(y).limit_denominator(N-1).denominator

    # return the (potential) period
    return r
github QuTech-Delft / quantuminspire / docs / example_projectq_grover.py View on Github external
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)

    All(Measure) | x
    Measure | oracle_out

    eng.flush()
    # return result
    return [int(qubit) for qubit in x]
github ProjectQ-Framework / ProjectQ / projectq / backends / _sim / _simulator.py View on Github external
def is_available(self, cmd):
        """
        Specialized implementation of is_available: The simulator can deal
        with all arbitrarily-controlled gates which provide a
        gate-matrix (via gate.matrix) and acts on 5 or less qubits (not
        counting the control qubits).

        Args:
            cmd (Command): Command for which to check availability (single-
                qubit gate, arbitrary controls)

        Returns:
            True if it can be simulated and False otherwise.
        """
        if (cmd.gate == Measure or cmd.gate == Allocate or
                cmd.gate == Deallocate or
                isinstance(cmd.gate, BasicMathGate) or
                isinstance(cmd.gate, TimeEvolution)):
            return True
        try:
            m = cmd.gate.matrix
            # Allow up to 5-qubit gates
            if len(m) > 2 ** 5:
                return False
            return True
        except:
            return False
github Huawei-HiQ / HiQsimulator / examples / phase_estimation_mpi.py View on Github external
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))

    print("===========================================================================")
    print("= This is the Phase Estimation algorithm demo")
    print("= The algorithm estimates the phase accurate to {} bits \n" 
          "= with probability of success at least {}".format(n_accuracy, 1 - epsilon))
    print("= Change the accuracy and probability by modifying n_accuracy and epsilon")
    print("= Change the unitary and psi by modifying U.matrix and state")