Beispiel #1
0
def main():
    topoMatrix = BuildMatrix()
    topo = Topology()
    topo.GenTopoFromMatrix(topoMatrix, 6, Node, Link)
    routing = Routing(topo)
    routing.BFS()
    for path in routing.pathList:
        print path, "\t", routing.pathList[path]
Beispiel #2
0
    def __init__(self, runNum=None, failIfNotInit=False):

        if failIfNotInit and not self._init:
            raise EnvironmentError('SimEngine singleton not initialized.')

        #===== start singleton
        if self._init:
            return
        self._init = True
        #===== end singleton

        # store params
        self.runNum = runNum

        # local variables
        self.dataLock = threading.RLock()
        self.pauseSem = threading.Semaphore(0)
        self.simPaused = False
        self.goOn = True
        self.asn = 0
        self.startCb = []
        self.endCb = []
        self.events = []
        self.settings = SimSettings.SimSettings()
        self.propagation = Propagation.Propagation()
        self.motes = [Mote.Mote(id) for id in range(self.settings.numMotes)]
        self.topology = Topology.Topology(self.motes)
        self.topology.createTopology()

        # boot all motes
        for i in range(len(self.motes)):
            self.motes[i].boot()

        self.initTimeStampTraffic = 0
        self.endTimeStampTraffic = 0

        # initialize parent class
        threading.Thread.__init__(self)
        #print "Initialized Parent class"
        self.name = 'SimEngine'
        self.scheduler = self.settings.scheduler

        self.objective_function = self.settings.objective_function

        #emunicio
        self.timeElapsedFlow = 0
        self.totalTx = 0
        self.totalRx = 0
        self.dropByCollision = 0
        self.dropByPropagation = 0
        self.bcstReceived = 0
        self.bcstTransmitted = 0
        self.packetsSentToRoot = 0  #total packets sent from all nodes to the root node
        self.packetReceivedInRoot = 0  #total packets sent from all nodes to the root node
        self.olGeneratedToRoot = 0  #average throughput generated
        self.thReceivedInRoot = 0  #average throughput received

        # emunicio settings
        self.numBroadcastCell = self.settings.numBroadcastCells
Beispiel #3
0
 def __init__(self):
     # eventually, we will create the network here.
     top = Topology.Topology()
     top.add_layer(85, "Input")
     top.add_layer(672)
     top.add_layer(336)
     top.add_layer(14)
     self.net = Network.Network(top, learning_rate=0.0001)
    def generateTopology(self):
#        Topology.__debug__ = 0
        TopoMap = Topology()
        PathIndex = {}
        TopoMap.place = {}
        for pathdir,pathList in self.PathSpecs.items(): # On, Order, and Terminates
            for GW in pathList: PathIndex[GW] = pathdir
            paName = pathdir[:-1]; paDir = pathdir[-1]
            if paDir == '-': continue
            path = Path(TopoMap,{'path':paName})
            lastPlace=None
            for (pl,gw) in pathList: # for pose along path
                plName = str(pl)
                place = TopoMap.place.setdefault(plName, Place(TopoMap,{'place':plName}))
                OnRelation(TopoMap,{'path':paName, 'thing':place.latex_str(), 'place':plName})
                if lastPlace is None:
                    TerminatesRelation(TopoMap,{'pathdir':paName+'-', 'place':plName})
                else:
                    OrderRelation(TopoMap,{'pathdir':pathdir,
                                           'thing':lastPlace.latex_str(), 'place':str(lastPlace),
                                           'thing2':place.latex_str(), 'place2':plName})
                lastPlace=place
            TerminatesRelation(TopoMap,{'pathdir':pathdir, 'place':plName})
        for Locations, Names in zip([self.TextureLocs, self.PictureLocs],
                                    [Meanings.Texture.Abbrevs, Meanings.Picture.Abbrevs]):
            for (pl,gw), appearance in Locations.items():
                AppearRelation(TopoMap,{'pathdir':PathIndex[(pl,gw)], 'place':plName, 'appearance':Names[appearance]})
        for pl,obj in self.ObjectLocs.items():
            AtRelation(TopoMap,{'place':str(pl), 'object':Meanings.Object.Abbrevs[obj]})
        for (pl,gw),pathdir in PathIndex.items():
            plName = str(pl)
            paName = pathdir[:-1]; paDir = pathdir[-1]
            for dir, nextGW in zip(('Right', 'Left'), (gw+1, gw-1)):
                pose = (pl,(nextGW)%self.NumPoses)
                if pose in PathIndex:
                    SideOfRelation(TopoMap,{'sideof':dir, 'place':plName, 'pathdir':pathdir, 'pathdir2':PathIndex[pose]})
        self.TopoMap = TopoMap
Beispiel #5
0
 def __init__(self,MyMacAdd,ID):
     self.myMACadd=MyMacAdd
     self.broadcast=b'\xff\xff\xff\xff\xff\xff'
     self.protocol=b'\x08\x01'
     self.payload=''
     self.Type_message={
     'Hello':'0',
     'MPR_message':'1',
     'Message':'2'
     }
     self.tp=Topology(ID)
     self.msj_out=''
     self.message_Hello=Hello(ID)
     self.message_MPR=MPRmsj(ID)
     self.message=Message(ID)
     self.temperature=0
Beispiel #6
0
 def __init__(self):
     Topo.__init__(self)
     g = Topology.OS3EWeightedGraph()
     i = 0
     for node in g.nodes:
         switches[node] = self.addSwitch('s'+str(i))
         i += 1
     for edge in g.edges:
         weight = g[edge[0]][edge[1]]['weight']
         delay = calc_latency(weight)
         if weight is not None:
             self.addLink(switches[edge[0]], switches[edge[1]], delay=str(delay)+'ms')
     j = 0
     for node in g.nodes:
         hosts[node] = self.addHost('h'+str(j))
         j += 1
         self.addLink(switches[node], hosts[node])
