コード例 #1
0
def update_network(children):
    global sample

    if children != '':
        local_network = Network(sample=sample)
        return local_network.get_figure()

    else:
        return layout.get_empty_figure(height=900)
コード例 #2
0
    def handle_routing_packet(self, packet, dynamic):
        """
        Updates the cost and routing tables using the given routing packet

        :param packet: Routing packet to update tables for
        :type packet: RoutingPacket
        :param dynamic: Whether we're handling a dynamic or static packet
        :type dynamic: bool
        :return: Nothing
        :rtype: None
        """
        # No routing table yet. Begin creation, then handle this packet
        if not self._get_intermediate_routing_table(dynamic):
            self.create_routing_table(dynamic)
        did_update = False
        cost_table = packet.costTable
        src_id = packet.src.id

        # Get the appropriate routing table
        routing_table = self._get_intermediate_routing_table(dynamic)
        # Update costs by adding the cost to travel to the source node
        src_cost = routing_table[src_id].cost
        for identifier in cost_table.keys():
            cost_table[identifier] = cost_table[identifier] + src_cost

        src_link = routing_table[src_id].link
        # Update our routing table based on the received table
        for identifier, cost in cost_table.items():
            # New entry to tables or smaller cost
            if identifier not in routing_table or \
                    cost < routing_table[identifier].cost:
                did_update = True
                routing_table[identifier] = LinkCostTuple(src_link, cost)

        # Store and broadcast the updated table if an update occurred
        if did_update:
            self.sameDataCounter = 0
            self.store_routing_table(dynamic, routing_table)
            new_cost_table = self.cost_table_from_routing_table(dynamic)
            self.broadcast_table(new_cost_table, dynamic)
        else:
            self.sameDataCounter += 1
            # Log the same data receipt
            Logger.debug(Network.get_time(),
                         "%s received no new routing table "
                         "data." % self)
            # Log finalized routing table
            Logger.trace(
                Network.get_time(), "%s final %s routing table:" %
                (self, "dynamic" if dynamic else "static"))
            if dynamic:
                self.handle_same_dynamic_routing_table()
コード例 #3
0
ファイル: router.py プロジェクト: cs143-2015/network-sim
    def handle_routing_packet(self, packet, dynamic):
        """
        Updates the cost and routing tables using the given routing packet

        :param packet: Routing packet to update tables for
        :type packet: RoutingPacket
        :param dynamic: Whether we're handling a dynamic or static packet
        :type dynamic: bool
        :return: Nothing
        :rtype: None
        """
        # No routing table yet. Begin creation, then handle this packet
        if not self._get_intermediate_routing_table(dynamic):
            self.create_routing_table(dynamic)
        did_update = False
        cost_table = packet.costTable
        src_id = packet.src.id

        # Get the appropriate routing table
        routing_table = self._get_intermediate_routing_table(dynamic)
        # Update costs by adding the cost to travel to the source node
        src_cost = routing_table[src_id].cost
        for identifier in cost_table.keys():
            cost_table[identifier] = cost_table[identifier] + src_cost

        src_link = routing_table[src_id].link
        # Update our routing table based on the received table
        for identifier, cost in cost_table.items():
            # New entry to tables or smaller cost
            if identifier not in routing_table or \
                    cost < routing_table[identifier].cost:
                did_update = True
                routing_table[identifier] = LinkCostTuple(src_link, cost)

        # Store and broadcast the updated table if an update occurred
        if did_update:
            self.sameDataCounter = 0
            self.store_routing_table(dynamic, routing_table)
            new_cost_table = self.cost_table_from_routing_table(dynamic)
            self.broadcast_table(new_cost_table, dynamic)
        else:
            self.sameDataCounter += 1
            # Log the same data receipt
            Logger.debug(Network.get_time(), "%s received no new routing table "
                                             "data." % self)
            # Log finalized routing table
            Logger.trace(Network.get_time(), "%s final %s routing table:"
                         % (self, "dynamic" if dynamic else "static"))
            if dynamic:
                self.handle_same_dynamic_routing_table()
コード例 #4
0
ファイル: router.py プロジェクト: cs143-2015/network-sim
    def update_dynamic_routing_table(self, routing_table):
        """
        Replace the old dynamicRoutingTable with the given new one

        :param routing_table: Routing table to update the old one with
        :type routing_table: dict[str, LinkCostTuple]
        :return: Nothing
        :rtype: None
        """
        Logger.trace(Network.get_time(), "%s:" % self)
        Logger.trace(Network.get_time(), "Replacing old dynamic routing table:")
        self.print_routing_table(self.dynamicRoutingTable)
        Logger.trace(Network.get_time(), "With new dynamic routing table:")
        self.print_routing_table(self.newDynamicRoutingTable)
        self.dynamicRoutingTable = routing_table
コード例 #5
0
    def update_dynamic_routing_table(self, routing_table):
        """
        Replace the old dynamicRoutingTable with the given new one

        :param routing_table: Routing table to update the old one with
        :type routing_table: dict[str, LinkCostTuple]
        :return: Nothing
        :rtype: None
        """
        Logger.trace(Network.get_time(), "%s:" % self)
        Logger.trace(Network.get_time(),
                     "Replacing old dynamic routing table:")
        self.print_routing_table(self.dynamicRoutingTable)
        Logger.trace(Network.get_time(), "With new dynamic routing table:")
        self.print_routing_table(self.newDynamicRoutingTable)
        self.dynamicRoutingTable = routing_table
