def pyray_save(self,S): """ save node positions into ini file, compliant with pyray standard Parameters ---------- filename : string name of the pyray file S : Simulation Scipy.Simulation object """ assert len(self.SubNet.keys()) == 1 , NameError('when network.ini_save() \ is used , only 1 rat must be involved in the Network.\ Please modify agent.ini') height= 1.5 pos=nx.get_node_attributes(self,'p').items() ### create ini files if self.idx == 0: self.init_save(height=height) ### save agent positions for i in range(len(pos)): if self.node[pos[i][0]]['type'] !='ap': config = ConfigParser.ConfigParser() config.read(pyu.getlong(str(pos[i][0]) + '.ini',pstruc['DIRNETSAVE'])) config.set('coordinates',str(self.idx+1),value = str(pos[i][1][0]) + ' ' + str(pos[i][1][1]) + ' '+str(height)) file=open(pyu.getlong(str(pos[i][0]) + '.ini',pstruc['DIRNETSAVE']),'w') config.write(file) file.close()
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 = 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()
def pyray_save(self,S): """ save node positions into ini file, compliant with pyray standard Attributes: ---------- filename : string name of the pyray file S : Simulation Scipy.Simulation object """ assert len(self.SubNet.keys()) == 1 , NameError('when network.ini_save() \ is used , only 1 rat must be involved in the Network.\ Please modify agent.ini') height= 1.5 pos=nx.get_node_attributes(self,'p').items() ### create ini files if self.idx == 0: self.init_save(height=height) ### save agent positions for i in range(len(pos)): if self.node[pos[i][0]]['type'] !='ap': config = ConfigParser.ConfigParser() config.read(pyu.getlong(str(pos[i][0]) + '.ini',pstruc['DIRNETSAVE'])) config.set('coordinates',str(self.idx+1),value = str(pos[i][1][0]) + ' ' + str(pos[i][1][1]) + ' '+str(height)) file=open(pyu.getlong(str(pos[i][0]) + '.ini',pstruc['DIRNETSAVE']),'w') config.write(file) file.close()
def load_dec_file(self): self.config = ConfigParser.ConfigParser() self.config.read(pyu.getlong(self.fileini, pstruc['DIRSIMUL'])) nodes = self.config.sections() ntype = nx.get_node_attributes(self.net, 'typ') for n in self: try: if ntype[n] == 'ag': self.dec[n] = {} di = self.config.items(n) self.dec[n]['wstd'] = eval( dict(self.config.items(n))['wstd']) self.dec[n]['action'] = eval( dict(self.config.items(n))['action']) self.dec[n]['rule'] = eval( dict(self.config.items(n))['rule']) except: nconfig = ConfigParser.ConfigParser() nconfig.add_section(n) nconfig.set(n, 'wstd', [self.net.node[n]['wstd'][0]]) nconfig.set(n, 'rule', ['always']) nconfig.set(n, 'action', ['range']) fileini = pyu.getlong(self.fileini, pstruc['DIRSIMUL']) fd = open(fileini, "a") nconfig.write(fd) fd.close() print('Warning: Communication of node ' + n + 'set with default values')
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 = 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()
def ini_save(self,S,filename='simulnet_data.ini',height=1.5): """ ---------- DEPRECATED ---------- Save an .ini file of node position . Only links which involve mobile nodes (type 'ag') are kept. The produced init file is filled as follow: [timestamp] nodeID1_nodeID2 = x1,y1,z1,x2,y2,z2 nodeID2_nodeID4 = x2,y2,z2,x4,y4,z4 .... Attributes: ---------- S : Simulation Scipy.Simulation object filename : string name of the saved ini file height : float height of the nodes """ assert len(self.SubNet.keys()) == 1 , NameError('when network.ini_save() \ is used , only 1 rat must be involved in the Network.\ Please modify agent.ini') if self.idx == 0: file=open(pyu.getlong(filename ,'output'),'w') else: file=open(pyu.getlong(filename ,'output'),'a') config = ConfigParser.ConfigParser() timestamp = pyu.timestamp(S.now()) config.add_section(timestamp) for e in self.edges(): if not ((self.node[e[0][0]]['type'] == 'ap') and (self.node[e[1][0]]['type'] == 'ap')): key=str(e[0]) +'_' +str(e[1]) value1 = str(self.node[e[0][0]]['p'][0])+ ',' +str(self.node[e[0][0]]['p'][1])+','+str(height) value2 = str(self.node[e[1][0]]['p'][0])+ ',' +str(self.node[e[1][0]]['p'][1])+','+str(height) config.set(timestamp, key, value1 + ' , ' + value2) config.write(file) file.close() self.idx=self.idx+1
def geomfile(self,iframe=0,verbose=False,topos=False,tag=''): """ create a geomview file from a body configuration Parameters ---------- iframe : int verbose : boolean topos : boolean tag : string """ cyl = geu.Geomoff('cylinder') pt = cyl.loadpt() if not topos: _filebody = str(iframe).zfill(4)+'body.list' else: _filebody = tag+'-body.list' filebody = pyu.getlong(_filebody,"geom") filestruc = pyu.getlong('DLR.off',"geom") fo = open(filebody,"w") fo.write("LIST\n") fo.write('{<'+filestruc+'}\n') if verbose: print ("LIST\n") for k,e in enumerate(self.g.edges()): e0 = e[0] e1 = e[1] if not topos: pA = self.d[:,e0,iframe].reshape(3,1) pB = self.d[:,e1,iframe].reshape(3,1) else: pA = self.topos[:,e0].reshape(3,1) pB = self.topos[:,e1].reshape(3,1) pM = (pA+pB)/2. T = geu.onbfromaxe(pA,pB) R = self.g[e0][e1]['radius'] Y = np.hstack((pM,pA,pB,pM+R*T[0,:,0].reshape(3,1),pM+R*T[0,:,1].reshape(3,1),pB+R*T[0,:,0].reshape(3,1))) A,B = geu.cylmap(Y) ptn = np.dot(A,pt.T)+B if not topos: _filename = 'edge'+str(k)+'-'+str(iframe)+'.off' else: _filename = tag+'-edge'+str(k)+'.off' filename = pyu.getlong(_filename,"geom") cyl.savept(ptn.T,_filename) fo.write('{<'+filename+'}\n') if verbose: print('{<'+filename+'}\n') fo.close()
def extract(self, i): """ extract the i-th radionode component Parameters ---------- i : integer Returns ------- u : RadioNode """ if self.typ == 'undefined': u = RadioNode(self.filestr) elif self.typ == 'tx': u = RadioTx(self.filestr, self.signal) elif self.typ == 'rx': u = RadioRx(self.filestr, self.fc, self.bandwidth, self.NF) u.position = self.position[:, i] # # # u.time = self.time[i] # u.orientation = self.orientation[:,:,i] u.filespa = "filespa.spa" # # Write the RadioNode Coordinate in filespa # if self.typ != 'undefined': if self.typ == 'tx': filespa = pyu.getlong("filespa.spa", pstruc['DIRLCH']) elif self.typ == 'rx': filespa = pyu.getlong("filespa.spa", pstruc['DIRTRA']) fi = open(filespa, 'w') fi.write("0\n") fi.write("1\n") x = str(self.position[0, i]) y = str(self.position[1, i]) z = str(self.position[2, i]) chaine = x + " " + y + " " + z + "\n" fi.write(chaine) fi.close() return u
def put(self, typ): """ recover last deleted coeff Parameters ---------- typ : int 2 : shape 2 (Nf , N*M ) 3 : shape 3 (Nf , K ) T ( K x 2 ) """ if typ == 2: file_ind = pyu.getlong("outfile_i2.txt", pstruc["DIRANT"]) aux = load(file_ind) ind = aux[0] ind2 = np.array([aux[1], aux[2]]) file_s2 = pyu.getlong("outfile_s2.txt", pstruc["DIRANT"]) s2 = load(file_s2) self.s2p = s2 a = insert(self.ind2, ind, ind2, axis=0) b = insert(self.s2, ind, s2, axis=1) self.ind2 = a self.s2 = b if typ == 3: file_ind = pyu.getlong("outfile_i3.txt", pstruc["DIRANT"]) aux = load(file_ind) ind = aux[0] ind3 = np.array([aux[1], aux[2]]) k2 = aux[3] file_s3 = pyu.getlong("outfile_s3.txt", pstruc["DIRANT"]) s3 = load(file_s3) a = insert(self.ind3, ind, ind3, axis=0) b = insert(self.k2, ind, k2) c = insert(self.s3, ind, s3[0], axis=1) self.ind3 = a self.k2 = b self.s3 = c os.remove(file_ind) os.remove(file_s3)
def put(self, typ): """ recover last deleted coeff Parameters ---------- typ : int 2 : shape 2 (Nf , N*M ) 3 : shape 3 (Nf , K ) T ( K x 2 ) """ if typ == 2: file_ind = pyu.getlong("outfile_i2.txt", pstruc['DIRANT']) aux = load(file_ind) ind = aux[0] ind2 = np.array([aux[1], aux[2]]) file_s2 = pyu.getlong("outfile_s2.txt", pstruc['DIRANT']) s2 = load(file_s2) self.s2p = s2 a = insert(self.ind2, ind, ind2, axis=0) b = insert(self.s2, ind, s2, axis=1) self.ind2 = a self.s2 = b if typ == 3: file_ind = pyu.getlong("outfile_i3.txt", pstruc['DIRANT']) aux = load(file_ind) ind = aux[0] ind3 = np.array([aux[1], aux[2]]) k2 = aux[3] file_s3 = pyu.getlong("outfile_s3.txt", pstruc['DIRANT']) s3 = load(file_s3) a = insert(self.ind3, ind, ind3, axis=0) b = insert(self.k2, ind, k2) c = insert(self.s3, ind, s3[0], axis=1) self.ind3 = a self.k2 = b self.s3 = c os.remove(file_ind) os.remove(file_s3)
def loadsrtm(self): """ load hgt and lcv files from srtm directory """ _filehgt = self.prefix + '.HGT' _filelcv = self.prefix + '.lcv' filehgt = pyu.getlong(_filehgt, os.path.join('gis', 'srtm')) filelcv = pyu.getlong(_filelcv, os.path.join('gis', 'srtm')) data = np.fromfile(filehgt, dtype='>i2') self.hgts = data.reshape(1201, 1201) data = np.fromfile(filelcv, dtype='>i1') self.lcvs = data.reshape(1201, 1201)
def load(self): """ Load simulnet_data configuration file """ self.simcfg = ConfigParser.ConfigParser() self.simcfg.read(pyu.getlong(self.simnetfile,pstruc['DIRNETSAVE'])) pdb.set_trace() 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()
def loadini(self, _filespa, rep='ini'): """ load an .ini file Parameters ---------- _filespa : string short filename rep : string directory name """ filespa = pyu.getlong(_filespa, rep) #print filespa+ " loadini" space = cp.ConfigParser() space.read(filespa) points = space.items("coordinates") self.points = pyu.lt2idic(points) self.N = len(self.points.keys()) del self.position for k in self.points.keys(): try: self.position = np.hstack( (self.position, self.points[k].reshape(3, 1))) except: self.position = self.points[k].reshape(3, 1) self.traj = Trajectory(pt=self.position.T)
def loadini(self, _filespa, rep='ini'): """ load an .ini file Parameters ---------- _filespa : string short filename rep : string directory name """ filespa = pyu.getlong(_filespa, rep) #print filespa+ " loadini" space = ConfigParser.ConfigParser() space.read(filespa) points = space.items("coordinates") self.points = pyu.lt2idic(points) self.N = len(self.points.keys()) del self.position for k in self.points.keys(): try: self.position = np.hstack((self.position, self.points[k].reshape(3,1))) except: self.position = self.points[k].reshape(3,1) self.traj=Trajectory(pt=self.position.T)
def show3(self, rays={}, bdis=True, bstruc=True, id=0, strucname='defstr'): """ plot 3D rays within the simulated environment Parameters ---------- raysarr: numpy.ndarray """ pTx = self.pTx.reshape((3, 1)) pRx = self.pRx.reshape((3, 1)) filename = pyu.getlong("grRay" + str(id) + ".list", pstruc['DIRGEOM']) fo = open(filename, "w") fo.write("LIST\n") if bstruc: fo.write("{<"+strucname+".off}\n") #fo.write("{<strucTxRx.off}\n") k = 0 for i in rays.keys(): for j in range(np.shape(rays[i]['pt'])[2]): ray = np.hstack((pTx, np.hstack((rays[i]['pt'][:, :, j], pRx)))) #ray = rays[i]['pt'][:,:,j] col = np.array([2, 0, 1]) print ray fileray = self.show_ray3d(ray=ray, bdis=False, bstruc=False, col=col, id=k) k += 1 fo.write("{< " + fileray + " }\n") fo.close() if (bdis): chaine = "geomview " + filename + " 2>/dev/null &" os.system(chaine) else: return(filename)
def save(self, force=False): if self.filename == '' or force: filename = QFileDialog.getSaveFileName( self, 'Save Layout', pyu.getlong('', pstruc['DIRINI']), '(*.ini);;(*.osm)') try: _filename = pyu.getshort(str(filename)) except: pass else: _filename = self.L.filename try: oldCursor = QCursor() QApplication.setOverrideCursor(QCursor(Qt.BusyCursor)) self.L.saveini(_filename) self.L.saveosm(_filename.split('.')[0] + '.osm') self.L = Layout(_filename) self.filename = self.L.filename self.setWindowTitle(self.L.filename + '- Pylayers : Stand Alone Editor (Beta)') QApplication.setOverrideCursor(oldCursor) print 'saved' except: pass
def __init__(self, _filename='', **kwargs): """ """ if _filename != '': if '.h5' not in _filename: _filename = _filename + '.h5' filename = pyu.getlong(_filename, pstruc['DIRMES']) if os.path.isfile(filename): self._filename = _filename self.filename = filename fd = h5py.File(self.filename, 'r') lkeys = fd.keys() lcal = [c for c in lkeys if 'cal' in c] lmes = [m for m in lkeys if 'mes' in m] self.gcal = {} for ke in lcal: num = int(ke.replace('cal', '')) self.gcal[ke] = self.get_dcal(gcal=num) self.dmes = {} for ke in lmes: self.dmes[ke] = '' fd.close defaults = {'Nt': 8, 'Nr': 4, 'imes': 4} for k in defaults: if k not in kwargs: kwargs[k] = defaults[k] self.Nr = kwargs.pop('Nr') self.Nt = kwargs.pop('Nt') self.imes = kwargs.pop('imes')
def devicels(): """ list available devices in project directory """ fp = open(pyu.getlong('devices.json', pstruc['DIRSIMUL'])) dev = json.load(fp) fp.close() print dev.keys()
def __init__(self, id='0', value=0, std=0, vcw=3, p=np.array([]), model={}, origin={}): Constraint.__init__(self, type='RSS', id=id, p=p, origin=origin) # Constraint.C_id = Constraint.C_id+1 # constraint counter is incremented self.value = value # attennation (dB) self.std = std self.vcw = vcw if model == {}: self.config = ConfigParser.ConfigParser() self.config.read(pyu.getlong('EMSolver.ini', 'ini')) param = dict(self.config.items('rat1_PLM')) self.model = PLSmodel(f=eval(param['f']), rssnp=eval(param['rssnp']), d0=eval(param['d0']), method=param['method']) # self.model={} # self.model['PL0'] =-34.7 # self.model['d0'] = 1.0 # self.model['RSSnp'] = 2.64 # self.model['RSSStd'] = 4.34 # self.model['Rest'] = 'mode' self.param = self.model.param else: self.model = model self.param = self.model.param self.update()
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 check_grpname(self,key,grpname): """Check if the key's data with a given groupname already exists in the h5py file Parameters ---------- key: string key of the h5py group grpname : string groupe name of the h5py file Notes ----- update the key grpname of self.dexist[key] dictionnary """ try : lfilename=pyu.getlong(self.filename,pstruc['DIRLNK']) f = h5py.File(lfilename,'r') if grpname.decode('utf8') in f[key].keys(): self.dexist[key]['exist']=True else : self.dexist[key]['exist']=False f.close() except: f.close() raise NameError('Link exist: issue during stacking')
def stack(self,key,array): """ stack new array in h5py file for a given key (dataframe/group) Parameters ---------- key : string array : np.ndarray Returns ------- idx : int indice of last element of the array of key """ try : lfilename=pyu.getlong(self.filename,pstruc['DIRLNK']) f=h5py.File(lfilename,'a') if key != 'T_map': sc = f[key].shape f[key].resize((sc[0]+1,sc[1])) f[key][-1,:]=array else: sc = f[key].shape f[key].resize((sc[0]+1,sc[1],sc[2])) f[key][-1,:,:]=array f.close() return np.array([sc[0]]) except: f.close() raise NameError('Link stack: issue during stacking')
def saveini(self, ical=1, _fileini='vna_config.ini'): """ save calibration parameters in .ini file Parameters ---------- _fileini : string calibration ini file ical : int calibration number """ dcal = self.dcal[str(ical)] config = ConfigParser.ConfigParser() # stimulus section config.add_section("stimulus") config.set("stimulus", 'fminghz', dcal['fminghz']) config.set("stimulus", 'fmaxghz', dcal['fmaxghz']) config.set("stimulus", 'nf', dcal['nf']) # response section config.add_section("response") config.set("response", 'param', dcal['param']) config.set("response", 'average', 'on') config.set("response", 'navrg', dcal['navrg']) config.set("response", 'ifbhz', dcal['ifbhz']) config.set("response", 'win', 1) fileini = pyu.getlong(_fileini, pstruc['DIRMES']) fd = open(fileini, "w") config.write(fd) fd.close()
def fill_dexist(self,key,grpname): """Check if the key's data with a given groupname already exists in the h5py file Parameters ---------- key: string key of the h5py group grpname : string groupe name of the h5py file Notes ----- update the key grpname of self.dexist[key] dictionnary """ try : lfilename=pyu.getlong(self.filename,pstruc['DIRLNK']) f=h5py.File(lfilename,'r') if grpname.decode('utf8') in f[key].keys(): self.dexist[key]['exist']=True else : self.dexist[key]['exist']=False f.close() except: f.close() raise NameError('Link exist: issue during stacking')
def loadcir(self, itx, irx): """ Parameters ---------- itx : Tx index irx : Rx index Returns ------- cir(itx,irx) """ _filecir = self.dcir[itx][irx] + '.mat' ext = str(itx) if len(ext) == 1: ext = '00' + ext if len(ext) == 2: ext = '0' + ext filecir = pyu.getlong(_filecir, pstruc['DIRCIR']+'/Tx' + ext) D = spio.loadmat(filecir) kxa = 'ta' + str(irx) kya = 'cira' + str(irx) kxo = 'to' + str(irx) kyo = 'ciro' + str(irx) cira = bs.TUsignal(D[kxa], D[kya][:, 0]) ciro = bs.TUsignal(D[kxo], D[kyo][:, 0]) return(cira, ciro)
def __init__(self,_filename): """ """ if '.h5' not in _filename: _filename = _filename+'.h5' self._filename = _filename self.filename = pyu.getlong(self._filename,pstruc['DIRMES'])
def __init__(self, **args): defaults = {'L': None, 'net': None, 'sim': None} ## 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 Process.__init__(self, name='save', sim=self.args['sim']) self.C = ConfigParser.ConfigParser() self.C.read(pyu.getlong('save.ini', 'ini')) self.opt = dict(self.C.items('config')) self.pos = dict(self.C.items('position')) self.ldp = dict(self.C.items('ldp')) self.wstd = dict(self.C.items('wstd')) self.lpos = eval(self.pos['position']) self.lldp = eval(self.ldp['ldp']) self.lwstd = eval(self.wstd['wstd']) self.sim = args['sim'] self.net = args['net']
def vrml2geom(tg, rac): """ convert vrml object into geomview files Parameters ---------- tg : list of objects rac : filename prefix """ for l in tg: # prepare geomview file fi1 = rac+l['name'] _fi1 = fi1+'.list' fina = pyu.getlong(_fi1, 'geom') fd = open(fina, 'w') fd.write('LIST') for k in l.keys(): if k != 'name': filename = fi1+'-'+str(k) fd.write('{<'+filename+'.off}\n') G = geo.Geomoff(filename) c = l[k]['coord'] i = l[k]['index'] tt = [] ltt = [] for u in i: if u == -1: ltt.append(tt) tt = [] else: tt.append(u) # build a geomview list of polygons G.polygons(c, ltt) fd.close()
def save(self, force=False): if self.filename == "" or force: filename = QFileDialog.getSaveFileName( self, "Save Layout", pyu.getlong("", pstruc["DIRINI"]), "(*.ini);;(*.osm)" ) try: _filename = pyu.getshort(str(filename)) except: pass else: _filename = self.L.filename try: oldCursor = QCursor() QApplication.setOverrideCursor(QCursor(Qt.BusyCursor)) self.L.saveini(_filename) self.L.saveosm(_filename.split(".")[0] + ".osm") self.L = Layout(_filename) self.filename = self.L.filename self.setWindowTitle(self.L.filename + "- Pylayers : Stand Alone Editor (Beta)") QApplication.setOverrideCursor(oldCursor) print "saved" except: pass
def vrml2geom(tg, rac): """ convert vrml object into geomview files Parameters ---------- tg : list of objects rac : filename prefix """ for l in tg: # prepare geomview file fi1 = rac + l["name"] _fi1 = fi1 + ".list" fina = pyu.getlong(_fi1, "geom") fd = open(fina, "w") fd.write("LIST") for k in l.keys(): if k != "name": filename = fi1 + "-" + str(k) fd.write("{<" + filename + ".off}\n") G = geo.Geomoff(filename) c = l[k]["coord"] i = l[k]["index"] tt = [] ltt = [] for u in i: if u == -1: ltt.append(tt) tt = [] else: tt.append(u) # build a geomview list of polygons G.polygons(c, ltt) fd.close()
def saveini(self,ical=1,_fileini='vna_config.ini'): """ save calibration parameters in .ini file Parameters ---------- _fileini : string calibration ini file ical : int calibration number """ dcal = self.dcal[str(ical)] config = ConfigParser.ConfigParser() # stimulus section config.add_section("stimulus") config.set("stimulus",'fminghz',dcal['fminghz']) config.set("stimulus",'fmaxghz',dcal['fmaxghz']) config.set("stimulus",'nf',dcal['nf']) config.set("stimulus",'power',dcal['power']) # response section config.add_section("response") config.set("response",'param',dcal['param']) config.set("response",'average','on') config.set("response",'navrg',dcal['navrg']) config.set("response",'ifbhz',dcal['ifbhz']) config.set("response",'win',1) fileini = pyu.getlong(_fileini,pstruc['DIRMES']) fd = open(fileini,"w") config.write(fd) fd.close()
def load(self, name, _fileini='defAP.json'): """ loading an access point from file Parameters ---------- _fileini : string access point description ini file """ self._fileini = _fileini fileini = pyu.getlong(_fileini, pstruc['DIRSIMUL']) fp = open(fileini, "r") ap = json.load(fp) self['name'] = name dap = ap[name] self['p'] = eval(dap['pos']) wstd = dap['wstd'] self['PtdBm'] = dap['ptdbm'] self['channels'] = eval(dap['chan']) self['sensdBm'] = dap['snsdbm'] self['nant'] = dap['nant'] standard = Wstandard(wstd) self.s = standard fp.close()
def importsn(_filename='pos.csv'): """ import simulnet csv file ****DEPRECATED Parameters ---------- filename : string default 'pos.csv' Returns ------- lt : list of trajectory """ filename = pyu.getlong(_filename, pstruc['DIRNETSAVE']) dt = pd.read_csv(filename) dtk = dt.keys() N = len(dtk) Ntraj = (N-1)/3 lt = [] for it in range(Ntraj): x = dt[dtk[3*it+1]].values y = dt[dtk[3*it+2]].values z = np.zeros(len(x)) pt = np.vstack((x, y, z)) T=Trajectory() lt.append(T.generate(t=dt['time'].values, pt=pt.T, unit='s')) return(lt)
def __init__(self, id='0', value=np.array(([0])), std=np.array((1.0)), vcw=3, p=np.array([]), model={}, origin={}): Constraint.__init__(self, type='RSS', id=id, p=p, origin=origin) self.value = value # attennation (dB) self.std = std self.vcw = vcw if model == {}: self.config = ConfigParser.ConfigParser() self.config.read(pyu.getlong('EMSolver.ini', 'ini')) param = dict(self.config.items('rat1_PLM')) self.model = PLSmodel(f=eval(param['f']), rssnp=eval(param['rssnp']), d0=eval(param['d0']), method=param['method']) # self.model={} # self.model['PL0'] =-34.7 # self.model['d0'] = 1.0 # self.model['RSSnp'] = 2.64 # self.model['RSSStd'] = 4.34 # self.model['Rest'] = 'mode' self.param = self.model.param else: self.model = model self.param = self.model.param self.update()
def mat_save(self,S): """ save node positions into a matlab structure file Attributes: ---------- filename : string name of the mat file S : Simulation Scipy.Simulation object """ pos=nx.get_node_attributes(self,'p').items() for i in range(len(pos)): if not 'BS' in pos[i][0]: try: self.mat[pos[i][0]]['pos']=np.vstack((self.mat[pos[i][0]]['pos'],pos[i][1])) self.mat[pos[i][0]]['time']=np.vstack((self.mat[pos[i][0]]['time'],S.now())) except: self.mat[pos[i][0]]={} self.mat[pos[i][0]]['pos']=pos[i][1] self.mat[pos[i][0]]['time']=np.array(S.now()) else : try: self.mat[pos[i][0]]['pos']=pos[i][1] except: self.mat[pos[i][0]]={} self.mat[pos[i][0]]['pos']=pos[i][1] sp.io.savemat(pyu.getlong('mat.mat','save_data'),self.mat)
def load(self,name,_fileini='defAP.json'): """ loading an access point from file Parameters ---------- _fileini : string access point description ini file """ self._fileini = _fileini fileini = pyu.getlong(_fileini,pstruc['DIRSIMUL']) fp = open(fileini,"r") ap = json.load(fp) self['name'] = name dap = ap[name] self['p'] = eval(dap['pos']) wstd = dap['wstd'] self['PtdBm'] = dap['ptdbm'] self['channels'] = eval(dap['chan']) self['sensdBm'] = dap['snsdbm'] self['nant'] = dap['nant'] standard = Wstandard(wstd) self.s = standard fp.close()
def __init__(self, **args): defaults = {'L': None, 'net': None, 'sim': None} ## 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 Process.__init__(self, name='save', sim=self.args['sim']) self.C = ConfigParser.ConfigParser() self.C.read(pyu.getlong('save.ini','ini')) self.opt = dict(self.C.items('config')) self.pos = dict(self.C.items('position')) self.ldp = dict(self.C.items('ldp')) self.rat = dict(self.C.items('rat')) self.lpos = eval(self.pos['position']) self.lldp = eval(self.ldp['ldp']) self.lrat = eval(self.rat['rat']) self.sim = args['sim'] self.net = args['net']
def load(self,stdname,_fileini='wstd.json'): """ load a standard from file Parameters ---------- stdname : string standard name _fileini : string file containing the description of available standards """ fp = open(pyu.getlong('wstd.json',pstruc['DIRSIMUL'])) stds = json.load(fp) fp.close() std = stds[stdname] for k in std: if k<> "channels": try: self[k] = eval(std[k]) except: self[k] = std[k] else: chan = std[k] for k in chan: bandname = k fstart=chan[k]['fstart'] fstop =chan[k]['fstop'] smhz =chan[k]['smhz'] bmhz = chan[k]['bmhz'] gmhz = chan[k]['gmhz'] self.bandplan(fstart=fstart,fstop=fstop,smhz=smhz,bmhz=bmhz,gmhz=gmhz)
def importsn(_filename='pos.csv'): """ import simulnet csv file Parameters ---------- filename : string default 'pos.csv' Returns ------- lt : list of trajectory """ filename = pyu.getlong(_filename,'save_data') dt = pd.read_csv(filename) dtk = dt.keys() N = len(dtk) Ntraj = (N-1)/3 lt = [] for it in range(Ntraj): pt = np.vstack((dt[dtk[3*it+1]].values,dt[dtk[3*it+2]].values)) lt.append(Trajectory(dt['time'].values,pt=pt.T,unit='s')) return(lt)
def vrml2geom(tg, rac): """ convert vrml object into geomview files Parameters ---------- tg : list of objects rac : filename prefix """ for l in tg: # prepare geomview file fi1 = rac + l['name'] _fi1 = fi1 + '.list' fina = pyu.getlong(_fi1, 'geom') fd = open(fina, 'w') fd.write('LIST') for k in l.keys(): if k != 'name': filename = fi1 + '-' + str(k) fd.write('{<' + filename + '.off}\n') G = geo.Geomoff(filename) c = l[k]['coord'] i = l[k]['index'] tt = [] ltt = [] for u in i: if u == -1: ltt.append(tt) tt = [] else: tt.append(u) # build a geomview list of polygons G.polygons(c, ltt) fd.close()
def loadaster(self,fileaster=[]): """ load Aster files """ # construct filename from prefix _fileaster = 'ASTGTM2_'+self.prefix+'_dem.tif' if fileaster==[]: fileaster = pyu.getlong(_fileaster,os.path.join('gis','aster')) else: _fieleaster = pyu.getshort(fileaster) # zip extraction ext = _fileaster.split('.') if ext[1]=='zip': with zipfile.Zipfile(fileaster) as zf: for member in zf.infolist(): words = member.filename.split('/') path = dest_dir for word in words[:-1]: drive, word = os.path.splitdrive(word) head, word = os.path.split(word) if word in (os.curdir, os.pardir, ''): continue path = os.path.join(path, word) zf.extract(member, path) f = gdal.Open(fileaster) self.hgta = f.ReadAsArray()
def save_model(self,RAT,model): """save a RAT model Parameters ---------- RAT : string RAT name model : dictionnary parameters of the PL model """ fileini = pyu.getlong(self.fileini, pstruc['DIRSIMUL']) fd = open(fileini, "a") nconfig = ConfigParser.ConfigParser() nconfig.add_section(RAT+'_PLM') nconfig.set(RAT+'_PLM','sigrss', str(model.sigrss)) nconfig.set(RAT+'_PLM','f', str(model.f)) nconfig.set(RAT+'_PLM','rssnp', str(model.rssnp)) nconfig.set(RAT+'_PLM','d0', str(model.d0)) nconfig.set(RAT+'_PLM','method', str(model.method)) nconfig.write(fd) fd.close()
def __init__(self,**args): defaults={'net':Network(), 'L':[], 'net_updt_time':0.001, 'sim':None, 'show_sg':False, 'disp_inf':False, 'save':[]} ## 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 Process.__init__(self,name='PNetwork',sim=self.sim) self.cpt=self.sim.now() self.filename='pos' if 'mysql' in self.save: config = ConfigParser.ConfigParser() config.read(pyu.getlong('simulnet.ini','ini')) sql_opt = dict(config.items('Mysql')) self.net.db = Database(sql_opt['host'],sql_opt['user'],sql_opt['passwd'],sql_opt['dbname'])
def loadcir(self, itx, irx): """ Parameters ---------- itx : Tx index irx : Rx index Returns ------- cir(itx,irx) """ _filecir = self.dcir[itx][irx] + '.mat' ext = str(itx) if len(ext) == 1: ext = '00' + ext if len(ext) == 2: ext = '0' + ext filecir = pyu.getlong(_filecir, pstruc['DIRCIR'] + '/Tx' + ext) D = spio.loadmat(filecir) kxa = 'ta' + str(irx) kya = 'cira' + str(irx) kxo = 'to' + str(irx) kyo = 'ciro' + str(irx) cira = bs.TUsignal(D[kxa], D[kya][:, 0]) ciro = bs.TUsignal(D[kxo], D[kyo][:, 0]) return (cira, ciro)
def importsn(_filename='pos.csv'): """ import simulnet csv file ****DEPRECATED Parameters ---------- filename : string default 'pos.csv' Returns ------- lt : list of trajectory """ filename = pyu.getlong(_filename, pstruc['DIRNETSAVE']) dt = pd.read_csv(filename) dtk = dt.keys() N = len(dtk) Ntraj = (N - 1) / 3 lt = [] for it in range(Ntraj): x = dt[dtk[3 * it + 1]].values y = dt[dtk[3 * it + 2]].values z = np.zeros(len(x)) pt = np.vstack((x, y, z)) T = Trajectory() lt.append(T.generate(t=dt['time'].values, pt=pt.T, unit='s')) return (lt)
def loadsrtm(self): """ load hgt and lcv files from srtm directory """ _filehgt = self.prefix+'.HGT' _filelcv = self.prefix+'.lcv' filehgt = pyu.getlong(_filehgt,os.path.join('gis','srtm')) filelcv = pyu.getlong(_filelcv,os.path.join('gis','srtm')) data = np.fromfile(filehgt,dtype='>i2') self.hgt = data.reshape(1201,1201) data = np.fromfile(filelcv,dtype='>i1') self.lcv = data.reshape(1201,1201)
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 loadh5(self, _filename='simulnet_TA-Office.h5',append =False): """ import simulnet h5 file Parameters ---------- filename : string default simulnet + Layout_filename . h5 append : boolean if True : append new trajectories to preexisting ones Returns ------- lt : list of trajectory Examples -------- .. plot:: :include-source: >>> from pylayers.mobility.trajectory import * >>> T = Trajectories() >>> T.loadh5() """ filename = pyu.getlong(_filename, pstruc['DIRNETSAVE']) if os.path.exists(filename): fil = pd.io.pytables.HDFStore(filename) else: raise NameError(filename + ' not found') if not append: [self.pop(0) for i in range(len(self))] for k in fil.keys(): df = fil[k] #df = df.set_index('t') df.index = pd.to_datetime(df.t) ID = fil.get_storer(k).attrs.ID name = fil.get_storer(k).attrs.name typ = fil.get_storer(k).attrs.typ layout = fil.get_storer(k).attrs.layout # # velocity # v = np.array((df.vx.values,df.vy.values)) # d = np.sqrt(np.sum(v*v,axis=0)) s = np.cumsum(d) df['s'] = s self.append(Trajectory(df=df,ID=ID,name=name,typ=typ)) fil.close() self.Lfilename = layout self.t = self.time()
def loadpd(self): """ load data from previous simulations """ filenameh5 = pyu.getlong(self.filename, pstruc['DIRLNK']) store = pd.HDFStore(filenameh5) #self.data = pd.read_hdf(filenameh5,'df') self.data = store.get('df') self.data.index.name='t' self.data = self.data.sort()
def chgover(self): """ change overlay file """ filename = QFileDialog.getOpenFileName(self,'Open Pylayers Layout File',pyu.getlong('',pstruc['DIRIMAGE']),'(*.png);;(*.jpg)') if filename != '': _filename= pyu.getshort(str(filename)) self.L.display['fileoverlay']=_filename print 'loaded overlay'
def dir(self): path = pyu.getlong('', pstruc['DIRMES']) fileh5 = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) ] for k in fileh5: if '.h5' in k: print k
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