Beispiel #7
0
    def __init__(self):

        #mhashtables (name to number)
        self.atom = {}
        self.res = {}
        self.chain = {}
        self.atomtype = {}

        #structure(whole pdb in numeric format, via hashtable)
        self.data = []

        #atoms connectivity (hash calling bonds, angles, and dihedrals, corresponding a table)
        self.topology = T.Topology()

        #head, tail, hook head, hook tail
        self.limit = {}

        self.pdbfile = ""
        self.topfile = ""
Beispiel #8
0
    def __init__(self, runNum=None, failIfNotInit=False):

        if failIfNotInit and not self._init:
            raise EnvironmentError('SimEngine singleton not initialized.')

        #===== start singleton
        if self._init:
            return
        self._init = True
        #===== end singleton

        # store params
        self.runNum = runNum

        # local variables
        self.dataLock = threading.RLock()
        self.pauseSem = threading.Semaphore(0)
        self.simPaused = False
        self.goOn = True
        self.asn = 0
        self.startCb = []
        self.endCb = []
        self.events = []
        self.settings = SimSettings.SimSettings()
        self.pce = SimPce.SimPce(self.runNum)
        self.pce.readTopologyFile()
        self.propagation = Propagation.Propagation()
        self.motes = [Mote.Mote(id) for id in range(self.settings.numMotes)]
        self.moteLocation = self.pce.fileContent
        self.topology = Topology.Topology(self.motes, self.moteLocation)
        #self.topology                       = Topology.Topology(self.motes)
        self.topology.createTopology()

        if self.settings.enableCellAllocation:
            self.pce.readSchedulesFile()

        # boot all motes
        for i in range(len(self.motes)):
            self.motes[i].boot()

        # initialize parent class
        threading.Thread.__init__(self)
        self.name = 'SimEngine'
Beispiel #9
0
"""
Assignment 1 of EH2745, KTH Royal Institute of Technology
Author: oadamanik (Oscar Aristo Damanik)
"""

from GUI import *
import tkinter as tk
from Elements import *
from Topology import *
from PandapowerNetwork import *

my_grid_elements = GridElements()
my_topology = Topology()
my_pandapower = PandapowerNetwork()

root = tk.Tk()

my_gui = MainPage(root, my_grid_elements, my_topology, my_pandapower)


root.mainloop()
Beispiel #10
0
                    type=int,
                    default=70,
                    help="cone angle in degrees")
#parser.add_argument("-u", "--maxtype", type=int, default=3, help="Up to what maximum type should I process data?")
#parser.add_argument("--getMSD", action='store_true', default=False, help="Compute mean squared displacement?")
#parser.add_argument("--plot", action='store_true', default=False, help="Plot MSD and correlations")
#parser.add_argument("--ignore", action='store_true', default=False, help="Ignore complications like missing potentials for quick result (warning!)")

args = parser.parse_args()

# Use the Configuration constructor in its readCSV format to generate the topology
# fromCSV(kwargs["parampath"],kwargs["datapath"],kwargs["multiopt"])
parampath0 = args.directory + args.conffile
param = Param(parampath0)
Cornea = Topology(initype="fromCSV",
                  param=param,
                  datapath=args.directory,
                  multiopt="many")
# Now read in as desired
# def readDataMany(self,skip=0,step=1,howmany='all',Nvariable=False,readtypes = 'all'):
Cornea.readDataMany("SAMoS",
                    args.skip,
                    args.step,
                    args.howmany,
                    True,
                    readtypes=[1, 2])
#def __init__(self,directory,conffile,skip,howmany,ignore=True,maxtype=3):

data = {'configuration': args.conffile}

write = Writer()
output = True
Beispiel #11
0
    def __init__(self, runNum=None, failIfNotInit=False):

        if failIfNotInit and not self._init:
            raise EnvironmentError('SimEngine singleton not initialized.')

        #===== start singleton
        if self._init:
            return
        self._init = True
        #===== end singleton

        # store params
        self.runNum = runNum

        # local variables
        self.dataLock = threading.RLock()
        self.pauseSem = threading.Semaphore(0)
        self.simPaused = False
        self.goOn = True
        self.asn = 0
        self.startCb = []
        self.endCb = []
        self.events = []
        self.settings = SimSettings.SimSettings()
        self.propagation = Propagation.Propagation()
        self.motes = [Mote.Mote(id) for id in range(self.settings.numMotes)]
        self.topology = Topology.Topology(self.motes)
        self.topology.createTopology()

        # load flows:
        file = open('flows.input', 'r')
        import ast
        string = file.readline()
        flows_dictionary = ast.literal_eval(string)
        s = list()
        for key, value in flows_dictionary.items():
            s.append(value)
        counter = 0
        flow_id = 0
        for i in s:
            for j in range(i[1]):
                self.motes[counter].flow.update({
                    'flow_id': flow_id,
                    'priority': i[0]
                })
                print self.motes[counter].flow
                counter += 1
            flow_id += 1

        # boot all motes
        for i in range(len(self.motes)):
            self.motes[i].boot()

        self.initTimeStampTraffic = 0
        self.endTimeStampTraffic = 0

        # initialize parent class
        threading.Thread.__init__(self)
        #print "Initialized Parent class"
        self.name = 'SimEngine'
        self.scheduler = self.settings.scheduler

        #emunicio
        self.timeElapsedFlow = 0
        self.totalTx = 0
        self.totalRx = 0
        self.dropByCollision = 0
        self.dropByPropagation = 0
        self.bcstReceived = 0
        self.bcstTransmitted = 0
        self.packetsSentToRoot = 0  #total packets sent from all nodes to the root node
        self.packetReceivedInRoot = 0  #total packets sent from all nodes to the root node
        self.olGeneratedToRoot = 0  #average throughput generated
        self.thReceivedInRoot = 0  #average throughput received

        # emunicio settings
        self.numBroadcastCell = self.settings.numBroadcastCells