コード例 #6
0
    def create_routing_table(self, dynamic=None):
        """
        Begins creation of a routing table by broadcasting adjacent link costs

        :param dynamic: Whether to create a dynamic or static routing table
        :type dynamic: bool
        :return: Nothing
        :rtype: None
        """
        if not dynamic:
            dynamic = self.dynamicEnabled
        # Only add the dynamic routing table update timer once
        if dynamic and not self.dynamicRoutingTableTimerAdded:
            self.add_timer(UpdateDynamicRoutingTableEvent(None, self),
                           Network.get_time(), DYNAMIC_UPDATE_INTERVAL)
            self.dynamicRoutingTableTimerAdded = True
        # Reset the dynamic routing table same data counter
        self.sameDataCounter = 0
        # Initialize cost of reaching oneself as 0
        routing_table = {self.id: LinkCostTuple(None, 0)}
        # Create cost table to broadcast with costs of this router's neighbors
        # { node_id : cost }
        cost_table = {}
        for link in self.links:
            # Get the dynamic or static cost of the link
            cost = link.dynamic_cost() if dynamic else link.static_cost()
            other_node_id = link.other_node(self).id
            cost_table[other_node_id] = cost
            routing_table[other_node_id] = LinkCostTuple(link, cost)
        self.store_routing_table(dynamic, routing_table)
        self.broadcast_table(cost_table, dynamic)
コード例 #7
0
def main():
    backend = CQCBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.7
    hosts = {'alice': Host('Alice', backend),
             'bob': Host('Bob', backend)}

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    hosts['alice'].send_superdense(hosts['bob'].host_id, '01')

    messages = hosts['bob'].classical
    i = 0
    while i < 5 and len(messages) == 0:
        messages = hosts['bob'].classical
        i += 1
        time.sleep(1)

    assert messages is not None
    assert len(messages) > 0
    assert (messages[0].sender == hosts['alice'].host_id)
    assert (messages[0].content == '01')
    print("All tests succesfull!")
    network.stop(True)
    exit()
コード例 #8
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve"]
    network.start(nodes)
    network.delay = 0.1

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.add_connections(['Alice', 'Eve'])
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.start()

    network.add_hosts([host_alice, host_bob, host_eve])

    host_bob.q_relay_sniffing = True
    host_bob.q_relay_sniffing_fn = bob_sniffing_quantum

    host_bob.c_relay_sniffing = True
    host_bob.c_relay_sniffing_fn = bob_sniffing_classical

    t1 = host_alice.run_protocol(alice)
    t2 = host_eve.run_protocol(eve)

    t1.join()
    t2.join()

    network.stop(True)
    exit()
コード例 #9
0
def main():
    network = Network.get_instance()
    nodes = ['Alice', 'Bob', 'Eve']
    network.delay = 0.2
    network.start(nodes)

    host_alice = Host('Alice')
    host_bob = Host('Bob')
    host_eve = Host('Eve')

    host_alice.add_connection('Bob')
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_eve.add_connection('Bob')

    host_alice.start()
    host_bob.start()
    host_eve.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)

    q = Qubit(host_alice)
    q.X()

    host_alice.send_teleport('Eve', q, await_ack=True)
    q_eve = host_eve.get_data_qubit(host_alice.host_id, q.id, wait=5)

    assert q_eve is not None
    print('Eve measures: %d' % q_eve.measure())
コード例 #10
0
def main():
    network = Network.get_instance()
    network.delay = 0.1
    nodes = ["Alice", "Bob", "Eve"]
    network.start(nodes)

    host_alice = Host('Alice', )
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)

    host_alice.send_superdense('Eve', '11')
    host_alice.send_superdense('Eve', '10')
    host_alice.send_superdense('Eve', '00')

    time.sleep(5)
    messages = host_eve.get_classical('Alice')

    for m in messages:
        print('----')
        print(m)
        print('----')
コード例 #11
0
ファイル: protocol_send_EPR.py プロジェクト: h-oll/QuNetSim
def main():
    network = Network.get_instance()
    nodes = ['A', 'B', 'C']
    network.start(nodes)
    network.delay = 0.1

    host_A = Host('A')
    host_A.add_connection('B')
    host_A.start()

    host_B = Host('B')
    host_B.add_connection('A')
    host_B.add_connection('C')
    host_B.start()

    host_C = Host('C')
    host_C.add_connection('B')
    host_C.start()

    network.add_host(host_A)
    network.add_host(host_B)
    network.add_host(host_C)

    host_A.run_protocol(protocol_1, (host_C.host_id,))
    host_C.run_protocol(protocol_2, (host_A.host_id,))
コード例 #12
0
def main():
    backend = CQCBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.0
    hosts = {'alice': Host('Alice', backend), 'bob': Host('Bob', backend)}

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    q = Qubit(hosts['alice'])
    q.X()

    hosts['alice'].send_teleport(hosts['bob'].host_id, q)

    q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
    i = 0
    while q2 is None and i < 5:
        q2 = hosts['bob'].get_data_qubit(hosts['alice'].host_id)
        i += 1
        time.sleep(1)

    assert q2 is not None
    assert q2.measure() == 1
    print("All tests succesfull!")
    network.stop(True)
    exit()
コード例 #13
0
ファイル: q_udp.py プロジェクト: witt-designs/QuNetSim
def main():
    network = Network.get_instance()

    nodes = ["Alice", "Bob"]
    network.x_error_rate = 0
    network.delay = 0.5
    network.start(nodes)

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.max_ack_wait = 10
    host_alice.delay = 0.2
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.max_ack_wait = 10
    host_bob.delay = 0.2
    host_bob.add_connection('Alice')
    host_bob.start()

    network.add_host(host_alice)
    network.add_host(host_bob)

    q_size = 6

    host_alice.run_protocol(qudp_sender, (q_size, host_bob.host_id))
    host_bob.run_protocol(qudp_receiver, (q_size, host_alice.host_id))

    start_time = time.time()
    while time.time() - start_time < 50:
        pass

    network.stop(stop_hosts=True)
