Exemple #1
0
    def create_network(self):
        """ create the whole network
        """

        self.net = Network(EMS=self.EMS)
        self.gcom = Gcom(net=self.net, sim=self)

        self.create_agent()
        # create network
        if str2bool(self.net_opt['network']):
            self.net.create()

            # create All Personnal networks
            for n in self.net.nodes():
                self.net.node[n]['PN']._get_wstd()
                self.net.node[n]['PN']._get_SubNet()
            self.gcom.create()

           # create Process Network
            self.Pnet = PNetwork(net=self.net,
                                 net_updt_time=float(
                                     self.net_opt['network_update_time']),
                                 L=self.L,
                                 sim=self,
                                 show_sg=str2bool(self.net_opt['show_sg']),
                                 disp_inf=str2bool(self.net_opt['dispinfo']),
                                 save=eval(self.save_opt['save']))
            self.activate(self.Pnet, self.Pnet.run(), 0.0)
Exemple #2
0
    def __init__(self,**args):
        """

        Parameters
        ----------

        'PN'  : Network
            Personal Network
        'net' : Network
            Global Network
        'method' : list of string
        'ID' : string
        'save' : list


        """

        defaults={'PN':Network(),'net':Network(),'method':['geo','alg'],'model':{},'ID':'0','save':[]}

        for key, value in defaults.items():
            if key in args:
                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key] = value
        self.args = args
        self.config = ConfigParser.ConfigParser()
        self.config.read(pyu.getlong('EMSolver.ini', 'ini'))
        self.cla = CLA()
        self.algloc = algloc()
        self.idx = 0
Exemple #3
0
    def __init__(self, **args):
        defaults = {
            'sim': None,
            'net': Network(),
            #'gcom': Gcom(),
            'gcom': [],  # Temporary
            'ID': 0,
            'dec': {},
            'devt': {},
            'lcst': []
        }
        ##       initialize attributes

        for key, value in defaults.items():
            if key in args:
                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key] = value

        self.args = args
        self.gcom = self.args['gcom']

        if sys.version_info.major == 2:
            self.cmdrq = SimEvent('RQ' + str(self.ID),
                                  sim=self.sim)  # command request
        else:
            pass
            # Python3 implementation not done

        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()

#        self.create_evt()

#        self.c_init()

        if sys.version_info.major == 2:
            Process.__init__(self, name='Tx' + str(self.ID), sim=self.sim)
        else:
            pass
            #Process.__init__(self,env,generator)
            # Python3 implementation not done

        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        for s in Cf.sections():
            try:
                d = dict(Cf.items(s))
                if d['id'] == self.ID:
                    self.refreshTOA = eval(d['refreshtoa'])
                    break
            except:
                pass
Exemple #4
0
    def _gen_net(self):
        """ generate Network and associated links

        Notes
        -----

        Create self.N : Network object

        See Also
        --------

        pylayers.network.network

        """

        #
        # Create Network
        #
        N = Network()
        #
        # get devices on bodies
        #
        # forall person
        #   forall device
        for p in self.dpersons:
            D = []
            for dev in self.dpersons[p].dev:
                aDev = Device(self.dpersons[p].dev[dev]['name'], ID = dev)
                D.append(aDev)

                D[-1].ant['A1']['name'] = self.dpersons[p].dev[dev]['file']
                D[-1].ant['antenna'] = self.dpersons[p].dev[dev]['ant']
            N.add_devices(D, grp=p)
        #
        # get access point devices
        #
        for ap in self.dap:
            D = Device(self.dap[ap]['name'], ID = ap)
            D.ant['antenna'] = self.dap[ap]['ant']
            N.add_devices(D, grp = 'ap', p = self.dap[ap]['pos'])
            N.update_orient(ap, self.dap[ap]['T'], now = 0.)
        # create Network
        #
        #    _get_wstd
        #    _get_grp
        #    _connect
        #    _init_PN
        #
        N.create()
        self.N = N
Exemple #5
0
    def create_network(self):
        """ create the whole network
        """

        self.net = Network(EMS=self.EMS)
        self.gcom=Gcom(net=self.net,sim=self)

        self.create_agent()
        # create network
        if str2bool(self.net_opt['network']):
            self.net.create()

            # create All Personnal networks
            for n in self.net.nodes():
                self.net.node[n]['PN']._get_wstd()
                self.net.node[n]['PN']._get_SubNet()
            self.gcom.create()


           # create Process Network
            self.Pnet = PNetwork(net=self.net,
                                 net_updt_time=float(self.net_opt['network_update_time']),
                                 L=self.L,
                                 sim=self,
                                 show_sg=str2bool(self.net_opt['show_sg']),
                                 disp_inf=str2bool(self.net_opt['dispinfo']),
                                 save=eval(self.save_opt['save']))
            self.activate(self.Pnet, self.Pnet.run(), 0.0)
Exemple #6
0
    def gen_net(self):
        """ generate Network and associated links

        Notes
        -----

        Create self.N : Network object

        See Also
        --------

        pylayers.network.network

        """

        N = Network()
        # get devices on bodies
        for p in self.dpersons:
            D = []
            for dev in self.dpersons[p].dev:
                D.append(
                    Device(self.dpersons[p].dev[dev]['name'], ID=dev + '_' + p))
            N.add_devices(D, grp=p)
        # get access point devices
        for ap in self.dap:
            D = Device(self.dap[ap]['name'], ID=ap)
            N.add_devices(D, grp='ap', p=self.dap[ap]['pos'])
        # create Network
        N.create()
        self.N = N
Exemple #7
0
    def __init__(self, **args):
        defaults = {
            'sim': None,
            'net': Network(),
            'gcom': Gcom(),
            'ID': 0,
            'dec': {},
            'devt': {},
            'lcst': []
        }
        ##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key] = value
        self.args = args
        self.gcom = self.args['gcom']

        self.cmdrq = SimEvent('RQ' + str(self.ID),
                              sim=self.sim)  # command request

        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()

#        self.create_evt()

#        self.c_init()
        Process.__init__(self, name='Tx' + str(self.ID), sim=self.sim)
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        for s in Cf.sections():
            try:
                d = dict(Cf.items(s))
                if d['id'] == self.ID:
                    self.refreshTOA = eval(d['refreshtoa'])
                    break
            except:
                pass
Exemple #8
0
    def __init__(self,**args):
        defaults={'sim':None,
                  'net': Network(),
                  #'gcom': Gcom(),
                  'gcom': [], # Temporary
                  'ID': 0,
                  'dec':{},
                  'devt': {},
                  'lcst': []
                  }
##       initialize attributes

        for key, value in defaults.items():
            if key in args:
                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value

        self.args = args
        self.gcom = self.args['gcom']


        if sys.version_info.major==2:
            self.cmdrq =SimEvent('RQ'+str(self.ID),sim=self.sim) # command request
        else:
            pass
            # Python3 implementation not done

        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()

#        self.create_evt()

#        self.c_init()

        if sys.version_info.major==2:
            Process.__init__(self,name='Tx'+str(self.ID),sim=self.sim)
        else:
            pass
            #Process.__init__(self,env,generator)
            # Python3 implementation not done

        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshTOA=eval(d['refreshtoa'])
                    break
            except:
                pass
Exemple #9
0
    def __init__(self, net=Network(), sim=Simulation()):
        """
        net : pylayers.network.Network

        """
        nx.MultiDiGraph.__init__(self)
        self.net = net
        self.sim = sim
        self.fileini = 'communication.ini'
        self.dec = {}
        self.devt = {}
Exemple #10
0
    def __init__(self, **args):
        defaults = {
            'sim': None,
            'ID': '1',
            'net': Network(),
            #'gcom': Gcom(),
            'gcom': [],
            'devt': {},
            'refreshRSS': 0.3,
            'refreshTOA': 0.3,
            'mp': False
        }
        ##       initialize attributes
        for key, value in defaults.items():
            if key in args:

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key] = value
        self.args = args
        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()
        self.create_evt()

        Process.__init__(self, name='Rx-' + str(self.ID), sim=self.sim)

        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        for s in Cf.sections():
            try:
                d = dict(Cf.items(s))
                if d['id'] == self.ID:
                    self.refreshRSS = eval(d['refreshrss'])
                    self.refreshTOA = eval(d['refreshtoa'])
                    break

            except:
                pass
Exemple #11
0
    def __init__(self,**args):
        defaults={'sim':None,
                  'net': Network(),
                  'gcom': Gcom(),
                  'ID': 0,
                  'dec':{},
                  'devt': {},
                  'lcst': []
                  }
##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value
        self.args=args
        self.gcom=self.args['gcom']


        self.cmdrq=SimEvent('RQ'+str(self.ID),sim=self.sim) # command request

        try:
            self.PN=self.net.node[self.ID]['PN']
        except:
            self.PN=Network()

#        self.create_evt()

#        self.c_init()
        Process.__init__(self,name='Tx'+str(self.ID),sim=self.sim)
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshTOA=eval(d['refreshtoa'])
                    break
            except:
                pass
Exemple #12
0
    def __init__(self,**args):
        defaults={'sim':None,
                  'ID':'1',
                  'net':Network(),
                  'gcom': Gcom(),
                  'devt': {},
                  'refreshRSS':0.3,
                  'refreshTOA':0.3,
                  'mp':False
                  }
##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value  
        self.args=args
        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()
        self.create_evt()

        Process.__init__(self,name='Rx-'+str(self.ID),sim=self.sim)

        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshRSS=eval(d['refreshrss'])
                    self.refreshTOA=eval(d['refreshtoa'])
                    break

            except:
                pass
Exemple #13
0
    def _gen_net(self):
        """ generate Network and associated links

        Notes
        -----

        Create self.N : Network object

        See Also
        --------

        pylayers.network.network

        """

        N = Network()
        # get devices on bodies
        for p in self.dpersons:
            D = []
            for dev in self.dpersons[p].dev:
                D.append(
                    Device(self.dpersons[p].dev[dev]['name'], ID=dev))

                D[-1].ant['A1']['name'] = self.dpersons[p].dev[dev]['file']
                D[-1].ant['antenna']= self.dpersons[p].dev[dev]['ant']
            N.add_devices(D, grp=p)
        #
        # get access point devices
        #
        #
        for ap in self.dap:

            D = Device(self.dap[ap]['name'], ID=ap)
            D.ant['antenna']= antenna.Antenna(D.ant['A1']['name'])

            N.add_devices(D, grp='ap', p=self.dap[ap]['pos'])
            
        # create Network
        N.create()
        self.N = N
Exemple #14
0
class TX():
    """
       TX process ( not used for now)
        Each agent use the TX process for querying LDP/information/message passing data
        to other agent
    """
    def __init__(self,**args):
        defaults={'sim':None,
                  'net': Network(),
                  #'gcom': Gcom(),
                  'gcom': [], # Temporary
                  'ID': 0,
                  'dec':{},
                  'devt': {},
                  'lcst': []
                  }
##       initialize attributes

        for key, value in defaults.items():
            if key in args:
                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value

        self.args = args
        self.gcom = self.args['gcom']


        if sys.version_info.major==2:
            self.cmdrq =SimEvent('RQ'+str(self.ID),sim=self.sim) # command request
        else:
            pass
            # Python3 implementation not done

        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()

#        self.create_evt()

#        self.c_init()

        if sys.version_info.major==2:
            Process.__init__(self,name='Tx'+str(self.ID),sim=self.sim)
        else:
            pass
            #Process.__init__(self,env,generator)
            # Python3 implementation not done

        Cf = ConfigParser.ConfigParser(inline_comment_prefixes=(';',),comment_prefixes=('#',';'))
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshTOA=eval(d['refreshtoa'])
                    break
            except:
                pass


    def run(self):
        while True:
            self.levt=[]
            for d in self.dcond.keys():
                if self.c_interpret(self.dcond[d]):
                    self.levt.append(self.dcste[c])
            print('Tx ', self.ID,' @',self.sim.now())
            yield hold, self, self.refresh


    def create_evt(self):
        """
        Create simpy events from communication gaph

        The available reception event for the given id are pickup into the
        communication graph to fill self.devt.

        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> T = TX()
        >>> T.create_evt()
        """
        for e in self.PN.edges(self.ID,keys=True):
            self.devt[e]=self.gcom.devt[e]



#    def request_TOA(self):
#        """
#        Request TOA


#        Every self.refreshTOA time interval, send a devent signal to nodes
#        in visibility torefresh the TOA information