import numpy as np

import Neural_Network as Nn
import Topology as Tp

shape = (784, 100, 10)
initializer = Tp.Initializer.normal()
activation = Tp.ActivationFunction.sigmoid()
output_activation = Tp.ActivationFunction.sigmoid()

dense = Nn.CreateNeuralNetwork(shape=shape,
                               initializer=initializer,
                               activation=activation,
                               output_activation=output_activation)

# np_loader = np.load('image_classification_47_balanced_test.npz')
# data_base = Tp.CreateDatabase(np_loader['arr_0']/256, np_loader['arr_1'])
n = 10000
data_base = Tp.CreateDatabase(Nn.np.random.random([n, shape[0]]),
                              Nn.np.random.random([n, shape[-1]]))
epochs = 10
batch_size = -1
loss_function = Tp.LossFunction.mean_square()
optimizer = Tp.Optimizer.traditional_gradient_decent(dense, 1)

dense.train(train_database=data_base,
            epochs=epochs,
            batch_size=batch_size,
            loss_function=loss_function,
            optimizer=optimizer)
Beispiel #13
0
from Topology import *
from helpers import *
from glob import glob

topos_files = glob("topos/*")
for topo_file in topos_files:
    output_file = topo_file.replace("topos/", "output/").replace(".txt", ".log")
    print "executing: ", topo_file
    open_log(output_file)
    topo = Topology(topo_file)
    topo.run_topo()
    finish_log()
Beispiel #14
0
 def generateTopology(self):
     #        Topology.__debug__ = 0
     TopoMap = Topology()
     PathIndex = {}
     TopoMap.place = {}
     for pathdir, pathList in self.PathSpecs.items(
     ):  # On, Order, and Terminates
         for GW in pathList:
             PathIndex[GW] = pathdir
         paName = pathdir[:-1]
         paDir = pathdir[-1]
         if paDir == '-': continue
         path = Path(TopoMap, {'path': paName})
         lastPlace = None
         for (pl, gw) in pathList:  # for pose along path
             plName = str(pl)
             place = TopoMap.place.setdefault(
                 plName, Place(TopoMap, {'place': plName}))
             OnRelation(TopoMap, {
                 'path': paName,
                 'thing': place.latex_str(),
                 'place': plName
             })
             if lastPlace is None:
                 TerminatesRelation(TopoMap, {
                     'pathdir': paName + '-',
                     'place': plName
                 })
             else:
                 OrderRelation(
                     TopoMap, {
                         'pathdir': pathdir,
                         'thing': lastPlace.latex_str(),
                         'place': str(lastPlace),
                         'thing2': place.latex_str(),
                         'place2': plName
                     })
             lastPlace = place
         TerminatesRelation(TopoMap, {'pathdir': pathdir, 'place': plName})
     for Locations, Names in zip(
         [self.TextureLocs, self.PictureLocs],
         [Meanings.Texture.Abbrevs, Meanings.Picture.Abbrevs]):
         for (pl, gw), appearance in Locations.items():
             AppearRelation(
                 TopoMap, {
                     'pathdir': PathIndex[(pl, gw)],
                     'place': plName,
                     'appearance': Names[appearance]
                 })
     for pl, obj in self.ObjectLocs.items():
         AtRelation(TopoMap, {
             'place': str(pl),
             'object': Meanings.Object.Abbrevs[obj]
         })
     for (pl, gw), pathdir in PathIndex.items():
         plName = str(pl)
         paName = pathdir[:-1]
         paDir = pathdir[-1]
         for dir, nextGW in zip(('Right', 'Left'), (gw + 1, gw - 1)):
             pose = (pl, (nextGW) % self.NumPoses)
             if pose in PathIndex:
                 SideOfRelation(
                     TopoMap, {
                         'sideof': dir,
                         'place': plName,
                         'pathdir': pathdir,
                         'pathdir2': PathIndex[pose]
                     })
     self.TopoMap = TopoMap
Beispiel #15
0
#     python run_topo.py <topology_file> <log_file>
# For instance, to run topo1.py and log to topo1.log that we created, use the following:
#     python run_topo.py topo1 topo1.log
# Note how the topology file doesn't have the .py extension.
#
# Students should not modify this file.
#
# Copyright 2015 Sean Donovan

import sys
from Topology import *
from Node import *
from helpers import *

# if len(sys.argv) != 3:
#     print("Syntax:")
#     print("    python run_topo.py <topology_file> <log_file>")
#     exit()

# Start up the logfile
open_log('MyAnswers/simplified_complex_topo.log')

# Populate the topology
topo = Topology('Topologies/simplified_complex_topo.txt')

# Run the topology.
topo.run_topo()

# Close the logfile
finish_log()
    def __init__(self, runNum=None, failIfNotInit=False):

        if failIfNotInit and not self._init:
            raise EnvironmentError('SimEngine singleton not initialized.')

        #===== start singleton
        if self._init:
            return
        self._init = True
        #===== end singleton

        # store params
        self.runNum = runNum

        # local variables
        self.dataLock = threading.RLock()
        self.pauseSem = threading.Semaphore(0)
        self.simPaused = False
        self.goOn = True
        self.asn = 0
        self.startCb = []
        self.endCb = []
        self.events = []
        self.settings = SimSettings.SimSettings()
        self.propagation = Propagation.Propagation()
        self.motes = [Mote.Mote(id) for id in range(self.settings.numMotes)]

        #before create topology, define the obstacles
        if self.settings.mobilityModel == 'RPGM':
            #set a destination for all motes in RPGM
            self.setNewDestination()
            self.margin = 0.02
            #self.obstacles="4squares"
            self.obstacles = "2rectangles"
        else:
            self.obstacles = "none"

