diff --git a/schainpy2/Controller/controller.py b/schainpy2/Controller/controller.py deleted file mode 100644 index a5e9e06..0000000 --- a/schainpy2/Controller/controller.py +++ /dev/null @@ -1,370 +0,0 @@ -''' -Created on September , 2012 -@author: -''' -from xml.etree.ElementTree import Element, SubElement, ElementTree -from element import prettify -from xml.etree import ElementTree as ET -import sys - - -#def save(a, b): -# -# nameP = "Alexnder" -# descripcion = self.projectWindow.Text() -# id = 1 -# x = self.data.projectWindow.cmbbox.value() -# -# projectObj = Project(id, name, description) -# -# projectObj.setup(id, name, description) - -class Project(): - - id = None - name = None - description = None - readBranchObjList = None - procBranchObjList = None - - def __init__(self): - -# self.id = id -# self.name = name -# self.description = description - - self.readBranchObjList = [] - self.procBranchObjList = [] - - def setParms(self, id, name, description): - - self.id = id - self.name = name - self.description = description - - def addReadBranch(self, dpath, dataformat, readMode, startDate='', endDate='', startTime='', endTime=''): - - id = len(self.readBranchObjList) + 1 - - readBranchObj = ReadBranch(id, dpath, dataformat, readMode, startDate, endDate, startTime, endTime) - - self.readBranchObjList.append(readBranchObj) - - return readBranchObj - - def addProcBranch(self, name): - - id = len(self.procBranchObjList) + 1 - - procBranchObj = ProcBranch(id, name) - - self.procBranchObjList.append(procBranchObj) - - return procBranchObj - - def makeXml(self): - - projectElement = Element('Project') - projectElement.set('id', str(self.id)) - projectElement.set('name', self.name) - #projectElement.set('description', self.description) - - se = SubElement(projectElement, 'description',description=self.description)#ESTO ES LO ULTIMO QUE SE TRABAJO - #se.text = self.description #ULTIMA MODIFICACION PARA SACAR UN SUB ELEMENT - - for readBranchObj in self.readBranchObjList: - readBranchObj.makeXml(projectElement) - - for procBranchObj in self.procBranchObjList: - procBranchObj.makeXml(projectElement) - - self.projectElement = projectElement - - def writeXml(self, filename): - - self.makeXml() - ElementTree(self.projectElement).write(filename, method='xml') - print prettify(self.projectElement) - - def readXml(self,workspace): - print "Aqui estoy leyendo" - tree=ET.parse(workspace) - root=tree.getroot() - self.project=root.tag - self.idProyect= root.attrib.get('id') - self.nameProyect= root.attrib.get('name') - for description in root.findall('description'): - description = description.get('description') - - self.description= description - - for readBranch in root.findall('readBranch'): - id = readBranch.get('id') - self.idrb=id - - for procBranch in root.findall('procBranch'): - id = readBranch.get('id') - name = readBranch.get('name') - self.idpb=id - self.nameBranch=name -# -# - print self.project - print self.idProyect - print self.nameProyect - print self.description - print self.idrb - print self.idpb - print self.nameBranch -# -####ESTO DEL MEDIO ESTABA COMENTADO -# print root.tag , root.attrib -# -# print root.attrib.get('id') -# print root.attrib.get('name') - - -# for description in root.findall('description'): -# description = root.find('description').text -# name = root.get('name') -# print name, description - -# description=root.find('description').text -# print description -# ESTO FUNCIONABA HACIA ABAJO - print "Otra forma " - root=tree.getroot() - print root.tag , root.attrib - for child in root: - print child.tag ,child.attrib - for child in child: - print child.tag ,child.attrib - for child in child: - print child.tag ,child.attrib - for child in child: - print child.tag ,child.attrib -# -class ReadBranch(): - - id = None - dpath = None - dataformat = None - readMode = None - startDate = None - endDate = None - startTime = None - endTime = None - - def __init__(self, id, dpath, dataformat, readMode, startDate, endDate, startTime, endTime): - - self.id = id - self.dpath = dpath - self.dataformat = dataformat - self.readMode = readMode - self.startDate = startDate - self.endDate = endDate - self.startTime = startTime - self.endTime = endTime - - def makeXml(self, projectElement): - - readBranchElement = SubElement(projectElement, 'readBranch') - readBranchElement.set('id', str(self.id)) - -# readBranchElement.set('dpath', self.dpath) -# readBranchElement.set('dataformat', self.dataformat) -# readBranchElement.set('startDate', self.startDate) -# readBranchElement.set('endDate', self.endDate) -# readBranchElement.set('startTime', self.startTime) -# readBranchElement.set('endTime', self.endTime) -# readBranchElement.set('readMode', str(self.readMode)) - -# se = SubElement(readBranchElement, 'dpath')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.dpath -# -# se = SubElement(readBranchElement, 'dataformat')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.dataformat -# -# se = SubElement(readBranchElement, 'startDate')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.startDate -# -# se = SubElement(readBranchElement, 'endDate')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.endDate -# -# se = SubElement(readBranchElement, 'startTime')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.startTime -# -# se = SubElement(readBranchElement, 'endTime')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.endTime -# -# se = SubElement(readBranchElement, 'readMode')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = str(self.readMode) - - ########################################################################## - se = SubElement(readBranchElement, 'parameter', name='dpath' , value=self.dpath) - se = SubElement(readBranchElement, 'parameter', name='dataformat', value=self.dataformat) - se = SubElement(readBranchElement, 'parameter', name='startDate' , value=self.startDate) - se = SubElement(readBranchElement, 'parameter', name='endDate' , value=self.endDate) - se = SubElement(readBranchElement, 'parameter', name='startTime' , value=self.startTime) - se = SubElement(readBranchElement, 'parameter', name='endTime' , value=self.endTime) - se = SubElement(readBranchElement, 'parameter', name='readMode' , value=str(self.readMode)) - - -class ProcBranch(): - - id = None - name = None - - upObjList = None - - def __init__(self, id, name): - - self.id = id - self.name = name - - self.upObjList = [] - - def addUP(self, name, type): - - id = len(self.upObjList) + 1 - - upObj = UP(id, name, type) - - self.upObjList.append(upObj) - - return upObj - - def makeXml(self, projectElement): - - procBranchElement = SubElement(projectElement, 'procBranch') - procBranchElement.set('id', str(self.id)) - procBranchElement.set('name', self.name) - - for upObj in self.upObjList: - upObj.makeXml(procBranchElement) - -class UP(): - - id = None - name = None - type = None - - opObjList = [] - - def __init__(self, id, name, type): - - self.id = id - self.name = name - self.type = type - - self.opObjList = [] - - def addOperation(self, name, priority): - - id = len(self.opObjList) + 1 - - opObj = Operation(id, name, priority) - - self.opObjList.append(opObj) - - return opObj - - def makeXml(self, procBranchElement): - - upElement = SubElement(procBranchElement, 'UP') - upElement.set('id', str(self.id)) - upElement.set('name', self.name) - upElement.set('type', self.type) - - for opObj in self.opObjList: - opObj.makeXml(upElement) - -class Operation(): - - id = 0 - name = None - priority = None - parmObjList = [] - - def __init__(self, id, name, priority): - - self.id = id - self.name = name - self.priority = priority - - self.parmObjList = [] - - def addParameter(self, name, value): - - id = len(self.parmObjList) + 1 - - parmObj = Parameter(id, name, value) - - self.parmObjList.append(parmObj) - - return parmObj - - def makeXml(self, upElement): - - opElement = SubElement(upElement, 'Operation') - opElement.set('id', str(self.id)) - opElement.set('name', self.name) - opElement.set('priority', str(self.priority)) - - for parmObj in self.parmObjList: - parmObj.makeXml(opElement) - -class Parameter(): - - id = None - name = None - value = None - - def __init__(self, id, name, value): - - self.id = id - self.name = name - self.value = value - - def makeXml(self, opElement): - - parmElement = SubElement(opElement, 'Parameter') - parmElement.set('name', self.name) - parmElement.set('value', self.value) - -# se = SubElement(parmElement, 'value')#ESTO ES LO ULTIMO QUE SE TRABAJO -# se.text = self.value - -if __name__ == '__main__': - - desc = "Este es un test" - filename = "test.xml" - - workspace=str("C:\\Users\\alex\\workspace\\GUIV2.0\\test.xml") - - projectObj = Project() - - projectObj.setParms(id = '11', name='test01', description=desc) - - readBranchObj = projectObj.addReadBranch(dpath='mydata', dataformat='rawdata', readMode=0, startDate='1', endDate='3', startTime='4', endTime='5') - - procBranchObj = projectObj.addProcBranch(name='Branch1') - - procBranchObj1 = projectObj.addProcBranch(name='Branch2') - upObj1 = procBranchObj.addUP(name='UP1', type='Voltage') - upObj2 = procBranchObj.addUP(name='UP2', type='Voltage') - - opObj11 = upObj1.addOperation(name='removeDC', priority=1) - opObj11.addParameter(name='type', value='1') - - - opObj12 = upObj1.addOperation(name='decodification', priority=2) - opObj12.addParameter(name='ncode', value='2') - opObj12.addParameter(name='nbauds', value='8') - opObj12.addParameter(name='code1', value='001110011') - opObj12.addParameter(name='code2', value='001110011') - - projectObj.writeXml(filename) - - projectObj.readXml(workspace) - \ No newline at end of file diff --git a/schainpy2/Controller/controller1.py b/schainpy2/Controller/controller1.py deleted file mode 100644 index 54a7176..0000000 --- a/schainpy2/Controller/controller1.py +++ /dev/null @@ -1,358 +0,0 @@ -''' -Created on September , 2012 -@author: -''' -from xml.etree.ElementTree import Element, SubElement, ElementTree -from element import prettify -from xml.etree import ElementTree as ET -import sys - -class Project(): - - id = None - name = None - description = None - readBranchObjList = None - procBranchObjList = None - - def __init__(self): - -# self.id = id -# self.name = name -# self.description = description - - self.readBranchObjList = [] - self.procBranchObjList = [] - - def setParms(self, id, name, description): - - self.id = id - self.name = name - self.description = description - - def addReadBranch(self,id, dpath, dataformat, opMode,readMode, startDate='', endDate='', startTime='', endTime=''): - - #id = len(self.readBranchObjList) + 1 - - readBranchObj = ReadBranch(id, dpath, dataformat, opMode , readMode, startDate, endDate, startTime, endTime) - - self.readBranchObjList.append(readBranchObj) - - return readBranchObj - - def addProcBranch(self, id,name): - - # id = len(self.procBranchObjList) + 1 - - procBranchObj = ProcBranch(id, name) - - self.procBranchObjList.append(procBranchObj) - - return procBranchObj - - def makeXml(self): - - projectElement = Element('Project') - projectElement.set('id', str(self.id)) - projectElement.set('name', self.name) - #projectElement.set('description', self.description) - - se = SubElement(projectElement, 'description',description=self.description)#ESTO ES LO ULTIMO QUE SE TRABAJO - #se.text = self.description #ULTIMA MODIFICACION PARA SACAR UN SUB ELEMENT - - for readBranchObj in self.readBranchObjList: - readBranchObj.makeXml(projectElement) - - for branchObj in self.procBranchObjList: - branchObj.makeXml(projectElement) - - self.projectElement = projectElement - - def writeXml(self, filename): - - self.makeXml() - ElementTree(self.projectElement).write(filename, method='xml') - #print prettify(self.projectElement) - -class ReadBranch(): - - id = None - dpath = None - dataformat = None - opMode =None - readMode = None - startDate = None - endDate = None - startTime = None - endTime = None - - def __init__(self, id, dpath, dataformat,opMode, readMode, startDate, endDate, startTime, endTime): - - self.id = id - self.dpath = dpath - self.dataformat = dataformat - self.opMode = opMode - self.readMode = readMode - self.startDate = startDate - self.endDate = endDate - self.startTime = startTime - self.endTime = endTime - - def makeXml(self, projectElement): - - readBranchElement = SubElement(projectElement, 'readBranch') - readBranchElement.set('id', str(self.id)) - - ########################################################################## - se = SubElement(readBranchElement, 'parameter', name='dpath' , value=self.dpath) - se = SubElement(readBranchElement, 'parameter', name='dataformat', value=self.dataformat) - se = SubElement(readBranchElement, 'parameter', name='opMode' , value=self.opMode) - se = SubElement(readBranchElement, 'parameter', name='startDate' , value=self.startDate) - se = SubElement(readBranchElement, 'parameter', name='endDate' , value=self.endDate) - se = SubElement(readBranchElement, 'parameter', name='startTime' , value=self.startTime) - se = SubElement(readBranchElement, 'parameter', name='endTime' , value=self.endTime) - se = SubElement(readBranchElement, 'parameter', name='readMode' , value=str(self.readMode)) - -class ProcBranch(): - - id = None - name = None - - upObjList = None - upsubObjList=None - - def __init__(self, id, name): - - self.id = id - self.name = name - - self.upObjList = [] - self.upsubObjList = [] - - def addUP(self,id, name, type): - - #id = len(self.upObjList) + 1 - - upObj = UP(id, name, type) - - self.upObjList.append(upObj) - - return upObj - - def addUPSUB(self,id, name, type): - - # id = len(self.upsubObjList) + 1 - - upsubObj = UPSUB(id, name, type) - - self.upsubObjList.append(upsubObj) - - return upsubObj - - def makeXml(self, projectElement): - - procBranchElement = SubElement(projectElement, 'procBranch') - procBranchElement.set('id', str(self.id)) - procBranchElement.set('name', self.name) - - for upObj in self.upObjList: - upObj.makeXml(procBranchElement) - - for upsubObj in self.upsubObjList: - upsubObj.makeXml(procBranchElement) - -class UP(): - - id = None - name = None - type = None - upsubObjList=None - opObjList = None - - def __init__(self, id, name, type): - - self.id = id - self.name = name - self.type = type - self.upsubObjList=[] - self.up2subObjList=[] - self.opObjList = [] - - def addOperation(self,id, name, priority): - - #id = len(self.opObjList) + 1 - - opObj = Operation(id, name, priority) - - self.opObjList.append(opObj) - - return opObj - - def addUPSUB(self,id, name, type): - -# id = len(self.upsubObjList) + 1 - - upsubObj = UPSUB(id, name, type) - - self.upsubObjList.append(upsubObj) - - return upsubObj - - def addUP2SUB(self,id, name, type): - -# id = len(self.upsubObjList) + 1 - - up2subObj = UP2SUB(id, name, type) - - self.up2subObjList.append(up2subObj) - - return up2subObj - - def makeXml(self, procBranchElement): - - upElement = SubElement(procBranchElement, 'UP') - upElement.set('id', str(self.id)) - upElement.set('name', self.name) - upElement.set('type', self.type) - - for opObj in self.opObjList: - opObj.makeXml(upElement) - - for upsubObj in self.upsubObjList: - upsubObj.makeXml(upElement) - -class UPSUB(): - - id = None - name = None - type = None - opObjList = None - up2subObjList=None - - - def __init__(self, id, name, type): - - self.id = id - self.name = name - self.type = type - self.up2subObjList = [] - self.opObjList = [] - - def addOperation(self, name, priority): - - id = len(self.opObjList) + 1 - - opObj = Operation(id, name, priority) - - self.opObjList.append(opObj) - - return opObj - - - def addUP2SUB(self,id, name, type): -# -# id = len(self.opObjList) + 1 - up2subObj = UP2SUB(id, name, type) - - self.up2subObjList.append(up2subObj) - - return up2subObj - - def makeXml(self, upElement): - - upsubElement = SubElement(upElement, 'UPSUB') - upsubElement.set('id', str(self.id)) - upsubElement.set('name', self.name) - upsubElement.set('type', self.type) - - for opObj in self.opObjList: - opObj.makeXml(upsubElement) - - for up2subObj in self.up2subObjList: - up2subObj.makeXml(upsubElement) - -class UP2SUB(): - - id = None - name = None - type = None - opObjList = None - - def __init__(self, id, name, type): - - self.id = id - self.name = name - self.type = type - self.opObjList = [] - - def addOperation(self, name, priority): - - id = len(self.opObjList) + 1 - - opObj = Operation(id, name, priority) - - self.opObjList.append(opObj) - - return opObj - - def makeXml(self,upsubElement): - up2subElement = SubElement(upsubElement, 'UPD2SUB') - up2subElement.set('id', str(self.id)) - up2subElement.set('name', self.name) - up2subElement.set('type', self.type) - - for opObj in self.opObjList: - opObj.makeXml(up2subElement) - -class Operation(): - - id = 0 - name = None - priority = None - parmObjList = [] - - def __init__(self, id, name, priority): - - self.id = id - self.name = name - self.priority = priority - - self.parmObjList = [] - - def addParameter(self, name, value): - - id = len(self.parmObjList) + 1 - - parmObj = Parameter(id, name, value) - - self.parmObjList.append(parmObj) - - return parmObj - - def makeXml(self, upElement): - - opElement = SubElement(upElement, 'Operation') - opElement.set('id', str(self.id)) - opElement.set('name', self.name) - opElement.set('priority', str(self.priority)) - - for parmObj in self.parmObjList: - parmObj.makeXml(opElement) - -class Parameter(): - - id = None - name = None - value = None - - def __init__(self, id, name, value): - - self.id = id - self.name = name - self.value = value - - def makeXml(self, opElement): - - parmElement = SubElement(opElement, 'Parameter') - parmElement.set('name', self.name) - parmElement.set('value', self.value) \ No newline at end of file diff --git a/schainpy2/Data/JROData.py b/schainpy2/Data/JROData.py deleted file mode 100644 index c232a9d..0000000 --- a/schainpy2/Data/JROData.py +++ /dev/null @@ -1,248 +0,0 @@ -''' - -$Author$ -$Id$ -''' - -import os, sys -import copy -import numpy - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from IO.JROHeaderIO import SystemHeader, RadarControllerHeader - -class JROData: - -# m_BasicHeader = BasicHeader() -# m_ProcessingHeader = ProcessingHeader() - - systemHeaderObj = SystemHeader() - - radarControllerHeaderObj = RadarControllerHeader() - -# data = None - - type = None - - dtype = None - - nChannels = None - - nHeights = None - - nProfiles = None - - heightList = None - - channelList = None - - channelIndexList = None - - flagNoData = True - - flagTimeBlock = False - - utctime = None - - blocksize = None - - nCode = None - - nBaud = None - - code = None - - flagDecodeData = True #asumo q la data esta decodificada - - flagDeflipData = True #asumo q la data esta sin flip - - flagShiftFFT = False - - ippSeconds = None - - timeInterval = None - - set=None - - deltaHeight = None - - def __init__(self): - - raise ValueError, "This class has not been implemented" - - def copy(self, inputObj=None): - - if inputObj == None: - return copy.deepcopy(self) - - for key in inputObj.__dict__.keys(): - self.__dict__[key] = inputObj.__dict__[key] - - def deepcopy(self): - - return copy.deepcopy(self) - -class Voltage(JROData): - - nCohInt = None - - #data es un numpy array de 2 dmensiones (canales, alturas) - data = None - - def __init__(self): - ''' - Constructor - ''' - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.systemHeaderObj = SystemHeader() - - self.type = "Voltage" - - self.data = None - - self.dtype = None - - self.nChannels = 0 - - self.nHeights = 0 - - self.nProfiles = None - - self.heightList = None - - self.channelList = None - - self.channelIndexList = None - - self.flagNoData = True - - self.flagTimeBlock = False - - self.utctime = None - - self.nCohInt = None - - self.blocksize = None - -class Spectra(JROData): - - #data es un numpy array de 2 dmensiones (canales, perfiles, alturas) - data_spc = None - - #data es un numpy array de 2 dmensiones (canales, pares, alturas) - data_cspc = None - - #data es un numpy array de 2 dmensiones (canales, alturas) - data_dc = None - - nFFTPoints = None - - nPairs = None - - pairsList = None - - nIncohInt = None - - wavelength = None #Necesario para cacular el rango de velocidad desde la frecuencia - - nCohInt = None #se requiere para determinar el valor de timeInterval - - def __init__(self): - ''' - Constructor - ''' - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.systemHeaderObj = SystemHeader() - - self.type = "Spectra" - -# self.data = None - - self.dtype = None - - self.nChannels = 0 - - self.nHeights = 0 - - self.nProfiles = None - - self.heightList = None - - self.channelList = None - - self.channelIndexList = None - - self.flagNoData = True - - self.flagTimeBlock = False - - self.utctime = None - - self.nIncohInt = None - - self.blocksize = None - - self.nFFTPoints = None - - self.wavelength = None - - def getFrequencies(self): - - xrange = numpy.arange(self.nFFTPoints) - xrange = xrange - return None - - -class SpectraHeis(JROData): - - data_spc = None - - data_cspc = None - - data_dc = None - - nFFTPoints = None - - nPairs = None - - pairsList = None - - nIncohInt = None - - def __init__(self): - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.systemHeaderObj = SystemHeader() - - self.type = "SpectraHeis" - - self.dtype = None - - self.nChannels = 0 - - self.nHeights = 0 - - self.nProfiles = None - - self.heightList = None - - self.channelList = None - - self.channelIndexList = None - - self.flagNoData = True - - self.flagTimeBlock = False - - self.nPairs = 0 - - self.utctime = None - - self.blocksize = None diff --git a/schainpy2/Data/__init__.py b/schainpy2/Data/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/schainpy2/Data/__init__.py +++ /dev/null diff --git a/schainpy2/Graphics/BaseGraph_mpl.py b/schainpy2/Graphics/BaseGraph_mpl.py deleted file mode 100644 index 294502a..0000000 --- a/schainpy2/Graphics/BaseGraph_mpl.py +++ /dev/null @@ -1,883 +0,0 @@ -''' -Created on Feb 7, 2012 - -@autor $Author$ -@version $Id$ - -''' - -import numpy - -import time -import datetime - - -import matplotlib as mpl -mpl.use('TKAgg') -import matplotlib.pyplot as plt - -import scitools.numpyutils as sn - -def cmap1_init(colormap='gray'): - pass - -def setColormap(colormap='jet'): - pass - -def savePlplot(filename,width,height): - 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(): - plt.clf() - -def closePage(): - 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) - -def setFigure(indexFig): - plt.figure(indexFig) - -def refresh(): - plt.draw() - -def show(): - plt.ioff() - plt.show() - plt.ion() - -def setPlTitle(pltitle,color, szchar=0.7): - pass - -def setSubpages(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): - pass - - def setColor(self, color): - pass - - def setXAxisAsTime(self, value=False): - self.xaxisIsTime = value - - def basicLineTimePlot(self, x, y, colline=1): - ax = self.__axesId - if self.setXYData() == None: - ax.plot(x,y) - plt.tight_layout() - else: - ax.lines[0].set_data(x,y) - - def basicXYPlot(self, 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): - pass - - def __getBoxpltr(self, x, y, deltax=None, deltay=None): - 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): - ax = self.__axesId - ax.pcolormesh(x,y,data.T,vmin=zmin,vmax=zmax) - - def colorbarPlot(self, xmin=0., xmax=1., ymin=0., ymax=1.): - 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): - 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) - - def delLabels(self): - pass - - def plotImage(self,x,y,z,xrange,yrange,zrange): - pass - - -class LinearPlot(): - linearObjDic = {} - __xpos = None - __ypos = None - isPlotIni = None - - def __init__(self, indexFig,nsubplot,winTitle): - self.width = 700 - self.height = 800 - self.indexFig = indexFig - self.ncol = 1 - self.nrow = nsubplot - initMatplotlib(indexFig,self.ncol,self.nrow,winTitle,self.width,self.height) - - self.isPlotIni = False - - - def setFigure(self,indexFig): - setFigure(indexFig) - - def setNewPage(self, pltitle='No title'): - szchar = 0.7 -# setNewPage() - setPlTitle(pltitle,'black', szchar=szchar) - setSubpages(self.ncol, self.nrow) - - def setPosition(self): - xi = 0.07; xf = 0.9 - yi = 0.15; yf = 0.8 - - xpos = [xi,xf] - ypos = [yi,yf] - - self.__xpos = xpos - self.__ypos = ypos - - return xpos,ypos - - def createObjects(self,subplot,xmin,xmax,ymin,ymax,title,xlabel,ylabel): - szchar = 0.7 - 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) - self.linearObjDic[key] = linearObj - - def iniPlot(self,subplot): - name = 'linear' - key = name + '%d'%subplot - - linearObj = self.linearObjDic[key] - 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') - - - def plot(self,subplot,x,y,type='abs'): - name = 'linear' - key = name + '%d'%subplot - - linearObj = self.linearObjDic[key] - - if type.lower() == 'simple': - colline = 9 - linearObj.basicLineTimePlot(x, y) - linearObj.setXYData(x,y,'real') - - def refresh(self): - refresh() - - def show(self): - show() - -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): - - setPlTitle(pltitle,'black') - - 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) - 10 - ymax = numpy.max(y1) + 10 - - subplotTitle = "subplot no. " - xlabel = "" - ylabel = "" - - indexFig = 1 - nsubplot = 6 - winTitle = "figura" - - isPlotIni = False - isPlotConfig = False - ntimes = 100 - - - # Instancia del objeto - linearObj = LinearPlot(indexFig,nsubplot,winTitle) - - - for i in range(ntimes): - # Crea los subplots - if not(linearObj.isPlotIni): - for index in range(nsubplot): - indexplot = index + 1 - title = subplotTitle + '%d'%indexplot - linearObj.createObjects(indexplot,xmin,xmax,ymin,ymax,title,xlabel,ylabel) - linearObj.isPlotIni = True - - # Inicializa el grafico en cada iteracion - linearObj.setFigure(indexFig) - linearObj.setNewPage("") - - for index in range(nsubplot): - subplot = index - linearObj.iniPlot(subplot+1) - - #plotea los datos - for channel in range(nsubplot): - data = y1 + numpy.random.rand(len(y1)) - linearObj.plot(channel+1, x, data, type='simple') - - linearObj.refresh() - -# linearObj.closePage() #descomentar esta linea para mas iteraciones - - time.sleep(0.05) - - linearObj.show() - - print "example 1 completed" - - - - """ - 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 "example 2 completed" \ No newline at end of file diff --git a/schainpy2/Graphics/__init__.py b/schainpy2/Graphics/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/schainpy2/Graphics/__init__.py +++ /dev/null diff --git a/schainpy2/Graphics/schainPlot.py b/schainpy2/Graphics/schainPlot.py deleted file mode 100644 index 62e1680..0000000 --- a/schainpy2/Graphics/schainPlot.py +++ /dev/null @@ -1,412 +0,0 @@ -import numpy -import datetime -import time -import os -from schainPlotLib import Driver - -class Figure: - - __isDriverOpen = False - __isFigureOpen = False - __isConfig = False - __counter = 0 - drvObj = None - driver = None - idfigure = None - nframes = None - wintitle = None - colormap = None - overplot = None - colorbar = None - - frameObjList = [] - - xw = None - yw = None - - xmin = None - xmax = None - ymin = None - ymax = None - - minvalue = None - maxvalue = None - deltax = None - deltay = None - - - figuretitle = "" - xrangestep = None - - def __init__(self,idfigure, nframes, wintitle, xw=600, yw=800, overplot=0, driver='plplot', colormap=None, colorbar= True, *args): - - self.__isDriverOpen = False - self.__isFigureOpen = False - self.__isConfig = False - self.__counter = 0 - - self.drvObj = Driver(driver, idfigure, xw, yw, wintitle, overplot, colormap, colorbar) - self.driver = driver - self.idfigure = idfigure - self.nframes = nframes - self.wintitle = wintitle - self.colormap = colormap - self.overplot = overplot - self.colorbar = colorbar - - self.xw = xw - self.yw = yw - - self.frameObjList = [] - - self.drvObj.driver.setFigure() - self.drvObj.driver.setColormap(colormap) - - def __openDriver(self): - - self.drvObj.driver.openDriver() - - def __newPage(self): - - - self.drvObj.driver.openPage() - nrows, ncolumns = self.getSubplots() - self.drvObj.driver.setFigTitle(self.figuretitle) - self.drvObj.driver.setSubPlots(nrows, ncolumns) - - def __closePage(self): - - self.drvObj.driver.closeFigure() - - def selectFigure(self): - - self.drvObj.driver.selectFigure() - - def __isOutOfXRange(self,x): - try: - if ((x>=self.xmin) and (x0 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)) - - return xg, yg - - - def pcolor(self, id, xpos, ypos, data, x, y, xmin, xmax, ymin, ymax, zmin, zmax, deltax=None, deltay=None, getGrid=True, xaxisastime = False, timefmt="%H:%M"): - - plplot.pladv(id) - plplot.plvpor(xpos[0], xpos[1], ypos[0], ypos[1]) - plplot.plwind(float(xmin),float(xmax), float(ymin), float(ymax)) - - if xaxisastime: - timedelta = (xmax - xmin + 1)/8. - - if getGrid: - self.__xg, self.__yg = self.__getGrid(x, y, deltax, deltay) - - if deltax == None: deltax = x[-1] - x[0] -# if deltay == None: deltay = y[-1] - y[-2] - - xmin = x[0] - xmax = xmin + deltax - - plplot.plimagefr(data, - float(xmin), - float(xmax), - float(ymin), - float(ymax), - 0., - 0., - float(zmin), - float(zmax), - plplot.pltr2, - self.__xg, - self.__yg) - - if xaxisastime: - plplot.pltimefmt(timefmt) - xopt = "bcstd" - yopt = "bcst" - plplot.plbox(xopt, timedelta, 3, yopt, 0.0, 0) - else: - xopt = "bcst" - yopt = "bcst" - plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0) - - - def plotBox(self, id, xpos, ypos, xmin, xmax, ymin, ymax, minvalue, maxvalue, xopt, yopt, szchar=0.6, xaxisastime = False, timefmt="%H:%M"): - """ - xopt, yopt: entradas que no se aplican en MPL - """ - plplot.pladv(id) - 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 refresh(self): - plplot.plflush() - - def show(self): - plplot.plspause(True) - plplot.plend() - - def basicLine(self, id, xpos, ypos, x, y, xmin, xmax, ymin, ymax, color, xopt="bcst", yopt="bcst"): - - """ - Inputs: - x: datos en el eje x - - y: datos en el eje y - - xmin, xmax: intervalo de datos en el eje x - - ymin, ymax: intervalo de datos en el eje y - - color: color de la linea a dibujarse - - id: identificador del plot, en este caso indica al frame que pertenece, la posicion de cada - plot esta definido por xpos, ypos. - - xpos,ypos: coordenadas que indican la posicion del plot en el frame - - """ - - plplot.pladv(id) - plplot.plvpor(xpos[0], xpos[1], ypos[0], ypos[1]) - plplot.plwind(float(xmin),float(xmax), float(ymin), float(ymax)) - - if color == "blue": - colline = 9 - if color == "green": - colline = 3 - - plplot.plcol0(colline) - plplot.plline(x, y) - plplot.plcol0(1) -# plplot.plbox(xopt, 0.0, 0, yopt, 0.0, 0) - - def save(self, filename): - curr_strm = plplot.plgstrm() - save_strm = plplot.plmkstrm() - plplot.plsetopt("geometry", "%dx%d"%(self.xw,self.yw)) - plplot.plsdev("png") - plplot.plsfnam(filename) - plplot.plcpstrm(curr_strm,0) - plplot.plreplot() - plplot.plend1() - plplot.plsstrm(curr_strm) - - def setColormap(self, 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 (%s) is not valid" %(colormap) - - plplot.plscmap1n(ncolor) - plplot.plscmap1l(1, pos, r, g, b) - - return rgb_lvl - - -class MplDriver: -# fig = None - nrows = None - ncolumns = None - __axesId = None - __setData = None - - def __init__(self, idfigure, xw, yw, wintitle, overplot, colormap, colorbar): - - 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.colorbar = colorbar - self.__axesId = {} - - def setFigure(self): - plt.ioff() - fig = plt.figure(self.idfigure) - fig.canvas.manager.set_window_title(self.wintitle) - fig.canvas.resize(self.xw,self.yw) - plt.ion() - - - def setColormap(self, colormap): - pass - - def openDriver(self): - pass - - def openFigure(self): - pass - - def setFigTitle(self,title): - fig = plt.figure(self.idfigure) - fig.suptitle(title,fontsize=11, fontweight='bold') - - def setSubPlots(self,nrows,ncolumns): - fig = plt.figure(self.idfigure) - self.nrows = nrows - self.ncolumns = ncolumns - #self.__axesId = fig.add_subplot(nrows,ncolumns) - - def plotBox(self, id, xpos, ypos, xmin, xmax, ymin, ymax, minvalue, maxvalue, xopt, yopt, szchar, xaxisastime, timefmt): - fig = plt.figure(self.idfigure) - ax = fig.add_subplot(self.nrows,self.ncolumns,id) - ax.set_xlim([xmin,xmax]) - ax.set_ylim([ymin,ymax]) - self.__axesId.setdefault(id) - self.__axesId[id] = ax - - - def setPlotLabels(self, id, xlabel, ylabel, title): - ax = self.__axesId[id] - ax.set_xlabel(xlabel) - ax.set_ylabel(ylabel) - ax.set_title(title) - - def basicLine(self, id, xpos, ypos, x, y, xmin, xmax, ymin, ymax, color): - ax = self.__axesId[id] - - if self.__setData == None: - ax.plot(x,y,color) - self.__setData = True - else: - ax.lines[0].set_data(x,y) - - def refresh(self): - plt.draw() - - - def plotColorbar(self): - pass - - - def closePage(self): - pass \ No newline at end of file diff --git a/schainpy2/Graphics/schainPlotTypes.py b/schainpy2/Graphics/schainPlotTypes.py deleted file mode 100644 index 34ccc78..0000000 --- a/schainpy2/Graphics/schainPlotTypes.py +++ /dev/null @@ -1,699 +0,0 @@ -import numpy -import datetime -import time -from schainPlot import * - -class CrossSpc(Figure): - overplot = 0 - xw = 900 - yw = 650 - showprofile = False - signalA = None - signalB = None - coherence = None - phase = None - - def __init__(self, idfigure, nframes, wintitle, driver, colormap, colorbar, showprofile): - Figure.__init__(self,idfigure, nframes, wintitle, self.xw, self.yw, self.overplot, driver, colormap, colorbar) - - self.showprofile = showprofile - self.signalA = None - self.signalB = None - self.coherence = None - self.phase = None - - def getSubplots(self): - nrows = self.nframes - ncolumns = 1 - return nrows, ncolumns - - def setParms(self, data, x, y, xmin, xmax, ymin, ymax, minvalue, maxvalue, *args): - - if xmin == None: xmin = numpy.min(x) - if xmax == None: xmax = numpy.max(x) - if ymin == None: ymin = numpy.min(y) - if ymax == None: ymax = numpy.max(y) - if minvalue == None: minvalue = 20. - if maxvalue == None: maxvalue = 90. - - self.signalA = self.data[0] - self.signalB = self.data[1] - self.coherence = self.data[2] - self.phase = self.data[3] - - self.xmin = xmin - self.xmax = xmax - self.minrange = ymin - self.maxrange = ymax - self.ymin = ymin - self.ymax = ymax - self.minvalue = minvalue - self.maxvalue = maxvalue - - def changeXRange(self, *args): - pass - - def createFrames(self): - self.frameObjList = [] - - for frame in range(self.nframes): - frameObj = CrossSpcFrame(self.drvObj,frame + 1, self.colorbar, self.showprofile) - self.frameObjList.append(frameObj) - - -class CrossSpcFrame(Frame): - xi = None - xw = None - yi = None - yw = None - alpha = None - def __init__(self): - self.drvObj = drvObj - self.idframe = idframe - self.nplots = 4 - - if showprofile: - self.nplots += 4 - - self.colorbar = colorbar - self.showprofile = showprofile - self.xi = 0. - self.xw = 0. - self.yi = 0. - self.yw = 0. - self.alpha = 1. - - self.createPlots() - - def createPlots(self): - plotObjList = [] - idplot = 0 - counter_plot = 0 - for i in range(self.nplots): - xi, yi, xw, yw = self.getScreenPos(idplot) - plotObj = SpcPlot(self.drvObj, self.idframe, idplot, xi, yi, xw, yw, self.colorbar) - plotObjList.append(plotObj) - - if self.showprofile: - xi, yi, xw, yw = self.getScreenPosGraph1(idplot) - type = "pwbox" - title = "" - xlabel = "dB" - ylabel = "" - idplot += 1 - plotObj = Plot1D(self.drvObj, self.idframe, idplot, xi, yi, xw, yw, type, title, xlabel, ylabel) - plotObjList.append(plotObj) - idplot += 1 - - self.plotObjList = plotObjList - -# def getScreenPos(self,idplot): -# pass - - def getScreenPos(self, diplot): - - xi = self.xi - xw = self.xw - - if self.showprofile: - width = 0.55 - xw += width - - - - - self.xi = 0.15 + idplot*self.alpha - - if self.showprofile: - width = 0.55 - self.xw += width - - else: - width = 0.65 - self.xw += width - - if self.colorbar: - self.xw = self.xw - 0.06 - - - self.alpha = self.xw - - yi = 0.20; yw = 0.75 - - return xi, yi, xw, yw - - def getScreenPosGraph1(self): - if self.colorbar: - xi = self.xw + 0.08 - else: - xi = self.xw + 0.05 - - xw = xi + 0.2 - - self.alpha = xw - - if self.colorbar: - self.xi = 0.65 + 0.08 - else: - self.xi = 0.75 + 0.05 - - xw = xi + 0.2 - - yi = 0.2; yw = 0.75 - - return xi, yi, xw, yw - - def plot(self,x, y, data): - plotObj = self.plotObjList[0] - plotObj.plot(x,y,data) - - if self.showprofile: - plotObj = self.plotObjList[1] - avg_data = numpy.average(data, axis=0) - plotObj.plot(avg_data,y) - - -class SpcFigure(Figure): - overplot = 0 - xw = 900 - yw = 650 - showprofile = False - - def __init__(self, idfigure, nframes, wintitle, driver, colormap, colorbar, showprofile): - Figure.__init__(self,idfigure, nframes, wintitle, self.xw, self.yw, self.overplot, driver, colormap, colorbar) - - self.showprofile = showprofile - - def getSubplots(self): - ncolumns = int(numpy.sqrt(self.nframes)+0.9) - nrows = int(self.nframes*1./ncolumns + 0.9) - - return nrows, ncolumns - - def setParms(self, data, x, y, xmin, xmax, ymin, ymax, minvalue, maxvalue, *args): - - if xmin == None: xmin = numpy.min(x) - if xmax == None: xmax = numpy.max(x) - if ymin == None: ymin = numpy.min(y) - if ymax == None: ymax = numpy.max(y) - if minvalue == None: minvalue = 20. - if maxvalue == None: maxvalue = 90. - - self.xmin = xmin - self.xmax = xmax - self.minrange = ymin - self.maxrange = ymax - self.ymin = ymin - self.ymax = ymax - self.minvalue = minvalue - self.maxvalue = maxvalue - - - def changeXRange(self, *args): - pass - - def createFrames(self): - - self.frameObjList = [] - - for frame in range(self.nframes): - frameObj = SpcFrame(self.drvObj,frame + 1, self.colorbar, self.showprofile) - self.frameObjList.append(frameObj) - -class SpcFrame(Frame): - def __init__(self,drvObj,idframe,colorbar,showprofile): - self.drvObj = drvObj - self.idframe = idframe - self.nplots = 1 - - if showprofile: - self.nplots += 1 - - self.colorbar = colorbar - self.showprofile = showprofile - self.createPlots() - - def createPlots(self): - plotObjList = [] - idplot = 0 - xi, yi, xw, yw = self.getScreenPos(idplot) - plotObj = SpcPlot(self.drvObj, self.idframe, idplot, xi, yi, xw, yw, self.colorbar) - plotObjList.append(plotObj) - - if self.showprofile: - idplot = 1 - xi, yi, xw, yw = self.getScreenPos(idplot) - type = "pwbox" - title = "" - xlabel = "dB" - ylabel = "" - szchar = 0.70 - plotObj = Plot1D(self.drvObj, self.idframe, idplot, xi, yi, xw, yw, type, title, xlabel, ylabel, szchar) - plotObjList.append(plotObj) - - self.plotObjList = plotObjList - - def getScreenPosMainPlot(self): - - xi = 0.10 - - if self.showprofile: - xw = 0.62 - - else: - xw = 0.9 - - if self.colorbar: - xw = xw - 0.06 - - yi = 0.1; yw = 0.87 - - return xi, yi, xw, yw - - def getScreenPosGraph1(self): - - if self.colorbar: - xi = 0.65 + 0.08 - else: - xi = 0.75 + 0.05 - - xw = xi + 0.2 - - yi = 0.1; yw = 0.87 - - return xi, yi, xw, yw - - def plot(self,x, y, data): - plotObj = self.plotObjList[0] - plotObj.plot(x,y,data) - - if self.showprofile: - plotObj = self.plotObjList[1] - avg_data = numpy.average(data, axis=0) - plotObj.plot(avg_data,y) - -class SpcPlot(Plot): - - getGrid = True - - def __init__(self, drvObj, idframe, idplot, xi, yi, xw, yw, colorbar): - self.drvObj = drvObj - self.idframe = idframe - self.idplot = idplot - self.xi = xi - self.yi = yi - self.xw = xw - self.yw = yw - self.colorbar = colorbar - - if self.colorbar: - cbxi = xw + 0.03 - cbxw = cbxi + 0.03 - cbyi = yi - cbyw = yw - self.cbxpos = [cbxi,cbxw] - self.cbypos = [cbyi,cbyw] - - self.xpos = [self.xi,self.xw] - self.ypos = [self.yi,self.yw] - self.xaxisastime = False - self.timefmt = None - self.xopt = "bcnst" - self.yopt = "bcnstv" - - self.szchar = 0.7 - self.strforchannel = "Channel %d"%self.idframe - self.xlabel = "m/s" - self.ylabel = "Range (Km)" - - def setBox(self, xmin, xmax, ymin, ymax, minvalue, maxvalue, *args): - self.xmin = xmin - self.xmax = xmax - self.ymin = ymin - self.ymax = ymax - self.minvalue = minvalue - self.maxvalue = maxvalue - self.colorbar = args[2] - self.title = "%s - %s"%(self.strforchannel,args[3]) - - - - def plot(self, x, y, data): - z = data - deltax = None - deltay = None - self.plotPcolor(x, y, z, deltax, deltay, self.getGrid) - self.getGrid = False - - -class RTIFigure(Figure): - overplot = 1 - xw = 700 - yw = 650 - showprofile = False - starttime = None - endtime = None - minrange = None - maxrange = None - minvalue = None - maxvalue = None - xrangestepinsecs = None - timefmt=None - - def __init__(self, idfigure, nframes, wintitle, driver, colormap="br_green", colorbar= True, showprofile=False): - Figure.__init__(self,idfigure, nframes, wintitle, self.xw, self.yw, self.overplot, driver, colormap, colorbar) - - self.showprofile = showprofile - - def getSubplots(self): - nrows = self.nframes - ncolumns = 1 - return nrows, ncolumns - - def setParms(self, data, x, y, xmin, xmax, ymin, ymax, minvalue, maxvalue, xrangestep, deltax): - - self.starttime = xmin - self.endtime = xmax - - cdatetime = datetime.datetime.utcfromtimestamp(x) - - mindatetime = datetime.datetime(cdatetime.year,cdatetime.month,cdatetime.day,self.starttime.hour,self.starttime.minute,self.starttime.second) - - maxdatetime = mindatetime + datetime.timedelta(seconds=xrangestep) - self.xrangestepinsecs = xrangestep - - xmin = time.mktime(mindatetime.timetuple()) - xmax = time.mktime(maxdatetime.timetuple()) - - if self.xrangestepinsecs<=60.: - self.timefmt="%H:%M:%S" - - if self.xrangestepinsecs>0. and self.xrangestepinsecs<=1200.: - self.timefmt="%H:%M:%S" - - if self.xrangestepinsecs>1200. and self.xrangestepinsecs<=86400.: - self.timefmt="%H:%M" - - if self.xrangestepinsecs>86400.: - self.timefmt="%y:%m:%d:%H" - - if ymin == None: ymin = numpy.min(y) - if ymax == None: ymax = numpy.max(y) - - if minvalue == None: minvalue = 0. - if maxvalue == None: maxvalue = 50. - - self.xmin = xmin - self.xmax = xmax - self.minrange = ymin - self.maxrange = ymax - self.ymin = ymin - self.ymax = ymax - self.minvalue = minvalue - self.maxvalue = maxvalue - self.xrangestep = xrangestep - self.deltax = deltax - - def changeXRange(self,x): - - cdatetime = datetime.datetime.utcfromtimestamp(x) - - if ((cdatetime.time()>=self.starttime) and (cdatetime.time()= self.xmaxpos: - - self.xminpos = currenttime - self.xmaxpos = currenttime + self.deltax - x = [currenttime] - y = range - z = numpy.reshape(data, (1,-1)) - getGrid = True - - self.plotPcolor(x, y, z, self.deltax, self.deltay, getGrid) - - -class ScopeFigure(Figure): - overplot = 0 - xw = 700 - yw = 650 - colorbar = None - - def __init__(self,idfigure,nframes,wintitle,driver): - colormap = None - colorbar = False - - Figure.__init__(self,idfigure, nframes, wintitle, self.xw, self.yw, self.overplot, driver, colormap, colorbar) - - - def getSubplots(self): - nrows = self.nframes - ncolumns = 1 - return nrows, ncolumns - - def createFrames(self): - - self.frameObjList = [] - - for frame in range(self.nframes): - frameObj = ScopeFrame(self.drvObj,frame + 1) - self.frameObjList.append(frameObj) - - -class ScopeFrame(Frame): - xlabel = "" - ylabel = "" - title = "" - szchar = 1.1 - - def __init__(self,drvObj,idframe): - self.drvObj = drvObj - self.idframe = idframe - self.nplots = 1 - self.createPlots() -# Frame.__init__(self, drvObj, idframe) - - def getScreenPosMainPlot(self):#cada Frame determina las coordenadas de los plots - xi = 0.08; xw = 0.9 - yi = 0.20; yw = 0.75 - return xi,yi,xw,yw - - def createPlots(self): - plotObjList = [] - for idplot in range(self.nplots): - xi, yi, xw, yw = self.getScreenPos(idplot) - type = "scopebox" - title = "Channel %d"%self.idframe - xlabel = "range (Km)" - ylabel = "intensity" - plotObj = Plot1D(self.drvObj, self.idframe, idplot, xi, yi, xw, yw, type, title, xlabel, ylabel, self.szchar) - plotObjList.append(plotObj) - - self.plotObjList = plotObjList - - - def plot(self, x, y, z=None): - for plotObj in self.plotObjList: - plotObj.plot(x, y) - - -class Plot1D(Plot): -# type, title, xlabel, ylabel - def __init__(self, drvObj, idframe, idplot, xi, yi, xw, yw, type, title, xlabel, ylabel, szchar): - self.drvObj = drvObj - self.idframe = idframe - self.idplot = idplot - self.xi = xi - self.yi = yi - self.xw = xw - self.yw = yw - self.xpos = [self.xi,self.xw] - self.ypos = [self.yi,self.yw] - self.xaxisastime = False - self.timefmt = None - self.xopt = "bcnst" - self.yopt = "bcnstv" - self.szchar = szchar - self.type = type - self.title = title - self.xlabel = xlabel - self.ylabel = ylabel - - - - def setBox(self, xmin, xmax, ymin, ymax, minvalue, maxvalue, *args): - if self.type == "pwbox": - self.xmin = minvalue - self.xmax = maxvalue - self.ymin = ymin - self.ymax = ymax - self.minvalue = minvalue - self.maxvalue = maxvalue - self.xopt = "bcnstg" - self.yopt = "bcmstv" - - else: - self.xmin = xmin - self.xmax = xmax - self.ymin = ymin - self.ymax = ymax - self.minvalue = minvalue - self.maxvalue = maxvalue - - self.colorbar = False - - def plot(self,x,y): - if y.dtype == "complex128": - color="blue" - self.plotBasicLine(x, y.real, color) - color="red" - self.plotBasicLine(x, y.imag, color) - else: - color="blue" - self.plotBasicLine(x, y, color) diff --git a/schainpy2/IO/JRODataIO.py b/schainpy2/IO/JRODataIO.py deleted file mode 100644 index 6e6563b..0000000 --- a/schainpy2/IO/JRODataIO.py +++ /dev/null @@ -1,1080 +0,0 @@ -''' - -$Author$ -$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 JROHeaderIO import * -from Data.JROData import JROData - -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. - - """ - basicHeaderObj = BasicHeader() - - try: - fp = open(filename,'rb') - except: - raise IOError, "The file %s can't be opened" %(filename) - - sts = basicHeaderObj.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 <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.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 - -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 - -class JRODataIO: - - c = 3E8 - - basicHeaderObj = BasicHeader() - - systemHeaderObj = SystemHeader() - - radarControllerHeaderObj = RadarControllerHeader() - - processingHeaderObj = ProcessingHeader() - - online = 0 - - dtype = None - - pathList = [] - - filenameList = [] - - filename = None - - ext = None - - flagNoMoreFiles = 0 - - flagIsNewFile = 1 - - flagTimeBlock = 0 - - flagIsNewBlock = 0 - - fp = None - - firstHeaderSize = 0 - - basicHeaderSize = 24 - - versionFile = 1103 - - fileSize = None - - ippSeconds = None - - fileSizeByHeader = None - - fileIndex = None - - profileIndex = None - - blockIndex = None - - nTotalBlocks = None - - maxTimeStep = 30 - - lastUTTime = None - - datablock = None - - dataOutObj = None - - blocksize = None - - set = None - - def __init__(self): - pass - -class JRODataReader(JRODataIO): - - nReadBlocks = 0 - - delay = 10 #number of seconds waiting a new file - - nTries = 3 #quantity tries - - nFiles = 3 #number of files for searching - - - def __init__(self): - pass - - def createObjByDefault(self): - """ - - """ - raise ValueError, "This method has not been implemented" - - def getBlockDimension(self): - - raise ValueError, "No implemented" - - def __searchFilesOffLine(self, - path, - startDate, - endDate, - startTime=datetime.time(0,0,0), - endTime=datetime.time(23,59,59), - set=None, - expLabel="", - ext=".r"): - 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 __searchFilesOnLine(self, path, startDate=None, endDate=None, startTime=None, endTime=None, expLabel = "", ext = 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) - - expLabel : Nombre del subexperimento (subfolder) - - 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 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 = False, - delay = 60): - - 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 - self.delay = delay - self.online = online - self.ext = ext.lower() - - if online: - print "Searching files in online mode..." - doypath, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext) - - if not(doypath): - for nTries in range( self.nTries ): - print '\tWaiting %0.2f sec for an 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=ext) - 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: - print "Searching files in offline mode ..." - pathList, filenameList = self.__searchFilesOffLine(path, startDate, endDate, startTime, endTime, set, expLabel, ext) - - if not(pathList): - print "No *%s files into the folder %s \nfor the range: %s - %s"%(ext, path, - datetime.datetime.combine(startDate,startTime).ctime(), - datetime.datetime.combine(endDate,endTime).ctime()) - - sys.exit(-1) - - - self.fileIndex = -1 - self.pathList = pathList - self.filenameList = filenameList - - 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 range: %s" %(datetime.datetime.combine(startDate,startTime).ctime()) - else: - print "No files" - - sys.exit(-1) - -# self.updateDataHeader() - - return self.dataOutObj - - def __setNextFileOffline(self): - - 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 __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 the file \"%s\" , 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" % 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, 'rb') - 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 setNextFile(self): - 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 __waitNewBlock(self): - #si es OnLine y ademas aun no se han leido un bloque completo entonces se espera por uno valido - if not self.online: - return 0 - - if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile): - return 0 - - currentPointer = self.fp.tell() - - neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize - - for nTries in range( self.nTries ): - - self.fp.close() - self.fp = open( self.filename, 'rb' ) - self.fp.seek( currentPointer ) - - self.fileSize = os.path.getsize( self.filename ) - currentSize = self.fileSize - currentPointer - - if ( currentSize >= neededSize ): - self.__rdBasicHeader() - return 1 - - print "\tWaiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1) - time.sleep( self.delay ) - - - return 0 - - def __setNewBlock(self): - if self.fp == None: - return 0 - - if self.flagIsNewFile: - return 1 - - self.lastUTTime = self.basicHeaderObj.utc - currentSize = self.fileSize - self.fp.tell() - neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize - - if (currentSize >= neededSize): - self.__rdBasicHeader() - return 1 - - if self.__waitNewBlock(): - return 1 - - if not(self.setNextFile()): - return 0 - - deltaTime = self.basicHeaderObj.utc - self.lastUTTime # - - self.flagTimeBlock = 0 - - if deltaTime > self.maxTimeStep: - self.flagTimeBlock = 1 - - return 1 - - - def readNextBlock(self): - if not(self.__setNewBlock()): - return 0 - - if not(self.readBlock()): - return 0 - - return 1 - - def __rdProcessingHeader(self, fp=None): - if fp == None: - fp = self.fp - - self.processingHeaderObj.read(fp) - - def __rdRadarControllerHeader(self, fp=None): - if fp == None: - fp = self.fp - - self.radarControllerHeaderObj.read(fp) - - def __rdSystemHeader(self, fp=None): - if fp == None: - fp = self.fp - - self.systemHeaderObj.read(fp) - - def __rdBasicHeader(self, fp=None): - if fp == None: - fp = self.fp - - self.basicHeaderObj.read(fp) - - - def __readFirstHeader(self): - self.__rdBasicHeader() - self.__rdSystemHeader() - self.__rdRadarControllerHeader() - self.__rdProcessingHeader() - - self.firstHeaderSize = self.basicHeaderObj.size - - datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR)) - if datatype == 0: - datatype_str = numpy.dtype([('real',' 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.blockIndex = 0 - - #guardando atributos - self.filename = filename - self.subfolder = subfolder - self.fp = fp - self.setFile = setFile - self.flagIsNewFile = 1 - - self.getDataHeader() - - 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.blockIndex < self.processingHeaderObj.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.basicHeaderObj self. - systemHeaderObj self.radarControllerHeaderObj self.processingHeaderObj self. - dtype Return: None - """ - - raise ValueError, "No implemented" - - def setup(self, path, blocksPerFile, profilesPerBlock=None, 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.ext = ext - - self.path = path - - self.setFile = set - 1 - - self.blocksPerFile = blocksPerFile - - self.profilesPerBlock = profilesPerBlock - - if not(self.setNextFile()): - print "There isn't a next file" - return 0 - - self.setBlockDimension() - - return 1 - - - - - - diff --git a/schainpy2/IO/JROHeaderIO.py b/schainpy2/IO/JROHeaderIO.py deleted file mode 100644 index edb3247..0000000 --- a/schainpy2/IO/JROHeaderIO.py +++ /dev/null @@ -1,505 +0,0 @@ -''' - -$Author$ -$Id$ -''' - -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.nWindows, - 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 - dtype = None - blockSize = None - profilesPerBlock = None - dataBlocksPerFile = None - nWindows = None - processFlags = None - nCohInt = None - nIncohInt = None - totalSpectra = None - struct = None - flag_dc = None - flag_cspc = None - - def __init__(self): - self.size = 0 - self.dtype = 0 - self.blockSize = 0 - self.profilesPerBlock = 0 - self.dataBlocksPerFile = 0 - self.nWindows = 0 - self.processFlags = 0 - self.nCohInt = 0 - self.nIncohInt = 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.dtype, - self.blockSize, - self.profilesPerBlock, - self.dataBlocksPerFile, - self.nWindows, - self.processFlags, - self.nCohInt, - self.nIncohInt, - self.totalSpectra) - - header = numpy.array(headerTuple,self.struct) - header.tofile(fp) - - if self.nWindows != 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: - nCode = self.nCode #Probar con un dato que almacene codigo, hasta el momento no se hizo la prueba - nCode.tofile(fp) - - nBaud = self.nBaud - nBaud.tofile(fp) - - code = self.code.reshape(nCode*nBaud) - 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/schainpy2/IO/SpectraIO.py b/schainpy2/IO/SpectraIO.py deleted file mode 100644 index 13adaa4..0000000 --- a/schainpy2/IO/SpectraIO.py +++ /dev/null @@ -1,949 +0,0 @@ -''' - -$Author$ -$Id$ -''' - -import os, sys -import numpy - -import pyfits -import glob -import fnmatch -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from JROHeaderIO import * -from JRODataIO import JRODataReader -from JRODataIO import JRODataWriter - -from Data.JROData import Spectra - -from Data.JROData import SpectraHeis - -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.data_spc - - print readerObj.data_cspc - - print readerObj.data_dc - - if readerObj.flagNoMoreFiles: - break - - """ - - pts2read_SelfSpectra = 0 - - pts2read_CrossSpectra = 0 - - pts2read_DCchannels = 0 - - ext = ".pdata" - - optchar = "P" - - dataOutObj = None - - nRdChannels = None - - nRdPairs = None - - rdPairList = [] - - - 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.pts2read_SelfSpectra = 0 - - self.pts2read_CrossSpectra = 0 - - self.pts2read_DCchannels = 0 - - self.datablock = None - - self.utc = None - - self.ext = ".pdata" - - self.optchar = "P" - - self.basicHeaderObj = BasicHeader() - - self.systemHeaderObj = SystemHeader() - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.processingHeaderObj = ProcessingHeader() - - self.online = 0 - - self.fp = None - - self.idFile = None - - self.dtype = None - - self.fileSizeByHeader = None - - self.filenameList = [] - - self.filename = None - - self.fileSize = None - - self.firstHeaderSize = 0 - - self.basicHeaderSize = 24 - - self.pathList = [] - - self.lastUTTime = 0 - - self.maxTimeStep = 30 - - self.flagNoMoreFiles = 0 - - self.set = 0 - - self.path = None - - self.delay = 3 #seconds - - self.nTries = 3 #quantity tries - - self.nFiles = 3 #number of files for searching - - self.nReadBlocks = 0 - - self.flagIsNewFile = 1 - - self.ippSeconds = 0 - - self.flagTimeBlock = 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.nRdChannels - self.nRdPairs - self.pts2read_SelfSpectra - self.pts2read_CrossSpectra - self.pts2read_DCchannels - self.blocksize - self.dataOutObj.nChannels - self.dataOutObj.nPairs - - Return: - None - """ - self.nRdChannels = 0 - self.nRdPairs = 0 - self.rdPairList = [] - - for i in range(0, self.processingHeaderObj.totalSpectra*2, 2): - if self.processingHeaderObj.spectraComb[i] == self.processingHeaderObj.spectraComb[i+1]: - self.nRdChannels = self.nRdChannels + 1 #par de canales iguales - else: - self.nRdPairs = self.nRdPairs + 1 #par de canales diferentes - self.rdPairList.append((self.processingHeaderObj.spectraComb[i], self.processingHeaderObj.spectraComb[i+1])) - - pts2read = self.processingHeaderObj.nHeights * self.processingHeaderObj.profilesPerBlock - - self.pts2read_SelfSpectra = int(self.nRdChannels * pts2read) - self.blocksize = self.pts2read_SelfSpectra - - if self.processingHeaderObj.flag_cspc: - self.pts2read_CrossSpectra = int(self.nRdPairs * pts2read) - self.blocksize += self.pts2read_CrossSpectra - - if self.processingHeaderObj.flag_dc: - self.pts2read_DCchannels = int(self.systemHeaderObj.nChannels * self.processingHeaderObj.nHeights) - 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.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.dtype[0], self.pts2read_SelfSpectra ) - spc = spc.reshape( (self.nRdChannels, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D - - if self.processingHeaderObj.flag_cspc: - cspc = numpy.fromfile( self.fp, self.dtype, self.pts2read_CrossSpectra ) - cspc = cspc.reshape( (self.nRdPairs, self.processingHeaderObj.nHeights, self.processingHeaderObj.profilesPerBlock) ) #transforma a un arreglo 3D - - if self.processingHeaderObj.flag_dc: - dc = numpy.fromfile( self.fp, self.dtype, self.pts2read_DCchannels ) #int(self.processingHeaderObj.nHeights*self.systemHeaderObj.nChannels) ) - dc = dc.reshape( (self.systemHeaderObj.nChannels, self.processingHeaderObj.nHeights) ) #transforma a un arreglo 2D - - - if not(self.processingHeaderObj.shif_fft): - spc = numpy.roll( spc, self.processingHeaderObj.profilesPerBlock/2, axis=2 ) #desplaza a la derecha en el eje 2 determinadas posiciones - - if self.processingHeaderObj.flag_cspc: - cspc = numpy.roll( cspc, self.processingHeaderObj.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.processingHeaderObj.flag_cspc: - cspc = numpy.transpose( cspc, (0,2,1) ) - self.data_cspc = cspc['real'] + cspc['imag']*1j - else: - self.data_cspc = None - - if self.processingHeaderObj.flag_dc: - self.data_dc = dc['real'] + dc['imag']*1j - else: - self.data_dc = None - - 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.flagTimeBlock - self.flagIsNewBlock - """ - - if self.flagNoMoreFiles: return 0 - - self.flagTimeBlock = 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.data_spc = self.data_spc - - self.dataOutObj.data_cspc = self.data_cspc - - self.dataOutObj.data_dc = self.data_dc - - self.dataOutObj.flagTimeBlock = self.flagTimeBlock - - self.dataOutObj.flagNoData = False - - self.dataOutObj.dtype = self.dtype - - self.dataOutObj.nChannels = self.nRdChannels - - self.dataOutObj.nPairs = self.nRdPairs - - self.dataOutObj.pairsList = self.rdPairList - - self.dataOutObj.nHeights = self.processingHeaderObj.nHeights - - self.dataOutObj.nProfiles = self.processingHeaderObj.profilesPerBlock - - self.dataOutObj.nFFTPoints = self.processingHeaderObj.profilesPerBlock - - self.dataOutObj.nIncohInt = self.processingHeaderObj.nIncohInt - - - xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight - - self.dataOutObj.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight) - - self.dataOutObj.channelList = range(self.systemHeaderObj.nChannels) - - self.dataOutObj.channelIndexList = range(self.systemHeaderObj.nChannels) - - self.dataOutObj.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000.#+ self.profileIndex * self.ippSeconds - - self.dataOutObj.ippSeconds = self.ippSeconds - - self.dataOutObj.timeInterval = self.ippSeconds * self.processingHeaderObj.nCohInt * self.processingHeaderObj.nIncohInt * self.dataOutObj.nFFTPoints - - self.dataOutObj.flagShiftFFT = self.processingHeaderObj.shif_fft - -# self.profileIndex += 1 - - self.dataOutObj.systemHeaderObj = self.systemHeaderObj.copy() - - self.dataOutObj.radarControllerHeaderObj = self.radarControllerHeaderObj.copy() - - return self.dataOutObj.data_spc - - -class SpectraWriter(JRODataWriter): - - """ - Esta clase permite escribir datos de espectros a archivos procesados (.pdata). La escritura - de los datos siempre se realiza por bloques. - """ - - ext = ".pdata" - - optchar = "P" - - shape_spc_Buffer = None - - shape_cspc_Buffer = None - - shape_dc_Buffer = None - - data_spc = None - - data_cspc = None - - data_dc = None - - wrPairList = [] - - nWrPairs = 0 - - nWrChannels = 0 - -# dataOutObj = None - - def __init__(self, dataOutObj=None): - """ - Inicializador de la clase SpectraWriter para la escritura de datos de espectros. - - Affected: - self.dataOutObj - self.basicHeaderObj - self.systemHeaderObj - self.radarControllerHeaderObj - self.processingHeaderObj - - 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.nTotalBlocks = 0 - - self.nWrChannels = self.dataOutObj.nChannels - -# if len(pairList) > 0: -# self.wrPairList = pairList -# -# self.nWrPairs = len(pairList) - - self.wrPairList = self.dataOutObj.pairsList - - self.nWrPairs = self.dataOutObj.nPairs - -# self.data_spc = None -# self.data_cspc = None -# self.data_dc = None - -# self.fp = None - -# self.flagIsNewFile = 1 -# -# self.nTotalBlocks = 0 -# -# self.flagIsNewBlock = 0 -# -# self.flagNoMoreFiles = 0 -# -# self.setFile = None -# -# self.dtype = None -# -# self.path = None -# -# self.noMoreFiles = 0 -# -# self.filename = None -# -# self.basicHeaderObj = BasicHeader() -# -# self.systemHeaderObj = SystemHeader() -# -# self.radarControllerHeaderObj = RadarControllerHeader() -# -# self.processingHeaderObj = 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.processingHeaderObj.nHeights, - self.processingHeaderObj.profilesPerBlock) - - self.shape_cspc_Buffer = (self.dataOutObj.nPairs, - self.processingHeaderObj.nHeights, - self.processingHeaderObj.profilesPerBlock) - - self.shape_dc_Buffer = (self.dataOutObj.nChannels, - self.processingHeaderObj.nHeights) - - - 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.processingHeaderObj.shif_fft ): - spc = numpy.roll( spc, self.processingHeaderObj.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.dtype ) - cspc = numpy.transpose( self.data_cspc, (0,2,1) ) - if not( self.processingHeaderObj.shif_fft ): - cspc = numpy.roll( cspc, self.processingHeaderObj.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) - - if self.data_dc != None: - data = numpy.zeros( self.shape_dc_Buffer, self.dtype ) - 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 - self.blockIndex += 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.flagTimeBlock: - self.data_spc.fill(0) - self.data_cspc.fill(0) - self.data_dc.fill(0) - self.setNextFile() - - if self.flagIsNewFile == 0: - self.getBasicHeader() - - self.data_spc = self.dataOutObj.data_spc - self.data_cspc = self.dataOutObj.data_cspc - self.data_dc = self.dataOutObj.data_dc - - # #self.processingHeaderObj.dataBlocksPerFile) - if self.hasAllDataInBuffer(): -# self.getDataHeader() - self.writeNextBlock() - - if self.flagNoMoreFiles: - #print 'Process finished' - return 0 - return 1 - - - def __getProcessFlags(self): - - processFlags = 0 - - dtype0 = numpy.dtype([('real',' 1: - processFlags += PROCFLAG.INCOHERENT_INTEGRATION - - if self.dataOutObj.data_dc != None: - processFlags += PROCFLAG.SAVE_CHANNELS_DC - - return processFlags - - - def __getBlockSize(self): - ''' - Este metodos determina el cantidad de bytes para un bloque de datos de tipo Spectra - ''' - - dtype0 = numpy.dtype([('real',' 0: - channelList = [] - for channel in range(self.dataOutObj.nChannels): - channelList.append(channel) - channelList.append(channel) - - pairsList = [] - for pair in self.dataOutObj.pairsList: - pairsList.append(pair[0]) - pairsList.append(pair[1]) - spectraComb = channelList + pairsList - spectraComb = numpy.array(spectraComb,dtype="u1") - self.processingHeaderObj.spectraComb = spectraComb - sizeOfSpcComb = len(spectraComb) - processingHeaderSize += sizeOfSpcComb - - if self.dataOutObj.code != None: - self.processingHeaderObj.code = self.dataOutObj.code - self.processingHeaderObj.nCode = self.dataOutObj.nCode - self.processingHeaderObj.nBaud = self.dataOutObj.nBaud - nCodeSize = 4 # bytes - nBaudSize = 4 # bytes - codeSize = 4 # bytes - sizeOfCode = int(nCodeSize + nBaudSize + codeSize * self.dataOutObj.nCode * self.dataOutObj.nBaud) - processingHeaderSize += sizeOfCode - - if self.processingHeaderObj.nWindows != 0: - self.processingHeaderObj.firstHeight = self.dataOutObj.heightList[0] - self.processingHeaderObj.deltaHeight = self.dataOutObj.heightList[1] - self.dataOutObj.heightList[0] - self.processingHeaderObj.nHeights = self.dataOutObj.nHeights - self.processingHeaderObj.samplesWin = self.dataOutObj.nHeights - sizeOfFirstHeight = 4 - sizeOfdeltaHeight = 4 - sizeOfnHeights = 4 - sizeOfWindows = (sizeOfFirstHeight + sizeOfdeltaHeight + sizeOfnHeights)*self.processingHeaderObj.nWindows - processingHeaderSize += sizeOfWindows - - self.processingHeaderObj.size = processingHeaderSize - - - -class FITS: - name=None - format=None - array =None - data =None - thdulist=None - prihdr=None - hdu=None - - def __init__(self): - - pass - - def setColF(self,name,format,array): - self.name=name - self.format=format - self.array=array - a1=numpy.array([self.array],dtype=numpy.float32) - self.col1 = pyfits.Column(name=self.name, format=self.format, array=a1) - return self.col1 - -# def setColP(self,name,format,data): -# self.name=name -# self.format=format -# self.data=data -# a2=numpy.array([self.data],dtype=numpy.float32) -# self.col2 = pyfits.Column(name=self.name, format=self.format, array=a2) -# return self.col2 - - - def writeData(self,name,format,data): - self.name=name - self.format=format - self.data=data - a2=numpy.array([self.data],dtype=numpy.float32) - self.col2 = pyfits.Column(name=self.name, format=self.format, array=a2) - return self.col2 - - def cFImage(self,idblock,year,month,day,hour,minute,second): - self.hdu= pyfits.PrimaryHDU(idblock) - self.hdu.header.set("Year",year) - self.hdu.header.set("Month",month) - self.hdu.header.set("Day",day) - self.hdu.header.set("Hour",hour) - self.hdu.header.set("Minute",minute) - self.hdu.header.set("Second",second) - return self.hdu - - - def Ctable(self,colList): - self.cols=pyfits.ColDefs(colList) - self.tbhdu = pyfits.new_table(self.cols) - return self.tbhdu - - - def CFile(self,hdu,tbhdu): - self.thdulist=pyfits.HDUList([hdu,tbhdu]) - - def wFile(self,filename): - self.thdulist.writeto(filename) - -class SpectraHeisWriter(JRODataWriter): - set = None - setFile = None - idblock = None - doypath = None - subfolder = None - - def __init__(self, dataOutObj): - self.wrObj = FITS() - self.dataOutObj = dataOutObj - self.nTotalBlocks=0 - self.set = None - self.setFile = 0 - self.idblock = 0 - self.wrpath = None - self.doypath = None - self.subfolder = None - - - 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 setup(self, wrpath): - - if not(os.path.exists(wrpath)): - os.mkdir(wrpath) - - self.wrpath = wrpath - self.setFile = 0 - - def putData(self): - name= time.localtime( self.dataOutObj.utctime) - ext=".fits" - - if self.doypath == None: - self.subfolder = 'F%4.4d%3.3d_%d' % (name.tm_year,name.tm_yday,time.mktime(datetime.datetime.now().timetuple())) - self.doypath = os.path.join( self.wrpath, self.subfolder ) - os.mkdir(self.doypath) - - if self.set == None: - self.set = self.dataOutObj.set - self.setFile = 0 - if self.set != self.dataOutObj.set: - self.set = self.dataOutObj.set - self.setFile = 0 - - #make the filename - file = 'D%4.4d%3.3d%3.3d_%3.3d%s' % (name.tm_year,name.tm_yday,self.set,self.setFile,ext) - - filename = os.path.join(self.wrpath,self.subfolder, file) - - idblock = numpy.array([self.idblock],dtype="int64") - header=self.wrObj.cFImage(idblock=idblock, - year=time.gmtime(self.dataOutObj.utctime).tm_year, - month=time.gmtime(self.dataOutObj.utctime).tm_mon, - day=time.gmtime(self.dataOutObj.utctime).tm_mday, - hour=time.gmtime(self.dataOutObj.utctime).tm_hour, - minute=time.gmtime(self.dataOutObj.utctime).tm_min, - second=time.gmtime(self.dataOutObj.utctime).tm_sec) - - c=3E8 - freq=numpy.arange(-1*self.dataOutObj.nHeights/2.,self.dataOutObj.nHeights/2.)*(c/(2*self.dataOutObj.deltaHeight*1000)) - - colList = [] - - colFreq=self.wrObj.setColF(name="freq", format=str(self.dataOutObj.nFFTPoints)+'E', array=freq) - - colList.append(colFreq) - - nchannel=self.dataOutObj.nChannels - - for i in range(nchannel): - col = self.wrObj.writeData(name="PCh"+str(i+1), - format=str(self.dataOutObj.nFFTPoints)+'E', - data=10*numpy.log10(self.dataOutObj.data_spc[i,:])) - - colList.append(col) - - data=self.wrObj.Ctable(colList=colList) - - self.wrObj.CFile(header,data) - - self.wrObj.wFile(filename) - - #update the setFile - self.setFile += 1 - self.idblock += 1 - - return 1 - - \ No newline at end of file diff --git a/schainpy2/IO/VoltageIO.py b/schainpy2/IO/VoltageIO.py deleted file mode 100644 index b35fe80..0000000 --- a/schainpy2/IO/VoltageIO.py +++ /dev/null @@ -1,602 +0,0 @@ -''' - -$Author$ -$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 JROHeaderIO import * -from JRODataIO import JRODataReader -from JRODataIO import JRODataWriter - -from Data.JROData import Voltage - -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 - - """ - - ext = ".r" - - optchar = "D" - dataOutObj = None - - - 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.basicHeaderObj = BasicHeader() - - self.systemHeaderObj = SystemHeader() - - self.radarControllerHeaderObj = RadarControllerHeader() - - self.processingHeaderObj = ProcessingHeader() - - self.online = 0 - - self.fp = None - - self.idFile = None - - self.dtype = 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.flagTimeBlock = 0 - - self.flagIsNewBlock = 0 - - self.nTotalBlocks = 0 - - self.blocksize = 0 - - def createObjByDefault(self): - - dataObj = Voltage() - - return dataObj - - def __hasNotDataInBuffer(self): - if self.profileIndex >= self.processingHeaderObj.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.processingHeaderObj.profilesPerBlock * self.processingHeaderObj.nHeights * self.systemHeaderObj.nChannels - 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.dtype, self.blocksize ) - - try: - junk = junk.reshape( (self.processingHeaderObj.profilesPerBlock, self.processingHeaderObj.nHeights, self.systemHeaderObj.nChannels) ) - 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 __getset(self,filename): - name = os.path.basename(filename) - basename,ext = os.path.splitext(name) - set = int(basename[8:]) - return set - - 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.flagTimeBlock - self.flagIsNewBlock - """ - if self.flagNoMoreFiles: return 0 - - self.flagTimeBlock = 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 - - self.dataOutObj.set = self.__getset(self.filename) - - self.dataOutObj.data = self.datablock[:,self.profileIndex,:] - - self.dataOutObj.dtype = self.dtype - - self.dataOutObj.nChannels = self.systemHeaderObj.nChannels - - self.dataOutObj.nHeights = self.processingHeaderObj.nHeights - - self.dataOutObj.nProfiles = self.processingHeaderObj.profilesPerBlock - - xf = self.processingHeaderObj.firstHeight + self.processingHeaderObj.nHeights*self.processingHeaderObj.deltaHeight - - self.dataOutObj.heightList = numpy.arange(self.processingHeaderObj.firstHeight, xf, self.processingHeaderObj.deltaHeight) - - self.dataOutObj.channelList = range(self.systemHeaderObj.nChannels) - - self.dataOutObj.channelIndexList = range(self.systemHeaderObj.nChannels) - - self.dataOutObj.flagTimeBlock = self.flagTimeBlock - - self.dataOutObj.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.ippSeconds - - self.dataOutObj.ippSeconds = self.ippSeconds - - self.dataOutObj.deltaHeight = self.processingHeaderObj.deltaHeight - - self.dataOutObj.timeInterval = self.ippSeconds * self.processingHeaderObj.nCohInt - - self.dataOutObj.nCohInt = self.processingHeaderObj.nCohInt - - self.dataOutObj.flagShiftFFT = False - - if self.processingHeaderObj.code != None: - self.dataOutObj.nCode = self.processingHeaderObj.nCode - - self.dataOutObj.nBaud = self.processingHeaderObj.nBaud - - self.dataOutObj.code = self.processingHeaderObj.code - - self.profileIndex += 1 - - self.dataOutObj.systemHeaderObj = self.systemHeaderObj.copy() - - self.dataOutObj.radarControllerHeaderObj = self.radarControllerHeaderObj.copy() - - self.dataOutObj.flagNoData = False - -# print self.profileIndex, self.dataOutObj.utctime -# if self.profileIndex == 800: -# a=1 - - return 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. - """ - - ext = ".r" - - optchar = "D" - - 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 - - self.nTotalBlocks = 0 - - self.profileIndex = 0 - - def hasAllDataInBuffer(self): - if self.profileIndex >= self.processingHeaderObj.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.processingHeaderObj.profilesPerBlock, - self.processingHeaderObj.nHeights, - self.systemHeaderObj.nChannels) - - self.datablock = numpy.zeros((self.systemHeaderObj.nChannels, - self.processingHeaderObj.profilesPerBlock, - self.processingHeaderObj.nHeights), - dtype=numpy.dtype('complex')) - - - def writeBlock(self): - """ - Escribe el buffer en el file designado - - Affected: - self.profileIndex - self.flagIsNewFile - self.flagIsNewBlock - self.nTotalBlocks - self.blockIndex - - Return: None - """ - data = numpy.zeros( self.shapeBuffer, self.dtype ) - - 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.blockIndex += 1 - self.nTotalBlocks += 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.flagTimeBlock: - - self.datablock.fill(0) - self.profileIndex = 0 - self.setNextFile() - - if self.profileIndex == 0: - self.getBasicHeader() - - self.datablock[:,self.profileIndex,:] = self.dataOutObj.data - - self.profileIndex += 1 - - if self.hasAllDataInBuffer(): - #if self.flagIsNewFile: - self.writeNextBlock() -# self.getDataHeader() - - if self.flagNoMoreFiles: - #print 'Process finished' - return 0 - - return 1 - - def __getProcessFlags(self): - - processFlags = 0 - - dtype0 = numpy.dtype([('real',' 1: - processFlags += PROCFLAG.COHERENT_INTEGRATION - - return processFlags - - - def __getBlockSize(self): - ''' - Este metodos determina el cantidad de bytes para un bloque de datos de tipo Voltage - ''' - - dtype0 = numpy.dtype([('real',' 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,datatime): - """ - data - - datatime [seconds] - """ - if self.firstdatatime == None or self.isReady: - self.firstdatatime = datatime - - if self.timeFlag: - if self.timeOut == None: - self.timeOut = datatime + self.timeIntervalInSeconds - - if datatime < 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 = datatime + self.timeIntervalInSeconds - else: - self.isReady = False - \ No newline at end of file diff --git a/schainpy2/Processing/VoltageProcessor.py b/schainpy2/Processing/VoltageProcessor.py deleted file mode 100644 index 611e0ae..0000000 --- a/schainpy2/Processing/VoltageProcessor.py +++ /dev/null @@ -1,429 +0,0 @@ -''' - -$Author$ -$Id$ -''' - -import os -import sys -import numpy -import datetime -import time - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Data.JROData import Voltage -from IO.VoltageIO import VoltageWriter -#from Graphics.schainPlotTypes import ScopeFigure, RTIFigure - -class VoltageProcessor: - - dataInObj = None - dataOutObj = None - integratorObjIndex = None - writerObjIndex = None - integratorObjList = None - writerObjList = None - - def __init__(self): - self.integratorObjIndex = None - self.writerObjIndex = None - self.plotObjIndex = None - self.integratorObjList = [] - self.writerObjList = [] - self.plotObjList = [] - - def setup(self,dataInObj=None,dataOutObj=None): - self.dataInObj = dataInObj - - if self.dataOutObj == None: - dataOutObj = Voltage() - - self.dataOutObj = dataOutObj - - return self.dataOutObj - - def init(self): - self.integratorObjIndex = 0 - self.writerObjIndex = 0 - self.plotObjIndex = 0 - - if not(self.dataInObj.flagNoData): - self.dataOutObj.copy(self.dataInObj) - # No necesita copiar en cada init() los atributos de dataInObj - # la copia deberia hacerse por cada nuevo bloque de datos - - def addRti(self, idfigure, nframes, wintitle, driver, colormap, colorbar, showprofile): - rtiObj = RTIFigure(idfigure, nframes, wintitle, driver, colormap, colorbar, showprofile) - self.plotObjList.append(rtiObj) - - def plotRti(self, idfigure=None, - starttime=None, - endtime=None, - rangemin=None, - rangemax=None, - minvalue=None, - maxvalue=None, - wintitle='', - driver='plplot', - colormap='br_greeen', - colorbar=True, - showprofile=False, - xrangestep=None, - save=False, - gpath=None, - ratio=1, - channelList=None): - - if self.dataOutObj.flagNoData: - return 0 - - if channelList == None: - channelList = self.dataOutObj.channelList - - nframes = len(channelList) - - if len(self.plotObjList) <= self.plotObjIndex: - self.addRti(idfigure, nframes, wintitle, driver, colormap, colorbar, showprofile) - - data = self.dataOutObj.data[channelList,:] * numpy.conjugate(self.dataOutObj.data[channelList,:]) - data = 10*numpy.log10(data.real) - - currenttime = self.dataOutObj.utctime - time.timezone - - range = self.dataOutObj.heightList - - thisdatetime = datetime.datetime.fromtimestamp(self.dataOutObj.utctime) - dateTime = "%s"%(thisdatetime.strftime("%d-%b-%Y %H:%M:%S")) - date = "%s"%(thisdatetime.strftime("%d-%b-%Y")) - - figuretitle = "RTI Plot Radar Data" #+ date - - plotObj = self.plotObjList[self.plotObjIndex] - - cleardata = False - - deltax = self.dataOutObj.timeInterval - - plotObj.plotPcolor(data=data, - x=currenttime, - y=range, - channelList=channelList, - xmin=starttime, - xmax=endtime, - ymin=rangemin, - ymax=rangemax, - minvalue=minvalue, - maxvalue=maxvalue, - figuretitle=figuretitle, - xrangestep=xrangestep, - deltax=deltax, - save=save, - gpath=gpath, - ratio=ratio, - cleardata=cleardata - ) - - - self.plotObjIndex += 1 - - def addScope(self, idfigure, nframes, wintitle, driver): - if idfigure==None: - idfigure = self.plotObjIndex - - scopeObj = ScopeFigure(idfigure, nframes, wintitle, driver) - self.plotObjList.append(scopeObj) - - def plotScope(self, - idfigure=None, - minvalue=None, - maxvalue=None, - xmin=None, - xmax=None, - wintitle='', - driver='plplot', - save=False, - gpath=None, - ratio=1, - type="power"): - - if self.dataOutObj.flagNoData: - return 0 - - nframes = len(self.dataOutObj.channelList) - - if len(self.plotObjList) <= self.plotObjIndex: - self.addScope(idfigure, nframes, wintitle, driver) - - - if type=="power": - data1D = self.dataOutObj.data * numpy.conjugate(self.dataOutObj.data) - data1D = data1D.real - - if type =="iq": - data1D = self.dataOutObj.data - - thisDatetime = datetime.datetime.fromtimestamp(self.dataOutObj.utctime) - - dateTime = "%s"%(thisDatetime.strftime("%d-%b-%Y %H:%M:%S")) - date = "%s"%(thisDatetime.strftime("%d-%b-%Y")) - - figuretitle = "Scope Plot Radar Data: " + date - - plotObj = self.plotObjList[self.plotObjIndex] - - plotObj.plot1DArray(data1D=data1D, - x=self.dataOutObj.heightList, - channelList=self.dataOutObj.channelList, - xmin=xmin, - xmax=xmax, - minvalue=minvalue, - maxvalue=maxvalue, - figuretitle=figuretitle, - save=save, - gpath=gpath, - ratio=ratio) - - - self.plotObjIndex += 1 - - - def addIntegrator(self, *args): - objCohInt = CoherentIntegrator(*args) - self.integratorObjList.append(objCohInt) - - def addWriter(self, *args): - writerObj = VoltageWriter(self.dataOutObj) - writerObj.setup(*args) - self.writerObjList.append(writerObj) - - def writeData(self, wrpath, blocksPerFile, profilesPerBlock): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.writerObjList) <= self.writerObjIndex: - self.addWriter(wrpath, blocksPerFile, profilesPerBlock) - - self.writerObjList[self.writerObjIndex].putData() - - self.writerObjIndex += 1 - - def integrator(self, nCohInt=None, timeInterval=None, overlapping=False): - - if self.dataOutObj.flagNoData: - return 0 - - if len(self.integratorObjList) <= self.integratorObjIndex: - self.addIntegrator(nCohInt, timeInterval, overlapping) - - myCohIntObj = self.integratorObjList[self.integratorObjIndex] - myCohIntObj.exe(data = self.dataOutObj.data, datatime=self.dataOutObj.utctime) - -# self.dataOutObj.timeInterval *= nCohInt - self.dataOutObj.flagNoData = True - - if myCohIntObj.isReady: - self.dataOutObj.data = myCohIntObj.data - self.dataOutObj.timeInterval *= myCohIntObj.nCohInt - self.dataOutObj.nCohInt = myCohIntObj.nCohInt * self.dataInObj.nCohInt - self.dataOutObj.utctime = myCohIntObj.firstdatatime - self.dataOutObj.flagNoData = False - - def selectChannels(self, channelList): - - self.selectChannelsByIndex(channelList) - - 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.channelList = [self.dataOutObj.channelList[i] for i in channelIndexList] - self.dataOutObj.nChannels = nChannels - - return 1 - -class CoherentIntegrator: - - - __profIndex = 0 - __withOverapping = False - - __isByTime = False - __initime = None - __integrationtime = None - - __buffer = None - - isReady = False - nCohInt = None - firstdatatime = None - - def __init__(self, nCohInt=None, timeInterval=None, overlapping=False): - - """ - Set the parameters of the integration class. - - Inputs: - - nCohInt : Number of coherent integrations - timeInterval : Time of integration. If nCohInt is selected this parameter does not work - overlapping : - - """ - - self.__buffer = None - self.isReady = False - - if nCohInt == None and timeInterval == None: - raise ValueError, "nCohInt or timeInterval should be specified ..." - - if nCohInt != None: - self.nCohInt = nCohInt - self.__isByTime = False - else: - self.__integrationtime = timeInterval * 60. #if (type(timeInterval)!=integer) -> change this line - self.__isByTime = True - - if overlapping: - self.__withOverapping = True - self.__buffer = None - else: - self.__withOverapping = False - self.__buffer = 0 - - self.__profIndex = 0 - firstdatatime = None - - def putData(self, data): - - """ - Add a profile to the __buffer and increase in one the __profileIndex - - """ - if not self.__withOverapping: - self.__buffer += data - self.__profIndex += 1 - return - - #Overlapping data - nChannels, nHeis = data.shape - data = numpy.reshape(data, (1, nChannels, nHeis)) - - if self.__buffer == None: - self.__buffer = data - self.__profIndex += 1 - return - - if self.__profIndex < self.nCohInt: - self.__buffer = numpy.vstack((self.__buffer, data)) - self.__profIndex += 1 - return - - self.__buffer = numpy.roll(self.__buffer, -1, axis=0) - self.__buffer[self.nCohInt-1] = data - #self.__profIndex = self.nCohInt - return - - - def pushData(self): - """ - Return the sum of the last profiles and the profiles used in the sum. - - Affected: - - self.__profileIndex - - """ - - if not self.__withOverapping: - data = self.__buffer - nCohInt = self.__profIndex - - self.__buffer = 0 - self.__profIndex = 0 - - return data, nCohInt - - #Overlapping data - data = numpy.sum(self.__buffer, axis=0) - nCohInt = self.__profIndex - - return data, nCohInt - - def byProfiles(self, data): - - self.isReady = False - avg_data = None - - self.putData(data) - - if self.__profIndex == self.nCohInt: - avg_data, nCohInt = self.pushData() - self.isReady = True - - return avg_data - - def byTime(self, data, datatime): - - self.isReady = False - avg_data = None - - if self.__initime == None: - self.__initime = datatime - - self.putData(data) - - if (datatime - self.__initime) >= self.__integrationtime: - avg_data, nCohInt = self.pushData() - self.nCohInt = nCohInt - self.isReady = True - - return avg_data - - def exe(self, data, datatime=None): - - - if self.firstdatatime == None or self.isReady: - self.firstdatatime = datatime - - if not self.__isByTime: - avg_data = self.byProfiles(data) - else: - avg_data = self.byTime(data, datatime) - - self.data = avg_data - - - - return avg_data - - diff --git a/schainpy2/Processing/__init__.py b/schainpy2/Processing/__init__.py deleted file mode 100644 index e69de29..0000000 --- a/schainpy2/Processing/__init__.py +++ /dev/null diff --git a/schainpy2/TestSpectraHeis.py b/schainpy2/TestSpectraHeis.py deleted file mode 100644 index 55f527c..0000000 --- a/schainpy2/TestSpectraHeis.py +++ /dev/null @@ -1,131 +0,0 @@ -''' -Created on Jul 31, 2012 - -@author $Author$ -@version $Id$ -''' - -import os, sys -import time, datetime -import getopt -#import pylab as pl - -from Data.JROData import Voltage -from IO.VoltageIO import * - -from Data.JROData import SpectraHeis -from IO.SpectraIO import * - -from Processing.VoltageProcessor import * -from Processing.SpectraProcessor import * - -#from Graphics.BaseGraph_mpl import LinearPlot - -class TestHeis(): - - def __init__(self): - self.setValues() - self.createObjects() - self.testSChain() - self.i=0 - - - - def VerifyArguments(self): - arglist = '' - longarglist = ['path=','online=','N=','fpath='] - optlist,args = getopt.getopt(sys.argv[1:],arglist, longarglist) - for opt in optlist: - if opt[0] == '--path': - self.path = opt[1] - elif opt[0] == '--online': - self.online = int(opt[1]) - - elif opt[0] == '--N': - self.N = int(opt[1]) - elif opt[0] == '--fpath': - self.fpath = opt[1] -# if self.online==0: -# if opt[0] == '--starDate': -# self.StarDate = opt[1] -# elif opt[0] == '--endDate': -# self.EndDate = opt[1] -# elif opt[0] == '--startTime': -# self.StartTime = opt[1] -# elif opt[0] == '--endTime': -# self.EndTime = opt[1] -# -# elif opt[0] == '--starDate': -# self.StarDate = None -# -# elif opt[0] == '--endDate': -# self.EndDate = None -# -# elif opt[0] == '--startTime': -# self.StartTime = None -# -# elif opt[0] == '--endTime': -# self.EndTime = None - - - def setValues(self): - self.VerifyArguments() - #stardateList=self.Stardate.split() - - self.startDate = datetime.date(2012,10,1) - self.endDate = datetime.date(2012,12,30) - - self.startTime = datetime.time(0,0,0) - self.endTime = datetime.time(23,0,0) - - - - def createObjects( self ): - - self.readerObj = VoltageReader() - self.specProcObj = SpectraHeisProcessor() - self.voltObj1 = self.readerObj.setup( - path = self.path, - startDate = self.startDate, - endDate = self.endDate, - startTime = self.startTime, - endTime = self.endTime, - expLabel = '', - online = self.online, - delay=10) - - if not(self.voltObj1): - sys.exit(0) - - self.specObj1 = self.specProcObj.setup(dataInObj = self.voltObj1,nFFTPoints=self.voltObj1.nHeights) -# - def testSChain( self ): - - ini = time.time() - counter = 0 - while(True): - self.readerObj.getData() - - self.specProcObj.init() - - self.specProcObj.integrator(self.N) ## return self.dataOutObj - - self.specProcObj.writedata(self.fpath) - - self.specProcObj.plotMatScope(idfigure=1) - - if self.readerObj.flagNoMoreFiles: - break - - - - if self.readerObj.flagIsNewBlock: - print 'Block No %04d, Time: %s' %(self.readerObj.basicHeaderObj.dataBlock, - datetime.datetime.fromtimestamp(self.readerObj.basicHeaderObj.utc),) - - - -if __name__ == '__main__': - TestHeis() - - \ No newline at end of file diff --git a/schainpy2/__init__.py b/schainpy2/__init__.py deleted file mode 100644 index d3f5a12..0000000 --- a/schainpy2/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/schainpy2/testSchainExp.py b/schainpy2/testSchainExp.py deleted file mode 100644 index d6731ec..0000000 --- a/schainpy2/testSchainExp.py +++ /dev/null @@ -1,118 +0,0 @@ -''' - -$Author$ -$Id$ -''' -import os, sys -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - -from Data.JROData import Voltage -from IO.VoltageIO import * - -from Processing.VoltageProcessor import * -from Processing.SpectraProcessor import * - -class TestSChain(): - - def __init__(self): - self.setValues() - self.createObjects() - self.testSChain() - - def setValues(self): - self.path = "/home/roj-idl71/Data/RAWDATA/Meteors" - self.path = "/remote/puma/2012_06/Meteors" - - self.startDate = datetime.date(2012,1,1) - self.endDate = datetime.date(2012,12,30) - - self.startTime = datetime.time(0,0,0) - self.endTime = datetime.time(23,59,59) - - self.nFFTPoints = 64 - - self.wrpath = "/home/roj-idl71/tmp/results" - self.profilesPerBlock = 40 - self.blocksPerFile = 50 - - def createObjects(self): - - self.readerObj = VoltageReader() - self.voltProcObj = VoltageProcessor() - self.specProcObj = SpectraProcessor() - - self.voltObj1 = self.readerObj.setup( - path = self.path, - startDate = self.startDate, - endDate = self.endDate, - startTime = self.startTime, - endTime = self.endTime, - expLabel = '', - online = 0) - - self.voltObj2 = self.voltProcObj.setup(dataInObj = self.voltObj1) - self.specObj1 = self.specProcObj.setup(dataInObj = self.voltObj2, nFFTPoints = self.nFFTPoints) - - def testSChain(self): - - ini = time.time() - - while(True): - self.readerObj.getData() - - self.voltProcObj.init() - - self.voltProcObj.integrator(100, overlapping=False) -# -# self.voltProcObj.writeData(self.wrpath,self.profilesPerBlock,self.blocksPerFile) - - - self.voltProcObj.plotScope(idfigure=0, - wintitle='test plot library', - driver='plplot', - save=False, - gpath=None, - type="power") - self.voltProcObj.plotRti( - idfigure=1, - starttime=self.startTime, - endtime=self.endTime, - rangemin=0, - rangemax=1000, - minvalue=None, - maxvalue=None, - wintitle='', - driver='plplot', - colormap='br_green', - colorbar=True, - showprofile=False, - xrangestep=1, - save=False, - gpath=None) - - -# self.specProcObj.init() -# -# self.specProcObj.plotSpc(idfigure=1, -# wintitle='Spectra', -# driver='plplot', -# colormap='br_green', -# colorbar=True, -# showprofile=False, -# save=False, -# gpath=None) - - if self.readerObj.flagNoMoreFiles: - break - - if self.readerObj.flagIsNewBlock: -# print 'Block No %04d, Time: %s' %(self.readerObj.nTotalBlocks, datetime.datetime.fromtimestamp(self.readerObj.basicHeaderObj.utc),) - print 'Block No %04d, Time: %s' %(self.readerObj.nTotalBlocks, - datetime.datetime.fromtimestamp(self.readerObj.basicHeaderObj.utc + self.readerObj.basicHeaderObj.miliSecond/1000.0),) - - -if __name__ == '__main__': - TestSChain() \ No newline at end of file diff --git a/schainpy2/testSchainSpecExp.py b/schainpy2/testSchainSpecExp.py deleted file mode 100644 index f67e0db..0000000 --- a/schainpy2/testSchainSpecExp.py +++ /dev/null @@ -1,85 +0,0 @@ -''' - -$Author$ -$Id$ -''' - -import os, sys -import time, datetime - -path = os.path.split(os.getcwd())[0] -sys.path.append(path) - - -from Data.JROData import Spectra -from IO.SpectraIO import * -from Processing.SpectraProcessor import * - - - -class TestSChain: - - def __init__(self): - self.setValues() - self.createObjects() - self.testSChain() - - def setValues(self): -# self.path = "/Users/jro/Documents/RadarData/MST_ISR/MST" -## self.path = "/home/roj-idl71/Data/RAWDATA/IMAGING" -# self.path = "/Users/danielangelsuarezmunoz/Data/EW_Drifts" -# self.path = "/Users/danielangelsuarezmunoz/Data/IMAGING" - self.path = "/home/daniel/RadarData/IMAGING" - - self.startDate = datetime.date(2012,3,1) - self.endDate = datetime.date(2012,3,30) - - self.startTime = datetime.time(0,0,0) - self.endTime = datetime.time(14,1,1) - - # paramatros para Escritura de Pdata - self.wrpath = "/home/daniel/RadarData/test_wr2" - self.blocksPerFile = 5 - - - - def createObjects(self): - - self.readerObj = SpectraReader() - - self.specObj1 = self.readerObj.setup( - path = self.path, - startDate = self.startDate, - endDate = self.endDate, - startTime = self.startTime, - endTime = self.endTime, - expLabel = '', - online = 0) - - self.specObjProc = SpectraProcessor() - - self.specObj2 = self.specObjProc.setup(dataInObj = self.specObj1) - - - - def testSChain(self): - - ini = time.time() - - while(True): - self.readerObj.getData() - - self.specObjProc.init() - - self.specObjProc.writeData(self.wrpath,self.blocksPerFile) -# - if self.readerObj.flagNoMoreFiles: - break - - if self.readerObj.flagIsNewBlock: - print 'Block No %04d, Time: %s' %(self.readerObj.nTotalBlocks, - datetime.datetime.fromtimestamp(self.readerObj.basicHeaderObj.utc)) - - -if __name__ == '__main__': - TestSChain() \ No newline at end of file