@@ -0,0 +1,34 | |||||
|
1 | from schainpy.controller import Project | |||
|
2 | ||||
|
3 | desc = "A schain project" | |||
|
4 | ||||
|
5 | controller = Project() | |||
|
6 | controller.setup(id='191', name="project", description=desc) | |||
|
7 | ||||
|
8 | readUnitConf = controller.addReadUnit(datatype='VoltageReader', | |||
|
9 | path="/home/nanosat/schain", | |||
|
10 | startDate="1970/01/01", | |||
|
11 | endDate="2017/12/31", | |||
|
12 | startTime="00:00:00", | |||
|
13 | endTime="23:59:59", | |||
|
14 | online=0, | |||
|
15 | verbose=1, | |||
|
16 | walk=1, | |||
|
17 | ) | |||
|
18 | ||||
|
19 | procUnitConf1 = controller.addProcUnit(datatype='VoltageProc', inputId=readUnitConf.getId()) | |||
|
20 | ||||
|
21 | opObj11 = procUnitConf1.addOperation(name='ProfileSelector', optype='other') | |||
|
22 | opObj11.addParameter(name='profileRangeList', value='120,183', format='intlist') | |||
|
23 | ||||
|
24 | opObj11 = procUnitConf1.addOperation(name='RTIPlot', optype='other') | |||
|
25 | opObj11.addParameter(name='wintitle', value='Jicamarca Radio Observatory', format='str') | |||
|
26 | opObj11.addParameter(name='showprofile', value='0', format='int') | |||
|
27 | opObj11.addParameter(name='xmin', value='0', format='int') | |||
|
28 | opObj11.addParameter(name='xmax', value='24', format='int') | |||
|
29 | opObj11.addParameter(name='figpath', value="/home/nanosat/schain/figs", format='str') | |||
|
30 | opObj11.addParameter(name='wr_period', value='5', format='int') | |||
|
31 | opObj11.addParameter(name='exp_code', value='22', format='int') | |||
|
32 | ||||
|
33 | ||||
|
34 | controller.start() |
@@ -0,0 +1,1 | |||||
|
1 | <Project description="A schain project" id="191" name="project"><ReadUnit datatype="Voltage" id="1911" inputId="0" name="VoltageReader"><Operation id="19111" name="run" priority="1" type="self"><Parameter format="str" id="191111" name="datatype" value="VoltageReader" /><Parameter format="str" id="191112" name="path" value="/home/nanosat/schain" /><Parameter format="date" id="191113" name="startDate" value="1970/01/01" /><Parameter format="date" id="191114" name="endDate" value="2017/12/31" /><Parameter format="time" id="191115" name="startTime" value="00:00:00" /><Parameter format="time" id="191116" name="endTime" value="23:59:59" /><Parameter format="int" id="191118" name="walk" value="1" /><Parameter format="int" id="191119" name="verbose" value="1" /><Parameter format="int" id="191120" name="online" value="0" /></Operation></ReadUnit><ProcUnit datatype="Voltage" id="1912" inputId="1911" name="VoltageProc"><Operation id="19121" name="run" priority="1" type="self" /><Operation id="19122" name="ProfileSelector" priority="2" type="other"><Parameter format="intlist" id="191221" name="profileRangeList" value="120,183" /></Operation><Operation id="19123" name="RTIPlot" priority="3" type="plotter"><Parameter format="str" id="191231" name="wintitle" value="Jicamarca Radio Observatory" /><Parameter format="int" id="191232" name="showprofile" value="0" /><Parameter format="int" id="191233" name="xmin" value="0" /><Parameter format="int" id="191234" name="xmax" value="24" /><Parameter format="str" id="191235" name="figpath" value="/home/nanosat/schain/figs" /><Parameter format="int" id="191236" name="wr_period" value="5" /><Parameter format="int" id="191237" name="exp_code" value="22" /></Operation></ProcUnit></Project> No newline at end of file |
@@ -0,0 +1,9 | |||||
|
1 | # schaing | |||
|
2 | ||||
|
3 | Command Line Interface for SIGNAL CHAIN - jro | |||
|
4 | ||||
|
5 | # Usage | |||
|
6 | ||||
|
7 | To use it: | |||
|
8 | ||||
|
9 | $ schain-cli --help |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
@@ -0,0 +1,34 | |||||
|
1 | from schainpy.controller import Project | |||
|
2 | ||||
|
3 | desc = "asdasddsad" | |||
|
4 | ||||
|
5 | controller = Project() | |||
|
6 | controller.setup(id='191', name="asdasd", description=desc) | |||
|
7 | ||||
|
8 | readUnitConf = controller.addReadUnit(datatype='VoltageReader', | |||
|
9 | path="/home/nanosat/schain/schain-cli", | |||
|
10 | startDate="1970/01/01", | |||
|
11 | endDate="2017/12/31", | |||
|
12 | startTime="00:00:00", | |||
|
13 | endTime="23:59:59", | |||
|
14 | online=0, | |||
|
15 | verbose=1, | |||
|
16 | walk=1, | |||
|
17 | ) | |||
|
18 | ||||
|
19 | procUnitConf1 = controller.addProcUnit(datatype='VoltageProc', inputId=readUnitConf.getId()) | |||
|
20 | ||||
|
21 | opObj11 = procUnitConf1.addOperation(name='ProfileSelector', optype='other') | |||
|
22 | opObj11.addParameter(name='profileRangeList', value='120,183', format='intlist') | |||
|
23 | ||||
|
24 | opObj11 = procUnitConf1.addOperation(name='RTIPlot', optype='other') | |||
|
25 | opObj11.addParameter(name='wintitle', value='Jicamarca Radio Observatory', format='str') | |||
|
26 | opObj11.addParameter(name='showprofile', value='0', format='int') | |||
|
27 | opObj11.addParameter(name='xmin', value='0', format='int') | |||
|
28 | opObj11.addParameter(name='xmax', value='24', format='int') | |||
|
29 | opObj11.addParameter(name='figpath', value="/home/nanosat/schain/schain-cli/figs", format='str') | |||
|
30 | opObj11.addParameter(name='wr_period', value='5', format='int') | |||
|
31 | opObj11.addParameter(name='exp_code', value='22', format='int') | |||
|
32 | ||||
|
33 | ||||
|
34 | controller.start() |
@@ -0,0 +1,188 | |||||
|
1 | import click | |||
|
2 | import schainpy | |||
|
3 | import subprocess | |||
|
4 | import os | |||
|
5 | import sys | |||
|
6 | import glob | |||
|
7 | save_stdout = sys.stdout | |||
|
8 | sys.stdout = open('trash', 'w') | |||
|
9 | from multiprocessing import cpu_count | |||
|
10 | from schaincli import templates | |||
|
11 | from schainpy import controller_api | |||
|
12 | from schainpy.model import Operation, ProcessingUnit | |||
|
13 | from schainpy.utils import log | |||
|
14 | from importlib import import_module | |||
|
15 | from pydoc import locate | |||
|
16 | from fuzzywuzzy import process | |||
|
17 | sys.stdout = save_stdout | |||
|
18 | ||||
|
19 | ||||
|
20 | def print_version(ctx, param, value): | |||
|
21 | if not value or ctx.resilient_parsing: | |||
|
22 | return | |||
|
23 | click.echo(schainpy.__version__) | |||
|
24 | ctx.exit() | |||
|
25 | ||||
|
26 | ||||
|
27 | cliLogger = log.makelogger('schain cli') | |||
|
28 | PREFIX = 'experiment' | |||
|
29 | ||||
|
30 | ||||
|
31 | @click.command() | |||
|
32 | @click.option('--version', '-v', is_flag=True, callback=print_version, help='SChain version', type=str) | |||
|
33 | @click.option('--xml', '-x', default=None, help='run an XML file', type=click.Path(exists=True, resolve_path=True)) | |||
|
34 | @click.argument('command', default='run', required=True) | |||
|
35 | @click.argument('nextcommand', default=None, required=False, type=str) | |||
|
36 | def main(command, nextcommand, version, xml): | |||
|
37 | """COMMAND LINE INTERFACE FOR SIGNAL CHAIN - JICAMARCA RADIO OBSERVATORY \n | |||
|
38 | Available commands.\n | |||
|
39 | --xml: runs a schain XML generated file\n | |||
|
40 | run: runs any python script starting 'experiment_'\n | |||
|
41 | generate: generates a template schain script\n | |||
|
42 | search: return avilable operations, procs or arguments of the give operation/proc\n""" | |||
|
43 | if xml is not None: | |||
|
44 | runFromXML(xml) | |||
|
45 | elif command == 'generate': | |||
|
46 | generate() | |||
|
47 | elif command == 'test': | |||
|
48 | test() | |||
|
49 | elif command == 'run': | |||
|
50 | runschain(nextcommand) | |||
|
51 | elif command == 'search': | |||
|
52 | search(nextcommand) | |||
|
53 | else: | |||
|
54 | log.error('Command {} is not defined'.format(command)) | |||
|
55 | ||||
|
56 | def check_module(possible, instance): | |||
|
57 | def check(x): | |||
|
58 | try: | |||
|
59 | instancia = locate('schainpy.model.{}'.format(x)) | |||
|
60 | return isinstance(instancia(), instance) | |||
|
61 | except Exception as e: | |||
|
62 | return False | |||
|
63 | clean = clean_modules(possible) | |||
|
64 | return [x for x in clean if check(x)] | |||
|
65 | ||||
|
66 | ||||
|
67 | def clean_modules(module): | |||
|
68 | noEndsUnder = [x for x in module if not x.endswith('__')] | |||
|
69 | noStartUnder = [x for x in noEndsUnder if not x.startswith('__')] | |||
|
70 | noFullUpper = [x for x in noStartUnder if not x.isupper()] | |||
|
71 | return noFullUpper | |||
|
72 | ||||
|
73 | ||||
|
74 | def search(nextcommand): | |||
|
75 | if nextcommand is None: | |||
|
76 | log.error('There is no Operation/ProcessingUnit to search') | |||
|
77 | elif nextcommand == 'procs': | |||
|
78 | module = dir(import_module('schainpy.model')) | |||
|
79 | procs = check_module(module, ProcessingUnit) | |||
|
80 | try: | |||
|
81 | procs.remove('ProcessingUnit') | |||
|
82 | except Exception as e: | |||
|
83 | pass | |||
|
84 | log.success('Current ProcessingUnits are:\n\033[1m{}\033[0m'.format('\n'.join(procs))) | |||
|
85 | ||||
|
86 | elif nextcommand == 'operations': | |||
|
87 | module = dir(import_module('schainpy.model')) | |||
|
88 | noProcs = [x for x in module if not x.endswith('Proc')] | |||
|
89 | operations = check_module(noProcs, Operation) | |||
|
90 | try: | |||
|
91 | operations.remove('Operation') | |||
|
92 | except Exception as e: | |||
|
93 | pass | |||
|
94 | log.success('Current Operations are:\n\033[1m{}\033[0m'.format('\n'.join(operations))) | |||
|
95 | else: | |||
|
96 | try: | |||
|
97 | module = locate('schainpy.model.{}'.format(nextcommand)) | |||
|
98 | args = module().getAllowedArgs() | |||
|
99 | log.warning('Use this feature with caution. It may not return all the allowed arguments') | |||
|
100 | try: | |||
|
101 | args.remove('self') | |||
|
102 | except Exception as e: | |||
|
103 | pass | |||
|
104 | try: | |||
|
105 | args.remove('dataOut') | |||
|
106 | except Exception as e: | |||
|
107 | pass | |||
|
108 | if len(args) == 0: | |||
|
109 | log.success('{} has no arguments'.format(nextcommand)) | |||
|
110 | else: | |||
|
111 | log.success('Showing arguments of {} are:\n\033[1m{}\033[0m'.format(nextcommand, '\n'.join(args))) | |||
|
112 | except Exception as e: | |||
|
113 | log.error('Module {} does not exists'.format(nextcommand)) | |||
|
114 | allModules = dir(import_module('schainpy.model')) | |||
|
115 | module = check_module(allModules, Operation) | |||
|
116 | module.extend(check_module(allModules, ProcessingUnit)) | |||
|
117 | similar = process.extractOne(nextcommand, module)[0] | |||
|
118 | log.success('Searching {} instead'.format(similar)) | |||
|
119 | search(similar) | |||
|
120 | ||||
|
121 | ||||
|
122 | def runschain(nextcommand): | |||
|
123 | if nextcommand is None: | |||
|
124 | currentfiles = glob.glob('./{}_*.py'.format(PREFIX)) | |||
|
125 | numberfiles = len(currentfiles) | |||
|
126 | if numberfiles > 1: | |||
|
127 | log.error('There is more than one file to run') | |||
|
128 | elif numberfiles == 1: | |||
|
129 | subprocess.call(['python ' + currentfiles[0]], shell=True) | |||
|
130 | else: | |||
|
131 | log.error('There is no file to run') | |||
|
132 | else: | |||
|
133 | try: | |||
|
134 | subprocess.call(['python ' + nextcommand], shell=True) | |||
|
135 | except Exception as e: | |||
|
136 | log.error("I cannot run the file. Does it exists?") | |||
|
137 | ||||
|
138 | ||||
|
139 | def basicInputs(): | |||
|
140 | inputs = {} | |||
|
141 | inputs['desc'] = click.prompt('Enter a description', default="A schain project", type=str) | |||
|
142 | inputs['name'] = click.prompt('Name of the project', default="project", type=str) | |||
|
143 | inputs['path'] = click.prompt('Data path', default=os.getcwd(), type=click.Path(exists=True, resolve_path=True)) | |||
|
144 | inputs['startDate'] = click.prompt('Start date', default='1970/01/01', type=str) | |||
|
145 | inputs['endDate'] = click.prompt('End date', default='2017/12/31', type=str) | |||
|
146 | inputs['startHour'] = click.prompt('Start hour', default='00:00:00', type=str) | |||
|
147 | inputs['endHour'] = click.prompt('End hour', default='23:59:59', type=str) | |||
|
148 | inputs['figpath'] = inputs['path'] + '/figs' | |||
|
149 | return inputs | |||
|
150 | ||||
|
151 | ||||
|
152 | def generate(): | |||
|
153 | inputs = basicInputs() | |||
|
154 | inputs['multiprocess'] = click.confirm('Is this a multiprocess script?') | |||
|
155 | if inputs['multiprocess']: | |||
|
156 | inputs['nProcess'] = click.prompt('How many process?', default=cpu_count(), type=int) | |||
|
157 | current = templates.multiprocess.format(**inputs) | |||
|
158 | else: | |||
|
159 | current = templates.basic.format(**inputs) | |||
|
160 | scriptname = '{}_{}.py'.format(PREFIX, inputs['name']) | |||
|
161 | script = open(scriptname, 'w') | |||
|
162 | try: | |||
|
163 | script.write(current) | |||
|
164 | log.success('Script {} generated'.format(scriptname)) | |||
|
165 | except Exception as e: | |||
|
166 | log.error('I cannot create the file. Do you have writing permissions?') | |||
|
167 | ||||
|
168 | ||||
|
169 | def test(): | |||
|
170 | log.warning('testing') | |||
|
171 | ||||
|
172 | ||||
|
173 | def runFromXML(filename): | |||
|
174 | controller = controller_api.ControllerThread() | |||
|
175 | if not controller.readXml(filename): | |||
|
176 | return | |||
|
177 | ||||
|
178 | plotterObj = controller.useExternalPlotter() | |||
|
179 | ||||
|
180 | controller.start() | |||
|
181 | plotterObj.start() | |||
|
182 | ||||
|
183 | cliLogger("Finishing all processes") | |||
|
184 | ||||
|
185 | controller.join(5) | |||
|
186 | ||||
|
187 | cliLogger("End of script") | |||
|
188 | return |
@@ -0,0 +1,75 | |||||
|
1 | basic = '''from schainpy.controller import Project | |||
|
2 | ||||
|
3 | desc = "{desc}" | |||
|
4 | ||||
|
5 | controller = Project() | |||
|
6 | controller.setup(id='191', name="{name}", description=desc) | |||
|
7 | ||||
|
8 | readUnitConf = controller.addReadUnit(datatype='VoltageReader', | |||
|
9 | path="{path}", | |||
|
10 | startDate="{startDate}", | |||
|
11 | endDate="{endDate}", | |||
|
12 | startTime="{startHour}", | |||
|
13 | endTime="{endHour}", | |||
|
14 | online=0, | |||
|
15 | verbose=1, | |||
|
16 | walk=1, | |||
|
17 | ) | |||
|
18 | ||||
|
19 | procUnitConf1 = controller.addProcUnit(datatype='VoltageProc', inputId=readUnitConf.getId()) | |||
|
20 | ||||
|
21 | opObj11 = procUnitConf1.addOperation(name='ProfileSelector', optype='other') | |||
|
22 | opObj11.addParameter(name='profileRangeList', value='120,183', format='intlist') | |||
|
23 | ||||
|
24 | opObj11 = procUnitConf1.addOperation(name='RTIPlot', optype='other') | |||
|
25 | opObj11.addParameter(name='wintitle', value='Jicamarca Radio Observatory', format='str') | |||
|
26 | opObj11.addParameter(name='showprofile', value='0', format='int') | |||
|
27 | opObj11.addParameter(name='xmin', value='0', format='int') | |||
|
28 | opObj11.addParameter(name='xmax', value='24', format='int') | |||
|
29 | opObj11.addParameter(name='figpath', value="{figpath}", format='str') | |||
|
30 | opObj11.addParameter(name='wr_period', value='5', format='int') | |||
|
31 | opObj11.addParameter(name='exp_code', value='22', format='int') | |||
|
32 | ||||
|
33 | ||||
|
34 | controller.start() | |||
|
35 | ''' | |||
|
36 | ||||
|
37 | multiprocess = '''from schainpy.controller import Project, multiSchain | |||
|
38 | ||||
|
39 | desc = "{desc}" | |||
|
40 | ||||
|
41 | def fiber(cursor, skip, q, day): | |||
|
42 | controller = Project() | |||
|
43 | controller.setup(id='191', name="{name}", description=desc) | |||
|
44 | ||||
|
45 | readUnitConf = controller.addReadUnit(datatype='SpectraReader', | |||
|
46 | path="{path}", | |||
|
47 | startDate=day, | |||
|
48 | endDate=day, | |||
|
49 | startTime="{startHour}", | |||
|
50 | endTime="{endHour}", | |||
|
51 | online=0, | |||
|
52 | queue=q, | |||
|
53 | cursor=cursor, | |||
|
54 | skip=skip, | |||
|
55 | verbose=1, | |||
|
56 | walk=1, | |||
|
57 | ) | |||
|
58 | ||||
|
59 | procUnitConf1 = controller.addProcUnit(datatype='Spectra', inputId=readUnitConf.getId()) | |||
|
60 | ||||
|
61 | procUnitConf2 = controller.addProcUnit(datatype='ParametersProc', inputId=readUnitConf.getId()) | |||
|
62 | opObj11 = procUnitConf2.addOperation(name='SpectralMoments', optype='other') | |||
|
63 | ||||
|
64 | opObj12 = procUnitConf2.addOperation(name='PublishData', optype='other') | |||
|
65 | opObj12.addParameter(name='zeromq', value=1, format='int') | |||
|
66 | opObj12.addParameter(name='verbose', value=0, format='bool') | |||
|
67 | ||||
|
68 | controller.start() | |||
|
69 | ||||
|
70 | ||||
|
71 | if __name__ == '__main__': | |||
|
72 | multiSchain(fiber, nProcess={nProcess}, startDate="{startDate}", endDate="{endDate}") | |||
|
73 | ||||
|
74 | ||||
|
75 | ''' |
@@ -0,0 +1,1 | |||||
|
1 |
@@ -0,0 +1,29 | |||||
|
1 | import pytest | |||
|
2 | from click.testing import CliRunner | |||
|
3 | from schaincli import cli | |||
|
4 | ||||
|
5 | ||||
|
6 | @pytest.fixture | |||
|
7 | def runner(): | |||
|
8 | return CliRunner() | |||
|
9 | ||||
|
10 | ||||
|
11 | def test_cli(runner): | |||
|
12 | result = runner.invoke(cli.main) | |||
|
13 | assert result.exit_code == 0 | |||
|
14 | assert not result.exception | |||
|
15 | assert result.output.strip() == 'Hello, world.' | |||
|
16 | ||||
|
17 | ||||
|
18 | def test_cli_with_option(runner): | |||
|
19 | result = runner.invoke(cli.main, ['--as-cowboy']) | |||
|
20 | assert not result.exception | |||
|
21 | assert result.exit_code == 0 | |||
|
22 | assert result.output.strip() == 'Howdy, world.' | |||
|
23 | ||||
|
24 | ||||
|
25 | def test_cli_with_arg(runner): | |||
|
26 | result = runner.invoke(cli.main, ['Jicamarca']) | |||
|
27 | assert result.exit_code == 0 | |||
|
28 | assert not result.exception | |||
|
29 | assert result.output.strip() == 'Hello, Jicamarca.' |
@@ -0,0 +1,34 | |||||
|
1 | from schainpy.controller import Project | |||
|
2 | ||||
|
3 | desc = "A schain project" | |||
|
4 | ||||
|
5 | controller = Project() | |||
|
6 | controller.setup(id='191', name="project", description=desc) | |||
|
7 | ||||
|
8 | readUnitConf = controller.addReadUnit(datatype='VoltageReader', | |||
|
9 | path="/home/nanosat/schain/schainpy", | |||
|
10 | startDate="1970/01/01", | |||
|
11 | endDate="2017/12/31", | |||
|
12 | startTime="00:00:00", | |||
|
13 | endTime="23:59:59", | |||
|
14 | online=0, | |||
|
15 | verbose=1, | |||
|
16 | walk=1, | |||
|
17 | ) | |||
|
18 | ||||
|
19 | procUnitConf1 = controller.addProcUnit(datatype='VoltageProc', inputId=readUnitConf.getId()) | |||
|
20 | ||||
|
21 | opObj11 = procUnitConf1.addOperation(name='ProfileSelector', optype='other') | |||
|
22 | opObj11.addParameter(name='profileRangeList', value='120,183', format='intlist') | |||
|
23 | ||||
|
24 | opObj11 = procUnitConf1.addOperation(name='RTIPlot', optype='other') | |||
|
25 | opObj11.addParameter(name='wintitle', value='Jicamarca Radio Observatory', format='str') | |||
|
26 | opObj11.addParameter(name='showprofile', value='0', format='int') | |||
|
27 | opObj11.addParameter(name='xmin', value='0', format='int') | |||
|
28 | opObj11.addParameter(name='xmax', value='24', format='int') | |||
|
29 | opObj11.addParameter(name='figpath', value="/home/nanosat/schain/schainpy/figs", format='str') | |||
|
30 | opObj11.addParameter(name='wr_period', value='5', format='int') | |||
|
31 | opObj11.addParameter(name='exp_code', value='22', format='int') | |||
|
32 | ||||
|
33 | ||||
|
34 | controller.start() |
@@ -0,0 +1,33 | |||||
|
1 | from schainpy.controller import Project | |||
|
2 | ||||
|
3 | desc = "A schain project" | |||
|
4 | ||||
|
5 | controller = Project() | |||
|
6 | controller.setup(id='191', name="project", description=desc) | |||
|
7 | ||||
|
8 | readUnitConf = controller.addReadUnit(datatype='VoltageReader', | |||
|
9 | path="/home/nanosat/schain/schainpy/scripts", | |||
|
10 | startDate="1970/01/01", | |||
|
11 | endDate="2017/12/31", | |||
|
12 | startTime="00:00:00", | |||
|
13 | endTime="23:59:59", | |||
|
14 | online=0, | |||
|
15 | walk=1, | |||
|
16 | ) | |||
|
17 | ||||
|
18 | procUnitConf1 = controller.addProcUnit(datatype='VoltageProc', inputId=readUnitConf.getId()) | |||
|
19 | ||||
|
20 | opObj11 = procUnitConf1.addOperation(name='ProfileSelector', optype='other') | |||
|
21 | opObj11.addParameter(name='profileRangeList', value='120,183', format='intlist') | |||
|
22 | ||||
|
23 | opObj11 = procUnitConf1.addOperation(name='RTIPlot', optype='other') | |||
|
24 | opObj11.addParameter(name='wintitle', value='Jicamarca Radio Observatory', format='str') | |||
|
25 | opObj11.addParameter(name='showprofile', value='0', format='int') | |||
|
26 | opObj11.addParameter(name='xmin', value='0', format='int') | |||
|
27 | opObj11.addParameter(name='xmax', value='24', format='int') | |||
|
28 | opObj11.addParameter(name='figpath', value="/home/nanosat/schain/schainpy/scripts/figs", format='str') | |||
|
29 | opObj11.addParameter(name='wr_period', value='5', format='int') | |||
|
30 | opObj11.addParameter(name='exp_code', value='22', format='int') | |||
|
31 | ||||
|
32 | ||||
|
33 | controller.start() |
1 | NO CONTENT: new file 100644 |
|
NO CONTENT: new file 100644 |
@@ -0,0 +1,45 | |||||
|
1 | """. | |||
|
2 | SCHAINPY - LOG | |||
|
3 | Simple helper for log standarization | |||
|
4 | Usage: | |||
|
5 | from schainpy.utils import log | |||
|
6 | log.error('A kitten died beacuse of you') | |||
|
7 | log.warning('You are doing it wrong but what the heck, I'll allow it) | |||
|
8 | log.succes('YOU ROCK!') | |||
|
9 | To create your own logger inside your class do it like this: | |||
|
10 | from schainpy.utils import log | |||
|
11 | awesomeLogger = log.makelogger("never gonna", bg="red", fg="white") | |||
|
12 | awesomeLogger('give you up') | |||
|
13 | which will look like this: | |||
|
14 | [NEVER GONNA] - give you up | |||
|
15 | with color red as background and white as foreground. | |||
|
16 | """ | |||
|
17 | ||||
|
18 | import click | |||
|
19 | ||||
|
20 | ||||
|
21 | def warning(message): | |||
|
22 | click.echo(click.style('[WARNING] - ' + message, fg='yellow')) | |||
|
23 | pass | |||
|
24 | ||||
|
25 | ||||
|
26 | def error(message): | |||
|
27 | click.echo(click.style('[ERROR] - ' + message, fg='red')) | |||
|
28 | pass | |||
|
29 | ||||
|
30 | ||||
|
31 | def success(message): | |||
|
32 | click.echo(click.style(message, fg='green')) | |||
|
33 | pass | |||
|
34 | ||||
|
35 | ||||
|
36 | def log(message): | |||
|
37 | click.echo('[LOG] - ' + message) | |||
|
38 | pass | |||
|
39 | ||||
|
40 | ||||
|
41 | def makelogger(topic, bg='reset', fg='reset'): | |||
|
42 | def func(message): | |||
|
43 | click.echo(click.style('[{}] - '.format(topic.upper()) + message, | |||
|
44 | bg=bg, fg=fg)) | |||
|
45 | return func |
@@ -0,0 +1,1 | |||||
|
1 | You should install "digital_rf_hdf5" module if you want to read USRP data |
@@ -1,1321 +1,1321 | |||||
1 | ''' |
|
1 | ''' | |
2 | Created on September , 2012 |
|
2 | Created on September , 2012 | |
3 | @author: |
|
3 | @author: | |
4 | ''' |
|
4 | ''' | |
5 |
|
5 | |||
6 | import sys |
|
6 | import sys | |
7 | import ast |
|
7 | import ast | |
8 | import datetime |
|
8 | import datetime | |
9 | import traceback |
|
9 | import traceback | |
10 | import math |
|
10 | import math | |
11 | import time |
|
11 | import time | |
12 | from multiprocessing import Process, Queue, cpu_count |
|
12 | from multiprocessing import Process, Queue, cpu_count | |
13 |
|
13 | |||
14 | import schainpy |
|
14 | import schainpy | |
15 | import schainpy.admin |
|
15 | import schainpy.admin | |
16 |
|
16 | |||
17 | from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring |
|
17 | from xml.etree.ElementTree import ElementTree, Element, SubElement, tostring | |
18 | from xml.dom import minidom |
|
18 | from xml.dom import minidom | |
19 |
|
19 | |||
20 | from schainpy.model import * |
|
20 | from schainpy.model import * | |
21 | from time import sleep |
|
21 | from time import sleep | |
22 |
|
22 | |||
23 | def prettify(elem): |
|
23 | def prettify(elem): | |
24 | """Return a pretty-printed XML string for the Element. |
|
24 | """Return a pretty-printed XML string for the Element. | |
25 | """ |
|
25 | """ | |
26 | rough_string = tostring(elem, 'utf-8') |
|
26 | rough_string = tostring(elem, 'utf-8') | |
27 | reparsed = minidom.parseString(rough_string) |
|
27 | reparsed = minidom.parseString(rough_string) | |
28 | return reparsed.toprettyxml(indent=" ") |
|
28 | return reparsed.toprettyxml(indent=" ") | |
29 |
|
29 | |||
30 | def multiSchain(child, nProcess=cpu_count(), startDate=None, endDate=None, by_day=False): |
|
30 | def multiSchain(child, nProcess=cpu_count(), startDate=None, endDate=None, by_day=False): | |
31 | skip = 0 |
|
31 | skip = 0 | |
32 | cursor = 0 |
|
32 | cursor = 0 | |
33 | nFiles = None |
|
33 | nFiles = None | |
34 | processes = [] |
|
34 | processes = [] | |
35 | dt1 = datetime.datetime.strptime(startDate, '%Y/%m/%d') |
|
35 | dt1 = datetime.datetime.strptime(startDate, '%Y/%m/%d') | |
36 | dt2 = datetime.datetime.strptime(endDate, '%Y/%m/%d') |
|
36 | dt2 = datetime.datetime.strptime(endDate, '%Y/%m/%d') | |
37 | days = (dt2 - dt1).days |
|
37 | days = (dt2 - dt1).days | |
38 |
|
38 | |||
39 | for day in range(days+1): |
|
39 | for day in range(days+1): | |
40 | skip = 0 |
|
40 | skip = 0 | |
41 | cursor = 0 |
|
41 | cursor = 0 | |
42 | q = Queue() |
|
42 | q = Queue() | |
43 | processes = [] |
|
43 | processes = [] | |
44 | dt = (dt1 + datetime.timedelta(day)).strftime('%Y/%m/%d') |
|
44 | dt = (dt1 + datetime.timedelta(day)).strftime('%Y/%m/%d') | |
45 | firstProcess = Process(target=child, args=(cursor, skip, q, dt)) |
|
45 | firstProcess = Process(target=child, args=(cursor, skip, q, dt)) | |
46 | firstProcess.start() |
|
46 | firstProcess.start() | |
47 | if by_day: |
|
47 | if by_day: | |
48 | continue |
|
48 | continue | |
49 | nFiles = q.get() |
|
49 | nFiles = q.get() | |
50 | firstProcess.terminate() |
|
50 | firstProcess.terminate() | |
51 | skip = int(math.ceil(nFiles/nProcess)) |
|
51 | skip = int(math.ceil(nFiles/nProcess)) | |
52 | while True: |
|
52 | while True: | |
53 | processes.append(Process(target=child, args=(cursor, skip, q, dt))) |
|
53 | processes.append(Process(target=child, args=(cursor, skip, q, dt))) | |
54 | processes[cursor].start() |
|
54 | processes[cursor].start() | |
55 | if nFiles < cursor*skip: |
|
55 | if nFiles < cursor*skip: | |
56 | break |
|
56 | break | |
57 | cursor += 1 |
|
57 | cursor += 1 | |
58 |
|
58 | |||
59 | def beforeExit(exctype, value, trace): |
|
59 | def beforeExit(exctype, value, trace): | |
60 | for process in processes: |
|
60 | for process in processes: | |
61 | process.terminate() |
|
61 | process.terminate() | |
62 | process.join() |
|
62 | process.join() | |
63 | print traceback.print_tb(trace) |
|
63 | print traceback.print_tb(trace) | |
64 |
|
64 | |||
65 | sys.excepthook = beforeExit |
|
65 | sys.excepthook = beforeExit | |
66 |
|
66 | |||
67 | for process in processes: |
|
67 | for process in processes: | |
68 | process.join() |
|
68 | process.join() | |
69 | process.terminate() |
|
69 | process.terminate() | |
70 | time.sleep(3) |
|
70 | time.sleep(3) | |
71 |
|
71 | |||
72 | class ParameterConf(): |
|
72 | class ParameterConf(): | |
73 |
|
73 | |||
74 | id = None |
|
74 | id = None | |
75 | name = None |
|
75 | name = None | |
76 | value = None |
|
76 | value = None | |
77 | format = None |
|
77 | format = None | |
78 |
|
78 | |||
79 | __formated_value = None |
|
79 | __formated_value = None | |
80 |
|
80 | |||
81 | ELEMENTNAME = 'Parameter' |
|
81 | ELEMENTNAME = 'Parameter' | |
82 |
|
82 | |||
83 | def __init__(self): |
|
83 | def __init__(self): | |
84 |
|
84 | |||
85 | self.format = 'str' |
|
85 | self.format = 'str' | |
86 |
|
86 | |||
87 | def getElementName(self): |
|
87 | def getElementName(self): | |
88 |
|
88 | |||
89 | return self.ELEMENTNAME |
|
89 | return self.ELEMENTNAME | |
90 |
|
90 | |||
91 | def getValue(self): |
|
91 | def getValue(self): | |
92 |
|
92 | |||
93 | value = self.value |
|
93 | value = self.value | |
94 | format = self.format |
|
94 | format = self.format | |
95 |
|
95 | |||
96 | if self.__formated_value != None: |
|
96 | if self.__formated_value != None: | |
97 |
|
97 | |||
98 | return self.__formated_value |
|
98 | return self.__formated_value | |
99 |
|
99 | |||
100 | if format == 'obj': |
|
100 | if format == 'obj': | |
101 | return value |
|
101 | return value | |
102 |
|
102 | |||
103 | if format == 'str': |
|
103 | if format == 'str': | |
104 | self.__formated_value = str(value) |
|
104 | self.__formated_value = str(value) | |
105 | return self.__formated_value |
|
105 | return self.__formated_value | |
106 |
|
106 | |||
107 | if value == '': |
|
107 | if value == '': | |
108 | raise ValueError, "%s: This parameter value is empty" %self.name |
|
108 | raise ValueError, "%s: This parameter value is empty" %self.name | |
109 |
|
109 | |||
110 | if format == 'list': |
|
110 | if format == 'list': | |
111 | strList = value.split(',') |
|
111 | strList = value.split(',') | |
112 |
|
112 | |||
113 | self.__formated_value = strList |
|
113 | self.__formated_value = strList | |
114 |
|
114 | |||
115 | return self.__formated_value |
|
115 | return self.__formated_value | |
116 |
|
116 | |||
117 | if format == 'intlist': |
|
117 | if format == 'intlist': | |
118 | """ |
|
118 | """ | |
119 | Example: |
|
119 | Example: | |
120 | value = (0,1,2) |
|
120 | value = (0,1,2) | |
121 | """ |
|
121 | """ | |
122 |
|
122 | |||
123 | new_value = ast.literal_eval(value) |
|
123 | new_value = ast.literal_eval(value) | |
124 |
|
124 | |||
125 | if type(new_value) not in (tuple, list): |
|
125 | if type(new_value) not in (tuple, list): | |
126 | new_value = [int(new_value)] |
|
126 | new_value = [int(new_value)] | |
127 |
|
127 | |||
128 | self.__formated_value = new_value |
|
128 | self.__formated_value = new_value | |
129 |
|
129 | |||
130 | return self.__formated_value |
|
130 | return self.__formated_value | |
131 |
|
131 | |||
132 | if format == 'floatlist': |
|
132 | if format == 'floatlist': | |
133 | """ |
|
133 | """ | |
134 | Example: |
|
134 | Example: | |
135 | value = (0.5, 1.4, 2.7) |
|
135 | value = (0.5, 1.4, 2.7) | |
136 | """ |
|
136 | """ | |
137 |
|
137 | |||
138 | new_value = ast.literal_eval(value) |
|
138 | new_value = ast.literal_eval(value) | |
139 |
|
139 | |||
140 | if type(new_value) not in (tuple, list): |
|
140 | if type(new_value) not in (tuple, list): | |
141 | new_value = [float(new_value)] |
|
141 | new_value = [float(new_value)] | |
142 |
|
142 | |||
143 | self.__formated_value = new_value |
|
143 | self.__formated_value = new_value | |
144 |
|
144 | |||
145 | return self.__formated_value |
|
145 | return self.__formated_value | |
146 |
|
146 | |||
147 | if format == 'date': |
|
147 | if format == 'date': | |
148 | strList = value.split('/') |
|
148 | strList = value.split('/') | |
149 | intList = [int(x) for x in strList] |
|
149 | intList = [int(x) for x in strList] | |
150 | date = datetime.date(intList[0], intList[1], intList[2]) |
|
150 | date = datetime.date(intList[0], intList[1], intList[2]) | |
151 |
|
151 | |||
152 | self.__formated_value = date |
|
152 | self.__formated_value = date | |
153 |
|
153 | |||
154 | return self.__formated_value |
|
154 | return self.__formated_value | |
155 |
|
155 | |||
156 | if format == 'time': |
|
156 | if format == 'time': | |
157 | strList = value.split(':') |
|
157 | strList = value.split(':') | |
158 | intList = [int(x) for x in strList] |
|
158 | intList = [int(x) for x in strList] | |
159 | time = datetime.time(intList[0], intList[1], intList[2]) |
|
159 | time = datetime.time(intList[0], intList[1], intList[2]) | |
160 |
|
160 | |||
161 | self.__formated_value = time |
|
161 | self.__formated_value = time | |
162 |
|
162 | |||
163 | return self.__formated_value |
|
163 | return self.__formated_value | |
164 |
|
164 | |||
165 | if format == 'pairslist': |
|
165 | if format == 'pairslist': | |
166 | """ |
|
166 | """ | |
167 | Example: |
|
167 | Example: | |
168 | value = (0,1),(1,2) |
|
168 | value = (0,1),(1,2) | |
169 | """ |
|
169 | """ | |
170 |
|
170 | |||
171 | new_value = ast.literal_eval(value) |
|
171 | new_value = ast.literal_eval(value) | |
172 |
|
172 | |||
173 | if type(new_value) not in (tuple, list): |
|
173 | if type(new_value) not in (tuple, list): | |
174 | raise ValueError, "%s has to be a tuple or list of pairs" %value |
|
174 | raise ValueError, "%s has to be a tuple or list of pairs" %value | |
175 |
|
175 | |||
176 | if type(new_value[0]) not in (tuple, list): |
|
176 | if type(new_value[0]) not in (tuple, list): | |
177 | if len(new_value) != 2: |
|
177 | if len(new_value) != 2: | |
178 | raise ValueError, "%s has to be a tuple or list of pairs" %value |
|
178 | raise ValueError, "%s has to be a tuple or list of pairs" %value | |
179 | new_value = [new_value] |
|
179 | new_value = [new_value] | |
180 |
|
180 | |||
181 | for thisPair in new_value: |
|
181 | for thisPair in new_value: | |
182 | if len(thisPair) != 2: |
|
182 | if len(thisPair) != 2: | |
183 | raise ValueError, "%s has to be a tuple or list of pairs" %value |
|
183 | raise ValueError, "%s has to be a tuple or list of pairs" %value | |
184 |
|
184 | |||
185 | self.__formated_value = new_value |
|
185 | self.__formated_value = new_value | |
186 |
|
186 | |||
187 | return self.__formated_value |
|
187 | return self.__formated_value | |
188 |
|
188 | |||
189 | if format == 'multilist': |
|
189 | if format == 'multilist': | |
190 | """ |
|
190 | """ | |
191 | Example: |
|
191 | Example: | |
192 | value = (0,1,2),(3,4,5) |
|
192 | value = (0,1,2),(3,4,5) | |
193 | """ |
|
193 | """ | |
194 | multiList = ast.literal_eval(value) |
|
194 | multiList = ast.literal_eval(value) | |
195 |
|
195 | |||
196 | if type(multiList[0]) == int: |
|
196 | if type(multiList[0]) == int: | |
197 | multiList = ast.literal_eval("(" + value + ")") |
|
197 | multiList = ast.literal_eval("(" + value + ")") | |
198 |
|
198 | |||
199 | self.__formated_value = multiList |
|
199 | self.__formated_value = multiList | |
200 |
|
200 | |||
201 | return self.__formated_value |
|
201 | return self.__formated_value | |
202 |
|
202 | |||
203 | if format == 'bool': |
|
203 | if format == 'bool': | |
204 | value = int(value) |
|
204 | value = int(value) | |
205 |
|
205 | |||
206 | if format == 'int': |
|
206 | if format == 'int': | |
207 | value = float(value) |
|
207 | value = float(value) | |
208 |
|
208 | |||
209 | format_func = eval(format) |
|
209 | format_func = eval(format) | |
210 |
|
210 | |||
211 | self.__formated_value = format_func(value) |
|
211 | self.__formated_value = format_func(value) | |
212 |
|
212 | |||
213 | return self.__formated_value |
|
213 | return self.__formated_value | |
214 |
|
214 | |||
215 | def updateId(self, new_id): |
|
215 | def updateId(self, new_id): | |
216 |
|
216 | |||
217 | self.id = str(new_id) |
|
217 | self.id = str(new_id) | |
218 |
|
218 | |||
219 | def setup(self, id, name, value, format='str'): |
|
219 | def setup(self, id, name, value, format='str'): | |
220 |
|
220 | |||
221 | self.id = str(id) |
|
221 | self.id = str(id) | |
222 | self.name = name |
|
222 | self.name = name | |
223 | if format == 'obj': |
|
223 | if format == 'obj': | |
224 | self.value = value |
|
224 | self.value = value | |
225 | else: |
|
225 | else: | |
226 | self.value = str(value) |
|
226 | self.value = str(value) | |
227 | self.format = str.lower(format) |
|
227 | self.format = str.lower(format) | |
228 |
|
228 | |||
229 | self.getValue() |
|
229 | self.getValue() | |
230 |
|
230 | |||
231 | return 1 |
|
231 | return 1 | |
232 |
|
232 | |||
233 | def update(self, name, value, format='str'): |
|
233 | def update(self, name, value, format='str'): | |
234 |
|
234 | |||
235 | self.name = name |
|
235 | self.name = name | |
236 | self.value = str(value) |
|
236 | self.value = str(value) | |
237 | self.format = format |
|
237 | self.format = format | |
238 |
|
238 | |||
239 | def makeXml(self, opElement): |
|
239 | def makeXml(self, opElement): | |
240 | if self.name not in ('queue',): |
|
240 | if self.name not in ('queue',): | |
241 | parmElement = SubElement(opElement, self.ELEMENTNAME) |
|
241 | parmElement = SubElement(opElement, self.ELEMENTNAME) | |
242 | parmElement.set('id', str(self.id)) |
|
242 | parmElement.set('id', str(self.id)) | |
243 | parmElement.set('name', self.name) |
|
243 | parmElement.set('name', self.name) | |
244 | parmElement.set('value', self.value) |
|
244 | parmElement.set('value', self.value) | |
245 | parmElement.set('format', self.format) |
|
245 | parmElement.set('format', self.format) | |
246 |
|
246 | |||
247 | def readXml(self, parmElement): |
|
247 | def readXml(self, parmElement): | |
248 |
|
248 | |||
249 | self.id = parmElement.get('id') |
|
249 | self.id = parmElement.get('id') | |
250 | self.name = parmElement.get('name') |
|
250 | self.name = parmElement.get('name') | |
251 | self.value = parmElement.get('value') |
|
251 | self.value = parmElement.get('value') | |
252 | self.format = str.lower(parmElement.get('format')) |
|
252 | self.format = str.lower(parmElement.get('format')) | |
253 |
|
253 | |||
254 | #Compatible with old signal chain version |
|
254 | #Compatible with old signal chain version | |
255 | if self.format == 'int' and self.name == 'idfigure': |
|
255 | if self.format == 'int' and self.name == 'idfigure': | |
256 | self.name = 'id' |
|
256 | self.name = 'id' | |
257 |
|
257 | |||
258 | def printattr(self): |
|
258 | def printattr(self): | |
259 |
|
259 | |||
260 | print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format) |
|
260 | print "Parameter[%s]: name = %s, value = %s, format = %s" %(self.id, self.name, self.value, self.format) | |
261 |
|
261 | |||
262 | class OperationConf(): |
|
262 | class OperationConf(): | |
263 |
|
263 | |||
264 | id = None |
|
264 | id = None | |
265 | name = None |
|
265 | name = None | |
266 | priority = None |
|
266 | priority = None | |
267 | type = None |
|
267 | type = None | |
268 |
|
268 | |||
269 | parmConfObjList = [] |
|
269 | parmConfObjList = [] | |
270 |
|
270 | |||
271 | ELEMENTNAME = 'Operation' |
|
271 | ELEMENTNAME = 'Operation' | |
272 |
|
272 | |||
273 | def __init__(self): |
|
273 | def __init__(self): | |
274 |
|
274 | |||
275 | self.id = '0' |
|
275 | self.id = '0' | |
276 | self.name = None |
|
276 | self.name = None | |
277 | self.priority = None |
|
277 | self.priority = None | |
278 | self.type = 'self' |
|
278 | self.type = 'self' | |
279 |
|
279 | |||
280 |
|
280 | |||
281 | def __getNewId(self): |
|
281 | def __getNewId(self): | |
282 |
|
282 | |||
283 | return int(self.id)*10 + len(self.parmConfObjList) + 1 |
|
283 | return int(self.id)*10 + len(self.parmConfObjList) + 1 | |
284 |
|
284 | |||
285 | def updateId(self, new_id): |
|
285 | def updateId(self, new_id): | |
286 |
|
286 | |||
287 | self.id = str(new_id) |
|
287 | self.id = str(new_id) | |
288 |
|
288 | |||
289 | n = 1 |
|
289 | n = 1 | |
290 | for parmObj in self.parmConfObjList: |
|
290 | for parmObj in self.parmConfObjList: | |
291 |
|
291 | |||
292 | idParm = str(int(new_id)*10 + n) |
|
292 | idParm = str(int(new_id)*10 + n) | |
293 | parmObj.updateId(idParm) |
|
293 | parmObj.updateId(idParm) | |
294 |
|
294 | |||
295 | n += 1 |
|
295 | n += 1 | |
296 |
|
296 | |||
297 | def getElementName(self): |
|
297 | def getElementName(self): | |
298 |
|
298 | |||
299 | return self.ELEMENTNAME |
|
299 | return self.ELEMENTNAME | |
300 |
|
300 | |||
301 | def getParameterObjList(self): |
|
301 | def getParameterObjList(self): | |
302 |
|
302 | |||
303 | return self.parmConfObjList |
|
303 | return self.parmConfObjList | |
304 |
|
304 | |||
305 | def getParameterObj(self, parameterName): |
|
305 | def getParameterObj(self, parameterName): | |
306 |
|
306 | |||
307 | for parmConfObj in self.parmConfObjList: |
|
307 | for parmConfObj in self.parmConfObjList: | |
308 |
|
308 | |||
309 | if parmConfObj.name != parameterName: |
|
309 | if parmConfObj.name != parameterName: | |
310 | continue |
|
310 | continue | |
311 |
|
311 | |||
312 | return parmConfObj |
|
312 | return parmConfObj | |
313 |
|
313 | |||
314 | return None |
|
314 | return None | |
315 |
|
315 | |||
316 | def getParameterObjfromValue(self, parameterValue): |
|
316 | def getParameterObjfromValue(self, parameterValue): | |
317 |
|
317 | |||
318 | for parmConfObj in self.parmConfObjList: |
|
318 | for parmConfObj in self.parmConfObjList: | |
319 |
|
319 | |||
320 | if parmConfObj.getValue() != parameterValue: |
|
320 | if parmConfObj.getValue() != parameterValue: | |
321 | continue |
|
321 | continue | |
322 |
|
322 | |||
323 | return parmConfObj.getValue() |
|
323 | return parmConfObj.getValue() | |
324 |
|
324 | |||
325 | return None |
|
325 | return None | |
326 |
|
326 | |||
327 | def getParameterValue(self, parameterName): |
|
327 | def getParameterValue(self, parameterName): | |
328 |
|
328 | |||
329 | parameterObj = self.getParameterObj(parameterName) |
|
329 | parameterObj = self.getParameterObj(parameterName) | |
330 |
|
330 | |||
331 | # if not parameterObj: |
|
331 | # if not parameterObj: | |
332 | # return None |
|
332 | # return None | |
333 |
|
333 | |||
334 | value = parameterObj.getValue() |
|
334 | value = parameterObj.getValue() | |
335 |
|
335 | |||
336 | return value |
|
336 | return value | |
337 |
|
337 | |||
338 |
|
338 | |||
339 | def getKwargs(self): |
|
339 | def getKwargs(self): | |
340 |
|
340 | |||
341 | kwargs = {} |
|
341 | kwargs = {} | |
342 |
|
342 | |||
343 | for parmConfObj in self.parmConfObjList: |
|
343 | for parmConfObj in self.parmConfObjList: | |
344 | if self.name == 'run' and parmConfObj.name == 'datatype': |
|
344 | if self.name == 'run' and parmConfObj.name == 'datatype': | |
345 | continue |
|
345 | continue | |
346 |
|
346 | |||
347 | kwargs[parmConfObj.name] = parmConfObj.getValue() |
|
347 | kwargs[parmConfObj.name] = parmConfObj.getValue() | |
348 |
|
348 | |||
349 | return kwargs |
|
349 | return kwargs | |
350 |
|
350 | |||
351 | def setup(self, id, name, priority, type): |
|
351 | def setup(self, id, name, priority, type): | |
352 |
|
352 | |||
353 | self.id = str(id) |
|
353 | self.id = str(id) | |
354 | self.name = name |
|
354 | self.name = name | |
355 | self.type = type |
|
355 | self.type = type | |
356 | self.priority = priority |
|
356 | self.priority = priority | |
357 |
|
357 | |||
358 | self.parmConfObjList = [] |
|
358 | self.parmConfObjList = [] | |
359 |
|
359 | |||
360 | def removeParameters(self): |
|
360 | def removeParameters(self): | |
361 |
|
361 | |||
362 | for obj in self.parmConfObjList: |
|
362 | for obj in self.parmConfObjList: | |
363 | del obj |
|
363 | del obj | |
364 |
|
364 | |||
365 | self.parmConfObjList = [] |
|
365 | self.parmConfObjList = [] | |
366 |
|
366 | |||
367 | def addParameter(self, name, value, format='str'): |
|
367 | def addParameter(self, name, value, format='str'): | |
368 |
|
368 | |||
369 | id = self.__getNewId() |
|
369 | id = self.__getNewId() | |
370 |
|
370 | |||
371 | parmConfObj = ParameterConf() |
|
371 | parmConfObj = ParameterConf() | |
372 | if not parmConfObj.setup(id, name, value, format): |
|
372 | if not parmConfObj.setup(id, name, value, format): | |
373 | return None |
|
373 | return None | |
374 |
|
374 | |||
375 | self.parmConfObjList.append(parmConfObj) |
|
375 | self.parmConfObjList.append(parmConfObj) | |
376 |
|
376 | |||
377 | return parmConfObj |
|
377 | return parmConfObj | |
378 |
|
378 | |||
379 | def changeParameter(self, name, value, format='str'): |
|
379 | def changeParameter(self, name, value, format='str'): | |
380 |
|
380 | |||
381 | parmConfObj = self.getParameterObj(name) |
|
381 | parmConfObj = self.getParameterObj(name) | |
382 | parmConfObj.update(name, value, format) |
|
382 | parmConfObj.update(name, value, format) | |
383 |
|
383 | |||
384 | return parmConfObj |
|
384 | return parmConfObj | |
385 |
|
385 | |||
386 | def makeXml(self, procUnitElement): |
|
386 | def makeXml(self, procUnitElement): | |
387 |
|
387 | |||
388 | opElement = SubElement(procUnitElement, self.ELEMENTNAME) |
|
388 | opElement = SubElement(procUnitElement, self.ELEMENTNAME) | |
389 | opElement.set('id', str(self.id)) |
|
389 | opElement.set('id', str(self.id)) | |
390 | opElement.set('name', self.name) |
|
390 | opElement.set('name', self.name) | |
391 | opElement.set('type', self.type) |
|
391 | opElement.set('type', self.type) | |
392 | opElement.set('priority', str(self.priority)) |
|
392 | opElement.set('priority', str(self.priority)) | |
393 |
|
393 | |||
394 | for parmConfObj in self.parmConfObjList: |
|
394 | for parmConfObj in self.parmConfObjList: | |
395 | parmConfObj.makeXml(opElement) |
|
395 | parmConfObj.makeXml(opElement) | |
396 |
|
396 | |||
397 | def readXml(self, opElement): |
|
397 | def readXml(self, opElement): | |
398 |
|
398 | |||
399 | self.id = opElement.get('id') |
|
399 | self.id = opElement.get('id') | |
400 | self.name = opElement.get('name') |
|
400 | self.name = opElement.get('name') | |
401 | self.type = opElement.get('type') |
|
401 | self.type = opElement.get('type') | |
402 | self.priority = opElement.get('priority') |
|
402 | self.priority = opElement.get('priority') | |
403 |
|
403 | |||
404 | #Compatible with old signal chain version |
|
404 | #Compatible with old signal chain version | |
405 | #Use of 'run' method instead 'init' |
|
405 | #Use of 'run' method instead 'init' | |
406 | if self.type == 'self' and self.name == 'init': |
|
406 | if self.type == 'self' and self.name == 'init': | |
407 | self.name = 'run' |
|
407 | self.name = 'run' | |
408 |
|
408 | |||
409 | self.parmConfObjList = [] |
|
409 | self.parmConfObjList = [] | |
410 |
|
410 | |||
411 | parmElementList = opElement.iter(ParameterConf().getElementName()) |
|
411 | parmElementList = opElement.iter(ParameterConf().getElementName()) | |
412 |
|
412 | |||
413 | for parmElement in parmElementList: |
|
413 | for parmElement in parmElementList: | |
414 | parmConfObj = ParameterConf() |
|
414 | parmConfObj = ParameterConf() | |
415 | parmConfObj.readXml(parmElement) |
|
415 | parmConfObj.readXml(parmElement) | |
416 |
|
416 | |||
417 | #Compatible with old signal chain version |
|
417 | #Compatible with old signal chain version | |
418 | #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER |
|
418 | #If an 'plot' OPERATION is found, changes name operation by the value of its type PARAMETER | |
419 | if self.type != 'self' and self.name == 'Plot': |
|
419 | if self.type != 'self' and self.name == 'Plot': | |
420 | if parmConfObj.format == 'str' and parmConfObj.name == 'type': |
|
420 | if parmConfObj.format == 'str' and parmConfObj.name == 'type': | |
421 | self.name = parmConfObj.value |
|
421 | self.name = parmConfObj.value | |
422 | continue |
|
422 | continue | |
423 |
|
423 | |||
424 | self.parmConfObjList.append(parmConfObj) |
|
424 | self.parmConfObjList.append(parmConfObj) | |
425 |
|
425 | |||
426 | def printattr(self): |
|
426 | def printattr(self): | |
427 |
|
427 | |||
428 | print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME, |
|
428 | print "%s[%s]: name = %s, type = %s, priority = %s" %(self.ELEMENTNAME, | |
429 | self.id, |
|
429 | self.id, | |
430 | self.name, |
|
430 | self.name, | |
431 | self.type, |
|
431 | self.type, | |
432 | self.priority) |
|
432 | self.priority) | |
433 |
|
433 | |||
434 | for parmConfObj in self.parmConfObjList: |
|
434 | for parmConfObj in self.parmConfObjList: | |
435 | parmConfObj.printattr() |
|
435 | parmConfObj.printattr() | |
436 |
|
436 | |||
437 | def createObject(self, plotter_queue=None): |
|
437 | def createObject(self, plotter_queue=None): | |
438 |
|
438 | |||
439 |
|
439 | |||
440 | if self.type == 'self': |
|
440 | if self.type == 'self': | |
441 | raise ValueError, "This operation type cannot be created" |
|
441 | raise ValueError, "This operation type cannot be created" | |
442 |
|
442 | |||
443 | if self.type == 'plotter': |
|
443 | if self.type == 'plotter': | |
444 | #Plotter(plotter_name) |
|
444 | #Plotter(plotter_name) | |
445 | if not plotter_queue: |
|
445 | if not plotter_queue: | |
446 | raise ValueError, "plotter_queue is not defined. Use:\nmyProject = Project()\nmyProject.setPlotterQueue(plotter_queue)" |
|
446 | raise ValueError, "plotter_queue is not defined. Use:\nmyProject = Project()\nmyProject.setPlotterQueue(plotter_queue)" | |
447 |
|
447 | |||
448 | opObj = Plotter(self.name, plotter_queue) |
|
448 | opObj = Plotter(self.name, plotter_queue) | |
449 |
|
449 | |||
450 | if self.type == 'external' or self.type == 'other': |
|
450 | if self.type == 'external' or self.type == 'other': | |
451 |
|
451 | |||
452 | className = eval(self.name) |
|
452 | className = eval(self.name) | |
453 | kwargs = self.getKwargs() |
|
453 | kwargs = self.getKwargs() | |
454 |
|
454 | |||
455 | opObj = className(**kwargs) |
|
455 | opObj = className(**kwargs) | |
456 |
|
456 | |||
457 | return opObj |
|
457 | return opObj | |
458 |
|
458 | |||
459 |
|
459 | |||
460 | class ProcUnitConf(): |
|
460 | class ProcUnitConf(): | |
461 |
|
461 | |||
462 | id = None |
|
462 | id = None | |
463 | name = None |
|
463 | name = None | |
464 | datatype = None |
|
464 | datatype = None | |
465 | inputId = None |
|
465 | inputId = None | |
466 | parentId = None |
|
466 | parentId = None | |
467 |
|
467 | |||
468 | opConfObjList = [] |
|
468 | opConfObjList = [] | |
469 |
|
469 | |||
470 | procUnitObj = None |
|
470 | procUnitObj = None | |
471 | opObjList = [] |
|
471 | opObjList = [] | |
472 |
|
472 | |||
473 | ELEMENTNAME = 'ProcUnit' |
|
473 | ELEMENTNAME = 'ProcUnit' | |
474 |
|
474 | |||
475 | def __init__(self): |
|
475 | def __init__(self): | |
476 |
|
476 | |||
477 | self.id = None |
|
477 | self.id = None | |
478 | self.datatype = None |
|
478 | self.datatype = None | |
479 | self.name = None |
|
479 | self.name = None | |
480 | self.inputId = None |
|
480 | self.inputId = None | |
481 |
|
481 | |||
482 | self.opConfObjList = [] |
|
482 | self.opConfObjList = [] | |
483 |
|
483 | |||
484 | self.procUnitObj = None |
|
484 | self.procUnitObj = None | |
485 | self.opObjDict = {} |
|
485 | self.opObjDict = {} | |
486 |
|
486 | |||
487 | def __getPriority(self): |
|
487 | def __getPriority(self): | |
488 |
|
488 | |||
489 | return len(self.opConfObjList)+1 |
|
489 | return len(self.opConfObjList)+1 | |
490 |
|
490 | |||
491 | def __getNewId(self): |
|
491 | def __getNewId(self): | |
492 |
|
492 | |||
493 | return int(self.id)*10 + len(self.opConfObjList) + 1 |
|
493 | return int(self.id)*10 + len(self.opConfObjList) + 1 | |
494 |
|
494 | |||
495 | def getElementName(self): |
|
495 | def getElementName(self): | |
496 |
|
496 | |||
497 | return self.ELEMENTNAME |
|
497 | return self.ELEMENTNAME | |
498 |
|
498 | |||
499 | def getId(self): |
|
499 | def getId(self): | |
500 |
|
500 | |||
501 | return self.id |
|
501 | return self.id | |
502 |
|
502 | |||
503 | def updateId(self, new_id, parentId=parentId): |
|
503 | def updateId(self, new_id, parentId=parentId): | |
504 |
|
504 | |||
505 |
|
505 | |||
506 | new_id = int(parentId)*10 + (int(self.id) % 10) |
|
506 | new_id = int(parentId)*10 + (int(self.id) % 10) | |
507 | new_inputId = int(parentId)*10 + (int(self.inputId) % 10) |
|
507 | new_inputId = int(parentId)*10 + (int(self.inputId) % 10) | |
508 |
|
508 | |||
509 | #If this proc unit has not inputs |
|
509 | #If this proc unit has not inputs | |
510 | if self.inputId == '0': |
|
510 | if self.inputId == '0': | |
511 | new_inputId = 0 |
|
511 | new_inputId = 0 | |
512 |
|
512 | |||
513 | n = 1 |
|
513 | n = 1 | |
514 | for opConfObj in self.opConfObjList: |
|
514 | for opConfObj in self.opConfObjList: | |
515 |
|
515 | |||
516 | idOp = str(int(new_id)*10 + n) |
|
516 | idOp = str(int(new_id)*10 + n) | |
517 | opConfObj.updateId(idOp) |
|
517 | opConfObj.updateId(idOp) | |
518 |
|
518 | |||
519 | n += 1 |
|
519 | n += 1 | |
520 |
|
520 | |||
521 | self.parentId = str(parentId) |
|
521 | self.parentId = str(parentId) | |
522 | self.id = str(new_id) |
|
522 | self.id = str(new_id) | |
523 | self.inputId = str(new_inputId) |
|
523 | self.inputId = str(new_inputId) | |
524 |
|
524 | |||
525 |
|
525 | |||
526 | def getInputId(self): |
|
526 | def getInputId(self): | |
527 |
|
527 | |||
528 | return self.inputId |
|
528 | return self.inputId | |
529 |
|
529 | |||
530 | def getOperationObjList(self): |
|
530 | def getOperationObjList(self): | |
531 |
|
531 | |||
532 | return self.opConfObjList |
|
532 | return self.opConfObjList | |
533 |
|
533 | |||
534 | def getOperationObj(self, name=None): |
|
534 | def getOperationObj(self, name=None): | |
535 |
|
535 | |||
536 | for opConfObj in self.opConfObjList: |
|
536 | for opConfObj in self.opConfObjList: | |
537 |
|
537 | |||
538 | if opConfObj.name != name: |
|
538 | if opConfObj.name != name: | |
539 | continue |
|
539 | continue | |
540 |
|
540 | |||
541 | return opConfObj |
|
541 | return opConfObj | |
542 |
|
542 | |||
543 | return None |
|
543 | return None | |
544 |
|
544 | |||
545 | def getOpObjfromParamValue(self, value=None): |
|
545 | def getOpObjfromParamValue(self, value=None): | |
546 |
|
546 | |||
547 | for opConfObj in self.opConfObjList: |
|
547 | for opConfObj in self.opConfObjList: | |
548 | if opConfObj.getParameterObjfromValue(parameterValue=value) != value: |
|
548 | if opConfObj.getParameterObjfromValue(parameterValue=value) != value: | |
549 | continue |
|
549 | continue | |
550 | return opConfObj |
|
550 | return opConfObj | |
551 | return None |
|
551 | return None | |
552 |
|
552 | |||
553 | def getProcUnitObj(self): |
|
553 | def getProcUnitObj(self): | |
554 |
|
554 | |||
555 | return self.procUnitObj |
|
555 | return self.procUnitObj | |
556 |
|
556 | |||
557 | def setup(self, id, name, datatype, inputId, parentId=None): |
|
557 | def setup(self, id, name, datatype, inputId, parentId=None): | |
558 |
|
558 | |||
559 | #Compatible with old signal chain version |
|
559 | #Compatible with old signal chain version | |
560 | if datatype==None and name==None: |
|
560 | if datatype==None and name==None: | |
561 | raise ValueError, "datatype or name should be defined" |
|
561 | raise ValueError, "datatype or name should be defined" | |
562 |
|
562 | |||
563 | if name==None: |
|
563 | if name==None: | |
564 | if 'Proc' in datatype: |
|
564 | if 'Proc' in datatype: | |
565 | name = datatype |
|
565 | name = datatype | |
566 | else: |
|
566 | else: | |
567 | name = '%sProc' %(datatype) |
|
567 | name = '%sProc' %(datatype) | |
568 |
|
568 | |||
569 | if datatype==None: |
|
569 | if datatype==None: | |
570 | datatype = name.replace('Proc','') |
|
570 | datatype = name.replace('Proc','') | |
571 |
|
571 | |||
572 | self.id = str(id) |
|
572 | self.id = str(id) | |
573 | self.name = name |
|
573 | self.name = name | |
574 | self.datatype = datatype |
|
574 | self.datatype = datatype | |
575 | self.inputId = inputId |
|
575 | self.inputId = inputId | |
576 | self.parentId = parentId |
|
576 | self.parentId = parentId | |
577 |
|
577 | |||
578 | self.opConfObjList = [] |
|
578 | self.opConfObjList = [] | |
579 |
|
579 | |||
580 | self.addOperation(name='run', optype='self') |
|
580 | self.addOperation(name='run', optype='self') | |
581 |
|
581 | |||
582 | def removeOperations(self): |
|
582 | def removeOperations(self): | |
583 |
|
583 | |||
584 | for obj in self.opConfObjList: |
|
584 | for obj in self.opConfObjList: | |
585 | del obj |
|
585 | del obj | |
586 |
|
586 | |||
587 | self.opConfObjList = [] |
|
587 | self.opConfObjList = [] | |
588 | self.addOperation(name='run') |
|
588 | self.addOperation(name='run') | |
589 |
|
589 | |||
590 | def addParameter(self, **kwargs): |
|
590 | def addParameter(self, **kwargs): | |
591 | ''' |
|
591 | ''' | |
592 | Add parameters to "run" operation |
|
592 | Add parameters to "run" operation | |
593 | ''' |
|
593 | ''' | |
594 | opObj = self.opConfObjList[0] |
|
594 | opObj = self.opConfObjList[0] | |
595 |
|
595 | |||
596 | opObj.addParameter(**kwargs) |
|
596 | opObj.addParameter(**kwargs) | |
597 |
|
597 | |||
598 | return opObj |
|
598 | return opObj | |
599 |
|
599 | |||
600 | def addOperation(self, name, optype='self'): |
|
600 | def addOperation(self, name, optype='self'): | |
601 |
|
601 | |||
602 | id = self.__getNewId() |
|
602 | id = self.__getNewId() | |
603 | priority = self.__getPriority() |
|
603 | priority = self.__getPriority() | |
604 |
|
604 | |||
605 | opConfObj = OperationConf() |
|
605 | opConfObj = OperationConf() | |
606 | opConfObj.setup(id, name=name, priority=priority, type=optype) |
|
606 | opConfObj.setup(id, name=name, priority=priority, type=optype) | |
607 |
|
607 | |||
608 | self.opConfObjList.append(opConfObj) |
|
608 | self.opConfObjList.append(opConfObj) | |
609 |
|
609 | |||
610 | return opConfObj |
|
610 | return opConfObj | |
611 |
|
611 | |||
612 | def makeXml(self, projectElement): |
|
612 | def makeXml(self, projectElement): | |
613 |
|
613 | |||
614 | procUnitElement = SubElement(projectElement, self.ELEMENTNAME) |
|
614 | procUnitElement = SubElement(projectElement, self.ELEMENTNAME) | |
615 | procUnitElement.set('id', str(self.id)) |
|
615 | procUnitElement.set('id', str(self.id)) | |
616 | procUnitElement.set('name', self.name) |
|
616 | procUnitElement.set('name', self.name) | |
617 | procUnitElement.set('datatype', self.datatype) |
|
617 | procUnitElement.set('datatype', self.datatype) | |
618 | procUnitElement.set('inputId', str(self.inputId)) |
|
618 | procUnitElement.set('inputId', str(self.inputId)) | |
619 |
|
619 | |||
620 | for opConfObj in self.opConfObjList: |
|
620 | for opConfObj in self.opConfObjList: | |
621 | opConfObj.makeXml(procUnitElement) |
|
621 | opConfObj.makeXml(procUnitElement) | |
622 |
|
622 | |||
623 | def readXml(self, upElement): |
|
623 | def readXml(self, upElement): | |
624 |
|
624 | |||
625 | self.id = upElement.get('id') |
|
625 | self.id = upElement.get('id') | |
626 | self.name = upElement.get('name') |
|
626 | self.name = upElement.get('name') | |
627 | self.datatype = upElement.get('datatype') |
|
627 | self.datatype = upElement.get('datatype') | |
628 | self.inputId = upElement.get('inputId') |
|
628 | self.inputId = upElement.get('inputId') | |
629 |
|
629 | |||
630 | if self.ELEMENTNAME == "ReadUnit": |
|
630 | if self.ELEMENTNAME == "ReadUnit": | |
631 | self.datatype = self.datatype.replace("Reader", "") |
|
631 | self.datatype = self.datatype.replace("Reader", "") | |
632 |
|
632 | |||
633 | if self.ELEMENTNAME == "ProcUnit": |
|
633 | if self.ELEMENTNAME == "ProcUnit": | |
634 | self.datatype = self.datatype.replace("Proc", "") |
|
634 | self.datatype = self.datatype.replace("Proc", "") | |
635 |
|
635 | |||
636 | if self.inputId == 'None': |
|
636 | if self.inputId == 'None': | |
637 | self.inputId = '0' |
|
637 | self.inputId = '0' | |
638 |
|
638 | |||
639 | self.opConfObjList = [] |
|
639 | self.opConfObjList = [] | |
640 |
|
640 | |||
641 | opElementList = upElement.iter(OperationConf().getElementName()) |
|
641 | opElementList = upElement.iter(OperationConf().getElementName()) | |
642 |
|
642 | |||
643 | for opElement in opElementList: |
|
643 | for opElement in opElementList: | |
644 | opConfObj = OperationConf() |
|
644 | opConfObj = OperationConf() | |
645 | opConfObj.readXml(opElement) |
|
645 | opConfObj.readXml(opElement) | |
646 | self.opConfObjList.append(opConfObj) |
|
646 | self.opConfObjList.append(opConfObj) | |
647 |
|
647 | |||
648 | def printattr(self): |
|
648 | def printattr(self): | |
649 |
|
649 | |||
650 | print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME, |
|
650 | print "%s[%s]: name = %s, datatype = %s, inputId = %s" %(self.ELEMENTNAME, | |
651 | self.id, |
|
651 | self.id, | |
652 | self.name, |
|
652 | self.name, | |
653 | self.datatype, |
|
653 | self.datatype, | |
654 | self.inputId) |
|
654 | self.inputId) | |
655 |
|
655 | |||
656 | for opConfObj in self.opConfObjList: |
|
656 | for opConfObj in self.opConfObjList: | |
657 | opConfObj.printattr() |
|
657 | opConfObj.printattr() | |
658 |
|
658 | |||
659 |
|
659 | |||
660 | def getKwargs(self): |
|
660 | def getKwargs(self): | |
661 |
|
661 | |||
662 | opObj = self.opConfObjList[0] |
|
662 | opObj = self.opConfObjList[0] | |
663 | kwargs = opObj.getKwargs() |
|
663 | kwargs = opObj.getKwargs() | |
664 |
|
664 | |||
665 | return kwargs |
|
665 | return kwargs | |
666 |
|
666 | |||
667 | def createObjects(self, plotter_queue=None): |
|
667 | def createObjects(self, plotter_queue=None): | |
668 |
|
668 | |||
669 | className = eval(self.name) |
|
669 | className = eval(self.name) | |
670 | kwargs = self.getKwargs() |
|
670 | kwargs = self.getKwargs() | |
671 | procUnitObj = className(**kwargs) |
|
671 | procUnitObj = className(**kwargs) | |
672 |
|
672 | |||
673 | for opConfObj in self.opConfObjList: |
|
673 | for opConfObj in self.opConfObjList: | |
674 |
|
674 | |||
675 | if opConfObj.type=='self' and self.name=='run': |
|
675 | if opConfObj.type=='self' and self.name=='run': | |
676 | continue |
|
676 | continue | |
677 | elif opConfObj.type=='self': |
|
677 | elif opConfObj.type=='self': | |
678 | procUnitObj.addOperationKwargs(opConfObj.id, **opConfObj.getKwargs()) |
|
678 | procUnitObj.addOperationKwargs(opConfObj.id, **opConfObj.getKwargs()) | |
679 | continue |
|
679 | continue | |
680 |
|
680 | |||
681 | opObj = opConfObj.createObject(plotter_queue) |
|
681 | opObj = opConfObj.createObject(plotter_queue) | |
682 |
|
682 | |||
683 | self.opObjDict[opConfObj.id] = opObj |
|
683 | self.opObjDict[opConfObj.id] = opObj | |
684 |
|
684 | |||
685 | procUnitObj.addOperation(opObj, opConfObj.id) |
|
685 | procUnitObj.addOperation(opObj, opConfObj.id) | |
686 |
|
686 | |||
687 | self.procUnitObj = procUnitObj |
|
687 | self.procUnitObj = procUnitObj | |
688 |
|
688 | |||
689 | return procUnitObj |
|
689 | return procUnitObj | |
690 |
|
690 | |||
691 | def run(self): |
|
691 | def run(self): | |
692 |
|
692 | |||
693 | is_ok = False |
|
693 | is_ok = False | |
694 |
|
694 | |||
695 | for opConfObj in self.opConfObjList: |
|
695 | for opConfObj in self.opConfObjList: | |
696 |
|
696 | |||
697 | kwargs = {} |
|
697 | kwargs = {} | |
698 | for parmConfObj in opConfObj.getParameterObjList(): |
|
698 | for parmConfObj in opConfObj.getParameterObjList(): | |
699 | if opConfObj.name == 'run' and parmConfObj.name == 'datatype': |
|
699 | if opConfObj.name == 'run' and parmConfObj.name == 'datatype': | |
700 | continue |
|
700 | continue | |
701 |
|
701 | |||
702 | kwargs[parmConfObj.name] = parmConfObj.getValue() |
|
702 | kwargs[parmConfObj.name] = parmConfObj.getValue() | |
703 |
|
703 | |||
704 | #ini = time.time() |
|
704 | #ini = time.time() | |
705 |
|
705 | |||
706 | #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id) |
|
706 | #print "\tRunning the '%s' operation with %s" %(opConfObj.name, opConfObj.id) | |
707 | sts = self.procUnitObj.call(opType = opConfObj.type, |
|
707 | sts = self.procUnitObj.call(opType = opConfObj.type, | |
708 | opName = opConfObj.name, |
|
708 | opName = opConfObj.name, | |
709 | opId = opConfObj.id, |
|
709 | opId = opConfObj.id, | |
710 | ) |
|
710 | ) | |
711 |
|
711 | |||
712 | # total_time = time.time() - ini |
|
712 | # total_time = time.time() - ini | |
713 | # |
|
713 | # | |
714 | # if total_time > 0.002: |
|
714 | # if total_time > 0.002: | |
715 | # print "%s::%s took %f seconds" %(self.name, opConfObj.name, total_time) |
|
715 | # print "%s::%s took %f seconds" %(self.name, opConfObj.name, total_time) | |
716 |
|
716 | |||
717 | is_ok = is_ok or sts |
|
717 | is_ok = is_ok or sts | |
718 |
|
718 | |||
719 | return is_ok |
|
719 | return is_ok | |
720 |
|
720 | |||
721 | def close(self): |
|
721 | def close(self): | |
722 |
|
722 | |||
723 | for opConfObj in self.opConfObjList: |
|
723 | for opConfObj in self.opConfObjList: | |
724 | if opConfObj.type == 'self': |
|
724 | if opConfObj.type == 'self': | |
725 | continue |
|
725 | continue | |
726 |
|
726 | |||
727 | opObj = self.procUnitObj.getOperationObj(opConfObj.id) |
|
727 | opObj = self.procUnitObj.getOperationObj(opConfObj.id) | |
728 | opObj.close() |
|
728 | opObj.close() | |
729 |
|
729 | |||
730 | self.procUnitObj.close() |
|
730 | self.procUnitObj.close() | |
731 |
|
731 | |||
732 | return |
|
732 | return | |
733 |
|
733 | |||
734 | class ReadUnitConf(ProcUnitConf): |
|
734 | class ReadUnitConf(ProcUnitConf): | |
735 |
|
735 | |||
736 | path = None |
|
736 | path = None | |
737 | startDate = None |
|
737 | startDate = None | |
738 | endDate = None |
|
738 | endDate = None | |
739 | startTime = None |
|
739 | startTime = None | |
740 | endTime = None |
|
740 | endTime = None | |
741 |
|
741 | |||
742 | ELEMENTNAME = 'ReadUnit' |
|
742 | ELEMENTNAME = 'ReadUnit' | |
743 |
|
743 | |||
744 | def __init__(self): |
|
744 | def __init__(self): | |
745 |
|
745 | |||
746 | self.id = None |
|
746 | self.id = None | |
747 | self.datatype = None |
|
747 | self.datatype = None | |
748 | self.name = None |
|
748 | self.name = None | |
749 | self.inputId = None |
|
749 | self.inputId = None | |
750 |
|
750 | |||
751 | self.parentId = None |
|
751 | self.parentId = None | |
752 |
|
752 | |||
753 | self.opConfObjList = [] |
|
753 | self.opConfObjList = [] | |
754 | self.opObjList = [] |
|
754 | self.opObjList = [] | |
755 |
|
755 | |||
756 | def getElementName(self): |
|
756 | def getElementName(self): | |
757 |
|
757 | |||
758 | return self.ELEMENTNAME |
|
758 | return self.ELEMENTNAME | |
759 |
|
759 | |||
760 | def setup(self, id, name, datatype, path, startDate="", endDate="", startTime="", endTime="", parentId=None, queue=None, **kwargs): |
|
760 | def setup(self, id, name, datatype, path, startDate="", endDate="", startTime="", endTime="", parentId=None, queue=None, **kwargs): | |
761 |
|
761 | |||
762 | #Compatible with old signal chain version |
|
762 | #Compatible with old signal chain version | |
763 | if datatype==None and name==None: |
|
763 | if datatype==None and name==None: | |
764 | raise ValueError, "datatype or name should be defined" |
|
764 | raise ValueError, "datatype or name should be defined" | |
765 |
|
765 | |||
766 | if name==None: |
|
766 | if name==None: | |
767 | if 'Reader' in datatype: |
|
767 | if 'Reader' in datatype: | |
768 | name = datatype |
|
768 | name = datatype | |
769 | else: |
|
769 | else: | |
770 | name = '%sReader' %(datatype) |
|
770 | name = '%sReader' %(datatype) | |
771 |
|
771 | |||
772 | if datatype==None: |
|
772 | if datatype==None: | |
773 | datatype = name.replace('Reader','') |
|
773 | datatype = name.replace('Reader','') | |
774 |
|
774 | |||
775 | self.id = id |
|
775 | self.id = id | |
776 | self.name = name |
|
776 | self.name = name | |
777 | self.datatype = datatype |
|
777 | self.datatype = datatype | |
778 |
|
778 | |||
779 | self.path = os.path.abspath(path) |
|
779 | self.path = os.path.abspath(path) | |
780 | self.startDate = startDate |
|
780 | self.startDate = startDate | |
781 | self.endDate = endDate |
|
781 | self.endDate = endDate | |
782 | self.startTime = startTime |
|
782 | self.startTime = startTime | |
783 | self.endTime = endTime |
|
783 | self.endTime = endTime | |
784 |
|
784 | |||
785 | self.inputId = '0' |
|
785 | self.inputId = '0' | |
786 | self.parentId = parentId |
|
786 | self.parentId = parentId | |
787 | self.queue = queue |
|
787 | self.queue = queue | |
788 | self.addRunOperation(**kwargs) |
|
788 | self.addRunOperation(**kwargs) | |
789 |
|
789 | |||
790 | def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs): |
|
790 | def update(self, datatype, path, startDate, endDate, startTime, endTime, parentId=None, name=None, **kwargs): | |
791 |
|
791 | |||
792 | #Compatible with old signal chain version |
|
792 | #Compatible with old signal chain version | |
793 | if datatype==None and name==None: |
|
793 | if datatype==None and name==None: | |
794 | raise ValueError, "datatype or name should be defined" |
|
794 | raise ValueError, "datatype or name should be defined" | |
795 |
|
795 | |||
796 | if name==None: |
|
796 | if name==None: | |
797 | if 'Reader' in datatype: |
|
797 | if 'Reader' in datatype: | |
798 | name = datatype |
|
798 | name = datatype | |
799 | else: |
|
799 | else: | |
800 | name = '%sReader' %(datatype) |
|
800 | name = '%sReader' %(datatype) | |
801 |
|
801 | |||
802 | if datatype==None: |
|
802 | if datatype==None: | |
803 | datatype = name.replace('Reader','') |
|
803 | datatype = name.replace('Reader','') | |
804 |
|
804 | |||
805 | self.datatype = datatype |
|
805 | self.datatype = datatype | |
806 | self.name = name |
|
806 | self.name = name | |
807 | self.path = path |
|
807 | self.path = path | |
808 | self.startDate = startDate |
|
808 | self.startDate = startDate | |
809 | self.endDate = endDate |
|
809 | self.endDate = endDate | |
810 | self.startTime = startTime |
|
810 | self.startTime = startTime | |
811 | self.endTime = endTime |
|
811 | self.endTime = endTime | |
812 |
|
812 | |||
813 | self.inputId = '0' |
|
813 | self.inputId = '0' | |
814 | self.parentId = parentId |
|
814 | self.parentId = parentId | |
815 |
|
815 | |||
816 | self.updateRunOperation(**kwargs) |
|
816 | self.updateRunOperation(**kwargs) | |
817 |
|
817 | |||
818 | def removeOperations(self): |
|
818 | def removeOperations(self): | |
819 |
|
819 | |||
820 | for obj in self.opConfObjList: |
|
820 | for obj in self.opConfObjList: | |
821 | del obj |
|
821 | del obj | |
822 |
|
822 | |||
823 | self.opConfObjList = [] |
|
823 | self.opConfObjList = [] | |
824 |
|
824 | |||
825 | def addRunOperation(self, **kwargs): |
|
825 | def addRunOperation(self, **kwargs): | |
826 |
|
826 | |||
827 | opObj = self.addOperation(name = 'run', optype = 'self') |
|
827 | opObj = self.addOperation(name = 'run', optype = 'self') | |
828 |
|
828 | |||
829 | opObj.addParameter(name='datatype' , value=self.datatype, format='str') |
|
829 | opObj.addParameter(name='datatype' , value=self.datatype, format='str') | |
830 | opObj.addParameter(name='path' , value=self.path, format='str') |
|
830 | opObj.addParameter(name='path' , value=self.path, format='str') | |
831 | opObj.addParameter(name='startDate' , value=self.startDate, format='date') |
|
831 | opObj.addParameter(name='startDate' , value=self.startDate, format='date') | |
832 | opObj.addParameter(name='endDate' , value=self.endDate, format='date') |
|
832 | opObj.addParameter(name='endDate' , value=self.endDate, format='date') | |
833 | opObj.addParameter(name='startTime' , value=self.startTime, format='time') |
|
833 | opObj.addParameter(name='startTime' , value=self.startTime, format='time') | |
834 | opObj.addParameter(name='endTime' , value=self.endTime, format='time') |
|
834 | opObj.addParameter(name='endTime' , value=self.endTime, format='time') | |
835 | opObj.addParameter(name='queue' , value=self.queue, format='obj') |
|
835 | opObj.addParameter(name='queue' , value=self.queue, format='obj') | |
836 |
|
836 | |||
837 | for key, value in kwargs.items(): |
|
837 | for key, value in kwargs.items(): | |
838 | opObj.addParameter(name=key, value=value, format=type(value).__name__) |
|
838 | opObj.addParameter(name=key, value=value, format=type(value).__name__) | |
839 |
|
839 | |||
840 | return opObj |
|
840 | return opObj | |
841 |
|
841 | |||
842 | def updateRunOperation(self, **kwargs): |
|
842 | def updateRunOperation(self, **kwargs): | |
843 |
|
843 | |||
844 | opObj = self.getOperationObj(name = 'run') |
|
844 | opObj = self.getOperationObj(name = 'run') | |
845 | opObj.removeParameters() |
|
845 | opObj.removeParameters() | |
846 |
|
846 | |||
847 | opObj.addParameter(name='datatype' , value=self.datatype, format='str') |
|
847 | opObj.addParameter(name='datatype' , value=self.datatype, format='str') | |
848 | opObj.addParameter(name='path' , value=self.path, format='str') |
|
848 | opObj.addParameter(name='path' , value=self.path, format='str') | |
849 | opObj.addParameter(name='startDate' , value=self.startDate, format='date') |
|
849 | opObj.addParameter(name='startDate' , value=self.startDate, format='date') | |
850 | opObj.addParameter(name='endDate' , value=self.endDate, format='date') |
|
850 | opObj.addParameter(name='endDate' , value=self.endDate, format='date') | |
851 | opObj.addParameter(name='startTime' , value=self.startTime, format='time') |
|
851 | opObj.addParameter(name='startTime' , value=self.startTime, format='time') | |
852 | opObj.addParameter(name='endTime' , value=self.endTime, format='time') |
|
852 | opObj.addParameter(name='endTime' , value=self.endTime, format='time') | |
853 |
|
853 | |||
854 | for key, value in kwargs.items(): |
|
854 | for key, value in kwargs.items(): | |
855 | opObj.addParameter(name=key, value=value, format=type(value).__name__) |
|
855 | opObj.addParameter(name=key, value=value, format=type(value).__name__) | |
856 |
|
856 | |||
857 | return opObj |
|
857 | return opObj | |
858 |
|
858 | |||
859 | # def makeXml(self, projectElement): |
|
859 | # def makeXml(self, projectElement): | |
860 | # |
|
860 | # | |
861 | # procUnitElement = SubElement(projectElement, self.ELEMENTNAME) |
|
861 | # procUnitElement = SubElement(projectElement, self.ELEMENTNAME) | |
862 | # procUnitElement.set('id', str(self.id)) |
|
862 | # procUnitElement.set('id', str(self.id)) | |
863 | # procUnitElement.set('name', self.name) |
|
863 | # procUnitElement.set('name', self.name) | |
864 | # procUnitElement.set('datatype', self.datatype) |
|
864 | # procUnitElement.set('datatype', self.datatype) | |
865 | # procUnitElement.set('inputId', str(self.inputId)) |
|
865 | # procUnitElement.set('inputId', str(self.inputId)) | |
866 | # |
|
866 | # | |
867 | # for opConfObj in self.opConfObjList: |
|
867 | # for opConfObj in self.opConfObjList: | |
868 | # opConfObj.makeXml(procUnitElement) |
|
868 | # opConfObj.makeXml(procUnitElement) | |
869 |
|
869 | |||
870 | def readXml(self, upElement): |
|
870 | def readXml(self, upElement): | |
871 |
|
871 | |||
872 | self.id = upElement.get('id') |
|
872 | self.id = upElement.get('id') | |
873 | self.name = upElement.get('name') |
|
873 | self.name = upElement.get('name') | |
874 | self.datatype = upElement.get('datatype') |
|
874 | self.datatype = upElement.get('datatype') | |
875 | self.inputId = upElement.get('inputId') |
|
875 | self.inputId = upElement.get('inputId') | |
876 |
|
876 | |||
877 | if self.ELEMENTNAME == "ReadUnit": |
|
877 | if self.ELEMENTNAME == "ReadUnit": | |
878 | self.datatype = self.datatype.replace("Reader", "") |
|
878 | self.datatype = self.datatype.replace("Reader", "") | |
879 |
|
879 | |||
880 | if self.inputId == 'None': |
|
880 | if self.inputId == 'None': | |
881 | self.inputId = '0' |
|
881 | self.inputId = '0' | |
882 |
|
882 | |||
883 | self.opConfObjList = [] |
|
883 | self.opConfObjList = [] | |
884 |
|
884 | |||
885 | opElementList = upElement.iter(OperationConf().getElementName()) |
|
885 | opElementList = upElement.iter(OperationConf().getElementName()) | |
886 |
|
886 | |||
887 | for opElement in opElementList: |
|
887 | for opElement in opElementList: | |
888 | opConfObj = OperationConf() |
|
888 | opConfObj = OperationConf() | |
889 | opConfObj.readXml(opElement) |
|
889 | opConfObj.readXml(opElement) | |
890 | self.opConfObjList.append(opConfObj) |
|
890 | self.opConfObjList.append(opConfObj) | |
891 |
|
891 | |||
892 | if opConfObj.name == 'run': |
|
892 | if opConfObj.name == 'run': | |
893 | self.path = opConfObj.getParameterValue('path') |
|
893 | self.path = opConfObj.getParameterValue('path') | |
894 | self.startDate = opConfObj.getParameterValue('startDate') |
|
894 | self.startDate = opConfObj.getParameterValue('startDate') | |
895 | self.endDate = opConfObj.getParameterValue('endDate') |
|
895 | self.endDate = opConfObj.getParameterValue('endDate') | |
896 | self.startTime = opConfObj.getParameterValue('startTime') |
|
896 | self.startTime = opConfObj.getParameterValue('startTime') | |
897 | self.endTime = opConfObj.getParameterValue('endTime') |
|
897 | self.endTime = opConfObj.getParameterValue('endTime') | |
898 |
|
898 | |||
899 | class Project(): |
|
899 | class Project(): | |
900 |
|
900 | |||
901 | id = None |
|
901 | id = None | |
902 | name = None |
|
902 | name = None | |
903 | description = None |
|
903 | description = None | |
904 | filename = None |
|
904 | filename = None | |
905 |
|
905 | |||
906 | procUnitConfObjDict = None |
|
906 | procUnitConfObjDict = None | |
907 |
|
907 | |||
908 | ELEMENTNAME = 'Project' |
|
908 | ELEMENTNAME = 'Project' | |
909 |
|
909 | |||
910 | plotterQueue = None |
|
910 | plotterQueue = None | |
911 |
|
911 | |||
912 | def __init__(self, plotter_queue=None): |
|
912 | def __init__(self, plotter_queue=None): | |
913 |
|
913 | |||
914 | self.id = None |
|
914 | self.id = None | |
915 | self.name = None |
|
915 | self.name = None | |
916 | self.description = None |
|
916 | self.description = None | |
917 |
|
917 | |||
918 | self.plotterQueue = plotter_queue |
|
918 | self.plotterQueue = plotter_queue | |
919 |
|
919 | |||
920 | self.procUnitConfObjDict = {} |
|
920 | self.procUnitConfObjDict = {} | |
921 |
|
921 | |||
922 | def __getNewId(self): |
|
922 | def __getNewId(self): | |
923 |
|
923 | |||
924 | idList = self.procUnitConfObjDict.keys() |
|
924 | idList = self.procUnitConfObjDict.keys() | |
925 |
|
925 | |||
926 | id = int(self.id)*10 |
|
926 | id = int(self.id)*10 | |
927 |
|
927 | |||
928 | while True: |
|
928 | while True: | |
929 | id += 1 |
|
929 | id += 1 | |
930 |
|
930 | |||
931 | if str(id) in idList: |
|
931 | if str(id) in idList: | |
932 | continue |
|
932 | continue | |
933 |
|
933 | |||
934 | break |
|
934 | break | |
935 |
|
935 | |||
936 | return str(id) |
|
936 | return str(id) | |
937 |
|
937 | |||
938 | def getElementName(self): |
|
938 | def getElementName(self): | |
939 |
|
939 | |||
940 | return self.ELEMENTNAME |
|
940 | return self.ELEMENTNAME | |
941 |
|
941 | |||
942 | def getId(self): |
|
942 | def getId(self): | |
943 |
|
943 | |||
944 | return self.id |
|
944 | return self.id | |
945 |
|
945 | |||
946 | def updateId(self, new_id): |
|
946 | def updateId(self, new_id): | |
947 |
|
947 | |||
948 | self.id = str(new_id) |
|
948 | self.id = str(new_id) | |
949 |
|
949 | |||
950 | keyList = self.procUnitConfObjDict.keys() |
|
950 | keyList = self.procUnitConfObjDict.keys() | |
951 | keyList.sort() |
|
951 | keyList.sort() | |
952 |
|
952 | |||
953 | n = 1 |
|
953 | n = 1 | |
954 | newProcUnitConfObjDict = {} |
|
954 | newProcUnitConfObjDict = {} | |
955 |
|
955 | |||
956 | for procKey in keyList: |
|
956 | for procKey in keyList: | |
957 |
|
957 | |||
958 | procUnitConfObj = self.procUnitConfObjDict[procKey] |
|
958 | procUnitConfObj = self.procUnitConfObjDict[procKey] | |
959 | idProcUnit = str(int(self.id)*10 + n) |
|
959 | idProcUnit = str(int(self.id)*10 + n) | |
960 | procUnitConfObj.updateId(idProcUnit, parentId = self.id) |
|
960 | procUnitConfObj.updateId(idProcUnit, parentId = self.id) | |
961 |
|
961 | |||
962 | newProcUnitConfObjDict[idProcUnit] = procUnitConfObj |
|
962 | newProcUnitConfObjDict[idProcUnit] = procUnitConfObj | |
963 | n += 1 |
|
963 | n += 1 | |
964 |
|
964 | |||
965 | self.procUnitConfObjDict = newProcUnitConfObjDict |
|
965 | self.procUnitConfObjDict = newProcUnitConfObjDict | |
966 |
|
966 | |||
967 | def setup(self, id, name, description): |
|
967 | def setup(self, id, name, description): | |
968 |
|
968 | |||
969 | self.id = str(id) |
|
969 | self.id = str(id) | |
970 | self.name = name |
|
970 | self.name = name | |
971 | self.description = description |
|
971 | self.description = description | |
972 |
|
972 | |||
973 | def update(self, name, description): |
|
973 | def update(self, name, description): | |
974 |
|
974 | |||
975 | self.name = name |
|
975 | self.name = name | |
976 | self.description = description |
|
976 | self.description = description | |
977 |
|
977 | |||
978 | def addReadUnit(self, id=None, datatype=None, name=None, **kwargs): |
|
978 | def addReadUnit(self, id=None, datatype=None, name=None, **kwargs): | |
979 |
|
979 | |||
980 | if id is None: |
|
980 | if id is None: | |
981 | idReadUnit = self.__getNewId() |
|
981 | idReadUnit = self.__getNewId() | |
982 | else: |
|
982 | else: | |
983 | idReadUnit = str(id) |
|
983 | idReadUnit = str(id) | |
984 |
|
984 | |||
985 | readUnitConfObj = ReadUnitConf() |
|
985 | readUnitConfObj = ReadUnitConf() | |
986 | readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs) |
|
986 | readUnitConfObj.setup(idReadUnit, name, datatype, parentId=self.id, **kwargs) | |
987 |
|
987 | |||
988 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj |
|
988 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj | |
989 |
|
989 | |||
990 | return readUnitConfObj |
|
990 | return readUnitConfObj | |
991 |
|
991 | |||
992 | def addProcUnit(self, inputId='0', datatype=None, name=None): |
|
992 | def addProcUnit(self, inputId='0', datatype=None, name=None): | |
993 |
|
993 | |||
994 | idProcUnit = self.__getNewId() |
|
994 | idProcUnit = self.__getNewId() | |
995 |
|
995 | |||
996 | procUnitConfObj = ProcUnitConf() |
|
996 | procUnitConfObj = ProcUnitConf() | |
997 | procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id) |
|
997 | procUnitConfObj.setup(idProcUnit, name, datatype, inputId, parentId=self.id) | |
998 |
|
998 | |||
999 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj |
|
999 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj | |
1000 |
|
1000 | |||
1001 | return procUnitConfObj |
|
1001 | return procUnitConfObj | |
1002 |
|
1002 | |||
1003 | def removeProcUnit(self, id): |
|
1003 | def removeProcUnit(self, id): | |
1004 |
|
1004 | |||
1005 | if id in self.procUnitConfObjDict.keys(): |
|
1005 | if id in self.procUnitConfObjDict.keys(): | |
1006 | self.procUnitConfObjDict.pop(id) |
|
1006 | self.procUnitConfObjDict.pop(id) | |
1007 |
|
1007 | |||
1008 | def getReadUnitId(self): |
|
1008 | def getReadUnitId(self): | |
1009 |
|
1009 | |||
1010 | readUnitConfObj = self.getReadUnitObj() |
|
1010 | readUnitConfObj = self.getReadUnitObj() | |
1011 |
|
1011 | |||
1012 | return readUnitConfObj.id |
|
1012 | return readUnitConfObj.id | |
1013 |
|
1013 | |||
1014 | def getReadUnitObj(self): |
|
1014 | def getReadUnitObj(self): | |
1015 |
|
1015 | |||
1016 | for obj in self.procUnitConfObjDict.values(): |
|
1016 | for obj in self.procUnitConfObjDict.values(): | |
1017 | if obj.getElementName() == "ReadUnit": |
|
1017 | if obj.getElementName() == "ReadUnit": | |
1018 | return obj |
|
1018 | return obj | |
1019 |
|
1019 | |||
1020 | return None |
|
1020 | return None | |
1021 |
|
1021 | |||
1022 | def getProcUnitObj(self, id=None, name=None): |
|
1022 | def getProcUnitObj(self, id=None, name=None): | |
1023 |
|
1023 | |||
1024 | if id != None: |
|
1024 | if id != None: | |
1025 | return self.procUnitConfObjDict[id] |
|
1025 | return self.procUnitConfObjDict[id] | |
1026 |
|
1026 | |||
1027 | if name != None: |
|
1027 | if name != None: | |
1028 | return self.getProcUnitObjByName(name) |
|
1028 | return self.getProcUnitObjByName(name) | |
1029 |
|
1029 | |||
1030 | return None |
|
1030 | return None | |
1031 |
|
1031 | |||
1032 | def getProcUnitObjByName(self, name): |
|
1032 | def getProcUnitObjByName(self, name): | |
1033 |
|
1033 | |||
1034 | for obj in self.procUnitConfObjDict.values(): |
|
1034 | for obj in self.procUnitConfObjDict.values(): | |
1035 | if obj.name == name: |
|
1035 | if obj.name == name: | |
1036 | return obj |
|
1036 | return obj | |
1037 |
|
1037 | |||
1038 | return None |
|
1038 | return None | |
1039 |
|
1039 | |||
1040 | def procUnitItems(self): |
|
1040 | def procUnitItems(self): | |
1041 |
|
1041 | |||
1042 | return self.procUnitConfObjDict.items() |
|
1042 | return self.procUnitConfObjDict.items() | |
1043 |
|
1043 | |||
1044 | def makeXml(self): |
|
1044 | def makeXml(self): | |
1045 |
|
1045 | |||
1046 | projectElement = Element('Project') |
|
1046 | projectElement = Element('Project') | |
1047 | projectElement.set('id', str(self.id)) |
|
1047 | projectElement.set('id', str(self.id)) | |
1048 | projectElement.set('name', self.name) |
|
1048 | projectElement.set('name', self.name) | |
1049 | projectElement.set('description', self.description) |
|
1049 | projectElement.set('description', self.description) | |
1050 |
|
1050 | |||
1051 | for procUnitConfObj in self.procUnitConfObjDict.values(): |
|
1051 | for procUnitConfObj in self.procUnitConfObjDict.values(): | |
1052 | procUnitConfObj.makeXml(projectElement) |
|
1052 | procUnitConfObj.makeXml(projectElement) | |
1053 |
|
1053 | |||
1054 | self.projectElement = projectElement |
|
1054 | self.projectElement = projectElement | |
1055 |
|
1055 | |||
1056 | def writeXml(self, filename=None): |
|
1056 | def writeXml(self, filename=None): | |
1057 |
|
1057 | |||
1058 | if filename == None: |
|
1058 | if filename == None: | |
1059 | if self.filename: |
|
1059 | if self.filename: | |
1060 | filename = self.filename |
|
1060 | filename = self.filename | |
1061 | else: |
|
1061 | else: | |
1062 | filename = "schain.xml" |
|
1062 | filename = "schain.xml" | |
1063 |
|
1063 | |||
1064 | if not filename: |
|
1064 | if not filename: | |
1065 | print "filename has not been defined. Use setFilename(filename) for do it." |
|
1065 | print "filename has not been defined. Use setFilename(filename) for do it." | |
1066 | return 0 |
|
1066 | return 0 | |
1067 |
|
1067 | |||
1068 | abs_file = os.path.abspath(filename) |
|
1068 | abs_file = os.path.abspath(filename) | |
1069 |
|
1069 | |||
1070 | if not os.access(os.path.dirname(abs_file), os.W_OK): |
|
1070 | if not os.access(os.path.dirname(abs_file), os.W_OK): | |
1071 | print "No write permission on %s" %os.path.dirname(abs_file) |
|
1071 | print "No write permission on %s" %os.path.dirname(abs_file) | |
1072 | return 0 |
|
1072 | return 0 | |
1073 |
|
1073 | |||
1074 | if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)): |
|
1074 | if os.path.isfile(abs_file) and not(os.access(abs_file, os.W_OK)): | |
1075 | print "File %s already exists and it could not be overwriten" %abs_file |
|
1075 | print "File %s already exists and it could not be overwriten" %abs_file | |
1076 | return 0 |
|
1076 | return 0 | |
1077 |
|
1077 | |||
1078 | self.makeXml() |
|
1078 | self.makeXml() | |
1079 |
|
1079 | |||
1080 | ElementTree(self.projectElement).write(abs_file, method='xml') |
|
1080 | ElementTree(self.projectElement).write(abs_file, method='xml') | |
1081 |
|
1081 | |||
1082 | self.filename = abs_file |
|
1082 | self.filename = abs_file | |
1083 |
|
1083 | |||
1084 | return 1 |
|
1084 | return 1 | |
1085 |
|
1085 | |||
1086 | def readXml(self, filename = None): |
|
1086 | def readXml(self, filename = None): | |
1087 |
|
1087 | |||
1088 | if not filename: |
|
1088 | if not filename: | |
1089 | print "filename is not defined" |
|
1089 | print "filename is not defined" | |
1090 | return 0 |
|
1090 | return 0 | |
1091 |
|
1091 | |||
1092 | abs_file = os.path.abspath(filename) |
|
1092 | abs_file = os.path.abspath(filename) | |
1093 |
|
1093 | |||
1094 | if not os.path.isfile(abs_file): |
|
1094 | if not os.path.isfile(abs_file): | |
1095 | print "%s file does not exist" %abs_file |
|
1095 | print "%s file does not exist" %abs_file | |
1096 | return 0 |
|
1096 | return 0 | |
1097 |
|
1097 | |||
1098 | self.projectElement = None |
|
1098 | self.projectElement = None | |
1099 | self.procUnitConfObjDict = {} |
|
1099 | self.procUnitConfObjDict = {} | |
1100 |
|
1100 | |||
1101 | try: |
|
1101 | try: | |
1102 | self.projectElement = ElementTree().parse(abs_file) |
|
1102 | self.projectElement = ElementTree().parse(abs_file) | |
1103 | except: |
|
1103 | except: | |
1104 | print "Error reading %s, verify file format" %filename |
|
1104 | print "Error reading %s, verify file format" %filename | |
1105 | return 0 |
|
1105 | return 0 | |
1106 |
|
1106 | |||
1107 | self.project = self.projectElement.tag |
|
1107 | self.project = self.projectElement.tag | |
1108 |
|
1108 | |||
1109 | self.id = self.projectElement.get('id') |
|
1109 | self.id = self.projectElement.get('id') | |
1110 | self.name = self.projectElement.get('name') |
|
1110 | self.name = self.projectElement.get('name') | |
1111 | self.description = self.projectElement.get('description') |
|
1111 | self.description = self.projectElement.get('description') | |
1112 |
|
1112 | |||
1113 | readUnitElementList = self.projectElement.iter(ReadUnitConf().getElementName()) |
|
1113 | readUnitElementList = self.projectElement.iter(ReadUnitConf().getElementName()) | |
1114 |
|
1114 | |||
1115 | for readUnitElement in readUnitElementList: |
|
1115 | for readUnitElement in readUnitElementList: | |
1116 | readUnitConfObj = ReadUnitConf() |
|
1116 | readUnitConfObj = ReadUnitConf() | |
1117 | readUnitConfObj.readXml(readUnitElement) |
|
1117 | readUnitConfObj.readXml(readUnitElement) | |
1118 |
|
1118 | |||
1119 | if readUnitConfObj.parentId == None: |
|
1119 | if readUnitConfObj.parentId == None: | |
1120 | readUnitConfObj.parentId = self.id |
|
1120 | readUnitConfObj.parentId = self.id | |
1121 |
|
1121 | |||
1122 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj |
|
1122 | self.procUnitConfObjDict[readUnitConfObj.getId()] = readUnitConfObj | |
1123 |
|
1123 | |||
1124 | procUnitElementList = self.projectElement.iter(ProcUnitConf().getElementName()) |
|
1124 | procUnitElementList = self.projectElement.iter(ProcUnitConf().getElementName()) | |
1125 |
|
1125 | |||
1126 | for procUnitElement in procUnitElementList: |
|
1126 | for procUnitElement in procUnitElementList: | |
1127 | procUnitConfObj = ProcUnitConf() |
|
1127 | procUnitConfObj = ProcUnitConf() | |
1128 | procUnitConfObj.readXml(procUnitElement) |
|
1128 | procUnitConfObj.readXml(procUnitElement) | |
1129 |
|
1129 | |||
1130 | if procUnitConfObj.parentId == None: |
|
1130 | if procUnitConfObj.parentId == None: | |
1131 | procUnitConfObj.parentId = self.id |
|
1131 | procUnitConfObj.parentId = self.id | |
1132 |
|
1132 | |||
1133 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj |
|
1133 | self.procUnitConfObjDict[procUnitConfObj.getId()] = procUnitConfObj | |
1134 |
|
1134 | |||
1135 | self.filename = abs_file |
|
1135 | self.filename = abs_file | |
1136 |
|
1136 | |||
1137 | return 1 |
|
1137 | return 1 | |
1138 |
|
1138 | |||
1139 | def printattr(self): |
|
1139 | def printattr(self): | |
1140 |
|
1140 | |||
1141 | print "Project[%s]: name = %s, description = %s" %(self.id, |
|
1141 | print "Project[%s]: name = %s, description = %s" %(self.id, | |
1142 | self.name, |
|
1142 | self.name, | |
1143 | self.description) |
|
1143 | self.description) | |
1144 |
|
1144 | |||
1145 | for procUnitConfObj in self.procUnitConfObjDict.values(): |
|
1145 | for procUnitConfObj in self.procUnitConfObjDict.values(): | |
1146 | procUnitConfObj.printattr() |
|
1146 | procUnitConfObj.printattr() | |
1147 |
|
1147 | |||
1148 | def createObjects(self): |
|
1148 | def createObjects(self): | |
1149 |
|
1149 | |||
1150 | for procUnitConfObj in self.procUnitConfObjDict.values(): |
|
1150 | for procUnitConfObj in self.procUnitConfObjDict.values(): | |
1151 | procUnitConfObj.createObjects(self.plotterQueue) |
|
1151 | procUnitConfObj.createObjects(self.plotterQueue) | |
1152 |
|
1152 | |||
1153 | def __connect(self, objIN, thisObj): |
|
1153 | def __connect(self, objIN, thisObj): | |
1154 |
|
1154 | |||
1155 | thisObj.setInput(objIN.getOutputObj()) |
|
1155 | thisObj.setInput(objIN.getOutputObj()) | |
1156 |
|
1156 | |||
1157 | def connectObjects(self): |
|
1157 | def connectObjects(self): | |
1158 |
|
1158 | |||
1159 | for thisPUConfObj in self.procUnitConfObjDict.values(): |
|
1159 | for thisPUConfObj in self.procUnitConfObjDict.values(): | |
1160 |
|
1160 | |||
1161 | inputId = thisPUConfObj.getInputId() |
|
1161 | inputId = thisPUConfObj.getInputId() | |
1162 |
|
1162 | |||
1163 | if int(inputId) == 0: |
|
1163 | if int(inputId) == 0: | |
1164 | continue |
|
1164 | continue | |
1165 |
|
1165 | |||
1166 | #Get input object |
|
1166 | #Get input object | |
1167 | puConfINObj = self.procUnitConfObjDict[inputId] |
|
1167 | puConfINObj = self.procUnitConfObjDict[inputId] | |
1168 | puObjIN = puConfINObj.getProcUnitObj() |
|
1168 | puObjIN = puConfINObj.getProcUnitObj() | |
1169 |
|
1169 | |||
1170 | #Get current object |
|
1170 | #Get current object | |
1171 | thisPUObj = thisPUConfObj.getProcUnitObj() |
|
1171 | thisPUObj = thisPUConfObj.getProcUnitObj() | |
1172 |
|
1172 | |||
1173 | self.__connect(puObjIN, thisPUObj) |
|
1173 | self.__connect(puObjIN, thisPUObj) | |
1174 |
|
1174 | |||
1175 | def __handleError(self, procUnitConfObj, send_email=True): |
|
1175 | def __handleError(self, procUnitConfObj, send_email=True): | |
1176 |
|
1176 | |||
1177 | import socket |
|
1177 | import socket | |
1178 |
|
1178 | |||
1179 | err = traceback.format_exception(sys.exc_info()[0], |
|
1179 | err = traceback.format_exception(sys.exc_info()[0], | |
1180 | sys.exc_info()[1], |
|
1180 | sys.exc_info()[1], | |
1181 | sys.exc_info()[2]) |
|
1181 | sys.exc_info()[2]) | |
1182 |
|
1182 | |||
1183 | print "***** Error occurred in %s *****" %(procUnitConfObj.name) |
|
1183 | print "***** Error occurred in %s *****" %(procUnitConfObj.name) | |
1184 | print "***** %s" %err[-1] |
|
1184 | print "***** %s" %err[-1] | |
1185 |
|
1185 | |||
1186 | message = "".join(err) |
|
1186 | message = "".join(err) | |
1187 |
|
1187 | |||
1188 | sys.stderr.write(message) |
|
1188 | sys.stderr.write(message) | |
1189 |
|
1189 | |||
1190 | if not send_email: |
|
1190 | if not send_email: | |
1191 | return |
|
1191 | return | |
1192 |
|
1192 | |||
1193 | subject = "SChain v%s: Error running %s\n" %(schainpy.__version__, procUnitConfObj.name) |
|
1193 | subject = "SChain v%s: Error running %s\n" %(schainpy.__version__, procUnitConfObj.name) | |
1194 |
|
1194 | |||
1195 | subtitle = "%s: %s\n" %(procUnitConfObj.getElementName() ,procUnitConfObj.name) |
|
1195 | subtitle = "%s: %s\n" %(procUnitConfObj.getElementName() ,procUnitConfObj.name) | |
1196 | subtitle += "Hostname: %s\n" %socket.gethostbyname(socket.gethostname()) |
|
1196 | subtitle += "Hostname: %s\n" %socket.gethostbyname(socket.gethostname()) | |
1197 | subtitle += "Working directory: %s\n" %os.path.abspath("./") |
|
1197 | subtitle += "Working directory: %s\n" %os.path.abspath("./") | |
1198 | subtitle += "Configuration file: %s\n" %self.filename |
|
1198 | subtitle += "Configuration file: %s\n" %self.filename | |
1199 | subtitle += "Time: %s\n" %str(datetime.datetime.now()) |
|
1199 | subtitle += "Time: %s\n" %str(datetime.datetime.now()) | |
1200 |
|
1200 | |||
1201 | readUnitConfObj = self.getReadUnitObj() |
|
1201 | readUnitConfObj = self.getReadUnitObj() | |
1202 | if readUnitConfObj: |
|
1202 | if readUnitConfObj: | |
1203 | subtitle += "\nInput parameters:\n" |
|
1203 | subtitle += "\nInput parameters:\n" | |
1204 | subtitle += "[Data path = %s]\n" %readUnitConfObj.path |
|
1204 | subtitle += "[Data path = %s]\n" %readUnitConfObj.path | |
1205 | subtitle += "[Data type = %s]\n" %readUnitConfObj.datatype |
|
1205 | subtitle += "[Data type = %s]\n" %readUnitConfObj.datatype | |
1206 | subtitle += "[Start date = %s]\n" %readUnitConfObj.startDate |
|
1206 | subtitle += "[Start date = %s]\n" %readUnitConfObj.startDate | |
1207 | subtitle += "[End date = %s]\n" %readUnitConfObj.endDate |
|
1207 | subtitle += "[End date = %s]\n" %readUnitConfObj.endDate | |
1208 | subtitle += "[Start time = %s]\n" %readUnitConfObj.startTime |
|
1208 | subtitle += "[Start time = %s]\n" %readUnitConfObj.startTime | |
1209 | subtitle += "[End time = %s]\n" %readUnitConfObj.endTime |
|
1209 | subtitle += "[End time = %s]\n" %readUnitConfObj.endTime | |
1210 |
|
1210 | |||
1211 | adminObj = schainpy.admin.SchainNotify() |
|
1211 | adminObj = schainpy.admin.SchainNotify() | |
1212 | adminObj.sendAlert(message=message, |
|
1212 | adminObj.sendAlert(message=message, | |
1213 | subject=subject, |
|
1213 | subject=subject, | |
1214 | subtitle=subtitle, |
|
1214 | subtitle=subtitle, | |
1215 | filename=self.filename) |
|
1215 | filename=self.filename) | |
1216 |
|
1216 | |||
1217 | def isPaused(self): |
|
1217 | def isPaused(self): | |
1218 | return 0 |
|
1218 | return 0 | |
1219 |
|
1219 | |||
1220 | def isStopped(self): |
|
1220 | def isStopped(self): | |
1221 | return 0 |
|
1221 | return 0 | |
1222 |
|
1222 | |||
1223 | def runController(self): |
|
1223 | def runController(self): | |
1224 | """ |
|
1224 | """ | |
1225 | returns 0 when this process has been stopped, 1 otherwise |
|
1225 | returns 0 when this process has been stopped, 1 otherwise | |
1226 | """ |
|
1226 | """ | |
1227 |
|
1227 | |||
1228 | if self.isPaused(): |
|
1228 | if self.isPaused(): | |
1229 | print "Process suspended" |
|
1229 | print "Process suspended" | |
1230 |
|
1230 | |||
1231 | while True: |
|
1231 | while True: | |
1232 | sleep(0.1) |
|
1232 | sleep(0.1) | |
1233 |
|
1233 | |||
1234 | if not self.isPaused(): |
|
1234 | if not self.isPaused(): | |
1235 | break |
|
1235 | break | |
1236 |
|
1236 | |||
1237 | if self.isStopped(): |
|
1237 | if self.isStopped(): | |
1238 | break |
|
1238 | break | |
1239 |
|
1239 | |||
1240 | print "Process reinitialized" |
|
1240 | print "Process reinitialized" | |
1241 |
|
1241 | |||
1242 | if self.isStopped(): |
|
1242 | if self.isStopped(): | |
1243 | print "Process stopped" |
|
1243 | print "Process stopped" | |
1244 | return 0 |
|
1244 | return 0 | |
1245 |
|
1245 | |||
1246 | return 1 |
|
1246 | return 1 | |
1247 |
|
1247 | |||
1248 | def setFilename(self, filename): |
|
1248 | def setFilename(self, filename): | |
1249 |
|
1249 | |||
1250 | self.filename = filename |
|
1250 | self.filename = filename | |
1251 |
|
1251 | |||
1252 | def setPlotterQueue(self, plotter_queue): |
|
1252 | def setPlotterQueue(self, plotter_queue): | |
1253 |
|
1253 | |||
1254 | raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class" |
|
1254 | raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class" | |
1255 |
|
1255 | |||
1256 | def getPlotterQueue(self): |
|
1256 | def getPlotterQueue(self): | |
1257 |
|
1257 | |||
1258 | raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class" |
|
1258 | raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class" | |
1259 |
|
1259 | |||
1260 | def useExternalPlotter(self): |
|
1260 | def useExternalPlotter(self): | |
1261 |
|
1261 | |||
1262 | raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class" |
|
1262 | raise NotImplementedError, "Use schainpy.controller_api.ControllerThread instead Project class" | |
1263 |
|
1263 | |||
1264 | def run(self): |
|
1264 | def run(self): | |
1265 |
|
1265 | |||
1266 |
|
1266 | |||
1267 | print "*"*60 |
|
1267 | print "*"*60 | |
1268 | print " Starting SIGNAL CHAIN PROCESSING v%s " %schainpy.__version__ |
|
1268 | print " Starting SIGNAL CHAIN PROCESSING v%s " %schainpy.__version__ | |
1269 | print "*"*60 |
|
1269 | print "*"*60 | |
1270 |
|
1270 | |||
1271 |
|
1271 | |||
1272 | keyList = self.procUnitConfObjDict.keys() |
|
1272 | keyList = self.procUnitConfObjDict.keys() | |
1273 | keyList.sort() |
|
1273 | keyList.sort() | |
1274 |
|
1274 | |||
1275 | while(True): |
|
1275 | while(True): | |
1276 |
|
1276 | |||
1277 | is_ok = False |
|
1277 | is_ok = False | |
1278 |
|
1278 | |||
1279 | for procKey in keyList: |
|
1279 | for procKey in keyList: | |
1280 | # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id) |
|
1280 | # print "Running the '%s' process with %s" %(procUnitConfObj.name, procUnitConfObj.id) | |
1281 |
|
1281 | |||
1282 | procUnitConfObj = self.procUnitConfObjDict[procKey] |
|
1282 | procUnitConfObj = self.procUnitConfObjDict[procKey] | |
1283 |
|
1283 | |||
1284 | try: |
|
1284 | try: | |
1285 | sts = procUnitConfObj.run() |
|
1285 | sts = procUnitConfObj.run() | |
1286 | is_ok = is_ok or sts |
|
1286 | is_ok = is_ok or sts | |
1287 | except KeyboardInterrupt: |
|
1287 | except KeyboardInterrupt: | |
1288 | is_ok = False |
|
1288 | is_ok = False | |
1289 | break |
|
1289 | break | |
1290 | except ValueError, e: |
|
1290 | except ValueError, e: | |
1291 | sleep(0.5) |
|
1291 | sleep(0.5) | |
1292 | self.__handleError(procUnitConfObj, send_email=True) |
|
1292 | self.__handleError(procUnitConfObj, send_email=True) | |
1293 | is_ok = False |
|
1293 | is_ok = False | |
1294 | break |
|
1294 | break | |
1295 | except: |
|
1295 | except: | |
1296 | sleep(0.5) |
|
1296 | sleep(0.5) | |
1297 | self.__handleError(procUnitConfObj) |
|
1297 | self.__handleError(procUnitConfObj) | |
1298 | is_ok = False |
|
1298 | is_ok = False | |
1299 | break |
|
1299 | break | |
1300 |
|
1300 | |||
1301 | #If every process unit finished so end process |
|
1301 | #If every process unit finished so end process | |
1302 | if not(is_ok): |
|
1302 | if not(is_ok): | |
1303 | # print "Every process unit have finished" |
|
1303 | # print "Every process unit have finished" | |
1304 | break |
|
1304 | break | |
1305 |
|
1305 | |||
1306 | if not self.runController(): |
|
1306 | if not self.runController(): | |
1307 | break |
|
1307 | break | |
1308 |
|
1308 | |||
1309 | #Closing every process |
|
1309 | #Closing every process | |
1310 | for procKey in keyList: |
|
1310 | for procKey in keyList: | |
1311 | procUnitConfObj = self.procUnitConfObjDict[procKey] |
|
1311 | procUnitConfObj = self.procUnitConfObjDict[procKey] | |
1312 | procUnitConfObj.close() |
|
1312 | procUnitConfObj.close() | |
1313 |
|
1313 | |||
1314 | print "Process finished" |
|
1314 | print "Process finished" | |
1315 |
|
1315 | |||
1316 | def start(self): |
|
1316 | def start(self, filename=None): | |
1317 |
|
1317 | |||
1318 | self.writeXml() |
|
1318 | self.writeXml(filename) | |
1319 | self.createObjects() |
|
1319 | self.createObjects() | |
1320 | self.connectObjects() |
|
1320 | self.connectObjects() | |
1321 | self.run() |
|
1321 | self.run() |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file |
@@ -1,1750 +1,1794 | |||||
1 | ''' |
|
1 | ''' | |
2 | Created on Jul 2, 2014 |
|
2 | Created on Jul 2, 2014 | |
3 |
|
3 | |||
4 | @author: roj-idl71 |
|
4 | @author: roj-idl71 | |
5 | ''' |
|
5 | ''' | |
6 | import os |
|
6 | import os | |
7 | import sys |
|
7 | import sys | |
8 | import glob |
|
8 | import glob | |
9 | import time |
|
9 | import time | |
10 | import numpy |
|
10 | import numpy | |
11 | import fnmatch |
|
11 | import fnmatch | |
|
12 | import inspect | |||
12 | import time, datetime |
|
13 | import time, datetime | |
13 | #import h5py |
|
14 | #import h5py | |
14 | import traceback |
|
15 | import traceback | |
15 |
|
16 | |||
16 | try: |
|
17 | try: | |
17 | from gevent import sleep |
|
18 | from gevent import sleep | |
18 | except: |
|
19 | except: | |
19 | from time import sleep |
|
20 | from time import sleep | |
20 |
|
21 | |||
21 | from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader |
|
22 | from schainpy.model.data.jroheaderIO import PROCFLAG, BasicHeader, SystemHeader, RadarControllerHeader, ProcessingHeader | |
22 | from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width |
|
23 | from schainpy.model.data.jroheaderIO import get_dtype_index, get_numpy_dtype, get_procflag_dtype, get_dtype_width | |
23 |
|
24 | |||
24 | LOCALTIME = True |
|
25 | LOCALTIME = True | |
25 |
|
26 | |||
26 | def isNumber(cad): |
|
27 | def isNumber(cad): | |
27 | """ |
|
28 | """ | |
28 | Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero. |
|
29 | Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero. | |
29 |
|
30 | |||
30 | Excepciones: |
|
31 | Excepciones: | |
31 | Si un determinado string no puede ser convertido a numero |
|
32 | Si un determinado string no puede ser convertido a numero | |
32 | Input: |
|
33 | Input: | |
33 | str, string al cual se le analiza para determinar si convertible a un numero o no |
|
34 | str, string al cual se le analiza para determinar si convertible a un numero o no | |
34 |
|
35 | |||
35 | Return: |
|
36 | Return: | |
36 | True : si el string es uno numerico |
|
37 | True : si el string es uno numerico | |
37 | False : no es un string numerico |
|
38 | False : no es un string numerico | |
38 | """ |
|
39 | """ | |
39 | try: |
|
40 | try: | |
40 | float( cad ) |
|
41 | float( cad ) | |
41 | return True |
|
42 | return True | |
42 | except: |
|
43 | except: | |
43 | return False |
|
44 | return False | |
44 |
|
45 | |||
45 | def isFileInEpoch(filename, startUTSeconds, endUTSeconds): |
|
46 | def isFileInEpoch(filename, startUTSeconds, endUTSeconds): | |
46 | """ |
|
47 | """ | |
47 | Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado. |
|
48 | Esta funcion determina si un archivo de datos se encuentra o no dentro del rango de fecha especificado. | |
48 |
|
49 | |||
49 | Inputs: |
|
50 | Inputs: | |
50 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) |
|
51 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) | |
51 |
|
52 | |||
52 | startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en |
|
53 | startUTSeconds : fecha inicial del rango seleccionado. La fecha esta dada en | |
53 | segundos contados desde 01/01/1970. |
|
54 | segundos contados desde 01/01/1970. | |
54 | endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en |
|
55 | endUTSeconds : fecha final del rango seleccionado. La fecha esta dada en | |
55 | segundos contados desde 01/01/1970. |
|
56 | segundos contados desde 01/01/1970. | |
56 |
|
57 | |||
57 | Return: |
|
58 | Return: | |
58 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
59 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
59 | fecha especificado, de lo contrario retorna False. |
|
60 | fecha especificado, de lo contrario retorna False. | |
60 |
|
61 | |||
61 | Excepciones: |
|
62 | Excepciones: | |
62 | Si el archivo no existe o no puede ser abierto |
|
63 | Si el archivo no existe o no puede ser abierto | |
63 | Si la cabecera no puede ser leida. |
|
64 | Si la cabecera no puede ser leida. | |
64 |
|
65 | |||
65 | """ |
|
66 | """ | |
66 | basicHeaderObj = BasicHeader(LOCALTIME) |
|
67 | basicHeaderObj = BasicHeader(LOCALTIME) | |
67 |
|
68 | |||
68 | try: |
|
69 | try: | |
69 | fp = open(filename,'rb') |
|
70 | fp = open(filename,'rb') | |
70 | except IOError: |
|
71 | except IOError: | |
71 | print "The file %s can't be opened" %(filename) |
|
72 | print "The file %s can't be opened" %(filename) | |
72 | return 0 |
|
73 | return 0 | |
73 |
|
74 | |||
74 | sts = basicHeaderObj.read(fp) |
|
75 | sts = basicHeaderObj.read(fp) | |
75 | fp.close() |
|
76 | fp.close() | |
76 |
|
77 | |||
77 | if not(sts): |
|
78 | if not(sts): | |
78 | print "Skipping the file %s because it has not a valid header" %(filename) |
|
79 | print "Skipping the file %s because it has not a valid header" %(filename) | |
79 | return 0 |
|
80 | return 0 | |
80 |
|
81 | |||
81 | if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)): |
|
82 | if not ((startUTSeconds <= basicHeaderObj.utc) and (endUTSeconds > basicHeaderObj.utc)): | |
82 | return 0 |
|
83 | return 0 | |
83 |
|
84 | |||
84 | return 1 |
|
85 | return 1 | |
85 |
|
86 | |||
86 | def isTimeInRange(thisTime, startTime, endTime): |
|
87 | def isTimeInRange(thisTime, startTime, endTime): | |
87 |
|
88 | |||
88 | if endTime >= startTime: |
|
89 | if endTime >= startTime: | |
89 | if (thisTime < startTime) or (thisTime > endTime): |
|
90 | if (thisTime < startTime) or (thisTime > endTime): | |
90 | return 0 |
|
91 | return 0 | |
91 |
|
92 | |||
92 | return 1 |
|
93 | return 1 | |
93 | else: |
|
94 | else: | |
94 | if (thisTime < startTime) and (thisTime > endTime): |
|
95 | if (thisTime < startTime) and (thisTime > endTime): | |
95 | return 0 |
|
96 | return 0 | |
96 |
|
97 | |||
97 | return 1 |
|
98 | return 1 | |
98 |
|
99 | |||
99 | def isFileInTimeRange(filename, startDate, endDate, startTime, endTime): |
|
100 | def isFileInTimeRange(filename, startDate, endDate, startTime, endTime): | |
100 | """ |
|
101 | """ | |
101 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. |
|
102 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. | |
102 |
|
103 | |||
103 | Inputs: |
|
104 | Inputs: | |
104 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) |
|
105 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) | |
105 |
|
106 | |||
106 | startDate : fecha inicial del rango seleccionado en formato datetime.date |
|
107 | startDate : fecha inicial del rango seleccionado en formato datetime.date | |
107 |
|
108 | |||
108 | endDate : fecha final del rango seleccionado en formato datetime.date |
|
109 | endDate : fecha final del rango seleccionado en formato datetime.date | |
109 |
|
110 | |||
110 | startTime : tiempo inicial del rango seleccionado en formato datetime.time |
|
111 | startTime : tiempo inicial del rango seleccionado en formato datetime.time | |
111 |
|
112 | |||
112 | endTime : tiempo final del rango seleccionado en formato datetime.time |
|
113 | endTime : tiempo final del rango seleccionado en formato datetime.time | |
113 |
|
114 | |||
114 | Return: |
|
115 | Return: | |
115 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
116 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
116 | fecha especificado, de lo contrario retorna False. |
|
117 | fecha especificado, de lo contrario retorna False. | |
117 |
|
118 | |||
118 | Excepciones: |
|
119 | Excepciones: | |
119 | Si el archivo no existe o no puede ser abierto |
|
120 | Si el archivo no existe o no puede ser abierto | |
120 | Si la cabecera no puede ser leida. |
|
121 | Si la cabecera no puede ser leida. | |
121 |
|
122 | |||
122 | """ |
|
123 | """ | |
123 |
|
124 | |||
124 |
|
125 | |||
125 | try: |
|
126 | try: | |
126 | fp = open(filename,'rb') |
|
127 | fp = open(filename,'rb') | |
127 | except IOError: |
|
128 | except IOError: | |
128 | print "The file %s can't be opened" %(filename) |
|
129 | print "The file %s can't be opened" %(filename) | |
129 | return None |
|
130 | return None | |
130 |
|
131 | |||
131 | firstBasicHeaderObj = BasicHeader(LOCALTIME) |
|
132 | firstBasicHeaderObj = BasicHeader(LOCALTIME) | |
132 | systemHeaderObj = SystemHeader() |
|
133 | systemHeaderObj = SystemHeader() | |
133 | radarControllerHeaderObj = RadarControllerHeader() |
|
134 | radarControllerHeaderObj = RadarControllerHeader() | |
134 | processingHeaderObj = ProcessingHeader() |
|
135 | processingHeaderObj = ProcessingHeader() | |
135 |
|
136 | |||
136 | lastBasicHeaderObj = BasicHeader(LOCALTIME) |
|
137 | lastBasicHeaderObj = BasicHeader(LOCALTIME) | |
137 |
|
138 | |||
138 | sts = firstBasicHeaderObj.read(fp) |
|
139 | sts = firstBasicHeaderObj.read(fp) | |
139 |
|
140 | |||
140 | if not(sts): |
|
141 | if not(sts): | |
141 | print "[Reading] Skipping the file %s because it has not a valid header" %(filename) |
|
142 | print "[Reading] Skipping the file %s because it has not a valid header" %(filename) | |
142 | return None |
|
143 | return None | |
143 |
|
144 | |||
144 | if not systemHeaderObj.read(fp): |
|
145 | if not systemHeaderObj.read(fp): | |
145 | return None |
|
146 | return None | |
146 |
|
147 | |||
147 | if not radarControllerHeaderObj.read(fp): |
|
148 | if not radarControllerHeaderObj.read(fp): | |
148 | return None |
|
149 | return None | |
149 |
|
150 | |||
150 | if not processingHeaderObj.read(fp): |
|
151 | if not processingHeaderObj.read(fp): | |
151 | return None |
|
152 | return None | |
152 |
|
153 | |||
153 | filesize = os.path.getsize(filename) |
|
154 | filesize = os.path.getsize(filename) | |
154 |
|
155 | |||
155 | offset = processingHeaderObj.blockSize + 24 #header size |
|
156 | offset = processingHeaderObj.blockSize + 24 #header size | |
156 |
|
157 | |||
157 | if filesize <= offset: |
|
158 | if filesize <= offset: | |
158 | print "[Reading] %s: This file has not enough data" %filename |
|
159 | print "[Reading] %s: This file has not enough data" %filename | |
159 | return None |
|
160 | return None | |
160 |
|
161 | |||
161 | fp.seek(-offset, 2) |
|
162 | fp.seek(-offset, 2) | |
162 |
|
163 | |||
163 | sts = lastBasicHeaderObj.read(fp) |
|
164 | sts = lastBasicHeaderObj.read(fp) | |
164 |
|
165 | |||
165 | fp.close() |
|
166 | fp.close() | |
166 |
|
167 | |||
167 | thisDatetime = lastBasicHeaderObj.datatime |
|
168 | thisDatetime = lastBasicHeaderObj.datatime | |
168 | thisTime_last_block = thisDatetime.time() |
|
169 | thisTime_last_block = thisDatetime.time() | |
169 |
|
170 | |||
170 | thisDatetime = firstBasicHeaderObj.datatime |
|
171 | thisDatetime = firstBasicHeaderObj.datatime | |
171 | thisDate = thisDatetime.date() |
|
172 | thisDate = thisDatetime.date() | |
172 | thisTime_first_block = thisDatetime.time() |
|
173 | thisTime_first_block = thisDatetime.time() | |
173 |
|
174 | |||
174 | #General case |
|
175 | #General case | |
175 | # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o |
|
176 | # o>>>>>>>>>>>>>><<<<<<<<<<<<<<o | |
176 | #-----------o----------------------------o----------- |
|
177 | #-----------o----------------------------o----------- | |
177 | # startTime endTime |
|
178 | # startTime endTime | |
178 |
|
179 | |||
179 | if endTime >= startTime: |
|
180 | if endTime >= startTime: | |
180 | if (thisTime_last_block < startTime) or (thisTime_first_block > endTime): |
|
181 | if (thisTime_last_block < startTime) or (thisTime_first_block > endTime): | |
181 | return None |
|
182 | return None | |
182 |
|
183 | |||
183 | return thisDatetime |
|
184 | return thisDatetime | |
184 |
|
185 | |||
185 | #If endTime < startTime then endTime belongs to the next day |
|
186 | #If endTime < startTime then endTime belongs to the next day | |
186 |
|
187 | |||
187 |
|
188 | |||
188 | #<<<<<<<<<<<o o>>>>>>>>>>> |
|
189 | #<<<<<<<<<<<o o>>>>>>>>>>> | |
189 | #-----------o----------------------------o----------- |
|
190 | #-----------o----------------------------o----------- | |
190 | # endTime startTime |
|
191 | # endTime startTime | |
191 |
|
192 | |||
192 | if (thisDate == startDate) and (thisTime_last_block < startTime): |
|
193 | if (thisDate == startDate) and (thisTime_last_block < startTime): | |
193 | return None |
|
194 | return None | |
194 |
|
195 | |||
195 | if (thisDate == endDate) and (thisTime_first_block > endTime): |
|
196 | if (thisDate == endDate) and (thisTime_first_block > endTime): | |
196 | return None |
|
197 | return None | |
197 |
|
198 | |||
198 | if (thisTime_last_block < startTime) and (thisTime_first_block > endTime): |
|
199 | if (thisTime_last_block < startTime) and (thisTime_first_block > endTime): | |
199 | return None |
|
200 | return None | |
200 |
|
201 | |||
201 | return thisDatetime |
|
202 | return thisDatetime | |
202 |
|
203 | |||
203 | def isFolderInDateRange(folder, startDate=None, endDate=None): |
|
204 | def isFolderInDateRange(folder, startDate=None, endDate=None): | |
204 | """ |
|
205 | """ | |
205 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. |
|
206 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. | |
206 |
|
207 | |||
207 | Inputs: |
|
208 | Inputs: | |
208 | folder : nombre completo del directorio. |
|
209 | folder : nombre completo del directorio. | |
209 | Su formato deberia ser "/path_root/?YYYYDDD" |
|
210 | Su formato deberia ser "/path_root/?YYYYDDD" | |
210 |
|
211 | |||
211 | siendo: |
|
212 | siendo: | |
212 | YYYY : Anio (ejemplo 2015) |
|
213 | YYYY : Anio (ejemplo 2015) | |
213 | DDD : Dia del anio (ejemplo 305) |
|
214 | DDD : Dia del anio (ejemplo 305) | |
214 |
|
215 | |||
215 | startDate : fecha inicial del rango seleccionado en formato datetime.date |
|
216 | startDate : fecha inicial del rango seleccionado en formato datetime.date | |
216 |
|
217 | |||
217 | endDate : fecha final del rango seleccionado en formato datetime.date |
|
218 | endDate : fecha final del rango seleccionado en formato datetime.date | |
218 |
|
219 | |||
219 | Return: |
|
220 | Return: | |
220 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
221 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
221 | fecha especificado, de lo contrario retorna False. |
|
222 | fecha especificado, de lo contrario retorna False. | |
222 | Excepciones: |
|
223 | Excepciones: | |
223 | Si el directorio no tiene el formato adecuado |
|
224 | Si el directorio no tiene el formato adecuado | |
224 | """ |
|
225 | """ | |
225 |
|
226 | |||
226 | basename = os.path.basename(folder) |
|
227 | basename = os.path.basename(folder) | |
227 |
|
228 | |||
228 | if not isRadarFolder(basename): |
|
229 | if not isRadarFolder(basename): | |
229 | print "The folder %s has not the rigth format" %folder |
|
230 | print "The folder %s has not the rigth format" %folder | |
230 | return 0 |
|
231 | return 0 | |
231 |
|
232 | |||
232 | if startDate and endDate: |
|
233 | if startDate and endDate: | |
233 | thisDate = getDateFromRadarFolder(basename) |
|
234 | thisDate = getDateFromRadarFolder(basename) | |
234 |
|
235 | |||
235 | if thisDate < startDate: |
|
236 | if thisDate < startDate: | |
236 | return 0 |
|
237 | return 0 | |
237 |
|
238 | |||
238 | if thisDate > endDate: |
|
239 | if thisDate > endDate: | |
239 | return 0 |
|
240 | return 0 | |
240 |
|
241 | |||
241 | return 1 |
|
242 | return 1 | |
242 |
|
243 | |||
243 | def isFileInDateRange(filename, startDate=None, endDate=None): |
|
244 | def isFileInDateRange(filename, startDate=None, endDate=None): | |
244 | """ |
|
245 | """ | |
245 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. |
|
246 | Retorna 1 si el archivo de datos se encuentra dentro del rango de horas especificado. | |
246 |
|
247 | |||
247 | Inputs: |
|
248 | Inputs: | |
248 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) |
|
249 | filename : nombre completo del archivo de datos en formato Jicamarca (.r) | |
249 |
|
250 | |||
250 | Su formato deberia ser "?YYYYDDDsss" |
|
251 | Su formato deberia ser "?YYYYDDDsss" | |
251 |
|
252 | |||
252 | siendo: |
|
253 | siendo: | |
253 | YYYY : Anio (ejemplo 2015) |
|
254 | YYYY : Anio (ejemplo 2015) | |
254 | DDD : Dia del anio (ejemplo 305) |
|
255 | DDD : Dia del anio (ejemplo 305) | |
255 | sss : set |
|
256 | sss : set | |
256 |
|
257 | |||
257 | startDate : fecha inicial del rango seleccionado en formato datetime.date |
|
258 | startDate : fecha inicial del rango seleccionado en formato datetime.date | |
258 |
|
259 | |||
259 | endDate : fecha final del rango seleccionado en formato datetime.date |
|
260 | endDate : fecha final del rango seleccionado en formato datetime.date | |
260 |
|
261 | |||
261 | Return: |
|
262 | Return: | |
262 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de |
|
263 | Boolean : Retorna True si el archivo de datos contiene datos en el rango de | |
263 | fecha especificado, de lo contrario retorna False. |
|
264 | fecha especificado, de lo contrario retorna False. | |
264 | Excepciones: |
|
265 | Excepciones: | |
265 | Si el archivo no tiene el formato adecuado |
|
266 | Si el archivo no tiene el formato adecuado | |
266 | """ |
|
267 | """ | |
267 |
|
268 | |||
268 | basename = os.path.basename(filename) |
|
269 | basename = os.path.basename(filename) | |
269 |
|
270 | |||
270 | if not isRadarFile(basename): |
|
271 | if not isRadarFile(basename): | |
271 | print "The filename %s has not the rigth format" %filename |
|
272 | print "The filename %s has not the rigth format" %filename | |
272 | return 0 |
|
273 | return 0 | |
273 |
|
274 | |||
274 | if startDate and endDate: |
|
275 | if startDate and endDate: | |
275 | thisDate = getDateFromRadarFile(basename) |
|
276 | thisDate = getDateFromRadarFile(basename) | |
276 |
|
277 | |||
277 | if thisDate < startDate: |
|
278 | if thisDate < startDate: | |
278 | return 0 |
|
279 | return 0 | |
279 |
|
280 | |||
280 | if thisDate > endDate: |
|
281 | if thisDate > endDate: | |
281 | return 0 |
|
282 | return 0 | |
282 |
|
283 | |||
283 | return 1 |
|
284 | return 1 | |
284 |
|
285 | |||
285 | def getFileFromSet(path, ext, set): |
|
286 | def getFileFromSet(path, ext, set): | |
286 | validFilelist = [] |
|
287 | validFilelist = [] | |
287 | fileList = os.listdir(path) |
|
288 | fileList = os.listdir(path) | |
288 |
|
289 | |||
289 | # 0 1234 567 89A BCDE |
|
290 | # 0 1234 567 89A BCDE | |
290 | # H YYYY DDD SSS .ext |
|
291 | # H YYYY DDD SSS .ext | |
291 |
|
292 | |||
292 | for thisFile in fileList: |
|
293 | for thisFile in fileList: | |
293 | try: |
|
294 | try: | |
294 | year = int(thisFile[1:5]) |
|
295 | year = int(thisFile[1:5]) | |
295 | doy = int(thisFile[5:8]) |
|
296 | doy = int(thisFile[5:8]) | |
296 | except: |
|
297 | except: | |
297 | continue |
|
298 | continue | |
298 |
|
299 | |||
299 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): |
|
300 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): | |
300 | continue |
|
301 | continue | |
301 |
|
302 | |||
302 | validFilelist.append(thisFile) |
|
303 | validFilelist.append(thisFile) | |
303 |
|
304 | |||
304 | myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set)) |
|
305 | myfile = fnmatch.filter(validFilelist,'*%4.4d%3.3d%3.3d*'%(year,doy,set)) | |
305 |
|
306 | |||
306 | if len(myfile)!= 0: |
|
307 | if len(myfile)!= 0: | |
307 | return myfile[0] |
|
308 | return myfile[0] | |
308 | else: |
|
309 | else: | |
309 | filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower()) |
|
310 | filename = '*%4.4d%3.3d%3.3d%s'%(year,doy,set,ext.lower()) | |
310 | print 'the filename %s does not exist'%filename |
|
311 | print 'the filename %s does not exist'%filename | |
311 | print '...going to the last file: ' |
|
312 | print '...going to the last file: ' | |
312 |
|
313 | |||
313 | if validFilelist: |
|
314 | if validFilelist: | |
314 | validFilelist = sorted( validFilelist, key=str.lower ) |
|
315 | validFilelist = sorted( validFilelist, key=str.lower ) | |
315 | return validFilelist[-1] |
|
316 | return validFilelist[-1] | |
316 |
|
317 | |||
317 | return None |
|
318 | return None | |
318 |
|
319 | |||
319 | def getlastFileFromPath(path, ext): |
|
320 | def getlastFileFromPath(path, ext): | |
320 | """ |
|
321 | """ | |
321 | Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext" |
|
322 | Depura el fileList dejando solo los que cumplan el formato de "PYYYYDDDSSS.ext" | |
322 | al final de la depuracion devuelve el ultimo file de la lista que quedo. |
|
323 | al final de la depuracion devuelve el ultimo file de la lista que quedo. | |
323 |
|
324 | |||
324 | Input: |
|
325 | Input: | |
325 | fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta |
|
326 | fileList : lista conteniendo todos los files (sin path) que componen una determinada carpeta | |
326 | ext : extension de los files contenidos en una carpeta |
|
327 | ext : extension de los files contenidos en una carpeta | |
327 |
|
328 | |||
328 | Return: |
|
329 | Return: | |
329 | El ultimo file de una determinada carpeta, no se considera el path. |
|
330 | El ultimo file de una determinada carpeta, no se considera el path. | |
330 | """ |
|
331 | """ | |
331 | validFilelist = [] |
|
332 | validFilelist = [] | |
332 | fileList = os.listdir(path) |
|
333 | fileList = os.listdir(path) | |
333 |
|
334 | |||
334 | # 0 1234 567 89A BCDE |
|
335 | # 0 1234 567 89A BCDE | |
335 | # H YYYY DDD SSS .ext |
|
336 | # H YYYY DDD SSS .ext | |
336 |
|
337 | |||
337 | for thisFile in fileList: |
|
338 | for thisFile in fileList: | |
338 |
|
339 | |||
339 | year = thisFile[1:5] |
|
340 | year = thisFile[1:5] | |
340 | if not isNumber(year): |
|
341 | if not isNumber(year): | |
341 | continue |
|
342 | continue | |
342 |
|
343 | |||
343 | doy = thisFile[5:8] |
|
344 | doy = thisFile[5:8] | |
344 | if not isNumber(doy): |
|
345 | if not isNumber(doy): | |
345 | continue |
|
346 | continue | |
346 |
|
347 | |||
347 | year = int(year) |
|
348 | year = int(year) | |
348 | doy = int(doy) |
|
349 | doy = int(doy) | |
349 |
|
350 | |||
350 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): |
|
351 | if (os.path.splitext(thisFile)[-1].lower() != ext.lower()): | |
351 | continue |
|
352 | continue | |
352 |
|
353 | |||
353 | validFilelist.append(thisFile) |
|
354 | validFilelist.append(thisFile) | |
354 |
|
355 | |||
355 | if validFilelist: |
|
356 | if validFilelist: | |
356 | validFilelist = sorted( validFilelist, key=str.lower ) |
|
357 | validFilelist = sorted( validFilelist, key=str.lower ) | |
357 | return validFilelist[-1] |
|
358 | return validFilelist[-1] | |
358 |
|
359 | |||
359 | return None |
|
360 | return None | |
360 |
|
361 | |||
361 | def checkForRealPath(path, foldercounter, year, doy, set, ext): |
|
362 | def checkForRealPath(path, foldercounter, year, doy, set, ext): | |
362 | """ |
|
363 | """ | |
363 | Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path, |
|
364 | Por ser Linux Case Sensitive entonces checkForRealPath encuentra el nombre correcto de un path, | |
364 | Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar |
|
365 | Prueba por varias combinaciones de nombres entre mayusculas y minusculas para determinar | |
365 | el path exacto de un determinado file. |
|
366 | el path exacto de un determinado file. | |
366 |
|
367 | |||
367 | Example : |
|
368 | Example : | |
368 | nombre correcto del file es .../.../D2009307/P2009307367.ext |
|
369 | nombre correcto del file es .../.../D2009307/P2009307367.ext | |
369 |
|
370 | |||
370 | Entonces la funcion prueba con las siguientes combinaciones |
|
371 | Entonces la funcion prueba con las siguientes combinaciones | |
371 | .../.../y2009307367.ext |
|
372 | .../.../y2009307367.ext | |
372 | .../.../Y2009307367.ext |
|
373 | .../.../Y2009307367.ext | |
373 | .../.../x2009307/y2009307367.ext |
|
374 | .../.../x2009307/y2009307367.ext | |
374 | .../.../x2009307/Y2009307367.ext |
|
375 | .../.../x2009307/Y2009307367.ext | |
375 | .../.../X2009307/y2009307367.ext |
|
376 | .../.../X2009307/y2009307367.ext | |
376 | .../.../X2009307/Y2009307367.ext |
|
377 | .../.../X2009307/Y2009307367.ext | |
377 | siendo para este caso, la ultima combinacion de letras, identica al file buscado |
|
378 | siendo para este caso, la ultima combinacion de letras, identica al file buscado | |
378 |
|
379 | |||
379 | Return: |
|
380 | Return: | |
380 | Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file |
|
381 | Si encuentra la cobinacion adecuada devuelve el path completo y el nombre del file | |
381 | caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas |
|
382 | caso contrario devuelve None como path y el la ultima combinacion de nombre en mayusculas | |
382 | para el filename |
|
383 | para el filename | |
383 | """ |
|
384 | """ | |
384 | fullfilename = None |
|
385 | fullfilename = None | |
385 | find_flag = False |
|
386 | find_flag = False | |
386 | filename = None |
|
387 | filename = None | |
387 |
|
388 | |||
388 | prefixDirList = [None,'d','D'] |
|
389 | prefixDirList = [None,'d','D'] | |
389 | if ext.lower() == ".r": #voltage |
|
390 | if ext.lower() == ".r": #voltage | |
390 | prefixFileList = ['d','D'] |
|
391 | prefixFileList = ['d','D'] | |
391 | elif ext.lower() == ".pdata": #spectra |
|
392 | elif ext.lower() == ".pdata": #spectra | |
392 | prefixFileList = ['p','P'] |
|
393 | prefixFileList = ['p','P'] | |
393 | else: |
|
394 | else: | |
394 | return None, filename |
|
395 | return None, filename | |
395 |
|
396 | |||
396 | #barrido por las combinaciones posibles |
|
397 | #barrido por las combinaciones posibles | |
397 | for prefixDir in prefixDirList: |
|
398 | for prefixDir in prefixDirList: | |
398 | thispath = path |
|
399 | thispath = path | |
399 | if prefixDir != None: |
|
400 | if prefixDir != None: | |
400 | #formo el nombre del directorio xYYYYDDD (x=d o x=D) |
|
401 | #formo el nombre del directorio xYYYYDDD (x=d o x=D) | |
401 | if foldercounter == 0: |
|
402 | if foldercounter == 0: | |
402 | thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy )) |
|
403 | thispath = os.path.join(path, "%s%04d%03d" % ( prefixDir, year, doy )) | |
403 | else: |
|
404 | else: | |
404 | thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter)) |
|
405 | thispath = os.path.join(path, "%s%04d%03d_%02d" % ( prefixDir, year, doy , foldercounter)) | |
405 | for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D" |
|
406 | for prefixFile in prefixFileList: #barrido por las dos combinaciones posibles de "D" | |
406 | filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext |
|
407 | filename = "%s%04d%03d%03d%s" % ( prefixFile, year, doy, set, ext ) #formo el nombre del file xYYYYDDDSSS.ext | |
407 | fullfilename = os.path.join( thispath, filename ) #formo el path completo |
|
408 | fullfilename = os.path.join( thispath, filename ) #formo el path completo | |
408 |
|
409 | |||
409 | if os.path.exists( fullfilename ): #verifico que exista |
|
410 | if os.path.exists( fullfilename ): #verifico que exista | |
410 | find_flag = True |
|
411 | find_flag = True | |
411 | break |
|
412 | break | |
412 | if find_flag: |
|
413 | if find_flag: | |
413 | break |
|
414 | break | |
414 |
|
415 | |||
415 | if not(find_flag): |
|
416 | if not(find_flag): | |
416 | return None, filename |
|
417 | return None, filename | |
417 |
|
418 | |||
418 | return fullfilename, filename |
|
419 | return fullfilename, filename | |
419 |
|
420 | |||
420 | def isRadarFolder(folder): |
|
421 | def isRadarFolder(folder): | |
421 | try: |
|
422 | try: | |
422 | year = int(folder[1:5]) |
|
423 | year = int(folder[1:5]) | |
423 | doy = int(folder[5:8]) |
|
424 | doy = int(folder[5:8]) | |
424 | except: |
|
425 | except: | |
425 | return 0 |
|
426 | return 0 | |
426 |
|
427 | |||
427 | return 1 |
|
428 | return 1 | |
428 |
|
429 | |||
429 | def isRadarFile(file): |
|
430 | def isRadarFile(file): | |
430 | try: |
|
431 | try: | |
431 | year = int(file[1:5]) |
|
432 | year = int(file[1:5]) | |
432 | doy = int(file[5:8]) |
|
433 | doy = int(file[5:8]) | |
433 | set = int(file[8:11]) |
|
434 | set = int(file[8:11]) | |
434 | except: |
|
435 | except: | |
435 | return 0 |
|
436 | return 0 | |
436 |
|
437 | |||
437 | return 1 |
|
438 | return 1 | |
438 |
|
439 | |||
439 | def getDateFromRadarFile(file): |
|
440 | def getDateFromRadarFile(file): | |
440 | try: |
|
441 | try: | |
441 | year = int(file[1:5]) |
|
442 | year = int(file[1:5]) | |
442 | doy = int(file[5:8]) |
|
443 | doy = int(file[5:8]) | |
443 | set = int(file[8:11]) |
|
444 | set = int(file[8:11]) | |
444 | except: |
|
445 | except: | |
445 | return None |
|
446 | return None | |
446 |
|
447 | |||
447 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1) |
|
448 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1) | |
448 | return thisDate |
|
449 | return thisDate | |
449 |
|
450 | |||
450 | def getDateFromRadarFolder(folder): |
|
451 | def getDateFromRadarFolder(folder): | |
451 | try: |
|
452 | try: | |
452 | year = int(folder[1:5]) |
|
453 | year = int(folder[1:5]) | |
453 | doy = int(folder[5:8]) |
|
454 | doy = int(folder[5:8]) | |
454 | except: |
|
455 | except: | |
455 | return None |
|
456 | return None | |
456 |
|
457 | |||
457 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1) |
|
458 | thisDate = datetime.date(year, 1, 1) + datetime.timedelta(doy-1) | |
458 | return thisDate |
|
459 | return thisDate | |
459 |
|
460 | |||
460 | class JRODataIO: |
|
461 | class JRODataIO: | |
461 |
|
462 | |||
462 | c = 3E8 |
|
463 | c = 3E8 | |
463 |
|
464 | |||
464 | isConfig = False |
|
465 | isConfig = False | |
465 |
|
466 | |||
466 | basicHeaderObj = None |
|
467 | basicHeaderObj = None | |
467 |
|
468 | |||
468 | systemHeaderObj = None |
|
469 | systemHeaderObj = None | |
469 |
|
470 | |||
470 | radarControllerHeaderObj = None |
|
471 | radarControllerHeaderObj = None | |
471 |
|
472 | |||
472 | processingHeaderObj = None |
|
473 | processingHeaderObj = None | |
473 |
|
474 | |||
474 | dtype = None |
|
475 | dtype = None | |
475 |
|
476 | |||
476 | pathList = [] |
|
477 | pathList = [] | |
477 |
|
478 | |||
478 | filenameList = [] |
|
479 | filenameList = [] | |
479 |
|
480 | |||
480 | filename = None |
|
481 | filename = None | |
481 |
|
482 | |||
482 | ext = None |
|
483 | ext = None | |
483 |
|
484 | |||
484 | flagIsNewFile = 1 |
|
485 | flagIsNewFile = 1 | |
485 |
|
486 | |||
486 | flagDiscontinuousBlock = 0 |
|
487 | flagDiscontinuousBlock = 0 | |
487 |
|
488 | |||
488 | flagIsNewBlock = 0 |
|
489 | flagIsNewBlock = 0 | |
489 |
|
490 | |||
490 | fp = None |
|
491 | fp = None | |
491 |
|
492 | |||
492 | firstHeaderSize = 0 |
|
493 | firstHeaderSize = 0 | |
493 |
|
494 | |||
494 | basicHeaderSize = 24 |
|
495 | basicHeaderSize = 24 | |
495 |
|
496 | |||
496 | versionFile = 1103 |
|
497 | versionFile = 1103 | |
497 |
|
498 | |||
498 | fileSize = None |
|
499 | fileSize = None | |
499 |
|
500 | |||
500 | # ippSeconds = None |
|
501 | # ippSeconds = None | |
501 |
|
502 | |||
502 | fileSizeByHeader = None |
|
503 | fileSizeByHeader = None | |
503 |
|
504 | |||
504 | fileIndex = None |
|
505 | fileIndex = None | |
505 |
|
506 | |||
506 | profileIndex = None |
|
507 | profileIndex = None | |
507 |
|
508 | |||
508 | blockIndex = None |
|
509 | blockIndex = None | |
509 |
|
510 | |||
510 | nTotalBlocks = None |
|
511 | nTotalBlocks = None | |
511 |
|
512 | |||
512 | maxTimeStep = 30 |
|
513 | maxTimeStep = 30 | |
513 |
|
514 | |||
514 | lastUTTime = None |
|
515 | lastUTTime = None | |
515 |
|
516 | |||
516 | datablock = None |
|
517 | datablock = None | |
517 |
|
518 | |||
518 | dataOut = None |
|
519 | dataOut = None | |
519 |
|
520 | |||
520 | blocksize = None |
|
521 | blocksize = None | |
521 |
|
522 | |||
522 | getByBlock = False |
|
523 | getByBlock = False | |
523 |
|
524 | |||
524 | def __init__(self): |
|
525 | def __init__(self): | |
525 |
|
526 | |||
526 | raise NotImplementedError |
|
527 | raise NotImplementedError | |
527 |
|
528 | |||
528 | def run(self): |
|
529 | def run(self): | |
529 |
|
530 | |||
530 | raise NotImplementedError |
|
531 | raise NotImplementedError | |
531 |
|
532 | |||
532 | def getDtypeWidth(self): |
|
533 | def getDtypeWidth(self): | |
533 |
|
534 | |||
534 | dtype_index = get_dtype_index(self.dtype) |
|
535 | dtype_index = get_dtype_index(self.dtype) | |
535 | dtype_width = get_dtype_width(dtype_index) |
|
536 | dtype_width = get_dtype_width(dtype_index) | |
536 |
|
537 | |||
537 | return dtype_width |
|
538 | return dtype_width | |
538 |
|
539 | |||
|
540 | def getAllowedArgs(self): | |||
|
541 | return inspect.getargspec(self.run).args | |||
|
542 | ||||
539 | class JRODataReader(JRODataIO): |
|
543 | class JRODataReader(JRODataIO): | |
540 |
|
544 | |||
541 |
|
545 | |||
542 | online = 0 |
|
546 | online = 0 | |
543 |
|
547 | |||
544 | realtime = 0 |
|
548 | realtime = 0 | |
545 |
|
549 | |||
546 | nReadBlocks = 0 |
|
550 | nReadBlocks = 0 | |
547 |
|
551 | |||
548 | delay = 10 #number of seconds waiting a new file |
|
552 | delay = 10 #number of seconds waiting a new file | |
549 |
|
553 | |||
550 | nTries = 3 #quantity tries |
|
554 | nTries = 3 #quantity tries | |
551 |
|
555 | |||
552 | nFiles = 3 #number of files for searching |
|
556 | nFiles = 3 #number of files for searching | |
553 |
|
557 | |||
554 | path = None |
|
558 | path = None | |
555 |
|
559 | |||
556 | foldercounter = 0 |
|
560 | foldercounter = 0 | |
557 |
|
561 | |||
558 | flagNoMoreFiles = 0 |
|
562 | flagNoMoreFiles = 0 | |
559 |
|
563 | |||
560 | datetimeList = [] |
|
564 | datetimeList = [] | |
561 |
|
565 | |||
562 | __isFirstTimeOnline = 1 |
|
566 | __isFirstTimeOnline = 1 | |
563 |
|
567 | |||
564 | __printInfo = True |
|
568 | __printInfo = True | |
565 |
|
569 | |||
566 | profileIndex = None |
|
570 | profileIndex = None | |
567 |
|
571 | |||
568 | nTxs = 1 |
|
572 | nTxs = 1 | |
569 |
|
573 | |||
570 | txIndex = None |
|
574 | txIndex = None | |
571 |
|
575 | |||
572 | #Added-------------------- |
|
576 | #Added-------------------- | |
573 |
|
577 | |||
574 | selBlocksize = None |
|
578 | selBlocksize = None | |
575 |
|
579 | |||
576 | selBlocktime = None |
|
580 | selBlocktime = None | |
577 |
|
581 | |||
578 |
|
582 | |||
579 | def __init__(self): |
|
583 | def __init__(self): | |
580 |
|
584 | |||
581 | """ |
|
585 | """ | |
582 | This class is used to find data files |
|
586 | This class is used to find data files | |
583 |
|
587 | |||
584 | Example: |
|
588 | Example: | |
585 | reader = JRODataReader() |
|
589 | reader = JRODataReader() | |
586 | fileList = reader.findDataFiles() |
|
590 | fileList = reader.findDataFiles() | |
587 |
|
591 | |||
588 | """ |
|
592 | """ | |
589 | pass |
|
593 | pass | |
590 |
|
594 | |||
591 |
|
595 | |||
592 | def createObjByDefault(self): |
|
596 | def createObjByDefault(self): | |
593 | """ |
|
597 | """ | |
594 |
|
598 | |||
595 | """ |
|
599 | """ | |
596 | raise NotImplementedError |
|
600 | raise NotImplementedError | |
597 |
|
601 | |||
598 | def getBlockDimension(self): |
|
602 | def getBlockDimension(self): | |
599 |
|
603 | |||
600 | raise NotImplementedError |
|
604 | raise NotImplementedError | |
601 |
|
605 | |||
602 | def __searchFilesOffLine(self, |
|
606 | def __searchFilesOffLine(self, | |
603 | path, |
|
607 | path, | |
604 | startDate=None, |
|
608 | startDate=None, | |
605 | endDate=None, |
|
609 | endDate=None, | |
606 | startTime=datetime.time(0,0,0), |
|
610 | startTime=datetime.time(0,0,0), | |
607 | endTime=datetime.time(23,59,59), |
|
611 | endTime=datetime.time(23,59,59), | |
608 | set=None, |
|
612 | set=None, | |
609 | expLabel='', |
|
613 | expLabel='', | |
610 | ext='.r', |
|
614 | ext='.r', | |
611 | queue=None, |
|
615 | queue=None, | |
612 | cursor=None, |
|
616 | cursor=None, | |
613 | skip=None, |
|
617 | skip=None, | |
614 | walk=True): |
|
618 | walk=True): | |
615 |
|
619 | |||
616 | self.filenameList = [] |
|
620 | self.filenameList = [] | |
617 | self.datetimeList = [] |
|
621 | self.datetimeList = [] | |
618 |
|
622 | |||
619 | pathList = [] |
|
623 | pathList = [] | |
620 |
|
624 | |||
621 | dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True) |
|
625 | dateList, pathList = self.findDatafiles(path, startDate, endDate, expLabel, ext, walk, include_path=True) | |
622 |
|
626 | |||
623 | if dateList == []: |
|
627 | if dateList == []: | |
624 | # print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path) |
|
628 | # print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path) | |
625 | return None, None |
|
629 | return None, None | |
626 |
|
630 | |||
627 | if len(dateList) > 1: |
|
631 | if len(dateList) > 1: | |
628 | print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList)) |
|
632 | print "[Reading] Data found for date range [%s - %s]: total days = %d" %(startDate, endDate, len(dateList)) | |
629 | else: |
|
633 | else: | |
630 | print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0]) |
|
634 | print "[Reading] Data found for date range [%s - %s]: date = %s" %(startDate, endDate, dateList[0]) | |
631 |
|
635 | |||
632 | filenameList = [] |
|
636 | filenameList = [] | |
633 | datetimeList = [] |
|
637 | datetimeList = [] | |
634 |
|
638 | |||
635 | for thisPath in pathList: |
|
639 | for thisPath in pathList: | |
636 | # thisPath = pathList[pathDict[file]] |
|
640 | # thisPath = pathList[pathDict[file]] | |
637 |
|
641 | |||
638 | fileList = glob.glob1(thisPath, "*%s" %ext) |
|
642 | fileList = glob.glob1(thisPath, "*%s" %ext) | |
639 | fileList.sort() |
|
643 | fileList.sort() | |
640 |
|
644 | |||
641 | skippedFileList = [] |
|
645 | skippedFileList = [] | |
642 |
|
646 | |||
643 | if cursor is not None and skip is not None: |
|
647 | if cursor is not None and skip is not None: | |
644 | # if cursor*skip > len(fileList): |
|
648 | # if cursor*skip > len(fileList): | |
645 | if skip == 0: |
|
649 | if skip == 0: | |
646 | if queue is not None: |
|
650 | if queue is not None: | |
647 | queue.put(len(fileList)) |
|
651 | queue.put(len(fileList)) | |
648 | skippedFileList = [] |
|
652 | skippedFileList = [] | |
649 | else: |
|
653 | else: | |
650 | skippedFileList = fileList[cursor*skip: cursor*skip + skip] |
|
654 | skippedFileList = fileList[cursor*skip: cursor*skip + skip] | |
651 |
|
655 | |||
652 | else: |
|
656 | else: | |
653 | skippedFileList = fileList |
|
657 | skippedFileList = fileList | |
654 |
|
658 | |||
655 | for file in skippedFileList: |
|
659 | for file in skippedFileList: | |
656 |
|
660 | |||
657 | filename = os.path.join(thisPath,file) |
|
661 | filename = os.path.join(thisPath,file) | |
658 |
|
662 | |||
659 | if not isFileInDateRange(filename, startDate, endDate): |
|
663 | if not isFileInDateRange(filename, startDate, endDate): | |
660 | continue |
|
664 | continue | |
661 |
|
665 | |||
662 | thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime) |
|
666 | thisDatetime = isFileInTimeRange(filename, startDate, endDate, startTime, endTime) | |
663 |
|
667 | |||
664 | if not(thisDatetime): |
|
668 | if not(thisDatetime): | |
665 | continue |
|
669 | continue | |
666 |
|
670 | |||
667 | filenameList.append(filename) |
|
671 | filenameList.append(filename) | |
668 | datetimeList.append(thisDatetime) |
|
672 | datetimeList.append(thisDatetime) | |
669 |
|
673 | |||
670 | if not(filenameList): |
|
674 | if not(filenameList): | |
671 | print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path) |
|
675 | print "[Reading] Time range selected invalid [%s - %s]: No *%s files in %s)" %(startTime, endTime, ext, path) | |
672 | return None, None |
|
676 | return None, None | |
673 |
|
677 | |||
674 | print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime) |
|
678 | print "[Reading] %d file(s) was(were) found in time range: %s - %s" %(len(filenameList), startTime, endTime) | |
675 |
|
679 | |||
676 |
|
680 | |||
677 | for i in range(len(filenameList)): |
|
681 | for i in range(len(filenameList)): | |
678 | print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime()) |
|
682 | print "[Reading] %s -> [%s]" %(filenameList[i], datetimeList[i].ctime()) | |
679 |
|
683 | |||
680 | self.filenameList = filenameList |
|
684 | self.filenameList = filenameList | |
681 | self.datetimeList = datetimeList |
|
685 | self.datetimeList = datetimeList | |
682 |
|
686 | |||
683 | return pathList, filenameList |
|
687 | return pathList, filenameList | |
684 |
|
688 | |||
685 | def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None): |
|
689 | def __searchFilesOnLine(self, path, expLabel = "", ext = None, walk=True, set=None): | |
686 |
|
690 | |||
687 | """ |
|
691 | """ | |
688 | Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y |
|
692 | Busca el ultimo archivo de la ultima carpeta (determinada o no por startDateTime) y | |
689 | devuelve el archivo encontrado ademas de otros datos. |
|
693 | devuelve el archivo encontrado ademas de otros datos. | |
690 |
|
694 | |||
691 | Input: |
|
695 | Input: | |
692 | path : carpeta donde estan contenidos los files que contiene data |
|
696 | path : carpeta donde estan contenidos los files que contiene data | |
693 |
|
697 | |||
694 | expLabel : Nombre del subexperimento (subfolder) |
|
698 | expLabel : Nombre del subexperimento (subfolder) | |
695 |
|
699 | |||
696 | ext : extension de los files |
|
700 | ext : extension de los files | |
697 |
|
701 | |||
698 | walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath) |
|
702 | walk : Si es habilitado no realiza busquedas dentro de los ubdirectorios (doypath) | |
699 |
|
703 | |||
700 | Return: |
|
704 | Return: | |
701 | directory : eL directorio donde esta el file encontrado |
|
705 | directory : eL directorio donde esta el file encontrado | |
702 | filename : el ultimo file de una determinada carpeta |
|
706 | filename : el ultimo file de una determinada carpeta | |
703 | year : el anho |
|
707 | year : el anho | |
704 | doy : el numero de dia del anho |
|
708 | doy : el numero de dia del anho | |
705 | set : el set del archivo |
|
709 | set : el set del archivo | |
706 |
|
710 | |||
707 |
|
711 | |||
708 | """ |
|
712 | """ | |
709 | if not os.path.isdir(path): |
|
713 | if not os.path.isdir(path): | |
710 | return None, None, None, None, None, None |
|
714 | return None, None, None, None, None, None | |
711 |
|
715 | |||
712 | dirList = [] |
|
716 | dirList = [] | |
713 |
|
717 | |||
714 | if not walk: |
|
718 | if not walk: | |
715 | fullpath = path |
|
719 | fullpath = path | |
716 | foldercounter = 0 |
|
720 | foldercounter = 0 | |
717 | else: |
|
721 | else: | |
718 | #Filtra solo los directorios |
|
722 | #Filtra solo los directorios | |
719 | for thisPath in os.listdir(path): |
|
723 | for thisPath in os.listdir(path): | |
720 | if not os.path.isdir(os.path.join(path,thisPath)): |
|
724 | if not os.path.isdir(os.path.join(path,thisPath)): | |
721 | continue |
|
725 | continue | |
722 | if not isRadarFolder(thisPath): |
|
726 | if not isRadarFolder(thisPath): | |
723 | continue |
|
727 | continue | |
724 |
|
728 | |||
725 | dirList.append(thisPath) |
|
729 | dirList.append(thisPath) | |
726 |
|
730 | |||
727 | if not(dirList): |
|
731 | if not(dirList): | |
728 | return None, None, None, None, None, None |
|
732 | return None, None, None, None, None, None | |
729 |
|
733 | |||
730 | dirList = sorted( dirList, key=str.lower ) |
|
734 | dirList = sorted( dirList, key=str.lower ) | |
731 |
|
735 | |||
732 | doypath = dirList[-1] |
|
736 | doypath = dirList[-1] | |
733 | foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0 |
|
737 | foldercounter = int(doypath.split('_')[1]) if len(doypath.split('_'))>1 else 0 | |
734 | fullpath = os.path.join(path, doypath, expLabel) |
|
738 | fullpath = os.path.join(path, doypath, expLabel) | |
735 |
|
739 | |||
736 |
|
740 | |||
737 | print "[Reading] %s folder was found: " %(fullpath ) |
|
741 | print "[Reading] %s folder was found: " %(fullpath ) | |
738 |
|
742 | |||
739 | if set == None: |
|
743 | if set == None: | |
740 | filename = getlastFileFromPath(fullpath, ext) |
|
744 | filename = getlastFileFromPath(fullpath, ext) | |
741 | else: |
|
745 | else: | |
742 | filename = getFileFromSet(fullpath, ext, set) |
|
746 | filename = getFileFromSet(fullpath, ext, set) | |
743 |
|
747 | |||
744 | if not(filename): |
|
748 | if not(filename): | |
745 | return None, None, None, None, None, None |
|
749 | return None, None, None, None, None, None | |
746 |
|
750 | |||
747 | print "[Reading] %s file was found" %(filename) |
|
751 | print "[Reading] %s file was found" %(filename) | |
748 |
|
752 | |||
749 | if not(self.__verifyFile(os.path.join(fullpath, filename))): |
|
753 | if not(self.__verifyFile(os.path.join(fullpath, filename))): | |
750 | return None, None, None, None, None, None |
|
754 | return None, None, None, None, None, None | |
751 |
|
755 | |||
752 | year = int( filename[1:5] ) |
|
756 | year = int( filename[1:5] ) | |
753 | doy = int( filename[5:8] ) |
|
757 | doy = int( filename[5:8] ) | |
754 | set = int( filename[8:11] ) |
|
758 | set = int( filename[8:11] ) | |
755 |
|
759 | |||
756 | return fullpath, foldercounter, filename, year, doy, set |
|
760 | return fullpath, foldercounter, filename, year, doy, set | |
757 |
|
761 | |||
758 | def __setNextFileOffline(self): |
|
762 | def __setNextFileOffline(self): | |
759 |
|
763 | |||
760 | idFile = self.fileIndex |
|
764 | idFile = self.fileIndex | |
761 |
|
765 | |||
762 | while (True): |
|
766 | while (True): | |
763 | idFile += 1 |
|
767 | idFile += 1 | |
764 | if not(idFile < len(self.filenameList)): |
|
768 | if not(idFile < len(self.filenameList)): | |
765 | self.flagNoMoreFiles = 1 |
|
769 | self.flagNoMoreFiles = 1 | |
766 | # print "[Reading] No more Files" |
|
770 | # print "[Reading] No more Files" | |
767 | return 0 |
|
771 | return 0 | |
768 |
|
772 | |||
769 | filename = self.filenameList[idFile] |
|
773 | filename = self.filenameList[idFile] | |
770 |
|
774 | |||
771 | if not(self.__verifyFile(filename)): |
|
775 | if not(self.__verifyFile(filename)): | |
772 | continue |
|
776 | continue | |
773 |
|
777 | |||
774 | fileSize = os.path.getsize(filename) |
|
778 | fileSize = os.path.getsize(filename) | |
775 | fp = open(filename,'rb') |
|
779 | fp = open(filename,'rb') | |
776 | break |
|
780 | break | |
777 |
|
781 | |||
778 | self.flagIsNewFile = 1 |
|
782 | self.flagIsNewFile = 1 | |
779 | self.fileIndex = idFile |
|
783 | self.fileIndex = idFile | |
780 | self.filename = filename |
|
784 | self.filename = filename | |
781 | self.fileSize = fileSize |
|
785 | self.fileSize = fileSize | |
782 | self.fp = fp |
|
786 | self.fp = fp | |
783 |
|
787 | |||
784 | # print "[Reading] Setting the file: %s"%self.filename |
|
788 | # print "[Reading] Setting the file: %s"%self.filename | |
785 |
|
789 | |||
786 | return 1 |
|
790 | return 1 | |
787 |
|
791 | |||
788 | def __setNextFileOnline(self): |
|
792 | def __setNextFileOnline(self): | |
789 | """ |
|
793 | """ | |
790 | Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si |
|
794 | Busca el siguiente file que tenga suficiente data para ser leida, dentro de un folder especifico, si | |
791 | no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files |
|
795 | no encuentra un file valido espera un tiempo determinado y luego busca en los posibles n files | |
792 | siguientes. |
|
796 | siguientes. | |
793 |
|
797 | |||
794 | Affected: |
|
798 | Affected: | |
795 | self.flagIsNewFile |
|
799 | self.flagIsNewFile | |
796 | self.filename |
|
800 | self.filename | |
797 | self.fileSize |
|
801 | self.fileSize | |
798 | self.fp |
|
802 | self.fp | |
799 | self.set |
|
803 | self.set | |
800 | self.flagNoMoreFiles |
|
804 | self.flagNoMoreFiles | |
801 |
|
805 | |||
802 | Return: |
|
806 | Return: | |
803 | 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado |
|
807 | 0 : si luego de una busqueda del siguiente file valido este no pudo ser encontrado | |
804 | 1 : si el file fue abierto con exito y esta listo a ser leido |
|
808 | 1 : si el file fue abierto con exito y esta listo a ser leido | |
805 |
|
809 | |||
806 | Excepciones: |
|
810 | Excepciones: | |
807 | Si un determinado file no puede ser abierto |
|
811 | Si un determinado file no puede ser abierto | |
808 | """ |
|
812 | """ | |
809 | nFiles = 0 |
|
813 | nFiles = 0 | |
810 | fileOk_flag = False |
|
814 | fileOk_flag = False | |
811 | firstTime_flag = True |
|
815 | firstTime_flag = True | |
812 |
|
816 | |||
813 | self.set += 1 |
|
817 | self.set += 1 | |
814 |
|
818 | |||
815 | if self.set > 999: |
|
819 | if self.set > 999: | |
816 | self.set = 0 |
|
820 | self.set = 0 | |
817 | self.foldercounter += 1 |
|
821 | self.foldercounter += 1 | |
818 |
|
822 | |||
819 | #busca el 1er file disponible |
|
823 | #busca el 1er file disponible | |
820 | fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext ) |
|
824 | fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext ) | |
821 | if fullfilename: |
|
825 | if fullfilename: | |
822 | if self.__verifyFile(fullfilename, False): |
|
826 | if self.__verifyFile(fullfilename, False): | |
823 | fileOk_flag = True |
|
827 | fileOk_flag = True | |
824 |
|
828 | |||
825 | #si no encuentra un file entonces espera y vuelve a buscar |
|
829 | #si no encuentra un file entonces espera y vuelve a buscar | |
826 | if not(fileOk_flag): |
|
830 | if not(fileOk_flag): | |
827 | for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles |
|
831 | for nFiles in range(self.nFiles+1): #busco en los siguientes self.nFiles+1 files posibles | |
828 |
|
832 | |||
829 | if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces |
|
833 | if firstTime_flag: #si es la 1era vez entonces hace el for self.nTries veces | |
830 | tries = self.nTries |
|
834 | tries = self.nTries | |
831 | else: |
|
835 | else: | |
832 | tries = 1 #si no es la 1era vez entonces solo lo hace una vez |
|
836 | tries = 1 #si no es la 1era vez entonces solo lo hace una vez | |
833 |
|
837 | |||
834 | for nTries in range( tries ): |
|
838 | for nTries in range( tries ): | |
835 | if firstTime_flag: |
|
839 | if firstTime_flag: | |
836 | print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 ) |
|
840 | print "\t[Reading] Waiting %0.2f sec for the next file: \"%s\" , try %03d ..." % ( self.delay, filename, nTries+1 ) | |
837 | sleep( self.delay ) |
|
841 | sleep( self.delay ) | |
838 | else: |
|
842 | else: | |
839 | print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext) |
|
843 | print "\t[Reading] Searching the next \"%s%04d%03d%03d%s\" file ..." % (self.optchar, self.year, self.doy, self.set, self.ext) | |
840 |
|
844 | |||
841 | fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext ) |
|
845 | fullfilename, filename = checkForRealPath( self.path, self.foldercounter, self.year, self.doy, self.set, self.ext ) | |
842 | if fullfilename: |
|
846 | if fullfilename: | |
843 | if self.__verifyFile(fullfilename): |
|
847 | if self.__verifyFile(fullfilename): | |
844 | fileOk_flag = True |
|
848 | fileOk_flag = True | |
845 | break |
|
849 | break | |
846 |
|
850 | |||
847 | if fileOk_flag: |
|
851 | if fileOk_flag: | |
848 | break |
|
852 | break | |
849 |
|
853 | |||
850 | firstTime_flag = False |
|
854 | firstTime_flag = False | |
851 |
|
855 | |||
852 | print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename |
|
856 | print "\t[Reading] Skipping the file \"%s\" due to this file doesn't exist" % filename | |
853 | self.set += 1 |
|
857 | self.set += 1 | |
854 |
|
858 | |||
855 | if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta |
|
859 | if nFiles == (self.nFiles-1): #si no encuentro el file buscado cambio de carpeta y busco en la siguiente carpeta | |
856 | self.set = 0 |
|
860 | self.set = 0 | |
857 | self.doy += 1 |
|
861 | self.doy += 1 | |
858 | self.foldercounter = 0 |
|
862 | self.foldercounter = 0 | |
859 |
|
863 | |||
860 | if fileOk_flag: |
|
864 | if fileOk_flag: | |
861 | self.fileSize = os.path.getsize( fullfilename ) |
|
865 | self.fileSize = os.path.getsize( fullfilename ) | |
862 | self.filename = fullfilename |
|
866 | self.filename = fullfilename | |
863 | self.flagIsNewFile = 1 |
|
867 | self.flagIsNewFile = 1 | |
864 | if self.fp != None: self.fp.close() |
|
868 | if self.fp != None: self.fp.close() | |
865 | self.fp = open(fullfilename, 'rb') |
|
869 | self.fp = open(fullfilename, 'rb') | |
866 | self.flagNoMoreFiles = 0 |
|
870 | self.flagNoMoreFiles = 0 | |
867 | # print '[Reading] Setting the file: %s' % fullfilename |
|
871 | # print '[Reading] Setting the file: %s' % fullfilename | |
868 | else: |
|
872 | else: | |
869 | self.fileSize = 0 |
|
873 | self.fileSize = 0 | |
870 | self.filename = None |
|
874 | self.filename = None | |
871 | self.flagIsNewFile = 0 |
|
875 | self.flagIsNewFile = 0 | |
872 | self.fp = None |
|
876 | self.fp = None | |
873 | self.flagNoMoreFiles = 1 |
|
877 | self.flagNoMoreFiles = 1 | |
874 | # print '[Reading] No more files to read' |
|
878 | # print '[Reading] No more files to read' | |
875 |
|
879 | |||
876 | return fileOk_flag |
|
880 | return fileOk_flag | |
877 |
|
881 | |||
878 | def setNextFile(self): |
|
882 | def setNextFile(self): | |
879 | if self.fp != None: |
|
883 | if self.fp != None: | |
880 | self.fp.close() |
|
884 | self.fp.close() | |
881 |
|
885 | |||
882 | if self.online: |
|
886 | if self.online: | |
883 | newFile = self.__setNextFileOnline() |
|
887 | newFile = self.__setNextFileOnline() | |
884 | else: |
|
888 | else: | |
885 | newFile = self.__setNextFileOffline() |
|
889 | newFile = self.__setNextFileOffline() | |
886 |
|
890 | |||
887 | if not(newFile): |
|
891 | if not(newFile): | |
888 | print '[Reading] No more files to read' |
|
892 | print '[Reading] No more files to read' | |
889 | return 0 |
|
893 | return 0 | |
890 |
|
894 | |||
891 | if self.verbose: |
|
895 | if self.verbose: | |
892 | print '[Reading] Setting the file: %s' % self.filename |
|
896 | print '[Reading] Setting the file: %s' % self.filename | |
893 |
|
897 | |||
894 | self.__readFirstHeader() |
|
898 | self.__readFirstHeader() | |
895 | self.nReadBlocks = 0 |
|
899 | self.nReadBlocks = 0 | |
896 | return 1 |
|
900 | return 1 | |
897 |
|
901 | |||
898 | def __waitNewBlock(self): |
|
902 | def __waitNewBlock(self): | |
899 | """ |
|
903 | """ | |
900 | Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma. |
|
904 | Return 1 si se encontro un nuevo bloque de datos, 0 de otra forma. | |
901 |
|
905 | |||
902 | Si el modo de lectura es OffLine siempre retorn 0 |
|
906 | Si el modo de lectura es OffLine siempre retorn 0 | |
903 | """ |
|
907 | """ | |
904 | if not self.online: |
|
908 | if not self.online: | |
905 | return 0 |
|
909 | return 0 | |
906 |
|
910 | |||
907 | if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile): |
|
911 | if (self.nReadBlocks >= self.processingHeaderObj.dataBlocksPerFile): | |
908 | return 0 |
|
912 | return 0 | |
909 |
|
913 | |||
910 | currentPointer = self.fp.tell() |
|
914 | currentPointer = self.fp.tell() | |
911 |
|
915 | |||
912 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
916 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
913 |
|
917 | |||
914 | for nTries in range( self.nTries ): |
|
918 | for nTries in range( self.nTries ): | |
915 |
|
919 | |||
916 | self.fp.close() |
|
920 | self.fp.close() | |
917 | self.fp = open( self.filename, 'rb' ) |
|
921 | self.fp = open( self.filename, 'rb' ) | |
918 | self.fp.seek( currentPointer ) |
|
922 | self.fp.seek( currentPointer ) | |
919 |
|
923 | |||
920 | self.fileSize = os.path.getsize( self.filename ) |
|
924 | self.fileSize = os.path.getsize( self.filename ) | |
921 | currentSize = self.fileSize - currentPointer |
|
925 | currentSize = self.fileSize - currentPointer | |
922 |
|
926 | |||
923 | if ( currentSize >= neededSize ): |
|
927 | if ( currentSize >= neededSize ): | |
924 | self.basicHeaderObj.read(self.fp) |
|
928 | self.basicHeaderObj.read(self.fp) | |
925 | return 1 |
|
929 | return 1 | |
926 |
|
930 | |||
927 | if self.fileSize == self.fileSizeByHeader: |
|
931 | if self.fileSize == self.fileSizeByHeader: | |
928 | # self.flagEoF = True |
|
932 | # self.flagEoF = True | |
929 | return 0 |
|
933 | return 0 | |
930 |
|
934 | |||
931 | print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1) |
|
935 | print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1) | |
932 | sleep( self.delay ) |
|
936 | sleep( self.delay ) | |
933 |
|
937 | |||
934 |
|
938 | |||
935 | return 0 |
|
939 | return 0 | |
936 |
|
940 | |||
937 | def waitDataBlock(self,pointer_location): |
|
941 | def waitDataBlock(self,pointer_location): | |
938 |
|
942 | |||
939 | currentPointer = pointer_location |
|
943 | currentPointer = pointer_location | |
940 |
|
944 | |||
941 | neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize |
|
945 | neededSize = self.processingHeaderObj.blockSize #+ self.basicHeaderSize | |
942 |
|
946 | |||
943 | for nTries in range( self.nTries ): |
|
947 | for nTries in range( self.nTries ): | |
944 | self.fp.close() |
|
948 | self.fp.close() | |
945 | self.fp = open( self.filename, 'rb' ) |
|
949 | self.fp = open( self.filename, 'rb' ) | |
946 | self.fp.seek( currentPointer ) |
|
950 | self.fp.seek( currentPointer ) | |
947 |
|
951 | |||
948 | self.fileSize = os.path.getsize( self.filename ) |
|
952 | self.fileSize = os.path.getsize( self.filename ) | |
949 | currentSize = self.fileSize - currentPointer |
|
953 | currentSize = self.fileSize - currentPointer | |
950 |
|
954 | |||
951 | if ( currentSize >= neededSize ): |
|
955 | if ( currentSize >= neededSize ): | |
952 | return 1 |
|
956 | return 1 | |
953 |
|
957 | |||
954 | print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1) |
|
958 | print "[Reading] Waiting %0.2f seconds for the next block, try %03d ..." % (self.delay, nTries+1) | |
955 | sleep( self.delay ) |
|
959 | sleep( self.delay ) | |
956 |
|
960 | |||
957 | return 0 |
|
961 | return 0 | |
958 |
|
962 | |||
959 | def __jumpToLastBlock(self): |
|
963 | def __jumpToLastBlock(self): | |
960 |
|
964 | |||
961 | if not(self.__isFirstTimeOnline): |
|
965 | if not(self.__isFirstTimeOnline): | |
962 | return |
|
966 | return | |
963 |
|
967 | |||
964 | csize = self.fileSize - self.fp.tell() |
|
968 | csize = self.fileSize - self.fp.tell() | |
965 | blocksize = self.processingHeaderObj.blockSize |
|
969 | blocksize = self.processingHeaderObj.blockSize | |
966 |
|
970 | |||
967 | #salta el primer bloque de datos |
|
971 | #salta el primer bloque de datos | |
968 | if csize > self.processingHeaderObj.blockSize: |
|
972 | if csize > self.processingHeaderObj.blockSize: | |
969 | self.fp.seek(self.fp.tell() + blocksize) |
|
973 | self.fp.seek(self.fp.tell() + blocksize) | |
970 | else: |
|
974 | else: | |
971 | return |
|
975 | return | |
972 |
|
976 | |||
973 | csize = self.fileSize - self.fp.tell() |
|
977 | csize = self.fileSize - self.fp.tell() | |
974 | neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
978 | neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
975 | while True: |
|
979 | while True: | |
976 |
|
980 | |||
977 | if self.fp.tell()<self.fileSize: |
|
981 | if self.fp.tell()<self.fileSize: | |
978 | self.fp.seek(self.fp.tell() + neededsize) |
|
982 | self.fp.seek(self.fp.tell() + neededsize) | |
979 | else: |
|
983 | else: | |
980 | self.fp.seek(self.fp.tell() - neededsize) |
|
984 | self.fp.seek(self.fp.tell() - neededsize) | |
981 | break |
|
985 | break | |
982 |
|
986 | |||
983 | # csize = self.fileSize - self.fp.tell() |
|
987 | # csize = self.fileSize - self.fp.tell() | |
984 | # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
988 | # neededsize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
985 | # factor = int(csize/neededsize) |
|
989 | # factor = int(csize/neededsize) | |
986 | # if factor > 0: |
|
990 | # if factor > 0: | |
987 | # self.fp.seek(self.fp.tell() + factor*neededsize) |
|
991 | # self.fp.seek(self.fp.tell() + factor*neededsize) | |
988 |
|
992 | |||
989 | self.flagIsNewFile = 0 |
|
993 | self.flagIsNewFile = 0 | |
990 | self.__isFirstTimeOnline = 0 |
|
994 | self.__isFirstTimeOnline = 0 | |
991 |
|
995 | |||
992 | def __setNewBlock(self): |
|
996 | def __setNewBlock(self): | |
993 |
|
997 | |||
994 | if self.fp == None: |
|
998 | if self.fp == None: | |
995 | return 0 |
|
999 | return 0 | |
996 |
|
1000 | |||
997 | # if self.online: |
|
1001 | # if self.online: | |
998 | # self.__jumpToLastBlock() |
|
1002 | # self.__jumpToLastBlock() | |
999 |
|
1003 | |||
1000 | if self.flagIsNewFile: |
|
1004 | if self.flagIsNewFile: | |
1001 | self.lastUTTime = self.basicHeaderObj.utc |
|
1005 | self.lastUTTime = self.basicHeaderObj.utc | |
1002 | return 1 |
|
1006 | return 1 | |
1003 |
|
1007 | |||
1004 | if self.realtime: |
|
1008 | if self.realtime: | |
1005 | self.flagDiscontinuousBlock = 1 |
|
1009 | self.flagDiscontinuousBlock = 1 | |
1006 | if not(self.setNextFile()): |
|
1010 | if not(self.setNextFile()): | |
1007 | return 0 |
|
1011 | return 0 | |
1008 | else: |
|
1012 | else: | |
1009 | return 1 |
|
1013 | return 1 | |
1010 |
|
1014 | |||
1011 | currentSize = self.fileSize - self.fp.tell() |
|
1015 | currentSize = self.fileSize - self.fp.tell() | |
1012 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize |
|
1016 | neededSize = self.processingHeaderObj.blockSize + self.basicHeaderSize | |
1013 |
|
1017 | |||
1014 | if (currentSize >= neededSize): |
|
1018 | if (currentSize >= neededSize): | |
1015 | self.basicHeaderObj.read(self.fp) |
|
1019 | self.basicHeaderObj.read(self.fp) | |
1016 | self.lastUTTime = self.basicHeaderObj.utc |
|
1020 | self.lastUTTime = self.basicHeaderObj.utc | |
1017 | return 1 |
|
1021 | return 1 | |
1018 |
|
1022 | |||
1019 | if self.__waitNewBlock(): |
|
1023 | if self.__waitNewBlock(): | |
1020 | self.lastUTTime = self.basicHeaderObj.utc |
|
1024 | self.lastUTTime = self.basicHeaderObj.utc | |
1021 | return 1 |
|
1025 | return 1 | |
1022 |
|
1026 | |||
1023 | if not(self.setNextFile()): |
|
1027 | if not(self.setNextFile()): | |
1024 | return 0 |
|
1028 | return 0 | |
1025 |
|
1029 | |||
1026 | deltaTime = self.basicHeaderObj.utc - self.lastUTTime # |
|
1030 | deltaTime = self.basicHeaderObj.utc - self.lastUTTime # | |
1027 | self.lastUTTime = self.basicHeaderObj.utc |
|
1031 | self.lastUTTime = self.basicHeaderObj.utc | |
1028 |
|
1032 | |||
1029 | self.flagDiscontinuousBlock = 0 |
|
1033 | self.flagDiscontinuousBlock = 0 | |
1030 |
|
1034 | |||
1031 | if deltaTime > self.maxTimeStep: |
|
1035 | if deltaTime > self.maxTimeStep: | |
1032 | self.flagDiscontinuousBlock = 1 |
|
1036 | self.flagDiscontinuousBlock = 1 | |
1033 |
|
1037 | |||
1034 | return 1 |
|
1038 | return 1 | |
1035 |
|
1039 | |||
1036 | def readNextBlock(self): |
|
1040 | def readNextBlock(self): | |
1037 |
|
1041 | |||
1038 | #Skip block out of startTime and endTime |
|
1042 | #Skip block out of startTime and endTime | |
1039 | while True: |
|
1043 | while True: | |
1040 | if not(self.__setNewBlock()): |
|
1044 | if not(self.__setNewBlock()): | |
1041 | return 0 |
|
1045 | return 0 | |
1042 |
|
1046 | |||
1043 | if not(self.readBlock()): |
|
1047 | if not(self.readBlock()): | |
1044 | return 0 |
|
1048 | return 0 | |
1045 |
|
1049 | |||
1046 | self.getBasicHeader() |
|
1050 | self.getBasicHeader() | |
1047 |
|
1051 | |||
1048 | if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime): |
|
1052 | if not isTimeInRange(self.dataOut.datatime.time(), self.startTime, self.endTime): | |
1049 |
|
1053 | |||
1050 | print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks, |
|
1054 | print "[Reading] Block No. %d/%d -> %s [Skipping]" %(self.nReadBlocks, | |
1051 | self.processingHeaderObj.dataBlocksPerFile, |
|
1055 | self.processingHeaderObj.dataBlocksPerFile, | |
1052 | self.dataOut.datatime.ctime()) |
|
1056 | self.dataOut.datatime.ctime()) | |
1053 | continue |
|
1057 | continue | |
1054 |
|
1058 | |||
1055 | break |
|
1059 | break | |
1056 |
|
1060 | |||
1057 | if self.verbose: |
|
1061 | if self.verbose: | |
1058 | print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks, |
|
1062 | print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks, | |
1059 | self.processingHeaderObj.dataBlocksPerFile, |
|
1063 | self.processingHeaderObj.dataBlocksPerFile, | |
1060 | self.dataOut.datatime.ctime()) |
|
1064 | self.dataOut.datatime.ctime()) | |
1061 | return 1 |
|
1065 | return 1 | |
1062 |
|
1066 | |||
1063 | def __readFirstHeader(self): |
|
1067 | def __readFirstHeader(self): | |
1064 |
|
1068 | |||
1065 | self.basicHeaderObj.read(self.fp) |
|
1069 | self.basicHeaderObj.read(self.fp) | |
1066 | self.systemHeaderObj.read(self.fp) |
|
1070 | self.systemHeaderObj.read(self.fp) | |
1067 | self.radarControllerHeaderObj.read(self.fp) |
|
1071 | self.radarControllerHeaderObj.read(self.fp) | |
1068 | self.processingHeaderObj.read(self.fp) |
|
1072 | self.processingHeaderObj.read(self.fp) | |
1069 |
|
1073 | |||
1070 | self.firstHeaderSize = self.basicHeaderObj.size |
|
1074 | self.firstHeaderSize = self.basicHeaderObj.size | |
1071 |
|
1075 | |||
1072 | datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR)) |
|
1076 | datatype = int(numpy.log2((self.processingHeaderObj.processFlags & PROCFLAG.DATATYPE_MASK))-numpy.log2(PROCFLAG.DATATYPE_CHAR)) | |
1073 | if datatype == 0: |
|
1077 | if datatype == 0: | |
1074 | datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')]) |
|
1078 | datatype_str = numpy.dtype([('real','<i1'),('imag','<i1')]) | |
1075 | elif datatype == 1: |
|
1079 | elif datatype == 1: | |
1076 | datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')]) |
|
1080 | datatype_str = numpy.dtype([('real','<i2'),('imag','<i2')]) | |
1077 | elif datatype == 2: |
|
1081 | elif datatype == 2: | |
1078 | datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')]) |
|
1082 | datatype_str = numpy.dtype([('real','<i4'),('imag','<i4')]) | |
1079 | elif datatype == 3: |
|
1083 | elif datatype == 3: | |
1080 | datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')]) |
|
1084 | datatype_str = numpy.dtype([('real','<i8'),('imag','<i8')]) | |
1081 | elif datatype == 4: |
|
1085 | elif datatype == 4: | |
1082 | datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')]) |
|
1086 | datatype_str = numpy.dtype([('real','<f4'),('imag','<f4')]) | |
1083 | elif datatype == 5: |
|
1087 | elif datatype == 5: | |
1084 | datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')]) |
|
1088 | datatype_str = numpy.dtype([('real','<f8'),('imag','<f8')]) | |
1085 | else: |
|
1089 | else: | |
1086 | raise ValueError, 'Data type was not defined' |
|
1090 | raise ValueError, 'Data type was not defined' | |
1087 |
|
1091 | |||
1088 | self.dtype = datatype_str |
|
1092 | self.dtype = datatype_str | |
1089 | #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c |
|
1093 | #self.ippSeconds = 2 * 1000 * self.radarControllerHeaderObj.ipp / self.c | |
1090 | self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1) |
|
1094 | self.fileSizeByHeader = self.processingHeaderObj.dataBlocksPerFile * self.processingHeaderObj.blockSize + self.firstHeaderSize + self.basicHeaderSize*(self.processingHeaderObj.dataBlocksPerFile - 1) | |
1091 | # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels) |
|
1095 | # self.dataOut.channelList = numpy.arange(self.systemHeaderObj.numChannels) | |
1092 | # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) |
|
1096 | # self.dataOut.channelIndexList = numpy.arange(self.systemHeaderObj.numChannels) | |
1093 | self.getBlockDimension() |
|
1097 | self.getBlockDimension() | |
1094 |
|
1098 | |||
1095 | def __verifyFile(self, filename, msgFlag=True): |
|
1099 | def __verifyFile(self, filename, msgFlag=True): | |
1096 |
|
1100 | |||
1097 | msg = None |
|
1101 | msg = None | |
1098 |
|
1102 | |||
1099 | try: |
|
1103 | try: | |
1100 | fp = open(filename, 'rb') |
|
1104 | fp = open(filename, 'rb') | |
1101 | except IOError: |
|
1105 | except IOError: | |
1102 |
|
1106 | |||
1103 | if msgFlag: |
|
1107 | if msgFlag: | |
1104 | print "[Reading] File %s can't be opened" % (filename) |
|
1108 | print "[Reading] File %s can't be opened" % (filename) | |
1105 |
|
1109 | |||
1106 | return False |
|
1110 | return False | |
1107 |
|
1111 | |||
1108 | currentPosition = fp.tell() |
|
1112 | currentPosition = fp.tell() | |
1109 | neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize |
|
1113 | neededSize = self.processingHeaderObj.blockSize + self.firstHeaderSize | |
1110 |
|
1114 | |||
1111 | if neededSize == 0: |
|
1115 | if neededSize == 0: | |
1112 | basicHeaderObj = BasicHeader(LOCALTIME) |
|
1116 | basicHeaderObj = BasicHeader(LOCALTIME) | |
1113 | systemHeaderObj = SystemHeader() |
|
1117 | systemHeaderObj = SystemHeader() | |
1114 | radarControllerHeaderObj = RadarControllerHeader() |
|
1118 | radarControllerHeaderObj = RadarControllerHeader() | |
1115 | processingHeaderObj = ProcessingHeader() |
|
1119 | processingHeaderObj = ProcessingHeader() | |
1116 |
|
1120 | |||
1117 | if not( basicHeaderObj.read(fp) ): |
|
1121 | if not( basicHeaderObj.read(fp) ): | |
1118 | fp.close() |
|
1122 | fp.close() | |
1119 | return False |
|
1123 | return False | |
1120 |
|
1124 | |||
1121 | if not( systemHeaderObj.read(fp) ): |
|
1125 | if not( systemHeaderObj.read(fp) ): | |
1122 | fp.close() |
|
1126 | fp.close() | |
1123 | return False |
|
1127 | return False | |
1124 |
|
1128 | |||
1125 | if not( radarControllerHeaderObj.read(fp) ): |
|
1129 | if not( radarControllerHeaderObj.read(fp) ): | |
1126 | fp.close() |
|
1130 | fp.close() | |
1127 | return False |
|
1131 | return False | |
1128 |
|
1132 | |||
1129 | if not( processingHeaderObj.read(fp) ): |
|
1133 | if not( processingHeaderObj.read(fp) ): | |
1130 | fp.close() |
|
1134 | fp.close() | |
1131 | return False |
|
1135 | return False | |
1132 |
|
1136 | |||
1133 | neededSize = processingHeaderObj.blockSize + basicHeaderObj.size |
|
1137 | neededSize = processingHeaderObj.blockSize + basicHeaderObj.size | |
1134 | else: |
|
1138 | else: | |
1135 | msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename |
|
1139 | msg = "[Reading] Skipping the file %s due to it hasn't enough data" %filename | |
1136 |
|
1140 | |||
1137 | fp.close() |
|
1141 | fp.close() | |
1138 |
|
1142 | |||
1139 | fileSize = os.path.getsize(filename) |
|
1143 | fileSize = os.path.getsize(filename) | |
1140 | currentSize = fileSize - currentPosition |
|
1144 | currentSize = fileSize - currentPosition | |
1141 |
|
1145 | |||
1142 | if currentSize < neededSize: |
|
1146 | if currentSize < neededSize: | |
1143 | if msgFlag and (msg != None): |
|
1147 | if msgFlag and (msg != None): | |
1144 | print msg |
|
1148 | print msg | |
1145 | return False |
|
1149 | return False | |
1146 |
|
1150 | |||
1147 | return True |
|
1151 | return True | |
1148 |
|
1152 | |||
1149 | def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False): |
|
1153 | def findDatafiles(self, path, startDate=None, endDate=None, expLabel='', ext='.r', walk=True, include_path=False): | |
1150 |
|
1154 | |||
1151 | path_empty = True |
|
1155 | path_empty = True | |
1152 |
|
1156 | |||
1153 | dateList = [] |
|
1157 | dateList = [] | |
1154 | pathList = [] |
|
1158 | pathList = [] | |
1155 |
|
1159 | |||
1156 | multi_path = path.split(',') |
|
1160 | multi_path = path.split(',') | |
1157 |
|
1161 | |||
1158 | if not walk: |
|
1162 | if not walk: | |
1159 |
|
1163 | |||
1160 | for single_path in multi_path: |
|
1164 | for single_path in multi_path: | |
1161 |
|
1165 | |||
1162 | if not os.path.isdir(single_path): |
|
1166 | if not os.path.isdir(single_path): | |
1163 | continue |
|
1167 | continue | |
1164 |
|
1168 | |||
1165 | fileList = glob.glob1(single_path, "*"+ext) |
|
1169 | fileList = glob.glob1(single_path, "*"+ext) | |
1166 |
|
1170 | |||
1167 | if not fileList: |
|
1171 | if not fileList: | |
1168 | continue |
|
1172 | continue | |
1169 |
|
1173 | |||
1170 | path_empty = False |
|
1174 | path_empty = False | |
1171 |
|
1175 | |||
1172 | fileList.sort() |
|
1176 | fileList.sort() | |
1173 |
|
1177 | |||
1174 | for thisFile in fileList: |
|
1178 | for thisFile in fileList: | |
1175 |
|
1179 | |||
1176 | if not os.path.isfile(os.path.join(single_path, thisFile)): |
|
1180 | if not os.path.isfile(os.path.join(single_path, thisFile)): | |
1177 | continue |
|
1181 | continue | |
1178 |
|
1182 | |||
1179 | if not isRadarFile(thisFile): |
|
1183 | if not isRadarFile(thisFile): | |
1180 | continue |
|
1184 | continue | |
1181 |
|
1185 | |||
1182 | if not isFileInDateRange(thisFile, startDate, endDate): |
|
1186 | if not isFileInDateRange(thisFile, startDate, endDate): | |
1183 | continue |
|
1187 | continue | |
1184 |
|
1188 | |||
1185 | thisDate = getDateFromRadarFile(thisFile) |
|
1189 | thisDate = getDateFromRadarFile(thisFile) | |
1186 |
|
1190 | |||
1187 | if thisDate in dateList: |
|
1191 | if thisDate in dateList: | |
1188 | continue |
|
1192 | continue | |
1189 |
|
1193 | |||
1190 | dateList.append(thisDate) |
|
1194 | dateList.append(thisDate) | |
1191 | pathList.append(single_path) |
|
1195 | pathList.append(single_path) | |
1192 |
|
1196 | |||
1193 | else: |
|
1197 | else: | |
1194 | for single_path in multi_path: |
|
1198 | for single_path in multi_path: | |
1195 |
|
1199 | |||
1196 | if not os.path.isdir(single_path): |
|
1200 | if not os.path.isdir(single_path): | |
1197 | continue |
|
1201 | continue | |
1198 |
|
1202 | |||
1199 | dirList = [] |
|
1203 | dirList = [] | |
1200 |
|
1204 | |||
1201 | for thisPath in os.listdir(single_path): |
|
1205 | for thisPath in os.listdir(single_path): | |
1202 |
|
1206 | |||
1203 | if not os.path.isdir(os.path.join(single_path,thisPath)): |
|
1207 | if not os.path.isdir(os.path.join(single_path,thisPath)): | |
1204 | continue |
|
1208 | continue | |
1205 |
|
1209 | |||
1206 | if not isRadarFolder(thisPath): |
|
1210 | if not isRadarFolder(thisPath): | |
1207 | continue |
|
1211 | continue | |
1208 |
|
1212 | |||
1209 | if not isFolderInDateRange(thisPath, startDate, endDate): |
|
1213 | if not isFolderInDateRange(thisPath, startDate, endDate): | |
1210 | continue |
|
1214 | continue | |
1211 |
|
1215 | |||
1212 | dirList.append(thisPath) |
|
1216 | dirList.append(thisPath) | |
1213 |
|
1217 | |||
1214 | if not dirList: |
|
1218 | if not dirList: | |
1215 | continue |
|
1219 | continue | |
1216 |
|
1220 | |||
1217 | dirList.sort() |
|
1221 | dirList.sort() | |
1218 |
|
1222 | |||
1219 | for thisDir in dirList: |
|
1223 | for thisDir in dirList: | |
1220 |
|
1224 | |||
1221 | datapath = os.path.join(single_path, thisDir, expLabel) |
|
1225 | datapath = os.path.join(single_path, thisDir, expLabel) | |
1222 | fileList = glob.glob1(datapath, "*"+ext) |
|
1226 | fileList = glob.glob1(datapath, "*"+ext) | |
1223 |
|
1227 | |||
1224 | if not fileList: |
|
1228 | if not fileList: | |
1225 | continue |
|
1229 | continue | |
1226 |
|
1230 | |||
1227 | path_empty = False |
|
1231 | path_empty = False | |
1228 |
|
1232 | |||
1229 | thisDate = getDateFromRadarFolder(thisDir) |
|
1233 | thisDate = getDateFromRadarFolder(thisDir) | |
1230 |
|
1234 | |||
1231 | pathList.append(datapath) |
|
1235 | pathList.append(datapath) | |
1232 | dateList.append(thisDate) |
|
1236 | dateList.append(thisDate) | |
1233 |
|
1237 | |||
1234 | dateList.sort() |
|
1238 | dateList.sort() | |
1235 |
|
1239 | |||
1236 | if walk: |
|
1240 | if walk: | |
1237 | pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel) |
|
1241 | pattern_path = os.path.join(multi_path[0], "[dYYYYDDD]", expLabel) | |
1238 | else: |
|
1242 | else: | |
1239 | pattern_path = multi_path[0] |
|
1243 | pattern_path = multi_path[0] | |
1240 |
|
1244 | |||
1241 | if path_empty: |
|
1245 | if path_empty: | |
1242 | print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate) |
|
1246 | print "[Reading] No *%s files in %s for %s to %s" %(ext, pattern_path, startDate, endDate) | |
1243 | else: |
|
1247 | else: | |
1244 | if not dateList: |
|
1248 | if not dateList: | |
1245 | print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path) |
|
1249 | print "[Reading] Date range selected invalid [%s - %s]: No *%s files in %s)" %(startDate, endDate, ext, path) | |
1246 |
|
1250 | |||
1247 | if include_path: |
|
1251 | if include_path: | |
1248 | return dateList, pathList |
|
1252 | return dateList, pathList | |
1249 |
|
1253 | |||
1250 | return dateList |
|
1254 | return dateList | |
1251 |
|
1255 | |||
1252 | def setup(self, |
|
1256 | def setup(self, | |
1253 | path=None, |
|
1257 | path=None, | |
1254 | startDate=None, |
|
1258 | startDate=None, | |
1255 | endDate=None, |
|
1259 | endDate=None, | |
1256 | startTime=datetime.time(0,0,0), |
|
1260 | startTime=datetime.time(0,0,0), | |
1257 | endTime=datetime.time(23,59,59), |
|
1261 | endTime=datetime.time(23,59,59), | |
1258 | set=None, |
|
1262 | set=None, | |
1259 | expLabel = "", |
|
1263 | expLabel = "", | |
1260 | ext = None, |
|
1264 | ext = None, | |
1261 | online = False, |
|
1265 | online = False, | |
1262 | delay = 60, |
|
1266 | delay = 60, | |
1263 | walk = True, |
|
1267 | walk = True, | |
1264 | getblock = False, |
|
1268 | getblock = False, | |
1265 | nTxs = 1, |
|
1269 | nTxs = 1, | |
1266 | realtime=False, |
|
1270 | realtime=False, | |
1267 | blocksize=None, |
|
1271 | blocksize=None, | |
1268 | blocktime=None, |
|
1272 | blocktime=None, | |
1269 | queue=None, |
|
1273 | queue=None, | |
1270 | skip=None, |
|
1274 | skip=None, | |
1271 | cursor=None, |
|
1275 | cursor=None, | |
1272 | warnings=True, |
|
1276 | warnings=True, | |
1273 | verbose=True): |
|
1277 | verbose=True): | |
1274 |
|
1278 | |||
1275 | if path == None: |
|
1279 | if path == None: | |
1276 | raise ValueError, "[Reading] The path is not valid" |
|
1280 | raise ValueError, "[Reading] The path is not valid" | |
1277 |
|
1281 | |||
1278 | if ext == None: |
|
1282 | if ext == None: | |
1279 | ext = self.ext |
|
1283 | ext = self.ext | |
1280 |
|
1284 | |||
1281 | if online: |
|
1285 | if online: | |
1282 | print "[Reading] Searching files in online mode..." |
|
1286 | print "[Reading] Searching files in online mode..." | |
1283 |
|
1287 | |||
1284 | for nTries in range( self.nTries ): |
|
1288 | for nTries in range( self.nTries ): | |
1285 | fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set) |
|
1289 | fullpath, foldercounter, file, year, doy, set = self.__searchFilesOnLine(path=path, expLabel=expLabel, ext=ext, walk=walk, set=set) | |
1286 |
|
1290 | |||
1287 | if fullpath: |
|
1291 | if fullpath: | |
1288 | break |
|
1292 | break | |
1289 |
|
1293 | |||
1290 | print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1) |
|
1294 | print '[Reading] Waiting %0.2f sec for an valid file in %s: try %02d ...' % (self.delay, path, nTries+1) | |
1291 | sleep( self.delay ) |
|
1295 | sleep( self.delay ) | |
1292 |
|
1296 | |||
1293 | if not(fullpath): |
|
1297 | if not(fullpath): | |
1294 | print "[Reading] There 'isn't any valid file in %s" % path |
|
1298 | print "[Reading] There 'isn't any valid file in %s" % path | |
1295 | return |
|
1299 | return | |
1296 |
|
1300 | |||
1297 | self.year = year |
|
1301 | self.year = year | |
1298 | self.doy = doy |
|
1302 | self.doy = doy | |
1299 | self.set = set - 1 |
|
1303 | self.set = set - 1 | |
1300 | self.path = path |
|
1304 | self.path = path | |
1301 | self.foldercounter = foldercounter |
|
1305 | self.foldercounter = foldercounter | |
1302 | last_set = None |
|
1306 | last_set = None | |
1303 |
|
1307 | |||
1304 | else: |
|
1308 | else: | |
1305 | print "[Reading] Searching files in offline mode ..." |
|
1309 | print "[Reading] Searching files in offline mode ..." | |
1306 | pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate, |
|
1310 | pathList, filenameList = self.__searchFilesOffLine(path, startDate=startDate, endDate=endDate, | |
1307 | startTime=startTime, endTime=endTime, |
|
1311 | startTime=startTime, endTime=endTime, | |
1308 | set=set, expLabel=expLabel, ext=ext, |
|
1312 | set=set, expLabel=expLabel, ext=ext, | |
1309 | walk=walk, cursor=cursor, |
|
1313 | walk=walk, cursor=cursor, | |
1310 | skip=skip, queue=queue) |
|
1314 | skip=skip, queue=queue) | |
1311 |
|
1315 | |||
1312 | if not(pathList): |
|
1316 | if not(pathList): | |
1313 | # print "[Reading] No *%s files in %s (%s - %s)"%(ext, path, |
|
1317 | # print "[Reading] No *%s files in %s (%s - %s)"%(ext, path, | |
1314 | # datetime.datetime.combine(startDate,startTime).ctime(), |
|
1318 | # datetime.datetime.combine(startDate,startTime).ctime(), | |
1315 | # datetime.datetime.combine(endDate,endTime).ctime()) |
|
1319 | # datetime.datetime.combine(endDate,endTime).ctime()) | |
1316 |
|
1320 | |||
1317 | # sys.exit(-1) |
|
1321 | # sys.exit(-1) | |
1318 |
|
1322 | |||
1319 | self.fileIndex = -1 |
|
1323 | self.fileIndex = -1 | |
1320 | self.pathList = [] |
|
1324 | self.pathList = [] | |
1321 | self.filenameList = [] |
|
1325 | self.filenameList = [] | |
1322 | return |
|
1326 | return | |
1323 |
|
1327 | |||
1324 | self.fileIndex = -1 |
|
1328 | self.fileIndex = -1 | |
1325 | self.pathList = pathList |
|
1329 | self.pathList = pathList | |
1326 | self.filenameList = filenameList |
|
1330 | self.filenameList = filenameList | |
1327 | file_name = os.path.basename(filenameList[-1]) |
|
1331 | file_name = os.path.basename(filenameList[-1]) | |
1328 | basename, ext = os.path.splitext(file_name) |
|
1332 | basename, ext = os.path.splitext(file_name) | |
1329 | last_set = int(basename[-3:]) |
|
1333 | last_set = int(basename[-3:]) | |
1330 |
|
1334 | |||
1331 | self.online = online |
|
1335 | self.online = online | |
1332 | self.realtime = realtime |
|
1336 | self.realtime = realtime | |
1333 | self.delay = delay |
|
1337 | self.delay = delay | |
1334 | ext = ext.lower() |
|
1338 | ext = ext.lower() | |
1335 | self.ext = ext |
|
1339 | self.ext = ext | |
1336 | self.getByBlock = getblock |
|
1340 | self.getByBlock = getblock | |
1337 | self.nTxs = nTxs |
|
1341 | self.nTxs = nTxs | |
1338 | self.startTime = startTime |
|
1342 | self.startTime = startTime | |
1339 | self.endTime = endTime |
|
1343 | self.endTime = endTime | |
1340 |
|
1344 | |||
1341 | #Added----------------- |
|
1345 | #Added----------------- | |
1342 | self.selBlocksize = blocksize |
|
1346 | self.selBlocksize = blocksize | |
1343 | self.selBlocktime = blocktime |
|
1347 | self.selBlocktime = blocktime | |
1344 |
|
1348 | |||
1345 | # Verbose----------- |
|
1349 | # Verbose----------- | |
1346 | self.verbose = verbose |
|
1350 | self.verbose = verbose | |
1347 | self.warnings = warnings |
|
1351 | self.warnings = warnings | |
1348 |
|
1352 | |||
1349 | if not(self.setNextFile()): |
|
1353 | if not(self.setNextFile()): | |
1350 | if (startDate!=None) and (endDate!=None): |
|
1354 | if (startDate!=None) and (endDate!=None): | |
1351 | print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()) |
|
1355 | print "[Reading] No files in range: %s - %s" %(datetime.datetime.combine(startDate,startTime).ctime(), datetime.datetime.combine(endDate,endTime).ctime()) | |
1352 | elif startDate != None: |
|
1356 | elif startDate != None: | |
1353 | print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime()) |
|
1357 | print "[Reading] No files in range: %s" %(datetime.datetime.combine(startDate,startTime).ctime()) | |
1354 | else: |
|
1358 | else: | |
1355 | print "[Reading] No files" |
|
1359 | print "[Reading] No files" | |
1356 |
|
1360 | |||
1357 | self.fileIndex = -1 |
|
1361 | self.fileIndex = -1 | |
1358 | self.pathList = [] |
|
1362 | self.pathList = [] | |
1359 | self.filenameList = [] |
|
1363 | self.filenameList = [] | |
1360 | return |
|
1364 | return | |
1361 |
|
1365 | |||
1362 | # self.getBasicHeader() |
|
1366 | # self.getBasicHeader() | |
1363 |
|
1367 | |||
1364 | if last_set != None: |
|
1368 | if last_set != None: | |
1365 | self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock |
|
1369 | self.dataOut.last_block = last_set * self.processingHeaderObj.dataBlocksPerFile + self.basicHeaderObj.dataBlock | |
1366 | return |
|
1370 | return | |
1367 |
|
1371 | |||
1368 | def getBasicHeader(self): |
|
1372 | def getBasicHeader(self): | |
1369 |
|
1373 | |||
1370 | self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds |
|
1374 | self.dataOut.utctime = self.basicHeaderObj.utc + self.basicHeaderObj.miliSecond/1000. + self.profileIndex * self.radarControllerHeaderObj.ippSeconds | |
1371 |
|
1375 | |||
1372 | self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock |
|
1376 | self.dataOut.flagDiscontinuousBlock = self.flagDiscontinuousBlock | |
1373 |
|
1377 | |||
1374 | self.dataOut.timeZone = self.basicHeaderObj.timeZone |
|
1378 | self.dataOut.timeZone = self.basicHeaderObj.timeZone | |
1375 |
|
1379 | |||
1376 | self.dataOut.dstFlag = self.basicHeaderObj.dstFlag |
|
1380 | self.dataOut.dstFlag = self.basicHeaderObj.dstFlag | |
1377 |
|
1381 | |||
1378 | self.dataOut.errorCount = self.basicHeaderObj.errorCount |
|
1382 | self.dataOut.errorCount = self.basicHeaderObj.errorCount | |
1379 |
|
1383 | |||
1380 | self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime |
|
1384 | self.dataOut.useLocalTime = self.basicHeaderObj.useLocalTime | |
1381 |
|
1385 | |||
1382 | self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs |
|
1386 | self.dataOut.ippSeconds = self.radarControllerHeaderObj.ippSeconds/self.nTxs | |
1383 |
|
1387 | |||
1384 | # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs |
|
1388 | # self.dataOut.nProfiles = self.processingHeaderObj.profilesPerBlock*self.nTxs | |
1385 |
|
1389 | |||
1386 |
|
1390 | |||
1387 | def getFirstHeader(self): |
|
1391 | def getFirstHeader(self): | |
1388 |
|
1392 | |||
1389 | raise NotImplementedError |
|
1393 | raise NotImplementedError | |
1390 |
|
1394 | |||
1391 | def getData(self): |
|
1395 | def getData(self): | |
1392 |
|
1396 | |||
1393 | raise NotImplementedError |
|
1397 | raise NotImplementedError | |
1394 |
|
1398 | |||
1395 | def hasNotDataInBuffer(self): |
|
1399 | def hasNotDataInBuffer(self): | |
1396 |
|
1400 | |||
1397 | raise NotImplementedError |
|
1401 | raise NotImplementedError | |
1398 |
|
1402 | |||
1399 | def readBlock(self): |
|
1403 | def readBlock(self): | |
1400 |
|
1404 | |||
1401 | raise NotImplementedError |
|
1405 | raise NotImplementedError | |
1402 |
|
1406 | |||
1403 | def isEndProcess(self): |
|
1407 | def isEndProcess(self): | |
1404 |
|
1408 | |||
1405 | return self.flagNoMoreFiles |
|
1409 | return self.flagNoMoreFiles | |
1406 |
|
1410 | |||
1407 | def printReadBlocks(self): |
|
1411 | def printReadBlocks(self): | |
1408 |
|
1412 | |||
1409 | print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks |
|
1413 | print "[Reading] Number of read blocks per file %04d" %self.nReadBlocks | |
1410 |
|
1414 | |||
1411 | def printTotalBlocks(self): |
|
1415 | def printTotalBlocks(self): | |
1412 |
|
1416 | |||
1413 | print "[Reading] Number of read blocks %04d" %self.nTotalBlocks |
|
1417 | print "[Reading] Number of read blocks %04d" %self.nTotalBlocks | |
1414 |
|
1418 | |||
1415 | def printNumberOfBlock(self): |
|
1419 | def printNumberOfBlock(self): | |
1416 |
|
1420 | |||
1417 | if self.flagIsNewBlock: |
|
1421 | if self.flagIsNewBlock: | |
1418 | print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks, |
|
1422 | print "[Reading] Block No. %d/%d -> %s" %(self.nReadBlocks, | |
1419 | self.processingHeaderObj.dataBlocksPerFile, |
|
1423 | self.processingHeaderObj.dataBlocksPerFile, | |
1420 | self.dataOut.datatime.ctime()) |
|
1424 | self.dataOut.datatime.ctime()) | |
1421 |
|
1425 | |||
1422 | def printInfo(self): |
|
1426 | def printInfo(self): | |
1423 |
|
1427 | |||
1424 | if self.__printInfo == False: |
|
1428 | if self.__printInfo == False: | |
1425 | return |
|
1429 | return | |
1426 |
|
1430 | |||
1427 | self.basicHeaderObj.printInfo() |
|
1431 | self.basicHeaderObj.printInfo() | |
1428 | self.systemHeaderObj.printInfo() |
|
1432 | self.systemHeaderObj.printInfo() | |
1429 | self.radarControllerHeaderObj.printInfo() |
|
1433 | self.radarControllerHeaderObj.printInfo() | |
1430 | self.processingHeaderObj.printInfo() |
|
1434 | self.processingHeaderObj.printInfo() | |
1431 |
|
1435 | |||
1432 | self.__printInfo = False |
|
1436 | self.__printInfo = False | |
1433 |
|
1437 | |||
1434 |
|
1438 | |||
1435 |
def run(self, |
|
1439 | def run(self, | |
|
1440 | path=None, | |||
|
1441 | startDate=None, | |||
|
1442 | endDate=None, | |||
|
1443 | startTime=datetime.time(0,0,0), | |||
|
1444 | endTime=datetime.time(23,59,59), | |||
|
1445 | set=None, | |||
|
1446 | expLabel = "", | |||
|
1447 | ext = None, | |||
|
1448 | online = False, | |||
|
1449 | delay = 60, | |||
|
1450 | walk = True, | |||
|
1451 | getblock = False, | |||
|
1452 | nTxs = 1, | |||
|
1453 | realtime=False, | |||
|
1454 | blocksize=None, | |||
|
1455 | blocktime=None, | |||
|
1456 | queue=None, | |||
|
1457 | skip=None, | |||
|
1458 | cursor=None, | |||
|
1459 | warnings=True, | |||
|
1460 | verbose=True, **kwargs): | |||
1436 |
|
1461 | |||
1437 | if not(self.isConfig): |
|
1462 | if not(self.isConfig): | |
1438 |
|
||||
1439 | # self.dataOut = dataOut |
|
1463 | # self.dataOut = dataOut | |
1440 |
self.setup( |
|
1464 | self.setup( path=path, | |
|
1465 | startDate=startDate, | |||
|
1466 | endDate=endDate, | |||
|
1467 | startTime=startTime, | |||
|
1468 | endTime=endTime, | |||
|
1469 | set=set, | |||
|
1470 | expLabel=expLabel, | |||
|
1471 | ext=ext, | |||
|
1472 | online=online, | |||
|
1473 | delay=delay, | |||
|
1474 | walk=walk, | |||
|
1475 | getblock=getblock, | |||
|
1476 | nTxs=nTxs, | |||
|
1477 | realtime=realtime, | |||
|
1478 | blocksize=blocksize, | |||
|
1479 | blocktime=blocktime, | |||
|
1480 | queue=queue, | |||
|
1481 | skip=skip, | |||
|
1482 | cursor=cursor, | |||
|
1483 | warnings=warnings, | |||
|
1484 | verbose=verbose) | |||
1441 | self.isConfig = True |
|
1485 | self.isConfig = True | |
1442 |
|
1486 | |||
1443 | self.getData() |
|
1487 | self.getData() | |
1444 |
|
1488 | |||
1445 | class JRODataWriter(JRODataIO): |
|
1489 | class JRODataWriter(JRODataIO): | |
1446 |
|
1490 | |||
1447 | """ |
|
1491 | """ | |
1448 | Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura |
|
1492 | Esta clase permite escribir datos a archivos procesados (.r o ,pdata). La escritura | |
1449 | de los datos siempre se realiza por bloques. |
|
1493 | de los datos siempre se realiza por bloques. | |
1450 | """ |
|
1494 | """ | |
1451 |
|
1495 | |||
1452 | blockIndex = 0 |
|
1496 | blockIndex = 0 | |
1453 |
|
1497 | |||
1454 | path = None |
|
1498 | path = None | |
1455 |
|
1499 | |||
1456 | setFile = None |
|
1500 | setFile = None | |
1457 |
|
1501 | |||
1458 | profilesPerBlock = None |
|
1502 | profilesPerBlock = None | |
1459 |
|
1503 | |||
1460 | blocksPerFile = None |
|
1504 | blocksPerFile = None | |
1461 |
|
1505 | |||
1462 | nWriteBlocks = 0 |
|
1506 | nWriteBlocks = 0 | |
1463 |
|
1507 | |||
1464 | fileDate = None |
|
1508 | fileDate = None | |
1465 |
|
1509 | |||
1466 | def __init__(self, dataOut=None): |
|
1510 | def __init__(self, dataOut=None): | |
1467 | raise NotImplementedError |
|
1511 | raise NotImplementedError | |
1468 |
|
1512 | |||
1469 |
|
1513 | |||
1470 | def hasAllDataInBuffer(self): |
|
1514 | def hasAllDataInBuffer(self): | |
1471 | raise NotImplementedError |
|
1515 | raise NotImplementedError | |
1472 |
|
1516 | |||
1473 |
|
1517 | |||
1474 | def setBlockDimension(self): |
|
1518 | def setBlockDimension(self): | |
1475 | raise NotImplementedError |
|
1519 | raise NotImplementedError | |
1476 |
|
1520 | |||
1477 |
|
1521 | |||
1478 | def writeBlock(self): |
|
1522 | def writeBlock(self): | |
1479 | raise NotImplementedError |
|
1523 | raise NotImplementedError | |
1480 |
|
1524 | |||
1481 |
|
1525 | |||
1482 | def putData(self): |
|
1526 | def putData(self): | |
1483 | raise NotImplementedError |
|
1527 | raise NotImplementedError | |
1484 |
|
1528 | |||
1485 |
|
1529 | |||
1486 | def getProcessFlags(self): |
|
1530 | def getProcessFlags(self): | |
1487 |
|
1531 | |||
1488 | processFlags = 0 |
|
1532 | processFlags = 0 | |
1489 |
|
1533 | |||
1490 | dtype_index = get_dtype_index(self.dtype) |
|
1534 | dtype_index = get_dtype_index(self.dtype) | |
1491 | procflag_dtype = get_procflag_dtype(dtype_index) |
|
1535 | procflag_dtype = get_procflag_dtype(dtype_index) | |
1492 |
|
1536 | |||
1493 | processFlags += procflag_dtype |
|
1537 | processFlags += procflag_dtype | |
1494 |
|
1538 | |||
1495 | if self.dataOut.flagDecodeData: |
|
1539 | if self.dataOut.flagDecodeData: | |
1496 | processFlags += PROCFLAG.DECODE_DATA |
|
1540 | processFlags += PROCFLAG.DECODE_DATA | |
1497 |
|
1541 | |||
1498 | if self.dataOut.flagDeflipData: |
|
1542 | if self.dataOut.flagDeflipData: | |
1499 | processFlags += PROCFLAG.DEFLIP_DATA |
|
1543 | processFlags += PROCFLAG.DEFLIP_DATA | |
1500 |
|
1544 | |||
1501 | if self.dataOut.code is not None: |
|
1545 | if self.dataOut.code is not None: | |
1502 | processFlags += PROCFLAG.DEFINE_PROCESS_CODE |
|
1546 | processFlags += PROCFLAG.DEFINE_PROCESS_CODE | |
1503 |
|
1547 | |||
1504 | if self.dataOut.nCohInt > 1: |
|
1548 | if self.dataOut.nCohInt > 1: | |
1505 | processFlags += PROCFLAG.COHERENT_INTEGRATION |
|
1549 | processFlags += PROCFLAG.COHERENT_INTEGRATION | |
1506 |
|
1550 | |||
1507 | if self.dataOut.type == "Spectra": |
|
1551 | if self.dataOut.type == "Spectra": | |
1508 | if self.dataOut.nIncohInt > 1: |
|
1552 | if self.dataOut.nIncohInt > 1: | |
1509 | processFlags += PROCFLAG.INCOHERENT_INTEGRATION |
|
1553 | processFlags += PROCFLAG.INCOHERENT_INTEGRATION | |
1510 |
|
1554 | |||
1511 | if self.dataOut.data_dc is not None: |
|
1555 | if self.dataOut.data_dc is not None: | |
1512 | processFlags += PROCFLAG.SAVE_CHANNELS_DC |
|
1556 | processFlags += PROCFLAG.SAVE_CHANNELS_DC | |
1513 |
|
1557 | |||
1514 | if self.dataOut.flagShiftFFT: |
|
1558 | if self.dataOut.flagShiftFFT: | |
1515 | processFlags += PROCFLAG.SHIFT_FFT_DATA |
|
1559 | processFlags += PROCFLAG.SHIFT_FFT_DATA | |
1516 |
|
1560 | |||
1517 | return processFlags |
|
1561 | return processFlags | |
1518 |
|
1562 | |||
1519 | def setBasicHeader(self): |
|
1563 | def setBasicHeader(self): | |
1520 |
|
1564 | |||
1521 | self.basicHeaderObj.size = self.basicHeaderSize #bytes |
|
1565 | self.basicHeaderObj.size = self.basicHeaderSize #bytes | |
1522 | self.basicHeaderObj.version = self.versionFile |
|
1566 | self.basicHeaderObj.version = self.versionFile | |
1523 | self.basicHeaderObj.dataBlock = self.nTotalBlocks |
|
1567 | self.basicHeaderObj.dataBlock = self.nTotalBlocks | |
1524 |
|
1568 | |||
1525 | utc = numpy.floor(self.dataOut.utctime) |
|
1569 | utc = numpy.floor(self.dataOut.utctime) | |
1526 | milisecond = (self.dataOut.utctime - utc)* 1000.0 |
|
1570 | milisecond = (self.dataOut.utctime - utc)* 1000.0 | |
1527 |
|
1571 | |||
1528 | self.basicHeaderObj.utc = utc |
|
1572 | self.basicHeaderObj.utc = utc | |
1529 | self.basicHeaderObj.miliSecond = milisecond |
|
1573 | self.basicHeaderObj.miliSecond = milisecond | |
1530 | self.basicHeaderObj.timeZone = self.dataOut.timeZone |
|
1574 | self.basicHeaderObj.timeZone = self.dataOut.timeZone | |
1531 | self.basicHeaderObj.dstFlag = self.dataOut.dstFlag |
|
1575 | self.basicHeaderObj.dstFlag = self.dataOut.dstFlag | |
1532 | self.basicHeaderObj.errorCount = self.dataOut.errorCount |
|
1576 | self.basicHeaderObj.errorCount = self.dataOut.errorCount | |
1533 |
|
1577 | |||
1534 | def setFirstHeader(self): |
|
1578 | def setFirstHeader(self): | |
1535 | """ |
|
1579 | """ | |
1536 | Obtiene una copia del First Header |
|
1580 | Obtiene una copia del First Header | |
1537 |
|
1581 | |||
1538 | Affected: |
|
1582 | Affected: | |
1539 |
|
1583 | |||
1540 | self.basicHeaderObj |
|
1584 | self.basicHeaderObj | |
1541 | self.systemHeaderObj |
|
1585 | self.systemHeaderObj | |
1542 | self.radarControllerHeaderObj |
|
1586 | self.radarControllerHeaderObj | |
1543 | self.processingHeaderObj self. |
|
1587 | self.processingHeaderObj self. | |
1544 |
|
1588 | |||
1545 | Return: |
|
1589 | Return: | |
1546 | None |
|
1590 | None | |
1547 | """ |
|
1591 | """ | |
1548 |
|
1592 | |||
1549 | raise NotImplementedError |
|
1593 | raise NotImplementedError | |
1550 |
|
1594 | |||
1551 | def __writeFirstHeader(self): |
|
1595 | def __writeFirstHeader(self): | |
1552 | """ |
|
1596 | """ | |
1553 | Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader) |
|
1597 | Escribe el primer header del file es decir el Basic header y el Long header (SystemHeader, RadarControllerHeader, ProcessingHeader) | |
1554 |
|
1598 | |||
1555 | Affected: |
|
1599 | Affected: | |
1556 | __dataType |
|
1600 | __dataType | |
1557 |
|
1601 | |||
1558 | Return: |
|
1602 | Return: | |
1559 | None |
|
1603 | None | |
1560 | """ |
|
1604 | """ | |
1561 |
|
1605 | |||
1562 | # CALCULAR PARAMETROS |
|
1606 | # CALCULAR PARAMETROS | |
1563 |
|
1607 | |||
1564 | sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size |
|
1608 | sizeLongHeader = self.systemHeaderObj.size + self.radarControllerHeaderObj.size + self.processingHeaderObj.size | |
1565 | self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader |
|
1609 | self.basicHeaderObj.size = self.basicHeaderSize + sizeLongHeader | |
1566 |
|
1610 | |||
1567 | self.basicHeaderObj.write(self.fp) |
|
1611 | self.basicHeaderObj.write(self.fp) | |
1568 | self.systemHeaderObj.write(self.fp) |
|
1612 | self.systemHeaderObj.write(self.fp) | |
1569 | self.radarControllerHeaderObj.write(self.fp) |
|
1613 | self.radarControllerHeaderObj.write(self.fp) | |
1570 | self.processingHeaderObj.write(self.fp) |
|
1614 | self.processingHeaderObj.write(self.fp) | |
1571 |
|
1615 | |||
1572 | def __setNewBlock(self): |
|
1616 | def __setNewBlock(self): | |
1573 | """ |
|
1617 | """ | |
1574 | Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header |
|
1618 | Si es un nuevo file escribe el First Header caso contrario escribe solo el Basic Header | |
1575 |
|
1619 | |||
1576 | Return: |
|
1620 | Return: | |
1577 | 0 : si no pudo escribir nada |
|
1621 | 0 : si no pudo escribir nada | |
1578 | 1 : Si escribio el Basic el First Header |
|
1622 | 1 : Si escribio el Basic el First Header | |
1579 | """ |
|
1623 | """ | |
1580 | if self.fp == None: |
|
1624 | if self.fp == None: | |
1581 | self.setNextFile() |
|
1625 | self.setNextFile() | |
1582 |
|
1626 | |||
1583 | if self.flagIsNewFile: |
|
1627 | if self.flagIsNewFile: | |
1584 | return 1 |
|
1628 | return 1 | |
1585 |
|
1629 | |||
1586 | if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile: |
|
1630 | if self.blockIndex < self.processingHeaderObj.dataBlocksPerFile: | |
1587 | self.basicHeaderObj.write(self.fp) |
|
1631 | self.basicHeaderObj.write(self.fp) | |
1588 | return 1 |
|
1632 | return 1 | |
1589 |
|
1633 | |||
1590 | if not( self.setNextFile() ): |
|
1634 | if not( self.setNextFile() ): | |
1591 | return 0 |
|
1635 | return 0 | |
1592 |
|
1636 | |||
1593 | return 1 |
|
1637 | return 1 | |
1594 |
|
1638 | |||
1595 |
|
1639 | |||
1596 | def writeNextBlock(self): |
|
1640 | def writeNextBlock(self): | |
1597 | """ |
|
1641 | """ | |
1598 | Selecciona el bloque siguiente de datos y los escribe en un file |
|
1642 | Selecciona el bloque siguiente de datos y los escribe en un file | |
1599 |
|
1643 | |||
1600 | Return: |
|
1644 | Return: | |
1601 | 0 : Si no hizo pudo escribir el bloque de datos |
|
1645 | 0 : Si no hizo pudo escribir el bloque de datos | |
1602 | 1 : Si no pudo escribir el bloque de datos |
|
1646 | 1 : Si no pudo escribir el bloque de datos | |
1603 | """ |
|
1647 | """ | |
1604 | if not( self.__setNewBlock() ): |
|
1648 | if not( self.__setNewBlock() ): | |
1605 | return 0 |
|
1649 | return 0 | |
1606 |
|
1650 | |||
1607 | self.writeBlock() |
|
1651 | self.writeBlock() | |
1608 |
|
1652 | |||
1609 | print "[Writing] Block No. %d/%d" %(self.blockIndex, |
|
1653 | print "[Writing] Block No. %d/%d" %(self.blockIndex, | |
1610 | self.processingHeaderObj.dataBlocksPerFile) |
|
1654 | self.processingHeaderObj.dataBlocksPerFile) | |
1611 |
|
1655 | |||
1612 | return 1 |
|
1656 | return 1 | |
1613 |
|
1657 | |||
1614 | def setNextFile(self): |
|
1658 | def setNextFile(self): | |
1615 | """ |
|
1659 | """ | |
1616 | Determina el siguiente file que sera escrito |
|
1660 | Determina el siguiente file que sera escrito | |
1617 |
|
1661 | |||
1618 | Affected: |
|
1662 | Affected: | |
1619 | self.filename |
|
1663 | self.filename | |
1620 | self.subfolder |
|
1664 | self.subfolder | |
1621 | self.fp |
|
1665 | self.fp | |
1622 | self.setFile |
|
1666 | self.setFile | |
1623 | self.flagIsNewFile |
|
1667 | self.flagIsNewFile | |
1624 |
|
1668 | |||
1625 | Return: |
|
1669 | Return: | |
1626 | 0 : Si el archivo no puede ser escrito |
|
1670 | 0 : Si el archivo no puede ser escrito | |
1627 | 1 : Si el archivo esta listo para ser escrito |
|
1671 | 1 : Si el archivo esta listo para ser escrito | |
1628 | """ |
|
1672 | """ | |
1629 | ext = self.ext |
|
1673 | ext = self.ext | |
1630 | path = self.path |
|
1674 | path = self.path | |
1631 |
|
1675 | |||
1632 | if self.fp != None: |
|
1676 | if self.fp != None: | |
1633 | self.fp.close() |
|
1677 | self.fp.close() | |
1634 |
|
1678 | |||
1635 | timeTuple = time.localtime( self.dataOut.utctime) |
|
1679 | timeTuple = time.localtime( self.dataOut.utctime) | |
1636 | subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday) |
|
1680 | subfolder = 'd%4.4d%3.3d' % (timeTuple.tm_year,timeTuple.tm_yday) | |
1637 |
|
1681 | |||
1638 | fullpath = os.path.join( path, subfolder ) |
|
1682 | fullpath = os.path.join( path, subfolder ) | |
1639 | setFile = self.setFile |
|
1683 | setFile = self.setFile | |
1640 |
|
1684 | |||
1641 | if not( os.path.exists(fullpath) ): |
|
1685 | if not( os.path.exists(fullpath) ): | |
1642 | os.mkdir(fullpath) |
|
1686 | os.mkdir(fullpath) | |
1643 | setFile = -1 #inicializo mi contador de seteo |
|
1687 | setFile = -1 #inicializo mi contador de seteo | |
1644 | else: |
|
1688 | else: | |
1645 | filesList = os.listdir( fullpath ) |
|
1689 | filesList = os.listdir( fullpath ) | |
1646 | if len( filesList ) > 0: |
|
1690 | if len( filesList ) > 0: | |
1647 | filesList = sorted( filesList, key=str.lower ) |
|
1691 | filesList = sorted( filesList, key=str.lower ) | |
1648 | filen = filesList[-1] |
|
1692 | filen = filesList[-1] | |
1649 | # el filename debera tener el siguiente formato |
|
1693 | # el filename debera tener el siguiente formato | |
1650 | # 0 1234 567 89A BCDE (hex) |
|
1694 | # 0 1234 567 89A BCDE (hex) | |
1651 | # x YYYY DDD SSS .ext |
|
1695 | # x YYYY DDD SSS .ext | |
1652 | if isNumber( filen[8:11] ): |
|
1696 | if isNumber( filen[8:11] ): | |
1653 | setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file |
|
1697 | setFile = int( filen[8:11] ) #inicializo mi contador de seteo al seteo del ultimo file | |
1654 | else: |
|
1698 | else: | |
1655 | setFile = -1 |
|
1699 | setFile = -1 | |
1656 | else: |
|
1700 | else: | |
1657 | setFile = -1 #inicializo mi contador de seteo |
|
1701 | setFile = -1 #inicializo mi contador de seteo | |
1658 |
|
1702 | |||
1659 | setFile += 1 |
|
1703 | setFile += 1 | |
1660 |
|
1704 | |||
1661 | #If this is a new day it resets some values |
|
1705 | #If this is a new day it resets some values | |
1662 | if self.dataOut.datatime.date() > self.fileDate: |
|
1706 | if self.dataOut.datatime.date() > self.fileDate: | |
1663 | setFile = 0 |
|
1707 | setFile = 0 | |
1664 | self.nTotalBlocks = 0 |
|
1708 | self.nTotalBlocks = 0 | |
1665 |
|
1709 | |||
1666 | filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext ) |
|
1710 | filen = '%s%4.4d%3.3d%3.3d%s' % (self.optchar, timeTuple.tm_year, timeTuple.tm_yday, setFile, ext ) | |
1667 |
|
1711 | |||
1668 | filename = os.path.join( path, subfolder, filen ) |
|
1712 | filename = os.path.join( path, subfolder, filen ) | |
1669 |
|
1713 | |||
1670 | fp = open( filename,'wb' ) |
|
1714 | fp = open( filename,'wb' ) | |
1671 |
|
1715 | |||
1672 | self.blockIndex = 0 |
|
1716 | self.blockIndex = 0 | |
1673 |
|
1717 | |||
1674 | #guardando atributos |
|
1718 | #guardando atributos | |
1675 | self.filename = filename |
|
1719 | self.filename = filename | |
1676 | self.subfolder = subfolder |
|
1720 | self.subfolder = subfolder | |
1677 | self.fp = fp |
|
1721 | self.fp = fp | |
1678 | self.setFile = setFile |
|
1722 | self.setFile = setFile | |
1679 | self.flagIsNewFile = 1 |
|
1723 | self.flagIsNewFile = 1 | |
1680 | self.fileDate = self.dataOut.datatime.date() |
|
1724 | self.fileDate = self.dataOut.datatime.date() | |
1681 |
|
1725 | |||
1682 | self.setFirstHeader() |
|
1726 | self.setFirstHeader() | |
1683 |
|
1727 | |||
1684 | print '[Writing] Opening file: %s'%self.filename |
|
1728 | print '[Writing] Opening file: %s'%self.filename | |
1685 |
|
1729 | |||
1686 | self.__writeFirstHeader() |
|
1730 | self.__writeFirstHeader() | |
1687 |
|
1731 | |||
1688 | return 1 |
|
1732 | return 1 | |
1689 |
|
1733 | |||
1690 | def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4): |
|
1734 | def setup(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4): | |
1691 | """ |
|
1735 | """ | |
1692 | Setea el tipo de formato en la cual sera guardada la data y escribe el First Header |
|
1736 | Setea el tipo de formato en la cual sera guardada la data y escribe el First Header | |
1693 |
|
1737 | |||
1694 | Inputs: |
|
1738 | Inputs: | |
1695 | path : directory where data will be saved |
|
1739 | path : directory where data will be saved | |
1696 | profilesPerBlock : number of profiles per block |
|
1740 | profilesPerBlock : number of profiles per block | |
1697 | set : initial file set |
|
1741 | set : initial file set | |
1698 | datatype : An integer number that defines data type: |
|
1742 | datatype : An integer number that defines data type: | |
1699 | 0 : int8 (1 byte) |
|
1743 | 0 : int8 (1 byte) | |
1700 | 1 : int16 (2 bytes) |
|
1744 | 1 : int16 (2 bytes) | |
1701 | 2 : int32 (4 bytes) |
|
1745 | 2 : int32 (4 bytes) | |
1702 | 3 : int64 (8 bytes) |
|
1746 | 3 : int64 (8 bytes) | |
1703 | 4 : float32 (4 bytes) |
|
1747 | 4 : float32 (4 bytes) | |
1704 | 5 : double64 (8 bytes) |
|
1748 | 5 : double64 (8 bytes) | |
1705 |
|
1749 | |||
1706 | Return: |
|
1750 | Return: | |
1707 | 0 : Si no realizo un buen seteo |
|
1751 | 0 : Si no realizo un buen seteo | |
1708 | 1 : Si realizo un buen seteo |
|
1752 | 1 : Si realizo un buen seteo | |
1709 | """ |
|
1753 | """ | |
1710 |
|
1754 | |||
1711 | if ext == None: |
|
1755 | if ext == None: | |
1712 | ext = self.ext |
|
1756 | ext = self.ext | |
1713 |
|
1757 | |||
1714 | self.ext = ext.lower() |
|
1758 | self.ext = ext.lower() | |
1715 |
|
1759 | |||
1716 | self.path = path |
|
1760 | self.path = path | |
1717 |
|
1761 | |||
1718 | if set is None: |
|
1762 | if set is None: | |
1719 | self.setFile = -1 |
|
1763 | self.setFile = -1 | |
1720 | else: |
|
1764 | else: | |
1721 | self.setFile = set - 1 |
|
1765 | self.setFile = set - 1 | |
1722 |
|
1766 | |||
1723 | self.blocksPerFile = blocksPerFile |
|
1767 | self.blocksPerFile = blocksPerFile | |
1724 |
|
1768 | |||
1725 | self.profilesPerBlock = profilesPerBlock |
|
1769 | self.profilesPerBlock = profilesPerBlock | |
1726 |
|
1770 | |||
1727 | self.dataOut = dataOut |
|
1771 | self.dataOut = dataOut | |
1728 | self.fileDate = self.dataOut.datatime.date() |
|
1772 | self.fileDate = self.dataOut.datatime.date() | |
1729 | #By default |
|
1773 | #By default | |
1730 | self.dtype = self.dataOut.dtype |
|
1774 | self.dtype = self.dataOut.dtype | |
1731 |
|
1775 | |||
1732 | if datatype is not None: |
|
1776 | if datatype is not None: | |
1733 | self.dtype = get_numpy_dtype(datatype) |
|
1777 | self.dtype = get_numpy_dtype(datatype) | |
1734 |
|
1778 | |||
1735 | if not(self.setNextFile()): |
|
1779 | if not(self.setNextFile()): | |
1736 | print "[Writing] There isn't a next file" |
|
1780 | print "[Writing] There isn't a next file" | |
1737 | return 0 |
|
1781 | return 0 | |
1738 |
|
1782 | |||
1739 | self.setBlockDimension() |
|
1783 | self.setBlockDimension() | |
1740 |
|
1784 | |||
1741 | return 1 |
|
1785 | return 1 | |
1742 |
|
1786 | |||
1743 | def run(self, dataOut, **kwargs): |
|
1787 | def run(self, dataOut, path, blocksPerFile, profilesPerBlock=64, set=None, ext=None, datatype=4, **kwargs): | |
1744 |
|
1788 | |||
1745 | if not(self.isConfig): |
|
1789 | if not(self.isConfig): | |
1746 |
|
1790 | |||
1747 | self.setup(dataOut, **kwargs) |
|
1791 | self.setup(dataOut, path, blocksPerFile, profilesPerBlock=profilesPerBlock, set=set, ext=ext, datatype=datatype, **kwargs) | |
1748 | self.isConfig = True |
|
1792 | self.isConfig = True | |
1749 |
|
1793 | |||
1750 | self.putData() |
|
1794 | self.putData() |
@@ -1,1 +1,1 | |||||
1 |
<Project description="HF_EXAMPLE" id="191" name="test01"><ReadUnit datatype="Spectra |
|
1 | <Project description="HF_EXAMPLE" id="191" name="test01"><ReadUnit datatype="Spectra" id="1911" inputId="0" name="SpectraReader"><Operation id="19111" name="run" priority="1" type="self"><Parameter format="str" id="191111" name="datatype" value="SpectraReader" /><Parameter format="str" id="191112" name="path" value="/home/nanosat/data/sp1_f0" /><Parameter format="date" id="191113" name="startDate" value="2017/01/28" /><Parameter format="date" id="191114" name="endDate" value="2017/01/28" /><Parameter format="time" id="191115" name="startTime" value="00:00:00" /><Parameter format="time" id="191116" name="endTime" value="23:59:59" /><Parameter format="int" id="191118" name="cursor" value="5" /><Parameter format="int" id="191119" name="skip" value="177" /><Parameter format="int" id="191120" name="walk" value="1" /><Parameter format="int" id="191121" name="verbose" value="1" /><Parameter format="int" id="191122" name="online" value="0" /></Operation></ReadUnit><ProcUnit datatype="Parameters" id="1913" inputId="1911" name="ParametersProc"><Operation id="19131" name="run" priority="1" type="self" /><Operation id="19132" name="SpectralMoments" priority="2" type="other" /><Operation id="19133" name="PublishData" priority="3" type="other"><Parameter format="int" id="191331" name="zeromq" value="1" /><Parameter format="bool" id="191332" name="verbose" value="0" /><Parameter format="int" id="191333" name="delay" value="0" /></Operation></ProcUnit><ProcUnit datatype="Spectra" id="1912" inputId="1911" name="SpectraProc"><Operation id="19121" name="run" priority="1" type="self" /></ProcUnit></Project> No newline at end of file |
@@ -1,49 +1,57 | |||||
1 | ''' |
|
1 | """. | |
|
2 | ||||
2 | Created on Jul 16, 2014 |
|
3 | Created on Jul 16, 2014 | |
3 |
|
4 | |||
4 | @author: Miguel Urco |
|
5 | @author: Miguel Urco | |
5 | ''' |
|
6 | """ | |
6 |
|
7 | |||
7 | from schainpy import __version__ |
|
8 | from schainpy import __version__ | |
8 | from setuptools import setup, Extension |
|
9 | from setuptools import setup, Extension | |
9 |
|
10 | |||
10 | setup(name="schainpy", |
|
11 | setup(name="schainpy", | |
11 |
|
|
12 | version=__version__, | |
12 |
|
|
13 | description="Python tools to read, write and process Jicamarca data", | |
13 |
|
|
14 | author="Miguel Urco", | |
14 |
|
|
15 | author_email="miguel.urco@jro.igp.gob.pe", | |
15 |
|
|
16 | url="http://jro.igp.gob.pe", | |
16 |
|
|
17 | packages={'schainpy', | |
17 |
|
|
18 | 'schainpy.model', | |
18 |
|
|
19 | 'schainpy.model.data', | |
19 |
|
|
20 | 'schainpy.model.graphics', | |
20 |
|
|
21 | 'schainpy.model.io', | |
21 |
|
|
22 | 'schainpy.model.proc', | |
22 |
|
|
23 | 'schainpy.model.serializer', | |
23 |
|
|
24 | 'schainpy.model.utils', | |
24 |
|
|
25 | 'schainpy.gui', | |
25 |
|
|
26 | 'schainpy.gui.figures', | |
26 |
|
|
27 | 'schainpy.gui.viewcontroller', | |
27 |
|
|
28 | 'schainpy.gui.viewer', | |
28 |
|
|
29 | 'schainpy.gui.viewer.windows'}, | |
29 |
|
|
30 | ext_package='schainpy', | |
30 |
|
|
31 | py_modules=[''], | |
31 |
|
|
32 | package_data={'': ['schain.conf.template'], | |
32 |
|
|
33 | 'schainpy.gui.figures': ['*.png', '*.jpg'], | |
33 |
|
|
34 | }, | |
34 |
|
|
35 | include_package_data=False, | |
35 | scripts =['schainpy/gui/schainGUI', |
|
36 | entry_points={ | |
36 | 'schainpy/scripts/schain'], |
|
37 | 'console_scripts': [ | |
|
38 | 'schain = schaincli.cli:main', | |||
|
39 | ], | |||
|
40 | }, | |||
|
41 | scripts=['schainpy/gui/schainGUI'], | |||
37 |
|
|
42 | ext_modules=[Extension("cSchain", ["schainpy/model/proc/extensions.c"])], | |
38 |
|
|
43 | install_requires=[ | |
39 |
|
|
44 | "scipy >= 0.14.0", | |
40 |
|
|
45 | "h5py >= 2.2.1", | |
41 |
|
|
46 | "matplotlib >= 1.4.2", | |
42 |
|
|
47 | "pyfits >= 3.4", | |
43 |
|
|
48 | "numpy >= 1.11.2", | |
44 |
|
|
49 | "paramiko >= 2.1.2", | |
45 |
|
|
50 | "paho-mqtt >= 1.2", | |
46 |
|
|
51 | "zmq", | |
47 |
|
|
52 | "fuzzywuzzy", | |
|
53 | "click", | |||
|
54 | "colorama", | |||
|
55 | "python-Levenshtein" | |||
48 |
|
|
56 | ], | |
49 | ) |
|
57 | ) |
General Comments 0
You need to be logged in to leave comments.
Login now