#        """
#        self.create_evt()
#        while 1:
#            if self.sim.verbose:
#                print('request TOA', self.ID)
#            for wstd in self.PN.SubNet.keys():
#                for n in self.PN.SubNet[wstd].edge[self.ID].keys():
#                    # check nodes in visibility
#                    if self.net.edge[self.ID][n][wstd]['vis']:
#                        key='(\''+self.ID+'\', \''+n+'\', \''+wstd+'\')'
#                        self.devt[eval(key)].signal()
#            yield hold, self, self.refreshTOA
##                    devt[]
##                [self.PN.edge[self.ID][n][wstd].update(
##                {'TOA':self.net.edge[self.ID][n][wstd]['TOA'],'tTOA':self.sim.now()})
##                for n in self.PN.SubNet[wstd].edge[self.ID].keys() if self.net.edge[self.ID][n][wstd]['vis']]
##            print('refresh TOA node', self.ID, ' @',self.sim.now())



    def interpret_dec(self):
        """ interpret decision rule from self.dec
        """

        # n dict{wstd:np.array([node ids])}
        n={}
        # loop on wstd
        for wstd in self.dec['wstd']:
            try:
            # get all nodes connecteed to self.ID on subnetwork wstd
                n[wstd]=np.array(self.PN.SubNet[wstd].edges())[:,1]

                # initialize remained nodes to True
                rn = [True]*len(n[wstd])
                # loop on condition
                for r in self.dec['rule']:

                    if r == 'always':
                        pass

                # mettre boolean dans variable pour condition a plus d41 regle
                    if 'rssth' in r:
                        # rssth<100
                        rntmp = np.array(nx.get_edge_attributes(self.PN.SubNet[wstd],'Pr').values())
                        if len(r.split('<')) > 1:
                            rn = rn and ( rntmp  < eval(r.split('<')[1]) )
                        elif len(r.split('>')) > 1:
                            rn = rn and ( rntmp  > eval(r.split('>')[1]) )

    #                elif 'distance' in r :
    #                    # distance < 10
    #                    rntmp = np.array(nx.get_edge_attributes(self.net.SubNet[wstd],'d').values())
    #                    if len(r.split('<')) > 1:
    #                        rn = rn and ( rntmp  < eval(r.split('<')[1]) )
    #                    elif len(r.split('>')) > 1:
    #                        rn = rn and ( rntmp  > eval(r.split('<')[1]) )

                n[wstd][np.where(rn)]

            except:
                n[wstd]=np.array(())

        # retrun only node id which are compliant with rules
        return (n)


    def request(self):
        """ request a transmission initiated by localization
        """
        self.dec = self.gcom.dec[self.ID]
        self.create_evt()
        while 1:
            # wait request localization from localization layer
            yield waitevent,self,self.cmdrq
            if self.sim.verbose:
                print("communication requested by node ",self.ID)

            # n = nodes compliant with the rules given in communication.py
            #     and in self.gcom.dec[self.ID]
            rn = self.interpret_dec()


            # send a signal (a.k.a. request transmission) to nodes in n
            for wstd in rn.keys():
                for n in rn[wstd]:
                    # check if nodes in visibility
                    if self.net.edge[self.ID][n][wstd]['vis']:
                        key='(\''+self.ID+'\', \''+n+'\', \''+wstd+'\')'
                        # WARNING : PLEASE LEAVE THE 2 FOLLOWING LINES
                        # this is not a bad copy paste. It is required
                        # to force signalization ( probably a SimPy bug)
                        self.devt[eval(key)].signal()
                        self.devt[eval(key)].signal()
Exemple #15
0
 def __init__(self, net=Network(), sim=Simulation()):
     nx.MultiDiGraph.__init__(self)
     self.net = net
     self.sim = sim
Exemple #16
0
    def __init__(self, **args):
        """ Mobile Agent Init

           Parameters
           ----------

           'ID': string
                agent ID
           'name': string
                Agent name
           'typ': string
                agent typ . 'ag' for moving agent, 'ap' for static acces point
           'pos' : np.array([])
                numpy array containing the initial position of the agent
           'roomId': int
                Room number where the agent is initialized (Layout.Gr)
           'meca_updt': float
                update time interval for the mechanical process
           'loc': bool
                enable/disable localization process of the agent
           'loc_updt': float
                update time interval for localization process
           'L': pylayers.gis.Layout()
           'net':pylayers.network.Network(),
           'wstd': list of string
                list of used radio access techology of the agent
           'world': transit.world()
                Soon deprecated
           'save': list of string
                list of save method ( soon deprecated)
           'sim':Simpy.SimulationRT.Simulation(),
           'epwr': dictionnary
                dictionnary of emmited power of transsmitter{'wstd#':epwr value}
           'sens': dictionnary
                dictionnary of sensitivity of reveicer {'wstd#':sens value}
           'dcond': dictionnary
                Not used yet
           'gcom':pylayers.communication.Gcom()
                Communication graph
           'comm_mod': string
                Communication between nodes mode:
                'autonomous': all TOAs are refreshed regulary
                'synchro' : only visilbe TOAs are refreshed
        """
        defaults = {'ID': '0',
                    'name': 'johndoe',
                    'typ': 'ag',
                    'color': 'k',
                    'pdshow': False,
                    'pos': np.array([]),
                    'roomId': -1,
                    'froom': [],
                    'wait': [],
                    'seed': 0,
                    'cdest': 'random',
                    'meca_updt': 0.1,
                    'loc': False,
                    'loc_updt': 0.5,
                    'loc_method': ['geo'],
                    'L': Layout(),
                    'network': True,
                    'net': Network(),
                    'wstd': ['rat1'],
                    'world': world(),
                    'save': [],
                    'sim': Simulation(),
                    'epwr': {},
                    'sens': {},
                    'dcond': {},
                    'gcom': Gcom(),
                    'comm_mode': 'autonomous'}

        for key, value in defaults.items():
            if key not in args:
                args[key] = value

        self.args = args
        self.ID = args['ID']
        self.name = args['name']
        self.typ = args['typ']
        # Create Network
        self.net = args['net']
        self.epwr = args['epwr']
        self.gcom = args['gcom']
        self.sim = args['sim']
        self.wstd = args['wstd']
        if args['epwr'] == {}:
            self.epwr = {x: 0 for x in self.wstd}
        else:
            self.epwr = args['epwr']

        if args['sens'] == {}:
            self.sens = {x: -180 for x in self.wstd}
        else:
            self.sens = args['sens']

        try:
            self.dcond = args['dcond']
        except:
            pass

        # check if node id already given
        if self.ID in self.net.nodes():
            raise NameError(
                'another agent has the ID: ' + self.ID + ' .Please use an other ID')

        if self.typ == 'ag':
            # mechanical init
            self.meca = Person(ID=self.ID,
                               color=args['color'],
                               pdshow=args['pdshow'],
                               roomId=args['roomId'],
                               L=args['L'],
                               net=self.net,
                               interval=args['meca_updt'],
                               wld=args['world'],
                               sim=args['sim'],
                               seed=args['seed'],
                               moving=True,
                               froom=args['froom'],
                               wait=args['wait'],
                               cdest=args['cdest'],
                               save=args['save']
                               )
            self.meca.behaviors = [Seek(), Containment(),
                                   Separation(), InterpenetrationConstraint()]
            self.meca.steering_mind = queue_steering_mind
            # Network init
            self.node = Node(ID=self.ID,name=self.name, p=conv_vecarr(self.meca.position),
                             t=self.sim.now(), wstd=args['wstd'],
                             epwr=self.epwr, sens=self.sens, typ=self.typ)
            self.net.add_nodes_from(self.node.nodes(data=True))

            self.sim.activate(self.meca, self.meca.move(), 0.0)
            self.PN = self.net.node[self.ID]['PN']

            # Communication init

            if args['comm_mode'] == 'synchro' and args['network']:
                # The TOA requests are made every refreshTOA time ( can be modified in agent.ini)
                # This Mode will be deprecated in future version

                self.rxr = RX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)

                self.rxt = RX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)

                self.sim.activate(self.rxr, self.rxr.refresh_RSS(), 0.0)
                self.sim.activate(self.rxt, self.rxt.refresh_TOA(), 0.0)

            elif args['comm_mode'] == 'autonomous' and args['network']:
                # The requests are made by node only when they are in
                # visibility of pairs.

                # self.rxr only manage a refresh RSS process
                self.rxr = RX(net=self.net, ID=self.ID,
                              gcom=self.gcom, sim=self.sim)
                # self.tx manage all requests to other nodes
                self.tx = TX(net=self.net, ID=self.ID,
                             gcom=self.gcom, sim=self.sim)
                # self.tx replies to  requests from self.tx
                self.rx = RX(net=self.net, ID=self.ID,
                             gcom=self.gcom, sim=self.sim)

                self.sim.activate(self.rxr, self.rxr.refresh_RSS(), 0.0)
                self.sim.activate(self.tx, self.tx.request(), 0.0)
                self.sim.activate(self.rx, self.rx.wait_request(), 0.0)

        elif self.typ == 'ap':
            if args['roomId'] == -1:
                self.node = Node(ID=self.ID, p=self.args['pos'],
                                 t=self.sim.now(), wstd=args['wstd'],
                                 epwr=self.epwr, sens=self.sens, typ=self.typ)
            else:
                pp = np.array(args['L'].Gr.pos[self.args['roomId']])
                self.node = Node(
                    ID=self.ID, p=pp, t=self.sim.now(), wstd=args['wstd'],
                    epwr=self.epwr, sens=self.sens, typ=self.typ)
            self.net.add_nodes_from(self.node.nodes(data=True))
            self.sim = args['sim']

            self.PN = self.net.node[self.ID]['PN']
            self.PN.node[self.ID]['pe'] = self.net.node[self.ID]['p']
            if args['comm_mode'] == 'autonomous' and args['network']:
                self.rx = RX(net=self.net, ID=self.ID,
                             gcom=self.gcom, sim=self.sim)
                self.sim.activate(self.rx, self.rx.wait_request(), 0.0)

            p = self.args['pos']
            self.posdf = pd.DataFrame(
                {'t': pd.Timestamp(0), 'x': p[0], 'y': p[1], 'z': p[2],
                                       'vx': np.array([0.0]), 'vy': np.array([0.0]),
                                       'ax': np.array([0.0]), 'ay': np.array([0.0]),
                 }, columns=['t', 'x', 'y', 'z', 'vx', 'vy', 'ax', 'ay'], index=np.array([0]))

        else:
            raise NameError(
                'wrong agent typ, it must be either agent (ag) or acces point (ap) ')

        if self.typ == 'ap':
            self.MoA = 1
        else:
            self.MoA = 0

        if 'mysql' in args['save']:
            config = ConfigParser.ConfigParser()
            config.read(pyu.getlong('simulnet.ini', 'ini'))
            sql_opt = dict(config.items('Mysql'))
            db = Database(sql_opt['host'], sql_opt['user'],
                          sql_opt['passwd'], sql_opt['dbname'])
            db.writenode(self.ID, self.name, self.MoA)

        if 'txt' in args['save']:
            pyu.writenode(self)
        if self.typ != 'ap' and args['loc']:

            self.loc = Localization(net=self.net, ID=self.ID,
                                    method=args['loc_method'])
            self.Ploc = PLocalization(loc=self.loc,
                                      loc_updt_time=args['loc_updt'],
                                      tx=self.tx,
                                      sim=args['sim'])

            self.sim.activate(self.Ploc, self.Ploc.run(), 1.5)
