Esempio n. 1
0
def test_measurement(tmpdir):

    filename = os.path.join(str(tmpdir), 'CQC_File')

    with CQCToFile(file=filename) as cqc:

        q = qubit(cqc)
        a = q.measure()
        assert a == 0
Esempio n. 2
0
def commands_to_apply_mix_with_factory(cqc):
    qbit = qubit(cqc)

    with CQCMix(cqc) as pgrm:
        qbit.X()

        with pgrm.loop(times=3):
            qbit.H()

        qbit.Y()
Esempio n. 3
0
def compute(name: str, instructions: List[BaseInstruction], conn):
    from cqc.pythonLib import CQCConnection, qubit

    # Initialize the connection
    with CQCConnection(name) as connection:
        qubits = {}

        for inst in instructions:
            if isinstance(inst, SingeQubitInstruction):
                if inst.qubit not in qubits:
                    qubits[inst.qubit] = qubit(connection)
                inst.apply(qubits.get(inst.qubit))

            if isinstance(inst, CNOTInstruction):
                if inst.control_connection_name == inst.target_connection_name:
                    if inst.control not in qubits:
                        qubits[inst.control] = qubit(connection)
                    if inst.target not in qubits:
                        qubits[inst.target] = qubit(connection)

                    inst.apply(qubits.get(inst.control),
                               qubits.get(inst.target))
                else:
                    if inst.control_connection_name == connection.name:
                        if inst.control not in qubits:
                            qubits[inst.control] = qubit(connection)
                        inst.apply_on_control(connection,
                                              inst.target_connection_name,
                                              qubits.get(inst.control))
                    else:
                        if inst.target not in qubits:
                            qubits[inst.target] = qubit(connection)
                        inst.apply_on_target(connection,
                                             inst.control_connection_name,
                                             qubits.get(inst.target))

        results = [q.measure() for q in qubits.values()]
        conn.send(results)
        conn.close()

        print(f"Results for {name}", results)

        return results
Esempio n. 4
0
def prepareQubit(name, alpha, c, y, noise):
    q = qubit(name)
    if c == 0:
        q.rot_Y(round((256 / math.pi) * math.acos(math.sqrt(y))))
        q.rot_Z(128 * alpha)
    elif c == 1:
        q.rot_Y(round((256 / math.pi) * math.acos(math.sqrt(1 - y))))
        q.rot_Z(128 * ((alpha + 1) % 2))
    q = addNoise(q, noise)
    return q
Esempio n. 5
0
def main():

    # Initialize the connection
    with CQCConnection("Alice") as Alice:    # Here 1)we connect a node (ALice)
        q = qubit(Alice)                          # 2)produced a fresh qubit
        q.H()                                   # 3)applied Hadamard gate
        coin = q.measure()                        # 4)mesaured the qubit and the result printed
        to_print = "{}".format(coin)         
        print("| " + to_print + " |")
        return coin
Esempio n. 6
0
def encode_standard(connection, number, length):
    encoded = [None] * length
    num_vector = BitVector(intVal=number, size=length)

    for i in range(length):
        encoded[i] = qubit(connection)
        if num_vector[i] != 0:
            encoded[i].X()  # Apply not gate

    return encoded
Esempio n. 7
0
    def create_qubit(self, host_id):
        """
        Creates a new Qubit of the type of the backend.

        Args:
            host_id (String): Id of the host to whom the qubit belongs.

        Returns:
            Qubit of backend type.
        """
        return cqc.qubit(self._cqc_connections.get_from_dict(host_id))
def message_reciever(message, qubit2):
     with CQCConnection("Bob") as Bob:
         qubit2 = qubit(Bob)
         if message[1] == 1:
             qubit2.X()
         if message[0] == 1:
             qubit2.Z()
         d = qubit2.measure()
         recieve_bit = d
         recieve_bit = int(d)
     return recieve_bit
Esempio n. 9
0
 def testReset(self):
     with CQCConnection("Alice", appID=0, pend_messages=True) as cqc:
         q1 = qubit(cqc)
         cqc.flush()
         q1.X()
         q1.reset()
         cqc.flush_factory(self.iterations)
         q1.measure()
         m = cqc.flush()
         self.assertEqual(m, [0])
         self.assertEqual(len(cqc.pending_messages), 0)
Esempio n. 10
0
 def testMeasure(self):
     with CQCConnection("Alice", appID=0, pend_messages=True) as cqc:
         q = qubit(cqc)
         q.X()  # Let's do an X so all measurement outcomes should be 1
         # (to show no reinitialisation)
         cqc.flush()
         q.measure()
         with self.assertRaises(CQCNoQubitError):
             cqc.flush_factory(self.iterations)
         self.assertFalse(q._active)
         self.assertEqual(len(cqc._pending_headers), 0)
