### Full W State Example Source: https://tqsd.github.io/QuNetSim/_sources/examples/send_w.rst.txt A complete implementation showing the setup of the EQSN backend, network initialization, and host configuration. ```python from qunetsim.backends import EQSNBackend from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Logger Logger.DISABLED = False def main(): network = Network.get_instance() nodes = ["Alice", "Bob", "Eve", "Dean"] back = EQSNBackend() 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() ``` -------------------------------- ### Full example: network setup and EPR exchange Source: https://tqsd.github.io/QuNetSim/examples/send_epr.html Complete example that sets up a three-node network (A, B, C), connects hosts, and runs the sender and receiver protocols for EPR pair exchange. Disables logging and starts the network before running the protocols. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Logger Logger.DISABLED = True def protocol_1(host, receiver): """ Sender protocol for sending 5 EPR pairs. Args: host (Host): The sender Host. receiver (str): The ID of the receiver of the EPR pairs. """ # Here we write the protocol code for a host. for i in range(5): print('Sending EPR pair %d' % (i + 1)) epr_id, ack_arrived = host.send_epr(receiver, await_ack=True) if ack_arrived: # Receiver got the EPR pair and ACK came back # safe to use the EPR pair. q = host.get_epr(receiver, q_id=epr_id) print('Host 1 measured: %d' % q.measure()) else: print('The EPR pair was not properly established') print('Sender protocol done') def protocol_2(host, sender): """ Receiver protocol for receiving 5 EPR pairs. Args: host (Host): The sender Host. sender (str): The ID of the sender of the EPR pairs. """ # Host 2 waits 5 seconds for the EPR to arrive. for _ in range(5): q = host.get_epr(sender, wait=5) # q is None if the wait time expired. if q is not None: print('Host 2 measured: %d' % q.measure()) else: print('Host 2 did not receive an EPR pair') print('Receiver protocol done') def main(): network = Network.get_instance() nodes = ['A', 'B', 'C'] network.start(nodes) 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,)) if __name__ == '__main__': main() ``` -------------------------------- ### Full example: send EPR pairs Source: https://tqsd.github.io/QuNetSim/_sources/examples/send_epr.rst.txt Complete example combining network setup, protocol definitions, and execution. Imports from qunetsim, disables logging, and runs the protocols. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Logger Logger.DISABLED = True def protocol_1(host, receiver): """ Sender protocol for sending 5 EPR pairs. Args: host (Host): The sender Host. receiver (str): The ID of the receiver of the EPR pairs. """ # Here we write the protocol code for a host. for i in range(5): print('Sending EPR pair %d' % (i + 1)) epr_id, ack_arrived = host.send_epr(receiver, await_ack=True) if ack_arrived: # Receiver got the EPR pair and ACK came back # safe to use the EPR pair. q = host.get_epr(receiver, q_id=epr_id) print('Host 1 measured: %d' % q.measure()) else: print('The EPR pair was not properly established') print('Sender protocol done') def protocol_2(host, sender): """ Receiver protocol for receiving 5 EPR pairs. Args: host (Host): The sender Host. sender (str): The ID of the sender of the EPR pairs. """ # Host 2 waits 5 seconds for the EPR to arrive. for _ in range(5): q = host.get_epr(sender, wait=5) # q is None if the wait time expired. if q is not None: print('Host 2 measured: %d' % q.measure()) else: print('Host 2 did not receive an EPR pair') print('Receiver protocol done') def main(): network = Network.get_instance() nodes = ['A', 'B', 'C'] network.start(nodes) 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,)) ``` -------------------------------- ### B92 QKD full example: imports and network setup Source: https://tqsd.github.io/QuNetSim/_sources/examples/QKD_B92.rst.txt Full B92 QKD example using QuNetSim. It imports the required components, disables logging, sets a wait time, defines Eve's sniffing function, and starts building the network with hosts Alice, Bob, and Eve. ```python # This example implements the B92 QKD protocol using the QuNetSim package from qunetsim.components import Host, Network from qunetsim.objects import Qubit from qunetsim.objects import Logger from random import randint, random Logger.DISABLED = True wait_time = 60 def eve_sniffing_quantum(sender, receiver, qubit): # Eve will manipulate only part of the qubits she intercepts # She chooses the base in which she measures at random. if sender == 'Alice': r = random() if r > 0.5: base = randint(0, 1) if base == 1: qubit.H() qubit.measure(non_destructive=True) def build_network_b92(eve_interception): network = Network.get_instance() nodes = ['Alice', 'Bob', 'Eve'] network.start(nodes) host_alice = Host('Alice') host_bob = Host('Bob') host_eve = Host('Eve') ``` -------------------------------- ### Set up network hosts Source: https://tqsd.github.io/QuNetSim/examples/QKD_BB84.html Adds three hosts to the network to set up the topology Alice <--> Bob <--> Eve. This is the initial setup for the QKD example. ```python network.add_host(host_alice) network.add_host(host_bob) network.add_host(host_eve) ``` -------------------------------- ### start() Source: https://tqsd.github.io/QuNetSim/components/host.html Starts the host. ```APIDOC ## start() ### Description Starts the host. ### Method start ### Parameters None ### Response No return value. ``` -------------------------------- ### start(nodes=None, backend=None) Source: https://tqsd.github.io/QuNetSim/components/network.html Starts the network. ```APIDOC ## start(nodes=None, backend=None) ### Description Starts the network. ### Method start ### Parameters - **nodes** (optional) - Not documented in source. - **backend** (optional) - Not documented in source. ``` -------------------------------- ### Install QuNetSim via pip Source: https://tqsd.github.io/QuNetSim/install.html Install the package using pip and use the template script to generate an example. ```bash pip install qunetsim ``` ```bash template ``` -------------------------------- ### Import libraries and configure QKD example Source: https://tqsd.github.io/QuNetSim/examples/QKD_BB84.html Imports the required libraries and sets up the QKD example: imports `numpy`, `random`, and the `qunetsim` components/objects, disables the logger, and sets `wait_time = 10`. ```python import numpy as np import random from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Qubit from qunetsim.objects import Logger Logger.DISABLED = True wait_time = 10 ``` -------------------------------- ### Full Linear Protocol Example Source: https://tqsd.github.io/QuNetSim/examples/send_data.html A complete implementation of the linear protocol style, including network setup, host configuration, and the qubit transmission loop. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Qubit 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) for _ in range(10): # 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_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') # Stop the network at the end of the example network.stop(stop_hosts=True) if __name__ == '__main__': main() ``` -------------------------------- ### Install QuNetSim on Windows Source: https://tqsd.github.io/QuNetSim/install.html Commands to clone the repository, set up a virtual environment, install dependencies, and run the templater script on Windows. ```bash git clone git@github.com:tqsd/QuNetSim.git ``` ```bash python3 -m venv venv .\venv\Scripts\activate python -m pip install --upgrade pip python -m pip install -r .\QuNetSim\requirements.txt ``` ```bash python3 .\QuNetSim\templater.py ``` ```bash python3 .py ``` -------------------------------- ### Full CHSH game example with backend setup Source: https://tqsd.github.io/QuNetSim/examples/chsh.html Complete CHSH game example that imports and sets up the backend (ProjectQ or EQSN) to support rotation operators. The code is displayed with line numbers in the source, but the code content is not fully visible in the provided text. ```python ``` -------------------------------- ### QuNetSim Network Template Example Source: https://tqsd.github.io/QuNetSim/_sources/quick_start.rst.txt A generated template file demonstrating protocol definitions and network setup for a 4-node fully connected network. ```python from qunetsim.components.host import Host from qunetsim.components.network import Network from qunetsim.objects import Qubit from qunetsim.objects import Logger Logger.DISABLED = True def protocol_1(host, receiver): # Here we write the protocol code for a host. for i in range(5): q = Qubit(host) # Apply Hadamard gate to the qubit q.H() print('Sending qubit %d.' % (i+1)) # Send qubit and wait for an acknowledgement host.send_qubit(receiver, q, await_ack=True) print('Qubit %d was received by %s.' % (i+1, receiver)) def protocol_2(host, sender): # Here we write the protocol code for another host. for _ in range(5): # Wait for a qubit from Alice for 10 seconds. q = host.get_qubit(sender, wait=10) # Measure the qubit and print the result. print('%s received a qubit in the %d state.' % (host.host_id, q.measure())) def main(): network = Network.get_instance() nodes = ['A', 'B', 'C', 'D'] network.start(nodes) host_A = Host('A') host_A.add_connection('B') host_A.add_connection('C') host_A.add_connection('D') host_A.start() host_B = Host('B') host_B.add_connection('A') host_B.add_connection('C') host_B.add_connection('D') host_B.start() host_C = Host('C') host_C.add_connection('A') host_C.add_connection('B') host_C.add_connection('D') host_C.start() host_D = Host('D') host_D.add_connection('A') host_D.add_connection('B') host_D.add_connection('C') host_D.start() network.add_host(host_A) network.add_host(host_B) network.add_host(host_C) network.add_host(host_D) host_A.run_protocol(protocol_1, (host_D.host_id,)) host_D.run_protocol(protocol_2, (host_A.host_id,)) if __name__ == '__main__': main() ``` -------------------------------- ### Install QuNetSim on Linux/Mac OS X Source: https://tqsd.github.io/QuNetSim/install.html Commands to clone the repository, set up a virtual environment, install dependencies, and run the templater script. ```bash git clone git@github.com:tqsd/QuNetSim.git ``` ```bash python3 -m venv venv source ./venv/bin/activate pip install --upgrade pip pip install -r ./QuNetSim/requirements.txt ``` ```bash export PYTHONPATH=$PYTHONPATH:$PWD/QuNetSim/ ``` ```bash python3 ./QuNetSim/templater.py ``` ```bash python3 .py ``` -------------------------------- ### Imports for entanglement routing example Source: https://tqsd.github.io/QuNetSim/_sources/examples/entanglement_routing.rst.txt Import the required modules for the example: Host, Network, Logger, networkx, and time. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Logger import networkx import time ``` -------------------------------- ### Full Entanglement Routing Implementation Source: https://tqsd.github.io/QuNetSim/examples/entanglement_routing.html A complete example showing the generation of entanglement, a custom routing algorithm using networkx, and the setup of a network with multiple hosts. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Logger import networkx import time def generate_entanglement(host): """ Generate entanglement if the host has nothing to process (i.e. is idle). """ while True: if host.is_idle(): host_connections = host.get_connections() for connection in host_connections: if connection['type'] == 'quantum': num_epr_pairs = len(host.get_epr_pairs(connection['connection'])) if num_epr_pairs < 4: host.send_epr(connection['connection'], await_ack=True) time.sleep(5) def routing_algorithm(di_graph, source, target): """ Entanglement based routing function. Note: any custom routing function must have exactly these three parameters and must return a list ordered by the steps in the route. Args: di_graph (networkx DiGraph): The directed graph representation of the network. source (str): The sender ID target (str: The receiver ID Returns: (list): The route ordered by the steps in the route. """ # Generate entanglement network entanglement_network = nx.DiGraph() nodes = di_graph.nodes() for node in nodes: host = network.get_host(node) host_connections = host.get_connections() for connection in host_connections: if connection['type'] == 'quantum': num_epr_pairs = len(host.get_epr_pairs(connection['connection'])) if num_epr_pairs == 0: entanglement_network.add_edge(host.host_id, connection['connection'], weight=1000) else: entanglement_network.add_edge(host.host_id, connection['connection'], weight=1. / num_epr_pairs) try: route = nx.shortest_path(entanglement_network, source, target, weight='weight') print('-------' + str(route) + '-------') return route except Exception as e: Logger.get_instance().error(e) def main(): network = Network.get_instance() network.quantum_routing_algo = routing_algorithm nodes = ['A', 'node_1', 'node_2', 'B'] network.use_hop_by_hop = False network.set_delay = 0.2 network.start(nodes) A = Host('A') A.add_connection('node_1') A.add_connection('node_2') A.start() node_1 = Host('node_1') node_1.add_connection('A') node_1.add_connection('B') node_1.start() node_2 = Host('node_2') node_2.add_connection('A') node_2.add_connection('B') node_2.start() B = Host('B') B.add_connection('node_1') B.add_connection('node_2') B.start() hosts = [A, node_1, node_2, B] for h in hosts: network.add_host(h) node_1.run_protocol(generate_entanglement) node_2.run_protocol(generate_entanglement) print('---- BUILDING ENTANGLEMENT ----') # Let the network build up entanglement time.sleep(15) print('---- DONE BUILDING ENTANGLEMENT ----') choices = ['00', '11', '10', '01'] for _ in range(5): print('---- sending superdense ----') A.send_superdense(B.host_id, random.choice(choices), await_ack=True) time.sleep(1) # Let the network run for 40 seconds time.sleep(40) print('stopping') network.stop(stop_hosts=True) ``` -------------------------------- ### Full example: send data qubits from Alice to Dean Source: https://tqsd.github.io/QuNetSim/_sources/examples/send_data.rst.txt Complete runnable example that configures the network and sends 10 qubits from Alice to Dean. It includes imports, network delay setting, and the sending loop. The send_qubit call uses await_ack=True but ignores the ACK boolean. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Qubit 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) for _ in range(10): # 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_qubit('Alice', q_id) ``` -------------------------------- ### Expected output of the eavesdropping example Source: https://tqsd.github.io/QuNetSim/_sources/examples/packet_sniffing.rst.txt Shows the expected console output when running the example. Classical messages are prefixed with '** Bob was here :) **' and qubits are measured as 0 due to Bob's X operation. ```bash Alice sends: Hi Eve. Eve Received classical: ** Bob was here :) ** Hi Eve.. Alice sends: Hi Eve. Eve Received classical: ** Bob was here :) ** Hi Eve.. Alice sends: Hi Eve. Eve Received classical: ** Bob was here :) ** Hi Eve.. Alice sends: Hi Eve. Eve Received classical: ** Bob was here :) ** Hi Eve.. Alice sends: Hi Eve. Eve Received classical: ** Bob was here :) ** Hi Eve.. Alice sends qubit in the |1> state Eve measured: 0. Alice sends qubit in the |1> state Eve measured: 0. Alice sends qubit in the |1> state Eve measured: 0. Alice sends qubit in the |1> state Eve measured: 0. Alice sends qubit in the |1> state Eve measured: 0. ``` -------------------------------- ### Full eavesdropping example with imports and Logger disabled Source: https://tqsd.github.io/QuNetSim/_sources/examples/packet_sniffing.rst.txt Complete runnable example that includes imports, disables the logger, and defines all functions. It uses 'amount_transmit' instead of 'amount_to_transmit' and includes a type check for Message in the classical sniffing function. ```python from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Message from qunetsim.objects import Qubit from qunetsim.objects import Logger Logger.DISABLED = True amount_transmit = 5 def alice(host): for _ in range(amount_transmit): s = 'Hi Eve.' print("Alice sends: %s" % s) host.send_classical('Eve', s, await_ack=True) for _ in range(amount_transmit): print("Alice sends qubit in the |1> state") q = Qubit(host) q.X() host.send_qubit('Eve', q, await_ack=True) def bob_sniffing_quantum(sender, receiver, qubit): # Bob applies an X operation to all qubits that are routed through him qubit.X() def bob_sniffing_classical(sender, receiver, msg): # Bob modifies the message content of all classical messages routed through him if isinstance(msg, Message): msg.content = "** Bob was here :) ** " + msg.content ``` -------------------------------- ### Full Example for Anonymous Transfer Protocol in QuNetSim Source: https://tqsd.github.io/QuNetSim/_sources/examples/anonymous_transfer.rst.txt Complete QuNetSim example implementing the anonymous transfer protocol. It defines functions for distribution, sending, receiving, and intermediate nodes, plus the main function that sets up the network and hosts. It requires the QuNetSim library. ```python import time from qunetsim.components import Host from qunetsim.components import Network import random from qunetsim.objects import Qubit def distribute(host, nodes): # distribute=True => sender doesn't keep part of the GHZ host.send_ghz(nodes, distribute=True) def sender(host, distributor, r, epr_id): q = host.get_ghz(distributor, wait=10) b = random.choice(['0', '1']) host.send_broadcast(b) if b == '1': q.Z() host.add_epr(r, q, q_id=epr_id) sending_qubit = Qubit(host) sending_qubit.X() print('Sending %s' % sending_qubit.id) # Generate EPR if none shouldn't change anything, but if there is # no shared entanglement between s and r, then there should # be a mistake in the protocol host.send_teleport(r, sending_qubit, generate_epr_if_none=False, await_ack=False) host.empty_classical() def receiver(host, distributor, s, epr_id): q = host.get_ghz(distributor, wait=10) b = random.choice(['0', '1']) host.send_broadcast(b) messages = [] # Await broadcast messages from all parties while len(messages) < 3: messages = host.classical messages = [x for x in messages if x.content != 'ACK'] time.sleep(0.5) print([m.content for m in messages]) parity = int(b) for m in messages: if m.sender != s: parity = parity ^ int(m.content) if parity == 1: q.Z() print('established secret EPR') host.add_epr(s, q, q_id=epr_id) q = host.get_qubit(s, wait=10) host.empty_classical() print('Received qubit %s in the %d state' % (q.id, q.measure())) def node(host, distributor): q = host.get_ghz(distributor, wait=10) if q is None: print('failed') return q.H() m = q.measure() host.send_broadcast(str(m)) def main(): network = Network.get_instance() nodes = ['A', 'B', 'C', 'D', 'E'] network.start(nodes) host_A = Host('A') host_A.add_connections(['B', 'C', 'D', 'E']) host_A.start() host_B = Host('B') host_B.add_c_connections(['C', 'D', 'E']) host_B.start() host_C = Host('C') host_C.add_c_connections(['B', 'D', 'E']) host_C.start() host_D = Host('D') host_D.add_c_connections(['B', 'C', 'E']) host_D.start() host_E = Host('E') host_E.add_c_connections(['B', 'C', 'D']) host_E.start() network.add_hosts([host_A, host_B, host_C, host_D, host_E]) ``` -------------------------------- ### Entanglement routing example: generate_entanglement, routing_algorithm, and main() Source: https://tqsd.github.io/QuNetSim/_sources/examples/entanglement_routing.rst.txt These three functions form the complete entanglement routing example: a background protocol that generates EPR pairs when a host is idle, a custom routing algorithm that builds a weighted entanglement network and uses nx.shortest_path, and a main() that sets up a 4-node network, runs the protocol, and sends superdense-coded messages. The routing function must accept exactly (di_graph, source, target) and return a route list; the example uses network.quantum_routing_algo, use_hop_by_hop=False, and set_delay=0.2. ```python def generate_entanglement(host): """ Generate entanglement if the host has nothing to process (i.e. is idle). """ while True: if host.is_idle(): host_connections = host.get_connections() for connection in host_connections: if connection['type'] == 'quantum': num_epr_pairs = len(host.get_epr_pairs(connection['connection'])) if num_epr_pairs < 4: host.send_epr(connection['connection'], await_ack=True) time.sleep(5) ``` ```python def routing_algorithm(di_graph, source, target): """ Entanglement based routing function. Note: any custom routing function must have exactly these three parameters and must return a list ordered by the steps in the route. Args: di_graph (networkx DiGraph): The directed graph representation of the network. source (str): The sender ID target (str: The receiver ID Returns: (list): The route ordered by the steps in the route. """ # Generate entanglement network entanglement_network = nx.DiGraph() nodes = di_graph.nodes() for node in nodes: host = network.get_host(node) host_connections = host.get_connections() for connection in host_connections: if connection['type'] == 'quantum': num_epr_pairs = len(host.get_epr_pairs(connection['connection'])) if num_epr_pairs == 0: entanglement_network.add_edge(host.host_id, connection['connection'], weight=1000) else: entanglement_network.add_edge(host.host_id, connection['connection'], weight=1. / num_epr_pairs) try: route = nx.shortest_path(entanglement_network, source, target, weight='weight') print('-------' + str(route) + '-------') return route except Exception as e: Logger.get_instance().error(e) ``` ```python def main(): network = Network.get_instance() network.quantum_routing_algo = routing_algorithm nodes = ['A', 'node_1', 'node_2', 'B'] network.use_hop_by_hop = False network.set_delay = 0.2 network.start(nodes) A = Host('A') A.add_connection('node_1') A.add_connection('node_2') A.start() node_1 = Host('node_1') node_1.add_connection('A') node_1.add_connection('B') node_1.start() node_2 = Host('node_2') node_2.add_connection('A') node_2.add_connection('B') node_2.start() B = Host('B') B.add_connection('node_1') B.add_connection('node_2') B.start() hosts = [A, node_1, node_2, B] for h in hosts: network.add_host(h) node_1.run_protocol(generate_entanglement) node_2.run_protocol(generate_entanglement) print('---- BUILDING ENTANGLEMENT ----') # Let the network build up entanglement time.sleep(15) print('---- DONE BUILDING ENTANGLEMENT ----') choices = ['00', '11', '10', '01'] for _ in range(5): print('---- sending superdense ----') A.send_superdense(B.host_id, random.choice(choices), await_ack=True) time.sleep(1) # Let the network run for 40 seconds time.sleep(40) print('stopping') network.stop(stop_hosts=True) ``` -------------------------------- ### Network Configuration Source: https://tqsd.github.io/QuNetSim/examples/entanglement_routing.html Initializes the network nodes and connections for the entanglement routing example. ```python nodes = ['A', 'node_1', 'node_2', 'B'] network.use_hop_by_hop = False network.set_delay = 0.1 network.start(nodes) A = Host('A') A.add_connection('node_1') A.add_connection('node_2') A.start() node_1 = Host('node_1') node_1.add_connection('A') node_1.add_connection('B') node_1.start() node_2 = Host('node_2') node_2.add_connection('A') node_2.add_connection('B') node_2.start() B = Host('B') B.add_connection('node_1') B.add_connection('node_2') B.start() hosts = [A, node_1, node_2, B] for h in hosts: network.add_host(h) ``` -------------------------------- ### Full W State Distribution Example Source: https://tqsd.github.io/QuNetSim/examples/send_w.html A complete script setting up the network, configuring hosts, distributing the W state, and performing measurements. ```python from qunetsim.backends import EQSNBackend from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Logger Logger.DISABLED = False def main(): network = Network.get_instance() nodes = ["Alice", "Bob", "Eve", "Dean"] back = EQSNBackend() 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, ack_received = host_alice.send_w(share_list, await_ack=True) print("Alice received ACK from all? " + str(ack_received)) q1 = host_alice.get_w('Alice', q_id1, wait=10) q2 = host_bob.get_w('Alice', q_id1, wait=10) q3 = host_eve.get_w('Alice', q_id1, wait=10) q4 = host_dean.get_w('Alice', q_id1, wait=10) print("System density matrix:") print(q1._qubit[0].data) m1 = q1.measure() m2 = q2.measure() m3 = q3.measure() m4 = q4.measure() print("\nResults of measurements are %d, %d, %d, %d." % (m1, m2, m3, m4)) network.stop(True) exit() if __name__ == '__main__': main() ``` -------------------------------- ### Set up network with three nodes Source: https://tqsd.github.io/QuNetSim/_sources/examples/send_epr.rst.txt Creates a network with nodes A, B, and C, adds connections, and starts hosts. The network is a line A<==>B<==>C with both classical and quantum connections. ```python network = Network.get_instance() nodes = ['A', 'B', 'C'] network.start(nodes) 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) # Network is A<==>B<==>C; # Note: we use 'A<==>B' to represent a classical and quantum connection # we use 'A<-->B' to represent a classical only connection # we use 'A<~~>B' to represent a quantum only connection # All connections are added uni-directionally, so '<' and '>' # represent the direction of the flow of traffic. ``` -------------------------------- ### Configure Network and Hosts Source: https://tqsd.github.io/QuNetSim/examples/send_data.html Initializes the network instance and sets up four hosts with connections forming a linear topology: Alice <==> Bob <==> Eve <==> Dean. ```python network = Network.get_instance() nodes = ["Alice", "Bob", "Eve", "Dean"] 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.add_connection('Dean') host_eve.start() host_dean = Host('Dean') host_dean.add_connection('Eve') host_dean.start() # Network will be: # Alice <==> Bob <==> Eve <==> Dean # Note: we use 'A<==>B' to represent a classical and quantum connection # we use 'A<-->B' to represent a classical only connection # we use 'A<~~>B' to represent a quantum only connection # All connections are added uni-directionally, so '<' and '>' ``` -------------------------------- ### Full BB84 QKD Example Source: https://tqsd.github.io/QuNetSim/_sources/examples/QKD_BB84.rst.txt The full BB84 QKD example with Alice and Eve. It includes the encryption/decryption functions, the QKD protocol, and the message sending functions. The source states this is the full example below the previous fragments. ```python import numpy as np import random from qunetsim.components import Host from qunetsim.components import Network from qunetsim.objects import Qubit from qunetsim.objects import Logger Logger.DISABLED = True wait_time = 10 # !! Warning: this Crypto algorithm is really bad! # !! Warning: Do not use it as a real Crypto Algorithm! # key has to be a string def encrypt(key, text): encrypted_text = "" for char in text: encrypted_text += chr(ord(key) ^ ord(char)) return encrypted_text def decrypt(key, encrypted_text): return encrypt(key, encrypted_text) def alice_qkd(alice, msg_buff, secret_key, receiver): sequence_nr = 0 # iterate over all bits in the secret key. for bit in secret_key: ack = False while not ack: print("Alice sent %d key bits" % (sequence_nr + 1)) # get a random base. 0 for Z base and 1 for X base. base = random.randint(0, 1) # create qubit q_bit = Qubit(alice) # Set qubit to the bit from the secret key. if bit == 1: q_bit.X() # Apply basis change to the bit if necessary. if base == 1: q_bit.H() # Send Qubit to Bob alice.send_qubit(receiver, q_bit, await_ack=True) # Get measured basis of Bob message = alice.get_next_classical_message(receiver, msg_buff, sequence_nr) ``` -------------------------------- ### Initialize QuNetSim network with hosts Alice, Bob, and Eve Source: https://tqsd.github.io/QuNetSim/_sources/examples/packet_sniffing.rst.txt Sets up the network and hosts. Alice connects to Bob, Bob connects to Alice and Eve, and Eve connects to Bob. Eve has a delay of 0.2. This is the first step in the eavesdropping example. ```python network = Network.get_instance() nodes = ["Alice", "Bob", "Eve"] network.start(nodes) network.delay = 0.0 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.delay = 0.2 host_eve.start() network.add_host(host_alice) network.add_host(host_bob) network.add_host(host_eve) ``` -------------------------------- ### Main network setup with sniffing Source: https://tqsd.github.io/QuNetSim/_sources/examples/packet_sniffing.rst.txt Sets up the network with Alice, Bob, and Eve. Bob is configured with quantum and classical relay sniffing functions. Alice runs the alice protocol and Eve runs the eve protocol, then the network stops. ```python def main(): network = Network.get_instance() nodes = ["Alice", "Bob", "Eve"] network.start(nodes) network.delay = 0.0 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.delay = 0.2 host_eve.start() network.add_host(host_alice) network.add_host(host_bob) network.add_host(host_eve) host_bob.q_relay_sniffing = True host_bob.q_relay_sniffing_fn = eve_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() ``` -------------------------------- ### Initialize EQSN Backend Source: https://tqsd.github.io/QuNetSim/_sources/backends.rst.txt Example of explicitly setting the EQSN backend by creating a backend object and passing it to the network and host instances. ```python import numpy as np # import the eqsn backend from qunetsim.backends import EQSNBackend # create the EQSN backend object backend = EQSNBackend() # Initialize a network and define the host IDs in the network network = Network.get_instance() nodes = ['Alice', 'Bob', 'Eve'] # Start the network with the hosts and explicitly set the backend network.start(nodes, backend) # Initialize the host Alice with the right backend host_alice = Host('Alice', backend) host_alice.add_connection('Bob') host_alice.start() # Initialize the host Bob with the right backend host_bob = Host('Bob', backend) host_bob.add_connection('Alice') host_bob.add_connection('Eve') host_bob.start() # Initialize the host Eve with the right backend host_eve = Host('Eve', backend) host_eve.add_connection('Bob') host_eve.start() # Add the hosts to the network network.add_host(host_alice) network.add_host(host_bob) network.add_host(host_eve) ``` -------------------------------- ### Initialize QuNetSim network with three hosts Source: https://tqsd.github.io/QuNetSim/_sources/examples/QKD_BB84.rst.txt Sets up a three-party QuNetSim network with hosts Alice, Bob, and Eve. Alice connects to Bob, Bob connects to both Alice and Eve, and Eve connects to Bob, forming a linear topology. The network is started and all hosts are added before any QKD protocol runs. ```python import numpy as np # Initialize a network network = Network.get_instance() # Define the host IDs in the network nodes = ['Alice', 'Bob', 'Eve'] # 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) ``` -------------------------------- ### host_id (property) Source: https://tqsd.github.io/QuNetSim/components/host.html Get the host_id of the host. ```APIDOC ## host_id (property) ### Description Get the host_id of the host. ### Method N/A (SDK property) ### Returns - (str) - The host ID of the host. ``` -------------------------------- ### quantum_connections (property) Source: https://tqsd.github.io/QuNetSim/components/host.html Get the quantum connections for the host. ```APIDOC ## quantum_connections (property) ### Description Get the quantum connections for the host. ### Method N/A (SDK property) ### Returns - (dict) - The quantum connections for the host. ``` -------------------------------- ### Initialize Network Hosts and Connections Source: https://tqsd.github.io/QuNetSim/_sources/examples/send_epr.rst.txt Configures three hosts (A, B, and C) with specific network connections and adds them to the network simulation. ```python 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) ``` -------------------------------- ### sender property Source: https://tqsd.github.io/QuNetSim/objects/routing_packet.html Gets the sender ID of the packet. ```APIDOC ## sender property ### Description Returns the sender ID of the packet. ### Returns - **sender** (str) - The sender ID of the packet. ``` -------------------------------- ### route property Source: https://tqsd.github.io/QuNetSim/objects/routing_packet.html Gets the route the packet should take. ```APIDOC ## route property ### Description Returns the route the packet should take. ### Returns - **route** (list) - A list of host IDs which the packet will travel. ``` -------------------------------- ### receiver property Source: https://tqsd.github.io/QuNetSim/objects/routing_packet.html Gets the receiver ID of the packet. ```APIDOC ## receiver property ### Description Returns the receiver ID of the packet. ### Returns - **receiver** (str) - The receiver ID of the packet. ``` -------------------------------- ### delay (property) Source: https://tqsd.github.io/QuNetSim/components/host.html Gets the delay of the queue processor. ```APIDOC ## delay (property) ### Description Get the delay of the queue processor. ### Returns The delay per tick for the queue processor (float). ```