#check maxNumHops
        if self.settings.maxNumHops != 'x':
            self.settings.maxNumHops = int(self.settings.maxNumHops)
        self.topology = Topology.Topology(self.motes)
        self.topology.createTopology()

        #dictionaries for init the experiment
        self.joiningTime = {}
        self.nodeHasTxCellsTime = {}
        self.nodeSendingTime = {}

        # boot all motes
        for i in range(len(self.motes)):
            self.motes[i].boot()

        self.initTimeStampTraffic = 0
        self.endTimeStampTraffic = 0

        # initialize parent class
        threading.Thread.__init__(self)
        self.name = 'SimEngine'

        #total TX and RX of data packets
        self.totalTx = 0
        self.totalRx = 0

        #all messages sent and received: data, 6top and RPL
        self.TRX = 0
        self.RDX = 0

        #duration of the experiment
        self.timeElapsedFlow = 0

        #drops in the PHY layer
        self.dropByCollision = 0
        self.dropByPropagation = 0

        #debras stats
        self.deBrasReceived = 0
        self.deBrasTransmitted = 0

        self.packetsSentToRoot = 0  #total packets sent from all nodes to the root node
        self.packetReceivedInRoot = 0  #total packets sent from all nodes to the root node
        self.olGeneratedToRoot = 0  #average throughput generated
        self.thReceivedInRoot = 0  #average throughput received
        self.pkprobeGeneratedToRoot = 0  #packet probe generated
        self.pkprobeReceivedInRoot = 0  #packet probe received

        #mote object that is the dagroot
        self.dagRoot = None

        #the saturation has been forced to start due to saturation reached or time limit exceeded
        self.simulationForced = False

        #initial values that will be overwritten in SimStats
        self.experimentInitTime = 10000
        self.experimentEndTime = self.settings.numCyclesPerRun

        #specifies the turn for a tidy joining process
        self.turn = 1

        #flag for saturation
        self.saturationReached = False
Beispiel #17
0
#     python run_topo.py <topology_file> <log_file>
# For instance, to run topo1.py and log to topo1.log that we created, use the following:
#     python run_topo.py topo1 topo1.log
# Note how the topology file doesn't have the .py extension.
#
# Students should not modify this file.
#
# Copyright 2015 Sean Donovan

import sys
from Topology import *
from Node import *
from helpers import *

if len(sys.argv) != 3:
    print("Syntax:")
    print("    python run_topo.py <topology_file> <log_file>")
    exit()

# Start up the logfile
open_log(sys.argv[2])

# Populate the topology
topo = Topology(sys.argv[1])

# Run the topology.
topo.run_topo()

# Close the logfile
finish_log()
# For instance, to run topo1.py and log to topo1.log that we created, use the following:
#     python run_topo.py topo1 topo1.log
# Note how the topology file doesn't have the .py extension.
#
# Students should not modify this file.
#
# Copyright 2015 Sean Donovan


import sys
from Topology import *
from Node import *
from helpers import *

if len(sys.argv) != 3:
    print "Syntax:"
    print "    python run_topo.py <topology_file> <log_file>"    
    exit()

# Start up the logfile
open_log(sys.argv[2])

# Populate the topology
topo = Topology(sys.argv[1])

# Run the topology.
topo.run_topo()

