예제 #1
0
    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()
예제 #2
0
    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()
예제 #3
0
class Coverage(PyLayers):
    """ Handle Layout Coverage

        Methods
        -------

        creategrid()
            create a uniform grid for evaluating losses
        cover()
            run the coverage calculation
        showPower()
            display the map of received power
        showLoss()
            display the map of losses


        Attributes
        ----------

        All attributes are read from fileini ino the ini directory of the
        current project

        _fileini
            default coverage.ini

        L     : a Layout
        nx    : number of point on x
        ny    : number of point on y
        tx    : transmitter position
        txpe  : transmitter power emmission level
        show  : boolean for automatic display power map
        na : number of access point

    """


    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
        filename = self.layoutopt['filename']
        if filename.endswith('ini'):
            self.typ = 'indoor'
            self.L = Layout(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
            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()

        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'])

    def __repr__(self):
        st=''
        if self.typ=='indoor':
            st = st+ 'Layout file : '+self.L.filename + '\n\n'
            st = st + '-----list of Access Points ------'+'\n'
            for k in self.dap:
                st = st + self.dap[k].__repr__()+'\n'
            st = st + '-----Rx------'+'\n'
            st= st+ 'temperature (K) : '+ str(self.temperaturek) + '\n'
            st= st+ 'noisefactor (dB) : '+ str(self.noisefactordb) + '\n\n'
            st = st + '--- Grid ----'+'\n'
            st= st+ 'mode : ' + str(self.mode) + '\n'
            if self.mode<>'file':
                st= st+ 'nx : ' + str(self.nx) + '\n'
                st= st+ 'ny : ' + str(self.ny) + '\n'
            if self.mode=='zone':
                st= st+ 'boundary (xmin,ymin,xmax,ymax) : ' + str(self.boundary) + '\n\n'
            if self.mode=='file':
                st = st+' filename : '+self.filespa+'\n'
        return(st)

    def creategrid(self,mode='full',boundary=[],_fileini=''):
        """ create a grid

        Parameters
        ----------

        full : boolean
            default (True) use all the layout area
        boundary : (xmin,ymin,xmax,ymax)
            if full is False the boundary argument is used

        """
        if mode=="file":
            self.RN = RadioNode(name='',
                               typ='rx',
                               _fileini = _fileini,
                               _fileant = 'def.vsh3')
            self.grid =self.RN.position[0:2,:].T
        else:
            if mode=="full":
                mi=np.min(self.L.Gs.pos.values(),axis=0)+0.01
                ma=np.max(self.L.Gs.pos.values(),axis=0)-0.01
            if mode=="zone":
                assert boundary<>[]
                mi = np.array([boundary[0],boundary[1]])
                ma = np.array([boundary[2],boundary[3]])

            x = np.linspace(mi[0],ma[0],self.nx)
            y = np.linspace(mi[1],ma[1],self.ny)

            self.grid=np.array((list(np.broadcast(*np.ix_(x, y)))))

        self.ng = self.grid.shape[0]

    def where1(self):
        """
        Unfinished : Not sure this is the right place (too specific)
        """
        M1 = UWBMeasure(1)
        self.dap={}
        self.dap[1]={}
        self.dap[2]={}
        self.dap[3]={}
        self.dap[4]={}
        self.dap[1]['p']=M1.rx[1,0:2]
        self.dap[2]['p']=M1.rx[1,0:2]
        self.dap[3]['p']=M1.rx[1,0:2]
        self.dap[4]['p']=M1.rx[1,0:2]
        for k in range(300):
            try:
                M = UWBMeasure(k)
                tx = M.tx
                self.grid=np.vstack((self.grid,tx[0:2]))
                D  = M.rx-tx[np.newaxis,:]
                D2 = D*D
                dist = np.sqrt(np.sum(D2,axis=1))[1:]
                Emax = M.Emax()
                Etot = M.Etot()[0]
                try:
                    td1 = np.hstack((td1,dist[0]))
                    td2 = np.hstack((td2,dist[1]))
                    td3 = np.hstack((td3,dist[2]))
                    td4 = np.hstack((td4,dist[3]))
                    te1 = np.hstack((te1,Emax[0]))
                    te2 = np.hstack((te2,Emax[1]))
                    te3 = np.hstack((te3,Emax[2]))
                    te4 = np.hstack((te4,Emax[3]))
                    tt1 = np.hstack((tt1,Etot[0]))
                    tt2 = np.hstack((tt2,Etot[1]))
                    tt3 = np.hstack((tt3,Etot[2]))
                    tt4 = np.hstack((tt4,Etot[3]))
                    #tdist = np.hstack((tdist,dist))
                    #te = np.hstack((te,Emax))
                except:
                    td1=np.array(dist[0])
                    td2=np.array(dist[1])
                    td3=np.array(dist[2])
                    td4=np.array(dist[3])
                    te1 =np.array(Emax[0])
                    te2 =np.array(Emax[1])
                    te3 =np.array(Emax[2])
                    te4 =np.array(Emax[3])
                    tt1 =np.array(Etot[0])
                    tt2 =np.array(Etot[1])
                    tt3 =np.array(Etot[2])
                    tt4 =np.array(Etot[3])
            except:
                pass

    def cover(self,sinr=True,snr=True,best=True):
        """ run the coverage calculation

        Parameters
        ----------

        sinr : boolean
        snr  : boolean
        best : boolean

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a=C.show(typ='sinr',figsize=(10,8))
            >>> plt.show()

        Notes
        -----

        self.fGHz is an array, it means that Coverage is calculated at once
        for a whole set of frequencies. In practice, it would be the center
        frequency of a given standard channel.

        This function is calling `loss.Losst` which calculates Losses along a
        straight path.

        In a future implementation we will
        abstract the EM solver in order to make use of other calculation
        approaches as a full or partial Ray Tracing.

        The following members variables are evaluated :

        + freespace Loss @ fGHz   PL()  PathLoss (shoud be rename FS as free space) $
        + prdbmo : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{odB}`
        + prdbmp : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{pdB}`
        + snro : SNR polar o (H)
        + snrp : SNR polar p (H)

        See Also
        --------

        pylayers.antprop.loss.Losst
        pylayers.antprop.loss.PL

        """
        #
        # select active AP
        #
        lactiveAP = []
        try:
            del self.aap
            del self.ptdbm
        except:
            pass

        self.kB = 1.3806503e-23 # Boltzmann constant
        for iap in self.dap:
            if self.dap[iap]['on']:
                lactiveAP.append(iap)
                fGHz = self.dap[iap].s.fcghz
                self.fGHz=np.unique(np.hstack((self.fGHz,fGHz)))
                apchan = self.dap[iap]['chan']
                try:
                    self.aap   = np.vstack((self.aap,self.dap[iap]['p'][0:2]))
                    self.ptdbm = np.vstack((self.ptdbm,self.dap[iap]['PtdBm']))
                    self.bmhz  = np.vstack((self.bmhz,
                                 self.dap[iap].s.chan[apchan[0]]['BMHz']))
                except:
                    self.aap   = self.dap[iap]['p'][0:2]
                    self.ptdbm = np.array(self.dap[iap]['PtdBm'])
                    self.bmhz  = np.array(self.dap[iap].s.chan[apchan[0]]['BMHz'])

        PnW = np.array((10**(self.noisefactordb/10.))*self.kB*self.temperaturek*self.bmhz*1e6)
        # Evaluate Noise Power (in dBm)
        self.pndbm = np.array(10*np.log10(PnW)+30)
        #lchan = map(lambda x: self.dap[x]['chan'],lap)
        #apchan = zip(self.dap.keys(),lchan)
        #self.bmhz = np.array(map(lambda x: self.dap[x[0]].s.chan[x[1][0]]['BMHz']*len(x[1]),apchan))

        self.ptdbm = self.ptdbm.T
        self.pndbm = self.pndbm.T
        # creating all links
        p = product(range(self.ng),lactiveAP)
        #
        # pa : access point
        # pg : grid point
        #
        # 1 x na
        for k in p:
            pg = self.grid[k[0],:]
            pa = self.dap[k[1]]['p'][0:2]
            try:
                self.pa = np.vstack((self.pa,pa))
            except:
                self.pa = pa
            try:
                self.pg = np.vstack((self.pg,pg))
            except:
                self.pg = pg

        self.pa = self.pa.T
        self.pg = self.pg.T
        self.nf = len(self.fGHz)

        # retrieving dimensions along the 3 axis
        na = len(lactiveAP)
        self.na = na
        ng = self.ng
        nf = self.nf

        Lwo,Lwp,Edo,Edp = loss.Losst(self.L,self.fGHz,self.pa,self.pg,dB=False)
        self.Lwo = Lwo.reshape(nf,ng,na)
        self.Edo = Edo.reshape(nf,ng,na)
        self.Lwp = Lwp.reshape(nf,ng,na)
        self.Edp = Edp.reshape(nf,ng,na)

        freespace = loss.PL(self.fGHz,self.pa,self.pg,dB=False)
        self.freespace = freespace.reshape(nf,ng,na)

        # transmitting power
        # f x g x a

        # CmW : Received Power coverage in mW
        self.CmWo = 10**(self.ptdbm[np.newaxis,...]/10.)*self.Lwo*self.freespace
        self.CmWp = 10**(self.ptdbm[np.newaxis,...]/10.)*self.Lwp*self.freespace


        if snr:
            self.evsnr()
        if sinr:
            self.evsinr()
        if best:
            self.evbestsv()

    def evsnr(self):
        """ calculates snr
        """

        NmW = 10**(self.pndbm/10.)[np.newaxis,:]

        self.snro = self.CmWo/NmW
        self.snrp = self.CmWp/NmW

    def evsinr(self):
        """ calculates sinr

        """

        # na : number of access point
        na = self.na

        # U : 1 x 1 x na x na
        U = (np.ones((na,na))-np.eye(na))[np.newaxis,np.newaxis,:,:]

        # CmWo : received power in mW orthogonal polarization
        # CmWp : received power in mW parallel polarization

        ImWo = np.einsum('ijkl,ijl->ijk',U,self.CmWo)
        ImWp = np.einsum('ijkl,ijl->ijk',U,self.CmWp)


        NmW = 10**(self.pndbm/10.)[np.newaxis,:]

        self.sinro = self.CmWo/(ImWo+NmW)
        self.sinrp = self.CmWp/(ImWp+NmW)

    def evbestsv(self):
        """ determine the best server map

        Notes
        -----

        C.bestsv

        """
        na = self.na
        ng = self.ng
        nf = self.nf
        # find best server regions
        Vo = self.CmWo
        Vp = self.CmWp
        self.bestsvo = np.empty(nf*ng*na).reshape(nf,ng,na)
        self.bestsvp = np.empty(nf*ng*na).reshape(nf,ng,na)
        for kf in range(nf):
            MaxVo = np.max(Vo[kf,:,:],axis=1)
            MaxVp = np.max(Vp[kf,:,:],axis=1)
            for ka in range(na):
                uo = np.where(Vo[kf,:,ka]==MaxVo)
                up = np.where(Vp[kf,:,ka]==MaxVp)
                self.bestsvo[kf,uo,ka]=ka+1
                self.bestsvp[kf,up,ka]=ka+1


#    def showEd(self,polar='o',**kwargs):
#        """ shows a map of direct path excess delay
#
#        Parameters
#        ----------
#
#        polar : string
#        'o' | 'p'
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            >> from pylayers.antprop.coverage import *
#            >> C = Coverage()
#            >> C.cover()
#            >> C.showEd(polar='o')
#
#        """
#
#        if not kwargs.has_key('alphacy'):
#            kwargs['alphacy']=0.0
#        if not kwargs.has_key('colorcy'):
#            kwargs['colorcy']='w'
#        if not kwargs.has_key('nodes'):
#            kwargs['nodes']=False
#
#        fig,ax = self.L.showG('s',**kwargs)
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        cdict = {
#        'red'  :  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'green':  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'blue' :  ((0., 0.5, 0.5), (1., 1., 1.))
#        }
#        #generate the colormap with 1024 interpolated values
#        my_cmap = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
#
#
#        if polar=='o':
#            mcEdof = np.ma.masked_where(prdbm < self.rxsens,self.Edo)
#
#            cov=ax.imshow(mcEdof.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'jet',
#                             origin='lower')
#
#
#
#            # cov=ax.imshow(self.Edo.reshape((self.nx,self.ny)).T,
#            #           extent=(l,r,b,t),
#            #           origin='lower')
#            titre = "Map of LOS excess delay, polar orthogonal"
#
#        if polar=='p':
#            mcEdpf = np.ma.masked_where(prdbm < self.rxsens,self.Edp)
#
#            cov=ax.imshow(mcEdpf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'jet',
#                             origin='lower')
#
#            # cov=ax.imshow(self.Edp.reshape((self.nx,self.ny)).T,
#            #           extent=(l,r,b,t),
#            #           origin='lower')
#            titre = "Map of LOS excess delay, polar parallel"
#
#        ax.scatter(self.tx[0],self.tx[1],linewidth=0)
#        ax.set_title(titre)
#
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        clb = fig.colorbar(cov,cax)
#        clb.set_label('excess delay (ns)')
#
#        if self.show:
#            plt.show()
#        return fig,ax
#
#    def showPower(self,rxsens=True,nfl=True,polar='o',**kwargs):
#        """ show the map of received power
#
#        Parameters
#        ----------
#
#        rxsens : bool
#              clip the map with rx sensitivity set in self.rxsens
#        nfl : bool
#              clip the map with noise floor set in self.pndbm
#        polar : string
#            'o'|'p'
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            > from pylayers.antprop.coverage import *
#            > C = Coverage()
#            > C.cover()
#            > C.showPower()
#
#        """
#
#        if not kwargs.has_key('alphacy'):
#            kwargs['alphacy']=0.0
#        if not kwargs.has_key('colorcy'):
#            kwargs['colorcy']='w'
#        if not kwargs.has_key('nodes'):
#            kwargs['nodes']=False
#        fig,ax = self.L.showG('s',**kwargs)
#
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
##        tCM = plt.cm.get_cmap('jet')
##        tCM._init()
##        alphas = np.abs(np.linspace(.0,1.0, tCM.N))
##        tCM._lut[:-3,-1] = alphas
#
#        title='Map of received power - Pt = ' + str(self.ptdbm) + ' dBm'+str(' fGHz =') + str(self.fGHz) + ' polar = '+polar
#
#        cdict = {
#        'red'  :  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'green':  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'blue' :  ((0., 0.5, 0.5), (1., 1., 1.))
#        }
#
#        if not kwargs.has_key('cmap'):
#        # generate the colormap with 1024 interpolated values
#            cmap = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
#        else:
#            cmap = kwargs['cmap']
#        #my_cmap = cm.copper
#
#
#        if rxsens :
#
#            ## values between the rx sensitivity and noise floor
#            mcPrf = np.ma.masked_where((prdbm > self.rxsens)
#                                     & (prdbm < self.pndbm),prdbm)
#            # mcPrf = np.ma.masked_where((prdbm > self.rxsens) ,prdbm)
#
#            cov1 = ax.imshow(mcPrf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = cm.copper,
#                             vmin=self.rxsens,origin='lower')
#
#            ### values above the sensitivity
#            mcPrs = np.ma.masked_where(prdbm < self.rxsens,prdbm)
#            cov = ax.imshow(mcPrs.reshape((self.nx,self.ny)).T,
#                            extent=(l,r,b,t),
#                            cmap = cmap,
#                            vmin=self.rxsens,origin='lower')
#            title=title + '\n black : Pr (dBm) < %.2f' % self.rxsens + ' dBm'
#
#        else :
#            cov=ax.imshow(prdbm.reshape((self.nx,self.ny)).T,
#                          extent=(l,r,b,t),
#                          cmap = cmap,
#                          vmin=self.pndbm,origin='lower')
#
#        if nfl:
#            ### values under the noise floor
#            ### we first clip the value below the noise floor
#            cl = np.nonzero(prdbm<=self.pndbm)
#            cPr = prdbm
#            cPr[cl] = self.pndbm
#            mcPruf = np.ma.masked_where(cPr > self.pndbm,cPr)
#            cov2 = ax.imshow(mcPruf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'binary',
#                             vmax=self.pndbm,origin='lower')
#            title=title + '\n white : Pr (dBm) < %.2f' % self.pndbm + ' dBm'
#
#
#        ax.scatter(self.tx[0],self.tx[1],s=10,c='k',linewidth=0)
#
#        ax.set_title(title)
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        clb = fig.colorbar(cov,cax)
#        clb.set_label('Power (dBm)')
#
#        if self.show:
#            plt.show()
#
#        return fig,ax
#
#
#    def showTransistionRegion(self,polar='o'):
#        """
#
#        Notes
#        -----
#
#        See  : "Analyzing the Transitional Region in Low Power Wireless Links"
#                Marco Zuniga and Bhaskar Krishnamachari
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            > from pylayers.antprop.coverage import *
#            > C = Coverage()
#            > C.cover()
#            > C.showTransitionRegion()
#
#        """
#
#        frameLength = self.framelengthbytes
#
#        PndBm = self.pndbm
#        gammaU = 10*np.log10(-1.28*np.log(2*(1-0.9**(1./(8*frameLength)))))
#        gammaL = 10*np.log10(-1.28*np.log(2*(1-0.1**(1./(8*frameLength)))))
#
#        PrU = PndBm + gammaU
#        PrL = PndBm + gammaL
#
#        fig,ax = self.L.showGs()
#
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
#        zones = np.zeros(np.shape(prdbm))
#        #pdb.set_trace()
#
#        uconnected  = np.nonzero(prdbm>PrU)
#        utransition = np.nonzero((prdbm < PrU)&(prdbm > PrL))
#        udisconnected = np.nonzero(prdbm < PrL)
#
#        zones[uconnected] = 1
#        zones[utransition] = (prdbm[utransition]-PrL)/(PrU-PrL)
#        cov = ax.imshow(zones.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'BuGn',origin='lower')
#
#        title='PDR region'
#        ax.scatter(self.tx[0],self.tx[1],linewidth=0)
#
#        ax.set_title(title)
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        fig.colorbar(cov,cax)
#        if self.show:
#            plt.show()
#
    def plot(self,**kwargs):
        """
        """
        defaults = { 'typ': 'pr',
                     'grid': False,
                     'f' : 0,
                     'a' : 0,
                     'db':True,
                     'col':'b'
                   }
        for k in defaults:
            if k not in kwargs:
                kwargs[k]=defaults[k]

        if 'fig' in kwargs:
            fig=kwargs['fig']
        else:
            fig=plt.figure()

        if 'ax' in kwargs:
            ax = kwargs['ax']
        else:
            ax = fig.add_subplot(111)

        if kwargs['typ']=='pr':
            if kwargs['a']<>-1:
                U = self.CmW[kwargs['f'],:,kwargs['a']]
            else:
                U = self.CmW[kwargs['f'],:,:].reshape(self.na*self.ng)
            if kwargs['db']:
                U = 10*np.log10(U)

        D = np.sqrt(np.sum((self.pa-self.pg)*(self.pa-self.pg),axis=0))
        if kwargs['a']<>-1:
            D = D.reshape(self.ng,self.na)
            ax.semilogx(D[:,kwargs['a']],U,'.',color=kwargs['col'])
        else:
            ax.semilogx(D,U,'.',color=kwargs['col'])

        return fig,ax

    def show(self,**kwargs):
        """ show coverage

        Parameters
        ----------

        typ : string
            'pr' | 'sinr' | 'capacity' | 'loss' | 'best' | 'egd'
        grid : boolean
        polar : string
            'o' | 'p'
        best : boolean
            draw best server contour if True
        f : int
            frequency index
        a : int
            access point index (-1 all access point)

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a = C.show(typ='pr',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='best',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='loss',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='sinr',figsize=(10,8))
            >>> plt.show()

        See Also
        --------

        pylayers.gis.layout.Layout.showG

        """
        defaults = { 'typ': 'pr',
                     'grid': False,
                     'polar':'p',
                     'f' : 0,
                     'a' :-1,
                     'db':True,
                     'cmap' :cm.jet,
                     'best':True
                   }

        title = self.dap[1].s.name+ ' : '

        for k in defaults:
            if k not in kwargs:
                kwargs[k]=defaults[k]
        polar = kwargs['polar']
        if 'fig' in kwargs:
            if 'ax' in kwargs:
                fig,ax=self.L.showG('s',fig=kwargs['fig'],ax=kwargs['ax'])
            else:
                fig,ax=self.L.showG('s',fig=kwargs['fig'])
        else:
            if 'figsize' in kwargs:
                fig,ax=self.L.showG('s',figsize=kwargs['figsize'])
            else:
                fig,ax=self.L.showG('s')

        # plot the grid
        if kwargs['grid']:
            for k in self.dap:
                p = self.dap[k].p
                ax.plot(p[0],p[1],'or')

        f = kwargs['f']
        a = kwargs['a']
        typ = kwargs['typ']
        best = kwargs['best']

        dB = kwargs['db']

        # setting the grid

        l = self.grid[0,0]
        r = self.grid[-1,0]
        b = self.grid[0,1]
        t = self.grid[-1,-1]

        if typ=='best':
            title = title + 'Best server'+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
            for ka in range(self.na):
                if polar=='p':
                    bestsv =  self.bestsvp[f,:,ka]
                if polar=='o':    
                    bestsv =  self.bestsvo[f,:,ka]
                m = np.ma.masked_where(bestsv == 0,bestsv)
                if self.mode<>'file':
                    W = m.reshape(self.nx,self.ny).T
                    ax.imshow(W, extent=(l,r,b,t),
                            origin='lower',
                            vmin=1,
                            vmax=self.na+1)
                else:
                    ax.scatter(self.grid[:,0],self.grid[:,1],c=m,s=20,linewidth=0)
            ax.set_title(title)
        else:
            if typ=='egd':
                title = title + 'excess group delay : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
                V = self.Ed
                dB = False
                legcb =  'Delay (ns)'
            if typ=='sinr':
                title = title + 'SINR : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar=='o':        
                    V = self.sinro
                if polar=='p':    
                    V = self.sinrp
            if typ=='snr':
                title = title + 'SNR : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar=='o':
                    V = self.snro
                if polar=='p':
                    V = self.snrp
            if typ=='capacity':
                title = title + 'Capacity : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
                legcb = 'Mbit/s'
                if polar=='o':
                    V = self.bmhz.T[np.newaxis,:]*np.log(1+self.sinro)/np.log(2)
                if polar=='p':
                    V = self.bmhz.T[np.newaxis,:]*np.log(1+self.sinrp)/np.log(2)
            if typ=='pr':
                title = title + 'Pr : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
                if dB:
                    legcb = 'dBm'
                else:
                    lgdcb = 'mW'
                if polar=='o':
                    V = self.CmWo
                if polar=='p':
                    V = self.CmWp

            if typ=='loss':
                title = title + 'Loss : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar=='o':
                    V = self.Lwo*self.freespace
                if polar=='p':
                    V = self.Lwp*self.freespace

            if a == -1:
                V = np.max(V[f,:,:],axis=1)
            else:
                V = V[f,:,a]

            # reshaping the data on the grid
            if self.mode!='file':
                U = V.reshape((self.nx,self.ny)).T
            else:
                U = V

            if dB:
                U = 10*np.log10(U)

            if 'vmin' in kwargs:
                vmin = kwargs['vmin']
            else:
                vmin = U.min()

            if 'vmax' in kwargs:
                vmax = kwargs['vmax']
            else:
                vmax = U.max()

            if self.mode!='file':
                img = ax.imshow(U,
                            extent=(l,r,b,t),
                            origin='lower',
                            vmin = vmin,
                            vmax = vmax,
                            cmap = kwargs['cmap'])
            else:
                img=ax.scatter(self.grid[:,0],self.grid[:,1],c=U,s=20,linewidth=0,cmap=kwargs['cmap'])

            for k in range(self.na):
                ax.annotate(str(k),xy=(self.pa[0,k],self.pa[1,k]))
            ax.set_title(title)

            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            clb = fig.colorbar(img,cax)
            clb.set_label(legcb)
            if best:
                if self.mode<>'file':
                    if polar=='o':
                        ax.contour(np.sum(self.bestsvo,axis=2)[f,:].reshape(self.nx,self.ny).T,extent=(l,r,b,t),linestyles='dotted')
                    if polar=='p':
                        ax.contour(np.sum(self.bestsvp,axis=2)[f,:].reshape(self.nx,self.ny).T,extent=(l,r,b,t),linestyles='dotted')

        # display access points
        if a==-1:
            ax.scatter(self.pa[0,:],self.pa[1,:],s=30,c='r',linewidth=0)
        else:
            ax.scatter(self.pa[0,a],self.pa[1,a],s=30,c='r',linewidth=0)
        plt.tight_layout()
        return(fig,ax)
예제 #4
0
    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)
예제 #5
0
    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()
예제 #6
0
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.showG('i',en=11)
#Ga = L.buildGr()
#L.showGs()
#nx.draw(Ga,Ga.pos)
예제 #7
0
class Simul(PyLayers):
    """ Simulation Class

    Methods
    -------

    gui()
        graphical user interface
    choose()
        choose a simulation file in simuldir
    info()
        info about the simulation
    showray(itx,irx,iray)
        show a single ray
    help()
        help on using Simulation object
    freq()
        return the frequency base
    save()
        save Simulation file
    layout
        load a Layout file
    load()
        load Simulation
    show3()
        geomview vizualization
    show3l(itx,irx)
        geomview vizualization of link itx irx
    show()
        2D visualization of simulation with furniture
    run(itx,irx)
        run simulation for links (itx,irx)
    cir(itx,irx,store_level=0,alpha=1.0)
        Channel Impulse Response calculation


    Attributes
    ----------

    fileconf

    filetauk
    filetang
    filerang

    tx
    rx

    progress

    indoor
    mat
    sl

    Notes
    ------

    This class group together all the parametrization files of a simulation

    Directory list file :

        fileconf

    Constitutive parameters file :

        fileslab
        filemat

    Ray Tracing parameters files :

        filepalch
        filetra

    Frequency list file :

        filefreq

    """
    def __init__(self, _filesimul='default.ini'):
        self.filesimul = _filesimul
        self.config = ConfigParser.ConfigParser()
        self.config.add_section("files")
        self.config.add_section("frequency")
        self.config.add_section("waveform")
        self.config.add_section("output")

        self.dtang = {}
        self.drang = {}
        self.dtauk = {}
        self.dfield = {}
        self.dcir = {}
        self.output = {}

        #
        # Here was a nasty bug : Rule for the future
        #    "Always precise the key value of the passed argument"
        #
        # Mal nommer les choses, c'est ajouter au malheur du monde ( Albert Camus )
        #
        self.tx = RadioNode(name = '',
                            typ = 'tx',
                            _fileini = 'radiotx.ini',
                            _fileant = 'defant.vsh3',
                            )

        self.rx = RadioNode(name = '',
                            typ = 'rx',
                            _fileini = 'radiorx.ini',
                            _fileant = 'defant.vsh3',
                            )

        self.filefreq = "def.freq"

        self.progress = -1  # simulation not loaded

        self.filetang = []
        self.filerang = []
        self.filetauk = []
        self.filefield = []

        self.fileconf = "project.conf"
        self.cfield = []
        self.fGHz = np.linspace(2, 11, 181, endpoint=True)
        self.wav = wvf.Waveform()
        try:
            self.load(_filesimul)
        except:
            pass


    def gui(self):
        """ gui to modify the simulation file
        """
        simulgui = multenterbox('', 'Simulation file',
                                ('filesimul',
                                 'filestr',
                                 'filefreq',
                                 'filespaTx',
                                 'filespaRx',
                                 'fileantTx'
                                 'fileantRx'),
                                (self.filesimul,
                                 self.filestr,
                                 self.filefreq,
                                 self.filespaTx,
                                 self.filespaRx,
                                 self.fileantTx,
                                 self.fileantRx))
        if simulgui is not None:
            self.filesimul = simulgui[0]
            self.filestr = simulgui[1]
            self.filefreq = simulgui[6]
            self.filespaTx = simulgui[7]
            self.filespaRx = simulgui[8]
            self.fileantTx = simulgui[9]
            self.fileantRx = simulgui[10]

    def updcfg(self):
        """ update simulation .ini config file 
        
        with values currently in use.
        """
        self.config.set("files", "struc", self.filestr)
        self.config.set("files", "conf", self.fileconf)
        self.config.set("files", "txant", self.tx.fileant)
        self.config.set("files", "rxant", self.rx.fileant)
        self.config.set("files", "tx", self.tx.fileini)
        self.config.set("files", "rx", self.rx.fileini)
        self.config.set("files", "mat", self.filematini)
        self.config.set("files", "slab", self.fileslabini)

        self.config.set("tud", "purc", str(self.patud.purc))
        self.config.set("tud", "nrmax", str(self.patud.nrmax))
        self.config.set("tud", "num", str(self.patud.num))

        #
        # frequency section
        #

        self.config.set("frequency", "fghzmin", self.fGHz[0])
        self.config.set("frequency", "fghzmax", self.fGHz[-1])
        self.config.set("frequency", "nf", str(len(self.fGHz)))
        #
        # waveform section
        #
        self.config.set("waveform", "tw", str(self.wav['twns']))
        self.config.set("waveform", "band", str(self.wav['bandGHz']))
        self.config.set("waveform", "fc", str(self.wav['fcGHz']))
        self.config.set("waveform", "thresh", str(self.wav['threshdB']))
        self.config.set("waveform", "type", str(self.wav['typ']))
        self.config.set("waveform", "fe", str(self.wav['feGHz']))
        #
        # output section
        #
        for k in self.output.keys():
            self.config.set("output",str(k),self.dout[k])

        # Initialize waveform
        self.wav = wvf.Waveform()
        # Update waveform 
        self.wav.read(self.config)
        self.save()

    def clean(self, level=1):
        """ clean

       Notes
       -----
       obsolete

        Parameters
        ----------
            level  = 1


        """
        if level > 0:
            for itx in range(self.tx.N):
                filename = pyu.getlong(self.filelch[itx], pstruc['DIRLCH'])
                print filename
        if level > 1:
            for itx in range(self.tx.N):
                for irx in range(self.rx.N):
                    filename = pyu.getlong(self.filetra[itx][irx],
                                           pstruc(['DIRTRA']))
                    print filename
        if level > 2:
            for itx in range(self.tx.N):
                for irx in range(self.rx.N):
                    filename = pyu.getlong(self.filetud[itx][irx], pstruc['DIRTUD'])
                    print filename
                    filename = pyu.getlong(self.filetauk[itx][irx],pstruc['DIRTUD'])
                    print filename
        if level > 3:
            for itx in range(self.tx.N):
                for irx in range(self.rx.N):
                    filename = pyu.getlong(self.filetang[itx][irx], pstruc['DIRTUD'])
                    print filename
                    filename = pyu.getlong(self.filerang[itx][irx], pstruc['DIRTUD'])
                    print filename
                    filename = pyu.getlong(self.filefield[itx][irx], pstruc['DIRTUD'])
                    print filename


    def clean_project(self,verbose= True):
        """
        Clean Pyrpoject directory

        remove .lch, .tra, .field .tud, .tauk, .tang, .rang, <pyproject>/output

        remove [output] entries into .ini of self.filesimul


        Parameters
        ----------
 
        verbose : boolean
            Verbose mode on/off


        Returns
        -------
            Boolean:
                True if the project has been cleaned, False otherwise


        """

        if verbose:

            print "-----------------------------------"
            print "-----------------------------------"
            print "          WARNING                  "
            print "-----------------------------------"
            print "-----------------------------------"
            print "You are about to remove ALL previous computed raytracing files."
            print "If you decide to remove it, you will need to restart the entire \
    raytracing simulation to exploit simulation results"
            print "\n Do you want to remove these simulation files ? y/n"
            r=raw_input()

        else :
            r =='y'

        if r == 'y':
            inifile=self.filesimul
            try:
                path=os.getenv('BASENAME')
            except:
                print('Error : there is no project  directory in $BASENAME')



            dirlist=['output']
            extension=['.lch','.field','.tra','.tud','.tang','.rang','.tauk']
            rindic=False


            # remove file

            for d in dirlist:
                for ex in extension:
                    files = os.listdir(path +'/' +d )
                    for f in files:
                        if not os.path.isdir(path+'/'+d+'/'+f) and ex in f:
                            rindic=True
                            if verbose:
                                print f
                            os.remove(path+'/'+d+'/'+f)



                    if rindic:
                        if verbose:
                            print 'removed *' + ex +' from ' +d +'\n'
                        rindic=False


            # remove output into the self.filesimul ini file

            simcfg = ConfigParser.ConfigParser()
            simcfg.read(pyu.getlong(inifile,pstruc['DIRSIMUL']))
            simcfg.remove_section('output')
            f=open(pyu.getlong(inifile,pstruc['DIRSIMUL']),'wb')
            simcfg.write(f)
            f.close()
            self.dout = {}
            self.dlch = {}
            self.dtra = {}
            self.dtud = {}
            self.dtang = {}
            self.drang = {}
            self.dtauk = {}
            self.dfield = {}
            self.dcir = {}
            self.output = {}

            if verbose:
                print 'removed [output] entries into ' +inifile +'\n'
                print 'Project CLEANED'
            return True
        else :
            if verbose:
                print "clean project process ABORTED"
            return False


    def save(self):
        """ save simulation file

        Simulation files are .ini files which are saved in a dedicated
        directory basename/ini in the Project tree

        """
        filesimul = pyu.getlong(self.filesimul, "ini")
        fd = open(filesimul, "w")
        # getting current spa file if any
        try:
            self.config.set("files", "tx", self.tx.fileini)
        except:
            pass
        try:
            self.config.set("files", "rx", self.rx.fileini)
        except:
            pass
        self.config.write(fd)
        fd.close()
        # save tx
        self.tx.save()
        # save rx
        self.rx.save()
        # save slab and mat file
        # --
        # self.slab.save(self.fileslabini)
        # self.slab.mat.save(self.filematini)
        # --
        # fix bug #189
        #   slab is a member of S.L not of S anymore
        #   mat is a member of S.L.sl not of S.slab
        try:
            self.L.sl.save(self.fileslabini)
        except:
            pass
        try:
            self.L.sl.mat.save(self.filematini)
        except:
            pass

#    def saveold(self):
#        """ save simulation file

#        """
#        filesimul = pyu.getlong(self.filesimul, "ini")
#        fd = open(filesimul, "w")
#        config = ConfigParser.ConfigParser()

#        #
#        # files section
#        #
#        #config.add_section("files")
#        self.config.set("files", "conf", self.fileconf)
#        self.config.set("files", "struc", self.filestr)
#        self.config.set("files", "slab", self.fileslab)
#        self.config.set("files", "mat", self.filemat)

#        try:
#            self.config.set("files", "tx", self.tx.filespa)
#        except:
#            pass
#        try:
#            self.config.set("files", "rx", self.rx.filespa)
#        except:
#            pass
#        try:
#            self.config.set("files", "txant", self.tx.fileant)
#        except:
#            pass
#        try:
#            self.config.set("files", "rxant", self.rx.fileant)
#        except:
#            pass
#        self.config.set("files", "patra", self.filepatra)
#        self.config.set("files", "palch", self.filepalch)
#        self.palch.save()
#        self.patra.save()

#        #
#        # tud section
#        #

#        self.config.set("tud", "purc", self.patud.purc)
#        self.config.set("tud", "nrmax", self.patud.nrmax)
#        self.config.set("tud", "num", self.patud.num)

#        #
#        # frequency section
#        #
#        self.config.set("frequency", "fghzmin", self.freq[0])
#        self.config.set("frequency", "fghzmax", self.freq[-1])
#        self.config.set("frequency", "Nf", len(self.freq))

#        #
#        # output section
#        #
#        #filelch exists
#        if self.progress > 0:
#            #config.add_section("output")
#            for k in range(len(self.filelch)):
#                _fileout = "out" + "???"
#                filename = self.filelch[k]
#                self.config.set("launch", str(k + 1), filename)

#        # filetra exists
#        for k in range(len(self.filelch)):
#            if self.progress > 1:
#                #self.config.add_section("trace")
#                for l in arange(len(self.filetra[k])):
#                    filename = self.filetra[k][l]
#                    self.config.set("trace", "rx" + str(l + 1), filename)

#        # .tang exists
#        # .rang exists
#        # .tud exists
#            if self.progress > 2:
#                #config.add_section("tud")
#                #config.add_section("tang")
#                #config.add_section("rang")

#                for l in arange(len(self.filetud[k])):
#                    ftud = self.filetud[k][l]
#                    self.config.set("tud", "rx" + str(l + 1), ftud)

#                for l in arange(len(self.filetang[k])):
#                    ftang = self.filetang[k][l]
#                    self.config.set("tang", "rx" + str(l + 1), ftang)

#                for l in arange(len(self.filerang[k])):
#                    frang = self.filerang[k][l]
#                    self.config.set("rang", "rx" + str(l + 1), frang)

#        # .field exist
#        # .tauk exist
#            if self.progress > 3:
#                #config.add_section("tauk")
#                #config.add_section("field")
#                for l in arange(len(self.filetud[k])):
#                    ftauk = self.filetud[k][l]
#                    self.config.set("tauk", "rx" + str(l + 1), ftauk)

#                for l in arange(len(self.filefield[k])):
#                    ffield = self.filefield[k][l]
#                    self.config.set("field", "rx" + str(l + 1), ffield)

#        self.config.write(fd)
#        fd.close()

    def save_project(self):
        """ save Simulation files in a zipfile

        Simulation files are .ini files which are saved in a dedicated
        directory basename/ini in the Project tree

        """
        root = Tkinter.Tk()
        zipfileName = tkFileDialog.asksaveasfilename(parent=root,
                            filetypes = [("zipped file","zip")] ,
                            title="Save Project",
                            )
        pyu.zipd(basename,zipfileName)
        root.withdraw()
        print "Current project saved in", zipfileName

    def load_project(self):
        """ load Simulation files from a zipfile

        Simulation files are .ini files which are saved in a dedicated
        directory basename/ini in the Project tree

        """
        root = Tkinter.Tk()
        zipfileName= tkFileDialog.askopenfile(parent=root,
                                            mode='rb',
                                            title='Choose a project')
        dirname = tkFileDialog.askdirectory(parent=root,
                                    initialdir=basename,
                                    title='Please select a directory',
                                    mustexist=0)
        pyu.unzipd(dirname,zipfileName)
        root.withdraw()
        print "Current project loaded in", dirname

    def choose(self):
        """
            Choose a simulation file in simuldir

        """
        import tkFileDialog as FD
        fichsimul = FD.askopenfilename(filetypes=[("Fichiers simul ",
                                                   "*.simul"),
                                                  ("All", "*")],
                                       title="Please choose a simulation file",
                                       initialdir=simuldir)
        self.filesimul = pyu.getshort(fichsimul)
        self.load()

    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:
            _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,
                                _filestr = self.filestr)

            self.rx = RadioNode(name = '',
                                typ = 'rx',
                                _fileini = _filerx,
                                _fileant = _fileantrx,
                                _filestr = self.filestr)
        except:
            raise NameError('Error during Radionode load')
