def test_run():
    from numpy import random
    random.seed(0)
    tl = Timeline()
    dummy = Dummy("dummy", tl)
    times = random.randint(0, 20, 200)
    priorities = random.randint(0, 20, 200)

    for t, p in zip(times, priorities):
        process = Process(dummy, "op", [])
        e = Event(t, process, p)
        tl.schedule(e)

    tl.init()
    tl.run()

    assert dummy.counter == 200

    tl = Timeline(5)
    for t, p in zip(times, priorities):
        process = Process(dummy, "op", [])
        e = Event(t, process, p)
        tl.schedule(e)

    tl.init()
    tl.run()

    assert tl.now() == tl.time < 5 and len(tl.events) > 0
def test_remove_event():
    tl = Timeline()
    dummy = Dummy('1', tl)
    event = Event(1, Process(dummy, 'op', []))
    d2 = Dummy('2', tl)
    event2 = Event(1, Process(d2, 'op', []))
    tl.schedule(event)
    tl.schedule(event2)
    tl.init()
    assert dummy.counter == 0 and d2.counter == 0
    tl.remove_event(event)
    tl.run()
    assert dummy.counter == 0 and d2.counter == 1
def test_update_event_time():
    tl = Timeline()
    d1 = Dummy('1', tl)
    event1 = Event(10, Process(d1, 'click', []))
    d2 = Dummy('2', tl)
    event2 = Event(10, Process(d2, 'click', []))

    tl.schedule(event1)
    tl.schedule(event2)
    tl.init()
    assert d1.click_time is None and d2.click_time is None
    tl.update_event_time(event2, 20)
    tl.run()

    assert d1.click_time == 10 and d2.click_time == 20
Beispiel #4
0
def test_BB84_time_bin():
    tl = Timeline(1e12)  # stop time is 1 s

    alice = QKDNode("alice", tl, encoding=time_bin, stack_size=1)
    bob = QKDNode("bob", tl, encoding=time_bin, stack_size=1)
    pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])

    qc = QuantumChannel("qc", tl, distance=10e3, polarization_fidelity=0.99, attenuation=0.00002)
    qc.set_ends(alice, bob)
    cc = ClassicalChannel("cc", tl, distance=10e3)
    cc.set_ends(alice, bob)

    # Parent
    pa = Parent(alice, 128, "alice")
    pb = Parent(bob, 128, "bob")
    alice.protocol_stack[0].upper_protocols.append(pa)
    pa.lower_protocols.append(alice.protocol_stack[0])
    bob.protocol_stack[0].upper_protocols.append(pb)
    pb.lower_protocols.append(bob.protocol_stack[0])

    process = Process(pa, "push", [])
    event = Event(0, process)
    tl.schedule(event)

    tl.init()
    tl.run()
    assert pa.counter == pb.counter == 10
Beispiel #5
0
def test_MemoryWithRandomCoherenceTime__schedule_expiration():
    NUM_TRIALS = 200
    coherence_period_avg = 1
    coherence_period_stdev = 0.15
    tl = Timeline()
    mem = MemoryWithRandomCoherenceTime(
        "mem",
        tl,
        fidelity=1,
        frequency=0,
        efficiency=1,
        coherence_time=coherence_period_avg,
        coherence_time_stdev=coherence_period_stdev,
        wavelength=500)
    parent = DumbParent(mem)

    times_of_expiration_calculated = [0]
    np.random.seed(2)
    for i in range(NUM_TRIALS):
        times_of_expiration_calculated.append(
            times_of_expiration_calculated[-1] +
            int(mem.coherence_time_distribution() * 1e12))
    times_of_expiration_calculated.pop(0)

    np.random.seed(2)
    process = Process(mem, "update_state",
                      [[complex(math.sqrt(1 / 2)),
                        complex(math.sqrt(1 / 2))]])
    for i in range(NUM_TRIALS):
        event = Event(tl.now(), process)
        tl.schedule(event)
        tl.init()
        tl.run()
        assert times_of_expiration_calculated[i] == tl.now()

    period_sum = times_of_expiration_calculated[0]
    period_squared_sum = times_of_expiration_calculated[0]**2
    for i in range(1, len(times_of_expiration_calculated)):
        period = times_of_expiration_calculated[
            i] - times_of_expiration_calculated[i - 1]
        period_sum += period
        period_squared_sum += period * period

    avg_simulated = period_sum / NUM_TRIALS * 1e-12
    stdev_simulated = np.sqrt(
        (period_squared_sum - period_sum * period_sum * 1.0 / NUM_TRIALS) /
        NUM_TRIALS) * 1e-12

    #check that values in series are different
    assert stdev_simulated > 0.0
    #probability of error below is less then 0.3%
    assert abs(avg_simulated - coherence_period_avg
               ) < 3 * coherence_period_stdev / np.sqrt(NUM_TRIALS)
    def start(self):
        now = self.node.timeline.now()
        nm = self.node.network_manager
        nm.request(node2,
                   start_time=(now + 1e12),
                   end_time=(now + 2e12),
                   memory_size=self.memory_size,
                   target_fidelity=self.target_fidelity)

        # schedule future start
        process = Process(self, "start", [])
        event = Event(now + 2e12, process)
        self.node.timeline.schedule(event)