Exemple #17
0
class Simul(SimulationRT):
    """

    Attributes
    ----------
    config  : config parser instance
    sim_opt : dictionary of configuration option for simulation
    ag_opt : dictionary of configuration option for agent
    lay_opt : dictionary of  configuration option for layout
    meca_opt : dictionary of  configuration option for mecanic
    net_opt : dictionary of  configuration option for network
    loc_opt : dictionary of  configuration option for localization
    save_opt : dictionary of  configuration option for save
    sql_opt : dictionary of  configuration option for sql

    Notes
    ------
     All the prvious dictionnary are obtained from the chosen simulnet.ini file
    in the project directory

    """
    def __init__(self):
        SimulationRT.__init__(self)
        self.initialize()
        self.config = ConfigParser.ConfigParser()
        self.config.read(pyu.getlong('simulnet.ini', 'ini'))
        self.sim_opt = dict(self.config.items('Simulation'))
        self.lay_opt = dict(self.config.items('Layout'))
        self.meca_opt = dict(self.config.items('Mechanics'))
        self.net_opt = dict(self.config.items('Network'))
        self.loc_opt = dict(self.config.items('Localization'))
        self.save_opt = dict(self.config.items('Save'))
        self.sql_opt = dict(self.config.items('Mysql'))

        self.verbose = str2bool(self.sim_opt['verbose'])
        if str2bool(self.net_opt['ipython_nb_show']):
            self.verbose = False
        self.roomlist = []

    def create_layout(self):
        """
        Create Layout in Simpy the_world thantks to Tk backend

        """

        self.the_world = world(width=float(self.lay_opt['the_world_width']),
                               height=float(self.lay_opt['the_world_height']),
                               scale=float(self.lay_opt['the_world_scale']))

        # tk = self.the_world.tk
        # canvas, x_, y_ = tk.canvas, tk.x_, tk.y_
        # canvas.create_rectangle(x_(-1), y_(-1), x_(100), y_(100), fill='white')

        _filename = self.lay_opt['filename']
        #sl=Slab.SlabDB(self.lay_opt['slab'],self.lay_opt['slabmat'])
        #G1   = Graph.Graph(sl=sl,filename=_filename)
        self.L = Layout()
        if _filename.split('.')[1] == 'str':
            self.L.loadstr(_filename)
        elif _filename.split('.')[1] == 'str2':
            self.L.loadstr2(_filename)
        elif _filename.split('.')[1] == 'ini':
            self.L.loadini(_filename)

        try:
            self.L.dumpr()
            print 'Layout graphs are loaded from ', basename, '/struc'
        except:
            #self.L.sl = sl
            #self.L.loadGr(G1)
            print 'This is the first time your use this layout file.\
            Layout graphs are curently being built, it may take few minutes.'

            self.L.buildGt()
            self.L.buildGr()
            self.L.buildGw()
            self.L.buildGv()
            self.L.buildGi()
            self.L.dumpw()
        x_offset = 0  # float(self.lay_opt['x_offset'])
        y_offset = 0  # float(self.lay_opt['y_offset'])
        for ks in self.L.Gs.pos.keys():
            self.L.Gs.pos[ks] = (self.L.Gs.pos[ks][0] + x_offset,
                                 self.L.Gs.pos[ks][1] + y_offset)
        for ks in self.L.Gr.pos.keys():
            self.L.Gr.pos[ks] = (self.L.Gr.pos[ks][0] + x_offset,
                                 self.L.Gr.pos[ks][1] + y_offset)
        for ks in self.L.Gw.pos.keys():
            self.L.Gw.pos[ks] = (self.L.Gw.pos[ks][0] + x_offset,
                                 self.L.Gw.pos[ks][1] + y_offset)

        #
        # Create Layout
        #
        walls = self.L.thwall(0, 0)
        for wall in walls:
            points = []
            # for point in wall:
            #          points.append(x_(point[0]))
            #          points.append(y_(point[1]))
            #      canvas.create_polygon(points, fill='maroon', outline='black')
            for ii in range(0, len(wall) - 1):
                self.the_world.add_wall(wall[ii], wall[ii + 1])

    def create_agent(self):
        """    
        create simulation's Agents

        ..todo:: change lAg list to a dictionnary ( modification in show.py too) 

        """

        self.lAg = []
        agents = []
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        agents = eval(dict(Cf.items('used_agent'))['list'])
        for i, ag in enumerate(agents):
            ag_opt = dict(Cf.items(ag))
            self.lAg.append(
                Agent(ID=ag_opt['id'],
                      name=ag_opt['name'],
                      type=ag_opt['type'],
                      pos=np.array(eval(ag_opt['pos'])),
                      roomId=int(ag_opt['roomid']),
                      froom=eval(ag_opt['froom']),
                      meca_updt=float(self.meca_opt['mecanic_update_time']),
                      wait=float(ag_opt['wait']),
                      cdest=eval(self.meca_opt['choose_destination']),
                      loc=str2bool(self.loc_opt['localization']),
                      loc_updt=float(self.loc_opt['localization_update_time']),
                      loc_method=eval(self.loc_opt['method']),
                      Layout=self.L,
                      net=self.net,
                      epwr=dict([(eval(
                          (ag_opt['rat']))[ep], eval((ag_opt['epwr']))[ep])
                                 for ep in range(len(eval((ag_opt['rat']))))]),
                      sens=dict([(eval(
                          (ag_opt['rat']))[ep], eval(
                              (ag_opt['sensitivity']))[ep])
                                 for ep in range(len(eval((ag_opt['rat']))))]),
                      world=self.the_world,
                      RAT=eval(ag_opt['rat']),
                      save=eval(self.save_opt['save']),
                      gcom=self.gcom,
                      comm_mode=eval(self.net_opt['communication_mode']),
                      sim=self))
            #
            if self.lAg[i].type == 'ag':
                self.activate(self.lAg[i].meca, self.lAg[i].meca.move(), 0.0)

    def create_EMS(self):
        """
            Electromagnetic Solver object
        """
        self.EMS = EMSolver(L=self.L)

    def create_network(self):
        """
            create the whole network
        """

        self.net = Network(EMS=self.EMS)
        self.gcom = Gcom(net=self.net, sim=self)
        self.create_agent()
        # create network

        self.net.create()

        # create All Personnal networks
        for n in self.net.nodes():
            self.net.node[n]['PN'].get_RAT()
            self.net.node[n]['PN'].get_SubNet()
        self.gcom.create()

        # create Process Network
        self.Pnet = PNetwork(net=self.net,
                             net_updt_time=float(
                                 self.net_opt['network_update_time']),
                             L=self.L,
                             sim=self,
                             show_sg=str2bool(self.net_opt['show_sg']),
                             disp_inf=str2bool(self.net_opt['dispinfo']),
                             save=eval(self.save_opt['save']))
        self.activate(self.Pnet, self.Pnet.run(), 0.0)

    def create_visual(self):
        """ Create visual Tk process
        """

        self.visu = Updater(interval=float(self.sim_opt['show_interval']),
                            sim=self)
        self.activate(self.visu, self.visu.execute(), 0.0)

    def create(self):
        """ Create the simulation, to be ready to run

        """

        # this is just to redump the database at each simulation
        if 'mysql' in self.save_opt['save']:
            if str2bool(self.sql_opt['dumpdb']):
                os.popen('mysql -u ' + self.sql_opt['user'] + ' -p ' + self.sql_opt['dbname'] +\
                '< /private/staff/t/ot/niamiot/svn2/devel/simulator/pyray/SimWHERE2.sql' )

        if 'txt' in self.save_opt['save']:
            pyu.writeDetails(self)
            if os.path.isfile(basename + '/output/Nodes.txt'):
                print 'would you like to erase previous txt files ?'
                A = raw_input()
                if A == 'y':
                    for f in os.listdir(basename + '/output/'):
                        try:
                            fi, ext = f.split('.')
                            if ext == 'txt':
                                os.remove(basename + '/output/' + f)
                        except:
                            pass

        self.create_layout()
        self.create_EMS()
        self.create_network()
        if str2bool(self.sim_opt['showtk']):
            self.create_visual()
        self.create_show()

        if str2bool(self.save_opt['savep']):
            self.save = Save(L=self.L, net=self.net, sim=self)
            self.activate(self.save, self.save.run(), 0.0)


#        if str2bool(self.save_opt['savep']):
#            self.save=Save(net=self.net,
#                    L= self.L,
#                    sim = self)
#            self.activate(self.save, self.save.run(), 0.0)

    def create_show(self):
        plt.ion()
        fig_net = 'network'
        fig_table = 'table'

        if str2bool(self.net_opt['show']):
            if str2bool(self.net_opt['ipython_nb_show']):
                notebook = True
            else:
                notebook = False
            self.sh = ShowNet(net=self.net,
                              L=self.L,
                              sim=self,
                              fname=fig_net,
                              notebook=notebook)
            self.activate(self.sh, self.sh.run(), 1.0)

        if str2bool(self.net_opt['show_table']):
            self.sht = ShowTable(net=self.net,
                                 lAg=self.lAg,
                                 sim=self,
                                 fname=fig_table)
            self.activate(self.sht, self.sht.run(), 1.0)

    def runsimul(self):
        """ Run simulation
        """
        self.create()
        self.simulate(until=float(self.sim_opt['duration']),
                      real_time=True,
                      rel_speed=float(self.sim_opt['speedratio']))
        #        self.simulate(until=float(self.sim_opt['duration']))
        if self.save_opt['savep']:
            print 'Processing save results, please wait'
            self.save.mat_export()
Exemple #18
0
    def __init__(self, **args):
        """ Mobile Agent Init

           Parameters
           ----------
           'ID': string
                agent ID
           'name': string
                Agent name
           'type': string
                agent type . 'ag' for moving agent, 'ap' for static acces point
           'pos' : np.array([])
                numpy array containing the initial position of the agent
           'roomId': int
                Room number where the agent is initialized (Layout.Gr)
           'meca_updt': float
                update time interval for the mechanical process
           'loc': bool
                enable/disable localization process of the agent
           'loc_updt': float
                update time interval for localization process
           'Layout': pylayers.gis.Layout()
           'net':pylayers.network.Network(),
           'RAT': list of string
                list of used radio access techology of the agent
           'world': transit.world()
                Soon deprecated
           'save': list of string
                list of save method ( soon deprecated)
           'sim':Simpy.SimulationRT.Simulation(),
           'epwr': dictionnary
                dictionnary of emmited power of transsmitter{'rat#':epwr value}
           'sens': dictionnary
                dictionnary of sensitivity of reveicer {'rat#':sens value}
           'dcond': dictionnary
                Not used yet
           'gcom':pylayers.communication.Gcom()
                Communication graph
           'comm_mod': string
                Communication between nodes mode: 
                'autonomous': all TOAs are refreshed regulary
                'synchro' : only visilbe TOAs are refreshed 
        """
        defaults = {
            'ID': 0,
            'name': 'johndoe',
            'type': 'ag',
            'pos': np.array([]),
            'roomId': 0,
            'froom': [],
            'wait': [],
            'cdest': 'random',
            'meca_updt': 0.1,
            'loc': False,
            'loc_updt': 0.5,
            'loc_method': ['geo'],
            'Layout': Layout(),
            'net': Network(),
            'RAT': ['wifi'],
            'world': world(),
            'save': [],
            'sim': Simulation(),
            'epwr': {},
            'sens': {},
            'dcond': {},
            'gcom': Gcom(),
            'comm_mode': 'autonomous'
        }

        for key, value in defaults.items():
            if key not in args:
                args[key] = value

        self.args = args
        self.ID = args['ID']
        self.name = args['name']
        self.type = args['type']
        # Create Network
        self.net = args['net']
        self.epwr = args['epwr']
        self.gcom = args['gcom']
        try:
            self.dcond = args['dcond']
        except:
            pass

        if self.type == 'ag':
            # mechanical init
            self.meca = Person(ID=self.ID,
                               roomId=args['roomId'],
                               L=args['Layout'],
                               net=self.net,
                               interval=args['meca_updt'],
                               wld=args['world'],
                               sim=args['sim'],
                               moving=True,
                               froom=args['froom'],
                               wait=args['wait'],
                               cdest=args['cdest'],
                               save=args['save'])
            self.meca.behaviors = [Queuing(),Seek(), Containment(),\
                                   Separation(), InterpenetrationConstraint()]
            self.meca.steering_mind = queue_steering_mind
            #            self.meca.steering_mind = queue_steering_mind
            # filll in network

            ## Network init
            self.node = Node(ID=self.ID,
                             p=conv_vecarr(self.meca.position),
                             t=time.time(),
                             RAT=args['RAT'],
                             epwr=args['epwr'],
                             sens=args['sens'],
                             type=self.type)
            self.net.add_nodes_from(self.node.nodes(data=True))
            self.sim = args['sim']
            self.sim.activate(self.meca, self.meca.move(), 0.0)
            self.PN = self.net.node[self.ID]['PN']

            ## Communication init

            if args['comm_mode'] == 'synchro':
                ## The TOA requests are made every refreshTOA time ( can be modified in agent.ini)

                self.rxr = RX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)
                self.rxt = RX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)

                self.sim.activate(self.rxr, self.rxr.refresh_RSS(), 0.0)
                self.sim.activate(self.rxt, self.rxt.refresh_TOA(), 0.0)

            elif args['comm_mode'] == 'autonomous':
                ## The TOA requests are made by node only when they are in visibility of pairs.

                self.rxr = RX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)
                self.rxt = RX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)
                self.txt = TX(net=self.net,
                              ID=self.ID,
                              dcond=self.dcond,
                              gcom=self.gcom,
                              sim=self.sim)

                self.sim.activate(self.rxr, self.rxr.refresh_RSS(), 0.0)
                self.sim.activate(self.rxt, self.rxt.wait_TOArq(), 0.0)
                self.sim.activate(self.txt, self.txt.request_TOA(), 0.0)

        elif self.type == 'ap':
            if args['roomId'] == -1:
                self.node = Node(ID=self.ID,
                                 p=self.args['pos'],
                                 t=time.time(),
                                 RAT=args['RAT'],
                                 epwr=args['epwr'],
                                 sens=args['sens'],
                                 type=self.type)
            else:
                pp = np.array(args['Layout'].Gr.pos[self.args['roomId']])
                self.node = Node(ID=self.ID,
                                 p=pp,
                                 t=time.time(),
                                 RAT=args['RAT'],
                                 epwr=args['epwr'],
                                 sens=args['sens'],
                                 type=self.type)
            self.net.add_nodes_from(self.node.nodes(data=True))
            self.sim = args['sim']
            #            self.sim.activate(self.meca, self.meca.move(),0.0)
            self.PN = self.net.node[self.ID]['PN']
            self.PN.node[self.ID]['pe'] = self.net.node[self.ID]['p']

        else:
            raise NameError(
                'wrong agent type, it must be either agent (ag) or acces point (ap) '
            )

        if self.type == 'ap':
            self.MoA = 1
        else:
            self.MoA = 0

        if 'mysql' in args['save']:
            config = ConfigParser.ConfigParser()
            config.read(pyu.getlong('simulnet.ini', 'ini'))
            sql_opt = dict(config.items('Mysql'))
            db = Database(sql_opt['host'], sql_opt['user'], sql_opt['passwd'],
                          sql_opt['dbname'])
            db.writenode(self.ID, self.name, self.MoA)

        if 'txt' in args['save']:
            pyu.writenode(self)
        if args['loc'] and self.type != 'ap':

            self.loc = Localization(net=self.net,
                                    ID=self.ID,
                                    method=args['loc_method'])
            self.Ploc = PLocalization(loc=self.loc,
                                      loc_updt_time=args['loc_updt'],
                                      sim=args['sim'])
            self.sim.activate(self.Ploc, self.Ploc.run(), 1.5)