#
# Load Layout
# 
        try:
            self.L = Layout(self.filestr)
        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 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 show(self, itx=[-1], irx=[-1], furniture=True, s=8, c='b', traj=False, num=False,fig=[],ax=[]):
        """ show simulation

            Parameters
            -----------
            itx        : list of tx indices
            irx        : list of rx indices
            furniture  : boolean for METALIC furniture display
            s          : scale fir scatter plot  (default 8)
            c          : color for scatter plot  (default 'b')
            traj       : boolean  (def False)
            num        : boolean  (def False)
                display a number


            Examples
            --------
            >>> import matplotlib.pyplot as plt
            >>> from pylayers.simul.simulem import *
            >>> S = Simul()
            >>> S.load('w1.ini')
            >>> S.L.loadfur('FurW1.ini')
            >>> S.show()
            >>> plt.show()



        """
        if type(itx) == int:
            itx = [itx]
        if type(irx) == int:
            irx = [irx]


        if fig ==[]:
            fig = plt.gcf()
        if ax==[]:
            ax = fig.gca()

        #self.L.display['scaled']=False
        fig,ax=self.L.showG('s',fig=fig,ax=ax, aw=True)
        #
        if furniture:
            if 'lfur' in self.L.__dict__:
                for fur in self.L.lfur:
                    if fur.Matname == 'METAL':
                        fur.show(fig, ax)
            else:
                print "Warning : no furniture file loaded"

        if irx[0] == -1:
            ax.scatter(self.rx.position[0,:],
                       self.rx.position[1,:], c='b', s=s, alpha=0.5)
            #ax.scatter(self.rx.position[0,0],self.rx.position[0,1],c='k',s=s,linewidth=0)
            #ax.scatter(self.rx.position[1,0],self.rx.position[1,1],c='b',s=s,linewidth=0)
            #ax.scatter(self.rx.position[2,0],self.rx.position[2,1],c='g',s=s,linewidth=0)
            #ax.scatter(self.rx.position[3,0],self.rx.position[3,1],c='c',s=s,linewidth=0)
        else:
            for k in irx:
                ax.scatter(self.rx.position[0,k - 1],
                           self.rx.position[1,k - 1], c='b', s=s, alpha=0.5)
                if num:
                    ax.text(self.rx.position[0,k - 1],
                            self.rx.position[1,k - 1],
                            str(k), color='blue')

        if itx[0] == -1:
            ax.scatter(self.tx.position[0,:],
                       self.tx.position[1,:], c='r', s=s)
        else:
            if traj:
                cpt = 1
            for k in itx:
                ax.scatter(self.tx.position[0,k - 1],
                           self.tx.position[1,k - 1],
                           c=c, s=s, linewidth=0)
                if num:
                    if traj:
                        ax.text(self.tx.position[0,k - 1],
                                self.tx.position[1,k - 1],
                                str(cpt), color='black')
                        cpt = cpt + 1
                    else:
                        ax.text(self.tx.position[0,k - 1],
                                self.tx.position[1,k - 1],
                                str(k), color='black')

        return (fig,ax)
        #for k in range(self.tx.N):
        #    ax.text(self.tx.position[0,k],self.tx.position[1,k],str(k+1),color='black')
        #    ax.scatter(self.tx.position[0,:],self.tx.position[0,:],

        #for k in range(self.rx.N):
        #   ax.text(self.rx.position[0,k],self.rx.position[1,k],str(k),color='black')

    def PL(self, itx):
        """ plot Path Loss

        itx
        """
        td = []
        tEa = []
        tEo = []
        for irx in self.dcir[itx].keys():
            d = self.delay(itx, irx) * 0.3
            cira, ciro = self.loadcir(itx, irx)

            td.append(d)
            tEa.append(Ea)
            tEo.append(Eo)

        plt.semilogx(td, 10 * np.log10(tEa), 'xr')
        plt.semilogx(td, 10 * np.log10(tEo), 'xb')
        plt.show()
        return td, tEa, tEo

    def evalcir(self,cutoff=4,algo='new'):
        """
        Parameters
        ----------

        S
        tx
        rx
        wav
        cutoff

        """

        crxp =-1
        ctxp =-1
        tcir = {}
        tx = self.tx.position
        Ntx = len(tx[0])
        rx = self.rx.position
        Nrx = len(rx[0])

        #for kt in range(1,Ntx-1):
        #print kt+1
        kt=0
        tcir[kt] = {}
        t = np.array([self.tx.position[0,kt],self.tx.position[1,kt],self.tx.position[2,kt]])
        for kr in range(Nrx):
            if (np.mod(kr,10)==0):
                print kr+1
            r = np.array([self.rx.position[0,kr],self.rx.position[1,kr],self.rx.position[2,kr]])
            ctx = self.L.pt2cy(t)
            crx = self.L.pt2cy(r)
            if (ctx<>ctxp)|(crx<>crxp):
                Si  = signature.Signatures(self.L,ctx,crx)
                ctxp = ctx
                crxp = crx
                Si.run4(cutoff=cutoff,algo=algo)
            r2d = Si.rays(t,r)
            #r2d.show(S.L)

            r3d = r2d.to3D(self.L)
            r3d.locbas(self.L)
            r3d.fillinter(self.L)
            Ct  = r3d.eval(self.fGHz)
            sca = Ct.prop2tran(self.tx.A,self.rx.A)
            cir = sca.applywavB(self.wav.sfg)
            tcir[kt][kr] = cir
        return(tcir)

    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 pltcir(self, itx=1, irx=1, mode='linear', noise=False, color='b',format='a',fig=[],ax=[]):
        """ plot Channel Impulse Response

        Parameters
        ----------

        itx : Tx index
        irx : Rx index
        mode : str
            {'linear','dB'}
            noise : boolean
        color : string
            default 'b'

        >>> from pylayers.simul.simulem import *
        >>> S = Simul()
        >>> S.load('where2.ini')
        >>> S.run(1,1)
        >>> S.pltcir(1,1,mode='linear',noise=False,color='k')

        """

        if fig ==[]:
            fig = plt.gcf()
        #if ax==[]:
        #    ax = fig.gca()

        _filecir = self.dcir[itx][irx] + '.mat'
        filecir = pyu.getlong(_filecir, pstruc['DIRCIR']+'/Tx' + str('%0.3d' % itx))
        D = spio.loadmat(filecir)
        ax = fig.add_subplot('211')

        fig,ax=self.show(itx, irx,fig=fig,ax=ax)
        ax=fig.add_subplot('212')
        if 'a' in format :
            kxa = 't'
            kya = 'cir'
            ta = D[kxa]
            Tobs = ta[-1] - ta[0]
            te = ta[1] - ta[0]
            if noise:
                na = bs.Noise(Tobs + te, 1. / te)
                naf = na.gating(4.493, 0.5)
            cira = bs.TUsignal(ta, D[kya][:, 0])


        if 'o' in format:
            kxo = 'to' + str(irx)
            kyo = 'ciro' + str(irx)
            to = D[kxo]
            Tobs = to[-1] - to[0]
            te = to[1] - to[0]
            if noise:
                no = bs.Noise(Tobs + te, 1. / te)
                nof = no.gating(4.493, 0.5)
            ciro = bs.TUsignal(to, D[kyo][:, 0])

        if mode == 'linear':
            #plt.plot(ta,naf.y,color='k',label='Noise')
            plt.plot(ta, D[kya], label='Rx ' + str(irx), color=color)
            plt.xlabel('Time (ns)')

            '''if noise:
                naf.plot(col='k')
            cira.plot(col=color)'''
        else:
            '''if noise:
                naf.plotdB(col='k')
            cira.plotdB()'''
            plt.plot(ta, 20 * np.log10(abs(D[kya])), label='Rx ' + str(irx), color=color)
            plt.xlabel('Time (ns)')
