diff --git a/schainpy/model/data/jrodata.py b/schainpy/model/data/jrodata.py index eaa0127..3eeafff 100644 --- a/schainpy/model/data/jrodata.py +++ b/schainpy/model/data/jrodata.py @@ -249,7 +249,7 @@ class JROData(GenericData): datatime = [] datatime.append(self.ltctime) - datatime.append(self.ltctime + self.timeInterval) + datatime.append(self.ltctime + self.timeInterval+60) datatime = numpy.array(datatime) @@ -319,6 +319,8 @@ class Voltage(JROData): Constructor ''' + self.useLocalTime = True + self.radarControllerHeaderObj = RadarControllerHeader() self.systemHeaderObj = SystemHeader() @@ -431,6 +433,8 @@ class Spectra(JROData): Constructor ''' + self.useLocalTime = True + self.radarControllerHeaderObj = RadarControllerHeader() self.systemHeaderObj = SystemHeader() diff --git a/schainpy/model/graphics/figure.py b/schainpy/model/graphics/figure.py index 7a27785..66d36fb 100644 --- a/schainpy/model/graphics/figure.py +++ b/schainpy/model/graphics/figure.py @@ -86,18 +86,18 @@ class Figure: else: txmin = numpy.min(x) timerange = self.timerange + thisdatetime = datetime.datetime.utcfromtimestamp(txmin) thisdate = datetime.datetime.combine(thisdatetime.date(), datetime.time(0,0,0)) + if xmin == None and xmax == None: xmin = (thisdatetime - thisdate).seconds/(60*60.) xmax = xmin + timerange/(60*60.) - - - mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=timezone) + mindt = thisdate + datetime.timedelta(hours=xmin) - datetime.timedelta(seconds=time.timezone) xmin_sec = time.mktime(mindt.timetuple()) - maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=timezone) + maxdt = thisdate + datetime.timedelta(hours=xmax) - datetime.timedelta(seconds=time.timezone) xmax_sec = time.mktime(maxdt.timetuple()) return xmin_sec, xmax_sec diff --git a/schainpy/model/graphics/jroplot_spectra.py b/schainpy/model/graphics/jroplot_spectra.py index afed8a8..c074c53 100644 --- a/schainpy/model/graphics/jroplot_spectra.py +++ b/schainpy/model/graphics/jroplot_spectra.py @@ -543,7 +543,7 @@ class RTIPlot(Figure): showprofile=showprofile, show=show) - self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange, timezone = dataOut.timezone) + self.xmin, self.xmax = self.getTimeLim(x, xmin, xmax, timerange) # if timerange != None: # self.timerange = timerange diff --git a/schainpy/model/io/jroIO_base.py b/schainpy/model/io/jroIO_base.py index d3af3c0..3681fe8 100644 --- a/schainpy/model/io/jroIO_base.py +++ b/schainpy/model/io/jroIO_base.py @@ -467,6 +467,9 @@ class JRODataReader(JRODataIO): thisPath = pathList[i] fileList = glob.glob1(thisPath, "*%s" %ext) + if len(fileList) < 1: + continue + fileList.sort() pathDict.setdefault(fileList[0]) pathDict[fileList[0]] = i diff --git a/schainpy/model/io/jrodataIO.py b/schainpy/model/io/jrodataIO.py index 2821b5f..498f2f2 100644 --- a/schainpy/model/io/jrodataIO.py +++ b/schainpy/model/io/jrodataIO.py @@ -3,4 +3,7 @@ from jroIO_spectra import * from jroIO_heispectra import * from jroIO_amisr import * from jroIO_HDF5 import * -from jroIO_hf import * \ No newline at end of file +try: + from jroIO_hf import * +except: + pass \ No newline at end of file diff --git a/schainpy/old/Controller/Controller.py b/schainpy/old/Controller/Controller.py deleted file mode 100644 index 2e17c3d..0000000 --- a/schainpy/old/Controller/Controller.py +++ /dev/null @@ -1,277 +0,0 @@ -''' -Created on June 5, 2012 - -$Author$ -$Id$ -''' - -import os -import sys -import datetime -import ConfigParser - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.Voltage import Voltage -from IO.VoltageIO import * - -from Model.Spectra import Spectra -from IO.SpectraIO import * - -from Processing.VoltageProcessor import * -from Processing.SpectraProcessor import * - -class Operation: - def __init__(self,name,parameters): - self.name = name - self.parameters = [] - parametersList = parameters.split(',') - nparms = len(parametersList)/2 - for id in range(nparms): - parmtype = parametersList[id*2] - value = parametersList[id*2+1] - if value == 'None': - value = None - else: - if parmtype == 'int': - value = int(value) - elif parmtype == 'float': - value = float(value) - elif parmtype == 'str': - value = str(value) - elif parmtype == 'datetime': - value = value.split('-'); value = numpy.asarray(value,dtype=numpy.int32) - value = datetime.datetime(value[0],value[1],value[2],value[3],value[4],value[5]) - else: - value = None - - self.parameters.append(value) - - -class ExecUnit: - def __init__(self,): - self.id = None - self.type = None - self.execObjIn = None - self.execObjOut = None - self.execProcObj = None - self.input = None - self.operationList = [] - self.flagSetIO = False - - def setIO(self): - self.execProcObj.setIO(self.execObjIn,self.execObjOut) - self.flagSetIO = True - - - def Pfunction(self,name): - - def setup(*args): - inputs = args[0] - if self.type == 'VoltageReader': - path = inputs[0] - startDateTime = inputs[1] - endDateTime = inputs[2] - set = inputs[3] - expLabel = inputs[4] - ext = inputs[5] - online = inputs[6] - - return self.execProcObj.setup(path,startDateTime,endDateTime,set,expLabel,ext,online) - - if self.type == 'Voltage': - return self.execProcObj.setup() - - if self.type == 'Spectra': - nFFTPoints = inputs[0] - pairList = inputs[1] - return self.execProcObj.setup(nFFTPoints,pairList) - - def getData(*args): - - return self.execProcObj.getData() - - def init(*args): - inputs = args[0] - - parm1 = inputs[0] - - if self.type == 'Voltage': - return self.execProcObj.init() - - if self.type == 'Spectra': - return self.execProcObj.init() - - - def plotData(*args): - inputs = args[0] - - if self.type == 'Voltage': - xmin = inputs[0] - xmax = inputs[1] - ymin = inputs[2] - ymax = inputs[3] - type = inputs[4] - winTitle = inputs[5] - index = inputs[6] - - return self.execProcObj.plotData(xmin,xmax,ymin,ymax,type,winTitle,index) - - if self.type == 'Spectra': - xmin = inputs[0] - xmax = inputs[1] - ymin = inputs[2] - ymax = inputs[3] - winTitle = inputs[4] - index = inputs[5] - - return self.execProcObj.plotData(xmin,xmax,ymin,ymax,winTitle,index) - - def integrator(*args): - inputs = args[0] - N = inputs[0] - timeInterval = inputs[1] - self.execProcObj.integrator(N, timeInterval) - - pfuncDict = { "setup": setup, - "getdata": getData, - "init": init, - "plotdata": plotData, - "integrator": integrator} - - return pfuncDict[name] - - - def run(self): - nopers = len(self.operationList) - for idOper in range(nopers): - operObj = self.operationList[idOper] - self.Pfunction(operObj.name)(operObj.parameters) - - -class Controller: - - def __init__(self): - self.sectionList = None - self.execUnitList = None - self.execObjList = None - self.readConfigFile() - self.createObjects() - self.setupOjects() - self.start() - - def readConfigFile(self, filename='experiment.cfg'): - - parser = ConfigParser.SafeConfigParser() - parser.read(filename) - self.sectionList = parser.sections() - self.execUnitList = [] - - for section_name in self.sectionList: - itemList = parser.items(section_name) - self.execUnitList.append(itemList) - - print - - def createObjects(self): - self.execObjList = [] - - for itemList in self.execUnitList: - execObj = ExecUnit() - for item in itemList: - name, value = item[0], item[1] - - if name == 'id': - execObj.id = int(value) - continue - - if name == 'type': - execObj.type = value - - if value == 'VoltageReader': - execObj.execObjOut = Voltage() - execObj.execProcObj = VoltageReader(execObj.execObjOut) - - - if value == 'SpectraReader': - execObj.execObjOut = Spectra() - execObj.execProcObj = SpectraReader(execObj.execObjOut) - - - if value == 'CorrelationReader': - execObj.execObjOut = Correlation() - execObj.execProcObj = CorrelationReader(execObj.execObjOut) - - - if value == 'Voltage': - execObj.execProcObj = VoltageProcessor() - execObj.execObjOut = Voltage() - - if value == 'Spectra': - execObj.execProcObj = SpectraProcessor() - execObj.execObjOut = Spectra() - - if value == 'Correlation': - execObj.execProcObj = CorrelationProcessor() - execObj.execObjOut = Correlation() - - elif name == 'input': - execObj.input = int(value) - - else: - operObj = Operation(name,value) - - if name != 'setup': - execObj.operationList.append(operObj) - else: - execObj.Pfunction(name)(operObj.parameters) - - del(operObj) - - self.execObjList.append(execObj) - del(execObj) - - - - def setupOjects(self): - for objIndex in range(len(self.execObjList)): - currExecObj = self.execObjList[objIndex] - - if not(currExecObj.type in ['VoltageReader','SpectraReader','CorrelationReader']): - - idSearch = currExecObj.input - - for objIndex2 in range(len(self.execObjList)): - - lastExecObj = self.execObjList[objIndex2] # este objeto si puede ser un readerl - - if lastExecObj.id == idSearch and currExecObj.flagSetIO == False: - currExecObj.execObjIn = lastExecObj.execObjOut - currExecObj.setIO() - - - - - - - def start(self): - - while(True): - for indexObj in range(len(self.execObjList)): - ExecObj = self.execObjList[indexObj] - ExecObj.run() - - readExecObj = self.execObjList[0] # se asume que el primer elemento es un Reader - if readExecObj.execProcObj.flagNoMoreFiles: - break - if readExecObj.execProcObj.flagIsNewBlock: - print 'Block No %04d, Time: %s' %(readExecObj.execProcObj.nTotalBlocks, - datetime.datetime.fromtimestamp(readExecObj.execProcObj.m_BasicHeader.utc),) - - - - -if __name__ == '__main__': - Controller() - \ No newline at end of file diff --git a/schainpy/old/Controller/experiment.cfg b/schainpy/old/Controller/experiment.cfg deleted file mode 100644 index 30996c1..0000000 --- a/schainpy/old/Controller/experiment.cfg +++ /dev/null @@ -1,13 +0,0 @@ -[Read0] -id = 0 -type = VoltageReader -setup = str,/Users/jro/Documents/RadarData/MST_ISR/MST,datetime,2009-01-01-0-0-1,datetime,2009-12-31-0-0-1,int,0,str,,str,None,int,0 -getData = None,None - -[Processing0] -id = 1 -type = Spectra -input = 0 -setup = int,16,None,None -init = None,None -plotData = float,None,float,None,float,None,float,None,str,Test Spectra Data,int,1 diff --git a/schainpy/old/Graphics/BaseGraph.py b/schainpy/old/Graphics/BaseGraph.py deleted file mode 100644 index ff527c5..0000000 --- a/schainpy/old/Graphics/BaseGraph.py +++ /dev/null @@ -1,1078 +0,0 @@ -""" -Created on Feb 7, 2012 - -@autor $Author$ -@version $Id$ - -""" -import os -import numpy -import sys -import time -import datetime -import time -import plplot - - -def cmap1_init(colormap="gray"): - - if colormap == None: - return - - ncolor = None - rgb_lvl = None - - # Routine for defining a specific color map 1 in HLS space. - # if gray is true, use basic grayscale variation from half-dark to light. - # otherwise use false color variation from blue (240 deg) to red (360 deg). - - # Independent variable of control points. - i = numpy.array((0., 1.)) - if colormap=="gray": - ncolor = 256 - # Hue for control points. Doesn't matter since saturation is zero. - h = numpy.array((0., 0.)) - # Lightness ranging from half-dark (for interest) to light. - l = numpy.array((0.5, 1.)) - # Gray scale has zero saturation - s = numpy.array((0., 0.)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap == 'jet': - ncolor = 256 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - - for i in range(ncolor): - if(i <= 35.0/100*(ncolor-1)): rf = 0.0 - elif (i <= 66.0/100*(ncolor-1)): rf = (100.0/31)*i/(ncolor-1) - 35.0/31 - elif (i <= 89.0/100*(ncolor-1)): rf = 1.0 - else: rf = (-100.0/22)*i/(ncolor-1) + 111.0/22 - - if(i <= 12.0/100*(ncolor-1)): gf = 0.0 - elif(i <= 38.0/100*(ncolor-1)): gf = (100.0/26)*i/(ncolor-1) - 12.0/26 - elif(i <= 64.0/100*(ncolor-1)): gf = 1.0 - elif(i <= 91.0/100*(ncolor-1)): gf = (-100.0/27)*i/(ncolor-1) + 91.0/27 - else: gf = 0.0 - - if(i <= 11.0/100*(ncolor-1)): bf = (50.0/11)*i/(ncolor-1) + 0.5 - elif(i <= 34.0/100*(ncolor-1)): bf = 1.0 - elif(i <= 65.0/100*(ncolor-1)): bf = (-100.0/31)*i/(ncolor-1) + 65.0/31 - else: bf = 0 - - r[i] = rf - g[i] = gf - b[i] = bf - - pos[i] = float(i)/float(ncolor-1) - - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - - - if colormap=="br_green": - ncolor = 256 - # Hue ranges from blue (240 deg) to red (0 or 360 deg) - h = numpy.array((240., 0.)) - # Lightness and saturation are constant (values taken from C example). - l = numpy.array((0.6, 0.6)) - s = numpy.array((0.8, 0.8)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap=="tricolor": - ncolor = 3 - # Hue ranges from blue (240 deg) to red (0 or 360 deg) - h = numpy.array((240., 0.)) - # Lightness and saturation are constant (values taken from C example). - l = numpy.array((0.6, 0.6)) - s = numpy.array((0.8, 0.8)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap == 'rgb' or colormap == 'rgb666': - - color_sz = 6 - ncolor = color_sz*color_sz*color_sz - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(color_sz): - for gi in range(color_sz): - for bi in range(color_sz): - r[ind] = ri/(color_sz-1.0) - g[ind] = gi/(color_sz-1.0) - b[ind] = bi/(color_sz-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,6,6] #Levels for RGB colors - - if colormap == 'rgb676': - ncolor = 6*7*6 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(6-1.0) - g[ind] = gi/(7-1.0) - b[ind] = bi/(6-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,7,6] #Levels for RGB colors - - if colormap == 'rgb685': - ncolor = 6*8*5 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(6-1.0) - g[ind] = gi/(8-1.0) - b[ind] = bi/(5-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,8,5] #Levels for RGB colors - - if colormap == 'rgb884': - ncolor = 8*8*4 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(8-1.0) - g[ind] = gi/(8-1.0) - b[ind] = bi/(4-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [8,8,4] #Levels for RGB colors - - if ncolor == None: - raise ValueError, "The colormap selected is not valid" - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - return rgb_lvl - -def setColormap(colormap="jet"): - cmap1_init(colormap) - -def savePlplot(filename,width,height): - curr_strm = plplot.plgstrm() - save_strm = plplot.plmkstrm() - plplot.plsetopt("geometry", "%dx%d"%(width,height)) - plplot.plsdev("png") - plplot.plsfnam(filename) - plplot.plcpstrm(curr_strm,0) - plplot.plreplot() - plplot.plend1() - plplot.plsstrm(curr_strm) - - -def initPlplot(indexPlot,ncol,nrow,winTitle,width,height): - plplot.plsstrm(indexPlot) - plplot.plparseopts([winTitle],plplot.PL_PARSE_FULL) - plplot.plsetopt("geometry", "%dx%d"%(width*ncol,height*nrow)) - plplot.plsdev("xwin") - plplot.plscolbg(255,255,255) - plplot.plscol0(1,0,0,0) - plplot.plinit() - plplot.plspause(False) - plplot.plssub(ncol,nrow) - -def setNewPage(): - plplot.plbop() - plplot.pladv(0) - -def closePage(): - plplot.pleop() - -def clearData(objGraph): - objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], "bc", "bc") - - objGraph.setColor(15) #Setting Line Color to White - - if objGraph.datatype == "complex": - objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.real) - objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.imag) - - if objGraph.datatype == "real": - objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata) - - objGraph.setColor(1) #Setting Line Color to Black -# objGraph.setLineStyle(2) -# objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], "bcntg", "bc") -# objGraph.setLineStyle(1) - -def setStrm(indexPlot): - plplot.plsstrm(indexPlot) - -def plFlush(): - plplot.plflush() - -def plShow(): - plplot.plspause(True) - plplot.plend() - -def setPlTitle(pltitle,color, szchar=0.7): - setSubpages(1, 0) - plplot.pladv(0) - plplot.plvpor(0., 1., 0., 1.) - - if color == "black": - plplot.plcol0(1) - if color == "white": - plplot.plcol0(15) - - plplot.plschr(0.0,szchar) - plplot.plmtex("t",-1., 0.5, 0.5, pltitle) - -def setSubpages(ncol,nrow): - plplot.plssub(ncol,nrow) - -class BaseGraph: - - __name = None - __xpos = None - __ypos = None - __subplot = None - __xg = None - __yg = None - xdata = None - ydata = None - getGrid = True - xaxisIsTime = False - deltax = None - xmin = None - xmax = None - - def __init__(self,name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange=None,deltax=1.0): - - self.setName(name) - self.setScreenPos(xpos, ypos) - self.setLabels(xlabel,ylabel,title) - self.setSubPlot(subplot) - self.setSizeOfChar(szchar) - self.setXYZrange(xrange,yrange,zrange) - self.getGrid = True - self.xaxisIsTime = False - self.deltax = deltax - - def setXYZrange(self,xrange,yrange,zrange): - self.xrange = xrange - self.yrange = yrange - self.zrange = zrange - - def setName(self, name): - self.__name = name - - def setScreenPos(self,xpos,ypos): - self.__xpos = xpos - self.__ypos = ypos - - def setXYData(self,xdata=None,ydata=None,datatype="real"): - if((xdata != None) and (ydata != None)): - self.xdata = xdata - self.ydata = ydata - self.datatype = datatype - - if((self.xdata == None) and (self.ydata == None)): - return None - - return 1 - - - def setLabels(self,xlabel=None,ylabel=None,title=None): - if xlabel != None: self.xlabel = xlabel - if ylabel != None: self.ylabel = ylabel - if title != None: self.title = title - - def setSubPlot(self,subplot): - self.__subplot = subplot - - def setSizeOfChar(self,szchar): - self.__szchar = szchar - - def setLineStyle(self,style): - plplot.pllsty(style) - - def setColor(self,color): - plplot.plcol0(color) - - def setXAxisAsTime(self,value=False): - self.xaxisIsTime = value - - def basicLineTimePlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None, colline=1): - - if xmin == None: xmin = x[0] - if xmax == None: xmax = x[-1] - if ymin == None: ymin = y[0] - if ymax == None: ymax = y[-1] - - plplot.plcol0(colline) - plplot.plline(x, y) - plplot.plcol0(1) - - def basicXYPlot(self, x, y, xmin=None, xmax=None, ymin=None, ymax=None): - - if xmin == None: xmin = x[0] - if xmax == None: xmax = x[-1] - if ymin == None: ymin = y[0] - if ymax == None: ymax = y[-1] - - plplot.plline(x, y) - - def basicPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None): - """ - """ - if xmin == None: xmin = x[0] - if xmax == None: xmax = x[-1] - if ymin == None: ymin = y[0] - if ymax == None: ymax = y[-1] - if zmin == None: zmin = numpy.nanmin(data) - if zmax == None: zmax = numpy.nanmax(data) - - plplot.plimage(data, - float(x[0]), - float(x[-1]), - float(y[0]), - float(y[-1]), - float(zmin), - float(zmax), - float(xmin), - float(xmax), - float(ymin), - float(ymax) - ) - - def __getBoxpltr(self, x, y, deltax=None, deltay=None): - - if not(len(x)>0 and len(y)>0): - raise ValueError, "x axis and y axis are empty" - - if deltax == None: deltax = x[-1] - x[-2] - if deltay == None: deltay = y[-1] - y[-2] - - x1 = numpy.append(x, x[-1] + deltax) - y1 = numpy.append(y, y[-1] + deltay) - - xg = (numpy.multiply.outer(x1, numpy.ones(len(y1)))) - yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1)) - - self.__xg = xg - self.__yg = yg - - return xg, yg - - - def advPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=0., zmax=0., deltax=1.0, deltay=None, getGrid = True): - if getGrid: - xg, yg = self.__getBoxpltr(x, y, deltax, deltay) - else: - xg = self.__xg - yg = self.__yg - - plplot.plimagefr(data, - float(xmin), - float(xmax), - float(ymin), - float(ymax), - 0., - 0., - float(zmin), - float(zmax), - plplot.pltr2, - xg, - yg) - - - def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.): - data = numpy.arange(256) - data = numpy.reshape(data, (1,-1)) - - plplot.plimage(data, - float(xmin), - float(xmax), - float(ymin), - float(ymax), - 0., - 255., - float(xmin), - float(xmax), - float(ymin), - float(ymax)) - - def plotBox(self, xmin, xmax, ymin, ymax, xopt, yopt, nolabels=False): - - plplot.plschr(0.0,self.__szchar-0.05) - plplot.pladv(self.__subplot) - plplot.plvpor(self.__xpos[0], self.__xpos[1], self.__ypos[0], self.__ypos[1]) - plplot.plwind(float(xmin), # self.xrange[0] - float(xmax), # self.xrange[1] - float(ymin), # self.yrange[0] - float(ymax) # self.yrange[1] - ) - - - - if self.xaxisIsTime: - plplot.pltimefmt("%H:%M") - timedelta = (xmax - xmin + 1)/8. - plplot.plbox(xopt, timedelta, 3, yopt, 0.0, 0) - else: - plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0) - - - if not(nolabels): - plplot.pllab(self.xlabel, self.ylabel, self.title) - - - def delLabels(self): - self.setColor(15) #Setting Line Color to White - plplot.pllab(self.xlabel, self.ylabel, self.title) - self.setColor(1) #Setting Line Color to Black - - - - def plotImage(self,x,y,z,xrange,yrange,zrange): - xi = x[0] - xf = x[-1] - yi = y[0] - yf = y[-1] - - plplot.plimage(z, - float(xi), - float(xf), - float(yi), - float(yf), - float(zrange[0]), - float(zrange[1]), - float(xi), - float(xf), - float(yrange[0]), - yrange[1]) - -class LinearPlot: - linearObjDic = {} - __xpos = None - __ypos = None - def __init__(self,indexPlot,nsubplot,winTitle): - self.width = 700 - self.height = 150 - ncol = 1 - nrow = nsubplot - initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height) - - - def setFigure(self,indexPlot): - setStrm(indexPlot) - - def setPosition(self): - - xi = 0.07; xf = 0.9 #0.8,0.7,0.5 - yi = 0.15; yf = 0.8 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__xpos = xpos - self.__ypos = ypos - - return xpos,ypos - - def show(self): - plShow() - - def refresh(self): - plFlush() - - def setup(self,subplot,xmin,xmax,ymin,ymax,title,xlabel,ylabel): - szchar = 1.10 - name = "linear" - key = name + "%d"%subplot - xrange = [xmin,xmax] - yrange = [ymin,ymax] - - xpos,ypos = self.setPosition() - linearObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange) - linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcnst", "bcnstv") - self.linearObjDic[key] = linearObj - - def plot(self,subplot,x,y,type="power"): - name = "linear" - key = name + "%d"%subplot - - linearObj = self.linearObjDic[key] - linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcst", "bcst") - - if linearObj.setXYData() != None: - clearData(linearObj) - - else: - if type.lower() == 'simple': - linearObj.setXYData(x,y,"real") - if type.lower() == 'power': - linearObj.setXYData(x,abs(y),"real") - if type.lower() == 'iq': - linearObj.setXYData(x,y,"complex") - - if type.lower() == 'simple': - colline = 9 - linearObj.basicLineTimePlot(x, y, xmin, xmax, ymin, ymax, colline) - linearObj.setXYData(x,y,"real") - - if type.lower() == 'power': - colline = 9 - linearObj.basicLineTimePlot(x, abs(y), xmin, xmax, ymin, ymax, colline) - linearObj.setXYData(x,abs(y),"real") - - if type.lower() == 'iq': - colline = 9 - linearObj.basicLineTimePlot(x=x, y=y.real, colline=colline) - colline = 13 - linearObj.basicLineTimePlot(x=x, y=y.imag, colline=colline) - - linearObj.setXYData(x,y,"complex") - - linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bcst", "bcst") - - -# linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], "bc", "bc") -# linearObj.basicXYPlot(data,y) -# linearObj.setXYData(data,y) - - - -class PcolorPlot: - pcolorObjDic = {} - colorbarObjDic = {} - pwprofileObjDic = {} - showColorbar = None - showPowerProfile = None - XAxisAsTime = None - width = None - height = None - __spcxpos = None - __spcypos = None - __cmapxpos = None - __cmapypos = None - __profxpos = None - __profypos = None - __lastTitle = None - - def __init__(self,indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime): - self.width = 460 - self.height = 300 - self.showColorbar = showColorbar - self.showPowerProfile = showPowerProfile - self.XAxisAsTime = XAxisAsTime - - - ncol = int(numpy.sqrt(nsubplot)+0.9) - nrow = int(nsubplot*1./ncol + 0.9) - - initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height) - setColormap(colormap) - self.ncol = ncol - self.nrow = nrow - - def setFigure(self,indexPlot): - setStrm(indexPlot) - - def setSpectraPos(self): #modificar valores de acuerdo al colorbar y pwprofile - if self.showPowerProfile: xi = 0.09; xf = 0.6 #0.075 - else: xi = 0.15; xf = 0.8 #0.8,0.7,0.5 - yi = 0.15; yf = 0.80 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__spcxpos = xpos - self.__spcypos = ypos - - return xpos,ypos - - def setColorbarScreenPos(self): - - xi = self.__spcxpos[1] + 0.03; xf = xi + 0.03 - yi = self.__spcypos[0]; yf = self.__spcypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__cmapxpos = xpos - self.__cmapypos = ypos - - return xpos,ypos - - def setPowerprofileScreenPos(self): - - xi = self.__cmapxpos[1] + 0.07; xf = xi + 0.25 - yi = self.__spcypos[0]; yf = self.__spcypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__profxpos = [xi,xf] - self.__profypos = [yi,yf] - - return xpos,ypos - - def createObjects(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel): - """ - Crea los objetos necesarios para un subplot - """ - - # Config Spectra plot - - szchar = 0.7 - name = "spc" - key = name + "%d"%subplot - xrange = [xmin,xmax] - yrange = [ymin,ymax] - zrange = [zmin,zmax] - - xpos,ypos = self.setSpectraPos() - pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange) - self.pcolorObjDic[key] = pcolorObj - - # Config Colorbar - if self.showColorbar: - szchar = 0.65 - name = "colorbar" - key = name + "%d"%subplot - - xpos,ypos = self.setColorbarScreenPos() - xrange = [0.,1.] - yrange = [zmin,zmax] - cmapObj = BaseGraph(name,subplot,xpos,ypos,"","","dB",szchar,xrange,yrange) - self.colorbarObjDic[key] = cmapObj - - # Config Power profile - if self.showPowerProfile: - szchar = 0.55 - name = "pwprofile" - key = name + "%d"%subplot - - xpos,ypos = self.setPowerprofileScreenPos() - xrange = [zmin,zmax] - yrange = [ymin,ymax] - powObj = BaseGraph(name,subplot,xpos,ypos,"dB","","Power Profile",szchar,xrange,yrange) - self.pwprofileObjDic[key] = powObj - - def setNewPage(self, pltitle='No title'): - szchar = 0.7 - setNewPage() - setPlTitle(pltitle,"black", szchar=szchar) - setSubpages(self.ncol, self.nrow) - - def closePage(self): - closePage() - - def iniPlot(self,subplot): - """ - Inicializa los subplots con su frame, titulo, etc - """ - - # Config Spectra plot - name = "spc" - key = name + "%d"%subplot - - pcolorObj = self.pcolorObjDic[key] - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcnst", "bcnstv") - - # Config Colorbar - if self.showColorbar: - name = "colorbar" - key = name + "%d"%subplot - - cmapObj = self.colorbarObjDic[key] - cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv") - cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1]) -# cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv") - - # Config Power profile - if self.showPowerProfile: - name = "pwprofile" - key = name + "%d"%subplot - - powObj = self.pwprofileObjDic[key] - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc") - powObj.setLineStyle(1) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc") - - def printTitle(self,pltitle): -# if self.__lastTitle != None: -# setPlTitle(self.__lastTitle,"white") -# -# self.__lastTitle = pltitle - - setPlTitle(pltitle,"black") - -# setSubpages(self.ncol,self.nrow) - - def plot(self,subplot,x,y,z,subtitle): - # Spectra plot - - name = "spc" - key = name + "%d"%subplot - -# newx = [x[0],x[-1]] - pcolorObj = self.pcolorObjDic[key] - - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcst", "bcst") - - #pcolorObj.delLabels() - pcolorObj.setLabels(title=subtitle) - - deltax = None; deltay = None - - pcolorObj.advPcolorPlot(z, - x, - y, - xmin=pcolorObj.xrange[0], - xmax=pcolorObj.xrange[1], - ymin=pcolorObj.yrange[0], - ymax=pcolorObj.yrange[1], - zmin=pcolorObj.zrange[0], - zmax=pcolorObj.zrange[1], - deltax=deltax, - deltay=deltay, - getGrid=pcolorObj.getGrid) - - #Solo se calcula la primera vez que se ingresa a la funcion - pcolorObj.getGrid = False - - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], "bcst", "bcst", nolabels=True) - - # Power Profile - if self.showPowerProfile: - power = numpy.average(z, axis=0) - name = "pwprofile" - key = name + "%d"%subplot - powObj = self.pwprofileObjDic[key] - - if powObj.setXYData() != None: - #clearData(powObj) - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc") - powObj.setLineStyle(1) - else: - powObj.setXYData(power,y) - - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc") - powObj.basicXYPlot(power,y) - powObj.setXYData(power,y) - - def savePlot(self,indexPlot,filename): - - width = self.width*self.ncol - hei = self.height*self.nrow - savePlplot(filename,width,hei) - - def refresh(self): - plFlush() - -class RtiPlot: - - pcolorObjDic = {} - colorbarObjDic = {} - pwprofileObjDic = {} - showColorbar = None - showPowerProfile = None - XAxisAsTime = None - widht = None - height = None - __rtixpos = None - __rtiypos = None - __cmapxpos = None - __cmapypos = None - __profxpos = None - __profypos = None - - def __init__(self,indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime): - self.width = 700 - self.height = 150 - self.showColorbar = showColorbar - self.showPowerProfile = showPowerProfile - self.XAxisAsTime = XAxisAsTime - - ncol = 1 - nrow = nsubplot - initPlplot(indexPlot,ncol,nrow,winTitle,self.width,self.height) - setColormap(colormap) - self.ncol = ncol - self.nrow = nrow - - def setFigure(self,indexPlot): - setStrm(indexPlot) - - def setRtiScreenPos(self): - - if self.showPowerProfile: xi = 0.07; xf = 0.65 - else: xi = 0.07; xf = 0.9 - yi = 0.15; yf = 0.80 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__rtixpos = xpos - self.__rtiypos = ypos - - return xpos,ypos - - def setColorbarScreenPos(self): - - xi = self.__rtixpos[1] + 0.03; xf = xi + 0.03 - - yi = self.__rtiypos[0]; yf = self.__rtiypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__cmapxpos = xpos - self.__cmapypos = ypos - - return xpos,ypos - - def setPowerprofileScreenPos(self): - - xi = self.__cmapxpos[1] + 0.05; xf = xi + 0.20 - - yi = self.__rtiypos[0]; yf = self.__rtiypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__profxpos = [xi,xf] - self.__profypos = [yi,yf] - - return xpos,ypos - - def setup(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone="lt",npoints=100): - # Config Rti plot - szchar = 1.10 - name = "rti" - key = name + "%d"%subplot - - # xmin, xmax --> minHour, max Hour : valores que definen el ejex x=[horaInicio,horaFinal] - thisDateTime = datetime.datetime.fromtimestamp(timedata) - startDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmin,0,0) - endDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmax,59,59) - deltaTime = 0 - if timezone == "lt": - deltaTime = time.timezone - startTimeInSecs = time.mktime(startDateTime.timetuple()) - deltaTime - endTimeInSecs = time.mktime(endDateTime.timetuple()) - deltaTime - - xrange = [startTimeInSecs,endTimeInSecs] - totalTimeInXrange = endTimeInSecs - startTimeInSecs + 1. - deltax = totalTimeInXrange / npoints - - yrange = [ymin,ymax] - zrange = [zmin,zmax] - - xpos,ypos = self.setRtiScreenPos() - pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange,deltax) - if self.XAxisAsTime: - pcolorObj.setXAxisAsTime(self.XAxisAsTime) - xopt = "bcnstd" - yopt = "bcnstv" - else: - xopt = "bcnst" - yopt = "bcnstv" - - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt) - self.pcolorObjDic[key] = pcolorObj - - - # Config Colorbar - if self.showColorbar: - szchar = 0.9 - name = "colorbar" - key = name + "%d"%subplot - - xpos,ypos = self.setColorbarScreenPos() - xrange = [0.,1.] - yrange = [zmin,zmax] - cmapObj = BaseGraph(name,subplot,xpos,ypos,"","","dB",szchar,xrange,yrange) - cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcm") - cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1]) - cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], "bc", "bcmtsv") - self.colorbarObjDic[key] = cmapObj - - - # Config Power profile - if self.showPowerProfile: - szchar = 0.8 - name = "pwprofile" - key = name + "%d"%subplot - - xpos,ypos = self.setPowerprofileScreenPos() - xrange = [zmin,zmax] - yrange = [ymin,ymax] - powObj = BaseGraph(name,subplot,xpos,ypos,"dB","","Power Profile",szchar,xrange,yrange) - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc") - powObj.setLineStyle(1) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc") - self.pwprofileObjDic[key] = powObj - - - def plot(self,subplot,x,y,z): - # RTI plot - name = "rti" - key = name + "%d"%subplot - - data = numpy.reshape(z, (1,-1)) - data = numpy.abs(data) - data = 10*numpy.log10(data) - newx = [x,x+1] - - pcolorObj = self.pcolorObjDic[key] - - if pcolorObj.xaxisIsTime: - xopt = "bcstd" - yopt = "bcst" - else: - xopt = "bcst" - yopt = "bcst" - - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt) - - deltax = pcolorObj.deltax - deltay = None - - if pcolorObj.xmin == None and pcolorObj.xmax == None: - pcolorObj.xmin = x - pcolorObj.xmax = x - - if x >= pcolorObj.xmax: - xmin = x - xmax = x + deltax - x = [x] - pcolorObj.advPcolorPlot(data, - x, - y, - xmin=xmin, - xmax=xmax, - ymin=pcolorObj.yrange[0], - ymax=pcolorObj.yrange[1], - zmin=pcolorObj.zrange[0], - zmax=pcolorObj.zrange[1], - deltax=deltax, - deltay=deltay, - getGrid=pcolorObj.getGrid) - - pcolorObj.xmin = xmin - pcolorObj.xmax = xmax - - - # Power Profile - if self.showPowerProfile: - data = numpy.reshape(data,(numpy.size(data))) - name = "pwprofile" - key = name + "%d"%subplot - powObj = self.pwprofileObjDic[key] - - if powObj.setXYData() != None: - clearData(powObj) - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bcntg", "bc") - powObj.setLineStyle(1) - else: - powObj.setXYData(data,y) - - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], "bc", "bc") - powObj.basicXYPlot(data,y) - powObj.setXYData(data,y) - - def savePlot(self,indexPlot,filename): - - width = self.width*self.ncol - hei = self.height*self.nrow - savePlplot(filename,width,hei) - - def refresh(self): - plFlush() - -if __name__ == '__main__': - - #Setting the signal - fs = 8000 - f0 = 200 - f1 = 400 - T = 1./fs - x = numpy.arange(160) - y1 = numpy.sin(2*numpy.pi*f0*x*T) - y2 = numpy.sin(2*numpy.pi*f1*x*T) - signalList = [y1,y2] - - xmin = numpy.min(x) - xmax = numpy.max(x) - ymin = numpy.min(y1) - ymax = numpy.max(y1) - - # Creating Object - indexPlot = 1 - nsubplot = 2 - winTitle = "mi grafico v1" - - subplotTitle = "subplot - No." - xlabel = "" - ylabel = "" - - linearObj = LinearPlot(indexPlot,nsubplot,winTitle) - - #Config SubPlots - for subplot in range(nsubplot): - indexplot = subplot + 1 - title = subplotTitle + '%d'%indexplot - linearObj.setup(indexplot, xmin, xmax, ymin, ymax, title, xlabel, ylabel) - - #Plotting - type = "simple" - for subplot in range(nsubplot): - indexplot = subplot + 1 - y = signalList[subplot] - linearObj.plot(indexplot, x, y, type) - - linearObj.refresh() - linearObj.show() - - print "end" \ No newline at end of file diff --git a/schainpy/old/Graphics/BaseGraph_mpl.py b/schainpy/old/Graphics/BaseGraph_mpl.py deleted file mode 100644 index ea3c18e..0000000 --- a/schainpy/old/Graphics/BaseGraph_mpl.py +++ /dev/null @@ -1,1211 +0,0 @@ -''' -Created on Feb 7, 2012 - -@autor $Author: dsuarez $ -@version $Id: BaseGraph.py 117 2012-09-04 21:16:59Z dsuarez $ - -''' -#from __future__ import division -#import os -import numpy -#import sys -import time -import datetime - -#import plplot -import matplotlib as mpl -mpl.use('TKAgg') -import matplotlib.pyplot as plt - -import scitools.numpyutils as sn - -def cmap1_init(colormap='gray'): - -# if colormap == None: -# return -# -# ncolor = None -# rgb_lvl = None -# -# # Routine for defining a specific color map 1 in HLS space. -# # if gray is true, use basic grayscale variation from half-dark to light. -# # otherwise use false color variation from blue (240 deg) to red (360 deg). -# -# # Independent variable of control points. -# i = numpy.array((0., 1.)) -# if colormap=='gray': -# ncolor = 256 -# # Hue for control points. Doesn't matter since saturation is zero. -# h = numpy.array((0., 0.)) -# # Lightness ranging from half-dark (for interest) to light. -# l = numpy.array((0.5, 1.)) -# # Gray scale has zero saturation -# s = numpy.array((0., 0.)) -# -# # number of cmap1 colours is 256 in this case. -# plplot.plscmap1n(ncolor) -# # Interpolate between control points to set up cmap1. -# plplot.plscmap1l(0, i, h, l, s) -# -# return None -# -# if colormap == 'jet': -# ncolor = 256 -# pos = numpy.zeros((ncolor)) -# r = numpy.zeros((ncolor)) -# g = numpy.zeros((ncolor)) -# b = numpy.zeros((ncolor)) -# -# for i in range(ncolor): -# if(i <= 35.0/100*(ncolor-1)): rf = 0.0 -# elif (i <= 66.0/100*(ncolor-1)): rf = (100.0/31)*i/(ncolor-1) - 35.0/31 -# elif (i <= 89.0/100*(ncolor-1)): rf = 1.0 -# else: rf = (-100.0/22)*i/(ncolor-1) + 111.0/22 -# -# if(i <= 12.0/100*(ncolor-1)): gf = 0.0 -# elif(i <= 38.0/100*(ncolor-1)): gf = (100.0/26)*i/(ncolor-1) - 12.0/26 -# elif(i <= 64.0/100*(ncolor-1)): gf = 1.0 -# elif(i <= 91.0/100*(ncolor-1)): gf = (-100.0/27)*i/(ncolor-1) + 91.0/27 -# else: gf = 0.0 -# -# if(i <= 11.0/100*(ncolor-1)): bf = (50.0/11)*i/(ncolor-1) + 0.5 -# elif(i <= 34.0/100*(ncolor-1)): bf = 1.0 -# elif(i <= 65.0/100*(ncolor-1)): bf = (-100.0/31)*i/(ncolor-1) + 65.0/31 -# else: bf = 0 -# -# r[i] = rf -# g[i] = gf -# b[i] = bf -# -# pos[i] = float(i)/float(ncolor-1) -# -# -# plplot.plscmap1n(ncolor) -# plplot.plscmap1l(1, pos, r, g, b) -# -# -# -# if colormap=='br_green': -# ncolor = 256 -# # Hue ranges from blue (240 deg) to red (0 or 360 deg) -# h = numpy.array((240., 0.)) -# # Lightness and saturation are constant (values taken from C example). -# l = numpy.array((0.6, 0.6)) -# s = numpy.array((0.8, 0.8)) -# -# # number of cmap1 colours is 256 in this case. -# plplot.plscmap1n(ncolor) -# # Interpolate between control points to set up cmap1. -# plplot.plscmap1l(0, i, h, l, s) -# -# return None -# -# if colormap=='tricolor': -# ncolor = 3 -# # Hue ranges from blue (240 deg) to red (0 or 360 deg) -# h = numpy.array((240., 0.)) -# # Lightness and saturation are constant (values taken from C example). -# l = numpy.array((0.6, 0.6)) -# s = numpy.array((0.8, 0.8)) -# -# # number of cmap1 colours is 256 in this case. -# plplot.plscmap1n(ncolor) -# # Interpolate between control points to set up cmap1. -# plplot.plscmap1l(0, i, h, l, s) -# -# return None -# -# if colormap == 'rgb' or colormap == 'rgb666': -# -# color_sz = 6 -# ncolor = color_sz*color_sz*color_sz -# pos = numpy.zeros((ncolor)) -# r = numpy.zeros((ncolor)) -# g = numpy.zeros((ncolor)) -# b = numpy.zeros((ncolor)) -# ind = 0 -# for ri in range(color_sz): -# for gi in range(color_sz): -# for bi in range(color_sz): -# r[ind] = ri/(color_sz-1.0) -# g[ind] = gi/(color_sz-1.0) -# b[ind] = bi/(color_sz-1.0) -# pos[ind] = ind/(ncolor-1.0) -# ind += 1 -# rgb_lvl = [6,6,6] #Levels for RGB colors -# -# if colormap == 'rgb676': -# ncolor = 6*7*6 -# pos = numpy.zeros((ncolor)) -# r = numpy.zeros((ncolor)) -# g = numpy.zeros((ncolor)) -# b = numpy.zeros((ncolor)) -# ind = 0 -# for ri in range(8): -# for gi in range(8): -# for bi in range(4): -# r[ind] = ri/(6-1.0) -# g[ind] = gi/(7-1.0) -# b[ind] = bi/(6-1.0) -# pos[ind] = ind/(ncolor-1.0) -# ind += 1 -# rgb_lvl = [6,7,6] #Levels for RGB colors -# -# if colormap == 'rgb685': -# ncolor = 6*8*5 -# pos = numpy.zeros((ncolor)) -# r = numpy.zeros((ncolor)) -# g = numpy.zeros((ncolor)) -# b = numpy.zeros((ncolor)) -# ind = 0 -# for ri in range(8): -# for gi in range(8): -# for bi in range(4): -# r[ind] = ri/(6-1.0) -# g[ind] = gi/(8-1.0) -# b[ind] = bi/(5-1.0) -# pos[ind] = ind/(ncolor-1.0) -# ind += 1 -# rgb_lvl = [6,8,5] #Levels for RGB colors -# -# if colormap == 'rgb884': -# ncolor = 8*8*4 -# pos = numpy.zeros((ncolor)) -# r = numpy.zeros((ncolor)) -# g = numpy.zeros((ncolor)) -# b = numpy.zeros((ncolor)) -# ind = 0 -# for ri in range(8): -# for gi in range(8): -# for bi in range(4): -# r[ind] = ri/(8-1.0) -# g[ind] = gi/(8-1.0) -# b[ind] = bi/(4-1.0) -# pos[ind] = ind/(ncolor-1.0) -# ind += 1 -# rgb_lvl = [8,8,4] #Levels for RGB colors -# -# if ncolor == None: -# raise ValueError, 'The colormap selected is not valid' -# -# plplot.plscmap1n(ncolor) -# plplot.plscmap1l(1, pos, r, g, b) -# -# return rgb_lvl - pass - -def setColormap(colormap='jet'): -# cmap1_init(colormap) - pass - -def savePlplot(filename,width,height): -# curr_strm = plplot.plgstrm() -# save_strm = plplot.plmkstrm() -# plplot.plsetopt('geometry', '%dx%d'%(width,height)) -# plplot.plsdev('png') -# plplot.plsfnam(filename) -# plplot.plcpstrm(curr_strm,0) -# plplot.plreplot() -# plplot.plend1() -# plplot.plsstrm(curr_strm) - pass - -def initMatplotlib(indexFig,ncol,nrow,winTitle,width,height): - - plt.ioff() - fig = plt.figure(indexFig) - fig.canvas.manager.set_window_title(winTitle) - fig.canvas.manager.resize(width,height) -# fig.add_subplot(nrow,ncol,1) - plt.ion() - -def setNewPage(): -# plplot.plbop() -# plplot.pladv(0) - plt.clf() - -def closePage(): -# plplot.pleop() - pass - -def clearData(objGraph): - objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], 'bc', 'bc') - - objGraph.setColor(15) #Setting Line Color to White - - if objGraph.datatype == 'complex': - objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.real) - objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata.imag) - - if objGraph.datatype == 'real': - objGraph.basicXYPlot(objGraph.xdata,objGraph.ydata) - - objGraph.setColor(1) #Setting Line Color to Black -# objGraph.setLineStyle(2) -# objGraph.plotBox(objGraph.xrange[0], objGraph.xrange[1], objGraph.yrange[0], objGraph.yrange[1], 'bcntg', 'bc') -# objGraph.setLineStyle(1) - -def setFigure(indexFig): -# plplot.plsstrm(indexFig) - plt.figure(indexFig) - -def refresh(): -# plplot.refresh() - plt.draw() - -def show(): -# plplot.plspause(True) -# plplot.plend() - plt.ioff() - plt.show() - plt.ion() - -def setPlTitle(pltitle,color, szchar=0.7): -# setSubpages(1, 0) -# plplot.pladv(0) -# plplot.plvpor(0., 1., 0., 1.) -# -# if color == 'black': -# plplot.plcol0(1) -# if color == 'white': -# plplot.plcol0(15) -# -# plplot.plschr(0.0,szchar) -# plplot.plmtex('t',-1., 0.5, 0.5, pltitle) - pass - -def setSubpages(ncol,nrow): -# plplot.plssub(ncol,nrow) - pass - -class BaseGraph: - - __name = None - __xpos = None - __ypos = None - __subplot = None - __xg = None - __yg = None - __axesId = None - xdata = None - ydata = None - getGrid = True - xaxisIsTime = False - deltax = None - xmin = None - xmax = None - - def __init__(self,name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange=None,deltax=1.0): - - self.setName(name) - self.setScreenPos(xpos, ypos) - self.setSubPlot(subplot) - self.setXYZrange(xrange,yrange,zrange) - self.setSizeOfChar(szchar) - self.setLabels(xlabel,ylabel,title) - self.getGrid = True - self.xaxisIsTime = False - self.deltax = deltax - pass - - def makeAxes(self,indexFig,nrow,ncol,subplot): - fig = plt.figure(indexFig) - self.__axesId = fig.add_subplot(nrow,ncol,subplot) - - def setParentAxesId(self,parent): - self.__axesId = parent.__axesId - - def setName(self, name): - self.__name = name - - def setScreenPos(self,xpos,ypos): - self.__xpos = xpos - self.__ypos = ypos - - def setSubPlot(self,subplot): - self.__subplot = subplot - - def setXYZrange(self,xrange,yrange,zrange): - self.xrange = xrange - self.yrange = yrange - self.zrange = zrange - - def setSizeOfChar(self,szchar): - self.__szchar = szchar - - def setLabels(self,xlabel=None,ylabel=None,title=None): - if xlabel != None: self.xlabel = xlabel - if ylabel != None: self.ylabel = ylabel - if title != None: self.title = title - - def setXYData(self,xdata=None,ydata=None,datatype='real'): - if ((xdata != None) and (ydata != None)): - self.xdata = xdata - self.ydata = ydata - self.datatype = datatype - if ((self.xdata == None) and (self.ydata == None)): - return None - return 1 - - def setLineStyle(self, style): -# plplot.pllsty(style) - pass - - def setColor(self, color): -# plplot.plcol0(color) - pass - - def setXAxisAsTime(self, value=False): - self.xaxisIsTime = value - - def basicLineTimePlot(self, x, y, colline=1): -# plplot.plcol0(colline) -# plplot.plline(x, y) -# plplot.plcol0(1) - ax = self.__axesId - if self.setXYData() == None: - ax.plot(x,y) - else: - ax.lines[0].set_data(x,y) - - def basicXYPlot(self, x, y): -# plplot.plline(x, y) - ax = self.__axesId - if self.setXYData() == None: - ax.plot(x,y) - else: - ax.lines[0].set_data(x,y) - - def basicPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None): -# -# if xmin == None: xmin = x[0] -# if xmax == None: xmax = x[-1] -# if ymin == None: ymin = y[0] -# if ymax == None: ymax = y[-1] -# if zmin == None: zmin = numpy.nanmin(data) -# if zmax == None: zmax = numpy.nanmax(data) -# -# plplot.plimage(data, -# float(x[0]), -# float(x[-1]), -# float(y[0]), -# float(y[-1]), -# float(zmin), -# float(zmax), -# float(xmin), -# float(xmax), -# float(ymin), -# float(ymax) -# ) - pass - - def __getBoxpltr(self, x, y, deltax=None, deltay=None): - -# if not(len(x)>0 and len(y)>0): -# raise ValueError, 'x axis and y axis are empty' -# -# if deltax == None: deltax = x[-1] - x[-2] -# if deltay == None: deltay = y[-1] - y[-2] -# -# x1 = numpy.append(x, x[-1] + deltax) -# y1 = numpy.append(y, y[-1] + deltay) -# -# xg = (numpy.multiply.outer(x1, numpy.ones(len(y1)))) -# yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1)) -# -# self.__xg = xg -# self.__yg = yg -# -# return xg, yg - pass - - def advPcolorPlot(self, data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=0., zmax=0., deltax=1.0, deltay=None, getGrid = True): - # if getGrid: - # xg, yg = self.__getBoxpltr(x, y, deltax, deltay) - # else: - # xg = self.__xg - # yg = self.__yg - # - # plplot.plimagefr(data, - # float(xmin), - # float(xmax), - # float(ymin), - # float(ymax), - # 0., - # 0., - # float(zmin), - # float(zmax), - # plplot.pltr2, - # xg, - # yg) - - ax = self.__axesId -# if self.setXYData() == None: - ax.pcolormesh(x,y,data.T,vmin=zmin,vmax=zmax) -# else: -# ax.lines[0].set_data(x,y) - - - def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.): -# data = numpy.arange(256) -# data = numpy.reshape(data, (1,-1)) -# plplot.plimage(data, -# float(xmin), -# float(xmax), -# float(ymin), -# float(ymax), -# 0., -# 255., -# float(xmin), -# float(xmax), -# float(ymin), -# float(ymax)) - ax = self.__axesId - cax, kw = mpl.colorbar.make_axes(ax) - norm = mpl.colors.Normalize(vmin=ymin, vmax=ymax) - cb = mpl.colorbar.ColorbarBase(cax,norm=norm,**kw) - self.__colorbarId = cb - cb.set_label(self.title) - - def plotBox(self, xmin, xmax, ymin, ymax, xopt, yopt, nolabels=False): - -# plplot.plschr(0.0,self.__szchar-0.05) -# plplot.pladv(self.__subplot) -# plplot.plvpor(self.__xpos[0], self.__xpos[1], self.__ypos[0], self.__ypos[1]) -# plplot.plwind(float(xmin), # self.xrange[0] -# float(xmax), # self.xrange[1] -# float(ymin), # self.yrange[0] -# float(ymax) # self.yrange[1] -# ) -# -# -# -# if self.xaxisIsTime: -# plplot.pltimefmt('%H:%M') -# timedelta = (xmax - xmin + 1)/8. -# plplot.plbox(xopt, timedelta, 3, yopt, 0.0, 0) -# else: -# plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0) -# -# -# if not(nolabels): -# plplot.pllab(self.xlabel, self.ylabel, self.title) - - ax = self.__axesId - ax.set_xlim([xmin,xmax]) - ax.set_ylim([ymin,ymax]) - - if not(nolabels): - ax.set_xlabel(self.xlabel) - ax.set_ylabel(self.ylabel) - ax.set_title(self.title) - -# fig = plt.gcf() -# nrows = self. -# fig.add_subplot -# print - pass - - def delLabels(self): -# self.setColor(15) #Setting Line Color to White -# plplot.pllab(self.xlabel, self.ylabel, self.title) -# self.setColor(1) #Setting Line Color to Black - pass - - def plotImage(self,x,y,z,xrange,yrange,zrange): -# xi = x[0] -# xf = x[-1] -# yi = y[0] -# yf = y[-1] -# -# plplot.plimage(z, -# float(xi), -# float(xf), -# float(yi), -# float(yf), -# float(zrange[0]), -# float(zrange[1]), -# float(xi), -# float(xf), -# float(yrange[0]), -# yrange[1]) - pass - -class LinearPlot: - - linearObjDic = {} - __xpos = None - __ypos = None - - def __init__(self,indexFig,nsubplot,winTitle): - self.width = 700 - self.height = 150 - self.indexFig = indexFig - self.ncol = 1 - self.nrow = nsubplot - initMatplotlib(indexFig,self.ncol,self.nrow,winTitle,self.width,self.height) - - def setFigure(self,indexFig): - setFigure(indexFig) - - def setPosition(self): - - xi = 0.07; xf = 0.9 #0.8,0.7,0.5 - yi = 0.15; yf = 0.8 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__xpos = xpos - self.__ypos = ypos - - return xpos,ypos - - def show(self): - show() - - def refresh(self): - refresh() - - def setup(self,subplot,xmin,xmax,ymin,ymax,title,xlabel,ylabel): - szchar = 1.10 - name = 'linear' - key = name + '%d'%subplot - xrange = [xmin,xmax] - yrange = [ymin,ymax] - - xpos,ypos = self.setPosition() - linearObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange) - linearObj.makeAxes(self.indexFig,self.nrow,self.ncol,subplot) - linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], 'bcnst', 'bcnstv') - self.linearObjDic[key] = linearObj - - - def plot(self,subplot,x,y,type='abs'): - name = 'linear' - key = name + '%d'%subplot - - linearObj = self.linearObjDic[key] - #linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], 'bcst', 'bcst') - -# if linearObj.setXYData() != None: -# clearData(linearObj) -# else: -# if type.lower() == 'simple': -# linearObj.setXYData(x,y,'real') -# if type.lower() == 'power': -# linearObj.setXYData(x,abs(y),'real') -# if type.lower() == 'iq': -# linearObj.setXYData(x,y,'complex') - - if type.lower() == 'simple': - colline = 9 - linearObj.basicLineTimePlot(x, y) - linearObj.setXYData(x,y,'real') - - if type.lower() == 'abs': - colline = 9 - linearObj.basicLineTimePlot(x, abs(y), colline) - linearObj.setXYData(x,abs(y),'real') - - if type.lower() == 'iq': - colline = 9 - linearObj.basicLineTimePlot(x=x, y=y.real, colline=colline) - colline = 13 - linearObj.basicLineTimePlot(x=x, y=y.imag, colline=colline) - linearObj.setXYData(x,y,'complex') - -# linearObj.plotBox(linearObj.xrange[0], linearObj.xrange[1], linearObj.yrange[0], linearObj.yrange[1], 'bcst', 'bcst') - - pass - - -class PcolorPlot: - - pcolorObjDic = {} - colorbarObjDic = {} - pwprofileObjDic = {} - showColorbar = None - showPowerProfile = None - XAxisAsTime = None - width = None - height = None - __spcxpos = None - __spcypos = None - __cmapxpos = None - __cmapypos = None - __profxpos = None - __profypos = None - __lastTitle = None - - def __init__(self,indexFig,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime): - - self.width = 460 - self.height = 300 - self.showColorbar = showColorbar - self.showPowerProfile = showPowerProfile - self.XAxisAsTime = XAxisAsTime - - ncol = int(numpy.sqrt(nsubplot)+0.9) - nrow = int(nsubplot*1./ncol + 0.9) - - self.ncol = ncol - self.nrow = nrow - self.indexFig = indexFig - - initMatplotlib(indexFig,ncol,nrow,winTitle,self.width,self.height) - setColormap(colormap) - - def setFigure(self,indexFig): - setFigure(indexFig) - - def setSpectraPos(self): #modificar valores de acuerdo al colorbar y pwprofile - if self.showPowerProfile: xi = 0.09; xf = 0.6 #0.075 - else: xi = 0.15; xf = 0.8 #0.8,0.7,0.5 - yi = 0.15; yf = 0.80 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__spcxpos = xpos - self.__spcypos = ypos - - return xpos,ypos - - def setColorbarScreenPos(self): - - xi = self.__spcxpos[1] + 0.03; xf = xi + 0.03 - yi = self.__spcypos[0]; yf = self.__spcypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__cmapxpos = xpos - self.__cmapypos = ypos - - return xpos,ypos - - def setPowerprofileScreenPos(self): - - xi = self.__cmapxpos[1] + 0.07; xf = xi + 0.25 - yi = self.__spcypos[0]; yf = self.__spcypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__profxpos = [xi,xf] - self.__profypos = [yi,yf] - - return xpos,ypos - - def createObjects(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel): - - ''' - Crea los objetos necesarios para un subplot - ''' - - # Config Spectra plot - - szchar = 0.7 - name = 'spc' - key = name + '%d'%subplot - xrange = [xmin,xmax] - yrange = [ymin,ymax] - zrange = [zmin,zmax] - - xpos,ypos = self.setSpectraPos() - pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange) - #pcolorObj.makeAxes(self.indexFig,self.nrow,self.ncol,subplot) - self.pcolorObjDic[key] = pcolorObj - - # Config Colorbar - if self.showColorbar: - szchar = 0.65 - name = 'colorbar' - key = name + '%d'%subplot - - xpos,ypos = self.setColorbarScreenPos() - xrange = [0.,1.] - yrange = [zmin,zmax] - cmapObj = BaseGraph(name,subplot,xpos,ypos,'','','dB',szchar,xrange,yrange) - self.colorbarObjDic[key] = cmapObj - - # Config Power profile - if self.showPowerProfile: - szchar = 0.55 - name = 'pwprofile' - key = name + '%d'%subplot - - xpos,ypos = self.setPowerprofileScreenPos() - xrange = [zmin,zmax] - yrange = [ymin,ymax] - powObj = BaseGraph(name,subplot,xpos,ypos,'dB','','Power Profile',szchar,xrange,yrange) - #powObj.makeAxes(self.indexFig,self.nrow,self.ncol,subplot) - self.pwprofileObjDic[key] = powObj - - def setNewPage(self, pltitle='No title'): - szchar = 0.7 - setNewPage() - setPlTitle(pltitle,'black', szchar=szchar) - setSubpages(self.ncol, self.nrow) - - def closePage(self): - closePage() - - def show(self): - show() - - def iniPlot(self,subplot): - ''' - Inicializa los subplots con su frame, titulo, etc - ''' - - # Config Spectra plot - name = 'spc' - key = name + '%d'%subplot - - pcolorObj = self.pcolorObjDic[key] - pcolorObj.makeAxes(self.indexFig,self.nrow,self.ncol,subplot) - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], 'bcnst', 'bcnstv') - - # Config Colorbar - if self.showColorbar: - name = 'colorbar' - key = name + '%d'%subplot - - cmapObj = self.colorbarObjDic[key] - cmapObj.setParentAxesId(pcolorObj) -# cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], 'bc', 'bcmtsv') - cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1]) -# cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], 'bc', 'bcmtsv') - - # Config Power profile - if self.showPowerProfile: - name = 'pwprofile' - key = name + '%d'%subplot - - powObj = self.pwprofileObjDic[key] - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bcntg', 'bc') - powObj.setLineStyle(1) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bc', 'bc') - - def printTitle(self,pltitle): -# if self.__lastTitle != None: -# setPlTitle(self.__lastTitle,'white') -# -# self.__lastTitle = pltitle - - setPlTitle(pltitle,'black') - -# setSubpages(self.ncol,self.nrow) - - def plot(self,subplot,x,y,z,subtitle=''): - # Spectra plot - - name = 'spc' - key = name + '%d'%subplot - -# newx = [x[0],x[-1]] - pcolorObj = self.pcolorObjDic[key] -# pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], 'bcst', 'bcst') - - #pcolorObj.delLabels() - pcolorObj.setLabels(title=subtitle) - - deltax = None; deltay = None - - pcolorObj.advPcolorPlot(z, - x, - y, - xmin=pcolorObj.xrange[0], - xmax=pcolorObj.xrange[1], - ymin=pcolorObj.yrange[0], - ymax=pcolorObj.yrange[1], - zmin=pcolorObj.zrange[0], - zmax=pcolorObj.zrange[1], - deltax=deltax, - deltay=deltay, - getGrid=pcolorObj.getGrid) - - #Solo se calcula la primera vez que se ingresa a la funcion - pcolorObj.getGrid = False - - #pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], 'bcst', 'bcst', nolabels=True) - - # Power Profile - if self.showPowerProfile: - power = numpy.average(z, axis=0) - name = 'pwprofile' - key = name + '%d'%subplot - powObj = self.pwprofileObjDic[key] - - if powObj.setXYData() != None: - #clearData(powObj) - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bcntg', 'bc') - powObj.setLineStyle(1) - else: - powObj.setXYData(power,y) - - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bc', 'bc') - powObj.basicXYPlot(power,y) - powObj.setXYData(power,y) - - def savePlot(self,indexFig,filename): - - width = self.width*self.ncol - hei = self.height*self.nrow - savePlplot(filename,width,hei) - - def refresh(self): - refresh() - - -class RtiPlot: - - pcolorObjDic = {} - colorbarObjDic = {} - pwprofileObjDic = {} - showColorbar = None - showPowerProfile = None - XAxisAsTime = None - widht = None - height = None - __rtixpos = None - __rtiypos = None - __cmapxpos = None - __cmapypos = None - __profxpos = None - __profypos = None - - def __init__(self,indexFig,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime): - self.width = 700 - self.height = 150 - self.showColorbar = showColorbar - self.showPowerProfile = showPowerProfile - self.XAxisAsTime = XAxisAsTime - - ncol = 1 - nrow = nsubplot - initMatplotlib(indexFig,ncol,nrow,winTitle,self.width,self.height) - setColormap(colormap) - self.ncol = ncol - self.nrow = nrow - - def setFigure(self,indexFig): - setFigure(indexFig) - - def setRtiScreenPos(self): - - if self.showPowerProfile: xi = 0.07; xf = 0.65 - else: xi = 0.07; xf = 0.9 - yi = 0.15; yf = 0.80 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__rtixpos = xpos - self.__rtiypos = ypos - - return xpos,ypos - - def setColorbarScreenPos(self): - - xi = self.__rtixpos[1] + 0.03; xf = xi + 0.03 - - yi = self.__rtiypos[0]; yf = self.__rtiypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__cmapxpos = xpos - self.__cmapypos = ypos - - return xpos,ypos - - def setPowerprofileScreenPos(self): - - xi = self.__cmapxpos[1] + 0.05; xf = xi + 0.20 - - yi = self.__rtiypos[0]; yf = self.__rtiypos[1] - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__profxpos = [xi,xf] - self.__profypos = [yi,yf] - - return xpos,ypos - - def setup(self,subplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone='lt',npoints=100): - # Config Rti plot - szchar = 1.10 - name = 'rti' - key = name + '%d'%subplot - - # xmin, xmax --> minHour, max Hour : valores que definen el ejex x=[horaInicio,horaFinal] - thisDateTime = datetime.datetime.fromtimestamp(timedata) - startDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmin,0,0) - endDateTime = datetime.datetime(thisDateTime.year,thisDateTime.month,thisDateTime.day,xmax,59,59) - deltaTime = 0 - if timezone == 'lt': - deltaTime = time.timezone - startTimeInSecs = time.mktime(startDateTime.timetuple()) - deltaTime - endTimeInSecs = time.mktime(endDateTime.timetuple()) - deltaTime - - xrange = [startTimeInSecs,endTimeInSecs] - totalTimeInXrange = endTimeInSecs - startTimeInSecs + 1. - deltax = totalTimeInXrange / npoints - - yrange = [ymin,ymax] - zrange = [zmin,zmax] - - xpos,ypos = self.setRtiScreenPos() - pcolorObj = BaseGraph(name,subplot,xpos,ypos,xlabel,ylabel,title,szchar,xrange,yrange,zrange,deltax) - if self.XAxisAsTime: - pcolorObj.setXAxisAsTime(self.XAxisAsTime) - xopt = 'bcnstd' - yopt = 'bcnstv' - else: - xopt = 'bcnst' - yopt = 'bcnstv' - - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt) - self.pcolorObjDic[key] = pcolorObj - - - # Config Colorbar - if self.showColorbar: - szchar = 0.9 - name = 'colorbar' - key = name + '%d'%subplot - - xpos,ypos = self.setColorbarScreenPos() - xrange = [0.,1.] - yrange = [zmin,zmax] - cmapObj = BaseGraph(name,subplot,xpos,ypos,'','','dB',szchar,xrange,yrange) - cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], 'bc', 'bcm') - cmapObj.colorbarPlot(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1]) - cmapObj.plotBox(cmapObj.xrange[0], cmapObj.xrange[1], cmapObj.yrange[0], cmapObj.yrange[1], 'bc', 'bcmtsv') - self.colorbarObjDic[key] = cmapObj - - - # Config Power profile - if self.showPowerProfile: - szchar = 0.8 - name = 'pwprofile' - key = name + '%d'%subplot - - xpos,ypos = self.setPowerprofileScreenPos() - xrange = [zmin,zmax] - yrange = [ymin,ymax] - powObj = BaseGraph(name,subplot,xpos,ypos,'dB','','Power Profile',szchar,xrange,yrange) - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bcntg', 'bc') - powObj.setLineStyle(1) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bc', 'bc') - self.pwprofileObjDic[key] = powObj - - - def plot(self,subplot,x,y,z): - # RTI plot - name = 'rti' - key = name + '%d'%subplot - - data = numpy.reshape(z, (1,-1)) - data = numpy.abs(data) - data = 10*numpy.log10(data) - newx = [x,x+1] - - pcolorObj = self.pcolorObjDic[key] - - if pcolorObj.xaxisIsTime: - xopt = 'bcstd' - yopt = 'bcst' - else: - xopt = 'bcst' - yopt = 'bcst' - - pcolorObj.plotBox(pcolorObj.xrange[0], pcolorObj.xrange[1], pcolorObj.yrange[0], pcolorObj.yrange[1], xopt, yopt) - - deltax = pcolorObj.deltax - deltay = None - - if pcolorObj.xmin == None and pcolorObj.xmax == None: - pcolorObj.xmin = x - pcolorObj.xmax = x - - if x >= pcolorObj.xmax: - xmin = x - xmax = x + deltax - x = [x] - pcolorObj.advPcolorPlot(data, - x, - y, - xmin=xmin, - xmax=xmax, - ymin=pcolorObj.yrange[0], - ymax=pcolorObj.yrange[1], - zmin=pcolorObj.zrange[0], - zmax=pcolorObj.zrange[1], - deltax=deltax, - deltay=deltay, - getGrid=pcolorObj.getGrid) - - pcolorObj.xmin = xmin - pcolorObj.xmax = xmax - - - # Power Profile - if self.showPowerProfile: - data = numpy.reshape(data,(numpy.size(data))) - name = 'pwprofile' - key = name + '%d'%subplot - powObj = self.pwprofileObjDic[key] - - if powObj.setXYData() != None: - clearData(powObj) - powObj.setLineStyle(2) - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bcntg', 'bc') - powObj.setLineStyle(1) - else: - powObj.setXYData(data,y) - - powObj.plotBox(powObj.xrange[0], powObj.xrange[1], powObj.yrange[0], powObj.yrange[1], 'bc', 'bc') - powObj.basicXYPlot(data,y) - powObj.setXYData(data,y) - - def savePlot(self,indexFig,filename): - - width = self.width*self.ncol - hei = self.height*self.nrow - savePlplot(filename,width,hei) - - def refresh(self): - refresh() - - -if __name__ == '__main__': - - """ - Ejemplo1 - """ - #Setting the signal - fs = 8000 - f0 = 200 - f1 = 400 - T = 1./fs - x = numpy.arange(160) - y1 = numpy.sin(2*numpy.pi*f0*x*T) - y2 = numpy.sin(2*numpy.pi*f1*x*T) - signalList = [y1,y2] - - xmin = numpy.min(x) - xmax = numpy.max(x) - ymin = numpy.min(y1) - ymax = numpy.max(y1) - - # Creating Object - indexPlot = 1 - nsubplot = 2 - winTitle = "mi grafico v1" - - subplotTitle = "subplot - No." - xlabel = "" - ylabel = "" - - linearObj = LinearPlot(indexPlot,nsubplot,winTitle) - - #Config SubPlots - for subplot in range(nsubplot): - indexplot = subplot + 1 - title = subplotTitle + '%d'%indexplot - linearObj.setup(indexplot, xmin, xmax, ymin, ymax, title, xlabel, ylabel) - - #Plotting - type = "simple" - for subplot in range(nsubplot): - indexplot = subplot + 1 - y = signalList[subplot] - linearObj.plot(indexplot, x, y, type) - - linearObj.refresh() -# linearObj.show() - - - """ - Ejemplo2 - """ - - # make these smaller to increase the resolution - dx, dy = 0.05, 0.05 - x = numpy.arange(-3.0, 3.0001, dx) - y = numpy.arange(-2.0, 2.0001, dy) -# X,Y = numpy.meshgrid(x, y) - X,Y = sn.ndgrid(x, y) - Z = (1- X/2 + X**5 + Y**3)*numpy.exp(-X**2-Y**2) - - # Creating Object - indexPlot = 2 - nsubplot = 1 - winTitle = "mi grafico pcolor" - colormap = "br_green" - showColorbar = True - showPowerProfile = False - XAxisAsTime = False - - subplotTitle = "subplot no. " - xlabel = "" - ylabel = "" - - xmin = -3.0 - xmax = 3.0 - ymin = -2.0 - ymax = 2.0 - zmin = -0.3 - zmax = 1.0 - - isPlotIni = False - isPlotConfig = False - ntimes = 10 - - - for i in range(ntimes): - - # Instancia del objeto - if not(isPlotConfig): - pcolorObj = PcolorPlot(indexPlot, nsubplot, winTitle, colormap, showColorbar, showPowerProfile, XAxisAsTime) - isPlotConfig = True - - # Crea los subplots - if not(isPlotIni): - for index in range(nsubplot): - indexplot = index + 1 - title = subplotTitle + '%d'%indexplot - subplot = index - pcolorObj.createObjects(indexplot,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel) - isPlotIni = True - - # Inicializa el grafico en cada iteracion - pcolorObj.setFigure(indexPlot) - pcolorObj.setNewPage("") - - for index in range(nsubplot): - subplot = index - pcolorObj.iniPlot(subplot+1) - - #plotea los datos - for channel in range(nsubplot): - data = Z+0.1*numpy.random.randn(len(x),len(y)) - pcolorObj.plot(channel+1, x, y, data) - - pcolorObj.refresh() - -# pcolorObj.closePage() #descomentar esta linea para mas iteraciones - - time.sleep(1) - - pcolorObj.show() - - print "end" \ No newline at end of file diff --git a/schainpy/old/Graphics/SpectraPlot.py b/schainpy/old/Graphics/SpectraPlot.py deleted file mode 100644 index 93eda02..0000000 --- a/schainpy/old/Graphics/SpectraPlot.py +++ /dev/null @@ -1,170 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -import numpy -import os -import sys -import plplot -import datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Graphics.BaseGraph import * -from Model.Spectra import Spectra - -class Spectrum: - colorplotObj = None - - def __init__(self, spectraObj, index): - self.__isPlotConfig = False - self.__isPlotIni = False - self.__xrange = None - self.__yrange = None - self.nsubplots = 0 - self.indexPlot = index - self.spectraObj = spectraObj - - def setup(self,indexPlot, nsubplots, winTitle='', colormap="br_green", showColorbar=False, showPowerProfile=False, XAxisAsTime=False): - """ - Crea un objeto colorPlot con las opciones seleccinoadas - """ - - self.nsubplots = nsubplots - self.colorplotObj = PcolorPlot(indexPlot, - nsubplots, - winTitle, - colormap, - showColorbar, - showPowerProfile, - XAxisAsTime) - - def createObjects(self,xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList): - """ - Configura cada subplot con los valores maximos y minimos incluyendo los subtitulos - """ - - for index in range(self.nsubplots): - title = titleList[index] - xlabel = xlabelList[index] - ylabel = ylabelList[index] - subplot = index - self.colorplotObj.createObjects(subplot+1,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel) - - def initPlot(self): - """ - Configura cada subplot con los valores maximos y minimos incluyendo los subtitulos - """ - - - for index in range(self.nsubplots): - subplot = index - self.colorplotObj.iniPlot(subplot+1) - - - def plotData(self, - xmin=None, - xmax=None, - ymin=None, - ymax=None, - zmin=None, - zmax=None, - titleList=None, - xlabelList=None, - ylabelList=None, - winTitle='', - colormap = "br_green", - showColorbar = True, - showPowerProfile = True, - XAxisAsTime = False, - save = False, - channelList=[]): - - if channelList == []: - channelList = numpy.arange(self.spectraObj.nChannels) - - - nsubplots = len(channelList) - nX = self.spectraObj.nFFTPoints - nY = self.spectraObj.nHeights - - if self.spectraObj.noise == None: - noise = numpy.ones(nsubplots) - else: - noise = 10.*numpy.log10(self.spectraObj.noise[channelList]) - - datadB = 10.*numpy.log10(self.spectraObj.data_spc[channelList,:,:]) - noisedB = 10.*numpy.log10(noise) - - x = numpy.arange(nX) - y = self.spectraObj.heightList - - indexPlot = self.indexPlot - - if not(self.__isPlotConfig): - self.setup(indexPlot, - nsubplots, - winTitle, - colormap, - showColorbar, - showPowerProfile, - XAxisAsTime) - - - self.__isPlotConfig = True - - if not(self.__isPlotIni): - if titleList == None: - titleList = [] - for i in range(nsubplots): - titleList.append("Channel: %d - Noise: %.2f" %(i, noise[i])) - - if xlabelList == None: - xlabelList = [] - for i in range(nsubplots): - xlabelList.append("") - - if ylabelList == None: - ylabelList = [] - for i in range(nsubplots): - ylabelList.append("Range (Km)") - - if xmin == None: xmin = x[0] - if xmax == None: xmax = x[-1] - if ymin == None: ymin = y[0] - if ymax == None: ymax = y[-1] - if zmin == None: zmin = datadB.min() - if zmax == None: zmax = datadB.max() - - self.createObjects(xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList) - self.__isPlotIni = True - - thisDatetime = datetime.datetime.fromtimestamp(self.spectraObj.m_BasicHeader.utc) - pltitle = "Self Spectra - Date: %s" %(thisDatetime.strftime("%d-%b-%Y %H:%M:%S")) - - self.colorplotObj.setFigure(indexPlot) - self.colorplotObj.setNewPage(pltitle) - self.initPlot() - - for channel in range(nsubplots): - data = datadB[channel,:,:] - subtitle = "Channel: %d - Noise: %.2f" %(channel, noise[channel]) - self.colorplotObj.plot(channel+1, x, y, data, subtitle) - - self.colorplotObj.refresh() - - if save: - self.colorplotObj.setFigure(indexPlot) - path = "/home/roj-idl71/tmp/" - now = datetime.datetime.now().timetuple() - file = "spc_img%02d_%03d_%02d%02d%02d.png"%(indexPlot,now[7],now[3],now[4],now[5]) - filename = os.path.join(path,file) - self.colorplotObj.savePlot(indexPlot, filename) - - self.colorplotObj.closePage() - - diff --git a/schainpy/old/Graphics/SpectraPlot2.py b/schainpy/old/Graphics/SpectraPlot2.py deleted file mode 100644 index 1a1ba9a..0000000 --- a/schainpy/old/Graphics/SpectraPlot2.py +++ /dev/null @@ -1,172 +0,0 @@ -import numpy -import sys -import schainPlot - -class RTIFigure(schainPlot.Figure): - - __driverObj = None - __isDriverOpen = False - __isFigureOpen = False - __isConfig = False - __xw = None - __yw = None - - xmin = None - xmax = None - minvalue = None - maxvalue = None - - id = None - nframes = None - wintitle = wintitle - colormap = None - driver = None - overplot = None - - frameObjList = [] - - def __init__(self, id, wintitle, xw=600, yw=800, overplot=0, driver=None, colormap='br_green', *showGraphs): - - self.id = id - self.wintitle = wintitle - self.colormap = colormap - self.driver = driver - self.overplot = overplot - - self.showGraphs = showGraphs - - showColorbar = showGraphs[0] - showPowerprofile = showGraphs[1] - self.__driverObj = Driver(id, wintitle,xw,yw,overplot,driver,colormap,showColorbar,showPowerprofile) - - - - def __openDriver(self): - - self.__driverObj.openDriver(self.id, self.wintitle, self.xw, self.yw) - - def __openFigure(self): - - nrows, ncolumns = self.getSubplots() - - self.__driverObj.openFigure() - self.__driverObj.setSubPlots(nrows, ncolumns) - - - def __isOutOfXRange(self, x): - pass - - def __changeXRange(self, x): - pass - - def __createFrames(self): - - for frame in range(self.nframes): - frameObj = Frame(idframe = frame, - showGraph1 = self.showGraph1, - showGraph2 = self.showGraph2 - ) - - self.frameObjList.append(frameObj) - - def plot1DArray(self, data1D, x=None, channelList=None, xmin=None, xmax=None, minvalue=None, maxvlaue=None, save=False, gpath='./'): - - nx, ny = data1D.shape - - if channelList == None: - chanellList = range(nx) - - if x == None: - x = numpy.arange(data1D.size) - - - - - if not(self.__isDriverOpen): - self.__openDriver() - self.__isDriverOpen = True - - if not(self.__isConfig): - if self.xmin == None: xmin = numpy.min(x) - if self.xmax == None: xmax = numpy.max(x) - if self.minvalue == None: minvalue = numpy.min(data1D) - if self.maxvalue == None: maxvalue = numpy.max(data1D) - - self.__createFrames() - self.__isConfig = True - - - if not(self.__isOutOfXRange(x)): - self.__changeXRange(x) - - if self.__isFigureOpen: - self.__driverObj.closePage() - self.__isFigureOpen = False - - if not(self.__isFigureOpen): - self.__openFigure() - - for channel in channelList: - frameObj = self.frameObjList[channel] - frameObj.init(xmin=xmin, - xmax=xmax, - minvalue=minvalue, - maxvalue=maxvalue) - - self.__isFigureOpen = True - - - for channel in channelList: - dataCh = data1D[channel] - frameObj = self.frameObjList[channel] - - frameObj.clearData() - frameObj.plot(dataCh) - - frameObj.refresh() - - if not(self.overplot): - self.__driverObj.closeFigure() - self.__isFigureOpen = False - - - def plot2DArray(self, x, y, data2D, xmin=None, xmax=None, ymin=None, ymax=None, minvalue=None, maxvalue=None, save=False, gpath='./'): - - if not(self.__isCOpen): - self.__createFrames() - self.__openFigure() - self.__isOpen = True - - if not(self.__isConfig): - self.setRange(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, minvalue=minvalue, maxvalue=maxvalue) - - self.__isConfig = True - - for channel in channelList: - dataCh = dataArray[channel] - frameObj = frameObjList[channel] - frameObj.plot(dataCh) - - def saveFigure(self, filename): - pass - - - def getSubplots(self): - - raise ValueError, '' - -class RTIFrame(schainPlot.Frame): - - def __init__(self): - pass - - def setup(self): - pass - -class RTIPlot(schainPlot.Plot): - - def __init__(self): - pass - - def setup(self): - pass \ No newline at end of file diff --git a/schainpy/old/Graphics/VoltagePlot.py b/schainpy/old/Graphics/VoltagePlot.py deleted file mode 100644 index 153770d..0000000 --- a/schainpy/old/Graphics/VoltagePlot.py +++ /dev/null @@ -1,199 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' -import numpy -import os -import sys - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Graphics.BaseGraph import * -from Model.Voltage import Voltage - -class Osciloscope: - linearplotObj = None - - def __init__(self, Voltage, index): - self.__isPlotConfig = False - self.__isPlotIni = False - self.__xrange = None - self.__yrange = None - self.indexPlot = index - self.voltageObj = Voltage - - def setup(self,indexPlot,nsubplot,winTitle=''): - self.linearplotObj = LinearPlot(indexPlot,nsubplot,winTitle) - - def initPlot(self,xmin,xmax,ymin,ymax,titleList,xlabelList,ylabelList): - nsubplot = self.voltageObj.nChannels - - for index in range(nsubplot): - title = titleList[index] - xlabel = xlabelList[index] - ylabel = ylabelList[index] - subplot = index - self.linearplotObj.setup(subplot+1,xmin,xmax,ymin,ymax,title,xlabel,ylabel) - - def plotData(self, - xmin=None, - xmax=None, - ymin=None, - ymax=None, - titleList=None, - xlabelList=None, - ylabelList=None, - winTitle='', - type="power"): - - databuffer = self.voltageObj.data - - height = self.voltageObj.heightList - nsubplot = self.voltageObj.nChannels - indexPlot = self.indexPlot - - - if not(self.__isPlotConfig): - self.setup(indexPlot,nsubplot,winTitle) - self.__isPlotConfig = True - - if not(self.__isPlotIni): - if titleList == None: - titleList = [] - thisDatetime = datetime.datetime.fromtimestamp(self.voltageObj.m_BasicHeader.utc) - txtdate = "Date: %s" %(thisDatetime.strftime("%d-%b-%Y")) - for i in range(nsubplot): - titleList.append("Channel: %d %s" %(i, txtdate)) - - if xlabelList == None: - xlabelList = [] - for i in range(nsubplot): - xlabelList.append("") - - if ylabelList == None: - ylabelList = [] - for i in range(nsubplot): - ylabelList.append("") - - if xmin == None: xmin = height[0] - if xmax == None: xmax = height[-1] - if ymin == None: ymin = numpy.nanmin(abs(databuffer)) - if ymax == None: ymax = numpy.nanmax(abs(databuffer)) - - self.initPlot(xmin,xmax,ymin,ymax,titleList,xlabelList,ylabelList) - self.__isPlotIni = True - - self.linearplotObj.setFigure(indexPlot) - - for index in range(nsubplot): - data = databuffer[index,:] - self.linearplotObj.plot(subplot=index+1,x=height,y=data,type=type) - - self.linearplotObj.refresh() - -class RTI: - colorplotObj = None - - def __init__(self, Voltage, index): - self.__isPlotConfig = False - self.__isPlotIni = False - self.__xrange = None - self.__yrange = None - self.indexPlot = index - self.voltageObj = Voltage - - def setup(self,indexPlot,nsubplot,winTitle='',colormap="br_green",showColorbar=False,showPowerProfile=False,XAxisAsTime=False): - self.colorplotObj = RtiPlot(indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime) - - def initPlot(self,xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList,timezone,npoints): - - nsubplot = self.voltageObj.nChannels - timedata = self.voltageObj.m_BasicHeader.utc - - for index in range(nsubplot): - title = titleList[index] - xlabel = xlabelList[index] - ylabel = ylabelList[index] - subplot = index - self.colorplotObj.setup(subplot+1,xmin,xmax,ymin,ymax,zmin,zmax,title,xlabel,ylabel,timedata,timezone,npoints) - - def plotData(self, - xmin=None, - xmax=None, - ymin=None, - ymax=None, - zmin=None, - zmax=None, - titleList=None, - xlabelList=None, - ylabelList=None, - winTitle='', - timezone='lt', - npoints=1000.0, - colormap="br_green", - showColorbar=True, - showPowerProfile=True, - XAxisAsTime=True, - save = False): - - databuffer = self.voltageObj.data - timedata = self.voltageObj.m_BasicHeader.utc - height = self.voltageObj.heightList - nsubplot = self.voltageObj.nChannels - indexPlot = self.indexPlot - - if not(self.__isPlotConfig): - self.setup(indexPlot,nsubplot,winTitle,colormap,showColorbar,showPowerProfile,XAxisAsTime) - self.__isPlotConfig = True - - if not(self.__isPlotIni): - if titleList == None: - titleList = [] - thisDatetime = datetime.datetime.fromtimestamp(timedata) - txtdate = "Date: %s" %(thisDatetime.strftime("%d-%b-%Y")) - for i in range(nsubplot): - titleList.append("Channel: %d %s" %(i, txtdate)) - - if xlabelList == None: - xlabelList = [] - for i in range(nsubplot): - xlabelList.append("") - - if ylabelList == None: - ylabelList = [] - for i in range(nsubplot): - ylabelList.append("") - - if xmin == None: xmin = 0 - if xmax == None: xmax = 23 - if ymin == None: ymin = min(self.voltageObj.heightList) - if ymax == None: ymax = max(self.voltageObj.heightList) - if zmin == None: zmin = 0 - if zmax == None: zmax = 50 - - - self.initPlot(xmin,xmax,ymin,ymax,zmin,zmax,titleList,xlabelList,ylabelList,timezone,npoints) - self.__isPlotIni = True - - - self.colorplotObj.setFigure(indexPlot) - - if timezone == 'lt': - timedata = timedata - time.timezone - - for index in range(nsubplot): - data = databuffer[index,:] - self.colorplotObj.plot(subplot=index+1,x=timedata,y=height,z=data) - - self.colorplotObj.refresh() - - if save: - self.colorplotObj.setFigure(indexPlot) - path = "/Users/jro/Pictures" - now = datetime.datetime.now().timetuple() - file = "rti_img%02d_%03d_%02d%02d%02d.png"%(indexPlot,now[7],now[3],now[4],now[5]) - filename = os.path.join(path,file) - self.colorplotObj.savePlot(indexPlot, filename) diff --git a/schainpy/old/Graphics/__init__.py b/schainpy/old/Graphics/__init__.py deleted file mode 100644 index afa4d9a..0000000 --- a/schainpy/old/Graphics/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' diff --git a/schainpy/old/Graphics/schainPlot.py b/schainpy/old/Graphics/schainPlot.py deleted file mode 100644 index 159b8f5..0000000 --- a/schainpy/old/Graphics/schainPlot.py +++ /dev/null @@ -1,270 +0,0 @@ - -import numpy -import schainPlplotLib - -class Figure: - - __driverObj = None - __isDriverOpen = False - __isFigureOpen = False - __isConfig = False - __xw = None - __yw = None - - xmin = None - xmax = None - minvalue = None - maxvalue = None - - idfigure = None - nframes = None - wintitle = wintitle - colormap = None - driver = None - overplot = None - - frameObjList = [] - - def __init__(self, idfigure, nframes, wintitle, xw=600, yw=800, overplot=0, driver='plplot', colormap='br_green', *showGraphs): - - self.driver = driver - self.idfigure = idfigure - self.nframes = nframes - self.wintitle = wintitle - self.overplot = overplot - self.colormap = colormap - - self.showGraph1 = showGraphs[0] - self.showGraph2 = showGraphs[1] - self.__xw = xw - self.__yw = yw - - self.__driverObj = Driver(driver, idfigure, xw, yw, wintitle, overplot, colormap, *showGraphs) - - self.__driverObj.driver.configDriver() - - - def __openDriver(self): - - self.__driverObj.driver.openDriver() - - def __openFigure(self): - - nrows, ncolumns = self.getSubplots() - - self.__driverObj.driver.openFigure() - self.__driverObj.driver.setSubPlots(nrows, ncolumns) - - - def __isOutOfXRange(self, x): - pass - - def __changeXRange(self, x): - pass - - def __createFrames(self): - - for frame in range(self.nframes): - frameObj = Frame(idframe = frame, - showGraph1 = self.showGraph1, - showGraph2 = self.showGraph2 - ) - - self.frameObjList.append(frameObj) - - def plot1DArray(self, data1D, x=None, channelList=None, xmin=None, xmax=None, minvalue=None, maxvlaue=None, save=False, gpath='./'): - - nx, ny = data1D.shape - - if channelList == None: - chanellList = range(nx) - - if x == None: - x = numpy.arange(data1D.size) - - - - - if not(self.__isDriverOpen): - self.__openDriver() - self.__isDriverOpen = True - - if not(self.__isConfig): - if self.xmin == None: xmin = numpy.min(x) - if self.xmax == None: xmax = numpy.max(x) - if self.minvalue == None: minvalue = numpy.min(data1D) - if self.maxvalue == None: maxvalue = numpy.max(data1D) - - self.__createFrames() - self.__isConfig = True - - - if not(self.__isOutOfXRange(x)): - self.__changeXRange(x) - - if self.__isFigureOpen: - self.__driverObj.closePage() - self.__isFigureOpen = False - - if not(self.__isFigureOpen): - self.__openFigure() - - for channel in channelList: - frameObj = self.frameObjList[channel] - frameObj.init(xmin=xmin, - xmax=xmax, - minvalue=minvalue, - maxvalue=maxvalue) - - self.__isFigureOpen = True - - - for channel in channelList: - dataCh = data1D[channel] - frameObj = self.frameObjList[channel] - - frameObj.clearData() - frameObj.plot(dataCh) - - frameObj.refresh() - - if not(self.overplot): - self.__driverObj.closeFigure() - self.__isFigureOpen = False - - - def plot2DArray(self, x, y, data2D, xmin=None, xmax=None, ymin=None, ymax=None, minvalue=None, maxvalue=None, save=False, gpath='./'): - - if not(self.__isCOpen): - self.__createFrames() - self.__openFigure() - self.__isOpen = True - - if not(self.__isConfig): - self.setRange(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, minvalue=minvalue, maxvalue=maxvalue) - - self.__isConfig = True - - for channel in channelList: - dataCh = dataArray[channel] - frameObj = frameObjList[channel] - frameObj.plot(dataCh) - - def saveFigure(self, filename): - pass - - - def getSubplots(self): - - raise ValueError, "No implemented" - -class Frame: - - """ - subplots - """ - - plotObjList = [] - - def __init__(self, idframe, showGraph1=False, showGraph2=False): - - self.idframe = idframe - self.showGraph1 = showGraph1 - self.showGraph2 = showGraph2 - - self.nplots = 1 + showGraph1 + showGraph2 - self.__createPlots() - - def __createPlots(self): - - for nplot in range(self.nplots): - xi, yi, xw, yw = self.__getScreenPos(nplot) - plotObj = Plot(xi, yi, xw, yw) - - self.plotObjList.append(plotObj) - - def __getScreenPosMainPlot(self): - - """ - Calcula las coordenadas asociadas al plot principal. - """ - - xi = 1.2 - yi = 2.3 - xw = 2.0 - yw = 1.4 - - return xi, yi, xw, yw - - def __getScreenPosGraph1(self): - xi = 1.2 - yi = 2.3 - xw = 2.0 - yw = 1.4 - - return xi, yi, xw, yw - - def __getScreenPosGraph2(self): - xi = 1.2 - yi = 2.3 - xw = 2.0 - yw = 1.4 - - return xi, yi, xw, yw - - def __getScreenPos(self, nplot): - - if nplot == 0: - xi, yi, xw, yw = self.__getScreenPosMain() - if nplot == 1: - xi, yi, xw, yw = self.__getScreenPosMain() - if nplot == 2: - xi, yi, xw, yw = self.__getScreenPosMain() - - return xi, yi, xw, yw - - - def init(self, xmin, xmax, ymin, yamx, minvalue, maxvalue): - - """ - """ - - for plotObj in self.plotObjList: - plotObj.plotBox(xmin, xmax, ymin, yamx, minvalue, maxvalue) - - def clearData(self): - pass - - def plot(self, data): - - for plotObj in self.plotObjList: - plotObj.plotData(data) - - def refresh(self): - pass - - - -class Plot: - - def __init__(self, xi, yi, xw, yw): - - self.xi = xi - self.yi = yi - self.xw = xw - self.yw = yw - - def __setRange(self, xrange, yrange, zrange): - pass - - def __setLabels(self, xlabel, ylabel, zlabel): - pass - - - def plotBox(self,xmin, xmax, ymin, yamx, minvalue, maxvalue): - pass - - def plotData(self): - - raise ValueError, "" - diff --git a/schainpy/old/Graphics/schainPlotLib.py b/schainpy/old/Graphics/schainPlotLib.py deleted file mode 100644 index 8bc1a15..0000000 --- a/schainpy/old/Graphics/schainPlotLib.py +++ /dev/null @@ -1,680 +0,0 @@ -import plplot -import numpy -import sys -import plplot #condicional - -class Driver: - def __init__(self,driver, idfigure, xw, yw, wintitle, overplot, colormap, *showGraphs): - if driver == "plplot": - self.driver = PlplotDriver(idfigure, xw, yw, wintitle, overplot, colormap, *showGraphs) - elif driver == "mpl": - self.driver = MplDriver(idfigure, xw, yw, wintitle, overplot, colormap, *showGraphs) - else: - raise ValueError, "The driver: %s is not defined"%driver - -class PlplotDriver: - - __isDriverOpen = False - pldriver = None - - def __init__(self, idfigure=None, xw, yw, wintitle, overplot, colormap, *showGraphs): - - if idfigure == None: - raise ValueError, 'idfigure input must be defined' - - self.idfigure = idfigure - self.xw = xw - self.yw = yw - self.wintitle = wintitle - self.overplot = overplot - self.colormap = colormap - self.showGraph1 = showGraphs[0] - self.showGraph2 = showGraphs[1] - - def configDriver(self): - """ - previous configuration to open(init) the plplot driver - """ - plplot.plsstrm(self.idfigure) - plplot.plparseopts([self.wintitle],plplot.PL_PARSE_FULL) - plplot.plsetopt("geometry", "%dx%d"%(self.xw, self.yw)) - - plplot.plscolbg(255,255,255) - plplot.plscol0(1,0,0,0) - - def openDriver(self, pldriver=None): - if pldriver == None: - if sys.platform == "linux": - pldriver = "xcairo" - - elif sys.platform == "darwin": - pldriver = "xwin" - - else: - pldriver = "" - - plplot.plsdev(pldriver) - plplot.plinit() - plplot.plspause(False) - - self.pldriver = pldriver - - def closeDriver(self): - pass - - def openPage(self): - plplot.plbop() - plplot.pladv(0) - - def closePage(self): - plplot.pleop() - - def openFigure(self): - plplot.plbop() - plplot.pladv(0) - - def closeFigure(self): - plplot.pleop() - - def setSubPlots(self,nrows, ncolumns): - plplot.plssub(nrows, ncolumns) - - def setColorMap(self,colormap): - - if colormap == None: - return - - ncolor = None - rgb_lvl = None - - # Routine for defining a specific color map 1 in HLS space. - # if gray is true, use basic grayscale variation from half-dark to light. - # otherwise use false color variation from blue (240 deg) to red (360 deg). - - # Independent variable of control points. - - i = numpy.array((0., 1.)) - - if colormap=="gray": - ncolor = 256 - # Hue for control points. Doesn't matter since saturation is zero. - h = numpy.array((0., 0.)) - # Lightness ranging from half-dark (for interest) to light. - l = numpy.array((0.5, 1.)) - # Gray scale has zero saturation - s = numpy.array((0., 0.)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap == 'jet': - ncolor = 256 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - - for i in range(ncolor): - if(i <= 35.0/100*(ncolor-1)): rf = 0.0 - elif (i <= 66.0/100*(ncolor-1)): rf = (100.0/31)*i/(ncolor-1) - 35.0/31 - elif (i <= 89.0/100*(ncolor-1)): rf = 1.0 - else: rf = (-100.0/22)*i/(ncolor-1) + 111.0/22 - - if(i <= 12.0/100*(ncolor-1)): gf = 0.0 - elif(i <= 38.0/100*(ncolor-1)): gf = (100.0/26)*i/(ncolor-1) - 12.0/26 - elif(i <= 64.0/100*(ncolor-1)): gf = 1.0 - elif(i <= 91.0/100*(ncolor-1)): gf = (-100.0/27)*i/(ncolor-1) + 91.0/27 - else: gf = 0.0 - - if(i <= 11.0/100*(ncolor-1)): bf = (50.0/11)*i/(ncolor-1) + 0.5 - elif(i <= 34.0/100*(ncolor-1)): bf = 1.0 - elif(i <= 65.0/100*(ncolor-1)): bf = (-100.0/31)*i/(ncolor-1) + 65.0/31 - else: bf = 0 - - r[i] = rf - g[i] = gf - b[i] = bf - - pos[i] = float(i)/float(ncolor-1) - - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - - - if colormap=="br_green": - ncolor = 256 - # Hue ranges from blue (240 deg) to red (0 or 360 deg) - h = numpy.array((240., 0.)) - # Lightness and saturation are constant (values taken from C example). - l = numpy.array((0.6, 0.6)) - s = numpy.array((0.8, 0.8)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap=="tricolor": - ncolor = 3 - # Hue ranges from blue (240 deg) to red (0 or 360 deg) - h = numpy.array((240., 0.)) - # Lightness and saturation are constant (values taken from C example). - l = numpy.array((0.6, 0.6)) - s = numpy.array((0.8, 0.8)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap == 'rgb' or colormap == 'rgb666': - - color_sz = 6 - ncolor = color_sz*color_sz*color_sz - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(color_sz): - for gi in range(color_sz): - for bi in range(color_sz): - r[ind] = ri/(color_sz-1.0) - g[ind] = gi/(color_sz-1.0) - b[ind] = bi/(color_sz-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,6,6] #Levels for RGB colors - - if colormap == 'rgb676': - ncolor = 6*7*6 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(6-1.0) - g[ind] = gi/(7-1.0) - b[ind] = bi/(6-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,7,6] #Levels for RGB colors - - if colormap == 'rgb685': - ncolor = 6*8*5 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(6-1.0) - g[ind] = gi/(8-1.0) - b[ind] = bi/(5-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,8,5] #Levels for RGB colors - - if colormap == 'rgb884': - ncolor = 8*8*4 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(8-1.0) - g[ind] = gi/(8-1.0) - b[ind] = bi/(4-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [8,8,4] #Levels for RGB colors - - if ncolor == None: - raise ValueError, "The colormap selected is not valid" - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - return rgb_lvl - - def setBox(self): - - pass - - def refreshBox(self): - - pass - - def save(self): - - pass - - def show(self): - - pass - - def colorbarPlot(self): - - pass - - def linePlot(self): - - pass - - def pcolorPlot(self): - - pass - - def setLabels(self): - - pass - - - - - -class MplDriver: - def __init__(self): - pass - -def config_driver(idfigure, wintitle, width, height): - plplot.plsstrm(idfigure) - plplot.plparseopts([wintitle],plplot.PL_PARSE_FULL) - plplot.plsetopt("geometry", "%dx%d"%(width,height)) - -def ini_driver(driver): - if sys.platform == "darwin": - plplot.plsdev("xwin") - if sys.platform == "linux": - plplot.plsdev("xcairo") - plplot.plscolbg(255,255,255) - plplot.plscol0(1,0,0,0) - plplot.plinit() - plplot.plspause(False) - -def set_subpages(ncol,nrow): - plplot.plssub(ncol,nrow) - -def cmap1_init(colormap="gray"): - - if colormap == None: - return - - ncolor = None - rgb_lvl = None - - # Routine for defining a specific color map 1 in HLS space. - # if gray is true, use basic grayscale variation from half-dark to light. - # otherwise use false color variation from blue (240 deg) to red (360 deg). - - # Independent variable of control points. - i = numpy.array((0., 1.)) - if colormap=="gray": - ncolor = 256 - # Hue for control points. Doesn't matter since saturation is zero. - h = numpy.array((0., 0.)) - # Lightness ranging from half-dark (for interest) to light. - l = numpy.array((0.5, 1.)) - # Gray scale has zero saturation - s = numpy.array((0., 0.)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap == 'jet': - ncolor = 256 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - - for i in range(ncolor): - if(i <= 35.0/100*(ncolor-1)): rf = 0.0 - elif (i <= 66.0/100*(ncolor-1)): rf = (100.0/31)*i/(ncolor-1) - 35.0/31 - elif (i <= 89.0/100*(ncolor-1)): rf = 1.0 - else: rf = (-100.0/22)*i/(ncolor-1) + 111.0/22 - - if(i <= 12.0/100*(ncolor-1)): gf = 0.0 - elif(i <= 38.0/100*(ncolor-1)): gf = (100.0/26)*i/(ncolor-1) - 12.0/26 - elif(i <= 64.0/100*(ncolor-1)): gf = 1.0 - elif(i <= 91.0/100*(ncolor-1)): gf = (-100.0/27)*i/(ncolor-1) + 91.0/27 - else: gf = 0.0 - - if(i <= 11.0/100*(ncolor-1)): bf = (50.0/11)*i/(ncolor-1) + 0.5 - elif(i <= 34.0/100*(ncolor-1)): bf = 1.0 - elif(i <= 65.0/100*(ncolor-1)): bf = (-100.0/31)*i/(ncolor-1) + 65.0/31 - else: bf = 0 - - r[i] = rf - g[i] = gf - b[i] = bf - - pos[i] = float(i)/float(ncolor-1) - - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - - - if colormap=="br_green": - ncolor = 256 - # Hue ranges from blue (240 deg) to red (0 or 360 deg) - h = numpy.array((240., 0.)) - # Lightness and saturation are constant (values taken from C example). - l = numpy.array((0.6, 0.6)) - s = numpy.array((0.8, 0.8)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap=="tricolor": - ncolor = 3 - # Hue ranges from blue (240 deg) to red (0 or 360 deg) - h = numpy.array((240., 0.)) - # Lightness and saturation are constant (values taken from C example). - l = numpy.array((0.6, 0.6)) - s = numpy.array((0.8, 0.8)) - - # number of cmap1 colours is 256 in this case. - plplot.plscmap1n(ncolor) - # Interpolate between control points to set up cmap1. - plplot.plscmap1l(0, i, h, l, s) - - return None - - if colormap == 'rgb' or colormap == 'rgb666': - - color_sz = 6 - ncolor = color_sz*color_sz*color_sz - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(color_sz): - for gi in range(color_sz): - for bi in range(color_sz): - r[ind] = ri/(color_sz-1.0) - g[ind] = gi/(color_sz-1.0) - b[ind] = bi/(color_sz-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,6,6] #Levels for RGB colors - - if colormap == 'rgb676': - ncolor = 6*7*6 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(6-1.0) - g[ind] = gi/(7-1.0) - b[ind] = bi/(6-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,7,6] #Levels for RGB colors - - if colormap == 'rgb685': - ncolor = 6*8*5 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(6-1.0) - g[ind] = gi/(8-1.0) - b[ind] = bi/(5-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [6,8,5] #Levels for RGB colors - - if colormap == 'rgb884': - ncolor = 8*8*4 - pos = numpy.zeros((ncolor)) - r = numpy.zeros((ncolor)) - g = numpy.zeros((ncolor)) - b = numpy.zeros((ncolor)) - ind = 0 - for ri in range(8): - for gi in range(8): - for bi in range(4): - r[ind] = ri/(8-1.0) - g[ind] = gi/(8-1.0) - b[ind] = bi/(4-1.0) - pos[ind] = ind/(ncolor-1.0) - ind += 1 - rgb_lvl = [8,8,4] #Levels for RGB colors - - if ncolor == None: - raise ValueError, "The colormap selected is not valid" - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - return rgb_lvl - -def set_colormap(colormap="jet"): - cmap1_init(colormap) - -def save_figure(filename,width,height): - curr_strm = plplot.plgstrm() - save_strm = plplot.plmkstrm() - plplot.plsetopt("geometry", "%dx%d"%(width,height)) - if sys.platform == "darwin": - plplot.plsdev("png") - if sys.platform == "linux": - plplot.plsdev("pngcairo") - plplot.plsfnam(filename) - plplot.plcpstrm(curr_strm,0) - plplot.plreplot() - plplot.plend1() - plplot.plsstrm(curr_strm) - -def set_new_figure(): - plplot.plbop() - plplot.pladv(0) - -def close_figure(): - plplot.pleop() - -def set_strm(indexPlot): - plplot.plsstrm(indexPlot) - -def refresh(): - plplot.plflush() - -def show(): - plplot.plspause(True) - plplot.plend() - -def set_title(pltitle,color, szchar=0.7): - setSubpages(1, 0) - plplot.pladv(0) - plplot.plvpor(0., 1., 0., 1.) - - if color == "black": - plplot.plcol0(1) - if color == "white": - plplot.plcol0(15) - - plplot.plschr(0.0,szchar) - plplot.plmtex("t",-1., 0.5, 0.5, pltitle) - -def set_line_style(style): - plplot.pllsty(style) - -def set_color(color): - plplot.plcol0(color) - -def set_labels(xlabel, ylabel, title): - plplot.pllab(xlabel, ylabel, title) - -def box(subplot, xpos, ypos, xmin, xmax, ymin, ymax, xopt, yopt, szchar, xaxisastime, timefmt="%H:%M"): - plplot.pladv(subplot) - plplot.plschr(0.0,szchar-0.05) - plplot.plvpor(xpos[0], xpos[1], ypos[0], ypos[1]) - plplot.plwind(float(xmin), - float(xmax), - float(ymin), - float(ymax) - ) - if xaxisastime: - plplot.pltimefmt(timefmt) - timedelta = (xmax - xmin + 1)/8. - plplot.plbox(xopt, timedelta, 3, yopt, 0.0, 0) - else: - plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0) - -def colorbar(xmin=0., xmax=1., ymin=0., ymax=1.): - data = numpy.arange(256) - data = numpy.reshape(data, (1,-1)) - - plplot.plimage(data, - float(xmin), - float(xmax), - float(ymin), - float(ymax), - 0., - 255., - float(xmin), - float(xmax), - float(ymin), - float(ymax)) - -def basicline_timeplot(x, y,colline=1): - plplot.plcol0(colline) - plplot.plline(x, y) - plplot.plcol0(1) - -def basic_xy_plot(x, y): - plplot.plline(x, y) - -def basic_pcolor_plot(data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None): - """ - """ - if xmin == None: xmin = x[0] - if xmax == None: xmax = x[-1] - if ymin == None: ymin = y[0] - if ymax == None: ymax = y[-1] - if zmin == None: zmin = numpy.nanmin(data) - if zmax == None: zmax = numpy.nanmax(data) - - plplot.plimage(data, - float(x[0]), - float(x[-1]), - float(y[0]), - float(y[-1]), - float(zmin), - float(zmax), - float(xmin), - float(xmax), - float(ymin), - float(ymax) - ) - -def image_plot(self,x,y,z,xrange,yrange,zrange): - xi = x[0] - xf = x[-1] - yi = y[0] - yf = y[-1] - - plplot.plimage(z, - float(xi), - float(xf), - float(yi), - float(yf), - float(zrange[0]), - float(zrange[1]), - float(xi), - float(xf), - float(yrange[0]), - yrange[1]) - -def adv_pcolor_plot(data, x, y, xg, yg, xmin=None, xmax=None, ymin=None, ymax=None, zmin=0., zmax=0.): - plplot.plimagefr(data, - float(xmin), - float(xmax), - float(ymin), - float(ymax), - 0., - 0., - float(zmin), - float(zmax), - plplot.pltr2, - xg, - yg) - -#------------------------------------ - -#def get_grid(x, y, deltax=None, deltay=None): -# -# if not(len(x)>0 and len(y)>0): -# raise ValueError, "x axis and y axis are empty" -# -# if deltax == None: deltax = x[-1] - x[-2] -# if deltay == None: deltay = y[-1] - y[-2] -# -# x1 = numpy.append(x, x[-1] + deltax) -# y1 = numpy.append(y, y[-1] + deltay) -# -# xg = (numpy.multiply.outer(x1, numpy.ones(len(y1)))) -# yg = (numpy.multiply.outer(numpy.ones(len(x1)), y1)) -# -# self.__xg = xg -# self.__yg = yg -# -# return xg, yg -# -#def advPcolorPlot(data, x, y, xmin=None, xmax=None, ymin=None, ymax=None, zmin=0., zmax=0., deltax=1.0, deltay=None, getGrid = True): -# if getGrid: -# xg, yg = self.__getBoxpltr(x, y, deltax, deltay) -# else: -# xg = self.__xg -# yg = self.__yg -# -# plplot.plimagefr(data, -# float(xmin), -# float(xmax), -# float(ymin), -# float(ymax), -# 0., -# 0., -# float(zmin), -# float(zmax), -# plplot.pltr2, -# xg, -# yg) diff --git a/schainpy/old/Graphics/schainPlotTypes.py b/schainpy/old/Graphics/schainPlotTypes.py deleted file mode 100644 index 791fe3e..0000000 --- a/schainpy/old/Graphics/schainPlotTypes.py +++ /dev/null @@ -1,79 +0,0 @@ -import numpy -from schainPlot import * - - -class RTIFigure(Figure): - - overplot = 1 # igual a 1 porque el grafico es RTI, para el caso de Spectra(Spc,CrossSpc) overplot = 0 - xw = 700 - yw = 150 - nframes = None - - def __init__(self, idfigure, nframes, wintitle, colormap, driver, showColorbar, showPowerProfile): - - showGraphs = (showColorbar, showPowerProfile) - - Figure.__init__(self, - idfigure=idfigure, - nframes = nframes, - wintitle=wintitle, - xw=self.xw, - yw=self.yw, - overplot=self.overplot, - driver=driver, - colormap=colormap, - *showGraphs) - - self.nframes = nframes - self.showColorbar = showColorbar - self.showPowerProfile = showPowerProfile - - def getSubplots(self): - nrows = self.nframes - ncolumns = 1 - - return nrows, ncolumns - - def __createFrames(self): - for frame in range(self.nframes): - frameObj = RTIFrame(idFrame = frame, - showGraph1 = self.showColorbar, - showGraph2 = self.showPowerProfile - ) - - self.frameObjList.append(frameObj) - - -class RTIFrame(Frame): - def __init__(self,idFrame, showColorbar, showPowerProfile): - self.idFrame = idFrame - self.showGraph1 = showColorbar - self.showGraph2 = showPowerProfile - - def setXYPos(self): - pass - -class SelfSpcFigure(Figure): - def __init__(self): - pass - -class SelfSpcFrame(Frame): - def __init__(self): - pass - -class CrossSpcFigure(Figure): - def __init__(self): - pass - -class CrossSpcFrame(Frame): - def __init__(self): - pass - -class ScopeFigure(Figure): - def __init__(self): - pass - -class ScopeFrame(Frame): - def __init__(self): - pass - diff --git a/schainpy/old/IO/CorrelationIO.py b/schainpy/old/IO/CorrelationIO.py deleted file mode 100644 index 06830f9..0000000 --- a/schainpy/old/IO/CorrelationIO.py +++ /dev/null @@ -1,40 +0,0 @@ -''' -Created on 23/01/2012 - -@author $Author$ -@version $Id$ -''' - -import os, sys -import numpy -import glob -import fnmatch -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.JROHeader import * -from Model.Voltage import Voltage - -from IO.JRODataIO import JRODataReader -from IO.JRODataIO import JRODataWriter - - -class CorrelationReader(JRODataReader):#JRODataReader para lectura de correlaciones en archivos HDF5 - - def __init__(self): - - pass - -class CorrelationWriter(JRODataWriter):#JRODataWriter para escritura de correlaciones en archivos HDF5 - - def __init__(self): - - pass - - def puData(self): - pass - - def writeBlock(self): - pass \ No newline at end of file diff --git a/schainpy/old/IO/JRODataIO.py b/schainpy/old/IO/JRODataIO.py deleted file mode 100644 index 0b09f69..0000000 --- a/schainpy/old/IO/JRODataIO.py +++ /dev/null @@ -1,1267 +0,0 @@ -''' -Created on 23/01/2012 - -@author $Author$ -@version $Id$ -@version $Id$ -''' - -import os, sys -import glob -import time -import numpy -import fnmatch -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.JROHeader import * -from Model.JROData import JROData - -def checkForRealPath(path, year, doy, set, ext): - """ - Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path, - Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar - el path exacto de un determinado file. - - Example : - nombre correcto del file es .../.../D2009307/P2009307367.ext - - Entonces la funcion prueba con las siguientes combinaciones - .../.../x2009307/y2009307367.ext - .../.../x2009307/Y2009307367.ext - .../.../X2009307/y2009307367.ext - .../.../X2009307/Y2009307367.ext - siendo para este caso, la ultima combinacion de letras, identica al file buscado - - Return: - Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file - caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas - para el filename - """ - filepath = None - find_flag = False - filename = None - - if ext.lower() == ".r": #voltage - header1 = "dD" - header2 = "dD" - elif ext.lower() == ".pdata": #spectra - header1 = "dD" - header2 = "pP" - else: - return None, filename - - for dir in header1: #barrido por las dos combinaciones posibles de "D" - for fil in header2: #barrido por las dos combinaciones posibles de "D" - doypath = "%s%04d%03d" % ( dir, year, doy ) #formo el nombre del directorio xYYYYDDD (x=d o x=D) - filename = "%s%04d%03d%03d%s" % ( fil, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext - filepath = os.path.join( path, doypath, filename ) #formo el path completo - if os.path.exists( filepath ): #verifico que exista - find_flag = True - break - if find_flag: - break - - if not(find_flag): - return None, filename - - return filepath, filename - - -def isNumber(str): - """ - Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero. - - Excepciones: - Si un determinado string no puede ser convertido a numero - Input: - str, string al cual se le analiza para determinar si convertible a un numero o no - - Return: - True : si el string es uno numerico - False : no es un string numerico - """ - try: - float( str ) - return True - except: - return False - - -def isThisFileinRange(filename, startUTSeconds, endUTSeconds): - """ - Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado. - - Inputs: - filename : nombre completo del archivo de datos en formato Jicamarca (.r) - - startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en - segundos contados desde 01/01/1970. - endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en - segundos contados desde 01/01/1970. - - Return: - Boolean : Retorna True si el archivo de datos contiene datos en el rango de - fecha especificado, de lo contrario retorna False. - - Excepciones: - Si el archivo no existe o no puede ser abierto - Si la cabecera no puede ser leida. - - """ - m_BasicHeader = BasicHeader() - - try: - fp = open(filename,'rb') - except: - raise IOError, "The file %s can't be opened" %(filename) - - sts = m_BasicHeader.read(fp) - fp.close() - - if not(sts): - print "Skipping the file %s because it has not a valid header" %(filename) - return 0 - - if not ((startUTSeconds <= m_BasicHeader.utc) and (endUTSeconds > m_BasicHeader.utc)): - return 0 - - return 1 - - -def getlastFileFromPath(path, ext): - """ - Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext" - al final de la depuracion devuelve el ultimo file de la lista que quedo. - - Input: - fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta - ext : extension de los files contenidos en una carpeta - - Return: - El ultimo file de una determinada carpeta, no se considera el path. - """ - validFilelist = [] - fileList = os.listdir(path) - - # 0 1234 567 89A BCDE - # H YYYY DDD SSS .ext - - for file in fileList: - try: - year = int(file[1:5]) - doy = int(file[5:8]) - - if (os.path.splitext(file)[-1].upper() != ext.upper()) : continue - except: - continue - - validFilelist.append(file) - - if validFilelist: - validFilelist = sorted( validFilelist, key=str.lower ) - return validFilelist[-1] - - return None - -class JRODataIO: - - #speed of light - c = 3E8 - - m_BasicHeader = BasicHeader() - - systemHeaderObj = SystemHeader() - - radarControllerHeaderObj = RadarControllerHeader() - - m_ProcessingHeader = ProcessingHeader() - - dataOutObj = None - - online = 0 - - fp = None - - dataType = None - - fileSizeByHeader = None - - filenameList = [] - - filename = None - - fileSize = None - - firstHeaderSize = 0 - - basicHeaderSize = 24 - - nTotalBlocks = 0 - - ippSeconds = 0 - - blocksize = 0 - - set = 0 - - ext = None - - path = None - - maxTimeStep = 30 - - - delay = 3 #seconds - - nTries = 3 #quantity tries - - nFiles = 3 #number of files for searching - - - flagNoMoreFiles = 0 - - flagIsNewFile = 1 - - flagResetProcessing = 0 - - flagIsNewBlock = 0 - - def __init__(self): - pass - -class JRODataReader(JRODataIO): - - """ - Esta clase es usada como la clase padre de las clases VoltageReader y SpectraReader. - Contiene todos lo metodos necesarios para leer datos desde archivos en formato - jicamarca o pdata (.r o .pdata). La lectura de los datos siempre se realiza por bloques. Los datos - leidos son array de 3 dimensiones: - - Para Voltajes - perfiles * alturas * canales - - Para Spectra - paresCanalesIguales * alturas * perfiles (Self Spectra) - paresCanalesDiferentes * alturas * perfiles (Cross Spectra) - canales * alturas (DC Channels) - - y son almacenados en su buffer respectivo. - - Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader, - RadarControllerHeader y DataObj. Los tres primeros se usan para almacenar informacion de la - cabecera de datos (metadata), y el cuarto (DataObj) para obtener y almacenar los datos desde - el buffer de datos cada vez que se ejecute el metodo "getData". - """ - - nReadBlocks = 0 - - def __init__(self, dataOutObj=None): - - raise ValueError, "This class can't be instanced" - - - def hasNotDataInBuffer(self): - - raise ValueError, "Not implemented" - - def getBlockDimension(self): - - raise ValueError, "No implemented" - - def readBlock(self): - - self.nTotalBlocks += 1 - self.nReadBlocks += 1 - - raise ValueError, "This method has not been implemented" - - def getData( self ): - - raise ValueError, "This method has not been implemented" - - def createObjByDefault(self): - """ - Los objetos creados por defecto por cada clase (Voltaje o Espectro) difieren en el tipo - raise ValueError, "This method has not been implemented - """ - raise ValueError, "This method has not been implemented" - -# def setup(self, dataOutObj=None, path=None, startDateTime=None, endDateTime=None, set=0, expLabel = "", ext = None, online = 0): - - def __searchFilesOnLine(self, path, expLabel = "", ext = None, startDate=None, endDate=None, startTime=None, endTime=None): - """ - Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y - devuelve el archivo encontrado ademas de otros datos. - - Input: - path : carpeta donde estan contenidos los files que contiene data - - startDate : Fecha inicial. Rechaza todos los directorios donde - file end time < startDate (obejto datetime.date) - - endDate : Fecha final. Rechaza todos los directorios donde - file start time > endDate (obejto datetime.date) - - startTime : Tiempo inicial. Rechaza todos los archivos donde - file end time < startTime (obejto datetime.time) - - endTime : Tiempo final. Rechaza todos los archivos donde - file start time > endTime (obejto datetime.time) - - ext : extension de los files - - Return: - directory : eL directorio donde esta el file encontrado - filename : el ultimo file de una determinada carpeta - year : el anho - doy : el numero de dia del anho - set : el set del archivo - - - """ - dirList = [] - pathList = [] - directory = None - - #Filtra solo los directorios - for thisPath in os.listdir(path): - if os.path.isdir(os.path.join(path, thisPath)): - dirList.append(thisPath) - - if not(dirList): - return None, None, None, None, None - - dirList = sorted( dirList, key=str.lower ) - - if startDate: - startDateTime = datetime.datetime.combine(startDate, startTime) - thisDateTime = startDateTime - if endDate == None: endDateTime = startDateTime - else: endDateTime = datetime.datetime.combine(endDate, endTime) - - while(thisDateTime <= endDateTime): - year = thisDateTime.timetuple().tm_year - doy = thisDateTime.timetuple().tm_yday - - match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy)) - if len(match) == 0: - thisDateTime += datetime.timedelta(1) - continue - - pathList.append(os.path.join(path,match[0], expLabel)) - thisDateTime += datetime.timedelta(1) - - if not(pathList): - print "\tNo files in range: %s - %s" %(startDateTime.ctime(), endDateTime.ctime()) - return None, None, None, None, None - - directory = pathList[0] - - else: - directory = dirList[-1] - directory = os.path.join(path,directory) - - filename = getlastFileFromPath(directory, ext) - - if not(filename): - return None, None, None, None, None - - if not(self.__verifyFile(os.path.join(directory, filename))): - return None, None, None, None, None - - year = int( filename[1:5] ) - doy = int( filename[5:8] ) - set = int( filename[8:11] ) - - return directory, filename, year, doy, set - - - def __searchFilesOffLine(self, path, startDate, endDate, startTime=datetime.time(0,0,0), endTime=datetime.time(23,59,59),set=None, expLabel = "", ext = ".r"): - """ - Realiza una busqueda de los archivos que coincidan con los parametros - especificados y se encuentren ubicados en el path indicado. Para realizar una busqueda - correcta la estructura de directorios debe ser la siguiente: - - ...path/D[yyyy][ddd]/expLabel/D[yyyy][ddd][sss].ext - - [yyyy]: anio - [ddd] : dia del anio - [sss] : set del archivo - - Inputs: - path : Directorio de datos donde se realizara la busqueda. Todos los - ficheros que concidan con el criterio de busqueda seran - almacenados en una lista y luego retornados. - startDate : Fecha inicial. Rechaza todos los directorios donde - file end time < startDate (obejto datetime.date) - - endDate : Fecha final. Rechaza todos los directorios donde - file start time > endDate (obejto datetime.date) - - startTime : Tiempo inicial. Rechaza todos los archivos donde - file end time < startTime (obejto datetime.time) - - endTime : Tiempo final. Rechaza todos los archivos donde - file start time > endTime (obejto datetime.time) - - set : Set del primer archivo a leer. Por defecto None - - expLabel : Nombre del subdirectorio de datos. Por defecto "" - - ext : Extension de los archivos a leer. Por defecto .r - - Return: - - (pathList, filenameList) - - pathList : Lista de directorios donde se encontraron archivos dentro - de los parametros especificados - filenameList : Lista de archivos (ruta completa) que coincidieron con los - parametros especificados. - - Variables afectadas: - - self.filenameList: Lista de archivos (ruta completa) que la clase utiliza - como fuente para leer los bloque de datos, si se termina - de leer todos los bloques de datos de un determinado - archivo se pasa al siguiente archivo de la lista. - - Excepciones: - - """ - - dirList = [] - for thisPath in os.listdir(path): - if os.path.isdir(os.path.join(path,thisPath)): - dirList.append(thisPath) - - if not(dirList): - return None, None - - pathList = [] - dateList = [] - - thisDate = startDate - - while(thisDate <= endDate): - year = thisDate.timetuple().tm_year - doy = thisDate.timetuple().tm_yday - - match = fnmatch.filter(dirList, '?' + '%4.4d%3.3d' % (year,doy)) - if len(match) == 0: - thisDate += datetime.timedelta(1) - continue - - pathList.append(os.path.join(path,match[0],expLabel)) - dateList.append(thisDate) - thisDate += datetime.timedelta(1) - - filenameList = [] - for index in range(len(pathList)): - - thisPath = pathList[index] - fileList = glob.glob1(thisPath, "*%s" %ext) - fileList.sort() - - #Busqueda de datos en el rango de horas indicados - thisDate = dateList[index] - startDT = datetime.datetime.combine(thisDate, startTime) - endDT = datetime.datetime.combine(thisDate, endTime) - - startUtSeconds = time.mktime(startDT.timetuple()) - endUtSeconds = time.mktime(endDT.timetuple()) - - for file in fileList: - - filename = os.path.join(thisPath,file) - - if isThisFileinRange(filename, startUtSeconds, endUtSeconds): - filenameList.append(filename) - - if not(filenameList): - return None, None - - self.filenameList = filenameList - - return pathList, filenameList - - def setup(self, dataOutObj=None, path=None, startDate=None, endDate=None, startTime=datetime.time(0,0,0), endTime=datetime.time(23,59,59), set=0, expLabel = "", ext = None, online = 0): - """ - setup configura los parametros de lectura de la clase DataReader. - - Si el modo de lectura es offline, primero se realiza una busqueda de todos los archivos - que coincidan con los parametros especificados; esta lista de archivos son almacenados en - self.filenameList. - - Input: - path : Directorios donde se ubican los datos a leer. Dentro de este - directorio deberia de estar subdirectorios de la forma: - - path/D[yyyy][ddd]/expLabel/P[yyyy][ddd][sss][ext] - - startDate : Fecha inicial. Rechaza todos los directorios donde - file end time < startDate (obejto datetime.date) - - endDate : Fecha final. Rechaza todos los directorios donde - file start time > endDate (obejto datetime.date) - - startTime : Tiempo inicial. Rechaza todos los archivos donde - file end time < startTime (obejto datetime.time) - - endTime : Tiempo final. Rechaza todos los archivos donde - file start time > endTime (obejto datetime.time) - - set : Set del primer archivo a leer. Por defecto None - - expLabel : Nombre del subdirectorio de datos. Por defecto "" - - ext : Extension de los archivos a leer. Por defecto .r - - online : Si es == a 0 entonces busca files que cumplan con las condiciones dadas - - Return: - 0 : Si no encuentra files que cumplan con las condiciones dadas - 1 : Si encuentra files que cumplan con las condiciones dadas - - Affected: - self.startYear - self.endYear - self.startDoy - self.endDoy - self.pathList - self.filenameList - self.online - """ - if path == None: - raise ValueError, "The path is not valid" - - if ext == None: - ext = self.ext - - if dataOutObj == None: - dataOutObj = self.createObjByDefault() - - self.dataOutObj = dataOutObj - - if online: - print "Searching files in online mode..." - doypath, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=exp) - - if not(doypath): - for nTries in range( self.nTries ): - print '\tWaiting %0.2f sec for valid file in %s: try %02d ...' % (self.delay, path, nTries+1) - time.sleep( self.delay ) - doypath, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=exp) - if doypath: - break - - if not(doypath): - print "There 'isn't valied files in %s" % path - return None - - self.year = year - self.doy = doy - self.set = set - 1 - self.path = path - - else: # offline - print "Searching files in offline mode..." - pathList, filenameList = self.__searchFilesOffLine(path, startDate, endDate, startTime, endTime, set, expLabel, ext) - if not(pathList): - print "No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()) - return None - - self.fileIndex = -1 - self.pathList = pathList - self.filenameList = filenameList - - self.online = online - self.ext = ext - - ext = ext.lower() - - if not( self.setNextFile() ): - if (startDate != None) and (endDate != None): - print "No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()) - - elif startDate != None: - print "No files in : %s" % datetime.datetime.combine(startDate,startTime).ctime() - else: - print "No files" - return None - - #call fillHeaderValues() - to Data Object - - self.updateDataHeader() - - return self.dataOutObj - - def __rdSystemHeader(self, fp=None): - - if fp == None: - fp = self.fp - - self.systemHeaderObj.read(fp) - - - def __rdRadarControllerHeader(self, fp=None): - if fp == None: - fp = self.fp - - self.radarControllerHeaderObj.read(fp) - - - def __rdProcessingHeader(self, fp=None): - if fp == None: - fp = self.fp - - self.m_ProcessingHeader.read(fp) - - - def __rdBasicHeader(self, fp=None): - - if fp == None: - fp = self.fp - - self.m_BasicHeader.read(fp) - - def __readFirstHeader(self): - """ - Lectura del First Header, es decir el Basic Header y el Long Header - - Affected: - self.m_BasicHeader - self.systemHeaderObj - self.radarControllerHeaderObj - self.m_ProcessingHeader - self.firstHeaderSize - self.dataType - self.fileSizeByHeader - self.ippSeconds - - Return: - None - """ - self.__rdBasicHeader() - self.__rdSystemHeader() - self.__rdRadarControllerHeader() - self.__rdProcessingHeader() - self.firstHeaderSize = self.m_BasicHeader.size - - datatype = int(numpy.log2((self.m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR)) - if datatype == 0: - datatype_str = numpy.dtype([('real','= neededSize ): - self.__rdBasicHeader() - return 1 - - #si es OnLine y ademas aun no se han leido un bloque completo entonces se espera por uno valido - if self.online and (self.nReadBlocks < self.m_ProcessingHeader.dataBlocksPerFile): - - fpointer = self.fp.tell() - - for nTries in range( self.nTries ): - #self.fp.close() - - print "\tWaiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1) - time.sleep( self.delay ) - - #self.fp = open( self.filename, 'rb' ) - #self.fp.seek( fpointer ) - - self.fileSize = os.path.getsize( self.filename ) - currentSize = self.fileSize - fpointer - - if ( currentSize >= neededSize ): - self.__rdBasicHeader() - return 1 - - #Setting new file - if not( self.setNextFile() ): - return 0 - - deltaTime = self.m_BasicHeader.utc - self.lastUTTime # check this - - self.flagResetProcessing = 0 - - if deltaTime > self.maxTimeStep: - self.flagResetProcessing = 1 - - return 1 - - def readNextBlock(self): - """ - Establece un nuevo bloque de datos a leer y los lee, si es que no existiese - mas bloques disponibles en el archivo actual salta al siguiente. - - Affected: - self.lastUTTime - - Return: None - """ - - if not(self.__setNewBlock()): - return 0 - - if not(self.readBlock()): - return 0 - - return 1 - - def __setNextFileOnline(self): - """ - Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si - no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files - siguientes. - - Affected: - self.flagIsNewFile - self.filename - self.fileSize - self.fp - self.set - self.flagNoMoreFiles - - Return: - 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado - 1 : si el file fue abierto con exito y esta listo a ser leido - - Excepciones: - Si un determinado file no puede ser abierto - """ - nFiles = 0 - fileOk_flag = False - firstTime_flag = True - - self.set += 1 - - #busca el 1er file disponible - file, filename = checkForRealPath( self.path, self.year, self.doy, self.set, self.ext ) - if file: - if self.__verifyFile(file, False): - fileOk_flag = True - - #si no encuentra un file entonces espera y vuelve a buscar - if not(fileOk_flag): - for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles - - if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces - tries = self.nTries - else: - tries = 1 #si no es la 1era vez entonces solo lo hace una vez - - for nTries in range( tries ): - if firstTime_flag: - print "\tWaiting %0.2f sec for new \"%s\" file, try %03d ..." % ( self.delay, filename, nTries+1 ) - time.sleep( self.delay ) - else: - print "\tSearching next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext) - - file, filename = checkForRealPath( self.path, self.year, self.doy, self.set, self.ext ) - if file: - if self.__verifyFile(file): - fileOk_flag = True - break - - if fileOk_flag: - break - - firstTime_flag = False - - print "\tSkipping the file \"%s\" due to this file doesn't exist yet" % filename - self.set += 1 - - if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta - self.set = 0 - self.doy += 1 - - if fileOk_flag: - self.fileSize = os.path.getsize( file ) - self.filename = file - self.flagIsNewFile = 1 - if self.fp != None: self.fp.close() - self.fp = open(file) - self.flagNoMoreFiles = 0 - print 'Setting the file: %s' % file - else: - self.fileSize = 0 - self.filename = None - self.flagIsNewFile = 0 - self.fp = None - self.flagNoMoreFiles = 1 - print 'No more Files' - - return fileOk_flag - - - def __setNextFileOffline(self): - """ - Busca el siguiente file dentro de un folder que tenga suficiente data para ser leida - - Affected: - self.flagIsNewFile - self.fileIndex - self.filename - self.fileSize - self.fp - - Return: - 0 : si un determinado file no puede ser abierto - 1 : si el file fue abierto con exito - - Excepciones: - Si un determinado file no puede ser abierto - """ - idFile = self.fileIndex - - while(True): - - idFile += 1 - - if not(idFile < len(self.filenameList)): - self.flagNoMoreFiles = 1 - print 'No more Files' - return 0 - - filename = self.filenameList[idFile] - - if not(self.__verifyFile(filename)): - continue - - fileSize = os.path.getsize(filename) - fp = open(filename,'rb') - break - - self.flagIsNewFile = 1 - self.fileIndex = idFile - self.filename = filename - self.fileSize = fileSize - self.fp = fp - - print 'Setting the file: %s'%self.filename - - return 1 - - - def setNextFile(self): - """ - Determina el siguiente file a leer y si hay uno disponible lee el First Header - - Affected: - self.m_BasicHeader - self.systemHeaderObj - self.radarControllerHeaderObj - self.m_ProcessingHeader - self.firstHeaderSize - - Return: - 0 : Si no hay files disponibles - 1 : Si hay mas files disponibles - """ - if self.fp != None: - self.fp.close() - - if self.online: - newFile = self.__setNextFileOnline() - else: - newFile = self.__setNextFileOffline() - - if not(newFile): - return 0 - - self.__readFirstHeader() - self.nReadBlocks = 0 - return 1 - - def __verifyFile(self, filename, msgFlag=True): - """ - Verifica que el filename tenga data valida, para ello leo el FirstHeader del file - - Return: - 0 : file no valido para ser leido - 1 : file valido para ser leido - """ - msg = None - - try: - fp = open( filename,'rb' ) #lectura binaria - currentPosition = fp.tell() - except: - if msgFlag: - print "The file %s can't be opened" % (filename) - return False - - neededSize = self.m_ProcessingHeader.blockSize + self.firstHeaderSize - - if neededSize == 0: - - m_BasicHeader = BasicHeader() - systemHeaderObj = SystemHeader() - radarControllerHeaderObj = RadarControllerHeader() - m_ProcessingHeader = ProcessingHeader() - - try: - if not( m_BasicHeader.read(fp) ): raise ValueError - if not( systemHeaderObj.read(fp) ): raise ValueError - if not( radarControllerHeaderObj.read(fp) ): raise ValueError - if not( m_ProcessingHeader.read(fp) ): raise ValueError - data_type = int(numpy.log2((m_ProcessingHeader.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR)) - - neededSize = m_ProcessingHeader.blockSize + m_BasicHeader.size - - except: - if msgFlag: - print "\tThe file %s is empty or it hasn't enough data" % filename - - fp.close() - return False - - else: - msg = "\tSkipping the file %s due to it hasn't enough data" %filename - - fp.close() - fileSize = os.path.getsize(filename) - currentSize = fileSize - currentPosition - - if currentSize < neededSize: - if msgFlag and (msg != None): - print msg #print"\tSkipping the file %s due to it hasn't enough data" %filename - return False - - return True - - def updateDataHeader(self): - - self.dataOutObj.m_BasicHeader = self.m_BasicHeader.copy() - self.dataOutObj.m_ProcessingHeader = self.m_ProcessingHeader.copy() - self.dataOutObj.radarControllerHeaderObj = self.radarControllerHeaderObj.copy() - self.dataOutObj.systemHeaderObj = self.systemHeaderObj.copy() - - self.dataOutObj.dataType = self.dataType - self.dataOutObj.updateObjFromHeader() - - -class JRODataWriter(JRODataIO): - - """ - Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura - de los datos siempre se realiza por bloques. - """ - - nWriteBlocks = 0 - - setFile = None - - - def __init__(self, dataOutObj=None): - raise ValueError, "Not implemented" - - - def hasAllDataInBuffer(self): - raise ValueError, "Not implemented" - - - def setBlockDimension(self): - raise ValueError, "Not implemented" - - - def writeBlock(self): - raise ValueError, "No implemented" - - - def putData(self): - raise ValueError, "No implemented" - - - def __writeFirstHeader(self): - """ - Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader) - - Affected: - __dataType - - Return: - None - """ - self.__writeBasicHeader() - self.__wrSystemHeader() - self.__wrRadarControllerHeader() - self.__wrProcessingHeader() - self.dataType = self.dataOutObj.dataType - - - def __writeBasicHeader(self, fp=None): - """ - Escribe solo el Basic header en el file creado - - Return: - None - """ - if fp == None: - fp = self.fp - - self.dataOutObj.m_BasicHeader.write(fp) - - - def __wrSystemHeader(self, fp=None): - """ - Escribe solo el System header en el file creado - - Return: - None - """ - if fp == None: - fp = self.fp - - self.dataOutObj.systemHeaderObj.write(fp) - - - def __wrRadarControllerHeader(self, fp=None): - """ - Escribe solo el RadarController header en el file creado - - Return: - None - """ - if fp == None: - fp = self.fp - - self.dataOutObj.radarControllerHeaderObj.write(fp) - - - def __wrProcessingHeader(self, fp=None): - """ - Escribe solo el Processing header en el file creado - - Return: - None - """ - if fp == None: - fp = self.fp - - self.dataOutObj.m_ProcessingHeader.write(fp) - - - def setNextFile(self): - """ - Determina el siguiente file que sera escrito - - Affected: - self.filename - self.subfolder - self.fp - self.setFile - self.flagIsNewFile - - Return: - 0 : Si el archivo no puede ser escrito - 1 : Si el archivo esta listo para ser escrito - """ - ext = self.ext - path = self.path - - if self.fp != None: - self.fp.close() - - timeTuple = time.localtime( self.dataOutObj.m_BasicHeader.utc ) - subfolder = 'D%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday) - - doypath = os.path.join( path, subfolder ) - if not( os.path.exists(doypath) ): - os.mkdir(doypath) - self.setFile = -1 #inicializo mi contador de seteo - else: - filesList = os.listdir( doypath ) - if len( filesList ) > 0: - filesList = sorted( filesList, key=str.lower ) - filen = filesList[-1] - # el filename debera tener el siguiente formato - # 0 1234 567 89A BCDE (hex) - # x YYYY DDD SSS .ext - if isNumber( filen[8:11] ): - self.setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file - else: - self.setFile = -1 - else: - self.setFile = -1 #inicializo mi contador de seteo - - setFile = self.setFile - setFile += 1 - - file = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, - timeTuple.tm_year, - timeTuple.tm_yday, - setFile, - ext ) - - filename = os.path.join( path, subfolder, file ) - - fp = open( filename,'wb' ) - - self.nWriteBlocks = 0 - - #guardando atributos - self.filename = filename - self.subfolder = subfolder - self.fp = fp - self.setFile = setFile - self.flagIsNewFile = 1 - - print 'Writing the file: %s'%self.filename - - self.__writeFirstHeader() - - return 1 - - - def __setNewBlock(self): - """ - Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header - - Return: - 0 : si no pudo escribir nada - 1 : Si escribio el Basic el First Header - """ - if self.fp == None: - self.setNextFile() - - if self.flagIsNewFile: - return 1 - - if self.nWriteBlocks < self.m_ProcessingHeader.dataBlocksPerFile: - self.__writeBasicHeader() - return 1 - - if not( self.setNextFile() ): - return 0 - - return 1 - - - def writeNextBlock(self): - """ - Selecciona el bloque siguiente de datos y los escribe en un file - - Return: - 0 : Si no hizo pudo escribir el bloque de datos - 1 : Si no pudo escribir el bloque de datos - """ - if not( self.__setNewBlock() ): - return 0 - - self.writeBlock() - - return 1 - - - def getDataHeader(self): - """ - Obtiene una copia del First Header - - Affected: - self.m_BasicHeader - self.systemHeaderObj - self.radarControllerHeaderObj - self.m_ProcessingHeader - self.dataType - - Return: - None - """ - self.dataOutObj.updateHeaderFromObj() - - self.m_BasicHeader = self.dataOutObj.m_BasicHeader.copy() - self.systemHeaderObj = self.dataOutObj.systemHeaderObj.copy() - self.radarControllerHeaderObj = self.dataOutObj.radarControllerHeaderObj.copy() - self.m_ProcessingHeader = self.dataOutObj.m_ProcessingHeader.copy() - - self.dataType = self.dataOutObj.dataType - - - def setup(self, path, set=0, ext=None): - """ - Setea el tipo de formato en la cual sera guardada la data y escribe el First Header - - Inputs: - path : el path destino en el cual se escribiran los files a crear - format : formato en el cual sera salvado un file - set : el setebo del file - - Return: - 0 : Si no realizo un buen seteo - 1 : Si realizo un buen seteo - """ - - if ext == None: - ext = self.ext - - ext = ext.lower() - - self.path = path - self.setFile = set - 1 - self.ext = ext - #self.format = format - self.getDataHeader() - - self.setBlockDimension() - - if not( self.setNextFile() ): - print "There isn't a next file" - return 0 - - return 1 diff --git a/schainpy/old/IO/SpectraIO.py b/schainpy/old/IO/SpectraIO.py deleted file mode 100644 index 2c257f8..0000000 --- a/schainpy/old/IO/SpectraIO.py +++ /dev/null @@ -1,535 +0,0 @@ -''' -File: SpectraIO.py -Created on 20/02/2012 - -@author $Author$ -@version $Id$ -''' - -import os, sys -import numpy -import glob -import fnmatch -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.JROHeader import * -from Model.Spectra import Spectra - -from JRODataIO import JRODataReader -from JRODataIO import JRODataWriter -from JRODataIO import isNumber - - -class SpectraReader(JRODataReader): - """ - Esta clase permite leer datos de espectros desde archivos procesados (.pdata). La lectura - de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones) - son almacenados en tres buffer's para el Self Spectra, el Cross Spectra y el DC Channel. - - paresCanalesIguales * alturas * perfiles (Self Spectra) - paresCanalesDiferentes * alturas * perfiles (Cross Spectra) - canales * alturas (DC Channels) - - Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader, - RadarControllerHeader y Spectra. Los tres primeros se usan para almacenar informacion de la - cabecera de datos (metadata), y el cuarto (Spectra) para obtener y almacenar un bloque de - datos desde el "buffer" cada vez que se ejecute el metodo "getData". - - Example: - dpath = "/home/myuser/data" - - startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0) - - endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0) - - readerObj = SpectraReader() - - readerObj.setup(dpath, startTime, endTime) - - while(True): - - readerObj.getData() - - print readerObj.dataOutObj.data - - if readerObj.flagNoMoreFiles: - break - - """ - dataOutObj = None - - data_spc = None - data_cspc = None - data_dc = None - - pts2read_SelfSpectra = 0 - pts2read_CrossSpectra = 0 - pts2read_DCchannels = 0 - - nChannels = 0 - nPairs = 0 - - flag_cspc = False - - def __init__(self, dataOutObj=None): - """ - Inicializador de la clase SpectraReader para la lectura de datos de espectros. - - Inputs: - dataOutObj : Objeto de la clase Spectra. Este objeto sera utilizado para - almacenar un perfil de datos cada vez que se haga un requerimiento - (getData). El perfil sera obtenido a partir del buffer de datos, - si el buffer esta vacio se hara un nuevo proceso de lectura de un - bloque de datos. - Si este parametro no es pasado se creara uno internamente. - - Affected: - self.dataOutObj - - Return : None - """ - - self.data_spc = None - self.data_cspc = None - self.data_dc = None - - self.pts2read_SelfSpectra = 0 - self.pts2read_CrossSpectra = 0 - self.pts2read_DCs = 0 - - self.nChannels = 0 - - self.nPairs = 0 - - self.ext = ".pdata" - - self.optchar = "P" - - ###################### - - self.m_BasicHeader = BasicHeader() - - self.systemHeaderObj = SystemHeader() - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.m_ProcessingHeader = ProcessingHeader() - - self.online = 0 - - self.fp = None - - self.fileSizeByHeader = None - - self.filenameList = [] - - self.filename = None - - self.fileSize = None - - self.firstHeaderSize = 0 - - self.basicHeaderSize = 24 - - self.dataType = None - - self.maxTimeStep = 30 - - self.flagNoMoreFiles = 0 - - self.set = 0 - - self.path = None - - self.delay = 60 #seconds - - self.nTries = 3 #quantity tries - - self.nFiles = 3 #number of files for searching - - self.nReadBlocks = 0 - - self.flagIsNewFile = 1 - - self.ippSeconds = 0 - - self.flagResetProcessing = 0 - - self.flagIsNewBlock = 0 - - self.nTotalBlocks = 0 - - self.blocksize = 0 - - def createObjByDefault(self): - - dataObj = Spectra() - - return dataObj - - def __hasNotDataInBuffer(self): - return 1 - - - def getBlockDimension(self): - """ - Obtiene la cantidad de puntos a leer por cada bloque de datos - - Affected: - self.nChannels - self.nPairs - self.pts2read_SelfSpectra - self.pts2read_CrossSpectra - self.pts2read_DCchannels - self.blocksize - self.dataOutObj.nChannels - self.dataOutObj.nPairs - - Return: - None - """ - self.nChannels = 0 - self.nPairs = 0 - self.pairList = [] - - for i in range( 0, self.m_ProcessingHeader.totalSpectra*2, 2 ): - if self.m_ProcessingHeader.spectraComb[i] == self.m_ProcessingHeader.spectraComb[i+1]: - self.nChannels = self.nChannels + 1 #par de canales iguales - else: - self.nPairs = self.nPairs + 1 #par de canales diferentes - self.pairList.append( (self.m_ProcessingHeader.spectraComb[i], self.m_ProcessingHeader.spectraComb[i+1]) ) - - pts2read = self.m_ProcessingHeader.numHeights * self.m_ProcessingHeader.profilesPerBlock - - self.pts2read_SelfSpectra = int(self.nChannels * pts2read) - self.blocksize = self.pts2read_SelfSpectra - - if self.m_ProcessingHeader.flag_cspc: - self.pts2read_CrossSpectra = int(self.nPairs * pts2read) - self.blocksize += self.pts2read_CrossSpectra - - if self.m_ProcessingHeader.flag_dc: - self.pts2read_DCchannels = int(self.systemHeaderObj.numChannels * self.m_ProcessingHeader.numHeights) - self.blocksize += self.pts2read_DCchannels - -# self.blocksize = self.pts2read_SelfSpectra + self.pts2read_CrossSpectra + self.pts2read_DCchannels - - - def readBlock(self): - """ - Lee el bloque de datos desde la posicion actual del puntero del archivo - (self.fp) y actualiza todos los parametros relacionados al bloque de datos - (metadata + data). La data leida es almacenada en el buffer y el contador del buffer - es seteado a 0 - - Return: None - - Variables afectadas: - self.datablockIndex - self.flagIsNewFile - self.flagIsNewBlock - self.nTotalBlocks - self.data_spc - self.data_cspc - self.data_dc - - Exceptions: - Si un bloque leido no es un bloque valido - """ - blockOk_flag = False - fpointer = self.fp.tell() - - spc = numpy.fromfile( self.fp, self.dataType[0], self.pts2read_SelfSpectra ) - spc = spc.reshape( (self.nChannels, self.m_ProcessingHeader.numHeights, self.m_ProcessingHeader.profilesPerBlock) ) #transforma a un arreglo 3D - - if self.flag_cspc: - cspc = numpy.fromfile( self.fp, self.dataType, self.pts2read_CrossSpectra ) - cspc = cspc.reshape( (self.nPairs, self.m_ProcessingHeader.numHeights, self.m_ProcessingHeader.profilesPerBlock) ) #transforma a un arreglo 3D - - if self.m_ProcessingHeader.flag_dc: - dc = numpy.fromfile( self.fp, self.dataType, self.pts2read_DCchannels ) #int(self.m_ProcessingHeader.numHeights*self.systemHeaderObj.numChannels) ) - dc = dc.reshape( (self.systemHeaderObj.numChannels, self.m_ProcessingHeader.numHeights) ) #transforma a un arreglo 2D - - - if not(self.m_ProcessingHeader.shif_fft): - spc = numpy.roll( spc, self.m_ProcessingHeader.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones - - if self.flag_cspc: - cspc = numpy.roll( cspc, self.m_ProcessingHeader.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones - - - spc = numpy.transpose( spc, (0,2,1) ) - self.data_spc = spc - - if self.flag_cspc: - cspc = numpy.transpose( cspc, (0,2,1) ) - self.data_cspc = cspc['real'] + cspc['imag']*1j - else: - self.data_cspc = None - - if self.m_ProcessingHeader.flag_dc: - self.data_dc = dc['real'] + dc['imag']*1j - else: - self.data_dc = None - - self.datablockIndex = 0 - self.flagIsNewFile = 0 - self.flagIsNewBlock = 1 - - self.nTotalBlocks += 1 - self.nReadBlocks += 1 - - return 1 - - - def getData(self): - """ - Copia el buffer de lectura a la clase "Spectra", - con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de - lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock" - - Return: - 0 : Si no hay mas archivos disponibles - 1 : Si hizo una buena copia del buffer - - Affected: - self.dataOutObj - self.datablockIndex - self.flagResetProcessing - self.flagIsNewBlock - """ - - if self.flagNoMoreFiles: return 0 - - self.flagResetProcessing = 0 - self.flagIsNewBlock = 0 - - if self.__hasNotDataInBuffer(): - - if not( self.readNextBlock() ): - return 0 - - self.updateDataHeader() - - if self.flagNoMoreFiles == 1: - print 'Process finished' - return 0 - - #data es un numpy array de 3 dmensiones (perfiles, alturas y canales) - - if self.data_dc == None: - self.dataOutObj.flagNoData = True - return 0 - - self.dataOutObj.flagNoData = False - self.dataOutObj.flagResetProcessing = self.flagResetProcessing - - self.dataOutObj.data_spc = self.data_spc - self.dataOutObj.data_cspc = self.data_cspc - self.dataOutObj.data_dc = self.data_dc - - return 1 - - -class SpectraWriter(JRODataWriter): - - """ - Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura - de los datos siempre se realiza por bloques. - """ - - dataOutObj = None - - shape_spc_Buffer = None - shape_cspc_Buffer = None - shape_dc_Buffer = None - - data_spc = None - data_cspc = None - data_dc = None - - - def __init__(self, dataOutObj=None): - """ - Inicializador de la clase SpectraWriter para la escritura de datos de espectros. - - Affected: - self.dataOutObj - self.m_BasicHeader - self.systemHeaderObj - self.radarControllerHeaderObj - self.m_ProcessingHeader - - Return: None - """ - if dataOutObj == None: - dataOutObj = Spectra() - - if not( isinstance(dataOutObj, Spectra) ): - raise ValueError, "in SpectraReader, dataOutObj must be an Spectra class object" - - self.dataOutObj = dataOutObj - - self.ext = ".pdata" - - self.optchar = "P" - - self.shape_spc_Buffer = None - self.shape_cspc_Buffer = None - self.shape_dc_Buffer = None - - self.data_spc = None - self.data_cspc = None - self.data_dc = None - - #################################### - - self.fp = None - - self.nWriteBlocks = 0 - - self.flagIsNewFile = 1 - - self.nTotalBlocks = 0 - - self.flagIsNewBlock = 0 - - self.flagNoMoreFiles = 0 - - self.setFile = None - - self.dataType = None - - self.path = None - - self.noMoreFiles = 0 - - self.filename = None - - self.m_BasicHeader= BasicHeader() - - self.systemHeaderObj = SystemHeader() - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.m_ProcessingHeader = ProcessingHeader() - - - def hasAllDataInBuffer(self): - return 1 - - - def setBlockDimension(self): - """ - Obtiene las formas dimensionales del los subbloques de datos que componen un bloque - - Affected: - self.shape_spc_Buffer - self.shape_cspc_Buffer - self.shape_dc_Buffer - - Return: None - """ - self.shape_spc_Buffer = (self.dataOutObj.nChannels, - self.m_ProcessingHeader.numHeights, - self.m_ProcessingHeader.profilesPerBlock) - - self.shape_cspc_Buffer = (self.dataOutObj.nPairs, - self.m_ProcessingHeader.numHeights, - self.m_ProcessingHeader.profilesPerBlock) - - self.shape_dc_Buffer = (self.systemHeaderObj.numChannels, - self.m_ProcessingHeader.numHeights) - - - def writeBlock(self): - """ - Escribe el buffer en el file designado - - Affected: - self.data_spc - self.data_cspc - self.data_dc - self.flagIsNewFile - self.flagIsNewBlock - self.nTotalBlocks - self.nWriteBlocks - - Return: None - """ - - spc = numpy.transpose( self.data_spc, (0,2,1) ) - if not( self.m_ProcessingHeader.shif_fft ): - spc = numpy.roll( spc, self.m_ProcessingHeader.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones - data = spc.reshape((-1)) - data.tofile(self.fp) - - if self.data_cspc != None: - data = numpy.zeros( self.shape_cspc_Buffer, self.dataType ) - cspc = numpy.transpose( self.data_cspc, (0,2,1) ) - if not( self.m_ProcessingHeader.shif_fft ): - cspc = numpy.roll( cspc, self.m_ProcessingHeader.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones - data['real'] = cspc.real - data['imag'] = cspc.imag - data = data.reshape((-1)) - data.tofile(self.fp) - - data = numpy.zeros( self.shape_dc_Buffer, self.dataType ) - dc = self.data_dc - data['real'] = dc.real - data['imag'] = dc.imag - data = data.reshape((-1)) - data.tofile(self.fp) - - self.data_spc.fill(0) - self.data_dc.fill(0) - if self.data_cspc != None: - self.data_cspc.fill(0) - - self.flagIsNewFile = 0 - self.flagIsNewBlock = 1 - self.nTotalBlocks += 1 - self.nWriteBlocks += 1 - - - def putData(self): - """ - Setea un bloque de datos y luego los escribe en un file - - Affected: - self.data_spc - self.data_cspc - self.data_dc - - Return: - 0 : Si no hay data o no hay mas files que puedan escribirse - 1 : Si se escribio la data de un bloque en un file - """ - self.flagIsNewBlock = 0 - - if self.dataOutObj.flagNoData: - return 0 - - if self.dataOutObj.flagResetProcessing: - self.data_spc.fill(0) - self.data_cspc.fill(0) - self.data_dc.fill(0) - self.setNextFile() - - self.data_spc = self.dataOutObj.data_spc - self.data_cspc = self.dataOutObj.data_cspc - self.data_dc = self.dataOutObj.data_dc - - # #self.m_ProcessingHeader.dataBlocksPerFile) - if self.hasAllDataInBuffer(): - self.getDataHeader() - self.writeNextBlock() - - if self.flagNoMoreFiles: - #print 'Process finished' - return 0 - - return 1 \ No newline at end of file diff --git a/schainpy/old/IO/VoltageIO.py b/schainpy/old/IO/VoltageIO.py deleted file mode 100644 index 040b483..0000000 --- a/schainpy/old/IO/VoltageIO.py +++ /dev/null @@ -1,433 +0,0 @@ -''' -Created on 23/01/2012 - -@author $Author$ -@version $Id$ -''' - -import os, sys -import numpy -import glob -import fnmatch -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.JROHeader import * -from Model.Voltage import Voltage - -from IO.JRODataIO import JRODataReader -from IO.JRODataIO import JRODataWriter - - -class VoltageReader(JRODataReader): - """ - Esta clase permite leer datos de voltage desde archivos en formato rawdata (.r). La lectura - de los datos siempre se realiza por bloques. Los datos leidos (array de 3 dimensiones: - perfiles*alturas*canales) son almacenados en la variable "buffer". - - perfiles * alturas * canales - - Esta clase contiene instancias (objetos) de las clases BasicHeader, SystemHeader, - RadarControllerHeader y Voltage. Los tres primeros se usan para almacenar informacion de la - cabecera de datos (metadata), y el cuarto (Voltage) para obtener y almacenar un perfil de - datos desde el "buffer" cada vez que se ejecute el metodo "getData". - - Example: - - dpath = "/home/myuser/data" - - startTime = datetime.datetime(2010,1,20,0,0,0,0,0,0) - - endTime = datetime.datetime(2010,1,21,23,59,59,0,0,0) - - readerObj = VoltageReader() - - readerObj.setup(dpath, startTime, endTime) - - while(True): - - #to get one profile - profile = readerObj.getData() - - #print the profile - print profile - - #If you want to see all datablock - print readerObj.datablock - - if readerObj.flagNoMoreFiles: - break - - """ - dataOutObj = None - - datablock = None - - ext = ".r" - - optchar = "D" - - - def __init__(self, dataOutObj=None): - """ - Inicializador de la clase VoltageReader para la lectura de datos de voltage. - - Input: - dataOutObj : Objeto de la clase Voltage. Este objeto sera utilizado para - almacenar un perfil de datos cada vez que se haga un requerimiento - (getData). El perfil sera obtenido a partir del buffer de datos, - si el buffer esta vacio se hara un nuevo proceso de lectura de un - bloque de datos. - Si este parametro no es pasado se creara uno internamente. - - Variables afectadas: - self.dataOutObj - - Return: - None - """ - - self.datablock = None - - self.utc = 0 - - self.ext = ".r" - - self.optchar = "D" - - self.m_BasicHeader = BasicHeader() - - self.systemHeaderObj = SystemHeader() - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.m_ProcessingHeader = ProcessingHeader() - - self.online = 0 - - self.fp = None - - self.idFile = None - - self.startDateTime = None - - self.endDateTime = None - - self.dataType = None - - self.fileSizeByHeader = None - - self.filenameList = [] - - self.filename = None - - self.fileSize = None - - self.firstHeaderSize = 0 - - self.basicHeaderSize = 24 - - self.pathList = [] - - self.filenameList = [] - - self.lastUTTime = 0 - - self.maxTimeStep = 30 - - self.flagNoMoreFiles = 0 - - self.set = 0 - - self.path = None - - self.profileIndex = 9999 - - self.delay = 60 #seconds - - self.nTries = 3 #quantity tries - - self.nFiles = 3 #number of files for searching - - self.nReadBlocks = 0 - - self.flagIsNewFile = 1 - - self.ippSeconds = 0 - - self.flagResetProcessing = 0 - - self.flagIsNewBlock = 0 - - self.nTotalBlocks = 0 - - self.blocksize = 0 - - def createObjByDefault(self): - - dataObj = Voltage() - - return dataObj - - def __hasNotDataInBuffer(self): - if self.profileIndex >= self.m_ProcessingHeader.profilesPerBlock: - return 1 - return 0 - - - def getBlockDimension(self): - """ - Obtiene la cantidad de puntos a leer por cada bloque de datos - - Affected: - self.blocksize - - Return: - None - """ - pts2read = self.m_ProcessingHeader.profilesPerBlock * self.m_ProcessingHeader.numHeights * self.systemHeaderObj.numChannels - self.blocksize = pts2read - - - def readBlock(self): - """ - readBlock lee el bloque de datos desde la posicion actual del puntero del archivo - (self.fp) y actualiza todos los parametros relacionados al bloque de datos - (metadata + data). La data leida es almacenada en el buffer y el contador del buffer - es seteado a 0 - - Inputs: - None - - Return: - None - - Affected: - self.profileIndex - self.datablock - self.flagIsNewFile - self.flagIsNewBlock - self.nTotalBlocks - - Exceptions: - Si un bloque leido no es un bloque valido - """ - - junk = numpy.fromfile( self.fp, self.dataType, self.blocksize ) - - try: - junk = junk.reshape( (self.m_ProcessingHeader.profilesPerBlock, self.m_ProcessingHeader.numHeights, self.systemHeaderObj.numChannels) ) - except: - print "The read block (%3d) has not enough data" %self.nReadBlocks - return 0 - - junk = numpy.transpose(junk, (2,0,1)) - self.datablock = junk['real'] + junk['imag']*1j - - self.profileIndex = 0 - - self.flagIsNewFile = 0 - self.flagIsNewBlock = 1 - - self.nTotalBlocks += 1 - self.nReadBlocks += 1 - - return 1 - - - def getData(self): - """ - getData obtiene una unidad de datos del buffer de lectura y la copia a la clase "Voltage" - con todos los parametros asociados a este (metadata). cuando no hay datos en el buffer de - lectura es necesario hacer una nueva lectura de los bloques de datos usando "readNextBlock" - - Ademas incrementa el contador del buffer en 1. - - Return: - data : retorna un perfil de voltages (alturas * canales) copiados desde el - buffer. Si no hay mas archivos a leer retorna None. - - Variables afectadas: - self.dataOutObj - self.profileIndex - - Affected: - self.dataOutObj - self.profileIndex - self.flagResetProcessing - self.flagIsNewBlock - """ - if self.flagNoMoreFiles: return 0 - - self.flagResetProcessing = 0 - self.flagIsNewBlock = 0 - - if self.__hasNotDataInBuffer(): - - if not( self.readNextBlock() ): - return 0 - - self.updateDataHeader() - - if self.flagNoMoreFiles == 1: - print 'Process finished' - return 0 - - #data es un numpy array de 3 dmensiones (perfiles, alturas y canales) - - if self.datablock == None: - self.dataOutObj.flagNoData = True - return 0 - - time = self.m_BasicHeader.utc + self.profileIndex * self.ippSeconds - self.dataOutObj.m_BasicHeader.utc = time - - self.dataOutObj.flagNoData = False - self.dataOutObj.flagResetProcessing = self.flagResetProcessing - - self.dataOutObj.data = self.datablock[:,self.profileIndex,:] - - self.profileIndex += 1 - - #call setData - to Data Object - - return 1 #self.dataOutObj.data - - -class VoltageWriter(JRODataWriter): - """ - Esta clase permite escribir datos de voltajes a archivos procesados (.r). La escritura - de los datos siempre se realiza por bloques. - """ - __configHeaderFile = 'wrSetHeadet.txt' - - dataOutObj = None - - ext = ".r" - - optchar = "D" - - datablock = None - - profileIndex = 0 - - shapeBuffer = None - - - def __init__(self, dataOutObj=None): - """ - Inicializador de la clase VoltageWriter para la escritura de datos de espectros. - - Affected: - self.dataOutObj - - Return: None - """ - if dataOutObj == None: - dataOutObj = Voltage() - - if not( isinstance(dataOutObj, Voltage) ): - raise ValueError, "in VoltageReader, dataOutObj must be an Spectra class object" - - self.dataOutObj = dataOutObj - - - def hasAllDataInBuffer(self): - if self.profileIndex >= self.m_ProcessingHeader.profilesPerBlock: - return 1 - return 0 - - - def setBlockDimension(self): - """ - Obtiene las formas dimensionales del los subbloques de datos que componen un bloque - - Affected: - self.shape_spc_Buffer - self.shape_cspc_Buffer - self.shape_dc_Buffer - - Return: None - """ - self.shapeBuffer = (self.m_ProcessingHeader.profilesPerBlock, - self.m_ProcessingHeader.numHeights, - self.systemHeaderObj.numChannels ) - - self.datablock = numpy.zeros((self.systemHeaderObj.numChannels, - self.m_ProcessingHeader.profilesPerBlock, - self.m_ProcessingHeader.numHeights), - dtype=numpy.dtype('complex')) - - - def writeBlock(self): - """ - Escribe el buffer en el file designado - - Affected: - self.profileIndex - self.flagIsNewFile - self.flagIsNewBlock - self.nTotalBlocks - self.nWriteBlocks - - Return: None - """ - data = numpy.zeros( self.shapeBuffer, self.dataType ) - - junk = numpy.transpose(self.datablock, (1,2,0)) - - data['real'] = junk.real - data['imag'] = junk.imag - - data = data.reshape( (-1) ) - - data.tofile( self.fp ) - - self.datablock.fill(0) - self.profileIndex = 0 - self.flagIsNewFile = 0 - self.flagIsNewBlock = 1 - self.nTotalBlocks += 1 - self.nWriteBlocks += 1 - - - def putData(self): - """ - Setea un bloque de datos y luego los escribe en un file - - Affected: - self.flagIsNewBlock - self.profileIndex - - Return: - 0 : Si no hay data o no hay mas files que puedan escribirse - 1 : Si se escribio la data de un bloque en un file - """ - self.flagIsNewBlock = 0 - - if self.dataOutObj.flagNoData: - return 0 - - if self.dataOutObj.flagResetProcessing: - - self.datablock.fill(0) - self.profileIndex = 0 - self.setNextFile() - - self.datablock[:,self.profileIndex,:] = self.dataOutObj.data - - self.profileIndex += 1 - - if self.hasAllDataInBuffer(): - #if self.flagIsNewFile: - self.getDataHeader() - self.writeNextBlock() - - if self.flagNoMoreFiles: - #print 'Process finished' - return 0 - - return 1 - \ No newline at end of file diff --git a/schainpy/old/IO/__init__.py b/schainpy/old/IO/__init__.py deleted file mode 100644 index 362268c..0000000 --- a/schainpy/old/IO/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -''' -Created on 23/01/2012 - -@author $Author$ -@version $Id$ -''' diff --git a/schainpy/old/Model/Correlation.py b/schainpy/old/Model/Correlation.py deleted file mode 100644 index c97a2ad..0000000 --- a/schainpy/old/Model/Correlation.py +++ /dev/null @@ -1,60 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' -from JROData import JROData, Noise -from JROHeader import RadarControllerHeader, ProcessingHeader, SystemHeader, BasicHeader - -class Correlation(JROData): - ''' - classdocs - ''' - - data = None - - nLags = None - - lagsList = None - - def __init__(self): - ''' - Constructor - ''' - - self.m_RadarControllerHeader = RadarControllerHeader() - - self.m_ProcessingHeader = ProcessingHeader() - - self.m_SystemHeader = SystemHeader() - - self.m_BasicHeader = BasicHeader() - - self.m_NoiseObj = Noise() - - self.type = "Correlation" - - self.dataType = None - - self.nHeights = 0 - - self.nChannels = 0 - - self.channelList = None - - self.heightList = None - - self.flagNoData = True - - self.flagResetProcessing = False - - - self.data = None - - self.nLags = 0 - - self.tauList = None - - self.pairList = None - \ No newline at end of file diff --git a/schainpy/old/Model/JROData.py b/schainpy/old/Model/JROData.py deleted file mode 100644 index c6b8b15..0000000 --- a/schainpy/old/Model/JROData.py +++ /dev/null @@ -1,105 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' -import copy -import numpy - -from JROHeader import RadarControllerHeader, ProcessingHeader, SystemHeader, BasicHeader - -class Data: - ''' - classdocs - ''' - - def __init__(self): - ''' - Constructor - ''' - raise ValueError, "This class has not been implemented" - - def copy(self, objIn=None): - - if objIn == None: - return copy.deepcopy(self) - - for key in objIn.__dict__.keys(): - self.__dict__[key] = objIn.__dict__[key] - - def deepcopy(self): - - return copy.deepcopy(self) - - - -class JROData(Data): - ''' - classdocs - ''' - - radarControllerHeaderObj = RadarControllerHeader() - - m_ProcessingHeader = ProcessingHeader() - - systemHeaderObj = SystemHeader() - - m_BasicHeader = BasicHeader() - - noise = None - - type = None - - dataType = None - - nHeights = None - - nProfiles = None - - nChannels = None - - heightList = None - - channelList = None - - channelIndexList = None - - pairList = None - - flagNoData = False - - flagResetProcessing = False - - def __init__(self): - ''' - Constructor - ''' - raise ValueError, "This class has not been implemented" - - def updateHeaderFromObj(self): - - xi = self.heightList[0] - step = self.heightList[1] - self.heightList[0] - - self.m_ProcessingHeader.firstHeight = xi - self.m_ProcessingHeader.deltaHeight = step - - self.m_ProcessingHeader.numHeights = self.nHeights - self.systemHeaderObj.numChannels = self.nChannels - self.systemHeaderObj.numProfiles = self.nProfiles - - def updateObjFromHeader(self): - - xi = self.m_ProcessingHeader.firstHeight - step = self.m_ProcessingHeader.deltaHeight - xf = xi + self.m_ProcessingHeader.numHeights*step - - self.heightList = numpy.arange(xi, xf, step) - self.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) - self.channelList = numpy.arange(self.systemHeaderObj.numChannels) - - self.nHeights = len(self.heightList) - self.nProfiles = self.systemHeaderObj.numProfiles - self.nChannels = len(self.channelList) - \ No newline at end of file diff --git a/schainpy/old/Model/JROHeader.py b/schainpy/old/Model/JROHeader.py deleted file mode 100644 index 8ec4b69..0000000 --- a/schainpy/old/Model/JROHeader.py +++ /dev/null @@ -1,505 +0,0 @@ -''' -Created on 23/01/2012 - -@author $Author: vsarmiento $ -@version $Id: HeaderIO.py 37 2012-03-26 22:55:13Z vsarmiento $ -''' - -import numpy -import copy - -class Header: - - def __init__(self): - raise - - def copy(self): - return copy.deepcopy(self) - - def read(): - pass - - def write(): - pass - -class BasicHeader(Header): - - size = None - version = None - dataBlock = None - utc = None - miliSecond = None - timeZone = None - dstFlag = None - errorCount = None - struct = None - - def __init__(self): - self.size = 0 - self.version = 0 - self.dataBlock = 0 - self.utc = 0 - self.miliSecond = 0 - self.timeZone = 0 - self.dstFlag = 0 - self.errorCount = 0 - self.struct = numpy.dtype([ - ('nSize',' 0: - fp.seek(jumpFp) - - except: - return 0 - - return 1 - - def write(self, fp): - headerTuple = (self.size, - self.expType, - self.nTx, - self.ipp, - self.txA, - self.txB, - self.numWindows, - self.numTaus, - self.codeType, - self.line6Function, - self.line5Function, - self.fClock, - self.prePulseBefore, - self.prePulserAfter, - self.rangeIpp, - self.rangeTxA, - self.rangeTxB) - - header = numpy.array(headerTuple,self.struct) - header.tofile(fp) - - dynamic = self.dynamic - dynamic.tofile(fp) - - return 1 - - - -class ProcessingHeader(Header): - - size = None - dataType = None - blockSize = None - profilesPerBlock = None - dataBlocksPerFile = None - numWindows = None - processFlags = None - coherentInt = None - incoherentInt = None - totalSpectra = None - struct = None - flag_dc = None - flag_cspc = None - - def __init__(self): - self.size = 0 - self.dataType = 0 - self.blockSize = 0 - self.profilesPerBlock = 0 - self.dataBlocksPerFile = 0 - self.numWindows = 0 - self.processFlags = 0 - self.coherentInt = 0 - self.incoherentInt = 0 - self.totalSpectra = 0 - self.struct = numpy.dtype([ - ('nSize',' 0: - self.flag_cspc = True - - except: - return 0 - - return 1 - - def write(self, fp): - headerTuple = (self.size, - self.dataType, - self.blockSize, - self.profilesPerBlock, - self.dataBlocksPerFile, - self.numWindows, - self.processFlags, - self.coherentInt, - self.incoherentInt, - self.totalSpectra) - - header = numpy.array(headerTuple,self.struct) - header.tofile(fp) - - if self.numWindows != 0: - sampleWindowTuple = (self.firstHeight,self.deltaHeight,self.samplesWin) - samplingWindow = numpy.array(sampleWindowTuple,self.structSamplingWindow) - samplingWindow.tofile(fp) - - - if self.totalSpectra != 0: - spectraComb = numpy.array([],numpy.dtype('u1')) - spectraComb = self.spectraComb - spectraComb.tofile(fp) - - - if self.processFlags & PROCFLAG.DEFINE_PROCESS_CODE == PROCFLAG.DEFINE_PROCESS_CODE: - numCode = self.numCode - numCode.tofile(fp) - - numBaud = self.numBaud - numBaud.tofile(fp) - - code = self.code.reshape(numCode*numBaud) - code.tofile(fp) - - return 1 - -class RCfunction: - NONE=0 - FLIP=1 - CODE=2 - SAMPLING=3 - LIN6DIV256=4 - SYNCHRO=5 - -class nCodeType: - NONE=0 - USERDEFINE=1 - BARKER2=2 - BARKER3=3 - BARKER4=4 - BARKER5=5 - BARKER7=6 - BARKER11=7 - BARKER13=8 - AC128=9 - COMPLEMENTARYCODE2=10 - COMPLEMENTARYCODE4=11 - COMPLEMENTARYCODE8=12 - COMPLEMENTARYCODE16=13 - COMPLEMENTARYCODE32=14 - COMPLEMENTARYCODE64=15 - COMPLEMENTARYCODE128=16 - CODE_BINARY28=17 - -class PROCFLAG: - COHERENT_INTEGRATION = numpy.uint32(0x00000001) - DECODE_DATA = numpy.uint32(0x00000002) - SPECTRA_CALC = numpy.uint32(0x00000004) - INCOHERENT_INTEGRATION = numpy.uint32(0x00000008) - POST_COHERENT_INTEGRATION = numpy.uint32(0x00000010) - SHIFT_FFT_DATA = numpy.uint32(0x00000020) - - DATATYPE_CHAR = numpy.uint32(0x00000040) - DATATYPE_SHORT = numpy.uint32(0x00000080) - DATATYPE_LONG = numpy.uint32(0x00000100) - DATATYPE_INT64 = numpy.uint32(0x00000200) - DATATYPE_FLOAT = numpy.uint32(0x00000400) - DATATYPE_DOUBLE = numpy.uint32(0x00000800) - - DATAARRANGE_CONTIGUOUS_CH = numpy.uint32(0x00001000) - DATAARRANGE_CONTIGUOUS_H = numpy.uint32(0x00002000) - DATAARRANGE_CONTIGUOUS_P = numpy.uint32(0x00004000) - - SAVE_CHANNELS_DC = numpy.uint32(0x00008000) - DEFLIP_DATA = numpy.uint32(0x00010000) - DEFINE_PROCESS_CODE = numpy.uint32(0x00020000) - - ACQ_SYS_NATALIA = numpy.uint32(0x00040000) - ACQ_SYS_ECHOTEK = numpy.uint32(0x00080000) - ACQ_SYS_ADRXD = numpy.uint32(0x000C0000) - ACQ_SYS_JULIA = numpy.uint32(0x00100000) - ACQ_SYS_XXXXXX = numpy.uint32(0x00140000) - - EXP_NAME_ESP = numpy.uint32(0x00200000) - CHANNEL_NAMES_ESP = numpy.uint32(0x00400000) - - OPERATION_MASK = numpy.uint32(0x0000003F) - DATATYPE_MASK = numpy.uint32(0x00000FC0) - DATAARRANGE_MASK = numpy.uint32(0x00007000) - ACQ_SYS_MASK = numpy.uint32(0x001C0000) \ No newline at end of file diff --git a/schainpy/old/Model/Spectra.py b/schainpy/old/Model/Spectra.py deleted file mode 100644 index f01c604..0000000 --- a/schainpy/old/Model/Spectra.py +++ /dev/null @@ -1,76 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -from JROData import JROData -from JROHeader import RadarControllerHeader, ProcessingHeader, SystemHeader, BasicHeader - -class Spectra(JROData): - ''' - classdocs - ''' - - data_spc = None - - data_cspc = None - - data_dc = None - - nFFTPoints = None - - nPairs = None - - pairsList = None - - - def __init__(self): - ''' - Constructor - ''' - - self.m_RadarControllerHeader = RadarControllerHeader() - - self.m_ProcessingHeader = ProcessingHeader() - - self.m_SystemHeader = SystemHeader() - - self.m_BasicHeader = BasicHeader() - - self.type = "Spectra" - - self.dataType = None - - self.nHeights = 0 - - self.nChannels = 0 - - self.channelList = None - - self.heightList = None - - self.flagNoData = True - - self.flagResetProcessing = False - - - #data es un numpy array de 3 dmensiones (perfiles, alturas y canales) - self.data_spc = None - - self.data_cspc = None - - self.data_dc = None - - self.nFFTPoints = None - - self.nAvg = None - - self.nPairs = 0 - - self.pairsList = None - - - - \ No newline at end of file diff --git a/schainpy/old/Model/Voltage.py b/schainpy/old/Model/Voltage.py deleted file mode 100644 index f06c2ea..0000000 --- a/schainpy/old/Model/Voltage.py +++ /dev/null @@ -1,61 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -from JROData import JROData -from JROHeader import RadarControllerHeader, ProcessingHeader, SystemHeader, BasicHeader - -class Voltage(JROData): - ''' - classdocs - ''' - - data = None - - nProfiles = None - - profileIndex = None - - def __init__(self): - ''' - Constructor - ''' - - self.m_RadarControllerHeader = RadarControllerHeader() - - self.m_ProcessingHeader = ProcessingHeader() - - self.m_SystemHeader = SystemHeader() - - self.m_BasicHeader = BasicHeader() - - self.type = "Voltage" - - #data es un numpy array de 3 dmensiones (perfiles, alturas y canales) - self.data = None - - self.dataType = None - - self.nHeights = 0 - - self.nChannels = 0 - - self.channelList = None - - self.heightList = None - - self.flagNoData = True - - self.flagResetProcessing = False - - self.nAvg = None - - self.profileIndex = None - - self.nProfiles = None - - - \ No newline at end of file diff --git a/schainpy/old/Model/__init__.py b/schainpy/old/Model/__init__.py deleted file mode 100644 index 7d0d670..0000000 --- a/schainpy/old/Model/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' \ No newline at end of file diff --git a/schainpy/old/Processing/CorrelationProcessor.py b/schainpy/old/Processing/CorrelationProcessor.py deleted file mode 100644 index 0394b93..0000000 --- a/schainpy/old/Processing/CorrelationProcessor.py +++ /dev/null @@ -1,146 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -import os, sys -import numpy - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.Correlation import Correlation -from IO.CorrelationIO import CorrelationWriter -#from Graphics.CorrelationPlot import Correlator - - -from Model.Voltage import Voltage -from Model.Spectra import Spectra - -class CorrelationProcessor: - ''' - classdocs - ''' - - integratorIndex = None - writerIndex = None - plotterIndex = None - - lagsList = None - - nLags = None - tauList = None - pairList = None - indexTau = None - - - def __init__(self,dataInObj, dataOutObj=None): - ''' - Constructor - ''' - self.dataInObj = dataInObj - - if dataOutObj == None: - self.dataOutObj = Correlation() - else: - self.dataOutObj = dataOutObj - - self.indexTau = 0 - self.buffer = None - - def init(self,pairList=None,tauList=None): - - self.integratorIndex = 0 - self.writerIndex = 0 - self.plotterIndex = 0 - - self.pairList = pairList - self.tauList = tauList - - if ( isinstance(self.dataInObj, Voltage) ): - self.__getCorrelation() - - if ( isinstance(self.dataInObj, Spectra) ): - sys.exit(0) - - if ( isinstance(self.dataInObj, Correlation) ): - sel.__getCopy() - - def __getCorrelation(self): - if self.dataInObj.flagNoData: - return 0 - - if self.tauList == None: # se lee el tauList desde el archivo - flip = None - if self.dataInObj.m_RadarControllerHeader.flip1 != None: - flip = self.dataInObj.m_RadarControllerHeader.flip1 - - if self.dataInObj.m_RadarControllerHeader.flip2 != None: - flip = self.dataInObj.m_RadarControllerHeader.flip2 - - if flip == None: - flip = 2 - print 'flip is None --> flip = %d '%flip - - ntaus = self.dataInObj.m_RadarControllerHeader.numTaus - taus = self.dataInObj.m_RadarControllerHeader.Taus.reshape(ntaus/flip,flip) - - index = 0 - self.tauList = taus[:,index] - print 'tauList is None --> tauList = obj.m_RadarControllerHeader.Taus[:,%d]'%index - - self.nLags = len(self.tauList) - - if self.pairList == None: - self.pairList = [(0,0)] # por defecto calcula la AutoCorrelacion de una canal - - self.dataOutObj.tauList = self.tauList - self.dataOutObj.nLags = self.nLags - self.dataOutObj.pairList = self.pairList - - if self.buffer == None: - nhei = self.dataInObj.nHeights - npairList = len(self.pairList) - self.buffer = numpy.zeros((self.nLags,nhei,npairList),dtype='complex') - - bufferZ = numpy.zeros((npairList,self.dataInObj.nHeights),dtype='complex') - - indexHeight = self.tauList[self.indexTau] / self.dataInObj.m_ProcessingHeader.deltaHeight - - countPair = 0 - - # make (signalA*signalB'), where signalA: channel without delay, signalB: channel with delay, - for pair in self.pairList: - bufferZ[countPair,0:self.dataInObj.nHeights-indexHeight] = self.dataInObj.data[pair[1],indexHeight:self.dataInObj.nHeights] - signalA = self.dataInObj.data[pair[0],:] - signalB = bufferZ[countPair,:] - data = signalA * numpy.conjugate(signalB) - self.buffer[self.indexTau,:,countPair] = data - countPair += 1 - - # change index Tau and lagCounter - self.indexTau += 1 - if self.indexTau >= self.nLags: - self.indexTau = 0 - self.dataOutObj.data = self.buffer - self.buffer = None - self.dataOutObj.flagNoData = False - else: - self.dataOutObj.flagNoData = True - - - def addIntegrator(self): - pass - - def addWriter(self): - pass - - def addPlotter(self): - pass - -class Integrator(): - def __init__(self): - pass - diff --git a/schainpy/old/Processing/JRONoise.py b/schainpy/old/Processing/JRONoise.py deleted file mode 100644 index e332aeb..0000000 --- a/schainpy/old/Processing/JRONoise.py +++ /dev/null @@ -1,200 +0,0 @@ -import numpy - -def hildebrand_sekhon(data, navg): - """ - This method is for the objective determination of de noise level in Doppler spectra. This - implementation technique is based on the fact that the standard deviation of the spectral - densities is equal to the mean spectral density for white Gaussian noise - - Inputs: - Data : heights - navg : numbers of averages - - Return: - -1 : any error - anoise : noise's level - """ - - dataflat = data.reshape(-1) - dataflat.sort() - npts = dataflat.size #numbers of points of the data - - if npts < 32: - print "error in noise - requires at least 32 points" - return -1.0 - - dataflat2 = numpy.power(dataflat,2) - - cs = numpy.cumsum(dataflat) - cs2 = numpy.cumsum(dataflat2) - - # data sorted in ascending order - nmin = int((npts + 7.)/8) - - for i in range(nmin, npts): - s = cs[i] - s2 = cs2[i] - p = s / float(i); - p2 = p**2; - q = s2 / float(i) - p2; - leftc = p2; - rightc = q * float(navg); - R2 = leftc/rightc - - # Signal detect: R2 < 1 (R2 = leftc/rightc) - if R2 < 1: - npts_noise = i - break - - - anoise = numpy.average(dataflat[0:npts_noise]) - - return anoise; - -def sorting_bruce(Data, navg): - sortdata = numpy.sort(Data) - lenOfData = len(Data) - nums_min = lenOfData/10 - - if (lenOfData/10) > 0: - nums_min = lenOfData/10 - else: - nums_min = 0 - - rtest = 1.0 + 1.0/navg - - sum = 0. - - sumq = 0. - - j = 0 - - cont = 1 - - while((cont==1)and(j nums_min: - if ((sumq*j) <= (rtest*sum**2)): - lnoise = sum / j - else: - j = j - 1 - sum = sum - sordata[j] - sumq = sumq - sordata[j]**2 - cont = 0 - - if j == nums_min: - lnoise = sum /j - - return lnoise - -class Noise: - """ - Clase que implementa los metodos necesarios para deternimar el nivel de ruido en un Spectro Doppler - """ - data = None - noise = None - dim = None - - def __init__(self, data=None): - """ - Inicializador de la clase Noise para la la determinacion del nivel de ruido en un Spectro Doppler. - - Inputs: - data: Numpy array de la forma nChan x nHeis x nProfiles - - Affected: - self.noise - - Return: - None - """ - - self.data = data - self.dim = None - self.nChannels = None - self.noise = None - - def setNoise(self, data): - """ - Inicializador de la clase Noise para la la determinacion del nivel de ruido en un Spectro Doppler. - - Inputs: - data: Numpy array de la forma nChan x nHeis x nProfiles - - Affected: - self.noise - - Return: - None - """ - - if data == None: - raise ValueError, "The data value is not defined" - - shape = data.shape - self.dim = len(shape) - if self.dim == 3: - nChan, nProfiles, nHeis = shape - elif self.dim == 2: - nChan, nHeis = shape - else: - raise ValueError, "" - - self.nChannels = nChan - self.data = data.copy() - self.noise = numpy.zeros(nChan) - - return 1 - - - def byHildebrand(self, navg=1): - """ - Determino el nivel de ruido usando el metodo Hildebrand-Sekhon - - Return: - noiselevel - """ - - daux = None - - for channel in range(self.nChannels): - daux = self.data[channel,:,:] - self.noise[channel] = hildebrand_sekhon(daux, navg) - return self.noise - - def byWindow(self, heiIndexMin, heiIndexMax, freqIndexMin, freqIndexMax): - """ - Determina el ruido del canal utilizando la ventana indicada con las coordenadas: - (heiIndexMIn, freqIndexMin) hasta (heiIndexMax, freqIndexMAx) - - Inputs: - heiIndexMin: Limite inferior del eje de alturas - heiIndexMax: Limite superior del eje de alturas - freqIndexMin: Limite inferior del eje de frecuencia - freqIndexMax: Limite supoerior del eje de frecuencia - """ - - data = self.data[:, heiIndexMin:heiIndexMax, freqIndexMin:freqIndexMax] - - for channel in range(self.nChannels): - daux = data[channel,:,:] - self.noise[channel] = numpy.average(daux) - - return self.noise - - def bySort(self,navg = 1): - daux = None - - for channel in range(self.nChannels): - daux = self.data[channel,:,:] - self.noise[channel] = sorting_bruce(daux, navg) - - return self.noise - - \ No newline at end of file diff --git a/schainpy/old/Processing/SpectraProcessor.py b/schainpy/old/Processing/SpectraProcessor.py deleted file mode 100644 index ab92820..0000000 --- a/schainpy/old/Processing/SpectraProcessor.py +++ /dev/null @@ -1,700 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' -import os, sys -import numpy -import time - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.Spectra import Spectra -from IO.SpectraIO import SpectraWriter -from Graphics.SpectraPlot import Spectrum -from JRONoise import Noise - -class SpectraProcessor: - ''' - classdocs - ''' - - dataInObj = None - - dataOutObj = None - - noiseObj = None - - integratorObjList = [] - - decoderObjList = [] - - writerObjList = [] - - plotterObjList = [] - - integratorObjIndex = None - - decoderObjIndex = None - - writerObjIndex = None - - plotterObjIndex = None - - buffer = None - - profIndex = 0 - - nFFTPoints = None - - nChannels = None - - nHeights = None - - nPairs = None - - pairList = None - - - def __init__(self): - ''' - Constructor - ''' - - self.integratorObjIndex = None - self.decoderObjIndex = None - self.writerObjIndex = None - self.plotterObjIndex = None - - self.integratorObjList = [] - self.decoderObjList = [] - self.writerObjList = [] - self.plotterObjList = [] - - self.noiseObj = None - self.buffer = None - self.profIndex = 0 - - def setup(self, dataInObj=None, dataOutObj=None, nFFTPoints=None, pairList=None): - - if dataInObj == None: - raise ValueError, "" - - if nFFTPoints == None: - raise ValueError, "" - - self.dataInObj = dataInObj - - if dataOutObj == None: - dataOutObj = Spectra() - - self.dataOutObj = dataOutObj - self.noiseObj = Noise() - - ########################################## - self.nFFTPoints = nFFTPoints - self.nChannels = self.dataInObj.nChannels - self.nHeights = self.dataInObj.nHeights - self.pairList = pairList - if pairList != None: - self.nPairs = len(pairList) - else: - self.nPairs = 0 - - self.dataOutObj.heightList = self.dataInObj.heightList - self.dataOutObj.channelIndexList = self.dataInObj.channelIndexList - self.dataOutObj.m_BasicHeader = self.dataInObj.m_BasicHeader.copy() - self.dataOutObj.m_ProcessingHeader = self.dataInObj.m_ProcessingHeader.copy() - self.dataOutObj.radarControllerHeaderObj = self.dataInObj.radarControllerHeaderObj.copy() - self.dataOutObj.systemHeaderObj = self.dataInObj.systemHeaderObj.copy() - - self.dataOutObj.dataType = self.dataInObj.dataType - self.dataOutObj.nPairs = self.nPairs - self.dataOutObj.nChannels = self.nChannels - self.dataOutObj.nProfiles = self.nFFTPoints - self.dataOutObj.nHeights = self.nHeights - self.dataOutObj.nFFTPoints = self.nFFTPoints - #self.dataOutObj.data = None - - self.dataOutObj.systemHeaderObj.numChannels = self.nChannels - self.dataOutObj.systemHeaderObj.nProfiles = self.nFFTPoints - - self.dataOutObj.m_ProcessingHeader.totalSpectra = self.nChannels + self.nPairs - self.dataOutObj.m_ProcessingHeader.profilesPerBlock = self.nFFTPoints - self.dataOutObj.m_ProcessingHeader.numHeights = self.nHeights - self.dataOutObj.m_ProcessingHeader.shif_fft = True - - spectraComb = numpy.zeros( (self.nChannels+self.nPairs)*2,numpy.dtype('u1')) - k = 0 - for i in range( 0,self.nChannels*2,2 ): - spectraComb[i] = k - spectraComb[i+1] = k - k += 1 - - k *= 2 - - if self.pairList != None: - - for pair in self.pairList: - spectraComb[k] = pair[0] - spectraComb[k+1] = pair[1] - k += 2 - - self.dataOutObj.m_ProcessingHeader.spectraComb = spectraComb - - return self.dataOutObj - - def init(self): - - self.nHeights = self.dataInObj.nHeights - self.dataOutObj.nHeights = self.nHeights - self.dataOutObj.heightList = self.dataInObj.heightList - - self.integratorObjIndex = 0 - self.decoderObjIndex = 0 - self.writerObjIndex = 0 - self.plotterObjIndex = 0 - - if self.dataInObj.type == "Voltage": - - if self.buffer == None: - self.buffer = numpy.zeros((self.nChannels, - self.nFFTPoints, - self.dataInObj.nHeights), - dtype='complex') - - self.buffer[:,self.profIndex,:] = self.dataInObj.data - self.profIndex += 1 - - if self.profIndex == self.nFFTPoints: - self.__getFft() - self.dataOutObj.flagNoData = False - - self.buffer = None - self.profIndex = 0 - return - - self.dataOutObj.flagNoData = True - - return - - #Other kind of data - if self.dataInObj.type == "Spectra": - self.dataOutObj.copy(self.dataInObj) - self.dataOutObj.flagNoData = False - return - - raise ValueError, "The datatype is not valid" - - def __getFft(self): - """ - Convierte valores de Voltaje a Spectra - - Affected: - self.dataOutObj.data_spc - self.dataOutObj.data_cspc - self.dataOutObj.data_dc - self.dataOutObj.heightList - self.dataOutObj.m_BasicHeader - self.dataOutObj.m_ProcessingHeader - self.dataOutObj.radarControllerHeaderObj - self.dataOutObj.systemHeaderObj - self.profIndex - self.buffer - self.dataOutObj.flagNoData - self.dataOutObj.dataType - self.dataOutObj.nPairs - self.dataOutObj.nChannels - self.dataOutObj.nProfiles - self.dataOutObj.systemHeaderObj.numChannels - self.dataOutObj.m_ProcessingHeader.totalSpectra - self.dataOutObj.m_ProcessingHeader.profilesPerBlock - self.dataOutObj.m_ProcessingHeader.numHeights - self.dataOutObj.m_ProcessingHeader.spectraComb - self.dataOutObj.m_ProcessingHeader.shif_fft - """ - - if self.dataInObj.flagNoData: - return 0 - - fft_volt = numpy.fft.fft(self.buffer,axis=1) - dc = fft_volt[:,0,:] - - #calculo de self-spectra - fft_volt = numpy.fft.fftshift(fft_volt,axes=(1,)) - spc = fft_volt * numpy.conjugate(fft_volt) - spc = spc.real - - blocksize = 0 - blocksize += dc.size - blocksize += spc.size - - cspc = None - pairIndex = 0 - if self.pairList != None: - #calculo de cross-spectra - cspc = numpy.zeros((self.nPairs, self.nFFTPoints, self.nHeights), dtype='complex') - for pair in self.pairList: - cspc[pairIndex,:,:] = numpy.abs(fft_volt[pair[0],:,:] * numpy.conjugate(fft_volt[pair[1],:,:])) - pairIndex += 1 - blocksize += cspc.size - - self.dataOutObj.data_spc = spc - self.dataOutObj.data_cspc = cspc - self.dataOutObj.data_dc = dc - self.dataOutObj.m_ProcessingHeader.blockSize = blocksize - self.dataOutObj.m_BasicHeader.utc = self.dataInObj.m_BasicHeader.utc - -# self.getNoise() - - def addWriter(self,wrpath): - objWriter = SpectraWriter(self.dataOutObj) - objWriter.setup(wrpath) - self.writerObjList.append(objWriter) - - def addPlotter(self,index=None): - if index==None: - index = self.plotterObjIndex - - plotObj = Spectrum(self.dataOutObj, index) - self.plotterObjList.append(plotObj) - - def addIntegrator(self,N,timeInterval): - - objIncohInt = IncoherentIntegration(N,timeInterval) - self.integratorObjList.append(objIncohInt) - - def writeData(self, wrpath): - if self.dataOutObj.flagNoData: - return 0 - - if len(self.writerObjList) <= self.writerObjIndex: - self.addWriter(wrpath) - - self.writerObjList[self.writerObjIndex].putData() - - self.writerObjIndex += 1 - - def plotData(self, - xmin=None, - xmax=None, - ymin=None, - ymax=None, - zmin=None, - zmax=None, - titleList=None, - xlabelList=None, - ylabelList=None, - winTitle='', - colormap="br_green", - showColorbar=False, - showPowerProfile=False, - XAxisAsTime=False, - save=False, - index=None, - channelList=[]): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.plotterObjList) <= self.plotterObjIndex: - self.addPlotter(index) - - self.plotterObjList[self.plotterObjIndex].plotData(xmin, - xmax, - ymin, - ymax, - zmin, - zmax, - titleList, - xlabelList, - ylabelList, - winTitle, - colormap, - showColorbar, - showPowerProfile, - XAxisAsTime, - save, - channelList) - - self.plotterObjIndex += 1 - - def integrator(self, N=None, timeInterval=None): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.integratorObjList) <= self.integratorObjIndex: - self.addIntegrator(N,timeInterval) - - myIncohIntObj = self.integratorObjList[self.integratorObjIndex] - myIncohIntObj.exe(data=self.dataOutObj.data_spc,timeOfData=self.dataOutObj.m_BasicHeader.utc) - - if myIncohIntObj.isReady: - self.dataOutObj.data_spc = myIncohIntObj.data - self.dataOutObj.nAvg = myIncohIntObj.navg - self.dataOutObj.m_ProcessingHeader.incoherentInt = self.dataInObj.m_ProcessingHeader.incoherentInt*myIncohIntObj.navg - #print "myIncohIntObj.navg: ",myIncohIntObj.navg - self.dataOutObj.flagNoData = False - - """Calcular el ruido""" - self.getNoise() - else: - self.dataOutObj.flagNoData = True - - self.integratorObjIndex += 1 - - - - def removeDC(self, type): - - if self.dataOutObj.flagNoData: - return 0 - - def removeInterference(self): - - if self.dataOutObj.flagNoData: - return 0 - - def removeSatellites(self): - - if self.dataOutObj.flagNoData: - return 0 - - def getNoise(self, type="hildebrand", parm=None): - - if parm == None: - parm =self.dataOutObj.m_ProcessingHeader.incoherentInt - - self.noiseObj.setNoise(self.dataOutObj.data_spc) - - if type == "hildebrand": - noise = self.noiseObj.byHildebrand(parm) - - if type == "window": - noise = self.noiseObj.byWindow(parm) - - if type == "sort": - noise = self.noiseObj.bySort(parm) - - self.dataOutObj.noise = noise -# print 10*numpy.log10(noise) - - def selectChannels(self, channelList, pairList=[]): - - channelIndexList = [] - - for channel in channelList: - if channel in self.dataOutObj.channelList: - index = self.dataOutObj.channelList.index(channel) - channelIndexList.append(index) - - pairIndexList = [] - - for pair in pairList: - if pair in self.dataOutObj.pairList: - index = self.dataOutObj.pairList.index(pair) - pairIndexList.append(index) - - self.selectChannelsByIndex(channelIndexList, pairIndexList) - - def selectChannelsByIndex(self, channelIndexList, pairIndexList=[]): - """ - Selecciona un bloque de datos en base a canales y pares segun el - channelIndexList y el pairIndexList - - Input: - channelIndexList : lista de indices de los canales a seleccionar por ej. - - Si tenemos los canales - - self.channelList = (2,3,5,7) - - y deseamos escoger los canales (3,7) - entonces colocaremos el parametro - - channelndexList = (1,3) - - pairIndexList : tupla de indice depares que se desea selecionar por ej. - - Si tenemos los pares : - - ( (0,1), (0,2), (1,3), (2,5) ) - - y deseamos seleccionar los pares ((0,2), (2,5)) - entonces colocaremos el parametro - - pairIndexList = (1,3) - - Affected: - self.dataOutObj.data_spc - self.dataOutObj.data_cspc - self.dataOutObj.data_dc - self.dataOutObj.nChannels - self.dataOutObj.nPairs - self.dataOutObj.m_ProcessingHeader.spectraComb - self.dataOutObj.systemHeaderObj.numChannels - - self.dataOutObj.noise - Return: - None - """ - - if self.dataOutObj.flagNoData: - return 0 - - if pairIndexList == []: - pairIndexList = numpy.arange(len(self.dataOutObj.pairList)) - - nChannels = len(channelIndexList) - nPairs = len(pairIndexList) - - blocksize = 0 - #self spectra - spc = self.dataOutObj.data_spc[channelIndexList,:,:] - blocksize += spc.size - - cspc = None - if pairIndexList != []: - cspc = self.dataOutObj.data_cspc[pairIndexList,:,:] - blocksize += cspc.size - - #DC channel - dc = None - if self.dataOutObj.m_ProcessingHeader.flag_dc: - dc = self.dataOutObj.data_dc[channelIndexList,:] - blocksize += dc.size - - #Almacenar las combinaciones de canales y cros espectros - - spectraComb = numpy.zeros( (nChannels+nPairs)*2,numpy.dtype('u1')) - i = 0 - for spcChannel in channelIndexList: - spectraComb[i] = spcChannel - spectraComb[i+1] = spcChannel - i += 2 - - if pairList != None: - for pair in pairList: - spectraComb[i] = pair[0] - spectraComb[i+1] = pair[1] - i += 2 - - ####### - - self.dataOutObj.data_spc = spc - self.dataOutObj.data_cspc = cspc - self.dataOutObj.data_dc = dc - self.dataOutObj.nChannels = nChannels - self.dataOutObj.nPairs = nPairs - - self.dataOutObj.channelIndexList = channelIndexList - - self.dataOutObj.m_ProcessingHeader.spectraComb = spectraComb - self.dataOutObj.m_ProcessingHeader.totalSpectra = nChannels + nPairs - self.dataOutObj.systemHeaderObj.numChannels = nChannels - self.dataOutObj.nChannels = nChannels - self.dataOutObj.m_ProcessingHeader.blockSize = blocksize - - if cspc == None: - self.dataOutObj.m_ProcessingHeader.flag_dc = False - if dc == None: - self.dataOutObj.m_ProcessingHeader.flag_cpsc = False - - def selectHeightsByValue(self, minHei, maxHei): - """ - Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango - minHei <= height <= maxHei - - Input: - minHei : valor minimo de altura a considerar - maxHei : valor maximo de altura a considerar - - Affected: - Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex - - Return: - None - """ - - if self.dataOutObj.flagNoData: - return 0 - - if (minHei < self.dataOutObj.heightList[0]) or (minHei > maxHei): - raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei) - - if (maxHei > self.dataOutObj.heightList[-1]): - raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei) - - minIndex = 0 - maxIndex = 0 - data = self.dataOutObj.heightList - - for i,val in enumerate(data): - if val < minHei: - continue - else: - minIndex = i; - break - - for i,val in enumerate(data): - if val <= maxHei: - maxIndex = i; - else: - break - - self.selectHeightsByIndex(minIndex, maxIndex) - - def selectHeightsByIndex(self, minIndex, maxIndex): - """ - Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango - minIndex <= index <= maxIndex - - Input: - minIndex : valor minimo de altura a considerar - maxIndex : valor maximo de altura a considerar - - Affected: - self.dataOutObj.data_spc - self.dataOutObj.data_cspc - self.dataOutObj.data_dc - self.dataOutObj.heightList - self.dataOutObj.nHeights - self.dataOutObj.m_ProcessingHeader.numHeights - self.dataOutObj.m_ProcessingHeader.blockSize - self.dataOutObj.m_ProcessingHeader.firstHeight - self.dataOutObj.radarControllerHeaderObj.numHeights - - Return: - None - """ - - if self.dataOutObj.flagNoData: - return 0 - - if (minIndex < 0) or (minIndex > maxIndex): - raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex) - - if (maxIndex >= self.dataOutObj.nHeights): - raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex) - - nChannels = self.dataOutObj.nChannels - nPairs = self.dataOutObj.nPairs - nProfiles = self.dataOutObj.nProfiles - dataType = self.dataOutObj.dataType - nHeights = maxIndex - minIndex + 1 - blockSize = 0 - - #self spectra - spc = self.dataOutObj.data_spc[:,:,minIndex:maxIndex+1] - blockSize += spc.size - - #cross spectra - cspc = None - if self.dataOutObj.data_cspc != None: - cspc = self.dataOutObj.data_cspc[:,:,minIndex:maxIndex+1] - blockSize += cspc.size - - #DC channel - dc = self.dataOutObj.data_dc[:,minIndex:maxIndex+1] - blockSize += dc.size - - self.dataOutObj.data_spc = spc - if cspc != None: - self.dataOutObj.data_cspc = cspc - self.dataOutObj.data_dc = dc - - firstHeight = self.dataOutObj.heightList[minIndex] - - self.dataOutObj.nHeights = nHeights - self.dataOutObj.m_ProcessingHeader.blockSize = blockSize - self.dataOutObj.m_ProcessingHeader.numHeights = nHeights - self.dataOutObj.m_ProcessingHeader.firstHeight = firstHeight - self.dataOutObj.radarControllerHeaderObj.numHeights = nHeights - - self.dataOutObj.heightList = self.dataOutObj.heightList[minIndex:maxIndex+1] - - -class IncoherentIntegration: - - integ_counter = None - data = None - navg = None - buffer = None - nIncohInt = None - - def __init__(self, N = None, timeInterval = None): - """ - N - timeInterval - interval time [min], integer value - """ - - self.data = None - self.navg = None - self.buffer = None - self.timeOut = None - self.exitCondition = False - self.isReady = False - self.nIncohInt = N - self.integ_counter = 0 - if timeInterval!=None: - self.timeIntervalInSeconds = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line - - if ((timeInterval==None) and (N==None)): - print 'N = None ; timeInterval = None' - sys.exit(0) - elif timeInterval == None: - self.timeFlag = False - else: - self.timeFlag = True - - - def exe(self,data,timeOfData): - """ - data - - timeOfData [seconds] - """ - - if self.timeFlag: - if self.timeOut == None: - self.timeOut = timeOfData + self.timeIntervalInSeconds - - if timeOfData < self.timeOut: - if self.buffer == None: - self.buffer = data - else: - self.buffer = self.buffer + data - self.integ_counter += 1 - else: - self.exitCondition = True - - else: - if self.integ_counter < self.nIncohInt: - if self.buffer == None: - self.buffer = data - else: - self.buffer = self.buffer + data - - self.integ_counter += 1 - - if self.integ_counter == self.nIncohInt: - self.exitCondition = True - - if self.exitCondition: - self.data = self.buffer - self.navg = self.integ_counter - self.isReady = True - self.buffer = None - self.timeOut = None - self.integ_counter = 0 - self.exitCondition = False - - if self.timeFlag: - self.buffer = data - self.timeOut = timeOfData + self.timeIntervalInSeconds - else: - self.isReady = False - \ No newline at end of file diff --git a/schainpy/old/Processing/VoltageProcessor.py b/schainpy/old/Processing/VoltageProcessor.py deleted file mode 100644 index 3cc32b0..0000000 --- a/schainpy/old/Processing/VoltageProcessor.py +++ /dev/null @@ -1,679 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -import os, sys -import numpy - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Model.Voltage import Voltage -from IO.VoltageIO import VoltageWriter -from Graphics.VoltagePlot import Osciloscope -from Graphics.VoltagePlot import RTI - -class VoltageProcessor: - ''' - classdocs - ''' - - dataInObj = None - dataOutObj = None - - integratorObjIndex = None - decoderObjIndex = None - profSelectorObjIndex = None - writerObjIndex = None - plotterObjIndex = None - flipIndex = None - - integratorObjList = [] - decoderObjList = [] - profileSelectorObjList = [] - writerObjList = [] - plotterObjList = [] - m_Voltage= Voltage() - - def __init__(self): - ''' - Constructor - ''' - - self.integratorObjIndex = None - self.decoderObjIndex = None - self.profSelectorObjIndex = None - self.writerObjIndex = None - self.plotterObjIndex = None - self.flipIndex = 1 - self.integratorObjList = [] - self.decoderObjList = [] - self.profileSelectorObjList = [] - self.writerObjList = [] - self.plotterObjList = [] - - def setup(self, dataInObj=None, dataOutObj=None): - - self.dataInObj = dataInObj - - if dataOutObj == None: - dataOutObj = Voltage() - - dataOutObj.copy(dataInObj) - - self.dataOutObj = dataOutObj - - return self.dataOutObj - - - def init(self): - - self.integratorObjIndex = 0 - self.decoderObjIndex = 0 - self.profSelectorObjIndex = 0 - self.writerObjIndex = 0 - self.plotterObjIndex = 0 - self.dataOutObj.copy(self.dataInObj) - - if self.profSelectorObjIndex != None: - for profSelObj in self.profileSelectorObjList: - profSelObj.incIndex() - - def addWriter(self, wrpath): - objWriter = VoltageWriter(self.dataOutObj) - objWriter.setup(wrpath) - self.writerObjList.append(objWriter) - - def addRti(self,index=None): - if index==None: - index = self.plotterObjIndex - - plotObj = RTI(self.dataOutObj, index) - self.plotterObjList.append(plotObj) - - def addPlotter(self, index=None): - if index==None: - index = self.plotterObjIndex - - plotObj = Osciloscope(self.dataOutObj, index) - self.plotterObjList.append(plotObj) - - def addIntegrator(self, N,timeInterval): - - objCohInt = CoherentIntegrator(N,timeInterval) - self.integratorObjList.append(objCohInt) - - def addDecoder(self, code, ncode, nbaud): - - objDecoder = Decoder(code,ncode,nbaud) - self.decoderObjList.append(objDecoder) - - def addProfileSelector(self, nProfiles): - - objProfSelector = ProfileSelector(nProfiles) - self.profileSelectorObjList.append(objProfSelector) - - def writeData(self,wrpath): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.writerObjList) <= self.writerObjIndex: - self.addWriter(wrpath) - - self.writerObjList[self.writerObjIndex].putData() - - self.writerObjIndex += 1 - - def addScope(self,index=None): - if index==None: - index = self.plotterObjIndex - - plotObj = Osciloscope(self.dataOutObj, index) - self.plotterObjList.append(plotObj) - - def plotScope(self, - xmin=None, - xmax=None, - ymin=None, - ymax=None, - titleList=None, - xlabelList=None, - ylabelList=None, - winTitle='', - type="power", - index=None): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.plotterObjList) <= self.plotterObjIndex: - self.addScope(index) - - self.plotterObjList[self.plotterObjIndex].plotData(xmin, - xmax, - ymin, - ymax, - titleList, - xlabelList, - ylabelList, - winTitle, - type) - - self.plotterObjIndex += 1 - - def plotRti(self, - xmin=None, - xmax=None, - ymin=None, - ymax=None, - zmin=None, - zmax=None, - titleList=None, - xlabelList=None, - ylabelList=None, - winTitle='', - timezone='lt', - npoints=1000.0, - colormap="br_green", - showColorbar=True, - showPowerProfile=False, - XAxisAsTime=True, - save=False, - index=None): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.plotterObjList) <= self.plotterObjIndex: - self.addRti(index) - - self.plotterObjList[self.plotterObjIndex].plotData(xmin, - xmax, - ymin, - ymax, - zmin, - zmax, - titleList, - xlabelList, - ylabelList, - winTitle, - timezone, - npoints, - colormap, - showColorbar, - showPowerProfile, - XAxisAsTime, - save) - - self.plotterObjIndex += 1 - - - def plotData(self,xmin=None, xmax=None, ymin=None, ymax=None, type='iq', winTitle='', index=None): - if self.dataOutObj.flagNoData: - return 0 - - if len(self.plotterObjList) <= self.plotterObjIndex: - self.addPlotter(index) - - self.plotterObjList[self.plotterObjIndex].plotData(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax,type=type, winTitle=winTitle) - - self.plotterObjIndex += 1 - - def integrator(self, N=None, timeInterval=None): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.integratorObjList) <= self.integratorObjIndex: - self.addIntegrator(N,timeInterval) - - myCohIntObj = self.integratorObjList[self.integratorObjIndex] - myCohIntObj.exe(data=self.dataOutObj.data,timeOfData=self.dataOutObj.m_BasicHeader.utc) - - if myCohIntObj.isReady: - self.dataOutObj.data = myCohIntObj.data - self.dataOutObj.nAvg = myCohIntObj.navg - self.dataOutObj.m_ProcessingHeader.coherentInt *= myCohIntObj.navg - #print "myCohIntObj.navg: ",myCohIntObj.navg - self.dataOutObj.flagNoData = False - - else: - self.dataOutObj.flagNoData = True - - self.integratorObjIndex += 1 - - def decoder(self,code=None, mode = 0): - - if self.dataOutObj.flagNoData: - return 0 - - if code == None: - code = self.dataOutObj.radarControllerHeaderObj.code - ncode, nbaud = code.shape - - if len(self.decoderObjList) <= self.decoderObjIndex: - self.addDecoder(code,ncode,nbaud) - - myDecodObj = self.decoderObjList[self.decoderObjIndex] - data, ndata = myDecodObj.exe(data=self.dataOutObj.data,mode=mode) - - self.dataOutObj.data = data - self.dataOutObj.nHeights = ndata - self.dataOutObj.heightList = self.dataInObj.heightList[:ndata] - self.dataOutObj.flagNoData = False - - self.decoderObjIndex += 1 - - - def filterByHei(self, window): - if window == None: - window = self.dataOutObj.radarControllerHeaderObj.txA / self.dataOutObj.m_ProcessingHeader.deltaHeight[0] - - newdelta = self.dataOutObj.m_ProcessingHeader.deltaHeight[0] * window - dim1 = self.dataOutObj.data.shape[0] - dim2 = self.dataOutObj.data.shape[1] - r = dim2 % window - - buffer = self.dataOutObj.data[:,0:dim2-r] - buffer = buffer.reshape(dim1,dim2/window,window) - buffer = numpy.sum(buffer,2) - self.dataOutObj.data = buffer - - self.dataOutObj.m_ProcessingHeader.deltaHeight = newdelta - self.dataOutObj.m_ProcessingHeader.numHeights = buffer.shape[1] - - self.dataOutObj.nHeights = self.dataOutObj.m_ProcessingHeader.numHeights - - #self.dataOutObj.heightList es un numpy.array - self.dataOutObj.heightList = numpy.arange(self.dataOutObj.m_ProcessingHeader.firstHeight[0],newdelta*self.dataOutObj.nHeights,newdelta) - - def deFlip(self): - self.dataOutObj.data *= self.flipIndex - self.flipIndex *= -1. - - def selectChannels(self, channelList): - pass - - def selectChannelsByIndex(self, channelIndexList): - """ - Selecciona un bloque de datos en base a canales segun el channelIndexList - - Input: - channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7] - - Affected: - self.dataOutObj.data - self.dataOutObj.channelIndexList - self.dataOutObj.nChannels - self.dataOutObj.m_ProcessingHeader.totalSpectra - self.dataOutObj.systemHeaderObj.numChannels - self.dataOutObj.m_ProcessingHeader.blockSize - - Return: - None - """ - if self.dataOutObj.flagNoData: - return 0 - - for channel in channelIndexList: - if channel not in self.dataOutObj.channelIndexList: - raise ValueError, "The value %d in channelIndexList is not valid" %channel - - nChannels = len(channelIndexList) - - data = self.dataOutObj.data[channelIndexList,:] - - self.dataOutObj.data = data - self.dataOutObj.channelIndexList = channelIndexList - self.dataOutObj.nChannels = nChannels - - self.dataOutObj.m_ProcessingHeader.totalSpectra = 0 - self.dataOutObj.systemHeaderObj.numChannels = nChannels - self.dataOutObj.m_ProcessingHeader.blockSize = data.size - return 1 - - - def selectHeightsByValue(self, minHei, maxHei): - """ - Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango - minHei <= height <= maxHei - - Input: - minHei : valor minimo de altura a considerar - maxHei : valor maximo de altura a considerar - - Affected: - Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex - - Return: - 1 si el metodo se ejecuto con exito caso contrario devuelve 0 - """ - if self.dataOutObj.flagNoData: - return 0 - - if (minHei < self.dataOutObj.heightList[0]) or (minHei > maxHei): - raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei) - - if (maxHei > self.dataOutObj.heightList[-1]): - raise ValueError, "some value in (%d,%d) is not valid" % (minHei, maxHei) - - minIndex = 0 - maxIndex = 0 - data = self.dataOutObj.heightList - - for i,val in enumerate(data): - if val < minHei: - continue - else: - minIndex = i; - break - - for i,val in enumerate(data): - if val <= maxHei: - maxIndex = i; - else: - break - - self.selectHeightsByIndex(minIndex, maxIndex) - return 1 - - - def selectHeightsByIndex(self, minIndex, maxIndex): - """ - Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango - minIndex <= index <= maxIndex - - Input: - minIndex : valor de indice minimo de altura a considerar - maxIndex : valor de indice maximo de altura a considerar - - Affected: - self.dataOutObj.data - self.dataOutObj.heightList - self.dataOutObj.nHeights - self.dataOutObj.m_ProcessingHeader.blockSize - self.dataOutObj.m_ProcessingHeader.numHeights - self.dataOutObj.m_ProcessingHeader.firstHeight - self.dataOutObj.radarControllerHeaderObj - - Return: - 1 si el metodo se ejecuto con exito caso contrario devuelve 0 - """ - if self.dataOutObj.flagNoData: - return 0 - - if (minIndex < 0) or (minIndex > maxIndex): - raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex) - - if (maxIndex >= self.dataOutObj.nHeights): - raise ValueError, "some value in (%d,%d) is not valid" % (minIndex, maxIndex) - - nHeights = maxIndex - minIndex + 1 - - #voltage - data = self.dataOutObj.data[:,minIndex:maxIndex+1] - - firstHeight = self.dataOutObj.heightList[minIndex] - - self.dataOutObj.data = data - self.dataOutObj.heightList = self.dataOutObj.heightList[minIndex:maxIndex+1] - self.dataOutObj.nHeights = nHeights - self.dataOutObj.m_ProcessingHeader.blockSize = data.size - self.dataOutObj.m_ProcessingHeader.numHeights = nHeights - self.dataOutObj.m_ProcessingHeader.firstHeight = firstHeight - self.dataOutObj.radarControllerHeaderObj.numHeights = nHeights - return 1 - - def selectProfilesByValue(self,indexList, nProfiles): - if self.dataOutObj.flagNoData: - return 0 - - if self.profSelectorObjIndex >= len(self.profileSelectorObjList): - self.addProfileSelector(nProfiles) - - profileSelectorObj = self.profileSelectorObjList[self.profSelectorObjIndex] - - if not(profileSelectorObj.isProfileInList(indexList)): - self.dataOutObj.flagNoData = True - self.profSelectorObjIndex += 1 - return 0 - - self.dataOutObj.flagNoData = False - self.profSelectorObjIndex += 1 - - return 1 - - - def selectProfilesByIndex(self, minIndex, maxIndex, nProfiles): - """ - Selecciona un bloque de datos en base a un grupo indices de perfiles segun el rango - minIndex <= index <= maxIndex - - Input: - minIndex : valor de indice minimo de perfil a considerar - maxIndex : valor de indice maximo de perfil a considerar - nProfiles : numero de profiles - - Affected: - self.dataOutObj.flagNoData - self.profSelectorObjIndex - - Return: - 1 si el metodo se ejecuto con exito caso contrario devuelve 0 - """ - - if self.dataOutObj.flagNoData: - return 0 - - if self.profSelectorObjIndex >= len(self.profileSelectorObjList): - self.addProfileSelector(nProfiles) - - profileSelectorObj = self.profileSelectorObjList[self.profSelectorObjIndex] - - if not(profileSelectorObj.isProfileInRange(minIndex, maxIndex)): - self.dataOutObj.flagNoData = True - self.profSelectorObjIndex += 1 - return 0 - - self.dataOutObj.flagNoData = False - self.profSelectorObjIndex += 1 - - return 1 - - def selectNtxs(self, ntx): - pass - - -class Decoder: - - data = None - profCounter = 1 - nCode = None - nBaud = None - codeIndex = 0 - code = None - flag = False - - def __init__(self,code, ncode, nbaud): - - self.data = None - self.ndata = None - self.profCounter = 1 - self.nCode = ncode - self.nBaud = nbaud - self.codeIndex = 0 - self.code = code #this is a List - self.flag = False - - def exe(self, data, ndata=None, mode = 0): - - if ndata == None: ndata = data.shape[1] - - if mode == 0: - self.convolutionInFreq(data,ndata) - - if mode == 1: - self.convolutionInTime(data, ndata) - - self.ndata = ndata - self.nBaud + 1 - - return self.data, self.ndata - - def convolutionInFreq(self,data, ndata): - - newcode = numpy.zeros(ndata) - newcode[0:self.nBaud] = self.code[self.codeIndex] - - self.codeIndex += 1 - - fft_data = numpy.fft.fft(data, axis=1) - fft_code = numpy.conj(numpy.fft.fft(newcode)) - fft_code = fft_code.reshape(1,len(fft_code)) - - conv = fft_data.copy() - conv.fill(0) - - conv = fft_data*fft_code - - data = numpy.fft.ifft(conv,axis=1) - self.data = data[:,:-self.nBaud+1] - self.flag = True - - if self.profCounter == self.nCode: - self.profCounter = 0 - self.codeIndex = 0 - - self.profCounter += 1 - - def convolutionInTime(self, data, ndata): - - nchannel = data.shape[1] - newcode = self.code[self.codeIndex] - self.codeIndex += 1 - conv = data.copy() - for i in range(nchannel): - conv[i,:] = numpy.correlate(data[i,:], newcode) - - self.data = conv - self.flag = True - - if self.profCounter == self.nCode: - self.profCounter = 0 - self.codeIndex = 0 - - self.profCounter += 1 - - -class CoherentIntegrator: - - integ_counter = None - data = None - navg = None - buffer = None - nCohInt = None - - def __init__(self, N=None,timeInterval=None): - - self.data = None - self.navg = None - self.buffer = None - self.timeOut = None - self.exitCondition = False - self.isReady = False - self.nCohInt = N - self.integ_counter = 0 - if timeInterval!=None: - self.timeIntervalInSeconds = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line - - if ((timeInterval==None) and (N==None)): - raise ValueError, "N = None ; timeInterval = None" - - if timeInterval == None: - self.timeFlag = False - else: - self.timeFlag = True - - def exe(self, data, timeOfData): - - if self.timeFlag: - if self.timeOut == None: - self.timeOut = timeOfData + self.timeIntervalInSeconds - - if timeOfData < self.timeOut: - if self.buffer == None: - self.buffer = data - else: - self.buffer = self.buffer + data - self.integ_counter += 1 - else: - self.exitCondition = True - - else: - if self.integ_counter < self.nCohInt: - if self.buffer == None: - self.buffer = data - else: - self.buffer = self.buffer + data - - self.integ_counter += 1 - - if self.integ_counter == self.nCohInt: - self.exitCondition = True - - if self.exitCondition: - self.data = self.buffer - self.navg = self.integ_counter - self.isReady = True - self.buffer = None - self.timeOut = None - self.integ_counter = 0 - self.exitCondition = False - - if self.timeFlag: - self.buffer = data - self.timeOut = timeOfData + self.timeIntervalInSeconds - else: - self.isReady = False - - - -class ProfileSelector: - - profileIndex = None - # Tamanho total de los perfiles - nProfiles = None - - def __init__(self, nProfiles): - - self.profileIndex = 0 - self.nProfiles = nProfiles - - def incIndex(self): - self.profileIndex += 1 - - if self.profileIndex >= self.nProfiles: - self.profileIndex = 0 - - def isProfileInRange(self, minIndex, maxIndex): - - if self.profileIndex < minIndex: - return False - - if self.profileIndex > maxIndex: - return False - - return True - - def isProfileInList(self, profileList): - - if self.profileIndex not in profileList: - return False - - return True - - - \ No newline at end of file diff --git a/schainpy/old/Processing/__init__.py b/schainpy/old/Processing/__init__.py deleted file mode 100644 index 7d0d670..0000000 --- a/schainpy/old/Processing/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' \ No newline at end of file diff --git a/schainpy/old/Utilities/FtpServer.py b/schainpy/old/Utilities/FtpServer.py deleted file mode 100644 index 0b472a5..0000000 --- a/schainpy/old/Utilities/FtpServer.py +++ /dev/null @@ -1,19 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -class FtpServer: - ''' - classdocs - ''' - - - def __init__(self): - ''' - Constructor - ''' - pass - \ No newline at end of file diff --git a/schainpy/old/Utilities/FtpServerList.py b/schainpy/old/Utilities/FtpServerList.py deleted file mode 100644 index 2056e0e..0000000 --- a/schainpy/old/Utilities/FtpServerList.py +++ /dev/null @@ -1,20 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' - -class FtpServerList: - ''' - classdocs - ''' - - - def __init__(self): - ''' - Constructor - ''' - pass - m_FtpServer= FtpServer() - diff --git a/schainpy/old/Utilities/__init__.py b/schainpy/old/Utilities/__init__.py deleted file mode 100644 index 7d0d670..0000000 --- a/schainpy/old/Utilities/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -''' -Created on Feb 7, 2012 - -@author $Author$ -@version $Id$ -''' \ No newline at end of file diff --git a/schainpy/test/150km_january_3.py b/schainpy/test/150km_january_3.py index 2fb7ca6..fe56f3e 100644 --- a/schainpy/test/150km_january_3.py +++ b/schainpy/test/150km_january_3.py @@ -14,7 +14,7 @@ controllerObj = Project() controllerObj.setup(id = '191', name='test01', description=desc) -path = '/Volumes/DATA/RAW_EXP/2015_ISR' +path = './' figpath = '/Users/miguel/tmp' @@ -32,37 +32,13 @@ readUnitConfObj = controllerObj.addReadUnit(datatype='VoltageReader', opObj11 = readUnitConfObj.addOperation(name='printNumberOfBlock') procUnitConfObj0 = controllerObj.addProcUnit(datatype='VoltageProc', inputId=readUnitConfObj.getId()) - -# opObj10 = procUnitConfObj0.addOperation(name='selectHeightsByIndex') -# opObj10.addParameter(name='minIndex', value='0', format='int') -# opObj10.addParameter(name='maxIndex', value='131', format='int') opObj11 = procUnitConfObj0.addOperation(name='ProfileSelector', optype='other') -# profileIndex = '20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99' -# opObj11.addParameter(name='profileList', value=profileIndex, format='intlist') -# opObj11.addParameter(name='rangeList', value='((1, 80), (341, 420), (761, 840), (1181,1260))', format='multiList') opObj11.addParameter(name='rangeList', value='(1,80),(341,420),(681,760),(1021,1100)', format='multiList') -# opObj11 = procUnitConfObjISR.addOperation(name='ProfileConcat', optype='other') -# opObj11.addParameter(name='m', value='5', format='int') - -# opObj11 = procUnitConfObj0.addOperation(name='Reshaper', optype='other') #Esta Operacion opera sobre bloques y reemplaza el ProfileConcat que opera sobre perfiles -# opObj11.addParameter(name='shape', value='8,84,140', format='intlist') # shape = (nchannels, nprofiles, nhieghts) -# -# -# opObj11 = procUnitConfObj0.addOperation(name='ProfileSelector', optype='other') -# # profileIndex = '20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99' -# # opObj11.addParameter(name='profileList', value=profileIndex, format='intlist') -# opObj11.addParameter(name='profileRangeList', value='1,80', format='intlist') - - -# opObj11 = procUnitConfObj0.addOperation(name='filterByHeights') -# opObj11.addParameter(name='window', value='1', format='int') -# opObj11.addParameter(name='axis', value='2', format='int') cod7barker="1,1,1,-1,-1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1,-1,-1,-1,1,1,-1,1" -# 1,1,1,-1,-1,1,-1 -#-1,-1,-1,1,1,-1,1 + opObj11 = procUnitConfObj0.addOperation(name='Decoder', optype='other') opObj11.addParameter(name='code', value=cod7barker, format='floatlist') opObj11.addParameter(name='nCode', value='4', format='int') @@ -71,16 +47,6 @@ opObj11.addParameter(name='nBaud', value='7', format='int') opObj11 = procUnitConfObj0.addOperation(name='deFlip') opObj11.addParameter(name='channelList', value='1,3,5,7', format='intlist') -# cod7barker="1,1,1,-1,-1,1,-1" -# opObj11 = procUnitConfObj0.addOperation(name='Decoder', optype='other') -# opObj11.addParameter(name='code', value=cod7barker, format='intlist') -# opObj11.addParameter(name='nCode', value='1', format='int') -# opObj11.addParameter(name='nBaud', value='7', format='int') - -# opObj11 = procUnitConfObj0.addOperation(name='Scope', optype='other') -# opObj11.addParameter(name='id', value='10', format='int') -# opObj11.addParameter(name='wintitle', value='Voltage', format='str') - procUnitConfObj1 = controllerObj.addProcUnit(datatype='SpectraProc', inputId=procUnitConfObj0.getId()) procUnitConfObj1.addParameter(name='nFFTPoints', value='80', format='int') procUnitConfObj1.addParameter(name='nProfiles', value='80', format='int') diff --git a/schainpy/test/150km_jicamarca.xml b/schainpy/test/150km_jicamarca.xml new file mode 100644 index 0000000..cceca18 --- /dev/null +++ b/schainpy/test/150km_jicamarca.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/schainpy/test/testProcData.py b/schainpy/test/testProcData.py index a08052c..e87e238 100644 --- a/schainpy/test/testProcData.py +++ b/schainpy/test/testProcData.py @@ -14,19 +14,20 @@ if __name__ == '__main__': controllerObj.setup(id = '191', name='test01', description=desc) - readUnitConfObj = controllerObj.addReadUnit(datatype='Spectra', - path='/remote/datos/IMAGING/IMAGING2', - startDate='2012/12/18', - endDate='2012/12/22', + readUnitConfObj = controllerObj.addReadUnit(datatype='SpectraReader', + path='/remote/puma/JULIA_EW_IMAGING/JULIA_EW/D2015', + startDate='2015/01/18', + endDate='2015/01/22', startTime='00:00:00', endTime='23:59:59', online=0, walk=1, - expLabel='') + expLabel='ESF_EW') -# opObj00 = readUnitConfObj.addOperation(name='printInfo') + opObj00 = readUnitConfObj.addOperation(name='printInfo') + opObj00 = readUnitConfObj.addOperation(name='printNumberOfBlock') -# procUnitConfObj1 = controllerObj.addProcUnit(datatype='Spectra', inputId=readUnitConfObj.getId()) + procUnitConfObj1 = controllerObj.addProcUnit(datatype='SpectraProc', inputId=readUnitConfObj.getId()) # opObj10 = procUnitConfObj0.addOperation(name='selectChannels') # opObj10.addParameter(name='channelList', value='3,4,5', format='intlist') @@ -43,14 +44,14 @@ if __name__ == '__main__': # procUnitConfObj1.addParameter(name='pairList', value='(0,1),(0,2),(1,2)', format='') -# opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='other') -# opObj11.addParameter(name='idfigure', value='1', format='int') -# opObj11.addParameter(name='wintitle', value='SpectraPlot0', format='str') -## opObj11.addParameter(name='zmin', value='30', format='int') -## opObj11.addParameter(name='zmax', value='70', format='int') -# opObj11.addParameter(name='showprofile', value='1', format='int') -# opObj11.addParameter(name='save', value='1', format='int') -# opObj11.addParameter(name='figpath', value='/home/roj-idl71/tmp/graphs') + opObj11 = procUnitConfObj1.addOperation(name='SpectraPlot', optype='other') + opObj11.addParameter(name='id', value='1', format='int') + opObj11.addParameter(name='wintitle', value='SpectraPlot0', format='str') +# opObj11.addParameter(name='zmin', value='30', format='int') +# opObj11.addParameter(name='zmax', value='70', format='int') + opObj11.addParameter(name='showprofile', value='1', format='int') +# opObj11.addParameter(name='save', value='1', format='int') +# opObj11.addParameter(name='figpath', value='/home/roj-idl71/tmp/graphs') ## # opObj11 = procUnitConfObj1.addOperation(name='CrossSpectraPlot', optype='other') # opObj11.addParameter(name='idfigure', value='2', format='int') @@ -60,12 +61,12 @@ if __name__ == '__main__': # opObj11.addParameter(name='save', value='1', format='int') # opObj11.addParameter(name='figpath', value='/home/roj-idl71/tmp/graphs') -# -# opObj11 = procUnitConfObj1.addOperation(name='CoherenceMap', optype='other') -# opObj11.addParameter(name='idfigure', value='3', format='int') -# opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str') -# opObj11.addParameter(name='zmin', value='40', format='int') -# opObj11.addParameter(name='zmax', value='90', format='int') + +# opObj11 = procUnitConfObj1.addOperation(name='CoherenceMap', optype='other') +# opObj11.addParameter(name='idfigure', value='3', format='int') +# opObj11.addParameter(name='wintitle', value='CrossSpectraPlot', format='str') +# opObj11.addParameter(name='zmin', value='40', format='int') +# opObj11.addParameter(name='zmax', value='90', format='int') # procUnitConfObj2 = controllerObj.addProcUnit(datatype='Voltage', inputId=procUnitConfObj0.getId()) # @@ -83,15 +84,15 @@ if __name__ == '__main__': # opObj11.addParameter(name='zmax', value='90', format='int') # opObj11.addParameter(name='showprofile', value='1', format='int') -# opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='other') -# opObj11.addParameter(name='idfigure', value='10', format='int') -# opObj11.addParameter(name='wintitle', value='RTI', format='str') -## opObj11.addParameter(name='xmin', value='21', format='float') -## opObj11.addParameter(name='xmax', value='22', format='float') -# opObj11.addParameter(name='zmin', value='40', format='int') -# opObj11.addParameter(name='zmax', value='90', format='int') -# opObj11.addParameter(name='showprofile', value='1', format='int') -# opObj11.addParameter(name='timerange', value=str(60), format='int') + opObj11 = procUnitConfObj1.addOperation(name='RTIPlot', optype='other') + opObj11.addParameter(name='id', value='10', format='int') + opObj11.addParameter(name='wintitle', value='RTI', format='str') +# opObj11.addParameter(name='xmin', value='0', format='float') +# opObj11.addParameter(name='xmax', value='10', format='float') +# opObj11.addParameter(name='zmin', value='40', format='int') +# opObj11.addParameter(name='zmax', value='90', format='int') + opObj11.addParameter(name='showprofile', value='1', format='int') + opObj11.addParameter(name='timerange', value=str(2*60*60), format='int') # opObj10 = procUnitConfObj1.addOperation(name='selectChannels') # opObj10.addParameter(name='channelList', value='0,2,4,6', format='intlist')