# Close the logfile
finish_log()
    def __init__(self, cpuID=None, runNum=None, failIfNotInit=False):

        if failIfNotInit and not self._init:
            raise EnvironmentError('SimEngine singleton not initialized.')

        #===== start singleton
        if self._init:
            return
        self._init = True
        #===== end singleton

        # store params
        self.cpuID                          = cpuID
        self.runNum                         = runNum

        self.rect1 = (0.0, 0.9, 3.0, 1.1)
        self.rect2 = (2.0, 1.9, 5.0, 2.1)
        self.rect3 = (0.0, 2.9, 3.0, 3.1)
        self.rect4 = (2.0, 3.9, 5.0, 4.1)

        # self.originX = 2.5 # in km
        # self.originY = 4.7 # in km
        # self.targetX = 4.5 # in km
        # self.targetY = 4.6 # in km

        # first one is the origin
        self.targets = [(4.6, 4.6), (0.9, 3.95), (4.6, 2.95), (0.9, 1.95), (4.6, 0.95)]
        # self.targets = [(1.0, 3.7), (4.0, 2.7), (1.0, 1.7), (4.5, 0.5)]
        # self.targets = [(4.0, 2.7), (1.0, 1.7), (4.5, 0.5)]
        self.targetType = {}

        self.targetRadius = 0.100 # in km
        self.targetPos = {} # dict: mote -> (x, y) relative to workingTargetX
        self.targetIndex = {}
        self.margin = 0.02
        self.goalDistanceFromTarget = 0.01

        # local variables
        self.dataLock                       = threading.RLock()
        self.pauseSem                       = threading.Semaphore(0)
        self.simPaused                      = False
        self.goOn                           = True
        self.asn                            = 0
        self.startCb                        = []
        self.endCb                          = []
        self.events                         = []
        self.settings                       = SimSettings.SimSettings()
        random.seed(self.settings.seed)
        np.random.seed(self.settings.seed)
        self.genMobility = random.Random()
        self.genMobility.seed(self.settings.seed)
        self.propagation                    = Propagation.Propagation()
        self.motes                          = [Mote.Mote(id) for id in range(self.settings.numMotes)]

        self.ilp_topology                   = None

        # self.comehere = {}

        if self.settings.ilpfile is not None:
            if self.settings.json == None:
                assert False # this file should not be None, because we want to use the same parameters as with we made the ILP file
            if self.settings.ilpschedule == None:
                assert False # this file should not be None, because we want to use the same parameters as with we made the ILP file
            # self.topology = Topology.Topology(self.motes)
            # self.topology.createTopology()

            with open(self.settings.ilpfile, 'r') as f:
                ilp_configuration = json.load(f)
            with open(self.settings.ilpschedule, 'r') as f:
                ilp_schedule = json.load(f)

            ilp_schedule = ilp_schedule['schedule']

            if len(ilp_schedule) != (len(self.motes) - 1):
                assert False

            minimal_modulation = Modulation.Modulation().minimalCellModulation[self.settings.modulationConfig]
            MINIMAL_SLOTS_OFFSET = self.settings.nrMinimalCells * Modulation.Modulation().modulationSlots[self.settings.modulationConfig][minimal_modulation]
            # # add it for all motes, also for the root
            # for (ts, ch, modulation) in ilp_configuration['minimal_slots']:
            #     assert modulation in Modulation.Modulation().modulationSlots[self.settings.modulationConfig]
            #     m._tsch_add_ilp_minimal_cell(ts, ch, modulation)

            # create the topology
            # do this before looping the motes, because we need the topology to add the minimal cells (for the myNeighbors function)
            self.ilp_topology = ilp_configuration['simulationTopology']
            self.topology = Topology.Topology(self.motes)
            self.topology.createTopology()

            for m in self.motes:
                # skip the root
                if m.id != 0:
                    chosenMCS = None
                    if str(m.id) not in ilp_schedule:
                        assert False # the m.id should be in the ILP schedule, if it is not the root
                    sigmaTXList = []
                    sigmaRXList = []
                    for timeslot in ilp_schedule[str(m.id)]:
                        for channel in ilp_schedule[str(m.id)][timeslot]:
                            if chosenMCS is None:
                                chosenMCS = ilp_schedule[str(m.id)][timeslot][channel]['mcs']
                            print 'mcs %s' % ilp_schedule[str(m.id)][timeslot][channel]['mcs']
                            print 'slots %s' % ilp_schedule[str(m.id)][timeslot][channel]['slots']
                            print 'parent %s' % ilp_schedule[str(m.id)][timeslot][channel]['parent']
                            sigmaTXList.append((MINIMAL_SLOTS_OFFSET + int(timeslot), int(channel), Mote.DIR_TX,
                                              int(ilp_schedule[str(m.id)][timeslot][channel]['parent']),
                                              ilp_schedule[str(m.id)][timeslot][channel]['mcs'],
                                              int(ilp_schedule[str(m.id)][timeslot][channel]['slots'])))
                            sigmaRXList.append((MINIMAL_SLOTS_OFFSET + int(timeslot), int(channel), Mote.DIR_RX,
                                                int(m.id),
                                                ilp_schedule[str(m.id)][timeslot][channel]['mcs'],
                                                int(ilp_schedule[str(m.id)][timeslot][channel]['slots'])))


                    assert str(m.id) in ilp_configuration['simulationTopology']
                    assert len(sigmaTXList) == len(sigmaRXList)

                    parent_id = ilp_configuration['simulationTopology'][str(m.id)]['parent']
                    # set the preferred parent, read from the ILP file
                    m.preferredParent = self.getMote(parent_id)

                    # if there are cells to add
                    if len(sigmaTXList) == len(sigmaRXList) and len(sigmaTXList) > 0:

                        pdr = self.topology._computePDR(m, m.preferredParent, modulation=chosenMCS)
                        m.setPDR(m.preferredParent, pdr)
                        m.preferredParent.setPDR(m, pdr)
                        m.setModulation(m.preferredParent, chosenMCS)
                        m.preferredParent.setModulation(m, chosenMCS)

                        print 'Adding for mote %d, which is %s' % (m.id, str(m))

                        # add the cells to the parent
                        m._ilp_tsch_addCells(sigmaTXList)
                        # add the cells to the child
                        m.preferredParent._ilp_tsch_addCells(sigmaRXList)

                        print '%d : %d' % (m.preferredParent.id, m.preferredParent.numCellsFromNeighbors[m])
                        # print '%d : %d' % (m.id, m.numCellsToNeighbors[m.preferredParent])

                        assert m.numCellsToNeighbors[m.preferredParent] == m.preferredParent.numCellsFromNeighbors[m]
                        # add the minimal cells for each mote

        else:
            # for m in self.motes:
            #     m.setModulation()
            self.topology                       = Topology.Topology(self.motes)
            self.topology.createTopology()

        # only do this if the parents are not dictated by the parent files
        if self.settings.ilpfile is None:
            self.dictParent = self.chooseParentInCircularFashion()
            for ix, mote in enumerate(self.motes):
                if not mote.dagRoot:
                    parent = self.dictParent[mote.id][0]
                    for parentIx, parentMote in enumerate(self.motes):
                        if parentMote.id == parent:
                            break
                    self.motes[ix].preferredParent = self.motes[parentIx]

        if self.settings.genTopology == 1:
            exp_file = None
            with open(self.settings.json) as data_file:
                exp_file = json.load(data_file)
            # split off the directory in front and the .json behind
            self.extendJSONWithTopology(exp_file, self.settings.json.split('/')[-1].split('.')[0])
            exit()

        # Not valid values. Will be set by the last mote that converged.
        self.asnInitExperiment = 999999999
        self.asnEndExperiment = 999999999

        # for the ILP
        self.ILPTerminationDelay = 999999999

        self.dedicatedCellConvergence = 99999999

        # self.datarates = [50, 100, 150, 200, 250] # kbps
        # self.datarates = [100, 150, 200, 300]
        # if self.settings.slotAggregation == 1:
        #     self.nrOfSlots = {50: 3, 100: 3, 150: 2, 200: 2, 250: 1}
        # if self.settings.slotAggregation == 2:
        #     self.nrOfSlots = {50: 3, 100: 3, 150: 3, 200: 3, 250: 3}
        # if self.settings.slotAggregation == 3:
        #     self.nrOfSlots = {50: 1, 100: 1, 150: 1, 200: 1, 250: 1}
        # if self.settings.slotAggregation == 4:
        #     self.nrOfSlots = {100: 2, 150: 2, 200: 2, 300: 1}

        # boot all motes at once here when loading an experiment from the ILP file
        # if you not do this, you will have problems because the active cells that are directly loaded from the ILP file will need
        # information from the other nodes that is only available after booting the node
        if self.settings.ilpfile is not None:
            for i in range(len(self.motes)):
                self.motes[i].boot()
                self.motes[i].isConverged = True # set all motes to being converged
                self.motes[i].isConvergedASN = self.asn

            self.dedicatedCellConvergence = self.asn

            # experiment time in ASNs
            simTime = self.settings.numCyclesPerRun * self.settings.slotframeLength
            # offset until the end of the current cycle
            offset = self.settings.slotframeLength - (self.asn % self.settings.slotframeLength)
            settlingTime = int((float(self.settings.settlingTime) / float(self.settings.slotDuration)))
            # experiment time + offset
            self.ILPTerminationDelay = simTime + offset + settlingTime
            self.asnInitExperiment = self.asn + offset + settlingTime
            log.info("Start ILP experiment set at ASN {0}, end experiment at ASN {1}.".format(self.asnInitExperiment, self.asnInitExperiment + simTime))

        if self.settings.ilpfile is None:
            self.motes[0].boot()

        # initialize parent class
        threading.Thread.__init__(self)
        self.name                           = 'SimEngine'