コード例 #14
0
ファイル: q_money.py プロジェクト: witt-designs/QuNetSim
def main():
    # Initialize a network
    network = Network.get_instance()

    nodes = ['Alice', 'Bob', 'Eve']
    network.delay = 0.0
    network.start(nodes)

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)

    print('Starting transfer')
    t1 = host_alice.run_protocol(banker_protocol, (host_eve.host_id, ))
    t2 = host_eve.run_protocol(customer_protocol, (host_alice.host_id, ))

    t1.join()
    t2.join()

    network.stop(True)
コード例 #15
0
ファイル: router.py プロジェクト: cs143-2015/network-sim
    def create_routing_table(self, dynamic=None):
        """
        Begins creation of a routing table by broadcasting adjacent link costs

        :param dynamic: Whether to create a dynamic or static routing table
        :type dynamic: bool
        :return: Nothing
        :rtype: None
        """
        if not dynamic:
            dynamic = self.dynamicEnabled
        # Only add the dynamic routing table update timer once
        if dynamic and not self.dynamicRoutingTableTimerAdded:
            self.add_timer(UpdateDynamicRoutingTableEvent(None, self),
                           Network.get_time(), DYNAMIC_UPDATE_INTERVAL)
            self.dynamicRoutingTableTimerAdded = True
        # Reset the dynamic routing table same data counter
        self.sameDataCounter = 0
        # Initialize cost of reaching oneself as 0
        routing_table = {self.id: LinkCostTuple(None, 0)}
        # Create cost table to broadcast with costs of this router's neighbors
        # { node_id : cost }
        cost_table = {}
        for link in self.links:
            # Get the dynamic or static cost of the link
            cost = link.dynamic_cost() if dynamic else link.static_cost()
            other_node_id = link.other_node(self).id
            cost_table[other_node_id] = cost
            routing_table[other_node_id] = LinkCostTuple(link, cost)
        self.store_routing_table(dynamic, routing_table)
        self.broadcast_table(cost_table, dynamic)
コード例 #16
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    backend = CQCBackend()
    network.start(nodes, backend)
    network.delay = 0.7

    hosts = {'alice': Host('Alice', backend),
             'bob': Host('Bob', backend)}

    network.delay = 0
    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    q1 = Qubit(hosts['alice'])
    hosts['alice'].send_qubit('Bob', q1, await_ack=True)
    q1 = Qubit(hosts['alice'])
    hosts['alice'].send_qubit('Bob', q1, await_ack=True)
    q1 = Qubit(hosts['alice'])
    hosts['alice'].send_qubit('Bob', q1, await_ack=True)
    q1 = Qubit(hosts['bob'])
    hosts['bob'].send_qubit('Alice', q1, await_ack=True)
    network.stop(True)
    exit()
コード例 #17
0
def main():
    backend = EQSNBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.0

    hosts = {'alice': Host('Alice', backend), 'bob': Host('Bob', backend)}

    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    ack_received_1 = hosts['alice'].send_classical(hosts['bob'].host_id,
                                                   'hello bob one',
                                                   await_ack=True)
    hosts['alice'].max_ack_wait = 0.0
    ack_received_2 = hosts['alice'].send_classical(hosts['bob'].host_id,
                                                   'hello bob one',
                                                   await_ack=True)
    assert ack_received_1
    assert not ack_received_2
    print("All tests succesfull!")
    network.stop(True)
    exit()
コード例 #18
0
def main():
    network = Network.get_instance()

    # backend = ProjectQBackend()
    backend = CQCBackend()

    nodes = ['A', 'B', 'C']
    network.start(nodes, backend)
    network.delay = 0.1

    host_A = Host('A', backend)
    host_A.add_connection('B')
    host_A.delay = 0
    host_A.start()

    host_B = Host('B', backend)
    host_B.add_connections(['A', 'C'])
    host_B.delay = 0
    host_B.start()

    host_C = Host('C', backend)
    host_C.add_connection('B')
    host_C.delay = 0
    host_C.start()

    network.add_host(host_A)
    network.add_host(host_B)
    network.add_host(host_C)

    t1 = host_A.run_protocol(protocol_1, (host_C.host_id, ))
    t2 = host_C.run_protocol(protocol_2, (host_A.host_id, ))

    t1.join()
    t2.join()
    network.stop(True)