Exemple #19
0
class Simul(SimulationRT): # Sympy 2
#class Simul(sympy.RealtimeEnvironment):
    """

    Attributes
    ----------
    config  : config parser instance
    sim_opt : dictionary of configuration option for simulation
    ag_opt : dictionary of configuration option for agent
    lay_opt : dictionary of  configuration option for layout
    meca_opt : dictionary of  configuration option for mecanic
    net_opt : dictionary of  configuration option for network
    loc_opt : dictionary of  configuration option for localization
    save_opt : dictionary of  configuration option for save
    sql_opt : dictionary of  configuration option for sql

    Notes
    ------
     All the prvious dictionnary are obtained from the chosen simulnet.ini file
    in the project directory

    """
    def __init__(self):
        SimulationRT.__init__(self) #Sympy 2
        #sympy.RealtimeEnvironment.__init__(self)  #simpy 3
        self.initialize()
        self.config = ConfigParser.ConfigParser()
        filename = pyu.getlong('simulnet.ini','ini')
        self.config.read(filename)
        self.sim_opt = dict(self.config.items('Simulation'))
        self.lay_opt = dict(self.config.items('Layout'))
        self.meca_opt = dict(self.config.items('Mechanics'))
        self.net_opt = dict(self.config.items('Network'))
        self.loc_opt = dict(self.config.items('Localization'))
        self.save_opt = dict(self.config.items('Save'))
        self.sql_opt = dict(self.config.items('Mysql'))

        self.verbose = str2bool(self.sim_opt['verbose'])
        if str2bool(self.net_opt['ipython_nb_show']):
            self.verbose = False
        self.roomlist=[]

        self.create()

    def create_layout(self):
        """
        Create Layout in Simpy the_world thanks to Tk backend

        """

        self.the_world = world(width = float(self.lay_opt['the_world_width']), 
                               height = float(self.lay_opt['the_world_height']),
                               scale=float(self.lay_opt['the_world_scale']))

        # tk = self.the_world.tk
        # canvas, x_, y_ = tk.canvas, tk.x_, tk.y_
        # canvas.create_rectangle(x_(-1), y_(-1), x_(100), y_(100), fill='white')

        _filename = self.lay_opt['filename']
        #sl=Slab.SlabDB(self.lay_opt['slab'],self.lay_opt['slabmat'])
        #G1   = Graph.Graph(sl=sl,filename=_filename)
        self.L = Layout(_filename)
        #if _filename.split('.')[1] == 'str':
        #    self.L.loadstr(_filename)
        #elif _filename.split('.')[1] == 'str2':
        #    self.L.loadstr2(_filename)
        #elif _filename.split('.')[1] == 'ini':
        #    self.L.loadini(_filename)


        try:
            self.L.dumpr()
            print 'Layout graphs are loaded from ',basename,'/struc/ini'
        except:
        #self.L.sl = sl
        #self.L.loadGr(G1)
            print 'This is the first time the layout file is used\
            Layout graphs are curently being built, it may take few minutes.'
            self.L.build()     
            self.L.dumpw()
        x_offset = 0  # float(self.lay_opt['x_offset'])
        y_offset = 0  # float(self.lay_opt['y_offset'])
        for ks in self.L.Gs.pos.keys():
            self.L.Gs.pos[ks] = (self.L.Gs.pos[ks][0] +
                                 x_offset, self.L.Gs.pos[ks][1] + y_offset)
        for ks in self.L.Gr.pos.keys():
            self.L.Gr.pos[ks] = (self.L.Gr.pos[ks][0] +
                                 x_offset, self.L.Gr.pos[ks][1] + y_offset)
        for ks in self.L.Gw.pos.keys():
            self.L.Gw.pos[ks] = (self.L.Gw.pos[ks][0] +
                                 x_offset, self.L.Gw.pos[ks][1] + y_offset)

        #
        # Create Layout
        #
        walls = self.L.thwall(0, 0)
        for wall in walls:
            points = []
            # for point in wall:
            #          points.append(x_(point[0]))
            #          points.append(y_(point[1]))
            #      canvas.create_polygon(points, fill='maroon', outline='black')
            for ii in range(0, len(wall) - 1):
                self.the_world.add_wall(wall[ii], wall[ii + 1])

    def create_agent(self):
        """    
        create simulation's Agents

        ..todo:: change lAg list to a dictionnary ( modification in show.py too) 

        """


        self.lAg = []
        agents=[]
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        agents=eval(dict(Cf.items('used_agent'))['list'])
        for i, ag in enumerate(agents):
            ag_opt = dict(Cf.items(ag))
            self.lAg.append(Agent(
                            ID=ag_opt['id'],
                            name=ag_opt['name'],
                            type=ag_opt['type'],
                            pos=np.array(eval(ag_opt['pos'])),
                            roomId=int(ag_opt['roomid']),
                            froom=eval(ag_opt['froom']),
                            meca_updt=float(self.meca_opt['mecanic_update_time']),
                            wait=float(ag_opt['wait']),
                            cdest=eval(self.meca_opt['choose_destination']),
                            loc=str2bool(self.loc_opt['localization']),
                            loc_updt=float(self.loc_opt['localization_update_time']),
                            loc_method=eval(self.loc_opt['method']),
                            Layout=self.L,
                            net=self.net,
                            epwr=dict([(eval((ag_opt['rat']))[ep],eval((ag_opt['epwr']))[ep]) for ep in range(len(eval((ag_opt['rat']))))]),
                            sens=dict([(eval((ag_opt['rat']))[ep],eval((ag_opt['sensitivity']))[ep]) for ep in range(len(eval((ag_opt['rat']))))]),
                            world=self.the_world,
                            RAT=eval(ag_opt['rat']),
                            save=eval(self.save_opt['save']),
                            gcom=self.gcom,
                            comm_mode=eval(self.net_opt['communication_mode']),
                            sim=self))
#                            
            if self.lAg[i].type == 'ag':
                self.activate(self.lAg[i].meca,
                              self.lAg[i].meca.move(), 0.0)

    def create_EMS(self):
        """
            Electromagnetic Solver object
        """
        self.EMS = EMSolver(L=self.L)

    def create_network(self):
        """
            create the whole network
        """

        self.net = Network(EMS=self.EMS)
        self.gcom=Gcom(net=self.net,sim=self)

        self.create_agent()
        # create network

        self.net.create()

        # create All Personnal networks
        for n in self.net.nodes():
            self.net.node[n]['PN'].get_RAT()
            self.net.node[n]['PN'].get_SubNet()
        self.gcom.create()


       # create Process Network
        self.Pnet = PNetwork(net=self.net,
                             net_updt_time=float(self.net_opt['network_update_time']),
                             L=self.L,
                             sim=self,
                             show_sg=str2bool(self.net_opt['show_sg']),
                             disp_inf=str2bool(self.net_opt['dispinfo']),
                             save=eval(self.save_opt['save']))
        self.activate(self.Pnet, self.Pnet.run(), 0.0)

    def create_visual(self):
        """ Create visual Tk process
        """

        self.visu = Updater(
            interval=float(self.sim_opt['show_interval']), sim=self)
        self.activate(self.visu, self.visu.execute(), 0.0)

    def create(self):
        """ Create the simulation 
            This method is called at the end of __init__

        """

        # this is just to redump the database at each simulation
        if 'mysql' in self.save_opt['save']:
            if str2bool(self.sql_opt['dumpdb']):
                os.popen('mysql -u ' + self.sql_opt['user'] + ' -p ' + self.sql_opt['dbname'] +\
                '< /private/staff/t/ot/niamiot/svn2/devel/simulator/pyray/SimWHERE2.sql' )

        ## TODO supprimer la ref en dur 
        if 'txt' in self.save_opt['save']:
            pyu.writeDetails(self)
            if os.path.isfile(basename+'/output/Nodes.txt'):
                print 'would you like to erase previous txt files ?'
                A=raw_input()
                if A == 'y':
                    for f in os.listdir(basename+'/output/'):
                        try:
                            fi,ext=f.split('.')
                            if ext == 'txt':
                                os.remove(basename+'/output/'+f)
                        except:
                            pass
                        
        self.create_layout()
        self.create_EMS()
        self.create_network()
        if str2bool(self.sim_opt['showtk']):
            self.create_visual()
        self.create_show()

        if str2bool(self.save_opt['savep']):
            self.save=Save(L=self.L,net=self.net,sim=self)
            self.activate(self.save,self.save.run(),0.0)
#        if str2bool(self.save_opt['savep']):
#            self.save=Save(net=self.net,
#                    L= self.L,
#                    sim = self)
#            self.activate(self.save, self.save.run(), 0.0)



    def create_show(self):
        """ 
        """

        plt.ion()
        fig_net = 'network'
        fig_table = 'table'

        if str2bool(self.net_opt['show']):
            if str2bool(self.net_opt['ipython_nb_show']):
                notebook=True
            else:
                notebook =False
            self.sh = ShowNet(net=self.net, L=self.L,sim=self,fname=fig_net,notebook=notebook)
            self.activate(self.sh,self.sh.run(),1.0)

        if str2bool(self.net_opt['show_table']):
            self.sht = ShowTable(net=self.net,lAg=self.lAg,sim=self,fname=fig_table)
            self.activate(self.sht,self.sht.run(),1.0)


    def runsimul(self):
        """ Run simulation
        """

        self.simulate(until=float(self.sim_opt['duration']),
                      real_time=True,
                      rel_speed=float(self.sim_opt['speedratio']))
#        self.simulate(until=float(self.sim_opt['duration']))
        if self.save_opt['savep']:
            print 'Processing save results, please wait'
            self.save.mat_export()