#        plt.legend()
        plt.show()
        #plt.savefig('Tx'+str(itx),format=pdf,dpi=300)

    def scatter(self, itx, irx, values,
                cmap=plt.cm.gray,
                s=30,
                spl=221,
                title='',
                vaxis=((-30, 10, 2, 18)),
                vmin=0,
                vmax=1,
                colbool=False,
                cblabel='dB'):
        """
            Parameters
            ----------

            itx
            irx
            values
            cmap
            s
            spl
            title
            vaxis
            vmin
            vmax
            colbool
            clabel

        """
        fig = plt.gcf()
        ax = fig.add_subplot(spl)
        xtx = self.tx.position[itx, 0]
        ytx = self.tx.position[itx, 1]
        xrx = self.rx.position[irx, 0]
        yrx = self.rx.position[irx, 1]
        self.L.display['title'] = title
        self.L.showGs(ax)
        for furk in siradel.siradel_furniture.keys():
            fur = siradel.siradel_furniture[furk]
            if fur.Matname == 'METAL':
                fur.show(fig, ax)

        #self.show(furniture=True)
        plt.axis(vaxis)
        b1 = ax.scatter(xtx, ytx, s=s, c=values, cmap=cmap,
                        linewidths=0, vmin=vmin, vmax=vmax)
        ax.scatter(xrx, yrx, s=30, c='b', linewidths=0)
        if colbool:
            cb = colorbar(b1)
            cb.set_label(cblabel, fontsize=14)
        return(b1)

    def info(self, itx=[], irx=[]):
        """ display simulation information

         Parameters
         ----------
         itx : Tx index
         irx : Rx index

        """
        print self.filesimul
        print '------------------------------------------'
        try:
            print "Layout Info : \n", self.L.info()
        except:
            print "provide a Layout in the simulation : S.L "
            print ">>> S.layout(filename.str) "
            print "or "
            print ">>> S.layout(filename.str2 "
            print "or "
            print ">>> S.layout(filename.str,filematini,filematini) "
            print "default files exists for filematini and fileslabini "

            return
        try:
            print "Tx Info :\n", self.tx.info()
        except:
            print "provide a tx in the simulation : S.tx "
            return
        try:
            print "Rx Info :\n", self.rx.info()
        except:
            print "provide a rx in the simulation : S.rx "
            return

        #    print "Tx : ",self.tx.points[itx]
            print "Rx : ", self.rx.points[itx]
            print "Delay (ns) :", self.delay(itx, irx)
            print "Distance (m) :", 0.3 / self.delay(itx, irx)
            print ""
            if itx in self.dlch.keys():
                print "-----"
                print "Launching "
                print "-----"
                print " ", self.dlch[itx]
            if irx in self.dtra[itx].keys():
                print "-----"
                print "Tracing "
                print "-----"
                print " ", self.dtra[itx][irx]
                gr = GrRay3D()
                gr.load(self.dtra[itx][irx], self.L)
                gr.info()
            if irx in self.dtud[itx].keys():
                print "-----"
                print "Tud parameters "
                print "-----"
                print " ", self.dtud[itx][irx]
                print " ", self.dtang[itx][irx]
                print " ", self.drang[itx][irx]
                gt = GrRay3D.GrRayTud()
                gt.load(self.dtud[itx][irx],
                        self.dtang[itx][irx],
                        self.drang[itx][irx], self.sl)
            if irx in self.dtauk[itx].keys():
                print self.dtauk[itx][irx]
                print self.dfield[itx][irx]
                VC = self.VC(itx, irx)
            if irx in self.dcir[itx].keys():
                print self.dcir[itx][irx]

    def info2(self):
        for i, j in enumerate(self.__dict__.keys()):
            print j, ':', self.__dict__.values()[i]

    def filtray(self, itx, irx, tau0, tau1, col='b'):
        """ filter rays

        Parameters
        ----------
        itx :
        irx :
        tau0 :
        tau1 :
        col :

        Display ray and nstr
        """
        gr = GrRay3D()
        gr.load(self.dtra[itx][irx], self.L)
        self.L.display['Thin'] = True
        self.L.display['Node'] = False
        self.L.display['NodeNum'] = False
        self.L.display['EdgeNum'] = False
        plt.axis('scaled')
        #self.L.show(fig,ax,nodelist,seglist)
        self.L.showGs()
        delays = gr.delay()
        rayset = np.nonzero((delays >= tau0) & (delays <= tau1))[0]
        fig = plt.gcf()
        ax = fig.get_axes()[0]
        gr.show(ax, rayset, col=col, node=False)
        plt.title('Tx' + str(itx) + '-Rx' + str(irx) + ' : ' + str(
            tau0) + ' < tau < ' + str(tau1))

    def showray(self, itx, irx, iray=np.array([]), fig=[], ax=[]):
        """ show layout and rays for a radio link

        Parameters
        ----------
        itx  : tx index
        irx  : rx index
        iray : list of rays to be displayed ndarray


        """

        #if ax==[]:
        #    fig = plt.figure()
        #    ax  = fig.add_subplot('111')

        gr = GrRay3D()
        gr.load(self.dtra[itx][irx], self.L)
        if len(iray == 1):
            ray = gr.ray3d[iray[0]]
            nstr = ray.nstr[1:-1]
            uneg = np.nonzero(nstr < 0)
            upos = np.nonzero((nstr > 0) & (nstr <= self.L.Ne))
            uceil = np.nonzero(nstr == self.L.Ne + 1)
            ufloor = np.nonzero(nstr == self.L.Ne + 2)
        #seglist  = nstr[upos[0]]-1
        #nodelist = -nstr[uneg[0]]-1
        #seglist2 = S.L.segpt(nodelist)
        self.L.display['Thin'] = True
        self.L.display['Node'] = False
        self.L.display['NodeNum'] = False
        self.L.display['EdgeNum'] = False
        #self.L.show(fig,ax)
        #print ray.nn
        #print len(ray.nstr)
        #print ray.nstr
        #print nodelist
        #print seglist
        #print seglist2
        #seglist = hstack((seglist,seglist2))
        self.L.display['Node'] = False
        self.L.display['Thin'] = False
        self.L.display['NodeNum'] = True
        self.L.display['EdgeNum'] = True
        plt.axis('scaled')
        #self.L.show(fig,ax,nodelist,seglist)
        fig, ax = self.L.showGs(show=False)
        gr.show(ax, iray, col='b', node=False)

        if len(iray) == 1:
            plt.title(str(nstr))
        else:
            plt.title('Tx' + str(itx) + '-Rx' + str(irx) +
                      ' ' + str(min(iray)) + ' ' + str(max(iray)))

    def show3l(self, itx, irx):
        """ geomview display of a specific link

        g = S.show3l(itx,irx)

        Parameters
        ----------
        itx
            transmitter index
        irx
            receiver index

        """
        filetra = self.dtra[itx][irx]
        gr = GrRay3D()
        gr.load(filetra, self.L)
        gr.show3()

        return(gr)

    def _show3(self,rays=[],newfig = False,**kwargs):
        """ display of the simulation configuration
            using Mayavi

        Parameters
        ----------

        rays: Ray3d object :
            display the rays of the simulation
        newfig : boolean (default : False)
        kwargs of Rays.show3()


        see also
        --------

        pylayers.gis.layout
        pylayers.antprop.antenna
        pylayers.antprop.rays

        """
        Atx = self.tx.A
        Arx = self.rx.A
        Ttx = self.tx.orientation
        Trx = self.rx.orientation
        ptx = self.tx.position
        prx = self.rx.position

        self.L._show3(newfig=False,opacity=0.7)
        Atx._show3(T=Ttx.reshape(3,3),po=ptx,
            title=False,colorbar=False,newfig=False)
        Arx._show3(T=Trx.reshape(3,3),po=prx,
            title=False,colorbar=False,newfig=False)
        if rays != []:
            rays._show3(**kwargs)



    def show3(self,rays=[],**kwargs):
        """ geomview display of the simulation configuration

        Parameters
        ----------

        centered : boolean
            center the scene if True
        bdis  : boolean
            display local basis

        """
        try:
            self.tx.save()
        except:
            print('tx set is no defined')
        try:
            self.rx.save()
        except:
            print('rx set is no defined')
        _filename = self.filesimul.replace('.ini', '.off')
        filename = pyu.getlong(_filename, pstruc['DIRGEOM'])
        fo = open(filename, "w")
        fo.write("LIST\n")
        try:
            sttx = "{<" + self.tx.filegeom + "}\n"
        except:
            sttx = "\n"
        try:
            strx = "{<" + self.rx.filegeom + "}\n"
        except:
            strx = "\n"
        try:
            stst = "{<" + self.L.filegeom + "}\n"
        except:
            stst = "\n"
        fo.write(sttx)
        fo.write(strx)
        fo.write(stst)
        fo.write("{</usr/share/geomview/geom/xyz.vect}\n")
        if rays !=[]:
            kwargs['bdis']=False
            kwargs['L']=self.L
            kwargs['centered']=False
            fo.write("{<" + rays.show3(**kwargs) + "}")

        fo.close()


        command = "geomview -nopanel -b 1 1 1 " + filename + " 2>/dev/null &"
        os.system(command)

    def run(self, link, cirforce=True,verbose=False,cutoff=4):
        """ run the simulation for 1 tx and a set of rx

            Parameters
            ----------

            itx      : tx index
            srx      : list of rx index
            cirforce : boolean

            Warnings
            --------

            index point start with 1

            Example
            -------

            >>> from pylayers.simul.simulem import *
            >>> itx = 1
            >>> srx = [1,2,3]
            >>> S   = Simul()
            >>> S.load('where2.ini')
            >>> out = S.run(itx,srx)


        """
        
        # get file prefix

        link = DLink(force=True,L=self.L,fGHz=self.fGHz, verbose=False)
        prefix = self.filesimul.replace('.ini', '') 
        lsig = []
        for k,il in enumerate(link):
            tx = self.tx.points[il[0]]
            rx = self.rx.points[il[1]]
            ctx = S.L.pt2cy(tx)
            crx = S.L.pt2cy(rx)
            _filecir = prefix +'-cir-'+str(k)+'-'+str(link)+'-'+str((ctx,crx))
            D = {}
            D['Tx'] = tx
            D['Rx'] = rx

            
            link.a = tx
            link.b = rx
            ak,tauk = link.eval(verbose=False,diffrction=True)
            if (ctx,crx) not in lsig:
                Si  = signature.Signatures(S.L,ctx,crx)
                #
                # Change the run number depending on
                # the algorithm used for signature determination
                #
                Si.run4(cutoff=cutoff)
                # keep track and save signature
                _filesir = prefix + '-sig-'+str((ctx,crx))
                fd = open(filesig,'w')
                pickle.dump(Si,filesig)
                fd.close()
                lsig.appeng((ctx,crx))
                Si.dump(S.L,(ctx,crx))



            r2d = Si.rays(tx,rx)
            r2d.show(S.L)
    
            r3d = r2d.to3D()
            r3d.locbas(S.L)
            r3d.fillinter(S.L)

            Ct  = r3d.eval(S.freq)
            sco = Ct.prop2tran(a='theta',b='phi')
            sca = Ct.prop2tran(a=S.tx.A,b=S.rx.A)

            ciro = sco.applywavB(self.wav.sfg)
            cira = sca.applywavB(self.wav.sfg)

            D['to'] = ciro.x
            D['ciro'] = ciro.y
            D['t'] = cira.x
            D['cir'] = cira.y

            filename = pyu.getlong(_filename, cirdir)
            spio.savemat(filename, D)
            
    def delay(self, itx, irx):
        """ calculate LOS link delay

            Parameters
            ----------

            itx
            irx

            Returns
            -------

            delay : float 
                delay in ns

        """
        tx = self.tx.points[itx]
        rx = self.rx.points[irx]
        df = tx - rx
        dist = np.sqrt(np.dot(df, df))
        return(dist / 0.3)
예제 #8
0
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 
ax2 = fig.add_subplot(323)
L.showG(fig=fig,ax=ax2,graph='t')
plt.title('Topological graph')
#plt.savefig('graphGt.png')
# build graph of rooms
ax3 = fig.add_subplot(324)
L.showG(fig=fig,ax=ax3,graph='r')
#plt.savefig('graphGr.png')
예제 #9
0
import matplotlib.pyplot as plt
import warnings
import shutil

warnings.filterwarnings("error")

#doctest.testmod(layout)
#L = Layout('TA-Office.ini')
L =  Layout()
lL = L.ls()
for tL in lL:
    print  'Layout :     ',tL
    print  '--------------------------'
    if 'Munich' not in tL:
        L = Layout(tL,bbuild=0,bgraphs=0)
        f,a = L.showG('s')
        plt.title(tL,fontsize=32)
        plt.show()
        plt.close('all')
    #if L.check():
    #    L.save()
        #filein = pyu.getlong(L._filename, pstruc['DIRLAY'])
        #fileout = '/home/uguen/Documents/rch/devel/pylayers/data/struc/lay/'+L._filename
        #print fileout
        #shutil.copy2(filein,fileout)