def test_cascade_run():
    KEYSIZE = 512
    KEYNUM = 10

    tl = Timeline(1e11)

    alice = QKDNode("alice", tl)
    bob = QKDNode("bob", tl)
    pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])
    pair_cascade_protocols(alice.protocol_stack[1], bob.protocol_stack[1])

    qc0 = QuantumChannel("qc0",
                         tl,
                         distance=1e3,
                         attenuation=2e-5,
                         polarization_fidelity=0.97)
    qc1 = QuantumChannel("qc1",
                         tl,
                         distance=1e3,
                         attenuation=2e-5,
                         polarization_fidelity=0.97)
    qc0.set_ends(alice, bob)
    qc1.set_ends(bob, alice)
    cc0 = ClassicalChannel("cc0", tl, distance=1e3)
    cc1 = ClassicalChannel("cc1", tl, distance=1e3)
    cc0.set_ends(alice, bob)
    cc1.set_ends(bob, alice)

    # Parent
    pa = Parent(alice, KEYSIZE, KEYNUM)
    pb = Parent(bob, KEYSIZE, KEYNUM)
    alice.protocol_stack[1].upper_protocols.append(pa)
    pa.lower_protocols.append(alice.protocol_stack[1])
    bob.protocol_stack[1].upper_protocols.append(pb)
    pb.lower_protocols.append(bob.protocol_stack[1])

    process = Process(pa, "push", [])
    event = Event(0, process)
    tl.schedule(event)

    tl.init()
    tl.run()

    assert pa.counter == pb.counter == KEYNUM
    for k1, k2 in zip(pa.keys, pb.keys):
        assert k1 == k2
        assert k1 < 2**KEYSIZE  # check that key is not too large
    assert alice.protocol_stack[1].error_bit_rate == 0
Beispiel #8
0
def test_run():
    class Dummy():
        def __init__(self):
            self.counter = 0

        def add(self, x):
            self.counter += x

        def minus(self, x):
            self.counter -= x

    a = Dummy()
    b = Dummy()
    p1 = Process(a, "add", [1])
    assert a.counter == 0 and b.counter == 0
    p1.run()
    assert a.counter == 1 and b.counter == 0
    p2 = Process(b, "minus", [10])
    assert a.counter == 1 and b.counter == 0
    p2.run()
    assert a.counter == 1 and b.counter == -10
Beispiel #9
0
def test_Memory__schedule_expiration():
    tl = Timeline()
    mem = Memory("mem",
                 tl,
                 fidelity=1,
                 frequency=0,
                 efficiency=1,
                 coherence_time=1,
                 wavelength=500)
    parent = DumbParent(mem)

    process = Process(mem, "expire", [])
    event = Event(1e12, process)
    tl.schedule(event)
    mem.expiration_event = event

    mem._schedule_expiration()

    counter = 0
    for event in tl.events:
        if event.is_invalid():
            counter += 1
    assert counter == 1