Beispiel #20
0
        global current_flow
        current_flow=current_flow+1
        flow={
        "eth_type":"0x0800",
        "cookie":"0",
        "priority":"32768",
        "active":"true",
        "hard_timeout":str(flow_timeout),
        "name":"flow_mod_"+str(current_flow),
        "switch":Switch,
        "ipv4_"+Type:Ip_Address,
        "actions":"output="+str(Out_Port)
        }
        flowOutput(flow)
        return flow
    
    for ip_address in Ip_List:
        pusher.set(flowMaker("dst",Switch_Src,ip_address,Out_Port_Src))
        pusher.set(flowMaker("src",Switch_Dst,ip_address,Out_Port_Dst))

if __name__ == '__main__':
    if os.getuid() != 0:
        print("You are NOT root")
    elif os.getuid() == 0:
        while True:
            Topology.shell("sudo ../nDPI/example/ndpiReader -i s1-eth1 -s "+str(sample_timeout)+" -w testResult.txt")
            getProtocolInfo("testResult.txt")
            #going the lower road, dirty code.
            flowSet(getIpList("Unknown"),"00:00:00:00:00:00:00:01","00:00:00:00:00:00:00:04",3,2)
            #flush the protocols.
            protocols=[]
Beispiel #21
0
# Project 2 for OMS6250 Spring 2017
#
# Usage:
# Generically, it is run as follows:
#     python run_spanning_tree.py <topology_file> <log_file>
# For instance, to run jellyfish_topo.py and log to jellyfish.log that we created, use the following:
#     python run_spanning_tree.py jellyfish_topo jellyfish.log
# Note how the topology file doesn't have the .py extension.
#
# Students should not modify this file.
#
# Copyright 2016 Michael Brown
#           Based on prior work by Sean Donovan, 2015

import sys
from Topology import *

if len(sys.argv) != 3:
    print "Syntax:"
    print "    python run_spanning_tree.py <topology_file> <log_file>"
    exit()

# Populate the topology
topo = Topology(sys.argv[1])

# Run the topology.
topo.run_spanning_tree()

# Close the logfile
topo.log_spanning_tree(sys.argv[2])
Beispiel #22
0
#
# Usage:
# Generically, it is run as follows:
#     python run_spanning_tree.py <topology_file> <log_file>
# For instance, to run jellyfish_topo.py and log to jellyfish.log that we created, use the following:
#     python run_spanning_tree.py jellyfish_topo jellyfish.log
# Note how the topology file doesn't have the .py extension.
#
# Students should not modify this file.
#
# Copyright 2016 Michael Brown
#           Based on prior work by Sean Donovan, 2015


import sys
from Topology import *

if len(sys.argv) != 3:
    print "Syntax:"
    print "    python run_spanning_tree.py <topology_file> <log_file>"    
    exit()

# Populate the topology
topo = Topology(sys.argv[1])

# Run the topology.
topo.run_spanning_tree()