#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')
예제 #10
0
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')
#plt.savefig('graphGs.png')
#build topological graph 
ax2 = fig.add_subplot(323)
L.showG(fig=fig,ax=ax2,graph='t')
plt.title('Topological graph')
예제 #11
0
class Coverage(PyLayers):
    """ Handle Layout Coverage
        Methods
        -------
        creategrid()
            create a uniform grid for evaluating losses
        cover()
            run the coverage calculation
        showPower()
            display the map of received power
        showLoss()
            display the map of losses
        Attributes
        ----------
        All attributes are read from fileini ino the ini directory of the
        current project
        _fileini
            default coverage.ini
        L     : a Layout
        nx    : number of point on x
        ny    : number of point on y
        tx    : transmitter position
        txpe  : transmitter power emmission level
        show  : boolean for automatic display power map
        na : number of access point
    """
    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
        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'])
        self.PtDB = eval(self.rxopt['ptdb'])
        self.Gt = eval(self.rxopt['gt'])
        self.Gr = eval(self.rxopt['gr'])
        self.do = eval(self.rxopt['do'])
        self.Prdo = eval(self.rxopt['prdo'])
        self.n = eval(self.rxopt['n'])
        self.desviopadrao = eval(self.rxopt['desviopadrao'])
        self.x0 = eval(self.rxopt['x0'])
        self.y0 = eval(self.rxopt['y0'])
        self.xt = eval(self.rxopt['xt'])
        self.yt = eval(self.rxopt['yt'])

        # show section
        self.bshow = str2bool(self.showopt['show'])

    def __repr__(self):
        st = ''
        if self.typ == 'indoor':
            st = st + 'Layout file : ' + self.L._filename + '\n\n'
            st = st + '-----list of Access Points ------' + '\n'
            for k in self.dap:
                st = st + self.dap[k].__repr__() + '\n'
            st = st + '-----Rx------' + '\n'
            st = st + 'temperature (K) : ' + str(self.temperaturek) + '\n'
            st = st + 'noisefactor (dB) : ' + str(self.noisefactordb) + '\n\n'
            st = st + '--- Grid ----' + '\n'
            st = st + 'mode : ' + str(self.mode) + '\n'
            if self.mode <> 'file':
                st = st + 'nx : ' + str(self.nx) + '\n'
                st = st + 'ny : ' + str(self.ny) + '\n'
            if self.mode == 'zone':
                st = st + 'boundary (xmin,ymin,xmax,ymax) : ' + str(
                    self.boundary) + '\n\n'
            if self.mode == 'file':
                st = st + ' filename : ' + self.filespa + '\n'
        return (st)

    def creategrid(self, mode='full', boundary=[], _fileini=''):
        """ create a grid
        Parameters
        ----------
        full : boolean
            default (True) use all the layout area
        boundary : (xmin,ymin,xmax,ymax)
            if full is False the boundary argument is used
        """

        if mode == "file":
            self.RN = RadioNode(name='',
                                typ='rx',
                                _fileini=_fileini,
                                _fileant='def.vsh3')
            self.grid = self.RN.position[0:2, :].T
        else:
            if mode == "full":
                mi = np.min(self.L.Gs.pos.values(), axis=0) + 0.01
                ma = np.max(self.L.Gs.pos.values(), axis=0) - 0.01
            if mode == "zone":
                assert boundary <> []
                mi = np.array([boundary[0], boundary[1]])
                ma = np.array([boundary[2], boundary[3]])

            x = np.linspace(mi[0], ma[0], self.nx)
            y = np.linspace(mi[1], ma[1], self.ny)

            self.grid = np.array((list(np.broadcast(*np.ix_(x, y)))))

        self.ng = self.grid.shape[0]

    def where1(self):
        """
        Unfinished : Not sure this is the right place (too specific)
        """
        M1 = UWBMeasure(1)
        self.dap = {}
        self.dap[1] = {}
        self.dap[2] = {}
        self.dap[3] = {}
        self.dap[4] = {}
        self.dap[1]['p'] = M1.rx[1, 0:2]
        self.dap[2]['p'] = M1.rx[1, 0:2]
        self.dap[3]['p'] = M1.rx[1, 0:2]
        self.dap[4]['p'] = M1.rx[1, 0:2]
        for k in range(300):
            try:
                M = UWBMeasure(k)
                tx = M.tx
                self.grid = np.vstack((self.grid, tx[0:2]))
                D = M.rx - tx[np.newaxis, :]
                D2 = D * D
                dist = np.sqrt(np.sum(D2, axis=1))[1:]
                Emax = M.Emax()
                Etot = M.Etot()[0]
                try:
                    td1 = np.hstack((td1, dist[0]))
                    td2 = np.hstack((td2, dist[1]))
                    td3 = np.hstack((td3, dist[2]))
                    td4 = np.hstack((td4, dist[3]))
                    te1 = np.hstack((te1, Emax[0]))
                    te2 = np.hstack((te2, Emax[1]))
                    te3 = np.hstack((te3, Emax[2]))
                    te4 = np.hstack((te4, Emax[3]))
                    tt1 = np.hstack((tt1, Etot[0]))
                    tt2 = np.hstack((tt2, Etot[1]))
                    tt3 = np.hstack((tt3, Etot[2]))
                    tt4 = np.hstack((tt4, Etot[3]))
                    #tdist = np.hstack((tdist,dist))
                    #te = np.hstack((te,Emax))
                except:
                    td1 = np.array(dist[0])
                    td2 = np.array(dist[1])
                    td3 = np.array(dist[2])
                    td4 = np.array(dist[3])
                    te1 = np.array(Emax[0])
                    te2 = np.array(Emax[1])
                    te3 = np.array(Emax[2])
                    te4 = np.array(Emax[3])
                    tt1 = np.array(Etot[0])
                    tt2 = np.array(Etot[1])
                    tt3 = np.array(Etot[2])
                    tt4 = np.array(Etot[3])
            except:
                pass

    def cover(self, sinr=True, snr=True, best=True):
        """ run the coverage calculation
        Parameters
        ----------
        sinr : boolean
        snr  : boolean
        best : boolean
        Examples
        --------
        .. plot::
            :include-source:
            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a=C.show(typ='sinr',figsize=(10,8))
            >>> plt.show()
        Notes
        -----
        self.fGHz is an array, it means that Coverage is calculated at once
        for a whole set of frequencies. In practice, it would be the center
        frequency of a given standard channel.
        This function is calling `loss.Losst` which calculates Losses along a
        straight path.
        In a future implementation we will
        abstract the EM solver in order to make use of other calculation
        approaches as a full or partial Ray Tracing.
        The following members variables are evaluated :
        + freespace Loss @ fGHz   PL()  PathLoss (shoud be rename FS as free space) $
        + prdbmo : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{odB}`
        + prdbmp : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{pdB}`
        + snro : SNR polar o (H)
        + snrp : SNR polar p (H)
        See Also
        --------
        pylayers.antprop.loss.Losst
        pylayers.antprop.loss.PL
        """
        #
        # select active AP
        #
        lactiveAP = []
        try:
            del self.aap
            del self.ptdbm
        except:
            pass

        self.kB = 1.3806503e-23  # Boltzmann constant
        #
        # Loop opver access points
        #
        for iap in self.dap:
            if self.dap[iap]['on']:
                lactiveAP.append(iap)
                fGHz = self.dap[iap].s.fcghz
                # The frequency band is set here
                self.fGHz = np.unique(np.hstack((self.fGHz, fGHz)))
                apchan = self.dap[iap]['chan']
                try:
                    self.aap = np.vstack((self.aap, self.dap[iap]['p']))
                    self.ptdbm = np.vstack(
                        (self.ptdbm, self.dap[iap]['PtdBm']))
                    self.bmhz = np.vstack(
                        (self.bmhz, self.dap[iap].s.chan[apchan[0]]['BMHz']))
                except:
                    self.aap = self.dap[iap]['p']
                    self.ptdbm = np.array(self.dap[iap]['PtdBm'])
                    self.bmhz = np.array(
                        self.dap[iap].s.chan[apchan[0]]['BMHz'])

        PnW = np.array((10**(self.noisefactordb / 10.)) * self.kB *
                       self.temperaturek * self.bmhz * 1e6)
        self.pnw = PnW
        # Evaluate Noise Power (in dBm)
        self.pndbm = np.array(10 * np.log10(PnW) + 30)

        #lchan = map(lambda x: self.dap[x]['chan'],lap)
        #apchan = zip(self.dap.keys(),lchan)
        #self.bmhz = np.array(map(lambda x: self.dap[x[0]].s.chan[x[1][0]]['BMHz']*len(x[1]),apchan))

        self.ptdbm = self.ptdbm.T
        self.pndbm = self.pndbm.T
        # creating all links
        # all grid to all ap
        #
        if len(self.pndbm.shape) == 0:
            self.ptdbm = self.ptdbm.reshape(1, 1)
            self.pndbm = self.pndbm.reshape(1, 1)

        p = product(range(self.ng), lactiveAP)
        #
        # pa : access point
        # pg : grid point
        #
        # 1 x na

        for k in p:
            pg = self.grid[k[0], :]
            pa = np.array(self.dap[k[1]]['p'])
            # exemple with 3 AP
            # 321 0
            # 321 1
            # 321 2
            # 322 0
            try:
                self.pa = np.vstack((self.pa, pa))
            except:
                self.pa = pa
            try:
                self.pg = np.vstack((self.pg, pg))
            except:
                self.pg = pg

        self.pa = self.pa.T
        shpa = self.pa.shape
        shpg = self.pg.shape

        if shpa[0] != 3:
            self.pa = np.vstack((self.pa, np.ones(shpa[1])))
        self.pg = self.pg.T
        self.pg = np.vstack((self.pg, self.zgrid * np.ones(shpg[0])))

        self.nf = len(self.fGHz)

        # retrieving dimensions along the 3 axis
        na = len(lactiveAP)
        self.na = na
        ng = self.ng
        nf = self.nf

        for k, iap in enumerate(self.dap):
            # select only one access point
            u = na * np.arange(0, ng, 1).astype('int') + k
            if self.dap[iap]['on']:
                pt = self.pa[:, u]
                pr = self.pg[:, u]
                azoffset = self.dap[iap]['phideg'] * np.pi / 180.
                self.dap[iap].A.eval(fGHz=self.fGHz,
                                     pt=pt,
                                     pr=pr,
                                     azoffset=azoffset)

                gain = (self.dap[iap].A.G).T
                #pdb.set_trace()
                # to handle omnidirectional antenna (nf,1,1)
                if gain.shape[1] == 1:
                    gain = np.repeat(gain, ng, axis=1)
                try:
                    tgain = np.dstack((tgain, gain[:, :, None]))
                except:
                    tgain = gain[:, :, None]

        #Lwo,Lwp,Edo,Edp = loss.Losst(self.L,self.fGHz,self.pa,self.pg,dB=False)
        Lwo, Lwp, Edo, Edp = loss.Losst(self.L,
                                        self.fGHz,
                                        self.pa,
                                        self.pg,
                                        dB=False)

        self.Lwo = Lwo.reshape(nf, ng, na)
        self.Edo = Edo.reshape(nf, ng, na)
        self.Lwp = Lwp.reshape(nf, ng, na)
        self.Edp = Edp.reshape(nf, ng, na)

        freespace = loss.PL(self.fGHz, self.pa, self.pg, dB=False)
        self.freespace = freespace.reshape(nf, ng, na)

        # transmitting power
        # f x g x a

        # CmW : Received Power coverage in mW
        self.CmWo = 10**(self.ptdbm[np.newaxis, ...] /
                         10.) * self.Lwo * self.freespace * tgain
        self.CmWp = 10**(self.ptdbm[np.newaxis, ...] /
                         10.) * self.Lwp * self.freespace * tgain
        if self.typ == 'intensity':
            self.cmWo = 10 * np.log10(self.cmWo)
            self.cmWo = 10 * np.log10(self.cmWp)

        if snr:
            self.evsnr()
        if sinr:
            self.evsinr()
        if best:
            self.evbestsv()

    def evsnr(self):
        """ calculates signal to noise ratio
        """

        NmW = 10**(self.pndbm / 10.)[np.newaxis, :]

        self.snro = self.CmWo / NmW
        self.snrp = self.CmWp / NmW

    def evsinr(self):
        """ calculates sinr
        """

        # na : number of access point
        na = self.na

        # U : 1 x 1 x na x na
        U = (np.ones((na, na)) - np.eye(na))[np.newaxis, np.newaxis, :, :]

        # CmWo : received power in mW orthogonal polarization
        # CmWp : received power in mW parallel polarization

        ImWo = np.einsum('ijkl,ijl->ijk', U, self.CmWo)
        ImWp = np.einsum('ijkl,ijl->ijk', U, self.CmWp)

        NmW = 10**(self.pndbm / 10.)[np.newaxis, :]

        self.sinro = self.CmWo / (ImWo + NmW)
        self.sinrp = self.CmWp / (ImWp + NmW)

    def evbestsv(self):
        """ determine the best server map
        Notes
        -----
        C.bestsv
        """
        na = self.na
        ng = self.ng
        nf = self.nf
        # find best server regions
        Vo = self.CmWo
        Vp = self.CmWp
        self.bestsvo = np.empty(nf * ng * na).reshape(nf, ng, na)
        self.bestsvp = np.empty(nf * ng * na).reshape(nf, ng, na)
        for kf in range(nf):
            MaxVo = np.max(Vo[kf, :, :], axis=1)
            MaxVp = np.max(Vp[kf, :, :], axis=1)
            for ka in range(na):
                uo = np.where(Vo[kf, :, ka] == MaxVo)
                up = np.where(Vp[kf, :, ka] == MaxVp)
                self.bestsvo[kf, uo, ka] = ka + 1
                self.bestsvp[kf, up, ka] = ka + 1

    def plot(self, **kwargs):
        """
        """
        defaults = {
            'typ': 'pr',
            'grid': False,
            'f': 0,
            'a': 0,
            'db': True,
            'label': '',
            'pol': 'p',
            'col': 'b'
        }
        for k in defaults:
            if k not in kwargs:
                kwargs[k] = defaults[k]

        if 'fig' in kwargs:
            fig = kwargs['fig']
        else:
            fig = plt.figure()

        if 'ax' in kwargs:
            ax = kwargs['ax']
        else:
            ax = fig.add_subplot(111)

        if kwargs['typ'] == 'pr':
            if kwargs['a'] <> -1:
                if kwargs['pol'] == 'p':
                    U = self.CmWp[kwargs['f'], :, kwargs['a']]
                if kwargs['pol'] == 'o':
                    U = self.CmWo[kwargs['f'], :, kwargs['a']]
            else:
                if kwargs['pol'] == 'p':
                    U = self.CmWp[kwargs['f'], :, :].reshape(self.na * self.ng)
                else:
                    U = self.CmWo[kwargs['f'], :, :].reshape(self.na * self.ng)
            if kwargs['db']:
                U = 10 * np.log10(U)

        D = np.sqrt(np.sum((self.pa - self.pg) * (self.pa - self.pg), axis=0))
        if kwargs['a'] <> -1:
            D = D.reshape(self.ng, self.na)
            ax.semilogx(D[:, kwargs['a']],
                        U,
                        '.',
                        color=kwargs['col'],
                        label=kwargs['label'])
        else:
            ax.semilogx(D, U, '.', color=kwargs['col'], label=kwargs['label'])

        return fig, ax

    def show(self, **kwargs):
        """ show coverage
        Parameters
        ----------
        typ : string
            'pr' | 'sinr' | 'capacity' | 'loss' | 'best' | 'egd'
        grid : boolean
        polar : string
            'o' | 'p'
        best : boolean
            draw best server contour if True
        f : int
            frequency index
        a : int
            access point index (-1 all access point)
        Examples
        --------
        .. plot::
            :include-source:
            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a = C.show(typ='pr',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='best',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='loss',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='sinr',figsize=(10,8))
            >>> plt.show()
        See Also
        --------
        pylayers.gis.layout.Layout.showG
        """
        defaults = {
            'typ': 'pr',
            'grid': False,
            'polar': 'p',
            'f': 0,
            'a': -1,
            'db': True,
            'cmap': cm.jet,
            'best': True
        }

        title = self.dap[self.dap.keys()[0]].s.name + ' : '

        for k in defaults:
            if k not in kwargs:
                kwargs[k] = defaults[k]
        polar = kwargs['polar']
        assert polar in ['p', 'o'], "polar wrongly defined in show coverage"

        if 'fig' in kwargs:
            if 'ax' in kwargs:
                fig, ax = self.L.showG('s', fig=kwargs['fig'], ax=kwargs['ax'])
            else:
                fig, ax = self.L.showG('s', fig=kwargs['fig'])
        else:
            if 'figsize' in kwargs:
                fig, ax = self.L.showG('s', figsize=kwargs['figsize'])
            else:
                fig, ax = self.L.showG('s')

        # plot the grid
        self.typ = kwargs['typ']
        typ = kwargs['typ']
        if kwargs['grid']:
            for k in self.dap:
                p = self.dap[k].p
                ax.plot(p[0], p[1], 'or')

        f = kwargs['f']
        a = kwargs['a']
        assert typ in [
            'best', 'egd', 'sinr', 'snr', 'capacity', 'pr', 'loss',
            'intensity', 'losssombreamento', 'prsombreamento',
            'snrsombreamento'
        ], "typ unknown in show coverage"
        best = kwargs['best']

        dB = kwargs['db']

        # setting the grid

        l = self.grid[0, 0]
        r = self.grid[-1, 0]
        b = self.grid[0, 1]
        t = self.grid[-1, -1]

        arq = open('cobertura.txt', 'w')
        texto = '''dBm e V/m \n'''
        arq.write(texto)
        arq.close()

        if typ == 'best':
            title = title + 'Best server' + ' fc = ' + str(
                self.fGHz[f]) + ' GHz' + ' polar : ' + polar
            for ka in range(self.na):
                if polar == 'p':
                    bestsv = self.bestsvp[f, :, ka]
                if polar == 'o':
                    bestsv = self.bestsvo[f, :, ka]
                m = np.ma.masked_where(bestsv == 0, bestsv)
                if self.mode <> 'file':
                    W = m.reshape(self.nx, self.ny).T
                    ax.imshow(W,
                              extent=(l, r, b, t),
                              origin='lower',
                              vmin=1,
                              vmax=self.na + 1)
                else:
                    ax.scatter(self.grid[:, 0],
                               self.grid[:, 1],
                               c=m,
                               s=20,
                               linewidth=0)
            ax.set_title(title)
        else:
            if typ == 'egd':
                title = title + 'excess group delay : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                V = self.Ed
                dB = False
                legcb = 'Delay (ns)'
            if typ == 'sinr':
                title = title + 'SINR : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar == 'o':
                    V = self.sinro
                if polar == 'p':
                    V = self.sinrp
            if typ == 'snr':
                title = title + 'SNR : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar == 'o':
                    V = self.snro
                if polar == 'p':
                    V = self.snrp
            if typ == 'capacity':
                title = title + 'Capacity : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                legcb = 'Mbit/s'
                if polar == 'o':
                    V = self.bmhz.T[np.newaxis, :] * np.log(
                        1 + self.sinro) / np.log(2)
                if polar == 'p':
                    V = self.bmhz.T[np.newaxis, :] * np.log(
                        1 + self.sinrp) / np.log(2)

            if typ == 'pr':
                title = title + 'Pr : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dBm'
                else:
                    lgdcb = 'mW'
                if polar == 'o':
                    V = self.CmWo
                if polar == 'p':
                    V = self.CmWp

            if typ == 'loss':
                title = title + 'Loss : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar == 'o':
                    V = self.Lwo * self.freespace
                if polar == 'p':
                    V = self.Lwp * self.freespace

            if typ == 'losssombreamento':
                #relaxa que esse so muda no final
                title = title + 'Loss Log : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    lgdcb = 'Linear scale'
                if polar == 'o':
                    V = self.CmWo
                if polar == 'p':
                    V = self.CmWp

            if typ == 'prsombreamento':
                #relaxa que esse so muda no final
                title = title + 'Pr Log : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dBm'
                else:
                    lgdcb = 'Linear scale'
                if polar == 'o':
                    V = self.CmWo
                if polar == 'p':
                    V = self.CmWp

            if typ == 'snrsombreamento':
                #relaxa que esse so muda no final
                title = title + 'SNR Log : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    lgdcb = 'Linear scale'
                if polar == 'o':
                    V = self.CmWo
                if polar == 'p':
                    V = self.CmWp

            if typ == 'intensity':
                title = title + 'Intensity : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                legcb = 'V/m'
                if polar == 'o':
                    V = np.power(10, (
                        (self.CmWo + 20 * np.log10(self.fGHz[f] * 1000) + 77.2)
                        / 20)) * 0.000001
                if polar == 'p':
                    V = np.power(10, (
                        (self.CmWp + 20 * np.log10(self.fGHz[f] * 1000) + 77.2)
                        / 20)) * 0.000001

            if a == -1:
                V = np.max(V[f, :, :], axis=1)
            else:
                V = V[f, :, a]

            # reshaping the data on the grid
            if self.mode != 'file':
                U = V.reshape((self.nx, self.ny)).T
            else:
                U = V

            if dB and typ != 'intensity':
                if typ == 'losssombreamento' or typ == 'prsombreamento' or typ == 'snrsombreamento':
                    f = self.fGHz[f] * 1000
                    Lf = self.PtDB - self.Prdo + self.Gt + self.Gr

                    medidas1 = []

                    dx = np.linspace(0, self.xt, self.nx)
                    dy = np.linspace(0, self.yt, self.ny)

                    for i in range(self.ny):
                        medidas1.append([])

                    for i in range(self.ny):
                        for j in range(self.nx):
                            medidas1[i].append(
                                np.sqrt(
                                    np.power(dx[j] - self.x0, 2) +
                                    np.power(dy[i] - self.y0, 2)) / 1000)

                    desvio = 0

                    X = np.random.normal(0, self.desviopadrao, len(medidas1))

                    PL2 = []
                    maior, menor = 0, 100

                    for i in range(self.ny):
                        PL2.append([])

                    for i in range(self.ny):
                        for j in range(self.nx):
                            oi = Lf + 10 * self.n * np.log10(
                                medidas1[i][j] / self.do) + X[i]
                            PL2[i].append(oi)
                            if (maior < oi):
                                maior = oi
                            if (menor > oi):
                                menor = oi

                    menor = np.floor(menor / 10) * 10
                    maior = np.ceil(maior / 10) * 10

                    if typ == 'prsombreamento':
                        maior, menor = -100, 0
                        pr = []
                        for i in range(self.ny):
                            pr.append([])

                        for i in range(self.ny):
                            for j in range(self.nx):
                                oi = self.PtDB - PL2[i][j]
                                pr[i].append(oi)
                                if (maior < oi):
                                    maior = oi
                                if (menor > oi):
                                    menor = oi
                        menor = np.floor(menor / 10) * 10
                        maior = np.ceil(maior / 10) * 10
                        U = pr
                    elif typ == 'snrsombreamento':
                        maior, menor = -100, 100
                        pr = []
                        for i in range(self.ny):
                            pr.append([])

                        for i in range(self.ny):
                            for j in range(self.nx):
                                oi = PL2[i][j] / self.pnw[0][0]
                                pr[i].append(oi)
                                if (maior < oi):
                                    maior = oi
                                if (menor > oi):
                                    menor = oi
                        menor = np.floor(menor / 10) * 10
                        maior = np.ceil(maior / 10) * 10
                        U = pr
                    else:
                        U = PL2
                else:
                    U = 10 * np.log10(U)
                #print U

            arq = open('cobertura.txt', 'w')
            texto = []
            for linha in U:
                texto.append(str(linha) + '\n')
            arq.writelines(texto)
            arq.close()

            if 'vmin' in kwargs:
                vmin = kwargs['vmin']
            else:
                if typ == 'losssombreamento' or typ == 'prsombreamento' or typ == 'snrsombreamento':
                    vmin = menor
                else:
                    vmin = U.min()

            if 'vmax' in kwargs:
                vmax = kwargs['vmax']
            else:
                if typ == 'losssombreamento' or typ == 'prsombreamento' or typ == 'snrsombreamento':
                    vmax = maior
                else:
                    vmax = U.max()

            if self.mode != 'file':
                img = ax.imshow(U,
                                extent=(l, r, b, t),
                                origin='lower',
                                vmin=vmin,
                                vmax=vmax,
                                cmap=kwargs['cmap'])
            else:
                img = ax.scatter(self.grid[:, 0],
                                 self.grid[:, 1],
                                 c=U,
                                 s=20,
                                 linewidth=0,
                                 cmap=kwargs['cmap'],
                                 vmin=vmin,
                                 vmax=vmax)

            for k in range(self.na):
                ax.annotate(str(k), xy=(self.pa[0, k], self.pa[1, k]))
            ax.set_title(title)

            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            clb = fig.colorbar(img, cax)
            clb.set_label(legcb)
            if typ == 'losssombreamento' or typ == 'prsombreamento' or typ == 'snrsombreamento':
                print 'Modelo do Sombreamento Log Normal'
            else:
                if best:
                    if self.mode <> 'file':
                        if polar == 'o':
                            ax.contour(np.sum(self.bestsvo,
                                              axis=2)[f, :].reshape(
                                                  self.nx, self.ny).T,
                                       extent=(l, r, b, t),
                                       linestyles='dotted')
                        if polar == 'p':
                            ax.contour(np.sum(self.bestsvp,
                                              axis=2)[f, :].reshape(
                                                  self.nx, self.ny).T,
                                       extent=(l, r, b, t),
                                       linestyles='dotted')

        # display access points
        if a == -1:
            ax.scatter(self.pa[0, :], self.pa[1, :], s=30, c='r', linewidth=0)
        else:
            ax.scatter(self.pa[0, a], self.pa[1, a], s=30, c='r', linewidth=0)
        plt.tight_layout()
        return (fig, ax)
