Esempio n. 1
0
class Coverage(object):
    """ Handle Layout Coverage

        Methods
        -------
        create grid()
            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
        model : a pylayers.network.model object.
        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

    """


    def __init__(self,_fileini='coverage.ini'):


        self.config = ConfigParser.ConfigParser()
        self.config.read(pyu.getlong(_fileini,pstruc['DIRSIMUL']))
        self.plm = dict(self.config.items('pl_model'))
        self.layoutopt = dict(self.config.items('layout'))
        self.gridopt = dict(self.config.items('grid'))
        self.txopt = dict(self.config.items('tx'))
        self.rxopt = dict(self.config.items('rx'))
        self.showopt = dict(self.config.items('show'))

        self.L = Layout(self.layoutopt['filename'])
        self.model = PLSmodel(f=eval(self.plm['fghz']),
                         rssnp=eval(self.plm['rssnp']),
                         d0=eval(self.plm['d0']),
                         sigrss=eval(self.plm['sigrss']))

        self.nx = eval(self.gridopt['nx'])
        self.ny = eval(self.gridopt['ny'])
        self.mode = eval(self.gridopt['full'])
        self.boundary = eval(self.gridopt['boundary'])
        # transitter 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.bandwidthmhz = eval(self.rxopt['bandwidthmhz'])
        self.temperaturek = eval(self.rxopt['temperaturek'])
        self.noisefactordb = eval(self.rxopt['noisefactordb'])

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

        self.show = str2bool(self.showopt['show'])

        try:
            self.L.Gt.nodes()
        except:
            pass
        try:
            self.L.dumpr('t')
        except:
            self.L.buildGt()
            self.L.dumpw('t')

        self.creategrid(full=self.mode,boundary=self.boundary)

    def __repr__(self):
        st=''
        st= st+ 'tx :'+str(self.txopt) + '\n'
        st= st+ 'rx :'+str(self.rxopt) + '\n'

    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 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:
            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 cover(self):
        """ start the coverage calculation

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showPr()

        """
        self.Lwo,self.Lwp,self.Edo,self.Edp = Loss0_v2(self.L,self.grid,self.model.f,self.tx)
        self.freespace = PL(self.grid,self.model.f,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 showEd(self,polarization='o'):
        """ show direct path excess of delay map

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showEdo()
        """

        fig=plt.figure()
        fig,ax=self.L.showGs(fig=fig)
        l=self.grid[0,0]
        r=self.grid[-1,0]
        b=self.grid[0,1]
        t=self.grid[-1,-1]
        if polarization=='o':
            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 polarization=='p':
            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()


    def showPower(self,rxsens=True,nfl=True,polarization='o'):
        """ 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
        polarization : string
            'o'|'p'

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showPower()

        """

        fig=plt.figure()
        fig,ax=self.L.showGs(fig=fig)
        l=self.grid[0,0]
        r=self.grid[-1,0]
        b=self.grid[0,1]
        t=self.grid[-1,-1]

        if polarization=='o':
            prdbm=self.prdbmo
        if polarization=='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'

        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 rxsens :

            ### values between the rx sensitivity and noise floor
            mcPrf = np.ma.masked_where((prdbm > self.rxsens) 
                                     & (prdbm < self.pndbm),prdbm)
            cov1 = ax.imshow(mcPrf.reshape((self.nx,self.ny)).T,
                             extent=(l,r,b,t),cmap = my_cmap,
                             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 = 'jet',
                            vmin=self.rxsens,origin='lower')
            title=title + '\n gray : Pr (dBm) < %.2f' % self.rxsens + ' dBm'

        else :
            cov=ax.imshow(prdbm.reshape((self.nx,self.ny)).T,
                          extent=(l,r,b,t),
                          cmap = 'jet',
                          vmin=self.pndbm,origin='lower')

        if nfl:
            ### values under the noise floor 
            ### we first clip the value below he 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,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()


    def showTransistionRegion(self,polarization='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=plt.figure()
        fig,ax = self.L.showGs(fig=fig)
        l = self.grid[0,0]
        r = self.grid[-1,0]
        b = self.grid[0,1]
        t = self.grid[-1,-1]

        if polarization=='o':
            prdbm=self.prdbmo
        if polarization=='p':
            prdbm=self.prdbmp

        zones = np.zeros(len(prdbm))
        uconnected  = np.nonzero(prdbm>PrU)[0]
        utransition = np.nonzero((prdbm < PrU)&(prdbm > PrL))[0]
        udisconnected = np.nonzero(prdbm < PrL)[0]

        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 showLoss(self,polarization='o'):
        """ show losses map

        Parameters
        ----------
        polarization : string 
            'o'|'p'|'both'

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showLoss(polarization='o')
            >>> C.showLoss(polarization='p')
        """
        fig = plt.figure()
        fig,ax=self.L.showGs(fig=fig)
        l=self.grid[0,0]
        r=self.grid[-1,0]
        b=self.grid[0,1]
        t=self.grid[-1,-1]

        if polarization=='o':
            cov = ax.imshow(self.Lwo.reshape((self.nx,self.ny)).T,
                            extent=(l,r,b,t),
                            origin='lower')
            title = ('Map of losses, orthogonal (V) polarization') 
        if polarization=='p':
            cov = ax.imshow(self.Lwp.reshape((self.nx,self.ny)).T,
                            extent=(l,r,b,t),
                            origin='lower')
            title = ('Map of losses, parallel (H) polarization') 

        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()
Esempio n. 2
0
class Coverage(object):
    """ Handle Layout Coverage 

        Methods
        -------
  
        create grid()
            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
        model : a pylayers.network.model object.
        xstep : x step for grid
        ystep : y step for grid
        tx    : transmitter position
        txpe  : transmitter power emmission level
        show  : boolean for automatic display power map

    """


    def __init__(self,_fileini='coverage.ini'):


        self.config = ConfigParser.ConfigParser()
        self.config.read(pyu.getlong(_fileini,pstruc['DIRSIMUL']))
        self.plm = dict(self.config.items('pl_model'))
        self.layoutopt = dict(self.config.items('layout'))
        self.gridopt = dict(self.config.items('grid'))
        self.txopt = dict(self.config.items('tx'))
        self.rxopt = dict(self.config.items('rx'))
        self.showopt=dict(self.config.items('show'))

        self.L=Layout(self.layoutopt['filename'])
        self.model=Model(f=eval(self.plm['f']),
                         rssnp=eval(self.plm['rssnp']),
                         d0=eval(self.plm['d0']),
                         sigrss=eval(self.plm['sigrss']))
        self.xstep = eval(self.gridopt['xstep'])
        self.ystep = eval(self.gridopt['ystep'])
        # transitter section
        self.tx = np.array((eval(self.txopt['x']),eval(self.txopt['y'])))
        self.ptdbm = eval(self.txopt['ptdbm'])
        self.framelengthbytes = eval(self.txopt['framelengthbytes'])

        # receiver section
        self.rxsens = eval(self.rxopt['sensitivity'])
        kBoltzmann = 1.3806503e-23
        self.bandwidthmhz = eval(self.rxopt['bandwidthmhz'])
        self.temperaturek = eval(self.rxopt['temperaturek'])
        self.noisefactordb = eval(self.rxopt['noisefactordb'])

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

        self.show = str2bool(self.showopt['show'])

        try:
            self.L.Gt.nodes()
        except:
            pass
        try:
            self.L.dumpr('t')
        except:
            self.L.buildGt()
            self.L.dumpw('t')
        self.creategrid()


    def creategrid(self):
        """create a grid
            create a grid for various evaluation

        """
        mi=np.min(self.L.Gs.pos.values(),axis=0)+0.01
        ma=np.max(self.L.Gs.pos.values(),axis=0)-0.01
        x=np.linspace(mi[0],ma[0],self.xstep)
        y=np.linspace(mi[1],ma[1],self.ystep)
        self.grid=np.array((list(np.broadcast(*np.ix_(x, y)))))




    def cover(self):
        """ start the coverage calculation

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showPr()

        """
        self.Lwo,self.Lwp,self.Edo,self.Edp = Loss0_v2(self.L,self.grid,self.model.f,self.tx)
        self.freespace = PL(self.grid,self.model.f,self.tx)
        self.prdbmo = self.ptdbm - self.freespace - self.Lwo
        self.prdbmp = self.ptdbm - self.freespace - self.Lwp


    def showEd(self,polarization='o'):
        """ show direct path excess of delay map

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showEdo()
        """

        fig=plt.figure()
        fig,ax=self.L.showGs(fig=fig)
        l=self.grid[0,0]
        r=self.grid[-1,0]
        b=self.grid[0,1]
        t=self.grid[-1,-1]
        if polarization=='o':
            cov=ax.imshow(self.Edo.reshape((self.xstep,self.ystep)).T,
                      extent=(l,r,b,t),
                      origin='lower')
            titre = "Map of LOS excess delay, polar orthogonal"
        if polarization=='p':
            cov=ax.imshow(self.Edp.reshape((self.xstep,self.ystep)).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()


    def showPower(self,rxsens=True,nfl=True,polarization='o'):
        """ 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
        polarization : string
            'o'|'p'

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showPower()

        """

        fig=plt.figure()
        fig,ax=self.L.showGs(fig=fig)
        l=self.grid[0,0]
        r=self.grid[-1,0]
        b=self.grid[0,1]
        t=self.grid[-1,-1]

        if polarization=='o':
            prdbm=self.prdbmo
        if polarization=='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'

        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 rxsens :

            ### values between the rx sensitivity and noise floor
            mcPrf = np.ma.masked_where((prdbm > self.rxsens) 
                                     & (prdbm < self.pndbm),prdbm)
            cov1 = ax.imshow(mcPrf.reshape((self.xstep,self.ystep)).T,
                             extent=(l,r,b,t),cmap = my_cmap,
                             vmin=self.rxsens,origin='lower')

            ### values above the sensitivity
            mcPrs = np.ma.masked_where(prdbm < self.rxsens,prdbm)
            cov = ax.imshow(mcPrs.reshape((self.xstep,self.ystep)).T,
                            extent=(l,r,b,t),
                            cmap = 'jet',
                            vmin=self.rxsens,origin='lower')
            title=title + '\n gray : Pr (dBm) < %.2f' % self.rxsens + ' dBm'

        else :
            cov=ax.imshow(prdbm.reshape((self.xstep,self.ystep)).T,
                          extent=(l,r,b,t),
                          cmap = 'jet',
                          vmin=self.PndBm,origin='lower')

        if nfl:
            ### values under the noise floor 
            ### we first clip the value below he 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.xstep,self.ystep)).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,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()


    def showTransistionRegion(self,polarization='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=plt.figure()
        fig,ax = self.L.showGs(fig=fig)
        l = self.grid[0,0]
        r = self.grid[-1,0]
        b = self.grid[0,1]
        t = self.grid[-1,-1]

        if polarization=='o':
            prdbm=self.prdbmo
        if polarization=='p':
            prdbm=self.prdbmp

        zones = np.zeros(len(prdbm))
        uconnected  = np.nonzero(prdbm>PrU)[0]
        utransition = np.nonzero((prdbm < PrU)&(prdbm > PrL))[0]
        udisconnected = np.nonzero(prdbm < PrL)[0]

        zones[uconnected] = 1
        zones[utransition] = (prdbm[utransition]-PrL)/(PrU-PrL)
        cov = ax.imshow(zones.reshape((self.xstep,self.ystep)).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 showLoss(self,polarization='o'):
        """ show losses map

        Parameters
        ----------
        polarization : string 
            'o'|'p'|'both'

        Examples
        --------
        .. plot::
            :include-source:

            >>> from pylayers.antprop.coverage import *
            >>> C = Coverage()
            >>> C.cover()
            >>> C.showLoss(polarization='o')
            >>> C.showLoss(polarization='p')
            
        """
        fig = plt.figure()
        fig,ax=self.L.showGs(fig=fig)
        l=self.grid[0,0]
        r=self.grid[-1,0]
        b=self.grid[0,1]
        t=self.grid[-1,-1]

        if polarization=='o':
            cov = ax.imshow(self.Lwo.reshape((self.xstep,self.ystep)).T,
                            extent=(l,r,b,t),
                            origin='lower')
            title = ('Map of losses, orthogonal (V) polarization') 
        if polarization=='p':
            cov = ax.imshow(self.Lwp.reshape((self.xstep,self.ystep)).T,
                            extent=(l,r,b,t),
                            origin='lower')
            title = ('Map of losses, parallel (H) polarization') 

        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()
Esempio n. 3
0
class Simul(SimulationRT):
    """

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

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

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

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

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

        """

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

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

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

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

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

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

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

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

        """

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

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

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

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

        self.net.create()

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

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

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

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

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

        """

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

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

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

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


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

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

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

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

    def runsimul(self):
        """ Run simulation
        """
        self.create()
        self.simulate(until=float(self.sim_opt['duration']),
                      real_time=True,
                      rel_speed=float(self.sim_opt['speedratio']))
        #        self.simulate(until=float(self.sim_opt['duration']))
        if self.save_opt['savep']:
            print 'Processing save results, please wait'
            self.save.mat_export()
Esempio n. 4
0
class Simul(SimulationRT):
    """

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

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

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

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

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

        """

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

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

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


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

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

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

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

        """


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

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

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

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

        self.net.create()

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


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

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

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

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

        """

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

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



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

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



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

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

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


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