Beispiel #10
0
        bob = QKDNode("bob", tl)
        for i in range(len(detector_params)):
            for name, param in detector_params[i].items():
                bob.update_detector_params(i, name, param)

        qc0.set_ends(alice, bob)
        qc1.set_ends(bob, alice)
        cc0.set_ends(alice, bob)
        cc1.set_ends(bob, alice)

        # BB84 config
        pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])
        # cascade config
        pair_cascade_protocols(alice.protocol_stack[1], bob.protocol_stack[1])

        process = Process(alice.protocol_stack[1], 'push',
                          [256, math.inf, 12e12])
        tl.schedule(Event(0, process))

        tl.init()
        tl.run()

        print("completed distance {}".format(distance))

        # log results
        bba = alice.protocol_stack[0]
        cascade_a = alice.protocol_stack[1]

        dist_list.append(distance)
        tp_list.append(cascade_a.throughput)
        key_error_list.append(cascade_a.error_bit_rate)
        latency_list.append(cascade_a.latency)
Beispiel #11
0
def test_ResourceManager2():
    from sequence.kernel.process import Process
    from sequence.kernel.event import Event
    from sequence.components.optical_channel import ClassicalChannel, QuantumChannel
    from sequence.topology.node import BSMNode
    from sequence.entanglement_management.generation import EntanglementGenerationA

    class TestNode(Node):
        def __init__(self, name, tl):
            Node.__init__(self, name, tl)
            self.memory_array = MemoryArray(name + ".MemoryArray",
                                            tl,
                                            num_memories=50)
            self.memory_array.owner = self
            self.resource_manager = ResourceManager(self)

        def receive_message(self, src: str, msg: "Message") -> None:
            if msg.receiver == "resource_manager":
                self.resource_manager.received_message(src, msg)
            else:
                if msg.receiver is None:
                    matching = [
                        p for p in self.protocols
                        if type(p) == msg.protocol_type
                    ]
                    for p in matching:
                        p.received_message(src, msg)
                else:
                    for protocol in self.protocols:
                        if protocol.name == msg.receiver:
                            protocol.received_message(src, msg)
                            break

        def get_idle_memory(self, info):
            pass

    def eg_rule_condition(memory_info, manager):
        if memory_info.state == "RAW":
            return [memory_info]
        else:
            return []

    def eg_rule_action1(memories_info):
        def eg_req_func(protocols):
            for protocol in protocols:
                if isinstance(protocol, EntanglementGenerationA):
                    return protocol

        memories = [info.memory for info in memories_info]
        memory = memories[0]
        protocol = EntanglementGenerationA(None, "EGA." + memory.name,
                                           "mid_node", "node2", memory)
        protocol.primary = True
        return [protocol, ["node2"], [eg_req_func]]

    def eg_rule_action2(memories_info):
        memories = [info.memory for info in memories_info]
        memory = memories[0]
        protocol = EntanglementGenerationA(None, "EGA." + memory.name,
                                           "mid_node", "node1", memory)
        return [protocol, [None], [None]]

    tl = Timeline()

    node1, node2 = TestNode("node1", tl), TestNode("node2", tl)
    mid_node = BSMNode("mid_node", tl, [node1.name, node2.name])
    mid_node.bsm.detectors[0].efficiency = 1
    mid_node.bsm.detectors[1].efficiency = 1

    cc0 = ClassicalChannel("cc_n1_n2", tl, 0, 1e3)
    cc1 = ClassicalChannel("cc_n2_n1", tl, 0, 1e3)
    cc2 = ClassicalChannel("cc_n1_m", tl, 0, 1e3)
    cc3 = ClassicalChannel("cc_m_n1", tl, 0, 1e3)
    cc4 = ClassicalChannel("cc_n2_m", tl, 0, 1e3)
    cc5 = ClassicalChannel("cc_m_n2", tl, 0, 1e3)
    cc0.set_ends(node1, node2)
    cc1.set_ends(node2, node1)
    cc2.set_ends(node1, mid_node)
    cc3.set_ends(mid_node, node1)
    cc4.set_ends(node2, mid_node)
    cc5.set_ends(mid_node, node2)

    qc0 = QuantumChannel("qc_n1_m", tl, 0, 1e3, frequency=8e7)
    qc1 = QuantumChannel("qc_n2_m", tl, 0, 1e3, frequency=8e7)
    qc0.set_ends(node1, mid_node)
    qc1.set_ends(node2, mid_node)

    tl.init()
    rule1 = Rule(10, eg_rule_action1, eg_rule_condition)
    node1.resource_manager.load(rule1)
    rule2 = Rule(10, eg_rule_action2, eg_rule_condition)
    node2.resource_manager.load(rule2)

    process = Process(node1.resource_manager, "expire", [rule1])
    event = Event(10, process)
    tl.schedule(event)

    process = Process(node2.resource_manager, "expire", [rule2])
    event = Event(10, process)
    tl.schedule(event)

    tl.run()

    # for info in node1.resource_manager.memory_manager:
    #     print(info.memory.name, info.state, info.remote_memo)
    #
    # for info in node2.resource_manager.memory_manager:
    #     print(info.memory.name, info.state, info.remote_memo)

    for info in node1.resource_manager.memory_manager:
        assert info.state == "RAW"

    for info in node2.resource_manager.memory_manager:
        assert info.state == "RAW"

    assert len(node1.protocols) == len(node2.protocols) == 0
    assert len(node1.resource_manager.pending_protocols) == len(
        node2.resource_manager.pending_protocols) == 0
    assert len(node1.resource_manager.waiting_protocols) == len(
        node2.resource_manager.waiting_protocols) == 0