예제 #12
0
class Simul(PyLayers):
    """ Simulation Class

    Methods
    -------

    gui()
        graphical user interface
    choose()
        choose a simulation file in simuldir
    info()
        info about the simulation
    showray(itx,irx,iray)
        show a single ray
    help()
        help on using Simulation object
    freq()
        return the frequency base
    save()
        save Simulation file
    layout
        load a Layout file
    load()
        load Simulation
    show3()
        geomview vizualization
    show3l(itx,irx)
        geomview vizualization of link itx irx
    show()
        2D visualization of simulation with furniture
    run(itx,irx)
        run simulation for links (itx,irx)
    cir(itx,irx,store_level=0,alpha=1.0)
        Channel Impulse Response calculation


    Attributes
    ----------

    fileconf

    filetauk
    filetang
    filerang

    tx
    rx

    progress

    indoor
    mat
    sl

    Notes
    ------

    This class group together all the parametrization files of a simulation

    """
    def __init__(self, _filesimul='default.ini'):
        self.filesimul = _filesimul
        self.config = ConfigParser.ConfigParser()
        self.config.add_section("files")
        self.config.add_section("frequency")
        self.config.add_section("waveform")
        self.config.add_section("output")

        self.dtang = {}
        self.drang = {}
        self.dtauk = {}
        self.dfield = {}
        self.dcir = {}
        self.output = {}

        #
        # Here was a nasty bug : Rule for the future
        #    "Always precise the key value of the passed argument"
        #
        # Mal nommer les choses, c'est ajouter au malheur du monde ( Albert Camus )
        #
        self.tx = RadioNode(
            name='',
            typ='tx',
            _fileini='radiotx.ini',
            _fileant='defant.vsh3',
        )

        self.rx = RadioNode(
            name='',
            typ='rx',
            _fileini='radiorx.ini',
            _fileant='defant.vsh3',
        )

        self.filefreq = "def.freq"

        self.progress = -1  # simulation not loaded

        self.filetang = []
        self.filerang = []
        self.filetauk = []
        self.filefield = []

        self.fileconf = "project.conf"
        self.cfield = []
        self.fGHz = np.linspace(2, 11, 181, endpoint=True)
        self.wav = wvf.Waveform()
        self.load(_filesimul)

    def gui(self):
        """ gui to modify the simulation file
        """
        simulgui = multenterbox(
            '', 'Simulation file', ('filesimul', 'filestr', 'filefreq',
                                    'filespaTx', 'filespaRx', 'fileantTx'
                                    'fileantRx'),
            (self.filesimul, self.filestr, self.filefreq, self.filespaTx,
             self.filespaRx, self.fileantTx, self.fileantRx))
        if simulgui is not None:
            self.filesimul = simulgui[0]
            self.filestr = simulgui[1]
            self.filefreq = simulgui[6]
            self.filespaTx = simulgui[7]
            self.filespaRx = simulgui[8]
            self.fileantTx = simulgui[9]
            self.fileantRx = simulgui[10]

    def updcfg(self):
        """ update simulation .ini config file 
        
        with values currently in use.
        """
        self.config.set("files", "struc", self.filestr)
        self.config.set("files", "conf", self.fileconf)
        self.config.set("files", "txant", self.tx.fileant)
        self.config.set("files", "rxant", self.rx.fileant)
        self.config.set("files", "tx", self.tx.fileini)
        self.config.set("files", "rx", self.rx.fileini)
        self.config.set("files", "mat", self.filematini)
        self.config.set("files", "slab", self.fileslabini)

        self.config.set("tud", "purc", str(self.patud.purc))
        self.config.set("tud", "nrmax", str(self.patud.nrmax))
        self.config.set("tud", "num", str(self.patud.num))

        #
        # frequency section
        #

        self.config.set("frequency", "fghzmin", self.fGHz[0])
        self.config.set("frequency", "fghzmax", self.fGHz[-1])
        self.config.set("frequency", "nf", str(len(self.fGHz)))
        #
        # waveform section
        #
        self.config.set("waveform", "tw", str(self.wav['twns']))
        self.config.set("waveform", "band", str(self.wav['bandGHz']))
        self.config.set("waveform", "fc", str(self.wav['fcGHz']))
        self.config.set("waveform", "thresh", str(self.wav['threshdB']))
        self.config.set("waveform", "type", str(self.wav['typ']))
        self.config.set("waveform", "fe", str(self.wav['feGHz']))
        #
        # output section
        #
        for k in self.output.keys():
            self.config.set("output", str(k), self.dout[k])

        # Initialize waveform
        self.wav = wvf.Waveform()
        # Update waveform
        self.wav.read(self.config)
        self.save()

    def clean_project(self, verbose=True):
        """
        Clean Pyrpoject directory

        remove .lch, .tra, .field .tud, .tauk, .tang, .rang, <pyproject>/output

        remove [output] entries into .ini of self.filesimul


        Parameters
        ----------
 
        verbose : boolean
            Verbose mode on/off


        Returns
        -------
            Boolean:
                True if the project has been cleaned, False otherwise


        """

        if verbose:

            print "-----------------------------------"
            print "-----------------------------------"
            print "          WARNING                  "
            print "-----------------------------------"
            print "-----------------------------------"
            print "You are about to remove ALL previous computed raytracing files."
            print "If you decide to remove it, you will need to restart the entire \
    raytracing simulation to exploit simulation results"

            print "\n Do you want to remove these simulation files ? y/n"
            r = raw_input()

        else:
            r == 'y'

        if r == 'y':
            inifile = self.filesimul
            try:
                path = os.getenv('BASENAME')
            except:
                print('Error : there is no project  directory in $BASENAME')

            dirlist = ['output']
            extension = [
                '.lch', '.field', '.tra', '.tud', '.tang', '.rang', '.tauk'
            ]
            rindic = False

            # remove file

            for d in dirlist:
                for ex in extension:
                    files = os.listdir(path + '/' + d)
                    for f in files:
                        if not os.path.isdir(path + '/' + d + '/' +
                                             f) and ex in f:
                            rindic = True
                            if verbose:
                                print f
                            os.remove(path + '/' + d + '/' + f)

                    if rindic:
                        if verbose:
                            print 'removed *' + ex + ' from ' + d + '\n'
                        rindic = False

            # remove output into the self.filesimul ini file

            simcfg = ConfigParser.ConfigParser()
            simcfg.read(pyu.getlong(inifile, pstruc['DIRSIMUL']))
            simcfg.remove_section('output')
            f = open(pyu.getlong(inifile, pstruc['DIRSIMUL']), 'wb')
            simcfg.write(f)
            f.close()
            self.dout = {}
            self.dlch = {}
            self.dtra = {}
            self.dtud = {}
            self.dtang = {}
            self.drang = {}
            self.dtauk = {}
            self.dfield = {}
            self.dcir = {}
            self.output = {}

            if verbose:
                print 'removed [output] entries into ' + inifile + '\n'
                print 'Project CLEANED'
            return True
        else:
            if verbose:
                print "clean project process ABORTED"
            return False

    def save(self):
        """ save simulation file

        Simulation files are .ini files which are saved in a dedicated
        directory basename/ini in the Project tree

        """
        filesimul = pyu.getlong(self.filesimul, "ini")
        fd = open(filesimul, "w")
        # getting current spa file if any
        try:
            self.config.set("files", "tx", self.tx.fileini)
        except:
            pass
        try:
            self.config.set("files", "rx", self.rx.fileini)
        except:
            pass
        self.config.write(fd)
        fd.close()
        # save tx
        self.tx.save()
        # save rx
        self.rx.save()
        # save slab and mat file
        # --
        # self.slab.save(self.fileslabini)
        # self.slab.mat.save(self.filematini)
        # --
        # fix bug #189
        #   slab is a member of S.L not of S anymore
        #   mat is a member of S.L.sl not of S.slab
        try:
            self.L.sl.save(self.fileslabini)
        except:
            pass
        try:
            self.L.sl.mat.save(self.filematini)
        except:
            pass

#    def saveold(self):
#        """ save simulation file

#        """
#        filesimul = pyu.getlong(self.filesimul, "ini")
#        fd = open(filesimul, "w")
#        config = ConfigParser.ConfigParser()

#        #
#        # files section
#        #
#        #config.add_section("files")
#        self.config.set("files", "conf", self.fileconf)
#        self.config.set("files", "struc", self.filestr)
#        self.config.set("files", "slab", self.fileslab)
#        self.config.set("files", "mat", self.filemat)

#        try:
#            self.config.set("files", "tx", self.tx.filespa)
#        except:
#            pass
#        try:
#            self.config.set("files", "rx", self.rx.filespa)
#        except:
#            pass
#        try:
#            self.config.set("files", "txant", self.tx.fileant)
#        except:
#            pass
#        try:
#            self.config.set("files", "rxant", self.rx.fileant)
#        except:
#            pass
#        self.config.set("files", "patra", self.filepatra)
#        self.config.set("files", "palch", self.filepalch)
#        self.palch.save()
#        self.patra.save()

#        #
#        # tud section
#        #

#        self.config.set("tud", "purc", self.patud.purc)
#        self.config.set("tud", "nrmax", self.patud.nrmax)
#        self.config.set("tud", "num", self.patud.num)

#        #
#        # frequency section
#        #
#        self.config.set("frequency", "fghzmin", self.freq[0])
#        self.config.set("frequency", "fghzmax", self.freq[-1])
#        self.config.set("frequency", "Nf", len(self.freq))

#        #
#        # output section
#        #
#        #filelch exists
#        if self.progress > 0:
#            #config.add_section("output")
#            for k in range(len(self.filelch)):
#                _fileout = "out" + "???"
#                filename = self.filelch[k]
#                self.config.set("launch", str(k + 1), filename)

#        # filetra exists
#        for k in range(len(self.filelch)):
#            if self.progress > 1:
#                #self.config.add_section("trace")
#                for l in arange(len(self.filetra[k])):
#                    filename = self.filetra[k][l]
#                    self.config.set("trace", "rx" + str(l + 1), filename)

#        # .tang exists
#        # .rang exists
#        # .tud exists
#            if self.progress > 2:
#                #config.add_section("tud")
#                #config.add_section("tang")
#                #config.add_section("rang")

#                for l in arange(len(self.filetud[k])):
#                    ftud = self.filetud[k][l]
#                    self.config.set("tud", "rx" + str(l + 1), ftud)

#                for l in arange(len(self.filetang[k])):
#                    ftang = self.filetang[k][l]
#                    self.config.set("tang", "rx" + str(l + 1), ftang)

#                for l in arange(len(self.filerang[k])):
#                    frang = self.filerang[k][l]
#                    self.config.set("rang", "rx" + str(l + 1), frang)

#        # .field exist
#        # .tauk exist
#            if self.progress > 3:
#                #config.add_section("tauk")
#                #config.add_section("field")
#                for l in arange(len(self.filetud[k])):
#                    ftauk = self.filetud[k][l]
#                    self.config.set("tauk", "rx" + str(l + 1), ftauk)

#                for l in arange(len(self.filefield[k])):
#                    ffield = self.filefield[k][l]
#                    self.config.set("field", "rx" + str(l + 1), ffield)

#        self.config.write(fd)
#        fd.close()

    def save_project(self):
        """ save Simulation files in a zipfile

        Simulation files are .ini files which are saved in a dedicated
        directory basename/ini in the Project tree

        """
        root = Tkinter.Tk()
        zipfileName = tkFileDialog.asksaveasfilename(
            parent=root,
            filetypes=[("zipped file", "zip")],
            title="Save Project",
        )
        pyu.zipd(basename, zipfileName)
        root.withdraw()
        print "Current project saved in", zipfileName

    def load_project(self):
        """ load Simulation files from a zipfile

        Simulation files are .ini files which are saved in a dedicated
        directory basename/ini in the Project tree

        """
        root = Tkinter.Tk()
        zipfileName = tkFileDialog.askopenfile(parent=root,
                                               mode='rb',
                                               title='Choose a project')
        dirname = tkFileDialog.askdirectory(parent=root,
                                            initialdir=basename,
                                            title='Please select a directory',
                                            mustexist=0)
        pyu.unzipd(dirname, zipfileName)
        root.withdraw()
        print "Current project loaded in", dirname

    def choose(self):
        """
            Choose a simulation file in simuldir

        """
        import tkFileDialog as FD
        fichsimul = FD.askopenfilename(filetypes=[("Fichiers simul ",
                                                   "*.simul"), ("All", "*")],
                                       title="Please choose a simulation file",
                                       initialdir=simuldir)
        self.filesimul = pyu.getshort(fichsimul)
        self.load()

    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 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 show(self, itx=[-1], irx=[-1], furniture=True, s=8, c='b', traj=False, num=False,fig=[],ax=[]):
    def show(self, **kwargs):
        """ show simulation

            Parameters
            -----------
            itx        : list of tx indices
            irx        : list of rx indices
            furniture  : boolean for METALIC furniture display
            s          : scale fir scatter plot  (default 8)
            c          : color for scatter plot  (default 'b')
            traj       : boolean  (def False)
            num        : boolean  (def False)
                display a number


            Examples
            --------
            >>> import matplotlib.pyplot as plt
            >>> from pylayers.simul.simulem import *
            >>> S = Simul()
            >>> S.load('w1.ini')
            >>> S.L.loadfur('FurW1.ini')
            >>> S.show()
            >>> plt.show()



        """

        defaults = {
            'itx': [-1],
            'irx': [-1],
            'furniture': True,
            's': 8,
            'c': 'b',
            'num': False,
            'fig': [],
            'ax': [],
            'aw': False
        }

        for k in defaults:
            if k not in kwargs:
                kwargs[k] = defaults[k]
            st = k + "=kwargs['" + k + "']"
            exec(st)

        if type(itx) == int:
            itx = [itx]
        if type(irx) == int:
            irx = [irx]

        if fig == []:
            fig = plt.gcf()
        if ax == []:
            ax = fig.gca()

        #self.L.display['scaled']=False
        fig, ax = self.L.showG('s', fig=fig, ax=ax, aw=aw)
        #
        if furniture:
            if 'lfur' in self.L.__dict__:
                for fur in self.L.lfur:
                    if fur.Matname == 'METAL':
                        fur.show(fig, ax)
            else:
                print "Warning : no furniture file loaded"

        if irx[0] == -1:
            ax.scatter(self.rx.position[0, :],
                       self.rx.position[1, :],
                       c='b',
                       s=s,
                       alpha=0.5)
            #ax.scatter(self.rx.position[0,0],self.rx.position[0,1],c='k',s=s,linewidth=0)
            #ax.scatter(self.rx.position[1,0],self.rx.position[1,1],c='b',s=s,linewidth=0)
            #ax.scatter(self.rx.position[2,0],self.rx.position[2,1],c='g',s=s,linewidth=0)
            #ax.scatter(self.rx.position[3,0],self.rx.position[3,1],c='c',s=s,linewidth=0)
        else:
            for k in irx:
                ax.scatter(self.rx.position[0, k - 1],
                           self.rx.position[1, k - 1],
                           c='b',
                           s=s,
                           alpha=0.5)
                if num:
                    ax.text(self.rx.position[0, k - 1],
                            self.rx.position[1, k - 1],
                            str(k),
                            color='blue')

        if itx[0] == -1:
            ax.scatter(self.tx.position[0, :],
                       self.tx.position[1, :],
                       c='r',
                       s=s)
        else:
            if traj:
                cpt = 1
            for k in itx:
                ax.scatter(self.tx.position[0, k - 1],
                           self.tx.position[1, k - 1],
                           c=c,
                           s=s,
                           linewidth=0)
                if num:
                    if traj:
                        ax.text(self.tx.position[0, k - 1],
                                self.tx.position[1, k - 1],
                                str(cpt),
                                color='black')
                        cpt = cpt + 1
                    else:
                        ax.text(self.tx.position[0, k - 1],
                                self.tx.position[1, k - 1],
                                str(k),
                                color='black')

        return (fig, ax)
        #for k in range(self.tx.N):
        #    ax.text(self.tx.position[0,k],self.tx.position[1,k],str(k+1),color='black')
        #    ax.scatter(self.tx.position[0,:],self.tx.position[0,:],

        #for k in range(self.rx.N):
        #   ax.text(self.rx.position[0,k],self.rx.position[1,k],str(k),color='black')

    def PL(self, itx):
        """ plot Path Loss

        itx
        """
        td = []
        tEa = []
        tEo = []
        for irx in self.dcir[itx].keys():
            d = self.delay(itx, irx) * 0.3
            cira, ciro = self.loadcir(itx, irx)

            td.append(d)
            tEa.append(Ea)
            tEo.append(Eo)

        plt.semilogx(td, 10 * np.log10(tEa), 'xr')
        plt.semilogx(td, 10 * np.log10(tEo), 'xb')
        plt.show()
        return td, tEa, tEo

    def eval(self, **kwrgs):
        """
        """
        for kt in range(Nb_tx):
            tx = np.array([
                self.tx.position[0, kt + 1], self.tx.position[1, kt + 1],
                self.tx.position[2, kt + 1]
            ])
            link.a = tx
            for kr in range(Nb_Run):
                rx = np.array([
                    S.rx.position[0, Run], S.rx.position[1, Run],
                    S.rx.position[2, Run]
                ])
                link.b = rx
                tic = time.clock()
                ak, tk = link.eval(verbose=False, diffraction=True)
                toc = time.clock()
                ciro = link.H.applywav(wav.sfg)
                cir = bs.TUsignal(ciro.x, np.squeeze(np.sum(ciro.y, axis=0)))
                tac = time.clock()
                tcir[Run] = cir
                print toc - tic, tac - toc

    def evalcir(self, cutoff=4, algo='new'):
        """
        Parameters
        ----------

        S
        tx
        rx
        wav
        cutoff

        """

        crxp = -1
        ctxp = -1
        tcir = {}
        tx = self.tx.position
        Ntx = len(tx[0])
        rx = self.rx.position
        Nrx = len(rx[0])

        #for kt in range(1,Ntx-1):
        #print kt+1
        kt = 0
        tcir[kt] = {}
        t = np.array([
            self.tx.position[0, kt], self.tx.position[1, kt],
            self.tx.position[2, kt]
        ])
        for kr in range(Nrx):
            if (np.mod(kr, 10) == 0):
                print kr + 1
            r = np.array([
                self.rx.position[0, kr], self.rx.position[1, kr],
                self.rx.position[2, kr]
            ])
            ctx = self.L.pt2cy(t)
            crx = self.L.pt2cy(r)
            if (ctx <> ctxp) | (crx <> crxp):
                Si = signature.Signatures(self.L, ctx, crx)
                ctxp = ctx
                crxp = crx
                Si.run4(cutoff=cutoff, algo=algo)
            r2d = Si.rays(t, r)
            #r2d.show(S.L)

            r3d = r2d.to3D(self.L)
            r3d.locbas(self.L)
            r3d.fillinter(self.L)
            Ct = r3d.eval(self.fGHz)
            sca = Ct.prop2tran(self.tx.A, self.rx.A)
            cir = sca.applywavB(self.wav.sfg)
            tcir[kt][kr] = cir
        return (tcir)

    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 pltcir(self,
               itx=1,
               irx=1,
               mode='linear',
               noise=False,
               color='b',
               format='a',
               fig=[],
               ax=[]):
        """ plot Channel Impulse Response

        Parameters
        ----------

        itx : Tx index
        irx : Rx index
        mode : str
            {'linear','dB'}
            noise : boolean
        color : string
            default 'b'

        >>> from pylayers.simul.simulem import *
        >>> S = Simul()
        >>> S.load('where2.ini')
        >>> S.run(1,1)
        >>> S.pltcir(1,1,mode='linear',noise=False,color='k')

        """

        if fig == []:
            fig = plt.gcf()
        #if ax==[]:
        #    ax = fig.gca()

        _filecir = self.dcir[itx][irx] + '.mat'
        filecir = pyu.getlong(_filecir,
                              pstruc['DIRCIR'] + '/Tx' + str('%0.3d' % itx))
        D = spio.loadmat(filecir)
        ax = fig.add_subplot('211')

        fig, ax = self.show(itx, irx, fig=fig, ax=ax)
        ax = fig.add_subplot('212')
        if 'a' in format:
            kxa = 't'
            kya = 'cir'
            ta = D[kxa]
            Tobs = ta[-1] - ta[0]
            te = ta[1] - ta[0]
            if noise:
                na = bs.Noise(Tobs + te, 1. / te)
                naf = na.gating(4.493, 0.5)
            cira = bs.TUsignal(ta, D[kya][:, 0])

        if 'o' in format:
            kxo = 'to' + str(irx)
            kyo = 'ciro' + str(irx)
            to = D[kxo]
            Tobs = to[-1] - to[0]
            te = to[1] - to[0]
            if noise:
                no = bs.Noise(Tobs + te, 1. / te)
                nof = no.gating(4.493, 0.5)
            ciro = bs.TUsignal(to, D[kyo][:, 0])

        if mode == 'linear':
            #plt.plot(ta,naf.y,color='k',label='Noise')
            plt.plot(ta, D[kya], label='Rx ' + str(irx), color=color)
            plt.xlabel('Time (ns)')
            '''if noise:
                naf.plot(col='k')
            cira.plot(col=color)'''
        else:
            '''if noise:
                naf.plotdB(col='k')
            cira.plotdB()'''
            plt.plot(ta,
                     20 * np.log10(abs(D[kya])),
                     label='Rx ' + str(irx),
                     color=color)
            plt.xlabel('Time (ns)')


