Source code for pylayers.exploit.simnet

from pylayers.util import project
import pylayers.util.CDF as cdf
import pylayers.signal.bsignal as bs
import pylayers.gis.layout as ly
import pylayers.util.pyutil as pyu
import sys
if sys.version_info.major==2:
    import ConfigParser
else:
    import configparser as ConfgParser

import matplotlib.pylab as plt
import itertools
import pickle
import pdb


[docs]class Simnet2cir(object): """ Simnet2cir This class allows to perform a raytracing simulation from a simulnet simulation. First of using it, you MUST have run a simulnet simulation. Notes ----- 1) From your Project directory, configure simulnet.ini save section with: Save =['pyray'] 2) Run simulnet from pylayers.simul.simulnet import * S = Simul() S.runsimul() 3) At the end of the simulnet simulation, a 'netsave' folder has been created into your Pylayers project directory. This folder contains all required files for Simnet2cir computation 4) Launch the Raytracing simulation from the pre-computed simulnet simulation: from pylayers.exploit.simnet import * E = Simnet2cir() E.compute() # 5) See CIR results using pltciri or pltcir: >>> E.pltcir(1,2,1) >>> E.pltciri(1,2) """ def __init__(self,simnetfile='pyray.ini'): self.simnetfile=simnetfile self.load()
[docs] def load(self): """ Load simulnet_data configuration file """ if not os.path.isfile(pyu.getlong(self.simnetfile,pstruc['DIRNETSAVE'])): raise NameError(self.simnetfile +' cannot be reached.\ Have you launch a simulnet simulation before ? \ Please use \'>>> Simnet2cir?\' to see help ') self.simcfg = ConfigParser.ConfigParser() self.simcfg.read(pyu.getlong(self.simnetfile,pstruc['DIRNETSAVE'])) self.Lfilename = self.simcfg.get('layout','layoutname') self.lAG = eval(self.simcfg.get('nodes','ag')) self.lAP = eval(self.simcfg.get('nodes','ap')) self.uptime = eval(self.simcfg.get('simulation','updatetime')) # create a Simul object with the correct layout self.S = sime.Simul() self.S.layout(self.Lfilename,'matDB.ini','slabDB.ini') self.lap = len(self.lAP) self.lag = len(self.lAG) self.L = self.S.L try: self.L.dumpr() print('Layout graphs are loaded from ',basename,'/struc') except: #self.L.sl = sl #self.L.loadGr(G1) print('First time your use the Layout.Graphs are curently build, it may take few minutes.') self.L.buildGt() self.L.dumpw()
[docs] def compute(self): """ Compute Raytracing simulation with the given simulation files """ # ### STEP 1 : all mobile node with all agent # self.S.clean_project(verbose=True) for apidx,ap in enumerate(self.lAP): self.S.tx = RadioNode(typ='tx',name=ap) self.S.tx.loadini(ap+'.ini',rep=pstruc['DIRNETSAVE']) for agidx,ag in enumerate(self.lAG): print('---------------------') print(' Raytracing for : ') print(' AP #',self.lAP[apidx-1] ,' / AG #',ag) print('---------------------') print(' Computed :') print('AP:',apidx-1,'/',self.lap+1) print('AG:',agidx,'/',self.lag) print('---------------------') self.S.rx = RadioNode(typ='rx',name=ag) self.S.rx.loadini(ag+'.ini',rep=pstruc['DIRNETSAVE']) self.S.run(apidx+1,range(1,self.S.rx.N+1)) #### STEP 2 : all mobile/mobile icag = itertools.combinations(self.lAG,2) for cag in icag: self.S.tx = RadioNode(typ='tx',name=cag[0]) self.S.tx.loadini(cag[0]+'.ini',rep=pstruc['DIRNETSAVE']) self.S.rx = RadioNode(typ='tx',name=cag[1]) self.S.rx.loadini(cag[1]+'.ini',rep=pstruc['DIRNETSAVE']) lidxpts = range(1,self.S.rx.N+1) print('---------------------') print(' Raytracing for : ') print(' AG #', cag[0] ,' / AG #',cag[1]) print('---------------------') for n in lidxpts: print(' trajectory point #',n,'/',self.S.rx.N+1) print('---------------------') self.S.run(n,n)
[docs] def pltcir(self,itx,irx,pn,fig=[]): """ Plot channel impulse response for Tx,Rx and a specified position Parameters ---------- itx : int node number irx : int node number pn : int position index of the Rx """ if fig == []: fig = plt.figure(2) fig.clf() cir = TUsignal() spn = str(pn) line = 'defaultcir-' +str(itx) +'-'+str(irx)+'-p'+spn.zfill(3) try: cir.readcir(line,str(itx)) except: return False print('load : ',line,'.mat') cir.show(fig) return True
[docs] def pltciri(self,itx,irx): """ Plot channel impulse response interactiveley. diplay all node position of Tx and Rx and chose for which link you display the CIR. Once you have call self.pltciri(node1,node2) 1) Press 't' on the displayed graph to chose the Tx 2) Press 'x' on the displayed graph to chose the Rx 3) Press Enter to display CIR betwen Tx-Rx Parameters ---------- itx : int node number irx : int node number usage >>> W = W2() >>> W.pltciri(6,1) """ plt.ion() fig1 = plt.figure(1) ax=fig1.add_subplot(111) self.ax2 = fig1.add_subplot(111) self.L.showG(fig=fig1,graph='') self.S.tx = RadioNode(typ='tx',name=itx) self.S.tx.loadini(str(itx)+'.ini',rep=pstruc['DIRNETSAVE']) self.S.rx = RadioNode(typ='rx',name=irx) self.S.rx.loadini(str(irx)+'.ini',rep=pstruc['DIRNETSAVE']) ax.plot(self.S.tx.position[0,:],self.S.tx.position[1,:],'ob') ax.plot(self.S.rx.position[0,:],self.S.rx.position[1,:],'or') plt.show() print('1. Press \'t\' and click to select a Tx ') print('2. Press \'x\' and click to select a Rx ' ) print('3. Press Enter to see the associated CIR ') self.key='' self.x1='' self.x2='' self.y1='' self.y2='' self.n1='' self.n2='' self.pos1='' self.pos2='' self.c1=[] self.c2=[] cid=fig1.canvas.mpl_connect('button_press_event', self.onclick) cid=fig1.canvas.mpl_connect('key_press_event', self.on_key)
[docs] def onclick(self,event): """ Events on click """ if event.button == 1: print (self.key) if self.key =='t': self.x1 = event.xdata self.y1 = event.ydata self.n1,self.pos1=self.srchpoint(self.x1,self.y1) print ('select node1(Tx) # ',self.n1,) if self.key =='x': self.x2 = event.xdata self.y2 = event.ydata self.n2,self.pos2=self.srchpoint(self.x2,self.y2) print ('select node2(Rx) # ',self.n2, ', at position #', self.pos2+1) if self.key == 'enter': pass
[docs] def on_key(self,event): """ Events on key stroke """ if event.key == 't': self.key = 't' if event.key == 'x': self.key = 'x' if event.key == 'enter': inv=False case = '' if self.pos1 !='' and self.pos2 !='': if self.n1 == self.n2: print ('ERROR :tx and rx on the same node') else : if str(self.n1) in self.lAG and str(self.n2) in self.lAG: upos = self.pos2[0]+1 case = '2agents' elif str(self.n2) in self.lAP: upos = self.pos1[0]+1 else : upos = self.pos2[0]+1 if self.pltcir(self.n1,self.n2,upos): pass else: self.pltcir(self.n2,self.n1,upos) inv=True print (inv) ### manage black cross for involved nodes try: self.c1.pop(0).remove() self.c2.pop(0).remove() except: pass if case == '2agents': ### manage 2 mobile nodes self.c1=self.ax2.plot(self.S.tx.position[0,upos-1],self.S.tx.position[1,upos-1],'xk',ms=10.,mew=3.) self.c2=self.ax2.plot(self.S.rx.position[0,upos-1],self.S.rx.position[1,upos-1],'xk',ms=10.,mew=3.) else: if self.S.tx.N == 1: self.c1=self.ax2.plot(self.S.tx.position[0,0],self.S.tx.position[1,0],'xk',ms=10.,mew=3.) self.c2=self.ax2.plot(self.S.rx.position[0,upos-1],self.S.rx.position[1,upos-1],'xk',ms=10.,mew=3.) else : self.c1=self.ax2.plot(self.S.tx.position[0,upos-1],self.S.tx.position[1,upos-1],'xk',ms=10.,mew=3.) self.c2=self.ax2.plot(self.S.rx.position[0,0],self.S.rx.position[1,0],'xk',ms=10.,mew=3.)
# ### manage 2 mobile nodes to take position of the 2nd click # if str(self.S.tx.name) in self.lAG and str(self.S.rx.name) in self.lAG : # self.pos1 = self.pos2 #
[docs] def srchpoint(self,x,y): """ Search from the closest point (x,y) into self.tx.position and self.rx.position Parameters ---------- x : y : Returns ------- N : int node ID pos : int index of the closest position """ t = self.S.tx.position[:2,:] r = self.S.rx.position[:2,:] p = np.array((x,y)) d1 = np.sqrt(np.sum((t.T-p)**2,axis=1)) d2 = np.sqrt(np.sum((r.T-p)**2,axis=1)) d1m=np.min(d1) d2m=np.min(d2) if d1m < d2m: n = self.S.tx.name pos = np.nonzero(d1==d1m)[0] else : n = self.S.rx.name pos = np.nonzero(d2==d2m)[0] return (n,pos)
#cid = fig.canvas.mpl_connect('button_press_event', onclick)
[docs]class Simnet2loc(object): """ Simnet2loc Summary ------- this class allows to plot cdf from localization obtained with simulet simulation Configure simulnet.ini save section with: Save =['loc'] """ def __init__(self,savefile='save.pck'): self.savefile=savefile self.load()
[docs] def load(self): """ Load simulnet_data configuration file """ self.savefile self.file=open(basename+'/' + pstruc['DIRNETSAVE'] +'/' +self.savefile,'r') self.savemat=pickle.load(self.file)
[docs] def CDF(self,node=['1'],method=['pe','pe_alg'],filename='CDF'): """ plot CDF from a saved simulation for a given node and for chosen algorithm """ methodname ={} for m in method: if m == 'pe': methodname[m]='Geometric' elif m == 'pe_alg': methodname[m]='Algebraic' self.error={} for n in node: L=[] leg=[] for m in method: try: L.append(np.sqrt(np.sum(self.savemat[n][m]-self.savemat[n]['p'],axis=1)**2) ) leg.append(methodname[m]) except: print ("given method is not save") self.error[n]=L lL=len(L) color=['k']*lL #MF=[500.,500.,500.,500.,500.,500.,500.,500.,500.,500.,500.,500.] MF=[100.,150.,400.,400.,400.,400.,400.,400.,400.] #color=['r','r','r','g','g','g','b','b','b'] #### CDF RSSHT atteint ML Msize=[5,3,4,4,6,3,6,3,3,3,3] MS=['','','','o','^','*','v',' ','^','o',' ','^','o'] MC=['w','w','w','w','w','w','w','w','w','w','w','w','w'] LS=['-','--',':','-','-','-','-','-','-','--','--','--','-.','-.','-.',':',':',':'] #color=['k']*lL color=['k','r','b','b','g','g','k','k','r','g','b','k','r','g','b','k'] it=0 lv=[] for i in range(lL): dx1 = {} dx1['values'] = L[i] dx1['filename'] = 'CDF' dx1['bound'] = np.arange(0,10.,0.01) dx1['legend'] = leg[i] dx1['xlabel'] = 'Positioning error [m]'#r"$ \| B - \hat{B} \| \quad [m]$" dx1['ylabel'] = 'Cumulative Probability'#r"$ Pr ( \| B - \hat{B} \| < \epsilon)$" dx1['title'] = 'CDF' dx1['marker'] = MS[it] try: dx1['markercolor'] = MC[it] except: pass dx1['markersize'] = Msize[i] dx1['markerfrequency'] = MF[it] dx1['line'] = LS[it] dx1['color'] = color[it] dx1['linewidth'] = 1. # if nb_rss[i/4]==3 : lv.append(dx1) it=it+1 # lv.append(dx1) cdf = cdf.CDF(lv,filename=basename + '/' +pstruc['DIRNETSAVE'] +'/'+filename) cdf.show()
[docs] def trajectory(self,node='1', L=ly.Layout('WHERE1.lay')): """ plot a trajectory of a node on a given structure , from a save simulation file Parameters ---------- node : string L : pylayers.gis.layout.Layout """ L.dumpr() pa=[] for p in self.savemat.keys(): try: if self.savemat[p]['type']=='ap': pa.append(self.savemat[p]['p'][0]) except: pass pa=np.array(pa) f=plt.figure() ax=f.add_subplot(111) f,ax=L.showG('',fig=f,ax=ax) P=self.savemat[node]['p'] label=np.arange(len(P)) ax.scatter(pa[:,0],pa[:,1],color='r',s=4) ax.scatter(P[:,0],P[:,1],color='g',s=3) plt.show()
# self.simcfg = ConfigParser.ConfigParser() # self.simcfg.read(pyu.getlong(self.simnetfile,pstruc['DIRNETSAVE'])) # self.Lfilename = self.simcfg.get('layout','layoutname') # self.lAG = eval(self.simcfg.get('nodes','ag')) # self.lAP = eval(self.simcfg.get('nodes','ap')) # self.uptime = eval(self.simcfg.get('simulation','updatetime')) # # create a Simul object with the correct layout # self.S = Simul() # self.S.layout(self.Lfilename,'matDB.ini','slabDB.ini') # self.lap = len(self.lAP) # self.lag = len(self.lAG) # self.L = self.S.L # try: # self.L.dumpr() # print 'Layout graphs are loaded from ',basename,'/struc' # except: # #self.L.sl = sl # #self.L.loadGr(G1) # print 'First time your use the Layout.Graphs are curently build, it may take few minutes.' # self.L.buildGt() # self.L.dumpw()