Beispiel #12
0
            "dark_count": dark_count,
            "time_resolution": 10
        }]
        bob = QKDNode("bob", tl, encoding=time_bin, stack_size=1)

        for i in range(len(detector_params)):
            for name, param in detector_params[i].items():
                bob.update_detector_params(i, name, param)

        qc.set_ends(alice, bob)
        cc.set_ends(alice, bob)

        # BB84
        pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])

        process = Process(alice.protocol_stack[0], "push", [256, 10, math.inf])
        event = Event(0, process)
        tl.schedule(event)

        tl.init()
        tl.run()

        bba = alice.protocol_stack[0]

        error = statistics.mean(bba.error_rates)
        throughput = statistics.mean(bba.throughputs)
        latency = bba.latency

        print("{} km:".format(distance))
        print("\tbb84 error:\t\t\t{}".format(error))
        print("\tbb84 throughput:\t{}".format(throughput))
    def __init__(self, tl: Timeline):
        self.opening = False
        self.timeline = tl

    def open(self) -> None:
        self.opening = True

    def close(self) -> None:
        self.opening = False


tl = Timeline()
store = Store(tl)

# open store at 7:00
open_proc = Process(store, 'open', [])
open_event = Event(7, open_proc)
tl.schedule(open_event)

tl.run()

print(tl.time, store.opening)

# close store at 19:00
close_proc = Process(store, 'close', [])
close_event = Event(19, close_proc)
tl.schedule(close_event)

tl.run()

print(tl.time, store.opening)
Beispiel #14
0
        qc.set_ends(alice, bob)
        cc.set_ends(alice, bob)

        # BB84 and cascade config
        pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])
        pair_cascade_protocols(alice.protocol_stack[1], bob.protocol_stack[1])

        # Parent
        pa = Parent(alice, KEYSIZE, KEYNUM)
        pb = Parent(bob, KEYSIZE, KEYNUM)
        alice.protocol_stack[1].upper_protocols.append(pa)
        pa.lower_protocols.append(alice.protocol_stack[1])
        bob.protocol_stack[1].upper_protocols.append(pb)
        pb.lower_protocols.append(bob.protocol_stack[1])

        process = Process(pa, "push", [])
        event = Event(0, process)
        tl.schedule(event)

        tl.init()
        tl.run()

        # get metrics
        bba = alice.protocol_stack[0]
        cascade_a = alice.protocol_stack[1]

        if bba.error_rates:
            error = statistics.mean(bba.error_rates)
        else:
            error = None