Exemple #20
0
    def __init__(self,
                 ID=0,
                 interval=0.05,
                 roomId=0,
                 L=[],
                 net=Network(),
                 wld=world(),
                 sim=None,
                 moving=True,
                 froom=[],
                 wait=1.0,
                 cdest='random',
                 save=[]):
        """ Class Person
            inherits of Simpy.SimulationRT
        Attributes
        ----------
            ID    : float/hex/str/...
                    agent Id
            interval : float
                    refresh interval of agent mobility
            roomId : int
                    room ID where agent start when simulation is launched
            L : pylayers.gis.layout.Layout()
                Layout instance, in which the agent is moving
            net : pylayers.network.Network()
                Network instance, in which network agent are communicating.
                This is used for fill the true position filed of the graph
                It must be removed in a further version ( when a proper save instance
                would be created)
            wld : pylayers.mobility.transit.world.world()
                world instance. equivalent to layout but in the pytk framework. 
                TODO : remove in a further version
            sim : SimPy.Simulation.Simulation.RT()
                Simulation instance share by all the pylayer project. 
            moving : bool 
                indicate if the agent is moving or not ( relevant for acces poitns)
            froom : list
                list of forbiden rooms. 
            wait : float
                wait time of the agent when he has reach teh desitaion
            cdest : str
                method for choosing setination 'random ' of file read
            save : list
                list of save option type .
                It will be removed in a further version ( when a proper save instance
                would be created)


        Method
        ------
            Move : make the agent move
            update : DEPRECATED used for Tkinter plot

    """
        #GeomNetType = np.dtype([('Id',int),
        #        ('time',int),
        #           ('p',float,(1,3)),
        #           ('v',float,(1,3)),
        #           ('a',float,(1,3))])
        Person.npers += 1
        Process.__init__(self, name='Person_ID' + str(ID), sim=sim)
        self.ID = ID
        self.L = L
        self.world = wld
        self.interval = interval
        self.manager = None
        self.manager_args = []
        self.waypoints = []
        self.moving = moving
        self.roomId = roomId
        self.forbidroomId = froom
        self.cdest = cdest  # choose tdestination type
        if self.cdest == 'random':
            self.nextroomId = int(np.floor(uniform(0, self.L.Gr.size())))
            while self.nextroomId == self.roomId or (
                    self.nextroomId in self.forbidroomId
            ):  # or (self.nextroomId in self.sim.roomlist): # test destination different de l'arrive
                self.nextroomId = int(np.floor(uniform(0, self.L.Gr.size())))
            #self.sim.roomlist.append(self.nextroomId) # list of all destiantion of all nodes in object sim
        elif self.cdest == 'file':
            cfg = ConfigParser.ConfigParser()
            cfg.read(pyu.getlong('nodes_destination.ini', 'ini'))
            self.room_seq = eval(dict(cfg.items(self.ID))['room_seq'])
            self.room_wait = eval(dict(cfg.items(self.ID))['room_wait'])
            print 'WARNING: when nodes_destination ini file is read:'
            print '1) the room initialization starts in the first room of the list, not in the room configured in agent.ini'
            print '2) forbiden rooms are neglected'
            self.room_counter = 1
            self.nb_room = len(self.room_seq)
            self.roomId = self.room_seq[0]
            self.nextroomId = self.room_seq[self.room_counter]
            self.wait = self.room_wait[self.room_counter]
        #self.sim.roomlist.append(self.nextroomId) # list of all destiantion of all nodes in object sim
        self.wp = self.L.waypointGw(self.roomId, self.nextroomId)
        for tup in self.wp[1:]:
            self.waypoints.append(vec3(tup))
        try:
            self.position = vec3(L.Gr.pos[self.roomId][0],
                                 L.Gr.pos[self.roomId][1])
        except:
            self.position = vec3()
#           self.old_pos = vec3()
        self.stuck = 0
        self.destination = self.waypoints[0]
        self.velocity = vec3()
        self.localx = vec3(1, 0)
        self.localy = vec3(0, 1)
        self.world.add_boid(self)

        # from Helbing, et al "Self-organizing pedestrian movement"
        self.max_speed = 1.2  #normalvariate(1.0, 0.26)
        self.desired_speed = self.max_speed
        self.radius = normalvariate(self.average_radius, 0.025) / 2
        self.intersection = vec3()
        self.arrived = False
        self.endpoint = False
        self.behaviors = []
        self.steering_mind = default_steering_mind
        self.cancelled = 0
        self.net = net
        self.wait = wait
        self.save = save

        if 'mysql' in self.save:
            config = ConfigParser.ConfigParser()
            config.read(pyu.getlong('simulnet.ini', 'ini'))
            sql_opt = dict(config.items('Mysql'))
            self.db = Database(sql_opt['host'], sql_opt['user'],
                               sql_opt['passwd'], sql_opt['dbname'])
            self.date = datetime.datetime.now()
Exemple #21
0
class TX(Process):
    """
       TX process ( not used for now)
        Each agent use the TX process for querying LDP/information/message passing data
        to other agent
    """
    def __init__(self, **args):
        defaults = {
            'sim': None,
            'net': Network(),
            'gcom': Gcom(),
            'ID': 0,
            'dcond': {},
            'devt': {},
            'lcst': []
        }
        ##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key] = value
        self.args = args
        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()

        self.create_evt()

        #        self.c_init()
        Process.__init__(self, name='Tx' + str(self.ID), sim=self.sim)
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        for s in Cf.sections():
            try:
                d = dict(Cf.items(s))
                if d['id'] == self.ID:
                    self.refreshTOA = eval(d['refreshtoa'])
                    break
            except:
                pass

    def run(self):
        while True:
            self.levt = []
            for d in self.dcond.keys():
                if self.c_interpret(self.dcond[d]):
                    self.levt.append(self.dcste[c])
            print 'Tx ', self.ID, ' @', self.sim.now()
            yield hold, self, self.refresh

    def create_evt(self):
        """
        Create simpy events from communication gaph

        The available reception event for the given id are pickup into the
        communication graph to fill self.devt.

        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> T = TX()
        >>> T.create_evt()
        """
        for e in self.PN.edges(self.ID, keys=True):
            self.devt[e] = self.gcom.devt[e]

    def request_TOA(self):
        """
        Request TOA


        Every self.refreshTOA time interval, send a devent signal to nodes 
        in visibility torefresh the TOA information

        """
        self.create_evt()
        while 1:
            if self.sim.verbose:
                print 'request TOA', self.ID
            for rat in self.PN.SubNet.keys():
                for n in self.PN.SubNet[rat].edge[self.ID].keys():
                    # check nodes in visibility
                    if self.net.edge[self.ID][n][rat]['vis']:
                        key = '(\'' + self.ID + '\', \'' + n + '\', \'' + rat + '\')'
                        self.devt[eval(key)].signal()
            yield hold, self, self.refreshTOA
Exemple #22
0
    def __init__(self,
                 ID=0,
                 interval=0.05,
                 roomId=-1,
                 L=[],
                 net=Network(),
                 wld=world(),
                 seed=0,
                 sim=None,
                 moving=True,
                 froom=[],
                 wait=1.0,
                 cdest='random',
                 save=[],
                 color='k',
                 pdshow=False):
        """ Class Person
            inherits of Simpy.SimulationRT
            """
        #GeomNetType = np.dtype([('Id',int),
        #        ('time',int),
        #           ('p',float,(1,3)),
        #           ('v',float,(1,3)),
        #           ('a',float,(1,3))])
        Person.npers += 1
        Process.__init__(self, name='Person_ID' + str(ID), sim=sim)
        self.ID = ID
        self.color = color
        self.pdshow = pdshow
        self.L = L
        self.world = wld
        self.interval = interval
        self.manager = None
        self.manager_args = []
        self.waypoints = []
        self.moving = moving
        # random.seed(seed)

        if roomId < 0:
            try:
                self.roomId = random.sample(self.L.Gr.nodes(), 1)[0]
            except:
                raise NameError(
                    'This error is due to the lack of Gr graph in the Layout argument passed to Person(Object)'
                )
        else:
            self.roomId = roomId
        self.forbidroomId = froom
        self.cdest = cdest  # choose tdestination type
        if self.cdest == 'random':
            # self.nextroomId   = int(np.floor(random.uniform(0,self.L.Gr.size())))
            try:
                self.nextroomId = random.sample(self.L.Gr.nodes(), 1)[0]
            except:
                raise NameError(
                    'This error is due to the lack of Gr graph in the Layout argument passed to Person(Object)'
                )
            while self.nextroomId == self.roomId or (
                    self.nextroomId in self.forbidroomId
            ):  # or (self.nextroomId in self.sim.roomlist): # test destination different de l'arrive
                # self.nextroomId   = int(np.floor(random.uniform(0,self.L.Gr.size())))
                self.nextroomId = random.sample(self.L.Gr.nodes(), 1)[0]
            #self.sim.roomlist.append(self.nextroomId) # list of all destiantion of all nodes in object sim
        elif self.cdest == 'file':
            cfg = ConfigParser.ConfigParser()
            cfg.read(pyu.getlong('nodes_destination.ini', 'ini'))
            self.room_seq = eval(dict(cfg.items(self.ID))['room_seq'])
            self.room_wait = eval(dict(cfg.items(self.ID))['room_wait'])
            print 'WARNING: when nodes_destination ini file is read:'
            print '1) the room initialization starts in the first room of the list, not in the room configured in agent.ini'
            print '2) forbiden rooms are neglected'
            self.room_counter = 1
            self.nb_room = len(self.room_seq)
            self.roomId = self.room_seq[0]
            self.nextroomId = self.room_seq[self.room_counter]
            self.wait = self.room_wait[self.room_counter]
        #self.sim.roomlist.append(self.nextroomId) # list of all destiantion of all nodes in object sim

        self.rooms, self.wp = self.L.waypointGw(self.roomId, self.nextroomId)
        # self.dlist =  [i in self.L.Gw.ldo for i in self.rooms]
        for tup in self.wp[1:]:
            self.waypoints.append(vec3(tup))
        try:
            self.position = vec3(L.Gr.pos[self.roomId][0],
                                 L.Gr.pos[self.roomId][1])
        except:
            self.position = vec3()
#           self.old_pos = vec3()
        self.stuck = 0
        self.destination = self.waypoints[0]
        self.arrived_in = False
        self.velocity = vec3()
        self.acceleration = vec3()
        self.localx = vec3(1, 0)
        self.localy = vec3(0, 1)
        self.world.add_boid(self)

        # from Helbing, et al "Self-organizing pedestrian movement"
        maxspeed = 0.8
        self.max_speed = maxspeed  #random.normalvariate(maxspeed, 0.1)
        self.desired_speed = maxspeed
        self.radius = self.average_radius  #random.normalvariate(self.average_radius, 0.025) / 2
        self.intersection = vec3()
        self.arrived = False
        self.endpoint = False
        self.behaviors = []
        self.steering_mind = default_steering_mind
        self.cancelled = 0
        self.net = net
        self.wait = wait
        self.df = pd.DataFrame(columns=['t', 'x', 'y', 'vx', 'vy', 'ax', 'ay'])
        self.df._metadata = self.ID
        self.save = save

        if 'mysql' in self.save:
            config = ConfigParser.ConfigParser()
            config.read(pyu.getlong('simulnet.ini', 'ini'))
            sql_opt = dict(config.items('Mysql'))
            self.db = Database(sql_opt['host'], sql_opt['user'],
                               sql_opt['passwd'], sql_opt['dbname'])
            self.date = datetime.datetime.now()
Exemple #23
0
class TX(Process):
    """
       TX process ( not used for now)
        Each agent use the TX process for querying LDP/information/message passing data
        to other agent
    """
    def __init__(self,**args):
        defaults={'sim':None,
                  'net': Network(),
                  'gcom': Gcom(),
                  'ID': 0,
                  'dec':{},
                  'devt': {},
                  'lcst': []
                  }
##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value
        self.args=args
        self.gcom=self.args['gcom']


        self.cmdrq=SimEvent('RQ'+str(self.ID),sim=self.sim) # command request

        try:
            self.PN=self.net.node[self.ID]['PN']
        except:
            self.PN=Network()

#        self.create_evt()

#        self.c_init()
        Process.__init__(self,name='Tx'+str(self.ID),sim=self.sim)
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshTOA=eval(d['refreshtoa'])
                    break
            except:
                pass


    def run(self):
        while True:
            self.levt=[]
            for d in self.dcond.keys():
                if self.c_interpret(self.dcond[d]):
                    self.levt.append(self.dcste[c])
            print 'Tx ', self.ID,' @',self.sim.now()
            yield hold, self, self.refresh


    def create_evt(self):
        """
        Create simpy events from communication gaph

        The available reception event for the given id are pickup into the
        communication graph to fill self.devt.

        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> T = TX()
        >>> T.create_evt()
        """
        for e in self.PN.edges(self.ID,keys=True):
            self.devt[e]=self.gcom.devt[e]



#    def request_TOA(self):
#        """
#        Request TOA


#        Every self.refreshTOA time interval, send a devent signal to nodes
#        in visibility torefresh the TOA information

