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 __init__(self, L=Layout()): self.config = ConfigParser.ConfigParser() self.fileini = 'EMSolver.ini' self.config.read(pyu.getlong(self.fileini, pstruc['DIRSIMUL'])) self.ems_opt = dict(self.config.items('EMS_config')) self.toa_opt = dict(self.config.items('TOA')) self.EMS_method = self.ems_opt['method'] self.sigmaTOA = float(self.toa_opt['sigmatoa']) # meters !!!!!! self.model = {} self.L = L
def __init__(self,_fileini='coverage.ini'): self.config = ConfigParser.ConfigParser() self.config.read(pyu.getlong(_fileini,pstruc['DIRSIMUL'])) self.plm = dict(self.config.items('pl_model')) self.layoutopt = dict(self.config.items('layout')) self.gridopt = dict(self.config.items('grid')) self.txopt = dict(self.config.items('tx')) self.rxopt = dict(self.config.items('rx')) self.showopt=dict(self.config.items('show')) self.L=Layout(self.layoutopt['filename']) self.model=Model(f=eval(self.plm['f']), rssnp=eval(self.plm['rssnp']), d0=eval(self.plm['d0']), sigrss=eval(self.plm['sigrss'])) self.xstep = eval(self.gridopt['xstep']) self.ystep = eval(self.gridopt['ystep']) # transitter section self.tx = np.array((eval(self.txopt['x']),eval(self.txopt['y']))) self.ptdbm = eval(self.txopt['ptdbm']) self.framelengthbytes = eval(self.txopt['framelengthbytes']) # receiver section self.rxsens = eval(self.rxopt['sensitivity']) kBoltzmann = 1.3806503e-23 self.bandwidthmhz = eval(self.rxopt['bandwidthmhz']) self.temperaturek = eval(self.rxopt['temperaturek']) self.noisefactordb = eval(self.rxopt['noisefactordb']) Pn = (10**(self.noisefactordb/10.)+1)*kBoltzmann*self.temperaturek*self.bandwidthmhz*1e3 self.pndbm = 10*np.log10(Pn)+60 self.show = str2bool(self.showopt['show']) try: self.L.Gt.nodes() except: pass try: self.L.dumpr('t') except: self.L.buildGt() self.L.dumpw('t') self.creategrid()
def load_simul(self, source): """ load a simultraj configuration file Parameters ---------- source : string name of simulation file to be loaded """ self.filetraj = source if not os.path.isfile(source): raise AttributeError('Trajectory file' + source + 'has not been found.\ Please make sure you have run a simulnet simulation before runining simultraj.' ) # get the trajectory traj = tr.Trajectories() traj.loadh5(self.filetraj) # get the layout self.L = Layout(traj.Lfilename) # resample trajectory for ut, t in enumerate(traj): if t.typ == 'ag': person = Body(t.name + '.ini') tt = t.time() self.dpersons.update({t.name: person}) self._tmin = tt[0] self._tmax = tt[-1] self.time = tt else: pos = np.array([t.x[0], t.y[0], t.z[0]]) self.dap.update({ t.ID: { 'pos': pos, 'ant': antenna.Antenna(), 'name': t.name } }) self.ctime = np.nan self.Nag = len(self.dpersons.keys()) self.Nap = len(self.dap.keys()) self.traj = traj
def layout(self, _filestruc): """ load a layout in the simulation oject Parameters ---------- _filestruc : string short file name of the Layout object Examples -------- >>> from pylayers.simul.simulem import * >>> S = Simul() >>> S.layout('defstr.ini') """ self.filestr = _filestruc self.L = Layout(_filestruc) # update config self.config.set("files", "struc", self.filestr) self.save()
def replay(self, fig=[], ax=[], **kwargs): """ replay a trajectory Parameters ---------- fig ax speed : float speed ratio """ # plt.ion() if fig == []: fig = plt.gcf() if ax == []: ax = plt.gca() limkwargs = copy.copy(kwargs) if 'c' in kwargs: limkwargs.pop('c') if 'color' in kwargs: limkwargs.pop('c') limkwargs['marker'] = '*' limkwargs['s'] = 20 if ('m' or 'marker') not in kwargs: kwargs['marker'] = 'o' if ('c' or 'color') not in kwargs: kwargs['color'] = 'b' L = Layout(self.Lfilename) fig, ax = L.showG('s', fig=fig, ax=ax, **kwargs) time = self[0].time() line, = ax.plot([], [], 'ob', lw=2) time_template = 'time = %.1fs' time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) def init(): line.set_data([], []) time_text.set_text('') return line, time_text def animate(it): X = [] Y = [] for t in self: if t.typ == 'ag': X.append(t['x'].values[it]) Y.append(t['y'].values[it]) line.set_data(X, Y) time_text.set_text(time_template % (time[it])) return line, time_text ani = animation.FuncAnimation(fig, animate, np.arange(1, len(time)), interval=25, blit=True, init_func=init) plt.show()
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 __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)
from pylayers.gis.layout import Layout import networkx as nx import matplotlib.pyplot as plt import doctest plt.ion() #doctest.testmod(layout) #L = Layout('TA-Office.ini') L = Layout('WHERE1.ini') #L= Layout('11Dbibli.ini') #L.show() #L = Layout('PTIN.ini') #L = Layout('DLR.ini') #L.build() L.dumpr() L.showGi(en=11) #Ga = L.buildGr() #L.showGs() #nx.draw(Ga,Ga.pos)
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)
from pylayers.gis.layout import Layout import matplotlib.pyplot as plt import doctest #doctest.testmod(layout) #L = Layout('TA-Office.ini') L = Layout('DLR.ini') try: L.dumpr() except: L.build() L.dumpw() #L.editor() fig = plt.gcf() #ax1 = fig.add_subplot(221) ax1 = fig.add_subplot(321) L.display['thin'] = True fig, ax1 = L.showGs(fig=fig, ax=ax1) #L.display['edlabel']=True #L.display['edlblsize']=50 # display selected segments L.display['thin'] = True L.showG(fig=fig, ax=ax1, graph='t') fig = plt.gcf() ax1 = plt.gca() fig, ax1 = L.showGs(fig=fig, ax=ax1, edlist=[125], width=4) ax11 = fig.add_subplot(322) L.showG(fig=fig, ax=ax11, graph='') #plt.savefig('graphGs.png') #build topological graph
def load(self, _filesimul): """ load a simulation configuration file each transmiter simulation results in the creation of an .ini file with the following sections related to the results obtained for different receivers Parameters ---------- _filesimul : file in the simul directory of the Project """ self.filesimul = _filesimul filesimul = pyu.getlong(self.filesimul, "ini") self.config.read(filesimul) sections = self.config.sections() try: _filetx = self.config.get("files", "tx") except: raise NameError('Error in section tx from ' + _filesimul) try: _filerx = self.config.get("files", "rx") except: raise NameError('Error in section rx from ' + _filesimul) try: _fileini = self.config.get("files", "struc") except: raise NameError('Error in section struc from ' + _fileini) try: _fileanttx = self.config.get("files", "txant") except: raise NameError('Error in section txant from ' + _filesimul) try: _fileantrx = self.config.get("files", "rxant") except: raise NameError('Error in section rxant from ' + _filesimul) try: self.tx = RadioNode(name='', typ='tx', _fileini=_filetx, _fileant=_fileanttx) self.rx = RadioNode(name='', typ='rx', _fileini=_filerx, _fileant=_fileantrx) except: raise NameError('Error during Radionode load') # # Load Layout # try: self.L = Layout(_fileini) except: raise NameError('Layout load error') # # Frequency base # if "frequency" in sections: try: self.fGHz = np.linspace( float(self.config.getfloat("frequency", "fghzmin")), float(self.config.getfloat("frequency", "fghzmax")), int(self.config.getint("frequency", "nf")), endpoint=True) except: raise NameError('Error in section frequency from ' + _filesimul) # update .freq file in tud directory filefreq = pyu.getlong(self.filefreq, pstruc['DIRTUD']) fd = open(filefreq, "w") chaine = self.config.get("frequency", "fghzmin") + ' ' + \ self.config.get("frequency", "fghzmax") + ' ' + \ self.config.get("frequency", "nf") fd.write(chaine) fd.close # # Simulation Progress # # self.output = {} # if "output" in sections: # for itx in self.config.options("output"): # _filename = self.config.get("output", itx) # self.dout[int(itx)] = _filename # filename = pyu.getlong(_filename, "output") # output = ConfigParser.ConfigParser() # output.read(filename) # secout = output.sections() # self.dtra[int(itx)] = {} # self.dtud[int(itx)] = {} # self.dtang[int(itx)] = {} # self.drang[int(itx)] = {} # self.dtauk[int(itx)] = {} # self.dfield[int(itx)] = {} # self.dcir[int(itx)] = {} # if "launch" in secout: # self.progress = 1 # keys_launch = output.options("launch") # for kl in keys_launch: # self.dlch[int(kl)] = output.get("launch", kl) # if "trace" in secout: # self.progress = 2 # keys_tra = output.options("trace") # for kt in keys_tra: # self.dtra[int(itx)][int(kt)] = output.get("trace", kt) # # if "tang" in secout: # self.progress = 3 # keys_tang = output.options("tang") # for kt in keys_tang: # self.dtang[int(itx)][int(kt)] = output.get("tang", kt) # self.drang[int(itx)][int(kt)] = output.get("rang", kt) # self.dtud[int(itx)][int(kt)] = output.get("tud", kt) # if "field" in secout: # self.progress = 4 # keys_field = output.options("field") # for kt in keys_field: # self.dfield[int(itx)][int(kt)] = output.get( # "field", kt) # self.dtauk[int(itx)][int(kt)] = output.get("tauk", kt) # if "cir" in secout: # self.progress = 5 # keys_cir = output.options("cir") # for kt in keys_cir: # self.dcir[int(itx)][int(kt)] = output.get("cir", kt) # # self.output[int(itx)] = output # # Waveform section # self.wav = wvf.Waveform() self.wav.read(self.config)
def __init__(self, _fileini='coverage.ini'): """ object constructor Parameters ---------- _fileini : string name of the configuration file Notes ----- Coverage is described in an ini file. Default file is coverage.ini and is placed in the ini directory of the current project. """ self.config = ConfigParser.ConfigParser(allow_no_value=True) self.config.read(pyu.getlong(_fileini, pstruc['DIRSIMUL'])) # section layout self.layoutopt = dict(self.config.items('layout')) # section sector self.gridopt = dict(self.config.items('grid')) # section ap (access point) self.apopt = dict(self.config.items('ap')) # section receiver parameters self.rxopt = dict(self.config.items('rx')) # section receiver parameters self.showopt = dict(self.config.items('show')) # get the Layout filename = self.layoutopt['filename'] if filename.endswith('lay'): self.typ = 'indoor' self.L = Layout(filename) # get the receiving grid self.nx = eval(self.gridopt['nx']) self.ny = eval(self.gridopt['ny']) if 'zgrid' in self.gridopt: self.zgrid = eval(self.gridopt['zgrid']) else: self.zgrid = 1.0 self.mode = self.gridopt['mode'] assert self.mode in ['file', 'full', 'zone'], "Error reading grid mode " self.boundary = eval(self.gridopt['boundary']) self.filespa = self.gridopt['file'] # # create grid # self.creategrid(mode=self.mode, boundary=self.boundary, _fileini=self.filespa) self.dap = {} for k in self.apopt: kwargs = eval(self.apopt[k]) ap = std.AP(**kwargs) self.dap[eval(k)] = ap try: self.L.Gt.nodes() except: pass try: self.L.dumpr() except: self.L.build() self.L.dumpw() else: self.typ = 'outdoor' self.E = ez.Ezone(filename) self.E.loadh5() self.E.rebase() # The frequency is fixed from the AP nature self.fGHz = np.array([]) #self.fGHz = eval(self.txopt['fghz']) #self.tx = np.array((eval(self.txopt['x']),eval(self.txopt['y']))) #self.ptdbm = eval(self.txopt['ptdbm']) #self.framelengthbytes = eval(self.txopt['framelengthbytes']) # receiver section #self.rxsens = eval(self.rxopt['sensitivity']) self.temperaturek = eval(self.rxopt['temperaturek']) self.noisefactordb = eval(self.rxopt['noisefactordb']) # show section self.bshow = str2bool(self.showopt['show']) self.sinr = False self.snr = False self.best = False self.egd = False self.Pr = False self.capacity = False self.pr = False self.loss = False
def Lname(self,Lname): # change layout and build/load self._L = Layout(Lname) self._Lname = Lname self.reset_config()
def __init__(self, **kwargs): """ deterministic link evaluation Parameters ---------- L : Layout Layout to be used a : np.ndarray (3,) position of a device dev_a b : np.ndarray (3,) position of a device dev_b Aa : Antenna Antenna of device dev_a Ab : Antenna Antenna of device dev_b Ta : np.ndarray (3,3) Rotation matrice of Antenna of device dev_a relative to global Layout scene Tb : np.ndarray (3,3) Rotation matrice of Antenna of device dev_b relative to global Layout scene fGHz : np.ndarray (Nf,) frequency range of Nf points used for evaluation of channel wav : Waveform Waveform to be applied on the channel save_idx : int number to identify the h5 file generated Advanced (change only if you really know what you do !) save_opt : list (['sig','ray','Ct','H']) information to be saved in the Links h5 file. Should never be Modified ! force_create : Boolean (False) forcecreating the h5py file (if already exist, will be erased) Notes ----- All simulations are stored into a unique file in your <PyProject>/output directory using the following convention: Links_<save_idx>_<LayoutFilename>.h5 where <save_idx> is an integer number to distinguish different links simulations and <LayoutFilename> is the Layout used for the link simulation. Dataset organisation: Links_<idx>_<Layout_name>.h5 | |/sig/si_ID#0/ | /si_ID#1/ | ... | |/ray/ray_ID#0/ | /ray_ID#1/ | ... | |/Ct/Ct_ID#0/ | /Ct_ID#1/ | ... | |/H/H_ID#0/ | /H_ID#1/ | ... | | |p_map |c_map |f_map |A_map |T_map Roots Dataset : c_map : Cycles (Nc x 3) p_map : Positions (Np x 3) f_map : Frequency (Nf x 3) T_map : Rotation matrices (Nt x 3) A_map : Antenna name (Na x 3) Groups and subgroups: Signature identifier (si_ID#N): ca_cb_cutoff Ray identifier (ray_ID#N): cutoff_ua_ub Ctilde identifier (Ct_ID#N): ua_ub_uf H identifier (H_ID#N): ua_ub_uf_uTa_uTb_uAa_uAb with ca : cycle number of a cb : cycle number of b cutoff : signature.run cutoff ua : indice of a position in 'p_map' position dataset ub : indice of a position in 'p_map' position dataset uf : indice of freq position in 'f_map' frequency dataset uTa : indice of a position in 'T_map' Rotation dataset uTb : indice of a position in 'T_map' Rotation dataset uAa : indice of a position in 'A_map' Antenna name dataset uAb : indice of b position in 'A_map' Antenna name dataset Examples -------- >>> from pylayers.simul.link import * >>> L = DLink(verbose=False) >>> aktk = L.eval() """ Link.__init__(self) defaults={ 'L':Layout(), 'a':np.array(()), 'b':np.array(()), 'Aa':Antenna(typ='Omni'), 'Ab':Antenna(typ='Omni'), 'Ta':np.eye(3), 'Tb':np.eye(3), 'fGHz':[], 'wav':wvf.Waveform(), 'cutoff':3, 'save_opt':['sig','ray','Ct','H'], 'save_idx':0, 'force_create':False, 'verbose':True, 'graph':'tcvirw' } self._ca=-1 self._cb=-1 specset = ['a','b','Aa','Ab','Ta','Tb','L','fGHz','wav'] # set default attribute for key, value in defaults.items(): if key not in kwargs: if key in specset : setattr(self,'_'+key,value) else : setattr(self,key,value) else : if key in specset : setattr(self,'_'+key,kwargs[key]) else : setattr(self,key,kwargs[key]) force=self.force_create delattr(self,'force_create') if self.fGHz == []: self.initfreq() else : pass try: self._Lname = self._L.filename except: self._L=Layout(self._L) self._Lname = self._L.filename ########### # Transmitter and Receiver positions ########### self.tx = RadioNode(name = '', typ = 'tx', _fileini = 'radiotx.ini', ) self.rx = RadioNode(name = '', typ = 'rx', _fileini = 'radiorx.ini', ) self.filename = 'Links_' + str(self.save_idx) + '_' + self._Lname + '.h5' filenameh5 = pyu.getlong(self.filename,pstruc['DIRLNK']) # check if save file alreasdy exists if not os.path.exists(filenameh5) or force: print 'Links save file for ' + self.L.filename + ' does not exist.' print 'Creating file. You\'ll see this message only once per Layout' self.save_init(filenameh5) # dictionnary data exists self.dexist={'sig':{'exist':False,'grpname':''}, 'ray':{'exist':False,'grpname':''}, 'Ct':{'exist':False,'grpname':''}, 'H':{'exist':False,'grpname':''} } try: self.L.dumpr() except: print('This is the first time the Layout is used. Graphs have to be built. Please Wait') self.L.build(graph=self.graph) self.L.dumpw() #self.L.build() ########### # init pos & cycles # # If a and b are not specified # they are chosen as center of gravity of cycle 0 # ########### if len(self.a)==0: self.ca = 1 # self.a = self.L.cy2pt(self.ca) else: if len(kwargs['a']) ==2: a=np.r_[kwargs['a'],1.0] else: a=kwargs['a'] self.a = a # self.ca = self.L.pt2cy(self.a) if len(self.b)==0: if len(self.L.Gt.node)>2: self.cb = 2 else: self.cb = 1 # self.b = self.L.cy2pt(self.cb) else: if len(kwargs['b']) ==2: b=np.r_[kwargs['b'],1.0] else: b=kwargs['b'] self.b = b # self.cb = self.L.pt2cy(self.b) ########### # init freq # TODO Check where it is used redundant with fGHz ########### #self.fmin = self.fGHz[0] #self.fmax = self.fGHz[-1] #self.fstep = self.fGHz[1]-self.fGHz[0] self.Si = Signatures(self.L,self.ca,self.cb,cutoff=self.cutoff) self.R = Rays(self.a,self.b) self.C = Ctilde() self.H = Tchannel()
from pylayers.gis.layout import Layout import networkx as nx import matplotlib.pyplot as plt #doctest.testmod(layout) #L = Layout('TA-Office.ini') L = Layout() lL = L.ls() for tL in lL: print 'Layout :', tL try: L = Layout(tL) L.save() except: print 'Layout :', tL, ' problem' #f = plt.figure(figsize=(20,10)) #plt.axis('off') #f,a = L.showG('s',nodes=False,fig=f) #plt.show() #f,a = L.showG('r',edge_color='b',linewidth=4,fig=f) #L= Layout('11Dbibli.ini') #L.show() #L = Layout('PTIN.ini') #L = Layout('DLR.ini') #L.buildGt() #Ga = L.buildGr() #L.showGs() #nx.draw(Ga,Ga.pos)
def ishow(self): """ interactive show of trajectories Examples -------- .. plot:: :include-source: >>> from pylayers.mobility.trajectory import * >>> T=Trajectories() >>> T.loadh5() >>> T.ishow() """ fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2, left=0.3) t = np.arange(0, len(self[0].index), self[0].ts) L = Layout(self.Lfilename) fig, ax = L.showG('s', fig=fig, ax=ax) valinit = 0 lines = [] labels = [] colors = "bgrcmykw" for iT, T in enumerate(self): if T.typ == 'ag': lines.extend( ax.plot(T['x'][0:valinit], T['y'][0:valinit], 'o', color=colors[iT], visible=True)) labels.append(T.name + ':' + T.ID) else: lines.extend( ax.plot(T['x'][0], T['y'][0], '^', ms=12, color=colors[iT], visible=True)) labels.append(T.name + ':' + T.ID) t = self[0].time() # init boolean value for visible in checkbutton blabels = [True] * len(labels) ######## # slider ######## slider_ax = plt.axes([0.1, 0.1, 0.8, 0.02]) slider = Slider(slider_ax, "time", self[0].tmin, self[0].tmax, valinit=valinit, color='#AAAAAA') def update(val): if val >= 1: pval = np.where(val > t)[0] ax.set_title(str( self[0].index[pval[-1]].time())[:11].ljust(12), loc='left') for iT, T in enumerate(self): if T.typ == 'ag': lines[iT].set_xdata(T['x'][pval]) lines[iT].set_ydata(T['y'][pval]) fig.canvas.draw() slider.on_changed(update) ######## # choose ######## rax = plt.axes([0.02, 0.5, 0.3, 0.2], aspect='equal') # check (ax.object, name of the object , bool value for the obsject) check = CheckButtons(rax, labels, tuple(blabels)) def func(label): i = labels.index(label) lines[i].set_visible(not lines[i].get_visible()) fig.canvas.draw() check.on_clicked(func) fig.canvas.draw() plt.show(fig)
def __init__(self,_fileini='coverage.ini'): """ object constructor Parameters ---------- _fileini : string name of the configuration file Notes ----- Coverage is described in an ini file. Default file is coverage.ini and is placed in the ini directory of the current project. """ self.config = ConfigParser.ConfigParser() self.config.read(pyu.getlong(_fileini,pstruc['DIRSIMUL'])) self.layoutopt = dict(self.config.items('layout')) self.gridopt = dict(self.config.items('grid')) self.apopt = dict(self.config.items('ap')) self.rxopt = dict(self.config.items('rx')) self.showopt = dict(self.config.items('show')) # get the Layout self.L = Layout(self.layoutopt['filename']) # get the receiving grid self.nx = eval(self.gridopt['nx']) self.ny = eval(self.gridopt['ny']) self.mode = self.gridopt['mode'] self.boundary = eval(self.gridopt['boundary']) self.filespa = self.gridopt['file'] # # create grid # self.creategrid(mode=self.mode,boundary=self.boundary,_fileini=self.filespa) self.dap = {} for k in self.apopt: kwargs = eval(self.apopt[k]) ap = std.AP(**kwargs) self.dap[eval(k)] = ap self.fGHz = np.array([]) #self.fGHz = eval(self.txopt['fghz']) #self.tx = np.array((eval(self.txopt['x']),eval(self.txopt['y']))) #self.ptdbm = eval(self.txopt['ptdbm']) #self.framelengthbytes = eval(self.txopt['framelengthbytes']) # receiver section #self.rxsens = eval(self.rxopt['sensitivity']) self.temperaturek = eval(self.rxopt['temperaturek']) self.noisefactordb = eval(self.rxopt['noisefactordb']) # show section self.bshow = str2bool(self.showopt['show']) try: self.L.Gt.nodes() except: pass try: self.L.dumpr() except: self.L.build() self.L.dumpw()
from pylayers.gis.layout import Layout import matplotlib.pyplot as plt import doctest #doctest.testmod(layout) L = Layout('TA-Office.ini') #L = Layout('DLR.ini') #L = Layout('TA-Office.ini') #L = Layout('WHERE1.ini') try: L.dumpr() except: L.build() L.dumpw() #L.editor() fig = plt.gcf() #ax1 = fig.add_subplot(221) ax1 = fig.add_subplot(321) L.display['thin'] = True fig, ax1 = L.showG(graph='s', fig=fig, ax=ax1) #L.display['edlabel']=True #L.display['edlblsize']=50 # display selected segments L.display['thin'] = True L.showG(fig=fig, ax=ax1, graph='t') fig = plt.gcf() ax1 = plt.gca() fig, ax1 = L.showGs(fig=fig, ax=ax1, edlist=[125], width=4) ax11 = fig.add_subplot(322) L.showG(fig=fig, ax=ax11, graph='s')
r""" =========================================== 8 Random Layout =========================================== This example display randomly N layout from the set of all available Layout file The file extension is .lay """ from pylayers.gis.layout import Layout import matplotlib.pyplot as plt import random import warnings warnings.filterwarnings("error") L = Layout() lL = L.ls() N = 8 for tL in random.sample(lL,N): if 'Munich' not in tL: L = Layout(tL,bbuild=0,bgraphs=0) f,a = L.showG('s') plt.title(tL,fontsize=32) plt.show()
from pylayers.gis.layout import Layout import networkx as nx import matplotlib.pyplot as plt #doctest.testmod(layout) #L = Layout('TA-Office.ini') L = Layout() lL = L.ls() for tL in lL: print tL #f = plt.figure(figsize=(20,10)) #plt.axis('off') #f,a = L.showG('s',nodes=False,fig=f) #plt.show() #f,a = L.showG('r',edge_color='b',linewidth=4,fig=f) #L= Layout('11Dbibli.ini') #L.show() #L = Layout('PTIN.ini') #L = Layout('DLR.ini') #L.buildGt() #Ga = L.buildGr() #L.showGs() #nx.draw(Ga,Ga.pos)