Beispiel #15
0
        }]
        bob = QKDNode("bob", tl, stack_size=1)

        for i in range(len(detector_params)):
            for name, param in detector_params[i].items():
                bob.update_detector_params(i, name, param)

        qc0.set_ends(alice, bob)
        qc1.set_ends(bob, alice)
        cc0.set_ends(alice, bob)
        cc1.set_ends(bob, alice)

        # BB84 config
        pair_bb84_protocols(alice.protocol_stack[0], bob.protocol_stack[0])

        process = Process(alice.protocol_stack[0], "push",
                          [256, math.inf, 6e12])
        event = Event(0, process)
        tl.schedule(event)

        tl.init()
        tl.run()

        print("completed distance {}".format(distance))

        # record metrics
        bba = alice.protocol_stack[0]

        dist_list.append(distance)
        tp_list.append(mean(bba.throughputs))
        error_rate_list.append(mean(bba.error_rates))
        latency_list.append(bba.latency)
Beispiel #16
0
    def init(self):
        pass

    def received_message(self, src: str, message: Message):
        assert message.msg_type == MsgType.PING
        print("node {} received ping message at time {}".format(
            self.own.name, self.own.timeline.now()))
        new_msg = Message(MsgType.PONG, self.other_name)
        self.own.send_message(self.other_node, new_msg)


if __name__ == "__main__":
    tl = Timeline(1e12)

    node1 = Node("node1", tl)
    node2 = Node("node2", tl)

    cc = ClassicalChannel("cc", tl, 1e3, 1e9)
    cc.set_ends(node1, node2)

    pingp = PingProtocol(node1, "pingp", "pongp", "node2")
    pongp = PongProtocol(node2, "pongp", "pingp", "node1")

    process = Process(pingp, "start", [])
    event = Event(0, process)
    tl.schedule(event)

    tl.init()
    tl.run()
from sequence.kernel.process import Process

class Store(object):
    def __init__(self, tl: Timeline):
        self.opening = False
        self.timeline = tl

    def open(self) -> None:
        self.opening = True
        process = Process(self, 'close', [])
        event = Event(self.timeline.now() + 12, process)
        self.timeline.schedule(event)

    def close(self) -> None:
        self.opening = False
        process = Process(self, 'open', [])
        event = Event(self.timeline.now() + 12, process)
        self.timeline.schedule(event)


tl = Timeline(60)
store = Store(tl)
print(tl.now())

process = Process(store, 'open', [])
event = Event(7, process)
tl.schedule(event)

tl.run()
print(store.opening)
Beispiel #18
0
    tl = Timeline(runtime)

    # nodes and hardware
    node1 = SenderNode("node1", tl)
    node2 = ReceiverNode("node2", tl)

    qc = QuantumChannel("qc", tl, attenuation=0, distance=1e3)
    qc.set_ends(node1, node2)

    # counter
    counter = Counter()
    node2.detector.attach(counter)

    # schedule events
    time_bin = int(1e12 / FREQUENCY)

    process1 = Process(node1.memory, "update_state",
                       [[complex(math.sqrt(1 / 2)),
                         complex(math.sqrt(1 / 2))]])
    process2 = Process(node1.memory, "excite", ["node2"])
    for i in range(NUM_TRIALS):
        event1 = Event(i * time_bin, process1)
        event2 = Event(i * time_bin + (time_bin / 2), process2)
        tl.schedule(event1)
        tl.schedule(event2)

    tl.init()
    tl.run()

    print("percent measured: {}%".format(100 * counter.count / NUM_TRIALS))
 def open(self) -> None:
     self.opening = True
     process = Process(self, 'close', [])
     event = Event(self.timeline.now() + 12, process)
     self.timeline.schedule(event)
 def close(self) -> None:
     self.opening = False
     process = Process(self, 'open', [])
     event = Event(self.timeline.now() + 12, process)
     self.timeline.schedule(event)