コード例 #19
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    back = ProjectQBackend()
    network.start(nodes, back)

    network.delay = 0.1

    host_alice = Host('Alice', back)
    host_alice.add_connection('Bob')
    host_alice.add_connection('Eve')
    host_alice.start()

    host_bob = Host('Bob', back)
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve', back)
    host_eve.add_connection('Bob')
    host_eve.add_connection('Dean')
    host_eve.add_connection('Alice')
    host_eve.start()

    host_dean = Host('Dean', back)
    host_dean.add_connection('Eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    share_list = ["Bob", "Eve", "Dean"]
    q_id1 = host_alice.send_ghz(share_list, no_ack=True)

    q1 = host_alice.get_ghz('Alice', q_id1, wait=10)
    q2 = host_bob.get_ghz('Alice', q_id1, wait=10)
    q3 = host_eve.get_ghz('Alice', q_id1, wait=10)
    q4 = host_dean.get_ghz('Alice', q_id1, wait=10)

    if q1 is None:
        raise ValueError("Q1 is none")
    if q2 is None:
        raise ValueError("Q2 is none")
    if q3 is None:
        raise ValueError("Q3 is none")
    if q4 is None:
        raise ValueError("Q4 is none")

    m1 = q1.measure()
    m2 = q2.measure()
    m3 = q3.measure()
    m4 = q4.measure()

    print("results of measurements are %d, %d, %d, and %d." % (m1, m2, m3, m4))

    network.stop(True)
    exit()
コード例 #20
0
def main():

    Y = 2
    M = 2

    network = Network.get_instance()
    nodes = ['Alice','C0','Bob']
    network.use_ent_swap = True
    network.start(nodes)
#0.01549
    alice = Host('Alice')
    alice.add_connection('C0', 100)
    alice.coherence_time = 1
    alice.max_ack_wait = 5
    alice.start()

    repeater0 = Host('C0')
    repeater0.add_connection('Alice', 100)
    repeater0.add_connection('Bob', 100)
    repeater0.coherence_time = 1
    repeater0.max_ack_wait = 5
    repeater0.start()

    # repeater1 = Host('C1')
    # repeater1.add_connection('C0')
    # repeater1.add_connection('C2')
    # repeater1.max_ack_wait = 5
    # repeater1.start()

    # repeater2 = Host('C2')
    # repeater2.add_connection('C1')
    # repeater2.add_connection('Bob')
    # repeater2.max_ack_wait = 5
    # repeater2.start()

    bob = Host('Bob')
    bob.add_connection('C0', 100)
    bob.coherence_time = 1
    bob.max_ack_wait = 5
    bob.start()

    network.add_host(alice)
    network.add_host(repeater0)
    #network.add_host(repeater1)
    #network.add_host(repeater2)
    network.add_host(bob)
    
    t1 = alice.run_protocol(AliceProtocol, (repeater0.host_id, Y, M))
    t2 = repeater0.run_protocol(RepeaterProtocol, (alice.host_id, bob.host_id, 0, 1, Y, M))
    #repeater1.run_protocol(RepeaterProtocol, (repeater0.host_id, repeater2.host_id, 1, 2, Y, M))
    #repeater2.run_protocol(RepeaterProtocol, (repeater1.host_id, bob.host_id, 2, 2, Y, M))
    t3 = bob.run_protocol(BobProtocol, (repeater0.host_id, Y, M))

    t1.join()
    t2.join()
    t3.join()

    network.stop(True)
コード例 #21
0
ファイル: qkd_eqsn.py プロジェクト: witt-designs/QuNetSim
def main():
    # Initialize a network
    network = Network.get_instance()
    backend = EQSNBackend()

    # Define the host IDs in the network
    nodes = ['Alice', 'Bob']

    network.delay = 0.0

    # Start the network with the defined hosts
    network.start(nodes, backend)

    # Initialize the host Alice
    host_alice = Host('Alice', backend)

    # Add a one-way connection (classical and quantum) to Bob
    host_alice.add_connection('Bob')
    host_alice.delay = 0.0

    # Start listening
    host_alice.start()

    host_bob = Host('Bob', backend)
    # Bob adds his own one-way connection to Alice
    host_bob.add_connection('Alice')
    host_bob.delay = 0.0
    host_bob.start()

    # Add the hosts to the network
    # The network is: Alice <--> Bob
    network.add_host(host_alice)
    network.add_host(host_bob)

    # Generate random key
    key_size = 20  # the size of the key in bit
    secret_key = np.random.randint(2, size=key_size)

    # Concatentate functions
    def alice_func(alice):
        msg_buff = []
        alice_qkd(alice, msg_buff, secret_key, host_bob.host_id)
        alice_send_message(alice, secret_key, host_bob.host_id)

    def bob_func(eve):
        msg_buff = []
        eve_key = eve_qkd(eve, msg_buff, key_size, host_alice.host_id)
        eve_receive_message(eve, msg_buff, eve_key, host_alice.host_id)

    # Run Bob and Alice

    host_alice.run_protocol(alice_func, ())
    host_bob.run_protocol(bob_func, (), blocking=True)

    time.sleep(1)
    network.stop(True)
コード例 #22
0
    def setUpClass(cls):
        simulaqron_settings.default_settings()
        nodes = ['Alice', 'Bob', 'Eve']
        cls.sim_network = SimulaNetwork(nodes=nodes, force=True)
        cls.sim_network.start()

        cls.network = Network.get_instance()
        cls.network.start()

        if os.path.exists('./components/__pycache__'):
            os.system('rm -rf ./components/__pycache__/')
コード例 #23
0
ファイル: checksum.py プロジェクト: witt-designs/QuNetSim
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    network.delay = 0.5

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.max_ack_wait = 30
    host_alice.delay = 0.2
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.max_ack_wait = 30
    host_bob.delay = 0.2
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.max_ack_wait = 30
    host_eve.delay = 0.2
    host_eve.add_connection('Bob')
    host_eve.add_connection('Dean')
    host_eve.start()

    host_dean = Host('Dean')
    host_dean.max_ack_wait = 30
    host_dean.delay = 0.2
    host_dean.add_connection('Eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    network.x_error_rate = 0
    network.packet_drop_rate = 0

    q_size = 6
    checksum_per_qubit = 2

    host_alice.run_protocol(checksum_sender,
                            (q_size, host_dean.host_id, checksum_per_qubit))
    host_dean.run_protocol(checksum_receiver,
                           (q_size, host_alice.host_id, checksum_per_qubit))

    start_time = time.time()
    while time.time() - start_time < 150:
        pass

    network.stop(stop_hosts=True)
    exit()
コード例 #24
0
def test_adding_hosts_to_backend(backend_generator):
    print("Starrting adding a host test...")
    backend = backend_generator()
    network = Network.get_instance()
    network.start(["Alice"], backend)
    alice = Host('Alice', backend)
    alice.start()

    network.add_host(alice)
    network.stop(True)
    print("Test was successfull!")
コード例 #25
0
def qunetsim():
    from components.host import Host
    from components.network import Network
    from objects.qubit import Qubit

    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    network.delay = 0.1

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.add_connection('Dean')
    host_eve.start()

    host_dean = Host('Dean')
    host_dean.add_connection('Eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    from mappings.qunetsim import mapping

    #return host_alice, host_bob, host_eve, network

    def source_protocol(source_host, target_host_id):
        _ = qpz_atomics.lib(mapping, source_host)
        for i in range(5):
            q = _.PREP()
            q = _.H(q)
            print("sending"), _.DISP(q)
            _.SEND(q, target_host_id)

    def target_protocol(target_host, source_host_id):
        _ = qpz_atomics.lib(mapping, target_host)
        for i in range(5):
            print(source_host_id)
            q = _.RECV(source_host_id)
            print("recieved"), _.DISP(q)

    host_alice.run_protocol(source_protocol, (host_bob.host_id, ))
    host_bob.run_protocol(target_protocol, (host_alice.host_id, ))
コード例 #26
0
def test_multiple_backends(backend_generator):
    print("Starting multiple backends test...")
    backend1 = backend_generator()
    backend2 = backend_generator()
    assert backend1._cqc_connections == backend2._cqc_connections
    network = Network.get_instance()
    network.start(["Alice", "Bob"], backend1)
    alice = Host('Alice', backend2)
    bob = Host('Bob', backend1)
    assert str(backend1._cqc_connections) == str(backend2._cqc_connections)
    assert str(backend1._hosts) == str(backend2._hosts)
    network.stop(True)
    print("Test was successfull!")
コード例 #27
0
def main():
    global thread_1_return
    global thread_2_return

    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    network.delay = 0.5

    host_alice = Host('alice')
    host_alice.add_connection('bob')
    host_alice.max_ack_wait = 30
    host_alice.delay = 0.2
    host_alice.start()

    host_bob = Host('bob')
    host_bob.max_ack_wait = 30
    host_bob.delay = 0.2
    host_bob.add_connection('alice')
    host_bob.add_connection('eve')
    host_bob.start()

    host_eve = Host('eve')
    host_eve.max_ack_wait = 30
    host_eve.delay = 0.2
    host_eve.add_connection('bob')
    host_eve.add_connection('dean')
    host_eve.start()

    host_dean = Host('dean')
    host_dean.max_ack_wait = 30
    host_dean.delay = 0.2
    host_dean.add_connection('eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    host_alice.run_protocol(retransmission_sender,
                            (host_dean.host_id, MAX_TRIAL_NUM))
    host_dean.run_protocol(retransmission_receiver,
                           (host_alice.host_id, MAX_TRIAL_NUM))

    start_time = time.time()
    while time.time() - start_time < 150:
        pass

    network.stop(stop_hosts=True)
    exit()
コード例 #28
0
ファイル: key_sharing.py プロジェクト: witt-designs/QuNetSim
def main():
    # Initialize a network
    network = Network.get_instance()
    # Define the host IDs in the network
    nodes = ['Alice', 'Bob', 'Eve']
    network.delay = 0.0
    # Start the network with the defined hosts
    network.start(nodes)
    # Initialize the host Alice
    host_alice = Host('Alice')
    # Add a one-way connection (classical and quantum) to Bob
    host_alice.add_connection('Bob')
    # Start listening
    host_alice.start()

    host_bob = Host('Bob')
    # Bob adds his own one-way connection to Alice and Eve
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.start()

    # Add the hosts to the network
    # The network is: Alice <--> Bob <--> Eve
    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)

    # Generate random key
    key_size = 8  # the size of the key in bit
    hosts = {'Alice': host_alice, 'Bob': host_bob, 'Eve': host_eve}

    # Run Alice and Eve
    host_alice.send_key(host_eve.host_id, key_size)

    start_time = time.time()
    while time.time() - start_time < 60:
        pass

    print('SENDER KEYS')
    print(host_alice.qkd_keys)

    print('RECEIVER KEYS')
    print(host_eve.qkd_keys)

    for h in hosts.values():
        h.stop()
    network.stop()
コード例 #29
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    backend = CQCBackend()
    network.start(nodes, backend)
    network.delay = 0.2
    network.packet_drop_rate = 0
    print('')

    host_alice = Host('Alice', backend)
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob', backend)
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve', backend)
    host_eve.add_connection('Bob')
    host_eve.add_connection('Dean')
    host_eve.start()

    host_dean = Host('Dean', backend)
    host_dean.add_connection('Eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    print('alice sends message')

    host_alice.send_classical('Bob', 'hello1')
    host_alice.send_classical('Bob', 'hello2')
    host_alice.send_classical('Bob', 'hello3')
    host_alice.send_classical('Bob', 'hello4')
    host_alice.send_classical('Bob', 'hello5')
    host_alice.send_classical('Bob', 'hello6')
    host_alice.send_classical('Bob', 'hello7')
    host_alice.send_classical('Bob', 'hello8')
    host_alice.send_classical('Bob', 'hello9')
    host_alice.send_classical('Bob', 'hello10')

    start_time = time.time()
    while time.time() - start_time < 10:
        pass

    network.stop(True)
    exit()
コード例 #30
0
 def handle_same_dynamic_routing_table(self):
     """
     Handle the receipt of a routing table that provided no updates. If we
     have seen the same data SAME_DATA_THRESHOLD times, dispatch an event
     to update the dynamic routing table in the future, and replace the old
     dynamic routing table with the new one. Otherwise re-broadcast the
     routing table.
     """
     if self.sameDataCounter >= self.SAME_DATA_THRESHOLD:
         self.update_dynamic_routing_table(self.newDynamicRoutingTable)
         # Reset the dynamic cost for the links, we're done updating
         map(lambda l: l.reset_dynamic_cost(Network.get_time()), self.links)
     else:
         new_cost_table = self.cost_table_from_routing_table(dynamic=True)
         self.broadcast_table(new_cost_table, dynamic=True)
コード例 #31
0
ファイル: router.py プロジェクト: cs143-2015/network-sim
 def handle_same_dynamic_routing_table(self):
     """
     Handle the receipt of a routing table that provided no updates. If we
     have seen the same data SAME_DATA_THRESHOLD times, dispatch an event
     to update the dynamic routing table in the future, and replace the old
     dynamic routing table with the new one. Otherwise re-broadcast the
     routing table.
     """
     if self.sameDataCounter >= self.SAME_DATA_THRESHOLD:
         self.update_dynamic_routing_table(self.newDynamicRoutingTable)
         # Reset the dynamic cost for the links, we're done updating
         map(lambda l: l.reset_dynamic_cost(Network.get_time()), self.links)
     else:
         new_cost_table = self.cost_table_from_routing_table(dynamic=True)
         self.broadcast_table(new_cost_table, dynamic=True)
コード例 #32
0
ファイル: router.py プロジェクト: cs143-2015/network-sim
    def broadcast_table(self, cost_table, dynamic):
        """
        Broadcasts given table to all nodes this router is connected to.

        :param cost_table: Cost table to broadcast
        :type cost_table: dict[str, float]
        :param dynamic: Whether we're broadcasting dynamic/static routing table
        :type dynamic: bool
        :return: Nothing
        :rtype: None
        """
        packet_type = DynamicRoutingPacket if dynamic else StaticRoutingPacket
        for link in self.links:
            packet = packet_type(deepcopy(cost_table), self, link.other_node(self))
            self.send(packet, link, Network.get_time())
コード例 #33
0
def main():
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes)
    network.delay = 0.1

    host_alice = Host('Alice')
    host_alice.add_connection('Bob')
    host_alice.start()

    host_bob = Host('Bob')
    host_bob.add_connection('Alice')
    host_bob.add_connection('Eve')
    host_bob.start()

    host_eve = Host('Eve')
    host_eve.add_connection('Bob')
    host_eve.add_connection('Dean')
    host_eve.start()

    host_dean = Host('Dean')
    host_dean.add_connection('Eve')
    host_dean.start()

    network.add_host(host_alice)
    network.add_host(host_bob)
    network.add_host(host_eve)
    network.add_host(host_dean)

    # Create a qubit owned by Alice
    q = Qubit(host_alice)
    # Put the qubit in the excited state
    q.X()
    # Send the qubit and await an ACK from Dean
    q_id, _ = host_alice.send_qubit('Dean', q, await_ack=True)

    # Get the qubit on Dean's side from Alice
    q_rec = host_dean.get_data_qubit('Alice', q_id)

    # Ensure the qubit arrived and then measure and print the results.
    if q_rec is not None:
        m = q_rec.measure()
        print("Results of the measurements for q_id are ", str(m))
    else:
        print('q_rec is none')

    network.stop(True)
    exit()
コード例 #34
0
def main():
    print("Skip test, this test has to be updated!")
    return
    backend = CQCBackend()
    network = Network.get_instance()
    nodes = ["Alice", "Bob", "Eve", "Dean"]
    network.start(nodes, backend)
    network.delay = 0.7

    hosts = {'alice': Host('Alice', backend), 'bob': Host('Bob', backend)}

    network.delay = 0
    # A <-> B
    hosts['alice'].add_connection('Bob')
    hosts['bob'].add_connection('Alice')

    hosts['alice'].start()
    hosts['bob'].start()

    for h in hosts.values():
        network.add_host(h)

    # print(f"ack test - SEND CLASSICAL - started at {time.strftime('%X')}")
    hosts['alice'].send_classical(hosts['bob'].host_id,
                                  'hello bob one',
                                  await_ack=True)
    hosts['alice'].send_classical(hosts['bob'].host_id,
                                  'hello bob two',
                                  await_ack=True)
    # print(f"ack test - SEND CLASSICAL - finished at {time.strftime('%X')}")

    saw_ack_1 = False
    saw_ack_2 = False
    messages = hosts['alice'].classical
    # print([m.seq_num for m in messages])
    for m in messages:
        if m.content == protocols.ACK and m.seq_num == 0:
            saw_ack_1 = True
        if m.content == protocols.ACK and m.seq_num == 1:
            saw_ack_2 = True
        if saw_ack_1 and saw_ack_2:
            break

    assert saw_ack_1
    assert saw_ack_2
    print("All tests succesfull!")
    network.stop(True)
    exit()
コード例 #35
0
    def broadcast_table(self, cost_table, dynamic):
        """
        Broadcasts given table to all nodes this router is connected to.

        :param cost_table: Cost table to broadcast
        :type cost_table: dict[str, float]
        :param dynamic: Whether we're broadcasting dynamic/static routing table
        :type dynamic: bool
        :return: Nothing
        :rtype: None
        """
        packet_type = DynamicRoutingPacket if dynamic else StaticRoutingPacket
        for link in self.links:
            packet = packet_type(deepcopy(cost_table), self,
                                 link.other_node(self))
            self.send(packet, link, Network.get_time())
コード例 #36
0
ファイル: population.py プロジェクト: chris-stock/pyglm
    def __init__(self, model):
        """
        Initialize the population of GLMs connected by a network.
        """
        self.model = model
        self.N = model['N']

        # TODO: Go through every key in the model and initialize the 
        # top level components.
        
        # Create a network model to connect the GLMs
        self.network = Network(model)

        # Create a single GLM that is shared across neurons
        # This is to simplify the model and reuse parameters. 
        # Basically it speeds up the gradient calculations since we 
        # can manually leverage conditional independencies among GLMs
        self.glm = Glm(model, self.network)
コード例 #37
0
ファイル: router.py プロジェクト: cs143-2015/network-sim
 def print_routing_table(routing_table):
     if not routing_table:
         Logger.trace(Network.get_time(), "None")
         return
     for i, j in routing_table.items():
         Logger.trace(Network.get_time(), "\t%s: %s" % (i, j))
コード例 #38
0
ファイル: population.py プロジェクト: chris-stock/pyglm
class Population:
    """
    Population connected GLMs.
    """
    def __init__(self, model):
        """
        Initialize the population of GLMs connected by a network.
        """
        self.model = model
        self.N = model['N']

        # TODO: Go through every key in the model and initialize the 
        # top level components.
        
        # Create a network model to connect the GLMs
        self.network = Network(model)

        # Create a single GLM that is shared across neurons
        # This is to simplify the model and reuse parameters. 
        # Basically it speeds up the gradient calculations since we 
        # can manually leverage conditional independencies among GLMs
        self.glm = Glm(model, self.network)

    def compute_log_p(self, vars):
        """ Compute the log joint probability under a given set of variables
        """
        lp = 0.0

        # Get set of symbolic variables
        # syms = self.get_variables()
        #
        # lp += seval(self.network.log_p,
        #             syms['net'],
        #             vars['net'])
        # for n in range(self.N):
        #     nvars = self.extract_vars(vars, n)
        #     lp += seval(self.glm.log_p,
        #                 syms,
        #                 nvars)

        lp += self.compute_ll(vars)
        lp += self.compute_log_prior(vars)

        return lp

    def compute_log_prior(self, vars):
        """ Compute the log joint probability under a given set of variables
        """
        lp = 0.0

        # Get set of symbolic variables
        syms = self.get_variables()

        lp += seval(self.network.log_p,
                    syms['net'],
                    vars['net'])
        for n in range(self.N):
            nvars = self.extract_vars(vars, n)
            lp += seval(self.glm.log_prior,
                        syms,
                        nvars)

        return lp

    def compute_ll(self, vars):
        """ Compute the log likelihood under a given set of variables
        """
        ll = 0.0

        # Get set of symbolic variables
        syms = self.get_variables()

        for n in range(self.N):
            nvars = self.extract_vars(vars, n)
            ll += seval(self.glm.ll,
                        syms,
                        nvars)

        return ll

    def eval_state(self, vars):
        """ Evaluate the population state expressions given the parameters, 
            e.g. the stimulus response curves from the basis function weights.
        """
        # Get set of symbolic variables
        syms = self.get_variables()

        # Get the symbolic state expression to evaluate
        state_vars = self.get_state()
        state = {}
        state['net'] = self._eval_state_helper(syms['net'], 
                                                  state_vars['net'], 
                                                  vars['net'])

        glm_states = []
        for n in np.arange(self.N):
            nvars = self.extract_vars(vars, n)
            glm_states.append(self._eval_state_helper(syms,
                                                      state_vars['glm'], 
                                                      nvars))
        state['glms'] = glm_states

        # Finally, evaluate the log probability and the log likelihood
        # state['logp'] = self.compute_log_p(vars)
        state['logprior'] = self.compute_log_prior(vars)
        state['ll'] = self.compute_ll(vars)
        state['logp'] = state['ll'] + state['logprior']
        return state

    def _eval_state_helper(self, syms, d, vars):
        """ Helper function to recursively evaluate state variables
        """
        state = {}
        for (k,v) in d.items():
            if isinstance(v,dict):
                state[k] = self._eval_state_helper(syms, v, vars)
            else:
                state[k] = seval(v, syms, vars)
        return state
        
    def get_variables(self):
        """ Get a list of all variables
        """
        v = {}
        v['net'] = self.network.get_variables()
        v['glm'] = self.glm.get_variables()
        return v

    def set_hyperparameters(self, model):
        """ Set the hyperparameters of the model
        """
        self.network.set_hyperparameters(model)
        self.glm.set_hyperparameters(model)

    def sample(self):
        """
        Sample parameters of the GLM from the prior
        """
        v = {}
        v['net'] = self.network.sample()
        v['glms'] =[]
        for n in range(self.N):
            xn = self.glm.sample()
            xn['n'] = n
            v['glms'].append(xn)

        return v

    def extract_vars(self, vals, n):
        """ Hacky helper function to extract the variables for only the
         n-th GLM.
        """

        newvals = {}
        for (k,v) in vals.items():
            if k=='glms':
                newvals['glm'] = v[n]
            else:
                newvals[k] = v
        return newvals

    def get_state(self):
        """ Get the 'state' of the system in symbolic Theano variables
        """
        state = {}
        state['net'] = self.network.get_state()
        state['glm'] = self.glm.get_state()

        return state

    def set_data(self, data):
        """
        Condition on the data
        """
        self.network.set_data(data)
        self.glm.set_data(data)

    def simulate(self, vars,  (T_start,T_stop), dt):
        """ Simulate spikes from a network of coupled GLMs
        :param vars - the variables corresponding to each GLM
        :type vars    list of N variable vectors
        :param dt    - time steps to simulate

        :rtype TxN matrix of spike counts in each bin
        """
        # Initialize the background rates
        N = self.model['N']
        t = np.arange(T_start, T_stop, dt)
        t_ind = np.arange(int(T_start/dt), int(T_stop/dt))
        assert len(t) == len(t_ind)
        nT = len(t)

        # Get set of symbolic variables
        syms = self.get_variables()

        # Initialize the background rate
        X = np.zeros((nT,N))
        for n in np.arange(N):
            nvars = self.extract_vars(vars, n)
            X[:,n] = seval(self.glm.bias_model.I_bias,
                           syms,
                           nvars)

        # Add stimulus induced currents if given
        for n in np.arange(N):
            nvars = self.extract_vars(vars, n)
            X[:,n] += seval(self.glm.bkgd_model.I_stim,
                            syms,
                            nvars)

        print "Max background rate: %s" % str(self.glm.nlin_model.f_nlin(np.amax(X)))

        # Get the impulse response functions
        imps = []
        for n_post in np.arange(N):
            nvars = self.extract_vars(vars, n_post)
            imps.append(seval(self.glm.imp_model.impulse,
                                  syms,
                                  nvars))
        imps = np.transpose(np.array(imps), axes=[1,0,2])
        T_imp = imps.shape[2]

        # Debug: compute effective weights
        # tt_imp = dt*np.arange(T_imp)
        # Weff = np.trapz(imps, tt_imp, axis=2)
        # print "Effective impulse weights: "
        # print Weff

        # Iterate over each time step and generate spikes
        S = np.zeros((nT,N))
        acc = np.zeros(N)
        thr = -np.log(np.random.rand(N))

        # TODO: Handle time-varying weights appropriately
        time_varying_weights = False
        if not time_varying_weights:
            At = np.tile(np.reshape(seval(self.network.graph.A,
                                          syms['net'],
                                          vars['net']),
                                    [N,N,1]),
                         [1,1,T_imp])

            Wt = np.tile(np.reshape(seval(self.network.weights.W,
                                          syms['net'],
                                          vars['net']),
                                    [N,N,1]),
                         [1,1,T_imp])

        # Count the number of exceptions arising from more spikes per bin than allowable
        n_exceptions = 0
        for t in np.arange(nT):
            # Update accumulator
            if np.mod(t,10000)==0:
                print "Iteration %d" % t
            # TODO Handle nonlinearities with variables
            #lam = np.array(map(lambda n: self.glm.nlin_model.f_nlin(X[t,n]),
            #               np.arange(N)))
            lam = self.glm.nlin_model.f_nlin(X[t,:])
            acc = acc + lam*dt

            # Spike if accumulator exceeds threshold
            i_spk = acc > thr
            S[t,i_spk] += 1
            n_spk = np.sum(i_spk)

            # Compute the length of the impulse response
            t_imp = np.minimum(nT-t-1,T_imp)

            # Get the instantaneous connectivity
            if time_varying_weights:
                # TODO: Really get the time-varying weights
                At = np.tile(np.reshape(seval(self.network.graph.A,
                                              syms['net'],
                                              vars['net']),
                                        [N,N,1]),
                             [1,1,t_imp])

                Wt = np.tile(np.reshape(seval(self.network.weights.W,
                                              syms['net'],
                                              vars['net']),
                                        [N,N,1]),
                             [1,1,t_imp])

            # Iterate until no more spikes
            # Cap the number of spikes in a time bin
            max_spks_per_bin = 10
            while n_spk > 0:
                if np.any(S[t,:] >= max_spks_per_bin):
                    #print "Limiting to at most %d spikes in time bin %d" % \
                    #      (max_spks_per_bin, t)
                    n_exceptions += 1
                    break
                # Add weighted impulse response to activation of other neurons)
                X[t+1:t+t_imp+1,:] += np.sum(At[i_spk,:,:t_imp] *
                                             Wt[i_spk,:,:t_imp] *
                                             imps[i_spk,:,:t_imp],0).T

                # Subtract threshold from the accumulator
                acc -= thr*i_spk
                acc[acc<0] = 0

                # Set new threshold after spike
                thr[i_spk] = -np.log(np.random.rand(n_spk))

                i_spk = acc > thr
                S[t,i_spk] += 1
                n_spk = np.sum(i_spk)

                #if np.any(S[t,:]>10):
                #    import pdb
                #    pdb.set_trace()
                #    raise Exception("More than 10 spikes in a bin! Decrease variance on impulse weights or decrease simulation bin width.")
                
        # DEBUG:
        tt = dt * np.arange(nT)
        lam = np.zeros_like(X)
        for n in np.arange(N):
            lam[:,n] = self.glm.nlin_model.f_nlin(X[:,n])
            
        print "Max firing rate (post sim): %f" % np.max(lam)
        E_nS = np.trapz(lam,tt,axis=0)
        nS = np.sum(S,0)

        print "Sampled %s spikes." % str(nS)
        print "Expected %s spikes." % str(E_nS)
        # import pdb; pdb.set_trace()

        if np.any(np.abs(nS-E_nS) > 3*np.sqrt(E_nS)):
            print "ERROR: Actual num spikes (%s) differs from expected (%s) by >3 std." % (str(nS),str(E_nS))

        print "Number of exceptions arising from multiple spikes per bin: %d" % n_exceptions

        return S,X