Esempio n. 11
0
def star_expansion(my_qubit_dict, name_inst, source, targets):
    """does the star expansion of the target from the source

	Arguments:
		my_qubit_dict {dict{simulacronQubitObject}} -- [description]
		name_inst {SimulacronCQCConnectionObjct} -- [description]
		source {str} -- [description]
		targets {str} -- [description]

	Returns:
		[type] -- [description]
	"""
    my_name = name_inst.name
    #protocol = protocol_from_json(my_name)
    if targets == [my_name]:  # (aka do nothing)
        #print("return flag1", my_name, source)

        my_qubit_dict[my_name] = my_qubit_dict[source]
        return my_qubit_dict
    else:
        if my_name in targets:
            #print("flag3", my_name)
            my_qubit_dict[my_name] = qubit(name_inst)
            my_qubit_dict[my_name].H()
            #print("flag2.5", my_name, my_qubit_dict[my_name])
        q_aux = qubit(name_inst)
        q_aux.H()
        q_aux.cphase(my_qubit_dict[source])

        for target in targets:
            #print("flag2", my_name, target)

            q_aux.cphase(my_qubit_dict[target])
        q_aux.Y()
        m1 = q_aux.measure()
        for t in targets:
            if t != my_name:
                #print("flag1", my_name, t)
                my_qubit_dict[t].Y()
                m2 = my_qubit_dict[t].measure()
        return my_qubit_dict
Esempio n. 12
0
 def test_send(self):
     for sender_name, receiver_name in self.edges:
         with CQCConnection(sender_name) as sender:
             with CQCConnection(receiver_name) as receiver:
                 q = qubit(sender)
                 sender.sendQubit(q=q,
                                  name=receiver_name,
                                  remote_appID=receiver._appID)
                 q = receiver.recvQubit()
                 m = q.measure()
                 self.assertEqual(m, 0)
     for sender_name, receiver_name in self.non_edges:
         with CQCConnection(sender_name) as sender:
             with CQCConnection(receiver_name) as receiver:
                 q = qubit(sender)
                 with self.assertRaises(CQCUnsuppError):
                     sender.sendQubit(q=q,
                                      name=receiver_name,
                                      remote_appID=receiver._appID)
                 m = q.measure()
                 self.assertEqual(m, 0)
def main():
    # Initialize the connection
    with CQCConnection("Alice") as Alice:
        # Create qubits
        q1 = qubit(Alice)
        q2 = qubit(Alice)
        J(q1, q2)  #passing them through J Gate
        q1.Z()  #sample decision
        Alice.sendQubit(
            q2, "Bob")  #sending Qubit to Bob after passing it through J gate
        q3 = Alice.recvQubit()  #recieve the manipulated qubit from Bob
        JD(q1, q3)  #passing it through reverse J gate
        # Measure the qubits

        a = q1.measure()
        b = q3.measure()
        to_print = "App {}: Measurement outcomes are: Alice={}, Bob={}".format(
            Alice.name, a, b)
        print("|" + "-" * (len(to_print) + 2) + "|")
        print("| " + to_print + " |")
        print("|" + "-" * (len(to_print) + 2) + "|")
def measure(node, q1, q2, measurements):
    """measurements is a string, with:
    - first element in ['+', '-']
    - second and third letter in ['I', 'X', 'Y', 'Z']"""
    # Create ancilla
    anc = qubit(node)
    ### ____
    pre_measure(node, q1, anc, measurements[1])
    pre_measure(node, q2, anc, measurements[2])
    if measurements[0] == "-":
        anc.X()
    return anc.measure()