#        """
#        self.create_evt()
#        while 1:
#            if self.sim.verbose:
#                print 'request TOA', self.ID
#            for wstd in self.PN.SubNet.keys():
#                for n in self.PN.SubNet[wstd].edge[self.ID].keys():
#                    # check nodes in visibility
#                    if self.net.edge[self.ID][n][wstd]['vis']:
#                        key='(\''+self.ID+'\', \''+n+'\', \''+wstd+'\')'
#                        self.devt[eval(key)].signal()
#            yield hold, self, self.refreshTOA
##                    devt[]
##                [self.PN.edge[self.ID][n][wstd].update(
##                {'TOA':self.net.edge[self.ID][n][wstd]['TOA'],'tTOA':self.sim.now()})
##                for n in self.PN.SubNet[wstd].edge[self.ID].keys() if self.net.edge[self.ID][n][wstd]['vis']]
##            print 'refresh TOA node', self.ID, ' @',self.sim.now()



    def interpret_dec(self):
        """ interpret decision rule from self.dec
        """

        # n dict{wstd:np.array([node ids])}
        n={}
        # loop on wstd
        for wstd in self.dec['wstd']:
            try:
            # get all nodes connecteed to self.ID on subnetwork wstd
                n[wstd]=np.array(self.PN.SubNet[wstd].edges())[:,1]

                # initialize remained nodes to True
                rn = [True]*len(n[wstd])
                # loop on condition
                for r in self.dec['rule']:

                    if r == 'always':
                        pass

                # mettre boolean dans variable pour condition a plus d41 regle
                    if 'rssth' in r:
                        # rssth<100
                        rntmp = np.array(nx.get_edge_attributes(self.PN.SubNet[wstd],'Pr').values())
                        if len(r.split('<')) > 1:
                            rn = rn and ( rntmp  < eval(r.split('<')[1]) )
                        elif len(r.split('>')) > 1:
                            rn = rn and ( rntmp  > eval(r.split('>')[1]) )

    #                elif 'distance' in r :
    #                    # distance < 10
    #                    rntmp = np.array(nx.get_edge_attributes(self.net.SubNet[wstd],'d').values())
    #                    if len(r.split('<')) > 1:
    #                        rn = rn and ( rntmp  < eval(r.split('<')[1]) )
    #                    elif len(r.split('>')) > 1:
    #                        rn = rn and ( rntmp  > eval(r.split('<')[1]) )

                n[wstd][np.where(rn)]

            except:
                n[wstd]=np.array(())

        # retrun only node id which are compliant with rules
        return (n)


    def request(self):
        """ request a transmission commanded by localizaiton
        """
        self.dec = self.gcom.dec[self.ID]
        self.create_evt()
        while 1:
            # wait request localization from localization layer
            yield waitevent,self,self.cmdrq
            if self.sim.verbose:
                print "communication requested by node ",self.ID

            # n = nodes compliant with the rules given in communication.py
            #     and in self.gcom.dec[self.ID]
            rn = self.interpret_dec()


            # send a signal (a.k.a. request transmission) to nodes in n
            for wstd in rn.keys():
                for n in rn[wstd]:
                    # check if nodes in visibility
                    if self.net.edge[self.ID][n][wstd]['vis']:
                        key='(\''+self.ID+'\', \''+n+'\', \''+wstd+'\')'
                        # WARNING : PLEASE LEAVE THE 2 FOLLOWING LINES
                        # this is not a bad copy paste. It is required
                        # to force signalization ( probably a SimPy bug)
                        self.devt[eval(key)].signal()
                        self.devt[eval(key)].signal()
Exemple #24
0
class TX(Process):
    """
       TX process ( not used for now)
        Each agent use the TX process for querying LDP/information/message passing data
        to other agent
    """
    def __init__(self,**args):
        defaults={'sim':None,
                  'net': Network(),
                  'gcom': Gcom(),
                  'ID': 0,
                  'dcond':{},
                  'devt': {},
                  'lcst': []
                  }
##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value  
        self.args=args
        try:
            self.PN=self.net.node[self.ID]['PN']
        except:
            self.PN=Network()

        self.create_evt()

#        self.c_init()
        Process.__init__(self,name='Tx'+str(self.ID),sim=self.sim)
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshTOA=eval(d['refreshtoa'])
                    break
            except:
                pass


    def run(self):
        while True:
            self.levt=[]
            for d in self.dcond.keys():
                if self.c_interpret(self.dcond[d]):
                    self.levt.append(self.dcste[c])
            print 'Tx ', self.ID,' @',self.sim.now()
            yield hold, self, self.refresh


    def create_evt(self):
        """
        Create simpy events from communication gaph

        The available reception event for the given id are pickup into the
        communication graph to fill self.devt.

        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> T = TX()
        >>> T.create_evt()
        """
        for e in self.PN.edges(self.ID,keys=True):
            self.devt[e]=self.gcom.devt[e]


    def request_TOA(self):
        """
        Request TOA


        Every self.refreshTOA time interval, send a devent signal to nodes 
        in visibility torefresh the TOA information

        """
        self.create_evt()
        while 1:
            if self.sim.verbose:
                print 'request TOA', self.ID
            for rat in self.PN.SubNet.keys():
                for n in self.PN.SubNet[rat].edge[self.ID].keys():
                    # check nodes in visibility
                    if self.net.edge[self.ID][n][rat]['vis']:
                        key='(\''+self.ID+'\', \''+n+'\', \''+rat+'\')'
                        self.devt[eval(key)].signal()
            yield hold, self, self.refreshTOA
Exemple #25
0
class Simul(object):  # Simpy 3
    """

    Attributes
    ----------

    config  : config parser instance
    sim_opt : dictionary of configuration option for simulation
    ag_opt : dictionary of configuration option for agent
    lay_opt : dictionary of  configuration option for layout
    meca_opt : dictionary of  configuration option for mecanic
    net_opt : dictionary of  configuration option for network
    loc_opt : dictionary of  configuration option for localization
    save_opt : dictionary of  configuration option for save
    sql_opt : dictionary of  configuration option for sql


    Parameters
    ----------

    self.lAg  : list of Agent(Object)
        list of agents involved in simulation
    self.L : Layout
        Layout used in simulation

    Note
    ----

    All the previous dictionnary are obtained from the chosen simulnet.ini file
    in the project directory

    """

    def __init__(self):

        #SimulationRT.__init__(self)  # Simpy 2
        simpy.RealtimeEnvironment.__init__(self)  #simpy 3
        #self.initialize()

        self.config = ConfigParser.ConfigParser(inline_comment_prefixes=(';',),comment_prefixes=('#',';'))
        filename = pyu.getlong('simulnet.ini', pstruc['DIRSIMUL'])

        self.config.read(filename)
        self.sim_opt = dict(self.config.items('Simulation'))
        self.lay_opt = dict(self.config.items('Layout'))
        self.meca_opt = dict(self.config.items('Mechanics'))
        self.net_opt = dict(self.config.items('Network'))
        self.loc_opt = dict(self.config.items('Localization'))
        self.save_opt = dict(self.config.items('Save'))
        self.sql_opt = dict(self.config.items('Mysql'))
        self.seed = eval(self.sim_opt['seed'])

        self.traj = Trajectories()

        self.verbose = str2bool(self.sim_opt['verbose'])
        if str2bool(self.net_opt['ipython_nb_show']):
            self.verbose = False
        self.roomlist = []

        self.finish = False
        self.create()

    def __repr__(self):

        s = 'Simulation information' + '\n----------------------'
        s = s + '\nLayout: ' + self.lay_opt['filename']
        s = s + '\nSimulation duration: ' + str(self.sim_opt['duration'])
        s = s + '\nRandom seed: ' + str(self.sim_opt['seed'])
        s = s + '\nSave simulation: ' + self.save_opt['savep']

        s = s + '\n\nUpdate times' + '\n-------------'
        s = s + '\nMechanical update: ' + \
            str(self.meca_opt['mecanic_update_time'])
        s = s + '\nNetwork update: ' + str(self.net_opt['network_update_time'])
        s = s + '\nLocalization update: ' + self.net_opt['communication_mode']

        s = s + '\n\nAgents => self.lAg[i]' + '\n------'
        s = s + '\nNumber of agents :' + str(len(self.lAg))
        s = s + '\nAgents IDs: ' + \
            str([self.lAg[i].ID for i in range(len(self.lAg))])
        s = s + '\nAgents names: ' + \
            str([self.lAg[i].name for i in range(len(self.lAg))])
        s = s + '\nDestination of chosen agents: ' + \
            self.meca_opt['choose_destination']

        s = s + '\n\nNetwork' + '\n-------'
        s = s + '\nNodes per wstd: ' + str(self.net.wstd)

        s = s + '\n\nLocalization' + '\n------------'
        s = s + '\nLocalization enable: ' + self.loc_opt['localization']
        s = s + '\nPostion estimation methods: ' + self.loc_opt['method']

        return s

    def create_layout(self):
        """ create Layout in Simpy the_world thanks to Tk backend

        """

        _filename = self.lay_opt['filename']

        self.L = Layout(_filename)
        self.L.build()
        self.L.buildGr()
        self.L.buildGw()

        self.the_world = world()

        try:
            self.L.dumpr()
            print('Layout graphs are loaded from ' + basename + '/struc/ini')
        except:
            #self.L.sl = sl
            # self.L.loadGr(G1)
            print('This is the first time the layout file is used\
            Layout graphs are curently being built, it may take few minutes.')
            self.L.build()
            self.L.dumpw()

        #
        # Create Layout
        #
        walls = self.L.thwall(0, 0)
        for wall in walls:
            for ii in range(0, len(wall) - 1):
                self.the_world.add_wall(wall[ii], wall[ii + 1])

    def create_agent(self):
        """ create simulation's Agents

        ..todo:: change lAg list to a dictionnary ( modification in show.py too) 

        """

        self.lAg = []
        agents = []
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        agents = eval(dict(Cf.items('used_agent'))['list'])
        for i, ag in enumerate(agents):
            ag_opt = dict(Cf.items(ag))
            self.lAg.append(
                    Agent(
                    ID=ag_opt['id'],
                    name=ag_opt['name'],
                    typ=ag_opt['typ'],
                    color=eval(ag_opt['color']),
                    pdshow=str2bool(self.meca_opt['pdshow']),
                    pos=np.array(eval(ag_opt['pos'])),
                    roomId=int(ag_opt['roomid']),
                    froom=eval(ag_opt['froom']),
                    meca_updt=float(self.meca_opt['mecanic_update_time']),
                    wait=float(ag_opt['wait']),
                    cdest=eval(self.meca_opt['choose_destination']),
                    loc=str2bool(self.loc_opt['localization']),
                    loc_updt=float(self.loc_opt['localization_update_time']),
                    loc_method=eval(self.loc_opt['method']),
                    L=self.L,
                    network=str2bool(self.net_opt['network']),
                    net=self.net,
                    epwr=dict([(eval((ag_opt['wstd']))[ep], 
                                eval((ag_opt['epwr']))[ep]) 
                                for ep in range(len(eval((ag_opt['wstd']))))]),
                    sens=dict([(eval((ag_opt['wstd']))[ep],
                                eval((ag_opt['sensitivity']))[ep]) 
                                for ep in range(len(eval((ag_opt['wstd']))))]),
                    world=self.the_world,
                    wstd=eval(ag_opt['wstd']),
                    save=eval(self.save_opt['save']),
                    gcom=self.gcom,
                    comm_mode=eval(self.net_opt['communication_mode']),
                    sim=self,
                    seed=self.seed))

    def create_EMS(self):
        """ create electromagnetic Solver object

        """
        self.EMS = EMSolver(L=self.L)

    def create_network(self):
        """ create the whole network
        """

        self.net = Network(EMS=self.EMS)
        self.gcom = Gcom(net=self.net, sim=self)

        self.create_agent()
        # create network
        if str2bool(self.net_opt['network']):
            self.net.create()

            # create All Personnal networks
            for n in self.net.nodes():
                self.net.node[n]['PN']._get_wstd()
                self.net.node[n]['PN']._get_SubNet()
            self.gcom.create()

           # create Process Network
            self.Pnet = PNetwork(net=self.net,
                                 net_updt_time=float(
                                     self.net_opt['network_update_time']),
                                 L=self.L,
                                 sim=self,
                                 show_sg=str2bool(self.net_opt['show_sg']),
                                 disp_inf=str2bool(self.net_opt['dispinfo']),
                                 save=eval(self.save_opt['save']))
            self.activate(self.Pnet, self.Pnet.run(), 0.0)

    def create_visual(self):
        """ create visual Tk process
        """

        self.visu = Updater(
            interval=float(self.sim_opt['show_interval']), sim=self)
        self.activate(self.visu, self.visu.execute(), 0.0)

    def create(self):
        """ create the simulation
            This method is called at the end of __init__

        """
        # this is to redump the database at each simulation
        if 'mysql' in self.save_opt['save']:
            if str2bool(self.sql_opt['dumpdb']):
                os.popen('mysql -u ' + self.sql_opt['user'] + ' -p ' + self.sql_opt['dbname'] +
                         '< /private/staff/t/ot/niamiot/svn2/devel/simulator/pyray/SimWHERE2.sql')

        # TODO remove the hard reference
        if 'txt' in self.save_opt['save']:
            pyu.writeDetails(self)
            if os.path.isfile(os.path.join(basename, 'output', 'Nodes.txt')):
                print('would you like to erase previous txt files ?')
                A = raw_input()
                if A == 'y':
                    for f in os.listdir(os.path.join(basename, 'output')):
                        try:
                            fi, ext = f.split('.')
                            if ext == 'txt':
                                os.remove(os.path.join(basename, 'output' + f))
                        except:
                            pass

        # Layout
        self.create_layout()
        # Electro Magnetic Simulator
        self.create_EMS()
        # Network
        self.create_network()

        if str2bool(self.sim_opt['showtk']):
            self.create_visual()
        self.create_show()

        if str2bool(self.save_opt['savep']):
            self.save = Save(L=self.L, net=self.net, sim=self)
            self.activate(self.save, self.save.run(), 0.0)

    def create_show(self):
        """ create a vizualization
        """

        plt.ion()
        fig_net = 'network'
        fig_table = 'table'

        if str2bool(self.net_opt['show']):
            if str2bool(self.net_opt['ipython_nb_show']):
                notebook = True
            else:
                notebook = False
            self.sh = ShowNet(net=self.net, L=self.L, sim=self,
                              fname=fig_net, notebook=notebook)
            self.activate(self.sh, self.sh.run(), 1.0)

        if str2bool(self.net_opt['show_table']):
            self.sht = ShowTable(net=self.net, lAg=self.lAg,
                                 sim=self, fname=fig_table)
            self.activate(self.sht, self.sht.run(), 1.0)

    def savepandas(self):
        """ save mechanics in pandas hdf5 format
        """
        filename = pyu.getlong(
            eval(self.sim_opt["filename"]), pstruc['DIRNETSAVE'])
        layfile = self.L._filename.split('.')[0]
        store = pd.HDFStore(filename + '_' + layfile + '.h5', 'w')
        for a in self.lAg:

            if a.typ != 'ap':
                store.put(a.ID, a.meca.df.convert_objects())

            else:  # if agent acces point, its position is saved
                store.put(a.ID, a.posdf)

            store.get_storer(a.ID).attrs.typ = a.typ
            store.get_storer(a.ID).attrs.name = a.name
            store.get_storer(a.ID).attrs.ID = a.ID
            store.get_storer(a.ID).attrs.layout = self.L._filename
        # saving metadata
        store.root._v_attrs.attributes=self.sim_opt
        store.close()
        self.traj.loadh5(
            eval(self.sim_opt["filename"]) + '_' + layfile + '.h5')





    def runsimul(self):
        """ run simulation
        """

        if not self.finish:
            # random number seed
            seed(self.seed)
            self.simulate(until=float(self.sim_opt['duration']),
                          real_time=True,
                          rel_speed=float(self.sim_opt['speedratio']))

            self.the_world._boids = {}

            # if str2bool(self.save_opt['savep']):
            # print 'Processing save results, please wait'
            # self.save.mat_export()

            if str2bool(self.save_opt['savepd']):
                self.savepandas()
            self.finish = True
        else:
            raise NameError('Reinstantiate a new simul object to run again')