#        plt.legend()
        plt.show()
        #plt.savefig('Tx'+str(itx),format=pdf,dpi=300)

    def scatter(self,
                itx,
                irx,
                values,
                cmap=plt.cm.gray,
                s=30,
                spl=221,
                title='',
                vaxis=((-30, 10, 2, 18)),
                vmin=0,
                vmax=1,
                colbool=False,
                cblabel='dB'):
        """
            Parameters
            ----------

            itx
            irx
            values
            cmap
            s
            spl
            title
            vaxis
            vmin
            vmax
            colbool
            clabel

        """
        fig = plt.gcf()
        ax = fig.add_subplot(spl)
        xtx = self.tx.position[itx, 0]
        ytx = self.tx.position[itx, 1]
        xrx = self.rx.position[irx, 0]
        yrx = self.rx.position[irx, 1]
        self.L.display['title'] = title
        self.L.showGs(ax)
        for furk in siradel.siradel_furniture.keys():
            fur = siradel.siradel_furniture[furk]
            if fur.Matname == 'METAL':
                fur.show(fig, ax)

        #self.show(furniture=True)
        plt.axis(vaxis)
        b1 = ax.scatter(xtx,
                        ytx,
                        s=s,
                        c=values,
                        cmap=cmap,
                        linewidths=0,
                        vmin=vmin,
                        vmax=vmax)
        ax.scatter(xrx, yrx, s=30, c='b', linewidths=0)
        if colbool:
            cb = colorbar(b1)
            cb.set_label(cblabel, fontsize=14)
        return (b1)

    def info(self, itx=[], irx=[]):
        """ display simulation information

         Parameters
         ----------
         itx : Tx index
         irx : Rx index

        """
        print self.filesimul
        print '------------------------------------------'
        try:
            print "Layout Info : \n", self.L.info()
        except:
            print "provide a Layout in the simulation : S.L "
            print ">>> S.layout(filename.str) "
            print "or "
            print ">>> S.layout(filename.str2 "
            print "or "
            print ">>> S.layout(filename.str,filematini,filematini) "
            print "default files exists for filematini and fileslabini "

            return
        try:
            print "Tx Info :\n", self.tx.info()
        except:
            print "provide a tx in the simulation : S.tx "
            return
        try:
            print "Rx Info :\n", self.rx.info()
        except:
            print "provide a rx in the simulation : S.rx "
            return

            #    print "Tx : ",self.tx.points[itx]
            print "Rx : ", self.rx.points[itx]
            print "Delay (ns) :", self.delay(itx, irx)
            print "Distance (m) :", 0.3 / self.delay(itx, irx)
            print ""
            if itx in self.dlch.keys():
                print "-----"
                print "Launching "
                print "-----"
                print " ", self.dlch[itx]
            if irx in self.dtra[itx].keys():
                print "-----"
                print "Tracing "
                print "-----"
                print " ", self.dtra[itx][irx]
                gr = GrRay3D()
                gr.load(self.dtra[itx][irx], self.L)
                gr.info()
            if irx in self.dtud[itx].keys():
                print "-----"
                print "Tud parameters "
                print "-----"
                print " ", self.dtud[itx][irx]
                print " ", self.dtang[itx][irx]
                print " ", self.drang[itx][irx]
                gt = GrRay3D.GrRayTud()
                gt.load(self.dtud[itx][irx], self.dtang[itx][irx],
                        self.drang[itx][irx], self.sl)
            if irx in self.dtauk[itx].keys():
                print self.dtauk[itx][irx]
                print self.dfield[itx][irx]
                VC = self.VC(itx, irx)
            if irx in self.dcir[itx].keys():
                print self.dcir[itx][irx]

    def info2(self):
        for i, j in enumerate(self.__dict__.keys()):
            print j, ':', self.__dict__.values()[i]

    def filtray(self, itx, irx, tau0, tau1, col='b'):
        """ filter rays

        Parameters
        ----------
        itx :
        irx :
        tau0 :
        tau1 :
        col :

        Display ray and nstr
        """
        gr = GrRay3D()
        gr.load(self.dtra[itx][irx], self.L)
        self.L.display['Thin'] = True
        self.L.display['Node'] = False
        self.L.display['NodeNum'] = False
        self.L.display['EdgeNum'] = False
        plt.axis('scaled')
        #self.L.show(fig,ax,nodelist,seglist)
        self.L.showGs()
        delays = gr.delay()
        rayset = np.nonzero((delays >= tau0) & (delays <= tau1))[0]
        fig = plt.gcf()
        ax = fig.get_axes()[0]
        gr.show(ax, rayset, col=col, node=False)
        plt.title('Tx' + str(itx) + '-Rx' + str(irx) + ' : ' + str(tau0) +
                  ' < tau < ' + str(tau1))

    def showray(self, itx, irx, iray=np.array([]), fig=[], ax=[]):
        """ show layout and rays for a radio link

        Parameters
        ----------
        itx  : tx index
        irx  : rx index
        iray : list of rays to be displayed ndarray


        """

        #if ax==[]:
        #    fig = plt.figure()
        #    ax  = fig.add_subplot('111')

        gr = GrRay3D()
        gr.load(self.dtra[itx][irx], self.L)
        if len(iray == 1):
            ray = gr.ray3d[iray[0]]
            nstr = ray.nstr[1:-1]
            uneg = np.nonzero(nstr < 0)
            upos = np.nonzero((nstr > 0) & (nstr <= self.L.Ne))
            uceil = np.nonzero(nstr == self.L.Ne + 1)
            ufloor = np.nonzero(nstr == self.L.Ne + 2)
        #seglist  = nstr[upos[0]]-1
        #nodelist = -nstr[uneg[0]]-1
        #seglist2 = S.L.segpt(nodelist)
        self.L.display['Thin'] = True
        self.L.display['Node'] = False
        self.L.display['NodeNum'] = False
        self.L.display['EdgeNum'] = False
        #self.L.show(fig,ax)
        #print ray.nn
        #print len(ray.nstr)
        #print ray.nstr
        #print nodelist
        #print seglist
        #print seglist2
        #seglist = hstack((seglist,seglist2))
        self.L.display['Node'] = False
        self.L.display['Thin'] = False
        self.L.display['NodeNum'] = True
        self.L.display['EdgeNum'] = True
        plt.axis('scaled')
        #self.L.show(fig,ax,nodelist,seglist)
        fig, ax = self.L.showGs(show=False)
        gr.show(ax, iray, col='b', node=False)

        if len(iray) == 1:
            plt.title(str(nstr))
        else:
            plt.title('Tx' + str(itx) + '-Rx' + str(irx) + ' ' +
                      str(min(iray)) + ' ' + str(max(iray)))

    def show3l(self, itx, irx):
        """ geomview display of a specific link

        g = S.show3l(itx,irx)

        Parameters
        ----------
        itx
            transmitter index
        irx
            receiver index

        """
        filetra = self.dtra[itx][irx]
        gr = GrRay3D()
        gr.load(filetra, self.L)
        gr.show3()

        return (gr)

    def _show3(self, rays=[], newfig=False, **kwargs):
        """ display of the simulation configuration
            using Mayavi

        Parameters
        ----------

        rays: Ray3d object :
            display the rays of the simulation
        newfig : boolean (default : False)
        kwargs of Rays.show3()


        see also
        --------

        pylayers.gis.layout
        pylayers.antprop.antenna
        pylayers.antprop.rays

        """
        Atx = self.tx.A
        Arx = self.rx.A
        Ttx = self.tx.orientation
        Trx = self.rx.orientation
        ptx = self.tx.position
        prx = self.rx.position

        self.L._show3(newfig=False, opacity=0.7)
        Atx._show3(T=Ttx.reshape(3, 3),
                   po=ptx,
                   title=False,
                   colorbar=False,
                   newfig=False)
        Arx._show3(T=Trx.reshape(3, 3),
                   po=prx,
                   title=False,
                   colorbar=False,
                   newfig=False)
        if rays != []:
            rays._show3(**kwargs)

    def show3(self, rays=[], **kwargs):
        """ geomview display of the simulation configuration

        Parameters
        ----------

        centered : boolean
            center the scene if True
        bdis  : boolean
            display local basis

        """
        try:
            self.tx.save()
        except:
            print('tx set is no defined')
        try:
            self.rx.save()
        except:
            print('rx set is no defined')
        _filename = self.filesimul.replace('.ini', '.off')
        filename = pyu.getlong(_filename, pstruc['DIRGEOM'])
        fo = open(filename, "w")
        fo.write("LIST\n")
        try:
            sttx = "{<" + self.tx.filegeom + "}\n"
        except:
            sttx = "\n"
        try:
            strx = "{<" + self.rx.filegeom + "}\n"
        except:
            strx = "\n"
        try:
            stst = "{<" + self.L.filegeom + "}\n"
        except:
            stst = "\n"
        fo.write(sttx)
        fo.write(strx)
        fo.write(stst)
        fo.write("{</usr/share/geomview/geom/xyz.vect}\n")
        if rays != []:
            kwargs['bdis'] = False
            kwargs['L'] = self.L
            kwargs['centered'] = False
            fo.write("{<" + rays.show3(**kwargs) + "}")

        fo.close()

        command = "geomview -nopanel -b 1 1 1 " + filename + " 2>/dev/null &"
        os.system(command)

    def run(self, link, cirforce=True, verbose=False, cutoff=4):
        """ run the simulation for 1 tx and a set of rx

            Parameters
            ----------

            itx      : tx index
            srx      : list of rx index
            cirforce : boolean

            Warnings
            --------

            index point start with 1

            Example
            -------

            >>> from pylayers.simul.simulem import *
            >>> itx = 1
            >>> srx = [1,2,3]
            >>> S   = Simul()
            >>> S.load('where2.ini')
            >>> out = S.run(itx,srx)


        """

        # get file prefix
        dl = DLink(force=True, L=self.L, fGHz=self.fGHz, verbose=False)
        prefix = self.filesimul.replace('.ini', '')
        lsig = []
        self.chan = {}
        for k, il in enumerate(link):
            tx = self.tx.points[il[0]]
            rx = self.rx.points[il[1]]
            ctx = self.L.pt2cy(tx)
            crx = self.L.pt2cy(rx)
            _filecir = prefix + '-cir-' + str(k) + '-' + str(link) + '-' + str(
                (ctx, crx))
            D = {}
            D['Tx'] = tx
            D['Rx'] = rx

            dl.a = tx
            dl.b = rx
            ak, tauk = dl.eval(verbose=False, diffraction=True)
            self.chan[k] = dl
            #cira = dl.H.applywavB(self.wav.sf)
            #cira = dl.H.applywavB(self.wav.sfg)

            #D['t'] = cira.x
            #D['cir'] = cira.y

            #filename = pyu.getlong(_filecir, 'output')
            #spio.savemat(filename, D)

    def delay(self, itx, irx):
        """ calculate LOS link delay

            Parameters
            ----------

            itx
            irx

            Returns
            -------

            delay : float 
                delay in ns

        """
        tx = self.tx.points[itx]
        rx = self.rx.points[irx]
        df = tx - rx
        dist = np.sqrt(np.dot(df, df))
        return (dist / 0.3)
예제 #13
0
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')
#plt.savefig('graphGs.png')
#build topological graph
ax2 = fig.add_subplot(323)
L.showG(fig=fig, ax=ax2, graph='t')
plt.title('Topological graph')
예제 #14
0
    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)
예제 #15
0
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()
예제 #16
0
class Coverage(PyLayers):
    """ Handle Layout Coverage

        Methods
        -------

        creategrid()
            create a uniform grid for evaluating losses
        cover()
            run the coverage calculation
        showPower()
            display the map of received power
        showLoss()
            display the map of losses


        Attributes
        ----------

        All attributes are read from fileini ino the ini directory of the
        current project

        _fileini
            default coverage.ini

        L :  a Layout
        nx    : number of point on x
        ny    : number of point on y
        tx    : transmitter position
        txpe  : transmitter power emmission level
        show  : boolean for automatic display power map
        na : number of access point

    """


    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.ng = self.nx*self.ny
        self.mode = eval(self.gridopt['full'])
        self.boundary = eval(self.gridopt['boundary'])

        # create grid
        # we could here construct a grid locally around the access point
        # to be done later for code acceleration
        #
        self.creategrid(full=self.mode,boundary=self.boundary)

        self.dap = {}
        for k in self.apopt:
            kwargs  = eval(self.apopt[k])
            ap = std.AP(**kwargs)
            self.dap[eval(k)] = ap
            try:
                self.aap = np.vstack((self.aap,ap['p'][0:2]))
                self.ptdbm = np.vstack((self.ptdbm,ap['PtdBm']))
            except:
                self.aap = ap['p'][0:2]
                self.ptdbm = ap['PtdBm']
        # 1 x na
        self.ptdbm = self.ptdbm.T

        # number of access points
        self.na = len(self.dap)

        # creating all links
        p = product(range(self.ng),range(self.na))
        #
        # a : access point
        # g : grid
        #
        for k in p:
            pg = self.grid[k[0],:]
            pa = self.aap[k[1]]
            try:
                self.pa = np.vstack((self.pa,pa))
            except:
                self.pa = pa
            try:
                self.pg = np.vstack((self.pg,pg))
            except:
                self.pg = pg

        self.pa = self.pa.T
        self.pg = self.pg.T

        # frequency is chosen as all the center frequencies of the standard
        # warning assuming the same standard
        self.fGHz = self.dap[0].s.fcghz
        self.nf = len(self.fGHz)

        # AP section
        #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'])

        kBoltzmann = 1.3806503e-23
        self.temperaturek = eval(self.rxopt['temperaturek'])
        self.noisefactordb = eval(self.rxopt['noisefactordb'])

        # list of access points
        lap  = self.dap.keys()
        # list of channels
        lchan = map(lambda x: self.dap[x]['chan'],lap)

        apchan = zip(self.dap.keys(),lchan)
        self.bmhz = np.array(map(lambda x: self.dap[x[0]].s.chan[x[1][0]]['BMHz']*len(x[1]),apchan))
        # Evaluate Noise Power (in dBm)

        Pn = (10**(self.noisefactordb/10.)+1)*kBoltzmann*self.temperaturek*self.bmhz*1e3
        self.pndbm = 10*np.log10(Pn)+60

        # 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()


    def __repr__(self):
        st=''
        st = st+ 'Layout file : '+self.L.filename + '\n\n'
        st = st + '-----list of Access Points ------'+'\n'
        for k in self.dap:
            st = st + self.dap[k].__repr__()+'\n'
        st = st + '-----Rx------'+'\n'
        st= st+ 'rxsens (dBm) : '+ str(self.rxsens) + '\n'
        st= st+ 'bandwith (Mhz) : '+ str(self.bmhz) + '\n'
        st= st+ 'temperature (K) : '+ str(self.temperaturek) + '\n'
        st= st+ 'noisefactor (dB) : '+ str(self.noisefactordb) + '\n\n'
        st = st + '--- Grid ----'+'\n'
        st= st+ 'nx : ' + str(self.nx) + '\n'
        st= st+ 'ny : ' + str(self.ny) + '\n'
        st= st+ 'nlink : ' + str(self.ng*self.na) + '\n'
        st= st+ 'full grid : ' + str(self.mode) + '\n'
        st= st+ 'boundary (xmin,ymin,xmax,ymax) : ' + str(self.boundary) + '\n\n'
        return(st)

    def creategrid(self,full=True,boundary=[]):
        """ create a grid

        Parameters
        ----------

        full : boolean
            default (True) use all the layout area
        boundary : (xmin,ymin,xmax,ymax)
            if full is False the boundary argument is used

        """

        if full:
            mi=np.min(self.L.Gs.pos.values(),axis=0)+0.01
            ma=np.max(self.L.Gs.pos.values(),axis=0)-0.01
        else:
            assert boundary<>[]
            mi = np.array([boundary[0],boundary[1]])
            ma = np.array([boundary[2],boundary[3]])

        x = np.linspace(mi[0],ma[0],self.nx)
        y = np.linspace(mi[1],ma[1],self.ny)

        self.grid=np.array((list(np.broadcast(*np.ix_(x, y)))))



#    def coverold(self):
#        """ run the coverage calculation (Deprecated)
#
#        Parameters
#        ----------
#
#        lay_bound : bool
#            If True, the coverage is performed only inside the Layout
#            and clip the values of the grid chosen in coverage.ini
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            >> from pylayers.antprop.coverage import *
#            >> C = Coverage()
#            >> C.cover()
#            >> C.showPower()
#
#        Notes
#        -----
#
#        self.fGHz is an array it means that coverage is calculated at once
#        for a whole set of frequencies. In practice the center frequency of a
#        given standard channel.
#
#        This function is calling `Losst` which calculates Losses along a
#        straight path. In a future implementation we will
#        abstract the EM solver in order to make use of other calculation
#        approaches as full or partial Ray Tracing.
#
#        The following members variables are evaluated :
#
#        + freespace Loss @ fGHz   PL()  PathLoss (shoud be rename FS as free space) $
#        + prdbmo : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{odB}`
#        + prdbmp : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{pdB}`
#        + snro : SNR polar o (H)
#        + snrp : SNR polar p (H)
#
#        See Also
#        --------
#
#        pylayers.antprop.loss.Losst
#        pylayers.antprop.loss.PL
#
#        """
#
#        self.Lwo,self.Lwp,self.Edo,self.Edp = loss.Losst(self.L,self.fGHz,self.grid.T,self.tx)
#        self.freespace = loss.PL(self.fGHz,self.grid,self.tx)
#
#        self.prdbmo = self.ptdbm - self.freespace - self.Lwo
#        self.prdbmp = self.ptdbm - self.freespace - self.Lwp
#        self.snro = self.prdbmo - self.pndbm
#        self.snrp = self.prdbmp - self.pndbm

    def cover(self,polar='o',sinr=True,snr=True,best=True):
        """ run the coverage calculation

        Parameters
        ----------

        polar : string
            'o' | 'p'
        sinr : boolean
        snr  : boolean
        best : boolean

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a=C.show(typ='sinr')
            >>> plt.show()

        Notes
        -----

        self.fGHz is an array it means that coverage is calculated at once
        for a whole set of frequencies. In practice the center frequency of a
        given standard channel.

        This function is calling `Losst` which calculates Losses along a
        straight path. In a future implementation we will
        abstract the EM solver in order to make use of other calculation
        approaches as full or partial Ray Tracing.

        The following members variables are evaluated :

        + freespace Loss @ fGHz   PL()  PathLoss (shoud be rename FS as free space) $
        + prdbmo : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{odB}`
        + prdbmp : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{pdB}`
        + snro : SNR polar o (H)
        + snrp : SNR polar p (H)

        See Also
        --------

        pylayers.antprop.loss.Losst
        pylayers.antprop.loss.PL

        """

        # retrieving dimensions along the 3 axis
        na = self.na
        ng = self.ng
        nf = self.nf

        Lwo,Lwp,Edo,Edp = loss.Losst(self.L,self.fGHz,self.pa,self.pg,dB=False)
        if polar=='o':
            self.polar='o'
            self.Lw = Lwo.reshape(nf,ng,na)
            self.Ed = Edo.reshape(nf,ng,na)
        if polar=='p':
            self.polar='p'
            self.Lw = Lwp.reshape(nf,ng,na)
            self.Ed = Edp.reshape(nf,ng,na)

        freespace = loss.PL(self.fGHz,self.pa,self.pg,dB=False)
        self.freespace = freespace.reshape(nf,ng,na)

        # Warning we are assuming here all transmitters have the same
        # transmitting power (to be modified)
        # f x g x a

        # CmW : Received Power coverage in mW
        self.CmW = 10**(self.ptdbm[np.newaxis,...]/10.)*self.Lw*self.freespace

        if snr:
            self.snr()
        if sinr:
            self.sinr()
        if best:
            self.best()

    def snr(self):
        """ calculate snr
        """

        NmW = 10**(self.pndbm/10.)[np.newaxis,np.newaxis,:]

        self.snr = self.CmW/NmW

    def sinr(self):
        """ calculate sinr
        """

        na = self.na

        U = (np.ones((na,na))-np.eye(na))[np.newaxis,np.newaxis,:,:]

        ImW = np.einsum('ijkl,ijl->ijk',U,self.CmW)

        NmW = 10**(self.pndbm/10.)[np.newaxis,np.newaxis,:]

        self.sinr = self.CmW/(ImW+NmW)

    def best(self):
        """ determine best server map

        Notes
        -----

        C.bestsv

        """
        na = self.na
        ng = self.ng
        nf = self.nf
        # find best server regions
        V = self.CmW
        self.bestsv = np.zeros(nf*ng*na).reshape(nf,ng,na)
        for kf in range(nf):
            MaxV = np.max(V[kf,:,:],axis=1)
            for ka in range(na):
                u = np.where(V[kf,:,ka]==MaxV)
                self.bestsv[kf,u,ka]=ka+1