Esempio n. 15
0
 def testMultipleTypes(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             q = qubit(alice)
             alice.flush()
             q.X()
             qubit(alice)
             q.measure(inplace=True)
             res = alice.flush_factory(8)
             alice.set_pending(False)
             q.measure()
             ms = res[1::2]
             qs = res[::2]
             for qu in qs:
                 self.assertEqual(qu.measure(), 0)
             self.assertEqual(len(res), 16)
             self.assertEqual(ms, [1, 0] * 4)
             alice.set_pending(True)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 16
0
def encode_hadamard(connection, number, length):
    encoded = [None] * length
    num_vector = BitVector(intVal=number, size=length)

    for i in range(length):
        encoded[i] = qubit(connection)
        if num_vector[i] != 0:
            encoded[i].X()  # Apply not gate

        # Put qubit into the hadamard basis
        encoded[i].H()

    return encoded
Esempio n. 17
0
 def testMeasureInplace(self):
     with CQCConnection("Alice", appID=0, pend_messages=True) as cqc:
         q = qubit(cqc)
         q.X()  # Let's do an X so all measurement outcomes should be 1
         # (to show no reinitialisation)
         cqc.flush()
         q.measure(inplace=True)
         m = cqc.flush_factory(self.iterations)
         self.assertEqual(len(m), self.iterations)
         self.assertTrue(x == 1 for x in m)
         q.measure()
         cqc.flush()
         self.assertEqual(len(cqc._pending_headers), 0)
Esempio n. 18
0
 def testSimpleSequence(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             q = qubit(alice)
             q.H()
             q.Z()
             q.H()
             q.measure()
             r = alice.flush()[1]
             self.assertEqual(r, 1)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 19
0
def test_createqubit(tmpdir):

    filename = os.path.join(str(tmpdir), 'CQC_File')

    with CQCToFile(file=filename, binary=False) as cqc:

        qubit(cqc)

        # Read the files before cqc goes out of context and flushes
        with open(filename) as f:
            lines = f.readlines()

    assert len(lines) == 1

    # Check that the first line initialize a qubit
    headers = parse_cqc_message(eval(lines[0][:-1]))
    assert len(headers) == 2
    hdr, cmd = headers
    assert isinstance(hdr, CQCHeader)
    assert hdr.tp == CQCType.COMMAND
    assert isinstance(cmd, CQCCmdHeader)
    assert cmd.qubit_id == 0
    assert cmd.instr == CQC_CMD_NEW
Esempio n. 20
0
 def testSend(self):
     with CQCConnection("Alice", appID=0, pend_messages=True) as cqc:
         q = qubit(cqc)
         q.X()
         cqc.flush()
         with CQCConnection("Bob", appID=1) as bob:
             # Get receiving host
             cqc.sendQubit(q, "Bob", remote_appID=1)
             with self.assertRaises(CQCNoQubitError):
                 cqc.flush_factory(self.iterations)
             qB = bob.recvQubit()
             self.assertTrue(qB.measure(), 1)
             self.assertFalse(q._active)
         self.assertEqual(len(cqc.pending_messages), 0)
Esempio n. 21
0
def initialize_Qubit_register(num_qubit, Owner):
    """
    Initialize quantum registers. Multiple qubits are stored and returned as an array.
    Returns an array of initialized qubits.

    :param num_qubit: Number of qubits to initialize
    :param Owner: The owner of the qubit / CQCConnection.
    """

    qubits = []
    for x in range(0, num_qubit):
        one_more_qubit = qubit(Owner)
        qubits.append(one_more_qubit)
    return qubits
Esempio n. 22
0
def main(agents):
    print("running Bob")

    # Initialize the connection
    with CQCConnection(agents[1]) as Bob:

        # Make an EPR pair with Alice
        qB = Bob.recvEPR()


        for agent in agents[2:]:
            # Create a fresh qubit
            qC = qubit(Bob)

            # Entangle the new qubit
            qB.cnot(qC)

            # Send qubit to Charlie
            Bob.sendQubit(qC, agent)

        mCharlies = []
        for charlie in agents[2:]:
            mCharlies.append(list(Bob.recvClassical())[0])

        bp = randint(0, 1)
        b = list(Bob.recvClassical())[0]

        if (bp + sum(mCharlies)) % 2 == 1:
            qB.Z()



        data = Bob.recvClassical()
        message = list(data)
        
        a = message[0]
        b = message[1]

        # Apply corrections
        if b == 1:
            qB.X()
        if a == 1:
            qB.Z()

            # Measure qubit

        m = qB.measure()

        print("Bob received message", m)
Esempio n. 23
0
    def test_send_for_last_position(self):
        with CQCConnection("Alice") as alice:
            with CQCConnection("Bob") as bob:
                alice_qubits = []
                bob_qubits = []
                for _ in range(simulaqron_settings.max_qubits):
                    q = qubit(alice)
                    alice_qubits.append(q)
                for _ in range(simulaqron_settings.max_qubits - 1):
                    q = qubit(bob)
                    bob_qubits.append(q)

                alice.sendQubit(alice_qubits[0], "Bob", remote_appID=bob._appID)
                q = bob.recvQubit()
                bob_qubits.append(q)

                with self.assertRaises(CQCNoQubitError):
                    alice.sendQubit(alice_qubits[1], "Bob", remote_appID=bob._appID)

                    # remove one qubit from Bob
                bob_qubits[0].measure()

                alice.sendQubit(alice_qubits[1], "Bob", remote_appID=bob._appID)
                bob.recvQubit()
Esempio n. 24
0
 def testMeasuringMultipleQubits(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             qA = qubit(alice)
             qs = alice.flush_factory(10)
             self.assertIsNone(qA._qID)
             self.assertFalse(qA.check_active())
             for q in qs:
                 q.measure()
             ms = alice.flush()
             self.assertEqual(ms, [0] * 10)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 25
0
def one_way_function(conn, BB84_key, db_id, r, M):
    owf_state = qubit(conn)

    BB84_key = int(BB84_key, 2)
    owf_key = bin(BB84_key)[2:] + bin(db_id)[2:] + bin(r)[2:] + bin(M)[2:]
    owf_key = int(abs(hash(str(owf_key))))
    # p1 , p2, p3 are prime numbers , so coprimes 
    # thus rotation X(key%p1) and Y(key%p2) and Z(key%p3) are independant
    p1 = 33179
    p2 = 32537
    p3 = 31259
    owf_state.rot_X(owf_key%p1%256)
    owf_state.rot_Y(owf_key%p2%256)
    owf_state.rot_Z(owf_key%p3%256)
    return owf_state
Esempio n. 26
0
 def testAlternating(self):
     with CQCConnection("Alice", pend_messages=True) as alice:
         with CQCConnection("Bob", appID=1, pend_messages=True) as bob:
             q = qubit(alice)
             alice.flush()
             q.X()
             q.measure(inplace=True)
             res = alice.flush_factory(10)
             q.measure()
             alice.flush()
             self.assertEqual(res, [1, 0] * 5)
             self.assertEqual(alice.pending_messages, [])
             self.assertEqual(bob.pending_messages, [])
             alice.flush()
             bob.flush()
Esempio n. 27
0
def create_conn(device_name, target_name):
    t0 = time.time()
    print('Sending RECV from %s to %s' % (device_name, target_name))
    send_rec(device_name, target_name)
    print('Starting creating and sending QK from: %s to: %s' %
          (device_name, target_name))
    secret_key = ''
    with CQCConnection(device_name) as Alice:
        print('start comm')
        for i in range(256):
            # Make an EPR pair with Bob
            qA = Alice.createEPR(target_name)
            # Create a random number
            q_random = qubit(Alice)
            q_random.H()
            r_number = q_random.measure()
            secret_key += str(r_number)
            #print('Random number: ' + str(r_number))
            # Create a qubit to teleport
            q = qubit(Alice)
            # Prepare the qubit to teleport in |+>
            if r_number == 1:
                q.X()
            # Apply the local teleportation operations
            q.cnot(qA)
            q.H()
            # Measure the qubits
            a = q.measure()
            b = qA.measure()
            Alice.sendClassical(target_name, [a, b])
        print(hex(int(secret_key, 2)))
    t1 = time.time()
    secs = t1 - t0
    print('It took: %d mins %d seconds' % (secs // 60, secs % 60))
    print(bitstring_to_bytes(secret_key))
    send(bitstring_to_bytes(secret_key))
Esempio n. 28
0
def swap_test(conn, q1, q2):
    # swap_test implementation from :
    # https://en.wikipedia.org/wiki/Swap_test

    q0 = qubit(conn)
    q0.H()
    CSWAP(q0, q1, q2)
    q0.H()
    m = q0.measure()

    # collaspse everything after swap_test to avoid :
    # cqc.pythonLib.CQCNoQubitError: No more qubits available
    q1.measure()
    q2.measure()
           
    return m
Esempio n. 29
0
def bobNode():

    with CQCConnection("Bob") as Bob:

        #Receving Alice's EPR
        qB = Bob.recvEPR()

        data = Bob.recvClassical()
        message = list(data)

        a = message[0]
        b = message[1]

        if b == 1:
            qB.X()
        if a == 1:
            qB.Z()

        m = qB.measure(inplace=True) #Similar to Alice's retention of qA.
        print("Bob: Measurement outcomes of A->B is: {}".format(m))
        print("-"*50+"\n\n")

        #Just flipping the previous outcome for fun
        n = 2**m - 1

        print("||   Now, Bob will send a message to Alice   ||")
        print("-"*25)

        #Creating Bob's own qubit and
        # controversially recreating EPR (Refer line 26 in Alice's code)
        qB = Bob.createEPR("Alice")
        q = qubit(Bob)

        #Using the flipped outcome
        if n:
            q.X()

        q.H()
        q.cnot(qB)
        q.H()

        c = q.measure()
        d = qB.measure()

        print("Bob: Measurement outcomes of B->A are: c={}, d={} \n\n".format(c, d))

        Bob.sendClassical("Alice", [c, d])
Esempio n. 30
0
File: zwdz.py Progetto: rasa97/qAuth
    def createRandom(self):
        """
        Method that creates the random key for the
        iteration. Uses randomness of Quantum 
        Mechanics to produce the required string.

        :return: Random key.
        :rtype: String
        """

        random_key = ''
        with CQCConnection(self.name) as User:
            for i in range(24):
                q = qubit(User)
                q.H()
                random_key = random_key + str(q.measure())
        return random_key