Exemple #26
0
class RX(Process):
    """
    RX process

    Each agent has a RX process to receive information asynchronously.

    Attributes
    ----------
    sim : SimPy.SimulationRT()
    ID : string
        id of the agent
    net : pylayers.network.network()
    gcom : pylayers.network.communication()
        a graph a communication
    devt : dictionary
        dictionnary of event
    refreshRSS : float
        time interval where RSS are refreshed
    refreshTOA : float
        time interval where TOA are refresh (if agent.comm_mode =='syncho')
    mp : bool
        message passing [Not yet implemented]
    """
    def __init__(self, **args):
        defaults = {
            'sim': None,
            'ID': '1',
            'net': Network(),
            'gcom': Gcom(),
            'devt': {},
            'refreshRSS': 0.3,
            'refreshTOA': 0.3,
            'mp': False
        }
        ##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key] = value
        self.args = args
        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()
        self.create_evt()

        Process.__init__(self, name='Rx-' + str(self.ID), sim=self.sim)

        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini', 'ini'))
        for s in Cf.sections():
            try:
                d = dict(Cf.items(s))
                if d['id'] == self.ID:
                    self.refreshRSS = eval(d['refreshrss'])
                    self.refreshTOA = eval(d['refreshtoa'])
                    break

            except:
                pass

    def swap_lt(self, lt):
        """
        For a list of tuple if the first element is self.ID,
        it is swapped with the second element
   
        
        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> R = RX()
        >>> R.ID
        '1'
        >>> lt= [('1','0','tuple1'),('10','5','tuple2')]
        >>> R.swap_lt(lt) # only first tuple is swapped because R.ID='1'
        [('0', '1', 'tuple1'), ('10', '5', 'tuple2')]

        """
        lto = []
        for t in lt:
            if t[0] == self.ID:
                lto.append((t[1], t[0], t[2]))
            else:
                lto.append((t[0], t[1], t[2]))
        return lto

    def create_evt(self):
        """
        Create simpy events from communication gaph

        The available reception event for the given id are pickup into the
        communication graph to fill self.devt.

        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> R = RX()
        >>> R.create_evt()

        """
        rPNe = self.swap_lt(self.PN.edges(keys=True))
        for e in rPNe:
            self.devt[e] = self.gcom.devt[e]
        if self.mp:
            for e in rPNe:
                self.devt[e] = self.gcom.devt[e + str(mp)]

    def refresh_RSS(self):
        """
            Refresh RSS process

            The RSS values on the edges of the Personnal Network of node self.ID 
            are refreshed every self.refreshRSS
        """
        self.create_evt()
        while 1:
            for rat in self.PN.SubNet.keys():

                # 2 approach to determine visibility
                ##  1) test visibility during the refresh
                #                [self.PN.edge[self.ID][n][rat].update(
                #                {'Pr':self.net.edge[self.ID][n][rat]['Pr'],
                #                'tPr':self.sim.now(),
                #                'vis':self.net.edge[self.ID][n][rat]['Pr'][0]>self.net.node[self.ID]['sens'][rat]})
                #                for n in self.PN.SubNet[rat].edge[self.ID].keys()]

                #  2) copy the visibility information from network layer
                [
                    self.PN.edge[self.ID][n][rat].update({
                        'Pr':
                        self.net.edge[self.ID][n][rat]['Pr'],
                        'tPr':
                        self.sim.now(),
                        'vis':
                        self.net.edge[self.ID][n][rat]['vis']
                    }) for n in self.PN.SubNet[rat].edge[self.ID].keys()
                ]

            if self.sim.verbose:
                print 'refresh RSS node', self.ID, ' @', self.sim.now()

            yield hold, self, self.refreshRSS

    def refresh_TOA(self):
        """
            Refresh TOA process

            The TOA values on the edges of the Personnal Network of node self.ID
            are refreshed every self.refreshTOA
        """
        self.create_evt()

        while 1:
            for rat in self.PN.SubNet.keys():

                # 2 approaches :
                ## 1) that commented code allow refresh TOA only when visibility
                #                [self.PN.edge[self.ID][n][rat].update(
                #                {'TOA':self.net.edge[self.ID][n][rat]['TOA'],'tTOA':self.sim.now()})
                #                for n in self.PN.SubNet[rat].edge[self.ID].keys() if self.net.edge[self.ID][n][rat]['vis']]

                # 2 refresj TOa whatever visibility or not
                [
                    self.PN.edge[self.ID][n][rat].update({
                        'TOA':
                        self.net.edge[self.ID][n][rat]['TOA'],
                        'tTOA':
                        self.sim.now()
                    }) for n in self.PN.SubNet[rat].edge[self.ID].keys()
                ]

            if self.sim.verbose:
                print 'refresh TOA node', self.ID, ' @', self.sim.now()

            yield hold, self, self.refreshTOA

    def wait_TOArq(self):
        """
            Wait TOA request

            The self.ID node wait a TOA request from another node of its Personal network.
            Once the request is received, self.ID reply to the requester node 
            and fill the PN edge with the measured TOA.
        """
        self.create_evt()
        while 1:
            yield waitevent, self, self.devt.values()
            for evt in self.devt.values():
                if evt.occurred:
                    # evt.name[0] = requester
                    # evt.name[1] = requested ( = self.ID)
                    # evt.name[2] = rat
                    # update personal network TOA value
                    self.PN.edge[evt.name[1]][evt.name[0]][evt.name[2]].update(
                        {
                            'TOA':
                            self.net.edge[evt.name[1]][evt.name[0]][
                                evt.name[2]]['TOA'],
                            'tTOA':
                            self.sim.now()
                        })
                    if self.sim.verbose:
                        print 'TOA requested by', evt.name[0], 'to', evt.name[
                            1], 'has been updated'
                    break