#    def showEd(self,polar='o',**kwargs):
#        """ shows a map of direct path excess delay
#
#        Parameters
#        ----------
#
#        polar : string
#        'o' | 'p'
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            >> from pylayers.antprop.coverage import *
#            >> C = Coverage()
#            >> C.cover()
#            >> C.showEd(polar='o')
#
#        """
#
#        if not kwargs.has_key('alphacy'):
#            kwargs['alphacy']=0.0
#        if not kwargs.has_key('colorcy'):
#            kwargs['colorcy']='w'
#        if not kwargs.has_key('nodes'):
#            kwargs['nodes']=False
#
#        fig,ax = self.L.showG('s',**kwargs)
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        cdict = {
#        'red'  :  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'green':  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'blue' :  ((0., 0.5, 0.5), (1., 1., 1.))
#        }
#        #generate the colormap with 1024 interpolated values
#        my_cmap = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
#
#
#        if polar=='o':
#            mcEdof = np.ma.masked_where(prdbm < self.rxsens,self.Edo)
#
#            cov=ax.imshow(mcEdof.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'jet',
#                             origin='lower')
#
#
#
#            # cov=ax.imshow(self.Edo.reshape((self.nx,self.ny)).T,
#            #           extent=(l,r,b,t),
#            #           origin='lower')
#            titre = "Map of LOS excess delay, polar orthogonal"
#
#        if polar=='p':
#            mcEdpf = np.ma.masked_where(prdbm < self.rxsens,self.Edp)
#
#            cov=ax.imshow(mcEdpf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'jet',
#                             origin='lower')
#
#            # cov=ax.imshow(self.Edp.reshape((self.nx,self.ny)).T,
#            #           extent=(l,r,b,t),
#            #           origin='lower')
#            titre = "Map of LOS excess delay, polar parallel"
#
#        ax.scatter(self.tx[0],self.tx[1],linewidth=0)
#        ax.set_title(titre)
#
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        clb = fig.colorbar(cov,cax)
#        clb.set_label('excess delay (ns)')
#
#        if self.show:
#            plt.show()
#        return fig,ax
#
#    def showPower(self,rxsens=True,nfl=True,polar='o',**kwargs):
#        """ show the map of received power
#
#        Parameters
#        ----------
#
#        rxsens : bool
#              clip the map with rx sensitivity set in self.rxsens
#        nfl : bool
#              clip the map with noise floor set in self.pndbm
#        polar : string
#            'o'|'p'
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            > from pylayers.antprop.coverage import *
#            > C = Coverage()
#            > C.cover()
#            > C.showPower()
#
#        """
#
#        if not kwargs.has_key('alphacy'):
#            kwargs['alphacy']=0.0
#        if not kwargs.has_key('colorcy'):
#            kwargs['colorcy']='w'
#        if not kwargs.has_key('nodes'):
#            kwargs['nodes']=False
#        fig,ax = self.L.showG('s',**kwargs)
#
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
##        tCM = plt.cm.get_cmap('jet')
##        tCM._init()
##        alphas = np.abs(np.linspace(.0,1.0, tCM.N))
##        tCM._lut[:-3,-1] = alphas
#
#        title='Map of received power - Pt = ' + str(self.ptdbm) + ' dBm'+str(' fGHz =') + str(self.fGHz) + ' polar = '+polar
#
#        cdict = {
#        'red'  :  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'green':  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'blue' :  ((0., 0.5, 0.5), (1., 1., 1.))
#        }
#
#        if not kwargs.has_key('cmap'):
#        # generate the colormap with 1024 interpolated values
#            cmap = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
#        else:
#            cmap = kwargs['cmap']
#        #my_cmap = cm.copper
#
#
#        if rxsens :
#
#            ## values between the rx sensitivity and noise floor
#            mcPrf = np.ma.masked_where((prdbm > self.rxsens)
#                                     & (prdbm < self.pndbm),prdbm)
#            # mcPrf = np.ma.masked_where((prdbm > self.rxsens) ,prdbm)
#
#            cov1 = ax.imshow(mcPrf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = cm.copper,
#                             vmin=self.rxsens,origin='lower')
#
#            ### values above the sensitivity
#            mcPrs = np.ma.masked_where(prdbm < self.rxsens,prdbm)
#            cov = ax.imshow(mcPrs.reshape((self.nx,self.ny)).T,
#                            extent=(l,r,b,t),
#                            cmap = cmap,
#                            vmin=self.rxsens,origin='lower')
#            title=title + '\n black : Pr (dBm) < %.2f' % self.rxsens + ' dBm'
#
#        else :
#            cov=ax.imshow(prdbm.reshape((self.nx,self.ny)).T,
#                          extent=(l,r,b,t),
#                          cmap = cmap,
#                          vmin=self.pndbm,origin='lower')
#
#        if nfl:
#            ### values under the noise floor
#            ### we first clip the value below the noise floor
#            cl = np.nonzero(prdbm<=self.pndbm)
#            cPr = prdbm
#            cPr[cl] = self.pndbm
#            mcPruf = np.ma.masked_where(cPr > self.pndbm,cPr)
#            cov2 = ax.imshow(mcPruf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'binary',
#                             vmax=self.pndbm,origin='lower')
#            title=title + '\n white : Pr (dBm) < %.2f' % self.pndbm + ' dBm'
#
#
#        ax.scatter(self.tx[0],self.tx[1],s=10,c='k',linewidth=0)
#
#        ax.set_title(title)
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        clb = fig.colorbar(cov,cax)
#        clb.set_label('Power (dBm)')
#
#        if self.show:
#            plt.show()
#
#        return fig,ax
#
#
#    def showTransistionRegion(self,polar='o'):
#        """
#
#        Notes
#        -----
#
#        See  : "Analyzing the Transitional Region in Low Power Wireless Links"
#                Marco Zuniga and Bhaskar Krishnamachari
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            > from pylayers.antprop.coverage import *
#            > C = Coverage()
#            > C.cover()
#            > C.showTransitionRegion()
#
#        """
#
#        frameLength = self.framelengthbytes
#
#        PndBm = self.pndbm
#        gammaU = 10*np.log10(-1.28*np.log(2*(1-0.9**(1./(8*frameLength)))))
#        gammaL = 10*np.log10(-1.28*np.log(2*(1-0.1**(1./(8*frameLength)))))
#
#        PrU = PndBm + gammaU
#        PrL = PndBm + gammaL
#
#        fig,ax = self.L.showGs()
#
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
#        zones = np.zeros(np.shape(prdbm))
#        #pdb.set_trace()
#
#        uconnected  = np.nonzero(prdbm>PrU)
#        utransition = np.nonzero((prdbm < PrU)&(prdbm > PrL))
#        udisconnected = np.nonzero(prdbm < PrL)
#
#        zones[uconnected] = 1
#        zones[utransition] = (prdbm[utransition]-PrL)/(PrU-PrL)
#        cov = ax.imshow(zones.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'BuGn',origin='lower')
#
#        title='PDR region'
#        ax.scatter(self.tx[0],self.tx[1],linewidth=0)
#
#        ax.set_title(title)
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        fig.colorbar(cov,cax)
#        if self.show:
#            plt.show()
#
    def show(self,**kwargs):
        """ show coverage

        Parameters
        ----------

        typ : string
            'pr' | 'sinr' | 'capacity' | 'loss' | 'best'
        grid : boolean
        best : boolean
            draw best server contour if True
        f : int
            frequency index
        a : int
            access point index (-1 all access point)

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover(polar='o')
            >>> f,a = C.show(typ='pr')
            >>> plt.show()
            >>> f,a = C.show(typ='best')
            >>> plt.show()
            >>> f,a = C.show(typ='loss')
            >>> plt.show()
            >>> f,a = C.show(typ='sinr')
            >>> plt.show()

        """
        defaults = { 'typ': 'pr',
                     'grid': False,
                     'f' : 0,
                     'a' :-1,
                     'db':True,
                     'cmap' :cm.jet,
                     'best':True
                   }

        title = self.dap[0].s.name+ ' : '
        for k in defaults:
            if k not in kwargs:
                kwargs[k]=defaults[k]

        if 'fig' in kwargs:
            fig,ax=self.L.showG('s',fig=kwargs['fig'])
        else:
            fig,ax=self.L.showG('s')

        # plot the grid
        if kwargs['grid']:
            for k in self.dap:
                p = self.dap[k].p
                ax.plot(p[0],p[1],'or')

        f = kwargs['f']
        a = kwargs['a']
        typ = kwargs['typ']
        best = kwargs['best']

        dB = kwargs['db']

        # setting the grid

        l = self.grid[0,0]
        r = self.grid[-1,0]
        b = self.grid[0,1]
        t = self.grid[-1,-1]

        if typ=='best':
            title = title + 'Best server'+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+self.polar
            for ka in range(self.na):
                bestsv =  self.bestsv[f,:,ka]
                m = np.ma.masked_where(bestsv == 0,bestsv)
                W = m.reshape(self.nx,self.ny).T
                ax.imshow(W, extent=(l,r,b,t),
                            origin='lower',
                            vmin=1,
                            vmax=self.na+1)
            ax.set_title(title)
        else:
            if typ=='sinr':
                title = title + 'SINR : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+self.polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                V = self.sinr

            if typ=='snr':
                title = title + 'SNR : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+self.polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                V = self.snr

            if typ=='capacity':
                title = title + 'Capacity : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+self.polar
                legcb = 'Mbit/s'
                V = self.bmhz[np.newaxis,np.newaxis,:]*np.log(1+self.sinr)/np.log(2)

            if typ=='pr':
                title = title + 'Pr : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+self.polar
                if dB:
                    legcb = 'dBm'
                else:
                    lgdcb = 'mW'
                V = self.CmW

            if typ=='loss':
                title = title + 'Loss : '+' fc = '+str(self.fGHz[f])+' GHz'+ ' polar : '+self.polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'

                V = self.Lw*self.freespace

            if a == -1:
                V = np.max(V[f,:,:],axis=1)
            else:
                V = V[f,:,a]

            # reshaping the data on the grid
            U = V.reshape((self.nx,self.ny)).T
            if dB:
                U = 10*np.log10(U)

            if 'vmin' in kwargs:
                vmin = kwargs['vmin']
            else:
                vmin = U.min()

            if 'vmax' in kwargs:
                vmax = kwargs['vmax']
            else:
                vmax = U.max()

            img = ax.imshow(U,
                            extent=(l,r,b,t),
                            origin='lower',
                            vmin = vmin,
                            vmax = vmax,
                            cmap = kwargs['cmap'])

            for k in range(self.na):
                ax.annotate(str(k),xy=(self.pa[0,k],self.pa[1,k]))
            ax.set_title(title)

            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            clb = fig.colorbar(img,cax)
            clb.set_label(legcb)
            if best:
                ax.contour(np.sum(self.bestsv,axis=2)[f,:].reshape(self.nx,self.ny).T,extent=(l,r,b,t),linestyles='dotted')

        # display access points
        ax.scatter(self.pa[0,:],self.pa[1,:],s=10,c='k',linewidth=0)

        return(fig,ax)
예제 #17
0
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
ax2 = fig.add_subplot(323)
L.showG(fig=fig, ax=ax2, graph='t')
plt.title('Topological graph')
#plt.savefig('graphGt.png')
# build graph of rooms
ax3 = fig.add_subplot(324)
L.showG(fig=fig, ax=ax3, graph='r')
#plt.savefig('graphGr.png')
예제 #18
0
class Coverage(PyLayers):
    """ Handle Layout Coverage

        Methods
        -------

        creategrid()
            create a uniform grid for evaluating losses
        cover()
            run the coverage calculation
        showPower()
            display the map of received power
        showLoss()
            display the map of losses


        Attributes
        ----------

        All attributes are read from fileini ino the ini directory of the
        current project

        _fileini
            default coverage.ini

        L     : a Layout
        nx    : number of point on x
        ny    : number of point on y
        tx    : transmitter position
        txpe  : transmitter power emmission level
        show  : boolean for automatic display power map
        na : number of access point

    """
    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 __repr__(self):
        st = ''
        if self.typ == 'indoor':
            st = st + 'Layout file : ' + self.L._filename + '\n\n'
            st = st + '-----list of Access Points ------' + '\n'
            for k in self.dap:
                st = st + self.dap[k].__repr__() + '\n'
            st = st + '-----Rx------' + '\n'
            st = st + 'temperature (K) : ' + str(self.temperaturek) + '\n'
            st = st + 'noisefactor (dB) : ' + str(self.noisefactordb) + '\n\n'
            st = st + '--- Grid ----' + '\n'
            st = st + 'mode : ' + str(self.mode) + '\n'
            if self.mode != 'file':
                st = st + 'nx : ' + str(self.nx) + '\n'
                st = st + 'ny : ' + str(self.ny) + '\n'
            if self.mode == 'zone':
                st = st + 'boundary (xmin,ymin,xmax,ymax) : ' + str(
                    self.boundary) + '\n\n'
            if self.mode == 'file':
                st = st + ' filename : ' + self.filespa + '\n'
        return (st)

    def creategrid(self, mode='full', boundary=[], _fileini=''):
        """ create a grid

        Parameters
        ----------

        full : boolean
            default (True) use all the layout area
        boundary : (xmin,ymin,xmax,ymax)
            if full is False the boundary argument is used

        """

        if mode == "file":
            self.RN = RadioNode(name='',
                                typ='rx',
                                _fileini=_fileini,
                                _fileant='def.vsh3')
            self.grid = self.RN.position[0:2, :].T
        else:
            if mode == "full":
                mi = np.min(np.array(list(self.L.Gs.pos.values())),
                            axis=0) + 0.01
                ma = np.max(np.array(list(self.L.Gs.pos.values())),
                            axis=0) - 0.01
            if mode == "zone":
                assert boundary != []
                mi = np.array([boundary[0], boundary[1]])
                ma = np.array([boundary[2], boundary[3]])

            x = np.linspace(mi[0], ma[0], self.nx)
            y = np.linspace(mi[1], ma[1], self.ny)

            self.grid = np.array((list(np.broadcast(*np.ix_(x, y)))))

        self.ng = self.grid.shape[0]

    def where1(self):
        """
        Unfinished : Not sure this is the right place (too specific)
        """
        M1 = UWBMeasure(1)
        self.dap = {}
        self.dap[1] = {}
        self.dap[2] = {}
        self.dap[3] = {}
        self.dap[4] = {}
        self.dap[1]['p'] = M1.rx[1, 0:2]
        self.dap[2]['p'] = M1.rx[1, 0:2]
        self.dap[3]['p'] = M1.rx[1, 0:2]
        self.dap[4]['p'] = M1.rx[1, 0:2]
        for k in range(300):
            try:
                M = UWBMeasure(k)
                tx = M.tx
                self.grid = np.vstack((self.grid, tx[0:2]))
                D = M.rx - tx[np.newaxis, :]
                D2 = D * D
                dist = np.sqrt(np.sum(D2, axis=1))[1:]
                Emax = M.Emax()
                Etot = M.Etot()[0]
                try:
                    td1 = np.hstack((td1, dist[0]))
                    td2 = np.hstack((td2, dist[1]))
                    td3 = np.hstack((td3, dist[2]))
                    td4 = np.hstack((td4, dist[3]))
                    te1 = np.hstack((te1, Emax[0]))
                    te2 = np.hstack((te2, Emax[1]))
                    te3 = np.hstack((te3, Emax[2]))
                    te4 = np.hstack((te4, Emax[3]))
                    tt1 = np.hstack((tt1, Etot[0]))
                    tt2 = np.hstack((tt2, Etot[1]))
                    tt3 = np.hstack((tt3, Etot[2]))
                    tt4 = np.hstack((tt4, Etot[3]))
                    #tdist = np.hstack((tdist,dist))
                    #te = np.hstack((te,Emax))
                except:
                    td1 = np.array(dist[0])
                    td2 = np.array(dist[1])
                    td3 = np.array(dist[2])
                    td4 = np.array(dist[3])
                    te1 = np.array(Emax[0])
                    te2 = np.array(Emax[1])
                    te3 = np.array(Emax[2])
                    te4 = np.array(Emax[3])
                    tt1 = np.array(Etot[0])
                    tt2 = np.array(Etot[1])
                    tt3 = np.array(Etot[2])
                    tt4 = np.array(Etot[3])
            except:
                pass

    def cover(self, **kwargs):
        """ run the coverage calculation

        Parameters
        ----------

        sinr : boolean
        snr  : boolean
        best : boolean
        size : integer 
            size of grid points block

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a = C.show(typ='sinr',figsize=(10,8))
            >>> plt.show()

        Notes
        -----

        self.fGHz is an array, it means that Coverage is calculated at once
        for a whole set of frequencies. In practice, it would be the center
        frequency of a given standard channel.

        This function is calling `loss.Losst` which calculates Losses along a
        straight path.

        In a future implementation we will
        abstract the EM solver in order to make use of other calculation
        approaches as a full or partial Ray Tracing.

        The following members variables are evaluated :

        + freespace Loss @ fGHz   PL()  PathLoss (shoud be rename FS as free space) $
        + prdbmo : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{odB}`
        + prdbmp : Received power in dBm .. math:`P_{rdBm} =P_{tdBm} - L_{pdB}`
        + snro : SNR polar o (H)
        + snrp : SNR polar p (H)

        See Also
        --------

        pylayers.antprop.loss.Losst
        pylayers.antprop.loss.PL

        """

        sizebloc = kwargs.pop('size', 100)

        #
        # select active AP
        #
        lactiveAP = []

        try:
            del self.aap
            del self.ptdbm
        except:
            pass

        # Boltzmann constant
        kB = 1.3806503e-23

        #
        # Loop over access points
        #    set parameter of each active ap
        #        p
        #        PtdBm
        #        BMHz

        for iap in self.dap:
            if self.dap[iap]['on']:
                lactiveAP.append(iap)
                # set frequency for each AP
                fGHz = self.dap[iap].s.fcghz
                self.fGHz = np.unique(np.hstack((self.fGHz, fGHz)))
                apchan = self.dap[iap]['chan']
                #
                # stacking  AP position Power Bandwidth
                #
                try:
                    self.aap = np.vstack((self.aap, self.dap[iap]['p']))
                    self.ptdbm = np.vstack(
                        (self.ptdbm, self.dap[iap]['PtdBm']))
                    self.bmhz = np.vstack(
                        (self.bmhz, self.dap[iap].s.chan[apchan[0]]['BMHz']))
                except:
                    self.aap = self.dap[iap]['p']
                    self.ptdbm = np.array(self.dap[iap]['PtdBm'])
                    self.bmhz = np.array(
                        self.dap[iap].s.chan[apchan[0]]['BMHz'])

        self.nf = len(self.fGHz)
        PnW = np.array((10**(self.noisefactordb / 10.)) * kB *
                       self.temperaturek * self.bmhz * 1e6)
        # Evaluate Noise Power (in dBm)

        self.pndbm = np.array(10 * np.log10(PnW) + 30)

        #lchan = map(lambda x: self.dap[x]['chan'],lap)
        #apchan = zip(self.dap.keys(),lchan)
        #self.bmhz = np.array(map(lambda x: self.dap[x[0]].s.chan[x[1][0]]['BMHz']*len(x[1]),apchan))

        self.ptdbm = self.ptdbm.T
        self.pndbm = self.pndbm.T
        # creating all links
        # from all grid point to all ap
        #

        if len(self.pndbm.shape) == 0:
            self.ptdbm = self.ptdbm.reshape(1, 1)
            self.pndbm = self.pndbm.reshape(1, 1)

        self.nf = len(self.fGHz)
        Nbloc = self.ng // sizebloc

        r1 = np.arange(0, (Nbloc + 1) * sizebloc, sizebloc)
        r1 = np.append(r1, self.ng)
        lblock = list(zip(r1[0:-1], r1[1:]))

        for bg in lblock:
            p = product(range(bg[0], bg[1]), lactiveAP)
            #
            # pa : access point ,3
            # pg : grid point ,2
            #
            # 1 x na

            for k in p:
                pg = self.grid[k[0], :]
                pa = np.array(self.dap[k[1]]['p'])
                # exemple with 3 AP
                # 321 0
                # 321 1
                # 321 2
                # 322 0
                try:
                    self.pa = np.vstack((self.pa, pa))
                except:
                    self.pa = pa
                try:
                    self.pg = np.vstack((self.pg, pg))
                except:
                    self.pg = pg

            self.pa = self.pa.T
            shpa = self.pa.shape
            shpg = self.pg.shape

            # extend in 3 dimensions if necessary

            if shpa[0] != 3:
                self.pa = np.vstack((self.pa, np.ones(shpa[1])))

            self.pg = self.pg.T
            self.pg = np.vstack((self.pg, self.zgrid * np.ones(shpg[0])))

            # retrieving dimensions along the 3 axis
            # a : number of active access points
            # g : grid block
            # f : frequency

            na = len(lactiveAP)
            self.na = na
            ng = self.ng
            nf = self.nf

            # calculate antenna gain from ap to grid point
            #
            # loop over all AP
            #
            k = 0
            for iap in self.dap:
                # select only one access point
                # n
                u = na * np.arange(0, bg[1] - bg[0], 1).astype('int') + k
                if self.dap[iap]['on']:
                    pa = self.pa[:, u]
                    pg = self.pg[:, u]
                    azoffset = self.dap[iap]['phideg'] * np.pi / 180.
                    # the eval function of antenna should also specify polar
                    self.dap[iap].A.eval(fGHz=self.fGHz,
                                         pt=pa,
                                         pr=pg,
                                         azoffset=azoffset)
                    gain = (self.dap[iap].A.G).T
                    # to handle omnidirectional antenna (nf,1,1)
                    if gain.shape[1] == 1:
                        gain = np.repeat(gain, bg[1] - bg[0], axis=1)
                    if k == 0:
                        tgain = gain[:, :, None]
                    else:
                        tgain = np.dstack((tgain, gain[:, :, None]))
                    k = k + 1

            tgain = tgain.reshape(nf, tgain.shape[1] * tgain.shape[2])
            Lwo, Lwp, Edo, Edp = loss.Losst(self.L,
                                            self.fGHz,
                                            self.pa,
                                            self.pg,
                                            dB=False)
            freespace = loss.PL(self.fGHz, self.pa, self.pg, dB=False)
            try:
                self.Lwo = np.hstack((self.Lwo, Lwo))
                self.Lwp = np.hstack((self.Lwp, Lwp))
                self.Edo = np.hstack((self.Edo, Edo))
                self.Edp = np.hstack((self.Edp, Edp))
                self.freespace = np.hstack((self.freespace, freespace))
                self.tgain = np.hstack((self.tgain, tgain))
            except:
                self.Lwo = Lwo
                self.Lwp = Lwp
                self.Edo = Edo
                self.Edp = Edp
                self.freespace = freespace
                self.tgain = tgain

        self.Lwo = self.Lwo.reshape(nf, ng, na)
        self.Edo = self.Edo.reshape(nf, ng, na)
        self.Lwp = self.Lwp.reshape(nf, ng, na)
        self.Edp = self.Edp.reshape(nf, ng, na)
        self.tgain = self.tgain.reshape(nf, ng, na)

        self.freespace = self.freespace.reshape(nf, ng, na)

        # transmitting power
        # f x g x a

        # CmW : Received Power coverage in mW
        # TODO : tgain in o and p polarization
        self.CmWo = 10**(self.ptdbm[np.newaxis, ...] /
                         10.) * self.Lwo * self.freespace * self.tgain
        self.CmWp = 10**(self.ptdbm[np.newaxis, ...] /
                         10.) * self.Lwp * self.freespace * self.tgain
        #self.CmWo = 10**(self.ptdbm[np.newaxis,...]/10.)*self.Lwo*self.freespace
        #self.CmWp = 10**(self.ptdbm[np.newaxis,...]/10.)*self.Lwp*self.freespace

        if self.snr:
            self.evsnr()
        if self.sinr:
            self.evsinr()
        if self.best:
            self.evbestsv()

    def evsnr(self):
        """ calculates signal to noise ratio
        """

        NmW = 10**(self.pndbm / 10.)[np.newaxis, :]

        self.snro = self.CmWo / NmW
        self.snrp = self.CmWp / NmW
        self.snr = True

    def evsinr(self):
        """ calculates sinr

        """

        # na : number of access point
        na = self.na

        # U : 1 x 1 x na x na
        U = (np.ones((na, na)) - np.eye(na))[np.newaxis, np.newaxis, :, :]

        # CmWo : received power in mW orthogonal polarization
        # CmWp : received power in mW parallel polarization

        ImWo = np.einsum('ijkl,ijl->ijk', U, self.CmWo)
        ImWp = np.einsum('ijkl,ijl->ijk', U, self.CmWp)

        NmW = 10**(self.pndbm / 10.)[np.newaxis, :]

        self.sinro = self.CmWo / (ImWo + NmW)
        self.sinrp = self.CmWp / (ImWp + NmW)

        self.sinr = True

    def evbestsv(self):
        """ determine the best server map

        Notes
        -----

        C.bestsv

        """
        na = self.na
        ng = self.ng
        nf = self.nf
        # find best server regions
        Vo = self.CmWo
        Vp = self.CmWp
        self.bestsvo = np.empty(nf * ng * na).reshape(nf, ng, na)
        self.bestsvp = np.empty(nf * ng * na).reshape(nf, ng, na)
        for kf in range(nf):
            MaxVo = np.max(Vo[kf, :, :], axis=1)
            MaxVp = np.max(Vp[kf, :, :], axis=1)
            for ka in range(na):
                uo = np.where(Vo[kf, :, ka] == MaxVo)
                up = np.where(Vp[kf, :, ka] == MaxVp)
                self.bestsvo[kf, uo, ka] = ka + 1
                self.bestsvp[kf, up, ka] = ka + 1
        self.best = True

#    def showEd(self,polar='o',**kwargs):
#        """ shows a map of direct path excess delay
#
#        Parameters
#        ----------
#
#        polar : string
#        'o' | 'p'
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            >> from pylayers.antprop.coverage import *
#            >> C = Coverage()
#            >> C.cover()
#            >> C.showEd(polar='o')
#
#        """
#
#        if not kwargs.has_key('alphacy'):
#            kwargs['alphacy']=0.0
#        if not kwargs.has_key('colorcy'):
#            kwargs['colorcy']='w'
#        if not kwargs.has_key('nodes'):
#            kwargs['nodes']=False
#
#        fig,ax = self.L.showG('s',**kwargs)
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        cdict = {
#        'red'  :  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'green':  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'blue' :  ((0., 0.5, 0.5), (1., 1., 1.))
#        }
#        #generate the colormap with 1024 interpolated values
#        my_cmap = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
#
#
#        if polar=='o':
#            mcEdof = np.ma.masked_where(prdbm < self.rxsens,self.Edo)
#
#            cov=ax.imshow(mcEdof.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'jet',
#                             origin='lower')
#
#
#
#            # cov=ax.imshow(self.Edo.reshape((self.nx,self.ny)).T,
#            #           extent=(l,r,b,t),
#            #           origin='lower')
#            titre = "Map of LOS excess delay, polar orthogonal"
#
#        if polar=='p':
#            mcEdpf = np.ma.masked_where(prdbm < self.rxsens,self.Edp)
#
#            cov=ax.imshow(mcEdpf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'jet',
#                             origin='lower')
#
#            # cov=ax.imshow(self.Edp.reshape((self.nx,self.ny)).T,
#            #           extent=(l,r,b,t),
#            #           origin='lower')
#            titre = "Map of LOS excess delay, polar parallel"
#
#        ax.scatter(self.tx[0],self.tx[1],linewidth=0)
#        ax.set_title(titre)
#
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        clb = fig.colorbar(cov,cax)
#        clb.set_label('excess delay (ns)')
#
#        if self.show:
#            plt.show()
#        return fig,ax
#
#    def showPower(self,rxsens=True,nfl=True,polar='o',**kwargs):
#        """ show the map of received power
#
#        Parameters
#        ----------
#
#        rxsens : bool
#              clip the map with rx sensitivity set in self.rxsens
#        nfl : bool
#              clip the map with noise floor set in self.pndbm
#        polar : string
#            'o'|'p'
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            > from pylayers.antprop.coverage import *
#            > C = Coverage()
#            > C.cover()
#            > C.showPower()
#
#        """
#
#        if not kwargs.has_key('alphacy'):
#            kwargs['alphacy']=0.0
#        if not kwargs.has_key('colorcy'):
#            kwargs['colorcy']='w'
#        if not kwargs.has_key('nodes'):
#            kwargs['nodes']=False
#        fig,ax = self.L.showG('s',**kwargs)
#
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
##        tCM = plt.cm.get_cmap('jet')
##        tCM._init()
##        alphas = np.abs(np.linspace(.0,1.0, tCM.N))
##        tCM._lut[:-3,-1] = alphas
#
#        title='Map of received power - Pt = ' + str(self.ptdbm) + ' dBm'+str(' fGHz =') + str(self.fGHz) + ' polar = '+polar
#
#        cdict = {
#        'red'  :  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'green':  ((0., 0.5, 0.5), (1., 1., 1.)),
#        'blue' :  ((0., 0.5, 0.5), (1., 1., 1.))
#        }
#
#        if not kwargs.has_key('cmap'):
#        # generate the colormap with 1024 interpolated values
#            cmap = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
#        else:
#            cmap = kwargs['cmap']
#        #my_cmap = cm.copper
#
#
#        if rxsens :
#
#            ## values between the rx sensitivity and noise floor
#            mcPrf = np.ma.masked_where((prdbm > self.rxsens)
#                                     & (prdbm < self.pndbm),prdbm)
#            # mcPrf = np.ma.masked_where((prdbm > self.rxsens) ,prdbm)
#
#            cov1 = ax.imshow(mcPrf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = cm.copper,
#                             vmin=self.rxsens,origin='lower')
#
#            ### values above the sensitivity
#            mcPrs = np.ma.masked_where(prdbm < self.rxsens,prdbm)
#            cov = ax.imshow(mcPrs.reshape((self.nx,self.ny)).T,
#                            extent=(l,r,b,t),
#                            cmap = cmap,
#                            vmin=self.rxsens,origin='lower')
#            title=title + '\n black : Pr (dBm) < %.2f' % self.rxsens + ' dBm'
#
#        else :
#            cov=ax.imshow(prdbm.reshape((self.nx,self.ny)).T,
#                          extent=(l,r,b,t),
#                          cmap = cmap,
#                          vmin=self.pndbm,origin='lower')
#
#        if nfl:
#            ### values under the noise floor
#            ### we first clip the value below the noise floor
#            cl = np.nonzero(prdbm<=self.pndbm)
#            cPr = prdbm
#            cPr[cl] = self.pndbm
#            mcPruf = np.ma.masked_where(cPr > self.pndbm,cPr)
#            cov2 = ax.imshow(mcPruf.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'binary',
#                             vmax=self.pndbm,origin='lower')
#            title=title + '\n white : Pr (dBm) < %.2f' % self.pndbm + ' dBm'
#
#
#        ax.scatter(self.tx[0],self.tx[1],s=10,c='k',linewidth=0)
#
#        ax.set_title(title)
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        clb = fig.colorbar(cov,cax)
#        clb.set_label('Power (dBm)')
#
#        if self.show:
#            plt.show()
#
#        return fig,ax
#
#
#    def showTransistionRegion(self,polar='o'):
#        """
#
#        Notes
#        -----
#
#        See  : "Analyzing the Transitional Region in Low Power Wireless Links"
#                Marco Zuniga and Bhaskar Krishnamachari
#
#        Examples
#        --------
#
#        .. plot::
#            :include-source:
#
#            > from pylayers.antprop.coverage import *
#            > C = Coverage()
#            > C.cover()
#            > C.showTransitionRegion()
#
#        """
#
#        frameLength = self.framelengthbytes
#
#        PndBm = self.pndbm
#        gammaU = 10*np.log10(-1.28*np.log(2*(1-0.9**(1./(8*frameLength)))))
#        gammaL = 10*np.log10(-1.28*np.log(2*(1-0.1**(1./(8*frameLength)))))
#
#        PrU = PndBm + gammaU
#        PrL = PndBm + gammaL
#
#        fig,ax = self.L.showGs()
#
#        l = self.grid[0,0]
#        r = self.grid[-1,0]
#        b = self.grid[0,1]
#        t = self.grid[-1,-1]
#
#        if polar=='o':
#            prdbm=self.prdbmo
#        if polar=='p':
#            prdbm=self.prdbmp
#
#        zones = np.zeros(np.shape(prdbm))
#        #pdb.set_trace()
#
#        uconnected  = np.nonzero(prdbm>PrU)
#        utransition = np.nonzero((prdbm < PrU)&(prdbm > PrL))
#        udisconnected = np.nonzero(prdbm < PrL)
#
#        zones[uconnected] = 1
#        zones[utransition] = (prdbm[utransition]-PrL)/(PrU-PrL)
#        cov = ax.imshow(zones.reshape((self.nx,self.ny)).T,
#                             extent=(l,r,b,t),cmap = 'BuGn',origin='lower')
#
#        title='PDR region'
#        ax.scatter(self.tx[0],self.tx[1],linewidth=0)
#
#        ax.set_title(title)
#        divider = make_axes_locatable(ax)
#        cax = divider.append_axes("right", size="5%", pad=0.05)
#        fig.colorbar(cov,cax)
#        if self.show:
#            plt.show()
#

    def plot(self, **kwargs):
        """
        """
        defaults = {
            'typ': 'pr',
            'grid': False,
            'f': 0,
            'a': 0,
            'db': True,
            'label': '',
            'pol': 'p',
            'col': 'b'
        }
        for k in defaults:
            if k not in kwargs:
                kwargs[k] = defaults[k]

        if 'fig' in kwargs:
            fig = kwargs['fig']
        else:
            fig = plt.figure()

        if 'ax' in kwargs:
            ax = kwargs['ax']
        else:
            ax = fig.add_subplot(111)

        if kwargs['typ'] == 'pr':
            if kwargs['a'] != -1:
                if kwargs['pol'] == 'p':
                    U = self.CmWp[kwargs['f'], :, kwargs['a']]
                if kwargs['pol'] == 'o':
                    U = self.CmWo[kwargs['f'], :, kwargs['a']]
            else:
                if kwargs['pol'] == 'p':
                    U = self.CmWp[kwargs['f'], :, :].reshape(self.na * self.ng)
                else:
                    U = self.CmWo[kwargs['f'], :, :].reshape(self.na * self.ng)
            if kwargs['db']:
                U = 10 * np.log10(U)

        D = np.sqrt(np.sum((self.pa - self.pg) * (self.pa - self.pg), axis=0))
        if kwargs['a'] != -1:
            D = D.reshape(self.ng, self.na)
            ax.semilogx(D[:, kwargs['a']],
                        U,
                        '.',
                        color=kwargs['col'],
                        label=kwargs['label'])
        else:
            ax.semilogx(D, U, '.', color=kwargs['col'], label=kwargs['label'])

        return fig, ax

    def show(self, **kwargs):
        """ show coverage

        Parameters
        ----------

        typ : string
            'pr' | 'sinr' | 'capacity' | 'loss' | 'best' | 'egd' | 'ref'
        grid : boolean
        polar : string
            'o' | 'p'
        best : boolean
            draw best server contour if True
        f : int
            frequency index
        a : int
            access point index (-1 all access point)

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> f,a = C.show(typ='pr',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='best',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='loss',figsize=(10,8))
            >>> plt.show()
            >>> f,a = C.show(typ='sinr',figsize=(10,8))
            >>> plt.show()

        See Also
        --------

        pylayers.gis.layout.Layout.showG

        """
        defaults = {
            'typ': 'pr',
            'grid': False,
            'polar': 'p',
            'scale': 30,
            'f': 0,
            'a': -1,
            'db': True,
            'cmap': cm.jet,
            'best': False,
            'title': ''
        }

        for k in defaults:
            if k not in kwargs:
                kwargs[k] = defaults[k]

        title = self.dap[list(
            self.dap.keys())[0]].s.name + ' : ' + kwargs['title'] + " :"
        polar = kwargs['polar']
        best = kwargs['best']
        scale = kwargs['scale']

        assert polar in ['p', 'o'], "polar wrongly defined in show coverage"

        if 'fig' in kwargs:
            if 'ax' in kwargs:
                fig, ax = self.L.showG('s', fig=kwargs['fig'], ax=kwargs['ax'])
            else:
                fig, ax = self.L.showG('s', fig=kwargs['fig'])
        else:
            if 'figsize' in kwargs:
                fig, ax = self.L.showG('s', figsize=kwargs['figsize'])
            else:
                fig, ax = self.L.showG('s')

        # plot the grid
        if kwargs['grid']:
            for k in self.dap:
                p = self.dap[k].p
                ax.plot(p[0], p[1], 'or')

        f = kwargs['f']
        a = kwargs['a']
        typ = kwargs['typ']
        assert typ in [
            'best', 'egd', 'sinr', 'snr', 'capacity', 'pr', 'loss', 'ref'
        ], "typ unknown in show coverage"
        best = kwargs['best']

        dB = kwargs['db']

        # setting the grid

        l = self.grid[0, 0]
        r = self.grid[-1, 0]
        b = self.grid[0, 1]
        t = self.grid[-1, -1]

        if typ == 'best' and self.best:
            title = title + 'Best server' + ' fc = ' + str(
                self.fGHz[f]) + ' GHz' + ' polar : ' + polar
            for ka in range(self.na):
                if polar == 'p':
                    bestsv = self.bestsvp[f, :, ka]
                if polar == 'o':
                    bestsv = self.bestsvo[f, :, ka]
                m = np.ma.masked_where(bestsv == 0, bestsv)
                if self.mode != 'file':
                    W = m.reshape(self.nx, self.ny).T
                    ax.imshow(W,
                              extent=(l, r, b, t),
                              origin='lower',
                              vmin=1,
                              vmax=self.na + 1)
                else:
                    ax.scatter(self.grid[:, 0],
                               self.grid[:, 1],
                               c=m,
                               s=scale,
                               linewidth=0)
            ax.set_title(title)
        else:
            if typ == 'egd':
                title = title + 'excess group delay : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                V = self.Ed
                dB = False
                legcb = 'Delay (ns)'
            if typ == 'sinr':
                title = title + 'SINR : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar == 'o':
                    V = self.sinro
                if polar == 'p':
                    V = self.sinrp
            if typ == 'snr':
                title = title + 'SNR : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar == 'o':
                    V = self.snro
                if polar == 'p':
                    V = self.snrp
            if typ == 'capacity':
                title = title + 'Capacity : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                legcb = 'Mbit/s'
                if polar == 'o':
                    V = self.bmhz.T[np.newaxis, :] * np.log(
                        1 + self.sinro) / np.log(2)
                if polar == 'p':
                    V = self.bmhz.T[np.newaxis, :] * np.log(
                        1 + self.sinrp) / np.log(2)
            if typ == "pr":
                title = title + 'Pr : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dBm'
                else:
                    lgdcb = 'mW'
                if polar == 'o':
                    V = self.CmWo
                if polar == 'p':
                    V = self.CmWp

            if typ == "ref":
                title = kwargs['title']
                V = 10**(self.ref / 10)
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'

            if typ == "loss":
                title = title + 'Loss : ' + ' fc = ' + str(
                    self.fGHz[f]) + ' GHz' + ' polar : ' + polar
                if dB:
                    legcb = 'dB'
                else:
                    legcb = 'Linear scale'
                if polar == 'o':
                    V = self.Lwo * self.freespace
                if polar == 'p':
                    V = self.Lwp * self.freespace

            if a == -1:
                V = np.max(V[f, :, :], axis=1)
            else:
                V = V[f, :, a]

            # reshaping the data on the grid
            if self.mode != 'file':
                U = V.reshape((self.nx, self.ny)).T
            else:
                U = V

            if dB:
                U = 10 * np.log10(U)

            if 'vmin' in kwargs:
                vmin = kwargs['vmin']
            else:
                vmin = U.min()

            if 'vmax' in kwargs:
                vmax = kwargs['vmax']
            else:
                vmax = U.max()

            if self.mode != 'file':
                img = ax.imshow(U,
                                extent=(l, r, b, t),
                                origin='lower',
                                vmin=vmin,
                                vmax=vmax,
                                cmap=kwargs['cmap'])
            else:
                img = ax.scatter(self.grid[:, 0],
                                 self.grid[:, 1],
                                 c=U,
                                 s=scale,
                                 linewidth=0,
                                 cmap=kwargs['cmap'],
                                 vmin=vmin,
                                 vmax=vmax)

            # for k in range(self.na):
            #     ax.annotate(str(k),xy=(self.pa[0,k],self.pa[1,k]))
            for k in self.dap.keys():
                ax.annotate(str(self.dap[k]['name']),
                            xy=(self.dap[k]['p'][0], self.dap[k]['p'][1]))
            ax.set_title(title)

            divider = make_axes_locatable(ax)
            cax = divider.append_axes("right", size="5%", pad=0.05)
            clb = fig.colorbar(img, cax)
            clb.set_label(legcb)
            if best:
                if self.mode != 'file':
                    if polar == 'o':
                        ax.contour(np.sum(self.bestsvo, axis=2)[f, :].reshape(
                            self.nx, self.ny).T,
                                   extent=(l, r, b, t),
                                   linestyles='dotted')
                    if polar == 'p':
                        ax.contour(np.sum(self.bestsvp, axis=2)[f, :].reshape(
                            self.nx, self.ny).T,
                                   extent=(l, r, b, t),
                                   linestyles='dotted')

        # display access points
        if a == -1:
            ax.scatter(self.pa[0, :],
                       self.pa[1, :],
                       s=scale + 10,
                       c='r',
                       linewidth=0)
        else:
            ax.scatter(self.pa[0, a],
                       self.pa[1, a],
                       s=scale + 10,
                       c='r',
                       linewidth=0)
        plt.tight_layout()
        return (fig, ax)
예제 #19
0
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.showG('i', en=11)
#Ga = L.buildGr()
#L.showGs()
#nx.draw(Ga,Ga.pos)