# Close the logfile
topo.log_spanning_tree(sys.argv[2])
Beispiel #23
0
def main():

    display_model = False

    load_model = False
    single_specie = True

    hm_initial = 5000
    hm_fittest = 500

    hm_iteration = 50

    if not display_model:

        population = [Topology() for _ in range(hm_initial)
                      ] if not load_model else load(open('pop.pkl', 'rb'))

        for _ in range(hm_iteration):

            # mutate

            muts = []

            for topology in population:

                for mutation in (
                        mutate_add_connection(copy(topology)),
                        mutate_split_connection(copy(topology)),
                        mutate_alter_connection(copy(topology)),
                        mutate_onoff_connection(copy(topology)),
                ):
                    if mutation:
                        muts.append(mutation)

            population.extend(muts)

            # specify

            if not single_specie:
                species = divide_into_species(population)
            else:
                species = [population, [], [], []]

            # survive

            species_results = [
                sorted({_: play_a_round(t)
                        for _, t in enumerate(population)}.items(),
                       key=itemgetter(1),
                       reverse=True) for population in species
            ]

            species = [[
                specie[e[0]] for e in specie_result[:hm_fittest]
            ] for specie, specie_result in zip(species, species_results)]

            population = species[0] + species[1] + species[2] + species[3]

            scores = [
                specie_result[0][1] for specie_result in species_results
                if specie_result
            ]

            # breed

            for specie in species:

                news = []

                for i, topology1 in enumerate(specie):
                    for topology2 in specie[i + 1:hm_fittest]:

                        res = crossover(copy(topology1), copy(topology2))
                        if res:
                            news.append(res)

                specie.extend(news)

            # survive

            species_results = [
                sorted({_: play_a_round(t)
                        for _, t in enumerate(population)}.items(),
                       key=itemgetter(1),
                       reverse=True) for population in species
            ]

            species = [[
                specie[e[0]] for e in specie_result[:hm_fittest]
            ] for specie, specie_result in zip(species, species_results)]

            population = species[0] + species[1] + species[2] + species[3]

            scores = [
                specie_result[0][1] for specie_result in species_results
                if specie_result
            ]

            print(
                f'iteration {_} ; max: {max(scores)} ; fitness: {scores} ; populations: {[len(pop) for pop in species]}',
                flush=True)

            # breed again

            population_breed = [
                population[e[0]] for e in sorted(
                    {_: play_a_round(t)
                     for _, t in enumerate(population)}.items(),
                    key=itemgetter(1),
                    reverse=True)[:hm_fittest]
            ]

            for i, topology1 in enumerate(population_breed):
                for topology2 in population_breed[i + 1:hm_fittest]:

                    res = crossover(copy(topology1), copy(topology2))
                    if res:
                        population.append(res)

    # displaying results

    # save

        pop_sort = sorted(
            {_: play_a_round(t)
             for _, t in enumerate(population)}.items(),
            key=itemgetter(1),
            reverse=True)
        print(pop_sort)  # TODO : remove
        fittest = population[pop_sort[0][0]]
        print(f'fittest: {pop_sort[0][1]}, sickest: {pop_sort[-1][1]}')

        with open(f'fit.pkl', 'wb+') as f:
            dump(fittest, f)
        with open(f'pop.pkl', 'wb+') as f:
            dump(population, f)

            # display

            play(fittest)

    else:

        # with open('fit.pkl', 'rb') as f:
        #     fit = load(f)
        with open('pop.pkl', 'rb') as f:
            population = load(f)
            pop_sort = sorted(
                {_: play_a_round(t)
                 for _, t in enumerate(population)}.items(),
                key=itemgetter(1),
                reverse=True)
            fit = population[pop_sort[0][0]]

        print('Showing result..')

        play(fit)

    # cleanup

    env.close()
Beispiel #24
0
for index, column in enumerate(data):
    column_mean = np.mean(column)
    column_std = np.std(column)
    data[index] = (column - column_mean) / column_std

data = np.transpose(data)
data = np.ndarray.tolist(data)

targets = iris["target"]
targets_lists = []
for target in targets:
    target_list = [0, 0, 0]
    target_list[target] = 1
    targets_lists.append(target_list)
x_train, x_test, y_train, y_test = train_test_split(data, targets_lists, test_size=0.3)
top = Topology.Topology()
top.add_layer(4, "Input")
top.add_layer(5)
top.add_layer(5)
top.add_layer(3)
net = Network.Network(top, learning_rate=0.01)

#plot_data = net.fit(x_train, y_train, x_test, y_test, method="genetic", fitness_callback=fitness_callback)
plot_data = net.fit(x_train, y_train, x_test, y_test, num_epochs=1000)

plt.plot(plot_data[0], plot_data[1], label="Train")
plt.plot(plot_data[0], plot_data[2], label="Test")
plt.xlabel = "Iteration"
plt.ylabel = "Error"
plt.title = "Diabetes"
plt.text = "Diabetes"
Beispiel #25
0
    def distributeKey(self):
        Topology_1 = Topology.Topology()
        Topology_1.config_construct('config/topology.ini')

        G1 = nx.DiGraph()
        G1.add_edge(1,
                    2,
                    weight=Topology_1.costs.get(('172.16.1.1', '172.16.2.1')))
        G1.add_edge(2,
                    5,
                    weight=Topology_1.costs.get(('172.16.2.1', '172.16.5.3')))
        G1.add_edge(2,
                    6,
                    weight=Topology_1.costs.get(('172.16.2.1', '172.16.6.4')))
        G1.add_edge(2,
                    7,
                    weight=Topology_1.costs.get(('172.16.2.1', '172.16.7.5')))

        G1.add_edge(5,
                    3,
                    weight=Topology_1.costs.get(('172.16.5.3', '172.16.3.2')))

        G1.add_edge(5,
                    4,
                    weight=Topology_1.costs.get(('172.16.5.3', '172.16.4.2')))
        G1.add_edge(7,
                    3,
                    weight=Topology_1.costs.get(('172.16.7.5', '172.16.3.2')))

        G1.add_edge(7,
                    5,
                    weight=Topology_1.costs.get(('172.16.7.5', '172.16.5.3')))

        G1.add_edge(6,
                    4,
                    weight=Topology_1.costs.get(('172.16.6.4', '172.16.4.2')))
        G1.add_edge(4,
                    8,
                    weight=Topology_1.costs.get(('172.16.4.2', '172.16.8.6')))
        G1.add_edge(3,
                    4,
                    weight=Topology_1.costs.get(('172.16.3.2', '172.16.4.2')))

        self.path = self.dijkstra(G1, 1, 8)
        self.textout.insert(END,
                            'Random path to Bob: ' + str(self.path) + '\n')

        pathLength = len(self.path)
        self.keyList = []  #list of AES keys
        self.keyIDList = []  #list of keyIDs
        self.keyIDReceivedList = [
        ]  # indicates the receiving status of each key reply

        for idx in range(pathLength - 1):
            key_id = random.randint(1, 1000000)
            NewKey = diff.DiffieHellman(key_id=key_id)
            NewKey.generate_private_key()
            NewKey.generate_public_key()
            self.keyList.append(NewKey)
            self.keyIDList.append(key_id)
            self.keyIDReceivedList.append(0)

            destination = self.iplist[self.path[idx + 1] -
                                      1]  # get destination ip
            msgGenerator = messageclass.message()
            keyInitMsg = msgGenerator.create_KeyInit(destination, key_id,
                                                     NewKey.generator,
                                                     NewKey.prime,
                                                     NewKey.public_key)
            self.keyMessageQueue.put(keyInitMsg)
            if idx == 0:
                self.sendKeyInitMsg()