Exemple #27
0
class Simul(SimulationRT): # Sympy 2
#class Simul(sympy.RealtimeEnvironment):
    """

    Attributes
    ----------
    config  : config parser instance
    sim_opt : dictionary of configuration option for simulation
    ag_opt : dictionary of configuration option for agent
    lay_opt : dictionary of  configuration option for layout
    meca_opt : dictionary of  configuration option for mecanic
    net_opt : dictionary of  configuration option for network
    loc_opt : dictionary of  configuration option for localization
    save_opt : dictionary of  configuration option for save
    sql_opt : dictionary of  configuration option for sql


    Parameters
    ----------

    self.lAg  : list of Agent(Object)
        list of agents involved in simulation
    self.L : Layout
        Layout used in simulation

    Notes
    -----

    All the previous dictionnary are obtained from the chosen simulnet.ini file
    in the project directory

    """
    def __init__(self):
        SimulationRT.__init__(self) #Sympy 2
        #sympy.RealtimeEnvironment.__init__(self)  #simpy 3
        self.initialize()
        self.config = ConfigParser.ConfigParser()
        filename = pyu.getlong('simulnet.ini',pstruc['DIRSIMUL'])
        self.config.read(filename)
        self.sim_opt = dict(self.config.items('Simulation'))
        self.lay_opt = dict(self.config.items('Layout'))
        self.meca_opt = dict(self.config.items('Mechanics'))
        self.net_opt = dict(self.config.items('Network'))
        self.loc_opt = dict(self.config.items('Localization'))
        self.save_opt = dict(self.config.items('Save'))
        self.sql_opt = dict(self.config.items('Mysql'))
        self.seed = eval(self.sim_opt['seed'])
        self.traj=Trajectories()

        self.verbose = str2bool(self.sim_opt['verbose'])
        if str2bool(self.net_opt['ipython_nb_show']):
            self.verbose = False
        self.roomlist=[]

        self.finish = False
        self.create()

    def __repr__(self):

        s = 'Simulation information' + '\n----------------------'
        s = s + '\nLayout: ' + self.lay_opt['filename']
        s = s + '\nSimulation duration: ' + self.sim_opt['duration']
        s = s + '\nRandom seed: ' + self.sim_opt['seed']
        s = s + '\nSave simulation: ' + self.save_opt['savep']

        s = s + '\n\nUpdate times' + '\n-------------'
        s = s + '\nMechanical update: ' + self.meca_opt['mecanic_update_time']
        s = s + '\nNetwork update: ' + self.net_opt['network_update_time']
        s = s + '\nLocalization update: ' + self.net_opt['communication_mode']

        s = s + '\n\nAgents => self.lAg[i]' + '\n------'
        s = s + '\nNumber of agents :' + str(len(self.lAg))
        s = s + '\nAgents IDs: ' + str([self.lAg[i].ID for i in range(len(self.lAg))])
        s = s + '\nAgents names: ' + str([self.lAg[i].name for i in range(len(self.lAg))])
        s = s + '\nDestination of chosen agents: ' + self.meca_opt['choose_destination']

        s = s + '\n\nNetwork' + '\n-------'
        s = s + '\nNodes per wstd: ' + str(self.net.wstd)

        s = s + '\n\nLocalization'  + '------------'
        s = s + '\nLocalization enable: ' + self.loc_opt['localization']
        s = s + '\nPostion estimation methods: ' + self.loc_opt['method']


        return s


    def create_layout(self):
        """ create Layout in Simpy the_world thanks to Tk backend

        """

        _filename = self.lay_opt['filename']

        self.L = Layout(_filename)

        self.the_world = world()

        try:
            self.L.dumpr()
            print 'Layout graphs are loaded from ',basename,'/struc/ini'
        except:
        #self.L.sl = sl
        #self.L.loadGr(G1)
            print 'This is the first time the layout file is used\
            Layout graphs are curently being built, it may take few minutes.'
            self.L.build()     
            self.L.dumpw()

        #
        # Create Layout
        #
        walls = self.L.thwall(0, 0)
        for wall in walls:
            for ii in range(0, len(wall) - 1):
                self.the_world.add_wall(wall[ii], wall[ii + 1])

    def create_agent(self):
        """ create simulation's Agents

        ..todo:: change lAg list to a dictionnary ( modification in show.py too) 

        """


        self.lAg = []
        agents=[]
        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        agents=eval(dict(Cf.items('used_agent'))['list'])
        for i, ag in enumerate(agents):
            ag_opt = dict(Cf.items(ag))
            self.lAg.append(Agent(
                            ID=ag_opt['id'],
                            name=ag_opt['name'],
                            typ=ag_opt['typ'],
                            color=eval(ag_opt['color']),
                            pdshow=str2bool(self.meca_opt['pdshow']),
                            pos=np.array(eval(ag_opt['pos'])),
                            roomId=int(ag_opt['roomid']),
                            froom=eval(ag_opt['froom']),
                            meca_updt=float(self.meca_opt['mecanic_update_time']),
                            wait=float(ag_opt['wait']),
                            cdest=eval(self.meca_opt['choose_destination']),
                            loc=str2bool(self.loc_opt['localization']),
                            loc_updt=float(self.loc_opt['localization_update_time']),
                            loc_method=eval(self.loc_opt['method']),
                            L=self.L,
                            network=str2bool(self.net_opt['network']),
                            net=self.net,
                            epwr=dict([(eval((ag_opt['wstd']))[ep],eval((ag_opt['epwr']))[ep]) for ep in range(len(eval((ag_opt['wstd']))))]),
                            sens=dict([(eval((ag_opt['wstd']))[ep],eval((ag_opt['sensitivity']))[ep]) for ep in range(len(eval((ag_opt['wstd']))))]),
                            world=self.the_world,
                            wstd=eval(ag_opt['wstd']),
                            save=eval(self.save_opt['save']),
                            gcom=self.gcom,
                            comm_mode=eval(self.net_opt['communication_mode']),
                            sim=self,
                            seed=self.seed))


    def create_EMS(self):
        """ electromagnetic Solver object
        """
        self.EMS = EMSolver(L=self.L)

    def create_network(self):
        """ create the whole network
        """

        self.net = Network(EMS=self.EMS)
        self.gcom=Gcom(net=self.net,sim=self)

        self.create_agent()
        # create network
        if str2bool(self.net_opt['network']):
            self.net.create()

            # create All Personnal networks
            for n in self.net.nodes():
                self.net.node[n]['PN']._get_wstd()
                self.net.node[n]['PN']._get_SubNet()
            self.gcom.create()


           # create Process Network
            self.Pnet = PNetwork(net=self.net,
                                 net_updt_time=float(self.net_opt['network_update_time']),
                                 L=self.L,
                                 sim=self,
                                 show_sg=str2bool(self.net_opt['show_sg']),
                                 disp_inf=str2bool(self.net_opt['dispinfo']),
                                 save=eval(self.save_opt['save']))
            self.activate(self.Pnet, self.Pnet.run(), 0.0)

    def create_visual(self):
        """ create visual Tk process
        """

        self.visu = Updater(
            interval=float(self.sim_opt['show_interval']), sim=self)
        self.activate(self.visu, self.visu.execute(), 0.0)

    def create(self):
        """ create the simulation
            This method is called at the end of __init__

        """

        # this is just to redump the database at each simulation
        if 'mysql' in self.save_opt['save']:
            if str2bool(self.sql_opt['dumpdb']):
                os.popen('mysql -u ' + self.sql_opt['user'] + ' -p ' + self.sql_opt['dbname'] +\
                '< /private/staff/t/ot/niamiot/svn2/devel/simulator/pyray/SimWHERE2.sql' )

        ## TODO supprimer la ref en dur 
        if 'txt' in self.save_opt['save']:
            pyu.writeDetails(self)
            if os.path.isfile(basename+'/output/Nodes.txt'):
                print 'would you like to erase previous txt files ?'
                A=raw_input()
                if A == 'y':
                    for f in os.listdir(basename+'/output/'):
                        try:
                            fi,ext=f.split('.')
                            if ext == 'txt':
                                os.remove(basename+'/output/'+f)
                        except:
                            pass

        self.create_layout()
        self.create_EMS()
        self.create_network()
        if str2bool(self.sim_opt['showtk']):
            self.create_visual()
        self.create_show()

        if str2bool(self.save_opt['savep']):
            self.save=Save(L=self.L,net=self.net,sim=self)
            self.activate(self.save,self.save.run(),0.0)

    def create_show(self):
        """ create a vizualization
        """

        plt.ion()
        fig_net = 'network'
        fig_table = 'table'

        if str2bool(self.net_opt['show']):
            if str2bool(self.net_opt['ipython_nb_show']):
                notebook=True
            else:
                notebook =False
            self.sh = ShowNet(net=self.net, L=self.L,sim=self,fname=fig_net,notebook=notebook)
            self.activate(self.sh,self.sh.run(),1.0)

        if str2bool(self.net_opt['show_table']):
            self.sht = ShowTable(net=self.net,lAg=self.lAg,sim=self,fname=fig_table)
            self.activate(self.sht,self.sht.run(),1.0)


    def savepandas(self):
        """ save mechanics in pandas hdf5 format
        """
        filename=pyu.getlong(eval(self.sim_opt["filename"]),pstruc['DIRNETSAVE'])
        layfile = self.L.filename.split('.')[0]
        store = pd.HDFStore(filename+'_'+layfile+'.h5','w')
        for a in self.lAg :

            if a.typ != 'ap':
                store.put( a.ID,a.meca.df.convert_objects() )

            else : # if agent acces point, its position is saved
                store.put( a.ID,a.posdf )

            store.get_storer(a.ID).attrs.typ = a.typ
            store.get_storer(a.ID).attrs.name = a.name
            store.get_storer(a.ID).attrs.ID = a.ID
            store.get_storer(a.ID).attrs.layout = self.L.filename
        #saving metadata
        store.close()
        self.traj.loadh5(eval(self.sim_opt["filename"])+'_'+layfile+'.h5')



    def runsimul(self):
        """ run simulation
        """
        if not self.finish :
            seed(self.seed)
            self.simulate(until=float(self.sim_opt['duration']),
                          real_time=True,
                          rel_speed=float(self.sim_opt['speedratio']))
            self.the_world._boids={}


            if str2bool(self.save_opt['savep']):
                print 'Processing save results, please wait'
                self.save.mat_export()


            if str2bool(self.save_opt['savepd']):
                self.savepandas()
            self.finish = True
        else :
            raise NameError('Reinstantiate a new simul object to run again')
Exemple #28
0
class RX(Process):
    """
    RX process

    Each agent has a RX process to receive information asynchronously.

    Attributes
    ----------
    sim : SimPy.SimulationRT()
    ID : string
        id of the agent
    net : pylayers.network.network()
    gcom : pylayers.network.communication()
        a graph a communication
    devt : dictionary
        dictionnary of event
    refreshRSS : float
        time interval where RSS are refreshed
    refreshTOA : float
        time interval where TOA are refresh (if agent.comm_mode =='syncho')
    mp : bool
        message passing [Not yet implemented]
    """

    def __init__(self,**args):
        defaults={'sim':None,
                  'ID':'1',
                  'net':Network(),
                  'gcom': Gcom(),
                  'devt': {},
                  'refreshRSS':0.3,
                  'refreshTOA':0.3,
                  'mp':False
                  }
##       initialize attributes
        for key, value in defaults.items():
            if args.has_key(key):

                setattr(self, key, args[key])
            else:
                setattr(self, key, value)
                args[key]=value  
        self.args=args
        try:
            self.PN = self.net.node[self.ID]['PN']
        except:
            self.PN = Network()
        self.create_evt()

        Process.__init__(self,name='Rx-'+str(self.ID),sim=self.sim)

        Cf = ConfigParser.ConfigParser()
        Cf.read(pyu.getlong('agent.ini','ini'))
        for s in Cf.sections():
            try:
                d= dict(Cf.items(s))
                if d['id']==self.ID:
                    self.refreshRSS=eval(d['refreshrss'])
                    self.refreshTOA=eval(d['refreshtoa'])
                    break

            except:
                pass



    def swap_lt(self,lt):
        """
        For a list of tuple if the first element is self.ID,
        it is swapped with the second element
   
        
        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> R = RX()
        >>> R.ID
        '1'
        >>> lt= [('1','0','tuple1'),('10','5','tuple2')]
        >>> R.swap_lt(lt) # only first tuple is swapped because R.ID='1'
        [('0', '1', 'tuple1'), ('10', '5', 'tuple2')]

        """
        lto=[]
        for t in lt :
            if t[0] == self.ID:
                lto.append((t[1],t[0],t[2]))
            else :
                lto.append((t[0],t[1],t[2]))
        return lto



    def create_evt(self):
        """
        Create simpy events from communication gaph

        The available reception event for the given id are pickup into the
        communication graph to fill self.devt.

        Examples
        --------

        >>> from pylayers.network.communication import *
        >>> R = RX()
        >>> R.create_evt()

        """
        rPNe = self.swap_lt(self.PN.edges(keys=True))
        for e in rPNe:
            self.devt[e]=self.gcom.devt[e]
        if self.mp :
            for e in rPNe:
                self.devt[e]=self.gcom.devt[e+str(mp)]


    def refresh_RSS(self):
        """
            Refresh RSS process

            The RSS values on the edges of the Personnal Network of node self.ID 
            are refreshed every self.refreshRSS
        """
        self.create_evt()
        while 1:
            for rat in self.PN.SubNet.keys():

            # 2 approach to determine visibility
            ##  1) test visibility during the refresh
#                [self.PN.edge[self.ID][n][rat].update(
#                {'Pr':self.net.edge[self.ID][n][rat]['Pr'],
#                'tPr':self.sim.now(),
#                'vis':self.net.edge[self.ID][n][rat]['Pr'][0]>self.net.node[self.ID]['sens'][rat]})
#                for n in self.PN.SubNet[rat].edge[self.ID].keys()]

            #  2) copy the visibility information from network layer
                [self.PN.edge[self.ID][n][rat].update(
                {'Pr':self.net.edge[self.ID][n][rat]['Pr'],'tPr':self.sim.now(),'vis':self.net.edge[self.ID][n][rat]['vis']})
                for n in self.PN.SubNet[rat].edge[self.ID].keys() ]

            if self.sim.verbose:
                print 'refresh RSS node', self.ID, ' @',self.sim.now()

            yield hold, self, self.refreshRSS


    def refresh_TOA(self):
        """
            Refresh TOA process

            The TOA values on the edges of the Personnal Network of node self.ID
            are refreshed every self.refreshTOA
        """
        self.create_evt()

        while 1:
            for rat in self.PN.SubNet.keys():

                # 2 approaches :
                ## 1) that commented code allow refresh TOA only when visibility
#                [self.PN.edge[self.ID][n][rat].update(
#                {'TOA':self.net.edge[self.ID][n][rat]['TOA'],'tTOA':self.sim.now()})
#                for n in self.PN.SubNet[rat].edge[self.ID].keys() if self.net.edge[self.ID][n][rat]['vis']]

                # 2 refresj TOa whatever visibility or not
                [self.PN.edge[self.ID][n][rat].update(
                {'TOA':self.net.edge[self.ID][n][rat]['TOA'],'tTOA':self.sim.now()})
                for n in self.PN.SubNet[rat].edge[self.ID].keys() ]

            if self.sim.verbose:
                print 'refresh TOA node', self.ID, ' @',self.sim.now()

            yield hold, self, self.refreshTOA


    def wait_TOArq(self):
        """
            Wait TOA request

            The self.ID node wait a TOA request from another node of its Personal network.
            Once the request is received, self.ID reply to the requester node 
            and fill the PN edge with the measured TOA.
        """
        self.create_evt()
        while 1:
            yield waitevent,self,self.devt.values()
            for evt in self.devt.values():
                if evt.occurred:
                    # evt.name[0] = requester
                    # evt.name[1] = requested ( = self.ID)
                    # evt.name[2] = rat
                    # update personal network TOA value
                    self.PN.edge[evt.name[1]][evt.name[0]][evt.name[2]].update(
                    {'TOA':self.net.edge[evt.name[1]][evt.name[0]][evt.name[2]]['TOA'],'tTOA':self.sim.now()})
                    if self.sim.verbose:
                        print 'TOA requested by',evt.name[0],'to',evt.name[1],'has been updated'
                    break