Beispiel #26
0
citylongitude = gn.geocode(destination).raw["lon"]
citylatitude = gn.geocode(destination).raw["lat"]

temperature,wind_speed=pl.get_temp(int(duration), destination)
if destination in top_fifty:
    trend_score=50-top_fifty.index(destination)

des_res = city_to_iata(destination)
if des_res[1] == True:
    des_airport = des_res[0]
    # print des_airport
else:
    print "NO iata information"
    sys.exit()

fares = Spouts.LowFareSpout(origin,des_airport,start,checkout)
hotels = Spouts.HotelSpout(des_airport,start,checkout)
poi = Topology.destination_Details(destination)
lowest_cost = float(hotels[0].get('total_price').get('amount')) + float(fares[0].get('fare').get('total_price'))
newscore=pl.rate(temperature,wind_speed,(lowest_cost),int(budget),trend_score)
print "new score is: "
print newscore
if abs(newscore-score)>10:
    plan_to_mail=pl.make_plan_new(int(duration),poi,fares,hotels,0)
    hotel_short = {"name":hotels[0]["property_name"],"address": hotels[0]["address"],"price":hotels[0]["total_price"]}
    mail = {"score":newscore,"user_email":email,"cost":lowest_cost,"plan":plan_to_mail,"flight_detail":fares[0],"hotel_detail":hotel_short}
    sp.sendPlan(mail)
    user_input = {"score":newscore,"user_email":email,"duration":duration,"budget":budget,"origin":origin,"destination":destination,"start":start}
    with open('plan_data.json', 'w') as fp:
        json.dump(user_input, fp)
        iter = 0
        while iter < 1:
            num_nodes = param[0]
            num_sinks = param[1]
            num_nodes_per_sink_avg = num_nodes / num_sinks
            width = 200
            length = 200

            r = 8000
            alpha_t = 50 * 10**(-6)
            alpha_r = 50 * 10**(-6)
            alpha_a = 10 * 10**(-9)
            R_sink, R_node = 100, 50
            alphas = [3]

            t1 = Topology.Topology(num_nodes, num_sinks, width, length)
            sensors, sinks = t1.deploy()
            dist1 = t1.calc_dist(sensors, sinks)  #sensor-sink distance
            dist2 = t1.calc_dist(sensors, sensors)  #sensor-sensor distance

            empty_nodes = t1.unreachable_nodes(dist1, R_node, R_sink)

            #dist1 = np.reshape(dist1, (num_nodes*num_sinks)) # reshape it for convenient computations during optimization
            C = t1.comm_cost(r, alpha_t, alpha_r, alpha_a, dist1)
            C = np.reshape(C, (num_nodes * num_sinks))
            """Multi-hop code START"""

            lvl_num = 1
            levels = [[sinks]]  #sinks are level 0
            row_num = [list(range(num_sinks))]
            lines = []
Beispiel #28
0
def buildNetwork(TopologyType,image):

	RouterPid = []
	data = getData('variable.json')
	NumberOfDevices = data["NumberOfDevices"]
	logToFile.info("	  Setting up the pre-requisite environment")
	device = Topology.preSetup(image)
	logToFile.info("	  Setting up the nodes of the network")

	for i in range(0,NumberOfDevices):						
	
		NodeID = Topology.createNodes(i,device)					 
		count = 3		
		while count >= 0:

			if NodeID:

				logToFile.info("		NODE CREATED(Router%d)",i+1)	
				RouterPid.append(NodeID.group(1))
				cmd = """ln -s /proc/%s/ns/net /var/run/netns/%s""" %(RouterPid[i],RouterPid[i])
				device.sendline(cmd)
				device.expect(['/d+',pexpect.EOF,pexpect.TIMEOUT],timeout=3)
				logger.info(device.before,also_console=True)
				break
			else:

				cmd = "sudo docker rm -f Router%d" %(i+1)
				device.sendline(cmd)
				NodeID = Topology.createNodes(i,device)
				count = count - 1 
				if count == -1:
					logToFile.debug("Unable to instantiate container for node creation")
					raise RuntimeError("Some error : Unable to instantiate docker container for Router") 
				else:
					continue


	logToFile.info("	  Adding links between routers")

	if TopologyType == 'Star':

		NumberOfInterfaces = (2 * NumberOfDevices) - 2 
		NumberOfNetworks = NumberOfDevices - 1
		intfList = []
		nwList = [] 
	
		for i in range(1,(NumberOfInterfaces+1)):
			intfList.append('eth' + str(i))

		for i in range(0,(NumberOfNetworks+1)):
			nwStart = data["Network"]
			nw = nwStart.split('/')
			nwOctets = nw[0].split('.')
			nwList.append(nwOctets[0] + '.' + nwOctets[1] + '.' + str(i+1) + '.' + nwOctets[3]+ '/' + nw[1])
		
		Topology.addLinks(device,intfList)  
		

		logToFile.info("	  Setting the interfaces UP")

		Topology.setInterfaceUp(device,RouterPid,intfList)
		TopoDet = {}
		TopoDet.update({'Interfaceslist' : intfList, 'Nwlist': nwList})

	return TopoDet