##// END OF EJS Templates
fixed indentation
rflores -
r1730:9e0e70fdf2b0
parent child
Show More
@@ -1,6939 +1,6939
1 1
2 2 import os
3 3 import sys
4 4 import numpy, math
5 5 from scipy import interpolate
6 6 from scipy.optimize import nnls
7 7 from schainpy.model.proc.jroproc_base import ProcessingUnit, Operation, MPDecorator
8 8 from schainpy.model.data.jrodata import Voltage, hildebrand_sekhon
9 9 from schainpy.utils import log
10 10 from time import time, mktime, strptime, gmtime, ctime
11 11 from scipy.optimize import least_squares
12 12 import datetime
13 13 import csv
14 14
15 15 try:
16 16 from schainpy.model.proc import fitacf_guess
17 17 from schainpy.model.proc import fitacf_fit_short
18 18 from schainpy.model.proc import fitacf_acf2
19 19 from schainpy.model.proc import full_profile_profile
20 20 except:
21 21 log.warning('Missing Faraday fortran libs')
22 22
23 23 class VoltageProc(ProcessingUnit):
24 24
25 25 def __init__(self):
26 26
27 27 ProcessingUnit.__init__(self)
28 28
29 29 self.dataOut = Voltage()
30 30 self.flip = 1
31 31 self.setupReq = False
32 32 #self.dataOut.test=1
33 33
34 34
35 35 def run(self, runNextUnit = 0):
36 36 #import time
37 37 #time.sleep(3)
38 38
39 39 if self.dataIn.type == 'AMISR':
40 40 self.__updateObjFromAmisrInput()
41 41
42 42 if self.dataIn.type == 'Voltage':
43 43 self.dataOut.copy(self.dataIn)
44 44 self.dataOut.runNextUnit = runNextUnit
45 45
46 46
47 47 #self.dataOut.flagNoData=True
48 48 #print(self.dataOut.data[-1,:])
49 49 #print(ctime(self.dataOut.utctime))
50 50 #print(self.dataOut.heightList)
51 51 #print(self.dataOut.nHeights)
52 52 #exit(1)
53 53 #print(self.dataOut.data[6,:32])
54 54 #print(self.dataOut.data[0,320-5:320+5-5])
55 55 ##print(self.dataOut.heightList[-20:])
56 56 #print(numpy.shape(self.dataOut.data))
57 57 #print(self.dataOut.code)
58 58 #print(numpy.shape(self.dataOut.code))
59 59 #exit(1)
60 60 #print(self.dataOut.CurrentBlock)
61 61 #print(self.dataOut.data[0,:,0])
62 62
63 63 #print(numpy.shape(self.dataOut.data))
64 64 #print(self.dataOut.data[0,:,1666:1666+320])
65 65 #exit(1)
66 66
67 67 #print(self.dataOut.utctime)
68 68 #self.dataOut.test+=1
69 69
70 70
71 71 def __updateObjFromAmisrInput(self):
72 72
73 73 self.dataOut.timeZone = self.dataIn.timeZone
74 74 self.dataOut.dstFlag = self.dataIn.dstFlag
75 75 self.dataOut.errorCount = self.dataIn.errorCount
76 76 self.dataOut.useLocalTime = self.dataIn.useLocalTime
77 77
78 78 self.dataOut.flagNoData = self.dataIn.flagNoData
79 79 self.dataOut.data = self.dataIn.data
80 80 self.dataOut.utctime = self.dataIn.utctime
81 81 self.dataOut.channelList = self.dataIn.channelList
82 82 # self.dataOut.timeInterval = self.dataIn.timeInterval
83 83 self.dataOut.heightList = self.dataIn.heightList
84 84 self.dataOut.nProfiles = self.dataIn.nProfiles
85 85
86 86 self.dataOut.nCohInt = self.dataIn.nCohInt
87 87 self.dataOut.ippSeconds = self.dataIn.ippSeconds
88 88 self.dataOut.frequency = self.dataIn.frequency
89 89
90 90 self.dataOut.azimuth = self.dataIn.azimuth
91 91 self.dataOut.zenith = self.dataIn.zenith
92 92
93 93 self.dataOut.beam.codeList = self.dataIn.beam.codeList
94 94 self.dataOut.beam.azimuthList = self.dataIn.beam.azimuthList
95 95 self.dataOut.beam.zenithList = self.dataIn.beam.zenithList
96 96
97 97 class selectChannels(Operation):
98 98
99 99 def run(self, dataOut, channelList):
100 100
101 101
102 102
103 103
104 104 channelIndexList = []
105 105 self.dataOut = dataOut
106 106 for channel in channelList:
107 107 if channel not in self.dataOut.channelList:
108 108 raise ValueError("Channel %d is not in %s" % (channel, str(self.dataOut.channelList)))
109 109
110 110 index = self.dataOut.channelList.index(channel)
111 111 channelIndexList.append(index)
112 112 self.selectChannelsByIndex(channelIndexList)
113 113
114 114 return self.dataOut
115 115
116 116
117 117 def selectChannelsByIndex(self, channelIndexList):
118 118 """
119 119 Selecciona un bloque de datos en base a canales segun el channelIndexList
120 120
121 121 Input:
122 122 channelIndexList : lista sencilla de canales a seleccionar por ej. [2,3,7]
123 123
124 124 Affected:
125 125 self.dataOut.data
126 126 self.dataOut.channelIndexList
127 127 self.dataOut.nChannels
128 128 self.dataOut.m_ProcessingHeader.totalSpectra
129 129 self.dataOut.systemHeaderObj.numChannels
130 130 self.dataOut.m_ProcessingHeader.blockSize
131 131
132 132 Return:
133 133 None
134 134 """
135 135
136 136 for channelIndex in channelIndexList:
137 137 if channelIndex not in self.dataOut.channelIndexList:
138 138 raise ValueError("The value %d in channelIndexList is not valid" % channelIndex)
139 139
140 140 if self.dataOut.type == 'Voltage':
141 141 if self.dataOut.flagDataAsBlock:
142 142 """
143 143 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
144 144 """
145 145 data = self.dataOut.data[channelIndexList, :, :]
146 146 else:
147 147 data = self.dataOut.data[channelIndexList, :]
148 148
149 149 self.dataOut.data = data
150 150 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
151 151 self.dataOut.channelList = range(len(channelIndexList))
152 152
153 153 elif self.dataOut.type == 'Spectra':
154 154 data_spc = self.dataOut.data_spc[channelIndexList, :]
155 155 data_dc = self.dataOut.data_dc[channelIndexList, :]
156 156
157 157 self.dataOut.data_spc = data_spc
158 158 self.dataOut.data_dc = data_dc
159 159
160 160 # self.dataOut.channelList = [self.dataOut.channelList[i] for i in channelIndexList]
161 161 self.dataOut.channelList = range(len(channelIndexList))
162 162 self.__selectPairsByChannel(channelIndexList)
163 163
164 164 return 1
165 165
166 166 def __selectPairsByChannel(self, channelList=None):
167 167
168 168 if channelList == None:
169 169 return
170 170
171 171 pairsIndexListSelected = []
172 172 for pairIndex in self.dataOut.pairsIndexList:
173 173 # First pair
174 174 if self.dataOut.pairsList[pairIndex][0] not in channelList:
175 175 continue
176 176 # Second pair
177 177 if self.dataOut.pairsList[pairIndex][1] not in channelList:
178 178 continue
179 179
180 180 pairsIndexListSelected.append(pairIndex)
181 181
182 182 if not pairsIndexListSelected:
183 183 self.dataOut.data_cspc = None
184 184 self.dataOut.pairsList = []
185 185 return
186 186
187 187 self.dataOut.data_cspc = self.dataOut.data_cspc[pairsIndexListSelected]
188 188 self.dataOut.pairsList = [self.dataOut.pairsList[i]
189 189 for i in pairsIndexListSelected]
190 190
191 191 return
192 192
193 193 class selectHeights(Operation):
194 194
195 195 def run(self, dataOut, minHei=None, maxHei=None, minIndex=None, maxIndex=None):
196 196 """
197 197 Selecciona un bloque de datos en base a un grupo de valores de alturas segun el rango
198 198 minHei <= height <= maxHei
199 199
200 200 Input:
201 201 minHei : valor minimo de altura a considerar
202 202 maxHei : valor maximo de altura a considerar
203 203
204 204 Affected:
205 205 Indirectamente son cambiados varios valores a travez del metodo selectHeightsByIndex
206 206
207 207 Return:
208 208 1 si el metodo se ejecuto con exito caso contrario devuelve 0
209 209 """
210 210
211 211 self.dataOut = dataOut
212
212
213 213 #if minHei and maxHei:
214 214 if 1:
215 215 if minHei == None:
216 216 minHei = self.dataOut.heightList[0]
217
217
218 218 if maxHei == None:
219 219 maxHei = self.dataOut.heightList[-1]
220 220
221 221 if (minHei < self.dataOut.heightList[0]):
222 222 minHei = self.dataOut.heightList[0]
223 223
224 224 if (maxHei > self.dataOut.heightList[-1]):
225 225 maxHei = self.dataOut.heightList[-1]
226 226
227 227 minIndex = 0
228 228 maxIndex = 0
229 229 heights = self.dataOut.heightList
230 230
231 231 inda = numpy.where(heights >= minHei)
232 232 indb = numpy.where(heights <= maxHei)
233 233
234 234 try:
235 235 minIndex = inda[0][0]
236 236 except:
237 237 minIndex = 0
238 238
239 239 try:
240 240 maxIndex = indb[0][-1]
241 241 except:
242 242 maxIndex = len(heights)
243
243
244 244 self.selectHeightsByIndex(minIndex, maxIndex)
245 245 #print(self.dataOut.nHeights)
246 246
247 247
248 248 return self.dataOut
249 249
250 250 def selectHeightsByIndex(self, minIndex, maxIndex):
251 251 """
252 252 Selecciona un bloque de datos en base a un grupo indices de alturas segun el rango
253 253 minIndex <= index <= maxIndex
254 254
255 255 Input:
256 256 minIndex : valor de indice minimo de altura a considerar
257 257 maxIndex : valor de indice maximo de altura a considerar
258 258
259 259 Affected:
260 260 self.dataOut.data
261 261 self.dataOut.heightList
262 262
263 263 Return:
264 264 1 si el metodo se ejecuto con exito caso contrario devuelve 0
265 265 """
266 266
267 267 if self.dataOut.type == 'Voltage':
268 268 if (minIndex < 0) or (minIndex > maxIndex):
269 269 raise ValueError("Height index range (%d,%d) is not valid" % (minIndex, maxIndex))
270 270
271 271 if (maxIndex >= self.dataOut.nHeights):
272 272 maxIndex = self.dataOut.nHeights
273 273
274 274 # voltage
275 275 if self.dataOut.flagDataAsBlock:
276 276 """
277 277 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
278 278 """
279 279 data = self.dataOut.data[:, :, minIndex:maxIndex]
280 280 else:
281 281 data = self.dataOut.data[:, minIndex:maxIndex]
282 282
283 283 # firstHeight = self.dataOut.heightList[minIndex]
284 284
285 285 self.dataOut.data = data
286 286 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex]
287 287
288 288 if self.dataOut.nHeights <= 1:
289 289 raise ValueError("selectHeights: Too few heights. Current number of heights is %d" % (self.dataOut.nHeights))
290 290 elif self.dataOut.type == 'Spectra':
291 291 if (minIndex < 0) or (minIndex > maxIndex):
292 292 raise ValueError("Error selecting heights: Index range (%d,%d) is not valid" % (
293 293 minIndex, maxIndex))
294 294
295 295 if (maxIndex >= self.dataOut.nHeights):
296 296 maxIndex = self.dataOut.nHeights - 1
297 297
298 298 # Spectra
299 299 data_spc = self.dataOut.data_spc[:, :, minIndex:maxIndex + 1]
300 300
301 301 data_cspc = None
302 302 if self.dataOut.data_cspc is not None:
303 303 data_cspc = self.dataOut.data_cspc[:, :, minIndex:maxIndex + 1]
304 304
305 305 data_dc = None
306 306 if self.dataOut.data_dc is not None:
307 307 data_dc = self.dataOut.data_dc[:, minIndex:maxIndex + 1]
308 308
309 309 self.dataOut.data_spc = data_spc
310 310 self.dataOut.data_cspc = data_cspc
311 311 self.dataOut.data_dc = data_dc
312
312
313 313 self.dataOut.heightList = self.dataOut.heightList[minIndex:maxIndex + 1]
314 314
315 315 return 1
316 316
317 317
318 318 class filterByHeights(Operation):
319 319
320 320 def run(self, dataOut, window):
321 321
322 322 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
323 323
324 324 if window == None:
325 325 window = (dataOut.radarControllerHeaderObj.txA / dataOut.radarControllerHeaderObj.nBaud) / deltaHeight
326 326
327 327 newdelta = deltaHeight * window
328 328 r = dataOut.nHeights % window
329 329 newheights = (dataOut.nHeights - r) / window
330 330
331 331 if newheights <= 1:
332 332 raise ValueError("filterByHeights: Too few heights. Current number of heights is %d and window is %d" % (dataOut.nHeights, window))
333 333
334 334 if dataOut.flagDataAsBlock:
335 335 """
336 336 Si la data es obtenida por bloques, dimension = [nChannels, nProfiles, nHeis]
337 337 """
338 338 buffer = dataOut.data[:, :, 0:int(dataOut.nHeights - r)]
339 339 buffer = buffer.reshape(dataOut.nChannels, dataOut.nProfiles, int(dataOut.nHeights / window), window)
340 340 buffer = numpy.sum(buffer, 3)
341 341
342 342 else:
343 343 buffer = dataOut.data[:, 0:int(dataOut.nHeights - r)]
344 344 buffer = buffer.reshape(dataOut.nChannels, int(dataOut.nHeights / window), int(window))
345 345 buffer = numpy.sum(buffer, 2)
346 346
347 347 dataOut.data = buffer
348 348 dataOut.heightList = dataOut.heightList[0] + numpy.arange(newheights) * newdelta
349 349 dataOut.windowOfFilter = window
350 350
351 351 return dataOut
352 352
353 353 class setOffset(Operation):
354 354
355 355 def run(self, dataOut, offset=None):
356 356
357 357 if not offset:
358 358 offset = 0.0
359 359
360 360 newHeiRange = dataOut.heightList - offset
361 361
362 362 dataOut.heightList = newHeiRange
363 363
364 return dataOut
365
364 return dataOut
365
366 366 class setH0(Operation):
367 367
368 368 def run(self, dataOut, h0, deltaHeight=None):
369 369
370 370 if not deltaHeight:
371 371 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
372 372
373 373 nHeights = dataOut.nHeights
374 374
375 375 newHeiRange = h0 + numpy.arange(nHeights) * deltaHeight
376 376
377 377 dataOut.heightList = newHeiRange
378 378
379 379 return dataOut
380 380
381 381
382 382 class deFlip(Operation):
383 383 def __init__(self):
384 384
385 385 self.flip = 1
386 386
387 387 def run(self, dataOut, channelList=[]):
388 388
389 389 data = dataOut.data.copy()
390 390 #print(dataOut.channelList)
391 391 #exit()
392 392
393 393 if channelList==1: #PARCHE
394 394 channelList=[1]
395 395
396 396
397 397 dataOut.FlipChannels=channelList
398 398 if dataOut.flagDataAsBlock:
399 399 flip = self.flip
400 400 profileList = list(range(dataOut.nProfiles))
401 401
402 402 if not channelList:
403 403 for thisProfile in profileList:
404 404 data[:, thisProfile, :] = data[:, thisProfile, :] * flip
405 405 flip *= -1.0
406 406 else:
407 407 for thisChannel in channelList:
408 408 if thisChannel not in dataOut.channelList:
409 409 continue
410 410
411 411 for thisProfile in profileList:
412 412 data[thisChannel, thisProfile, :] = data[thisChannel, thisProfile, :] * flip
413 413 flip *= -1.0
414 414
415 415 self.flip = flip
416 416
417 417 else:
418 418 if not channelList:
419 419 data[:, :] = data[:, :] * self.flip
420 420 else:
421 421 #channelList=[1]
422 422 #print(self.flip)
423 423 for thisChannel in channelList:
424 424 if thisChannel not in dataOut.channelList:
425 425 continue
426 426
427 427 data[thisChannel, :] = data[thisChannel, :] * self.flip
428 428
429 429 self.flip *= -1.
430 430
431 431 dataOut.data = data
432 432
433 433 return dataOut
434 434
435 435 class deFlipHP(Operation):
436 436 '''
437 437 Written by R. Flores
438 438 '''
439 439 def __init__(self):
440 440
441 441 self.flip = 1
442 442
443 443 def run(self, dataOut, byHeights = False, channelList = [], HeiRangeList = None):
444 444
445 445 data = dataOut.data.copy()
446 446
447 447 firstHeight = HeiRangeList[0]
448 448 lastHeight = HeiRangeList[1]+1
449 449
450 450 #if channelList==1: #PARCHE #Lista de un solo canal produce error
451 451 #channelList=[1]
452 452
453 453 dataOut.FlipChannels=channelList
454 454 if dataOut.flagDataAsBlock:
455 455 flip = self.flip
456 456 profileList = list(range(dataOut.nProfiles))
457 457
458 458 if not channelList:
459 459 for thisProfile in profileList:
460 460 data[:,thisProfile,:] = data[:,thisProfile,:]*flip
461 461 flip *= -1.0
462 462 else:
463 463 for thisChannel in channelList:
464 464 if thisChannel not in dataOut.channelList:
465 465 continue
466 466 if not byHeights:
467 467 for thisProfile in profileList:
468 468 data[thisChannel,thisProfile,:] = data[thisChannel,thisProfile,:]*flip
469 469 flip *= -1.0
470 470
471 471 else:
472 472 firstHeight = HeiRangeList[0]
473 473 lastHeight = HeiRangeList[1]+1
474 474 flip = -1.0
475 475 data[thisChannel,:,firstHeight:lastHeight] = data[thisChannel,:,firstHeight:lastHeight]*flip
476 476
477 477
478 478 self.flip = flip
479 479
480 480 else:
481 481 if not channelList:
482 482 data[:,:] = data[:,:]*self.flip
483 483 else:
484 484 #channelList=[1]
485 485
486 486 for thisChannel in channelList:
487 487 if thisChannel not in dataOut.channelList:
488 488 continue
489 489
490 490 if not byHeights:
491 491 data[thisChannel,:] = data[thisChannel,:]*flip
492 492
493 493 else:
494 494 firstHeight = HeiRangeList[0]
495 495 lastHeight = HeiRangeList[1]+1
496 496 flip = -1.0
497 497 data[thisChannel,firstHeight:lastHeight] = data[thisChannel,firstHeight:lastHeight]*flip
498 498
499 499 #data[thisChannel,:] = data[thisChannel,:]*self.flip
500 500
501 501 self.flip *= -1.
502 502
503 503 #print(dataOut.data[0,:12,1066+2])
504 504 #print(dataOut.data[1,:12,1066+2])
505 505 dataOut.data =data
506 506 #print(dataOut.data[0,:12,1066+2])
507 507 #print(dataOut.data[1,:12,1066+2])
508 508 #exit(1)
509 509
510 510 return dataOut
511 511
512 512 class setAttribute(Operation):
513 513 '''
514 514 Set an arbitrary attribute(s) to dataOut
515 515 '''
516 516
517 517 def __init__(self):
518 518
519 519 Operation.__init__(self)
520 520 self._ready = False
521 521
522 522 def run(self, dataOut, **kwargs):
523 523
524 524 for key, value in kwargs.items():
525 525 setattr(dataOut, key, value)
526 526
527 527 return dataOut
528 528
529 529
530 530 @MPDecorator
531 531 class printAttribute(Operation):
532 532 '''
533 533 Print an arbitrary attribute of dataOut
534 534 '''
535 535
536 536 def __init__(self):
537 537
538 538 Operation.__init__(self)
539 539
540 540 def run(self, dataOut, attributes):
541 541
542 542 if isinstance(attributes, str):
543 543 attributes = [attributes]
544 544 for attr in attributes:
545 545 if hasattr(dataOut, attr):
546 546 log.log(getattr(dataOut, attr), attr)
547 547
548 548
549 549 class interpolateHeights(Operation):
550 550
551 551 def run(self, dataOut, topLim, botLim):
552 552 # 69 al 72 para julia
553 553 # 82-84 para meteoros
554 554 if len(numpy.shape(dataOut.data)) == 2:
555 555 sampInterp = (dataOut.data[:, botLim - 1] + dataOut.data[:, topLim + 1]) / 2
556 556 sampInterp = numpy.transpose(numpy.tile(sampInterp, (topLim - botLim + 1, 1)))
557 557 # dataOut.data[:,botLim:limSup+1] = sampInterp
558 558 dataOut.data[:, botLim:topLim + 1] = sampInterp
559 559 else:
560 560 nHeights = dataOut.data.shape[2]
561 561 x = numpy.hstack((numpy.arange(botLim), numpy.arange(topLim + 1, nHeights)))
562 562 y = dataOut.data[:, :, list(range(botLim)) + list(range(topLim + 1, nHeights))]
563 563 f = interpolate.interp1d(x, y, axis=2)
564 564 xnew = numpy.arange(botLim, topLim + 1)
565 565 ynew = f(xnew)
566 566 dataOut.data[:, :, botLim:topLim + 1] = ynew
567 567
568 568 return dataOut
569 569
570 570
571 571 class LagsReshape(Operation):
572 572 '''
573 573 Written by R. Flores
574 574 '''
575 575 """Operation to reshape input data into (Channels,Profiles(with same lag),Heights,Lags) and heights reconstruction.
576 576
577 577 Parameters:
578 578 -----------
579 579
580 580
581 581 Example
582 582 --------
583 583
584 584 op = proc_unit.addOperation(name='LagsReshape')
585 585
586 586
587 587 """
588 588
589 589 def __init__(self, **kwargs):
590 590
591 591 Operation.__init__(self, **kwargs)
592 592
593 593 self.buffer=None
594 594 self.buffer_HR=None
595 595 self.buffer_HRonelag=None
596 596
597 597 def LagDistribution(self,dataOut):
598 598
599 599 dataOut.datapure=numpy.copy(dataOut.data[:,0:dataOut.NSCAN,:])
600 600 self.buffer = numpy.zeros((dataOut.nChannels,
601 601 int(dataOut.NSCAN/dataOut.DPL),
602 602 dataOut.nHeights,dataOut.DPL),
603 603 dtype='complex')
604 604
605 605 for j in range(int(self.buffer.shape[1]/2)):
606 606 for i in range(dataOut.DPL):
607 607 if j+1==int(self.buffer.shape[1]/2) and i+1==dataOut.DPL:
608 608 self.buffer[:,2*j:,:,i]=dataOut.datapure[:,2*i+int(2*j*dataOut.DPL):,:]
609 609 else:
610 610 self.buffer[:,2*j:2*(j+1),:,i]=dataOut.datapure[:,2*i+int(2*j*dataOut.DPL):2*(i+1)+int(2*j*dataOut.DPL),:]
611 611
612 612 return self.buffer
613 613
614 614 def HeightReconstruction(self,dataOut):
615 615
616 616 self.buffer_HR = numpy.zeros((int(dataOut.NSCAN/dataOut.DPL),
617 617 dataOut.nHeights,dataOut.DPL),
618 618 dtype='complex')
619 619
620 620 for i in range(int(dataOut.DPL)): #Only channel B
621 621 if i==0:
622 622 self.buffer_HR[:,:,i]=dataOut.datalags[1,:,:,i]
623 623 else:
624 624 self.buffer_HR[:,:,i]=self.HRonelag(dataOut,i)
625 625
626 626 return self.buffer_HR
627 627
628 628
629 629 def HRonelag(self,dataOut,whichlag):
630 630 self.buffer_HRonelag = numpy.zeros((int(dataOut.NSCAN/dataOut.DPL),
631 631 dataOut.nHeights),
632 632 dtype='complex')
633 633
634 634 for i in range(self.buffer_HRonelag.shape[0]):
635 635 for j in range(dataOut.nHeights):
636 636 if j+int(2*whichlag)<dataOut.nHeights:
637 637 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i,j+2*whichlag,whichlag]
638 638 else:
639 639 if whichlag!=10:
640 640 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i,(j+2*whichlag)%dataOut.nHeights,whichlag+1]
641 641 else:
642 642 if i+2<self.buffer_HRonelag.shape[0]:
643 643 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i+2,(j+2*whichlag)%dataOut.nHeights,0]
644 644 else: #i+1==self.buffer_HRonelag.shape[0]:
645 645 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i,(j+2*whichlag)%dataOut.nHeights,whichlag]
646 646
647 647 return self.buffer_HRonelag
648 648
649 649
650 650
651 651 def run(self,dataOut,DPL=11,NSCAN=132):
652 652
653 653 dataOut.DPL=DPL
654 654 dataOut.NSCAN=NSCAN
655 655 dataOut.paramInterval=0#int(dataOut.nint*dataOut.header[7][0]*2 )
656 656 dataOut.lat=-11.95
657 657 dataOut.lon=-76.87
658 658 dataOut.datalags=None
659 659
660 660 dataOut.datalags=numpy.copy(self.LagDistribution(dataOut))
661 661 dataOut.datalags[1,:,:,:]=self.HeightReconstruction(dataOut)
662 662
663 663 return dataOut
664 664
665 665 class LagsReshapeHP(Operation):
666 666 '''
667 667 Written by R. Flores
668 668 '''
669 669 """Operation to reshape input data into (Channels,Profiles(with same lag),Heights,Lags) and heights reconstruction.
670 670
671 671 Parameters:
672 672 -----------
673 673
674 674
675 675 Example
676 676 --------
677 677
678 678 op = proc_unit.addOperation(name='LagsReshape')
679 679
680 680
681 681 """
682 682
683 683 def __init__(self, **kwargs):
684 684
685 685 Operation.__init__(self, **kwargs)
686 686
687 687 self.buffer=None
688 688 self.buffer_HR=None
689 689 self.buffer_HRonelag=None
690 690
691 691 def LagDistribution(self,dataOut):
692 692
693 693 dataOut.datapure=numpy.copy(dataOut.data[:,0:dataOut.NSCAN,:])
694 694 self.buffer = numpy.zeros((dataOut.nChannels,
695 695 int(dataOut.NSCAN/dataOut.DPL),
696 696 dataOut.nHeights,dataOut.DPL),
697 697 dtype='complex')
698 698
699 699 for j in range(int(self.buffer.shape[1]/2)):
700 700 for i in range(dataOut.DPL):
701 701 if j+1==int(self.buffer.shape[1]/2) and i+1==dataOut.DPL:
702 702 self.buffer[:,2*j:,:,i]=dataOut.datapure[:,2*i+int(2*j*dataOut.DPL):,:]
703 703 else:
704 704 self.buffer[:,2*j:2*(j+1),:,i]=dataOut.datapure[:,2*i+int(2*j*dataOut.DPL):2*(i+1)+int(2*j*dataOut.DPL),:]
705 705
706 706 return self.buffer
707 707
708 708 def HeightReconstruction(self,dataOut):
709 709
710 710 self.buffer_HR = numpy.zeros((int(dataOut.NSCAN/dataOut.DPL),
711 711 dataOut.nHeights,dataOut.DPL),
712 712 dtype='complex')
713 713
714 714 for i in range(int(dataOut.DPL)): #Only channel B
715 715 if i==0:
716 716 self.buffer_HR[:,:,i]=dataOut.datalags[1,:,:,i]
717 717 else:
718 718 self.buffer_HR[:,:,i]=self.HRonelag(dataOut,i)
719 719
720 720 return self.buffer_HR
721 721
722 722
723 723 def HRonelag(self,dataOut,whichlag):
724 724 self.buffer_HRonelag = numpy.zeros((int(dataOut.NSCAN/dataOut.DPL),
725 725 dataOut.nHeights),
726 726 dtype='complex')
727 727
728 728 for i in range(self.buffer_HRonelag.shape[0]):
729 729 for j in range(dataOut.nHeights):
730 730 if j+int(2*whichlag)<dataOut.nHeights:
731 731 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i,j+2*whichlag,whichlag]
732 732 else:
733 733 if whichlag!=10:
734 734 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i,(j+2*whichlag)%dataOut.nHeights,whichlag+1]
735 735 else:
736 736 if i+2<self.buffer_HRonelag.shape[0]:
737 737 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i+2,(j+2*whichlag)%dataOut.nHeights,0]
738 738 else: #i+1==self.buffer_HRonelag.shape[0]:
739 739 self.buffer_HRonelag[i,j]=dataOut.datalags[1,i,(j+2*whichlag)%dataOut.nHeights,whichlag]
740 740
741 741 return self.buffer_HRonelag
742 742
743 743
744 744
745 745 def run(self,dataOut,DPL=11,NSCAN=132):
746 746
747 747 dataOut.DPL=DPL
748 748 dataOut.NSCAN=NSCAN
749 749 dataOut.paramInterval=0#int(dataOut.nint*dataOut.header[7][0]*2 )
750 750 dataOut.lat=-11.95
751 751 dataOut.lon=-76.87
752 752 dataOut.datalags=None
753 753
754 754 dataOut.datalags=numpy.copy(self.LagDistribution(dataOut))
755 755 dataOut.datalags[1,:,:,:]=self.HeightReconstruction(dataOut)
756 756
757 757 return dataOut
758 758
759 759 class LagsReshapeDP_V2(Operation):
760 760 '''
761 761 Written by R. Flores
762 762 '''
763 763 """Operation to reshape input data into (Channels,Profiles(with same lag),Heights,Lags) and heights reconstruction.
764 764
765 765 Parameters:
766 766 -----------
767 767
768 768
769 769 Example
770 770 --------
771 771
772 772 op = proc_unit.addOperation(name='LagsReshape')
773 773
774 774
775 775 """
776 776
777 777 def __init__(self, **kwargs):
778 778
779 779 Operation.__init__(self, **kwargs)
780 780
781 781 self.buffer=None
782 782 self.data_buffer = []
783 783
784 784 def setup(self,dataOut,DPL,NSCAN,NLAG,NRANGE,lagind,lagfirst):
785 785 dataOut.DPL=DPL
786 786 dataOut.NSCAN=NSCAN
787 787 dataOut.NLAG = NLAG
788 788 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
789 789 dataOut.NRANGE = NRANGE
790 790 dataOut.read_samples=int(dataOut.nHeights)
791 791 #print(dataOut.read_samples)
792 792 #print(dataOut.nHeights)
793 793 #exit(1)
794 794 dataOut.NDP = dataOut.NDT = int((dataOut.nHeights-dataOut.NRANGE)/2)
795 795 dataOut.heightList = numpy.arange(dataOut.NDP) *deltaHeight# + dataOut.heightList[0]
796 796 #dataOut.NDP = dataOut.NDT = int(dataOut.nHeights/2)#int((dataOut.nHeights-dataOut.NRANGE)/2)
797 797 #print(dataOut.NDP)
798 798 #print(dataOut.heightList)
799 799 dataOut.paramInterval=0#int(dataOut.nint*dataOut.header[7][0]*2 )
800 800 dataOut.lat=-11.95
801 801 dataOut.lon=-76.87
802 802 dataOut.datalags=None
803 803 dataOut.lagind=lagind
804 804 dataOut.lagfirst=lagfirst
805 805
806 806
807 807 def LagDistribution(self,dataOut):
808 808
809 809 self.buffer = numpy.zeros((dataOut.nChannels,
810 810 int(2*2*dataOut.NSCAN/dataOut.NLAG),
811 811 dataOut.NDP,dataOut.DPL),
812 812 dtype='complex')
813 813
814 814 indProfile = numpy.arange(0,dataOut.NSCAN,1)//8
815 815
816 816 #dataOut.nNoiseProfiles = dataOut.nProfiles-dataOut.NSCAN
817 817
818 818 for i in range(2):
819 819 if i==0:
820 820 aux = 0
821 821 else:
822 822 aux =16
823 823 for j in range(dataOut.NDP):
824 824 for k in range(int(dataOut.NSCAN)):
825 825
826 826 n=dataOut.lagind[k%dataOut.NLAG]
827 827
828 828 data_ChA=dataOut.data[0,k,dataOut.NRANGE+j+i*dataOut.NDT]#-dataOut.dc[0]
829 829
830 830 if dataOut.NRANGE+j+i*dataOut.NDT+2*n<dataOut.read_samples:
831 831
832 832 data_ChB=dataOut.data[1,k,dataOut.NRANGE+j+i*dataOut.NDT+2*n]#-dataOut.dc[1]
833 833 #print(data_ChB)
834 834 #exit(1)
835 835 #print("*1*")
836 836
837 837 else:
838 838 #print(i,j,n)
839 839 #exit(1)
840 840
841 841 if k+1<int(dataOut.NSCAN):
842 842 data_ChB=dataOut.data[1,k+1,(dataOut.NRANGE+j+i*dataOut.NDT+2*n)%dataOut.NDP]
843 843 #print(data_ChB)
844 844 #print("*2*")
845 845 #exit(1)
846 846 if k+1==int(dataOut.NSCAN):
847 847 data_ChB=dataOut.data[1,k,(dataOut.NRANGE+j+i*dataOut.NDT+2*n)%dataOut.NDP]
848 848 #print("*3*")
849 849 #if n == 7 and j == 65:
850 850 #print(k)
851 851 #print(data_ChB)
852 852 #exit(1)
853 853 if n == 8 or n == 9 or n == 10:
854 854 self.buffer[0,int((aux+indProfile[k]-1)/2),j,n] = data_ChA
855 855 self.buffer[1,int((aux+indProfile[k]-1)/2),j,n] = data_ChB
856 856 elif n == 1 or n == 2 or n == 7:
857 857 self.buffer[0,int((aux+indProfile[k])/2),j,n] = data_ChA
858 858 self.buffer[1,int((aux+indProfile[k])/2),j,n] = data_ChB
859 859 else:
860 860 self.buffer[0,aux+indProfile[k],j,n] = data_ChA
861 861 self.buffer[1,aux+indProfile[k],j,n] = data_ChB
862 862
863 863 #FindMe
864 864 pa1 = 20
865 865 pa2 = 10
866 866
867 867 #print(self.buffer[0,:,pa1,pa2])
868 868 #print(self.buffer[1,:,pa1,pa2])
869 869 '''
870 870 print(sum(self.buffer[0,:,pa1,pa2]))
871 871 print(sum(self.buffer[1,:,pa1,pa2]))
872 872 #exit(1)
873 873 '''
874 874
875 875 '''
876 876 for pa1 in range(67):
877 877 print(sum(self.buffer[0,:,pa1,pa2]))
878 878 print(sum(self.buffer[1,:,pa1,pa2]))
879 879 '''
880 880
881 881 '''
882 882 import matplotlib.pyplot as plt
883 883 fft = numpy.fft.fft(self.buffer[0,:,pa1,pa2])
884 884 fft2 = fft*numpy.conjugate(fft)
885 885 fft2 = fft2.real
886 886 fft2 = numpy.fft.fftshift(fft2)
887 887 '''
888 888 #print("before",fft2)
889 889 #plt.plot(fft2)
890 890 #plt.show()
891 891 #import time
892 892 #time.sleep(5)
893 893 #plt.close('all')
894 894 #exit(1)
895 895 return self.buffer
896 896
897 897
898 898
899 899 def run(self,dataOut,DPL=11,NSCAN=128,lagind=(0,1,2,3,4,5,6,7,0,3,4,5,6,8,9,10),lagfirst=(1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1), NLAG = 16, NRANGE = 200):
900 900
901 901 if not self.isConfig:
902 902 self.setup(dataOut,DPL,NSCAN,NLAG,NRANGE,lagind,lagfirst)
903 903 self.isConfig = True
904 904
905 905 #print(dataOut.data[1,:12,:15])
906 906 #exit(1)
907 907 #print(numpy.shape(dataOut.data))
908 908 #print(dataOut.profileIndex)
909 909
910 910 if not dataOut.flagDataAsBlock:
911 911
912 912 dataOut.flagNoData = True
913 913 #print("nProfiles: ",dataOut.nProfiles)
914 914 #if dataOut.profileIndex == 140:
915 915 #print("id: ",dataOut.profileIndex)
916 916 if dataOut.profileIndex == dataOut.nProfiles-1:
917 917 #print("here")
918 918 #print(dataOut.data.shape)
919 919 self.data_buffer.append(dataOut.data)
920 920 dataOut.data = numpy.transpose(numpy.array(self.data_buffer),(1,0,2))
921 921 #print(dataOut.data.shape)
922 922 #print(numpy.sum(dataOut.data))
923 923 #print(dataOut.data[1,100,:])
924 924 #exit(1)
925 925 dataOut.datalags = numpy.copy(self.LagDistribution(dataOut))
926 926 #print(numpy.shape(dataOut.datalags))
927 927 #exit(1)
928 928 #print("AFTER RESHAPE DP")
929 929
930 930 dataOut.data = dataOut.data[:,:,200:]
931 931 self.data_buffer = []
932 932 dataOut.flagDataAsBlock = True
933 933 dataOut.flagNoData = False
934 934
935 935 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
936 936 dataOut.heightList = numpy.arange(dataOut.NDP) *deltaHeight# + dataOut.heightList[0]
937 937 #exit(1)
938 938 #print(numpy.sum(dataOut.datalags))
939 939 #exit(1)
940 940
941 941 else:
942 942 self.data_buffer.append(dataOut.data)
943 943 #print(numpy.shape(dataOut.data))
944 944 #exit(1)
945 945 else:
946 946 #print(dataOut.data.shape)
947 947 #print(numpy.sum(dataOut.data))
948 948 #print(dataOut.data[1,100,:])
949 949 #exit(1)
950 950 dataOut.datalags = numpy.copy(self.LagDistribution(dataOut))
951 951 #print(dataOut.datalags.shape)
952 952 dataOut.data = dataOut.data[:,:,200:]
953 953 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
954 954 dataOut.heightList = numpy.arange(dataOut.NDP) * deltaHeight# + dataOut.heightList[0]
955 955 #print(dataOut.nHeights)
956 956 #print(numpy.sum(dataOut.datalags))
957 957 #exit(1)
958 958
959 959 return dataOut
960 960
961 961 class CrossProdDP(Operation):
962 962 '''
963 963 Written by R. Flores
964 964 '''
965 965 """Operation to calculate cross products of the Double Pulse Experiment.
966 966
967 967 Parameters:
968 968 -----------
969 969 NLAG : int
970 970 Number of lags Long Pulse.
971 971 NRANGE : int
972 972 Number of samples for Long Pulse.
973 973 NCAL : int
974 974 .*
975 975 DPL : int
976 976 Number of lags Double Pulse.
977 977 NDN : int
978 978 .*
979 979 NDT : int
980 980 Number of heights for Double Pulse.*
981 981 NDP : int
982 982 Number of heights for Double Pulse.*
983 983 NSCAN : int
984 984 Number of profiles when the transmitter is on.
985 985 flags_array : intlist
986 986 .*
987 987 NAVG : int
988 988 Number of blocks to be "averaged".
989 989 nkill : int
990 990 Number of blocks not to be considered when averaging.
991 991
992 992 Example
993 993 --------
994 994
995 995 op = proc_unit.addOperation(name='CrossProdDP', optype='other')
996 996 op.addParameter(name='NLAG', value='16', format='int')
997 997 op.addParameter(name='NRANGE', value='0', format='int')
998 998 op.addParameter(name='NCAL', value='0', format='int')
999 999 op.addParameter(name='DPL', value='11', format='int')
1000 1000 op.addParameter(name='NDN', value='0', format='int')
1001 1001 op.addParameter(name='NDT', value='66', format='int')
1002 1002 op.addParameter(name='NDP', value='66', format='int')
1003 1003 op.addParameter(name='NSCAN', value='132', format='int')
1004 1004 op.addParameter(name='flags_array', value='(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300)', format='intlist')
1005 1005 op.addParameter(name='NAVG', value='16', format='int')
1006 1006 op.addParameter(name='nkill', value='6', format='int')
1007 1007
1008 1008 """
1009 1009
1010 1010 def __init__(self, **kwargs):
1011 1011
1012 1012 Operation.__init__(self, **kwargs)
1013 1013 self.bcounter=0
1014 1014 self.aux=1
1015 1015 self.lag_products_LP_median_estimates_aux=0
1016 1016
1017 1017 def set_header_output(self,dataOut):
1018 1018
1019 1019 dataOut.read_samples=len(dataOut.heightList)#int(dataOut.systemHeaderObj.nSamples/dataOut.windowOfFilter)
1020 1020 padding=numpy.zeros(1,'int32')
1021 1021 hsize=numpy.zeros(1,'int32')
1022 1022 bufsize=numpy.zeros(1,'int32')
1023 1023 nr=numpy.zeros(1,'int32')
1024 1024 ngates=numpy.zeros(1,'int32') ### ### ### 2
1025 1025 time1=numpy.zeros(1,'uint64') # pos 3
1026 1026 time2=numpy.zeros(1,'uint64') # pos 4
1027 1027 lcounter=numpy.zeros(1,'int32')
1028 1028 groups=numpy.zeros(1,'int32')
1029 1029 system=numpy.zeros(4,'int8') # pos 7
1030 1030 h0=numpy.zeros(1,'float32')
1031 1031 dh=numpy.zeros(1,'float32')
1032 1032 ipp=numpy.zeros(1,'float32')
1033 1033 process=numpy.zeros(1,'int32')
1034 1034 tx=numpy.zeros(1,'int32')
1035 1035 ngates1=numpy.zeros(1,'int32') ### ### ### 13
1036 1036 time0=numpy.zeros(1,'uint64') # pos 14
1037 1037 nlags=numpy.zeros(1,'int32')
1038 1038 nlags1=numpy.zeros(1,'int32')
1039 1039 txb=numpy.zeros(1,'float32') ### ### ### 17
1040 1040 time3=numpy.zeros(1,'uint64') # pos 18
1041 1041 time4=numpy.zeros(1,'uint64') # pos 19
1042 1042 h0_=numpy.zeros(1,'float32')
1043 1043 dh_=numpy.zeros(1,'float32')
1044 1044 ipp_=numpy.zeros(1,'float32')
1045 1045 txa_=numpy.zeros(1,'float32')
1046 1046 pad=numpy.zeros(100,'int32')
1047 1047 nbytes=numpy.zeros(1,'int32')
1048 1048 limits=numpy.zeros(1,'int32')
1049 1049 ngroups=numpy.zeros(1,'int32') ### ### ### 27
1050 1050
1051 1051 dataOut.header=[hsize,bufsize,nr,ngates,time1,time2,
1052 1052 lcounter,groups,system,h0,dh,ipp,
1053 1053 process,tx,ngates1,padding,time0,nlags,
1054 1054 nlags1,padding,txb,time3,time4,h0_,dh_,
1055 1055 ipp_,txa_,pad,nbytes,limits,padding,ngroups]
1056 1056
1057 1057
1058 1058 #dataOut.header[1][0]=81864
1059 1059 dataOut.FirstHeight=int(dataOut.heightList[0])
1060 1060 dataOut.MAXNRANGENDT=max(dataOut.NRANGE,dataOut.NDT)
1061 1061 dataOut.header[3][0]=max(dataOut.NRANGE,dataOut.NDT)
1062 1062 dataOut.header[7][0]=dataOut.NAVG
1063 1063 dataOut.header[9][0]=int(dataOut.heightList[0])
1064 1064 dataOut.header[10][0]=dataOut.DH
1065 1065 dataOut.header[17][0]=dataOut.DPL
1066 1066 dataOut.header[18][0]=dataOut.NLAG
1067 1067 #self.header[5][0]=0
1068 1068 dataOut.header[15][0]=dataOut.NDP
1069 1069 dataOut.header[2][0]=dataOut.NR
1070 1070
1071 1071
1072 1072 def get_products_cabxys(self,dataOut):
1073 1073
1074 1074 if self.aux==1:
1075 1075 self.set_header_output(dataOut)
1076 1076 self.aux=0
1077 1077
1078 1078 dataOut.lags_array=[x / dataOut.DH for x in dataOut.flags_array]
1079 1079 self.cax=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1080 1080 self.cay=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1081 1081 self.cbx=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1082 1082 self.cby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1083 1083 self.cax2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1084 1084 self.cay2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1085 1085 self.cbx2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1086 1086 self.cby2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1087 1087 self.caxbx=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1088 1088 self.caxby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1089 1089 self.caybx=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1090 1090 self.cayby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1091 1091 self.caxay=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1092 1092 self.cbxby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
1093 1093
1094 1094 for i in range(2):
1095 1095 for j in range(dataOut.NDP):
1096 1096 for k in range(int(dataOut.NSCAN/2)):
1097 1097 n=k%dataOut.DPL
1098 1098 ax=dataOut.data[0,2*k+i,j].real
1099 1099 ay=dataOut.data[0,2*k+i,j].imag
1100 1100 if j+dataOut.lags_array[n]<dataOut.NDP:
1101 1101 bx=dataOut.data[1,2*k+i,j+int(dataOut.lags_array[n])].real
1102 1102 by=dataOut.data[1,2*k+i,j+int(dataOut.lags_array[n])].imag
1103 1103 else:
1104 1104 if k+1<int(dataOut.NSCAN/2):
1105 1105 bx=dataOut.data[1,2*(k+1)+i,(dataOut.NRANGE+dataOut.NCAL+j+int(dataOut.lags_array[n]))%dataOut.NDP].real
1106 1106 by=dataOut.data[1,2*(k+1)+i,(dataOut.NRANGE+dataOut.NCAL+j+int(dataOut.lags_array[n]))%dataOut.NDP].imag
1107 1107
1108 1108 if k+1==int(dataOut.NSCAN/2):
1109 1109 bx=dataOut.data[1,2*k+i,(dataOut.NRANGE+dataOut.NCAL+j+int(dataOut.lags_array[n]))%dataOut.NDP].real
1110 1110 by=dataOut.data[1,2*k+i,(dataOut.NRANGE+dataOut.NCAL+j+int(dataOut.lags_array[n]))%dataOut.NDP].imag
1111 1111
1112 1112 if(k<dataOut.DPL):
1113 1113 self.cax[j][n][i]=ax
1114 1114 self.cay[j][n][i]=ay
1115 1115 self.cbx[j][n][i]=bx
1116 1116 self.cby[j][n][i]=by
1117 1117 self.cax2[j][n][i]=ax*ax
1118 1118 self.cay2[j][n][i]=ay*ay
1119 1119 self.cbx2[j][n][i]=bx*bx
1120 1120 self.cby2[j][n][i]=by*by
1121 1121 self.caxbx[j][n][i]=ax*bx
1122 1122 self.caxby[j][n][i]=ax*by
1123 1123 self.caybx[j][n][i]=ay*bx
1124 1124 self.cayby[j][n][i]=ay*by
1125 1125 self.caxay[j][n][i]=ax*ay
1126 1126 self.cbxby[j][n][i]=bx*by
1127 1127 else:
1128 1128 self.cax[j][n][i]+=ax
1129 1129 self.cay[j][n][i]+=ay
1130 1130 self.cbx[j][n][i]+=bx
1131 1131 self.cby[j][n][i]+=by
1132 1132 self.cax2[j][n][i]+=ax*ax
1133 1133 self.cay2[j][n][i]+=ay*ay
1134 1134 self.cbx2[j][n][i]+=bx*bx
1135 1135 self.cby2[j][n][i]+=by*by
1136 1136 self.caxbx[j][n][i]+=ax*bx
1137 1137 self.caxby[j][n][i]+=ax*by
1138 1138 self.caybx[j][n][i]+=ay*bx
1139 1139 self.cayby[j][n][i]+=ay*by
1140 1140 self.caxay[j][n][i]+=ax*ay
1141 1141 self.cbxby[j][n][i]+=bx*by
1142 1142
1143 1143
1144 1144 def medi(self,data_navg,NAVG,nkill):
1145 1145 sorts=sorted(data_navg)
1146 1146 rsorts=numpy.arange(NAVG)
1147 1147 result=0.0
1148 1148 for k in range(NAVG):
1149 1149 if k>=nkill/2 and k<NAVG-nkill/2:
1150 1150 result+=sorts[k]*float(NAVG)/(float)(NAVG-nkill)
1151 1151 return result
1152 1152
1153 1153
1154 1154 def get_dc(self,dataOut):
1155 1155 if self.bcounter==0:
1156 1156 dataOut.dc=numpy.zeros(dataOut.NR,dtype='complex64')
1157 1157 def cabxys_navg(self,dataOut):
1158 1158
1159 1159
1160 1160 dataOut.header[5][0]=dataOut.TimeBlockSeconds
1161 1161
1162 1162 dataOut.LastAVGDate=dataOut.TimeBlockSeconds
1163 1163
1164 1164 if self.bcounter==0:
1165 1165 dataOut.FirstAVGDate=dataOut.TimeBlockSeconds
1166 1166 dataOut.header[4][0]=dataOut.header[5][0]#firsttimeofNAVG
1167 1167 if dataOut.CurrentBlock==1:
1168 1168 dataOut.FirstBlockDate=dataOut.TimeBlockSeconds
1169 1169 dataOut.header[16][0]=dataOut.header[5][0]#FirsTimeOfTotalBlocks
1170 1170
1171 1171 self.cax_navg=[]
1172 1172 self.cay_navg=[]
1173 1173 self.cbx_navg=[]
1174 1174 self.cby_navg=[]
1175 1175 self.cax2_navg=[]
1176 1176 self.cay2_navg=[]
1177 1177 self.cbx2_navg=[]
1178 1178 self.cby2_navg=[]
1179 1179 self.caxbx_navg=[]
1180 1180 self.caxby_navg=[]
1181 1181 self.caybx_navg=[]
1182 1182 self.cayby_navg=[]
1183 1183 self.caxay_navg=[]
1184 1184 self.cbxby_navg=[]
1185 1185
1186 1186 dataOut.noisevector=numpy.zeros((dataOut.MAXNRANGENDT,dataOut.NR,dataOut.NAVG),'float32') #30/03/2020
1187 1187
1188 1188 dataOut.noisevector_=numpy.zeros((dataOut.read_samples,dataOut.NR,dataOut.NAVG),'float32')
1189 1189
1190 1190 self.noisevectorizer(dataOut.NSCAN,dataOut.nProfiles,dataOut.NR,dataOut.MAXNRANGENDT,dataOut.noisevector,dataOut.data,dataOut.dc) #30/03/2020
1191 1191
1192 1192 self.cax_navg.append(self.cax)
1193 1193 self.cay_navg.append(self.cay)
1194 1194 self.cbx_navg.append(self.cbx)
1195 1195 self.cby_navg.append(self.cby)
1196 1196 self.cax2_navg.append(self.cax2)
1197 1197 self.cay2_navg.append(self.cay2)
1198 1198 self.cbx2_navg.append(self.cbx2)
1199 1199 self.cby2_navg.append(self.cby2)
1200 1200 self.caxbx_navg.append(self.caxbx)
1201 1201 self.caxby_navg.append(self.caxby)
1202 1202 self.caybx_navg.append(self.caybx)
1203 1203 self.cayby_navg.append(self.cayby)
1204 1204 self.caxay_navg.append(self.caxay)
1205 1205 self.cbxby_navg.append(self.cbxby)
1206 1206 self.bcounter+=1
1207 1207
1208 1208 def noise_estimation4x_DP(self,dataOut):
1209 1209 if self.bcounter==dataOut.NAVG:
1210 1210 dataOut.noise_final=numpy.zeros(dataOut.NR,'float32')
1211 1211 snoise=numpy.zeros((dataOut.NR,dataOut.NAVG),'float32')
1212 1212 nvector1=numpy.zeros((dataOut.NR,dataOut.NAVG,dataOut.MAXNRANGENDT),'float32')
1213 1213 for i in range(dataOut.NR):
1214 1214 dataOut.noise_final[i]=0.0
1215 1215 for k in range(dataOut.NAVG):
1216 1216 snoise[i][k]=0.0
1217 1217 for j in range(dataOut.MAXNRANGENDT):
1218 1218 nvector1[i][k][j]= dataOut.noisevector[j][i][k];
1219 1219 snoise[i][k]=self.noise_hs4x(dataOut.MAXNRANGENDT, nvector1[i][k])
1220 1220 dataOut.noise_final[i]=self.noise_hs4x(dataOut.NAVG, snoise[i])
1221 1221
1222 1222 def kabxys(self,dataOut):
1223 1223
1224 1224 if self.bcounter==dataOut.NAVG:
1225 1225
1226 1226 dataOut.flagNoData = False
1227 1227
1228 1228 self.kax=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1229 1229 self.kay=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1230 1230 self.kbx=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1231 1231 self.kby=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1232 1232 self.kax2=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1233 1233 self.kay2=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1234 1234 self.kbx2=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1235 1235 self.kby2=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1236 1236 self.kaxbx=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1237 1237 self.kaxby=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1238 1238 self.kaybx=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1239 1239 self.kayby=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1240 1240 self.kaxay=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1241 1241 self.kbxby=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1242 1242
1243 1243 for i in range(self.cax_navg[0].shape[0]):
1244 1244 for j in range(self.cax_navg[0].shape[1]):
1245 1245 for k in range(self.cax_navg[0].shape[2]):
1246 1246 data_navg=[item[i,j,k] for item in self.cax_navg]
1247 1247 self.kax[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1248 1248 data_navg=[item[i,j,k] for item in self.cay_navg]
1249 1249 self.kay[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1250 1250 data_navg=[item[i,j,k] for item in self.cbx_navg]
1251 1251 self.kbx[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1252 1252 data_navg=[item[i,j,k] for item in self.cby_navg]
1253 1253 self.kby[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1254 1254 data_navg=[item[i,j,k] for item in self.cax2_navg]
1255 1255 self.kax2[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1256 1256 data_navg=[item[i,j,k] for item in self.cay2_navg]
1257 1257 self.kay2[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1258 1258 data_navg=[item[i,j,k] for item in self.cbx2_navg]
1259 1259 self.kbx2[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1260 1260 data_navg=[item[i,j,k] for item in self.cby2_navg]
1261 1261 self.kby2[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1262 1262 data_navg=[item[i,j,k] for item in self.caxbx_navg]
1263 1263 self.kaxbx[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1264 1264 data_navg=[item[i,j,k] for item in self.caxby_navg]
1265 1265 self.kaxby[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1266 1266 data_navg=[item[i,j,k] for item in self.caybx_navg]
1267 1267 self.kaybx[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1268 1268 data_navg=[item[i,j,k] for item in self.cayby_navg]
1269 1269 self.kayby[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1270 1270 data_navg=[item[i,j,k] for item in self.caxay_navg]
1271 1271 self.kaxay[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1272 1272 data_navg=[item[i,j,k] for item in self.cbxby_navg]
1273 1273 self.kbxby[i,j,k]=self.medi(data_navg,dataOut.NAVG,dataOut.nkill)
1274 1274
1275 1275
1276 1276 dataOut.kax=self.kax
1277 1277 dataOut.kay=self.kay
1278 1278 dataOut.kbx=self.kbx
1279 1279 dataOut.kby=self.kby
1280 1280 dataOut.kax2=self.kax2
1281 1281 dataOut.kay2=self.kay2
1282 1282 dataOut.kbx2=self.kbx2
1283 1283 dataOut.kby2=self.kby2
1284 1284 dataOut.kaxbx=self.kaxbx
1285 1285 dataOut.kaxby=self.kaxby
1286 1286 dataOut.kaybx=self.kaybx
1287 1287 dataOut.kayby=self.kayby
1288 1288 dataOut.kaxay=self.kaxay
1289 1289 dataOut.kbxby=self.kbxby
1290 1290
1291 1291 self.bcounter=0
1292 1292
1293 1293 dataOut.crossprods=numpy.zeros((3,4,numpy.shape(dataOut.kax)[0],numpy.shape(dataOut.kax)[1],numpy.shape(dataOut.kax)[2]))
1294 1294
1295 1295 dataOut.crossprods[0]=[dataOut.kax,dataOut.kay,dataOut.kbx,dataOut.kby]
1296 1296 dataOut.crossprods[1]=[dataOut.kax2,dataOut.kay2,dataOut.kbx2,dataOut.kby2]
1297 1297 dataOut.crossprods[2]=[dataOut.kaxay,dataOut.kbxby,dataOut.kaxbx,dataOut.kaxby]
1298 1298 #print("before: ",self.dataOut.noise_final)
1299 1299 dataOut.data_for_RTI_DP=numpy.zeros((3,dataOut.NDP))
1300 1300 dataOut.data_for_RTI_DP[0],dataOut.data_for_RTI_DP[1],dataOut.data_for_RTI_DP[2]=self.RTI_COLUMN(dataOut.kax2,dataOut.kay2,dataOut.kbx2,dataOut.kby2,dataOut.kaxbx,dataOut.kayby,dataOut.kaybx,dataOut.kaxby, dataOut.NDP)
1301 1301
1302 1302
1303 1303
1304 1304 def RTI_COLUMN(self,kax2,kay2,kbx2,kby2,kaxbx,kayby,kaybx,kaxby, NDP):
1305 1305 x00=numpy.zeros(NDP,dtype='float32')
1306 1306 x01=numpy.zeros(NDP,dtype='float32')
1307 1307 x02=numpy.zeros(NDP,dtype='float32')
1308 1308 for j in range(2):# first couple lags
1309 1309 for k in range(2): #flip
1310 1310 for i in range(NDP): #
1311 1311 fx=numpy.sqrt((kaxbx[i,j,k]+kayby[i,j,k])**2+(kaybx[i,j,k]-kaxby[i,j,k])**2)
1312 1312 x00[i]=x00[i]+(kax2[i,j,k]+kay2[i,j,k])
1313 1313 x01[i]=x01[i]+(kbx2[i,j,k]+kby2[i,j,k])
1314 1314 x02[i]=x02[i]+fx
1315 1315
1316 1316 x00[i]=10.0*numpy.log10(x00[i]/512.)
1317 1317 x01[i]=10.0*numpy.log10(x01[i]/512.)
1318 1318 x02[i]=10.0*numpy.log10(x02[i])
1319 1319 return x02,x00,x01
1320 1320
1321 1321
1322 1322
1323 1323
1324 1324
1325 1325
1326 1326 #30/03/2020:
1327 1327 def noisevectorizer(self,NSCAN,nProfiles,NR,MAXNRANGENDT,noisevector,data,dc):
1328 1328
1329 1329 rnormalizer= 1./(float(nProfiles - NSCAN))
1330 1330 #rnormalizer= float(NSCAN)/((float(nProfiles - NSCAN))*float(MAXNRANGENDT))
1331 1331 for i in range(NR):
1332 1332 for j in range(MAXNRANGENDT):
1333 1333 for k in range(NSCAN,nProfiles):
1334 1334 #TODO:integrate just 2nd quartile gates
1335 1335 if k==NSCAN:
1336 1336 noisevector[j][i][self.bcounter]=(abs(data[i][k][j]-dc[i])**2)*rnormalizer
1337 1337 else:
1338 1338 noisevector[j][i][self.bcounter]+=(abs(data[i][k][j]-dc[i])**2)*rnormalizer
1339 1339
1340 1340
1341 1341
1342 1342
1343 1343 def noise_hs4x(self, ndatax, datax):
1344 1344 divider=10#divider was originally 10
1345 1345 noise=0.0
1346 1346 data=numpy.zeros(ndatax,'float32')
1347 1347 ndata1=int(ndatax/4)
1348 1348 ndata2=int(2.5*(ndatax/4.))
1349 1349 ndata=int(ndata2-ndata1)
1350 1350 sorts=sorted(datax)
1351 1351
1352 1352 for k in range(ndata2): # select just second quartile
1353 1353 data[k]=sorts[k+ndata1]
1354 1354 nums_min= int(ndata/divider)
1355 1355 if(int(ndata/divider)> 2):
1356 1356 nums_min= int(ndata/divider)
1357 1357 else:
1358 1358 nums_min=2
1359 1359 sump=0.0
1360 1360 sumq=0.0
1361 1361 j=0
1362 1362 cont=1
1363 1363 while ( (cont==1) and (j<ndata)):
1364 1364 sump+=data[j]
1365 1365 sumq+= data[j]*data[j]
1366 1366 j=j+1
1367 1367 if (j> nums_min):
1368 1368 rtest= float(j/(j-1)) +1.0/ndata
1369 1369 if( (sumq*j) > (rtest*sump*sump ) ):
1370 1370 j=j-1
1371 1371 sump-= data[j]
1372 1372 sumq-=data[j]*data[j]
1373 1373 cont= 0
1374 1374 noise= (sump/j)
1375 1375
1376 1376 return noise
1377 1377
1378 1378
1379 1379
1380 1380 def run(self, dataOut, NLAG=16, NRANGE=0, NCAL=0, DPL=11,
1381 1381 NDN=0, NDT=66, NDP=66, NSCAN=132,
1382 1382 flags_array=(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300), NAVG=16, nkill=6, **kwargs):
1383 1383
1384 1384 dataOut.NLAG=NLAG
1385 1385 dataOut.NR=len(dataOut.channelList)
1386 1386 dataOut.NRANGE=NRANGE
1387 1387 dataOut.NCAL=NCAL
1388 1388 dataOut.DPL=DPL
1389 1389 dataOut.NDN=NDN
1390 1390 dataOut.NDT=NDT
1391 1391 dataOut.NDP=NDP
1392 1392 dataOut.NSCAN=NSCAN
1393 1393 dataOut.DH=dataOut.heightList[1]-dataOut.heightList[0]
1394 1394 dataOut.H0=int(dataOut.heightList[0])
1395 1395 dataOut.flags_array=flags_array
1396 1396 dataOut.NAVG=NAVG
1397 1397 dataOut.nkill=nkill
1398 1398 dataOut.flagNoData = True
1399 1399
1400 1400 self.get_dc(dataOut)
1401 1401 self.get_products_cabxys(dataOut)
1402 1402 self.cabxys_navg(dataOut)
1403 1403 self.noise_estimation4x_DP(dataOut)
1404 1404 self.kabxys(dataOut)
1405 1405
1406 1406 return dataOut
1407 1407
1408 1408
1409 1409
1410 1410 class IntegrationDP(Operation):
1411 1411 '''
1412 1412 Written by R. Flores
1413 1413 '''
1414 1414 """Operation to integrate the Double Pulse data.
1415 1415
1416 1416 Parameters:
1417 1417 -----------
1418 1418 nint : int
1419 1419 Number of integrations.
1420 1420
1421 1421 Example
1422 1422 --------
1423 1423
1424 1424 op = proc_unit.addOperation(name='IntegrationDP', optype='other')
1425 1425 op.addParameter(name='nint', value='30', format='int')
1426 1426
1427 1427 """
1428 1428
1429 1429 def __init__(self, **kwargs):
1430 1430
1431 1431 Operation.__init__(self, **kwargs)
1432 1432
1433 1433 self.counter=0
1434 1434 self.aux=0
1435 1435 self.init_time=None
1436 1436
1437 1437 def integration_for_double_pulse(self,dataOut):
1438 1438
1439 1439 if self.aux==1:
1440 1440
1441 1441 dataOut.TimeBlockSeconds_for_dp_power=dataOut.utctime
1442 1442 dataOut.bd_time=gmtime(dataOut.TimeBlockSeconds_for_dp_power)
1443 1443 dataOut.year=dataOut.bd_time.tm_year+(dataOut.bd_time.tm_yday-1)/364.0
1444 1444 dataOut.ut_Faraday=dataOut.bd_time.tm_hour+dataOut.bd_time.tm_min/60.0+dataOut.bd_time.tm_sec/3600.0
1445 1445 self.aux=0
1446 1446
1447 1447 if self.counter==0:
1448 1448
1449 1449 tmpx=numpy.zeros((dataOut.NDP,dataOut.DPL,2),'float32')
1450 1450 dataOut.kabxys_integrated=[tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx,tmpx]
1451 1451 self.init_time=dataOut.utctime
1452 1452
1453 1453 if self.counter < dataOut.nint:
1454 1454
1455 1455 dataOut.final_cross_products=[dataOut.kax,dataOut.kay,dataOut.kbx,dataOut.kby,dataOut.kax2,dataOut.kay2,dataOut.kbx2,dataOut.kby2,dataOut.kaxbx,dataOut.kaxby,dataOut.kaybx,dataOut.kayby,dataOut.kaxay,dataOut.kbxby]
1456 1456
1457 1457 for ind in range(len(dataOut.kabxys_integrated)): #final cross products
1458 1458 dataOut.kabxys_integrated[ind]=dataOut.kabxys_integrated[ind]+dataOut.final_cross_products[ind]
1459 1459
1460 1460 self.counter+=1
1461 1461
1462 1462 if self.counter==dataOut.nint-1:
1463 1463 self.aux=1
1464 1464
1465 1465 if self.counter==dataOut.nint:
1466 1466 dataOut.flagNoData=False
1467 1467 dataOut.utctime=self.init_time
1468 1468 self.counter=0
1469 1469
1470 1470
1471 1471 def run(self,dataOut,nint=20):
1472 1472
1473 1473 dataOut.flagNoData=True
1474 1474 dataOut.nint=nint
1475 1475 dataOut.paramInterval=0#int(dataOut.nint*dataOut.header[7][0]*2 )
1476 1476 dataOut.lat=-11.95
1477 1477 dataOut.lon=-76.87
1478 1478
1479 1479 self.integration_for_double_pulse(dataOut)
1480 1480
1481 1481 return dataOut
1482 1482
1483 1483
1484 1484 class SumFlips(Operation):
1485 1485 '''
1486 1486 Written by R. Flores
1487 1487 '''
1488 1488 """Operation to sum the flip and unflip part of certain cross products of the Double Pulse.
1489 1489
1490 1490 Parameters:
1491 1491 -----------
1492 1492 None
1493 1493
1494 1494 Example
1495 1495 --------
1496 1496
1497 1497 op = proc_unit.addOperation(name='SumFlips', optype='other')
1498 1498
1499 1499 """
1500 1500
1501 1501 def __init__(self, **kwargs):
1502 1502
1503 1503 Operation.__init__(self, **kwargs)
1504 1504
1505 1505
1506 1506 def rint2DP(self,dataOut):
1507 1507
1508 1508 dataOut.rnint2=numpy.zeros(dataOut.DPL,'float32')
1509 1509
1510 1510 for l in range(dataOut.DPL):
1511 1511
1512 1512 dataOut.rnint2[l]=1.0/(dataOut.nint*dataOut.NAVG*12.0)
1513 1513
1514 1514
1515 1515 def SumLags(self,dataOut):
1516 1516
1517 1517 for l in range(dataOut.DPL):
1518 1518 dataOut.kabxys_integrated[4][:,l,0]=(dataOut.kabxys_integrated[4][:,l,0]+dataOut.kabxys_integrated[4][:,l,1])*dataOut.rnint2[l]
1519 1519 dataOut.kabxys_integrated[5][:,l,0]=(dataOut.kabxys_integrated[5][:,l,0]+dataOut.kabxys_integrated[5][:,l,1])*dataOut.rnint2[l]
1520 1520 dataOut.kabxys_integrated[6][:,l,0]=(dataOut.kabxys_integrated[6][:,l,0]+dataOut.kabxys_integrated[6][:,l,1])*dataOut.rnint2[l]
1521 1521 dataOut.kabxys_integrated[7][:,l,0]=(dataOut.kabxys_integrated[7][:,l,0]+dataOut.kabxys_integrated[7][:,l,1])*dataOut.rnint2[l]
1522 1522
1523 1523 dataOut.kabxys_integrated[8][:,l,0]=(dataOut.kabxys_integrated[8][:,l,0]-dataOut.kabxys_integrated[8][:,l,1])*dataOut.rnint2[l]
1524 1524 dataOut.kabxys_integrated[9][:,l,0]=(dataOut.kabxys_integrated[9][:,l,0]-dataOut.kabxys_integrated[9][:,l,1])*dataOut.rnint2[l]
1525 1525 dataOut.kabxys_integrated[10][:,l,0]=(dataOut.kabxys_integrated[10][:,l,0]-dataOut.kabxys_integrated[10][:,l,1])*dataOut.rnint2[l]
1526 1526 dataOut.kabxys_integrated[11][:,l,0]=(dataOut.kabxys_integrated[11][:,l,0]-dataOut.kabxys_integrated[11][:,l,1])*dataOut.rnint2[l]
1527 1527
1528 1528 def run(self,dataOut):
1529 1529
1530 1530 self.rint2DP(dataOut)
1531 1531 self.SumLags(dataOut)
1532 1532
1533 1533 return dataOut
1534 1534
1535 1535
1536 1536 class FlagBadHeights(Operation):
1537 1537 '''
1538 1538 Written by R. Flores
1539 1539 '''
1540 1540 """Operation to flag bad heights (bad data) of the Double Pulse.
1541 1541
1542 1542 Parameters:
1543 1543 -----------
1544 1544 None
1545 1545
1546 1546 Example
1547 1547 --------
1548 1548
1549 1549 op = proc_unit.addOperation(name='FlagBadHeights', optype='other')
1550 1550
1551 1551 """
1552 1552
1553 1553 def __init__(self, **kwargs):
1554 1554
1555 1555 Operation.__init__(self, **kwargs)
1556 1556
1557 1557 def run(self,dataOut):
1558 1558
1559 1559 dataOut.ibad=numpy.zeros((dataOut.NDP,dataOut.DPL),'int32')
1560 1560
1561 1561 for j in range(dataOut.NDP):
1562 1562 for l in range(dataOut.DPL):
1563 1563 ip1=j+dataOut.NDP*(0+2*l)
1564 1564
1565 1565 if( (dataOut.kabxys_integrated[5][j,l,0] <= 0.) or (dataOut.kabxys_integrated[4][j,l,0] <= 0.) or (dataOut.kabxys_integrated[7][j,l,0] <= 0.) or (dataOut.kabxys_integrated[6][j,l,0] <= 0.)):
1566 1566 dataOut.ibad[j][l]=1
1567 1567 else:
1568 1568 dataOut.ibad[j][l]=0
1569 1569
1570 1570 return dataOut
1571 1571
1572 1572 class FlagBadHeightsSpectra(Operation):
1573 1573 '''
1574 1574 Written by R. Flores
1575 1575 '''
1576 1576 """Operation to flag bad heights (bad data) of the Double Pulse.
1577 1577
1578 1578 Parameters:
1579 1579 -----------
1580 1580 None
1581 1581
1582 1582 Example
1583 1583 --------
1584 1584
1585 1585 op = proc_unit.addOperation(name='FlagBadHeightsSpectra', optype='other')
1586 1586
1587 1587 """
1588 1588
1589 1589 def __init__(self, **kwargs):
1590 1590
1591 1591 Operation.__init__(self, **kwargs)
1592 1592
1593 1593 def run(self,dataOut):
1594 1594
1595 1595 dataOut.ibad=numpy.zeros((dataOut.NDP,dataOut.DPL),'int32')
1596 1596
1597 1597 for j in range(dataOut.NDP):
1598 1598 for l in range(dataOut.DPL):
1599 1599 ip1=j+dataOut.NDP*(0+2*l)
1600 1600
1601 1601 if( (dataOut.kabxys_integrated[4][j,l,0] <= 0.) or (dataOut.kabxys_integrated[6][j,l,0] <= 0.)):
1602 1602 dataOut.ibad[j][l]=1
1603 1603 else:
1604 1604 dataOut.ibad[j][l]=0
1605 1605
1606 1606 return dataOut
1607 1607
1608 1608 class CleanCohEchoes(Operation):
1609 1609 '''
1610 1610 Written by R. Flores
1611 1611 '''
1612 1612 """Operation to clean coherent echoes.
1613 1613
1614 1614 Parameters:
1615 1615 -----------
1616 1616 None
1617 1617
1618 1618 Example
1619 1619 --------
1620 1620
1621 1621 op = proc_unit.addOperation(name='CleanCohEchoes')
1622 1622
1623 1623 """
1624 1624
1625 1625 def __init__(self, **kwargs):
1626 1626
1627 1627 Operation.__init__(self, **kwargs)
1628 1628
1629 1629 def remove_coh(self,pow):
1630 1630 q75,q25 = numpy.percentile(pow,[75,25],axis=0)
1631 1631 intr_qr = q75-q25
1632 1632
1633 1633 max = q75+(1.5*intr_qr)
1634 1634 min = q25-(1.5*intr_qr)
1635 1635
1636 1636 pow[pow > max] = numpy.nan
1637 1637
1638 1638 return pow
1639 1639
1640 1640 def mad_based_outlier_V0(self, points, thresh=3.5):
1641 1641
1642 1642 if len(points.shape) == 1:
1643 1643 points = points[:,None]
1644 1644 median = numpy.nanmedian(points, axis=0)
1645 1645 diff = numpy.nansum((points - median)**2, axis=-1)
1646 1646 diff = numpy.sqrt(diff)
1647 1647 med_abs_deviation = numpy.nanmedian(diff)
1648 1648
1649 1649 modified_z_score = 0.6745 * diff / med_abs_deviation
1650 1650
1651 1651 return modified_z_score > thresh
1652 1652
1653 1653 def mad_based_outlier(self, points, thresh=3.5):
1654 1654
1655 1655 median = numpy.nanmedian(points)
1656 1656 diff = (points - median)**2
1657 1657 diff = numpy.sqrt(diff)
1658 1658 med_abs_deviation = numpy.nanmedian(diff)
1659 1659
1660 1660 modified_z_score = 0.6745 * diff / med_abs_deviation
1661 1661
1662 1662 return modified_z_score > thresh
1663 1663
1664
1664
1665 1665
1666 1666 def removeSpreadF(self,dataOut):
1667 1667
1668 1668 #Removing outliers from the profile
1669 1669 nlag = 9
1670 1670 minHei = 180
1671 1671 #maxHei = 600
1672 1672 maxHei = 525
1673 1673 inda = numpy.where(dataOut.heightList >= minHei)
1674 1674 indb = numpy.where(dataOut.heightList <= maxHei)
1675 1675 minIndex = inda[0][0]
1676 1676 maxIndex = indb[0][-1]
1677 1677 outliers_IDs = []
1678 1678
1679 1679 for i in range(15):
1680 1680 minIndex = 12+i#12
1681 1681 #maxIndex = 22+i#35
1682 1682 if gmtime(dataOut.utctime).tm_hour >= 23. or gmtime(dataOut.utctime).tm_hour < 3.:
1683 1683 maxIndex = 31+i#35
1684 1684 else:
1685 1685 maxIndex = 22+i#35
1686 1686 for lag in range(11):
1687 1687 outliers = self.mad_based_outlier(dataOut.kabxys_integrated[6][minIndex:maxIndex,lag,0])
1688 1688 aux = minIndex+numpy.array(outliers.nonzero()).ravel()
1689 1689 outliers_IDs=numpy.append(outliers_IDs,aux)
1690 1690 if outliers_IDs != []:
1691 1691 outliers_IDs=numpy.array(outliers_IDs)
1692 1692 outliers_IDs=outliers_IDs.astype(numpy.dtype('int64'))
1693 1693 (uniq, freq) = (numpy.unique(outliers_IDs, return_counts=True))
1694 1694 aux_arr = numpy.column_stack((uniq,freq))
1695 1695 final_index = []
1696 1696 for i in range(aux_arr.shape[0]):
1697 1697 if aux_arr[i,1] >= 3*11:
1698 1698 final_index.append(aux_arr[i,0])
1699 1699
1700 1700 if final_index != []:# and len(final_index) > 1:
1701 1701 following_index = final_index[-1]+1 #Remove following index to ensure we remove remaining SpreadF
1702 1702 previous_index = final_index[0]-1 #Remove previous index to ensure we remove remaning SpreadF
1703 1703 final_index = numpy.concatenate(([previous_index],final_index,[following_index]))
1704 1704 final_index = numpy.unique(final_index) #If there was only one outlier
1705 1705 dataOut.kabxys_integrated[4][final_index,:,0] = numpy.nan
1706 1706 dataOut.kabxys_integrated[6][final_index,:,0] = numpy.nan
1707 1707
1708 1708 dataOut.flagSpreadF = True
1709 1709
1710 1710 #Removing echoes greater than 35 dB
1711 1711 if hasattr(dataOut.pbn, "__len__"):
1712 1712 maxdB = 10*numpy.log10(dataOut.pbn[0]) + 10 #Lag 0 Noise
1713 1713 else:
1714 1714 maxdB = 10*numpy.log10(dataOut.pbn) + 10
1715 1715
1716 1716 data = numpy.copy(10*numpy.log10(dataOut.kabxys_integrated[6][:,0,0])) #Lag0 ChB
1717 1717
1718 1718 for i in range(12,data.shape[0]):
1719 1719 if data[i]>maxdB:
1720 1720 dataOut.kabxys_integrated[4][i-2:i+3,:,0] = numpy.nan #Debido a que estos ecos son intensos, se
1721 1721 dataOut.kabxys_integrated[6][i-2:i+3,:,0] = numpy.nan #remueven ademΓ‘s dos muestras antes y despuΓ©s
1722 1722 dataOut.flagSpreadF = True
1723 1723
1724 1724 def run(self,dataOut):
1725 1725 dataOut.flagSpreadF = False
1726 1726 if gmtime(dataOut.utctime).tm_hour >= 23. or gmtime(dataOut.utctime).tm_hour < 11.: #18-06 LT
1727 1727 self.removeSpreadF(dataOut)
1728 1728
1729 1729 return dataOut
1730 1730 class NoisePower(Operation):
1731 1731 '''
1732 1732 Written by R. Flores
1733 1733 '''
1734 1734 """Operation to get noise power from the integrated data of the Double Pulse.
1735 1735
1736 1736 Parameters:
1737 1737 -----------
1738 1738 None
1739 1739
1740 1740 Example
1741 1741 --------
1742 1742
1743 1743 op = proc_unit.addOperation(name='NoisePower', optype='other')
1744 1744
1745 1745 """
1746 1746
1747 1747 def __init__(self, **kwargs):
1748 1748
1749 1749 Operation.__init__(self, **kwargs)
1750 1750
1751 1751 def hildebrand(self,dataOut,data):
1752 1752
1753 1753 divider=10 # divider was originally 10
1754 1754 noise=0.0
1755 1755 n1=0
1756 1756 n2=int(dataOut.NDP/2)
1757 1757 sorts= sorted(data)
1758 1758 nums_min= dataOut.NDP/divider
1759 1759 if((dataOut.NDP/divider)> 2):
1760 1760 nums_min= int(dataOut.NDP/divider)
1761 1761
1762 1762 else:
1763 1763 nums_min=2
1764 1764 sump=0.0
1765 1765 sumq=0.0
1766 1766 j=0
1767 1767 cont=1
1768 1768 while( (cont==1) and (j<n2)):
1769 1769 sump+=sorts[j+n1]
1770 1770 sumq+= sorts[j+n1]*sorts[j+n1]
1771 1771 t3= sump/(j+1)
1772 1772 j=j+1
1773 1773 if(j> nums_min):
1774 1774 rtest= float(j/(j-1)) +1.0/dataOut.NAVG
1775 1775 t1= (sumq*j)
1776 1776 t2=(rtest*sump*sump)
1777 1777 if( (t1/t2) > 0.990):
1778 1778 j=j-1
1779 1779 sump-= sorts[j+n1]
1780 1780 sumq-=sorts[j+n1]*sorts[j+n1]
1781 1781 cont= 0
1782 1782
1783 1783 noise= sump/j
1784 1784 stdv=numpy.sqrt((sumq- noise*noise)/(j-1))
1785 1785 return noise
1786 1786
1787 1787 def run(self,dataOut):
1788 1788
1789 1789 p=numpy.zeros((dataOut.NR,dataOut.NDP,dataOut.DPL),'float32')
1790 1790 av=numpy.zeros(dataOut.NDP,'float32')
1791 1791 dataOut.pnoise=numpy.zeros(dataOut.NR,'float32')
1792 1792
1793 1793 p[0,:,:]=dataOut.kabxys_integrated[4][:,:,0]+dataOut.kabxys_integrated[5][:,:,0] #total power for channel 0, just pulse with non-flip
1794 1794 p[1,:,:]=dataOut.kabxys_integrated[6][:,:,0]+dataOut.kabxys_integrated[7][:,:,0] #total power for channel 1
1795 1795
1796 1796 for i in range(dataOut.NR):
1797 1797 dataOut.pnoise[i]=0.0
1798 1798 for k in range(dataOut.DPL):
1799 1799 dataOut.pnoise[i]+= self.hildebrand(dataOut,p[i,:,k])
1800 1800
1801 1801 dataOut.pnoise[i]=dataOut.pnoise[i]/dataOut.DPL
1802 1802
1803 1803
1804 1804 dataOut.pan=1.0*dataOut.pnoise[0] # weights could change
1805 1805 dataOut.pbn=1.0*dataOut.pnoise[1] # weights could change
1806 1806
1807 1807 return dataOut
1808 1808
1809 1809
1810 1810 class DoublePulseACFs(Operation):
1811 1811 '''
1812 1812 Written by R. Flores
1813 1813 '''
1814 1814 """Operation to get the ACFs of the Double Pulse.
1815 1815
1816 1816 Parameters:
1817 1817 -----------
1818 1818 None
1819 1819
1820 1820 Example
1821 1821 --------
1822 1822
1823 1823 op = proc_unit.addOperation(name='DoublePulseACFs', optype='other')
1824 1824
1825 1825 """
1826 1826
1827 1827 def __init__(self, **kwargs):
1828 1828
1829 1829 Operation.__init__(self, **kwargs)
1830 1830 self.aux=1
1831 1831
1832 1832 def run(self,dataOut):
1833 1833
1834 1834 dataOut.igcej=numpy.zeros((dataOut.NDP,dataOut.DPL),'int32')
1835 1835
1836 1836 if self.aux==1:
1837 1837 dataOut.rhor=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1838 1838 dataOut.rhoi=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1839 1839 dataOut.sdp=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1840 1840 dataOut.sd=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1841 1841 dataOut.p=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1842 1842 dataOut.alag=numpy.zeros(dataOut.NDP,'float32')
1843 1843 for l in range(dataOut.DPL):
1844 1844 dataOut.alag[l]=l*dataOut.DH*2.0/150.0
1845 1845 self.aux=0
1846 1846 sn4=dataOut.pan*dataOut.pbn
1847 1847 rhorn=0
1848 1848 rhoin=0
1849 1849 panrm=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1850 1850
1851 1851 for i in range(dataOut.NDP):
1852 1852 for j in range(dataOut.DPL):
1853 1853 ################# Total power
1854 1854 pa=numpy.abs(dataOut.kabxys_integrated[4][i,j,0]+dataOut.kabxys_integrated[5][i,j,0])
1855 1855 pb=numpy.abs(dataOut.kabxys_integrated[6][i,j,0]+dataOut.kabxys_integrated[7][i,j,0])
1856 1856 st4=pa*pb
1857 1857 dataOut.p[i,j]=pa+pb-(dataOut.pan+dataOut.pbn)
1858 1858 dataOut.sdp[i,j]=2*dataOut.rnint2[j]*((pa+pb)*(pa+pb))
1859 1859 ## ACF
1860 1860 rhorp=dataOut.kabxys_integrated[8][i,j,0]+dataOut.kabxys_integrated[11][i,j,0]
1861 1861 rhoip=dataOut.kabxys_integrated[10][i,j,0]-dataOut.kabxys_integrated[9][i,j,0]
1862 1862 if ((pa>dataOut.pan)&(pb>dataOut.pbn)):
1863 1863
1864 1864 ss4=numpy.abs((pa-dataOut.pan)*(pb-dataOut.pbn))
1865 1865 panrm[i,j]=math.sqrt(ss4)
1866 1866 rnorm=1/panrm[i,j]
1867 1867 ## ACF
1868 1868 dataOut.rhor[i,j]=rhorp*rnorm
1869 1869 dataOut.rhoi[i,j]=rhoip*rnorm
1870 1870 ############# Compute standard error for ACF
1871 1871 stoss4=st4/ss4
1872 1872 snoss4=sn4/ss4
1873 1873 rp2=((rhorp*rhorp)+(rhoip*rhoip))/st4
1874 1874 rn2=((rhorn*rhorn)+(rhoin*rhoin))/sn4
1875 1875 rs2=(dataOut.rhor[i,j]*dataOut.rhor[i,j])+(dataOut.rhoi[i,j]*dataOut.rhoi[i,j])
1876 1876 st=1.0+rs2*(stoss4-(2*math.sqrt(stoss4*snoss4)))
1877 1877 stn=1.0+rs2*(snoss4-(2*math.sqrt(stoss4*snoss4)))
1878 1878 dataOut.sd[i,j]=((stoss4*((1.0+rp2)*st+(2.0*rp2*rs2*snoss4)-4.0*math.sqrt(rs2*rp2)))+(0.25*snoss4*((1.0+rn2)*stn+(2.0*rn2*rs2*stoss4)-4.0*math.sqrt(rs2*rn2))))*dataOut.rnint2[j]
1879 1879 dataOut.sd[i,j]=numpy.abs(dataOut.sd[i,j])
1880 1880
1881 1881 else: #default values for bad points
1882 1882 rnorm=1/math.sqrt(st4)
1883 1883 dataOut.sd[i,j]=1.e30
1884 1884 dataOut.ibad[i,j]=4
1885 1885 dataOut.rhor[i,j]=rhorp*rnorm
1886 1886 dataOut.rhoi[i,j]=rhoip*rnorm
1887 1887 if ((pb/dataOut.pbn-1.0)>2.25*(pa/dataOut.pan-1.0)): #To flag bad points from the pulse and EEJ for lags != 0 for Channel B
1888 1888 #print(dataOut.heightList[i],"EJJ")
1889 1889 dataOut.igcej[i,j]=1
1890 1890 elif ((pa/dataOut.pan-1.0)>2.25*(pb/dataOut.pbn-1.0)):
1891 1891 dataOut.igcej[i,j]=1
1892 1892
1893 1893 return dataOut
1894 1894
1895 1895 class DoublePulseACFs_PerLag(Operation):
1896 1896 '''
1897 1897 Written by R. Flores
1898 1898 '''
1899 1899 """Operation to get the ACFs of the Double Pulse.
1900 1900
1901 1901 Parameters:
1902 1902 -----------
1903 1903 None
1904 1904
1905 1905 Example
1906 1906 --------
1907 1907
1908 1908 op = proc_unit.addOperation(name='DoublePulseACFs', optype='other')
1909 1909
1910 1910 """
1911 1911
1912 1912 def __init__(self, **kwargs):
1913 1913
1914 1914 Operation.__init__(self, **kwargs)
1915 1915 self.aux=1
1916 1916
1917 1917 def run(self,dataOut):
1918 1918
1919 1919 dataOut.igcej=numpy.zeros((dataOut.NDP,dataOut.DPL),'int32')
1920 1920
1921 1921 if self.aux==1:
1922 1922 dataOut.rhor=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1923 1923 dataOut.rhoi=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1924 1924 dataOut.sdp=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1925 1925 dataOut.sd=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1926 1926 dataOut.p=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1927 1927 dataOut.alag=numpy.zeros(dataOut.NDP,'float32')
1928 1928 for l in range(dataOut.DPL):
1929 1929 dataOut.alag[l]=l*dataOut.DH*2.0/150.0
1930 1930 self.aux=0
1931 1931 sn4=dataOut.pan*dataOut.pbn
1932 1932 rhorn=0
1933 1933 rhoin=0
1934 1934 panrm=numpy.zeros((dataOut.NDP,dataOut.DPL), dtype=float)
1935 1935
1936 1936 id = numpy.where(dataOut.heightList>700)[0]
1937 1937
1938 1938 for i in range(dataOut.NDP):
1939 1939 for j in range(dataOut.DPL):
1940 1940 ################# Total power
1941 1941 pa=numpy.abs(dataOut.kabxys_integrated[4][i,j,0]+dataOut.kabxys_integrated[5][i,j,0])
1942 1942 pb=numpy.abs(dataOut.kabxys_integrated[6][i,j,0]+dataOut.kabxys_integrated[7][i,j,0])
1943 1943 st4=pa*pb
1944 1944 dataOut.p[i,j]=pa+pb-(dataOut.pan[j]+dataOut.pbn[j])
1945 1945 dataOut.sdp[i,j]=2*dataOut.rnint2[j]*((pa+pb)*(pa+pb))
1946 1946 ## ACF
1947 1947 rhorp=dataOut.kabxys_integrated[8][i,j,0]+dataOut.kabxys_integrated[11][i,j,0]
1948 1948 rhoip=dataOut.kabxys_integrated[10][i,j,0]-dataOut.kabxys_integrated[9][i,j,0]
1949 1949
1950 1950 if ((pa>dataOut.pan[j])&(pb>dataOut.pbn[j])):
1951 1951 ss4=numpy.abs((pa-dataOut.pan[j])*(pb-dataOut.pbn[j]))
1952 1952 panrm[i,j]=math.sqrt(ss4)
1953 1953 rnorm=1/panrm[i,j]
1954 1954 ## ACF
1955 1955 dataOut.rhor[i,j]=rhorp*rnorm
1956 1956 dataOut.rhoi[i,j]=rhoip*rnorm
1957 1957 ############# Compute standard error for ACF
1958 1958 stoss4=st4/ss4
1959 1959 snoss4=sn4[j]/ss4
1960 1960 rp2=((rhorp*rhorp)+(rhoip*rhoip))/st4
1961 1961 rn2=((rhorn*rhorn)+(rhoin*rhoin))/sn4[j]
1962 1962 rs2=(dataOut.rhor[i,j]*dataOut.rhor[i,j])+(dataOut.rhoi[i,j]*dataOut.rhoi[i,j])
1963 1963 st=1.0+rs2*(stoss4-(2*math.sqrt(stoss4*snoss4)))
1964 1964 stn=1.0+rs2*(snoss4-(2*math.sqrt(stoss4*snoss4)))
1965 1965 dataOut.sd[i,j]=((stoss4*((1.0+rp2)*st+(2.0*rp2*rs2*snoss4)-4.0*math.sqrt(rs2*rp2)))+(0.25*snoss4*((1.0+rn2)*stn+(2.0*rn2*rs2*stoss4)-4.0*math.sqrt(rs2*rn2))))*dataOut.rnint2[j]
1966 1966 dataOut.sd[i,j]=numpy.abs(dataOut.sd[i,j])
1967 1967 else: #default values for bad points
1968 1968 rnorm=1/math.sqrt(st4)
1969 1969 dataOut.sd[i,j]=1.e30
1970 1970 dataOut.ibad[i,j]=4
1971 1971 dataOut.rhor[i,j]=rhorp*rnorm
1972 1972 dataOut.rhoi[i,j]=rhoip*rnorm
1973 1973 if ((pb/dataOut.pbn[j]-1.0)>2.25*(pa/dataOut.pan[j]-1.0)): #To flag bad points from the pulse and EEJ for lags != 0 for Channel B
1974 1974 dataOut.igcej[i,j]=1
1975 1975
1976 1976 elif ((pa/dataOut.pan[j]-1.0)>2.25*(pb/dataOut.pbn[j]-1.0)):
1977 1977 dataOut.igcej[i,j]=1
1978 1978
1979 1979 return dataOut
1980 1980
1981 1981 class FaradayAngleAndDPPower(Operation):
1982 1982 '''
1983 1983 Written by R. Flores
1984 1984 '''
1985 1985 """Operation to calculate Faraday angle and Double Pulse power.
1986 1986
1987 1987 Parameters:
1988 1988 -----------
1989 1989 None
1990 1990
1991 1991 Example
1992 1992 --------
1993 1993
1994 1994 op = proc_unit.addOperation(name='FaradayAngleAndDPPower', optype='other')
1995 1995
1996 1996 """
1997 1997
1998 1998 def __init__(self, **kwargs):
1999 1999
2000 2000 Operation.__init__(self, **kwargs)
2001 2001 self.aux=1
2002 2002
2003 2003 def run(self,dataOut):
2004 2004
2005 2005 if self.aux==1:
2006 2006 dataOut.h2=numpy.zeros(dataOut.MAXNRANGENDT,'float32')
2007 2007 dataOut.range1=numpy.zeros(dataOut.MAXNRANGENDT,order='F',dtype='float32')
2008 2008 dataOut.sdn2=numpy.zeros(dataOut.NDP,'float32')
2009 2009 dataOut.ph2=numpy.zeros(dataOut.NDP,'float32')
2010 2010 dataOut.sdp2=numpy.zeros(dataOut.NDP,'float32')
2011 2011 dataOut.ibd=numpy.zeros(dataOut.NDP,'float32')
2012 2012 dataOut.phi=numpy.zeros(dataOut.NDP,'float32')
2013 2013
2014 2014 self.aux=0
2015 2015
2016 2016 for i in range(dataOut.MAXNRANGENDT):
2017 2017 dataOut.range1[i]=dataOut.H0 + i*dataOut.DH
2018 2018 dataOut.h2[i]=dataOut.range1[i]**2
2019 2019
2020 2020 for j in range(dataOut.NDP):
2021 2021 dataOut.ph2[j]=0.
2022 2022 dataOut.sdp2[j]=0.
2023 2023 ri=dataOut.rhoi[j][0]/dataOut.sd[j][0]
2024 2024 rr=dataOut.rhor[j][0]/dataOut.sd[j][0]
2025 2025 dataOut.sdn2[j]=1./dataOut.sd[j][0]
2026 2026
2027 2027 pt=0.# // total power
2028 2028 st=0.# // total signal
2029 2029 ibt=0# // bad lags
2030 2030 ns=0# // no. good lags
2031 2031 for l in range(dataOut.DPL):
2032 2032 #add in other lags if outside of e-jet contamination
2033 2033 if( (dataOut.igcej[j][l] == 0) and (dataOut.ibad[j][l] == 0) ):
2034 2034
2035 2035 dataOut.ph2[j]+=dataOut.p[j][l]/dataOut.sdp[j][l]
2036 2036 dataOut.sdp2[j]=dataOut.sdp2[j]+1./dataOut.sdp[j][l]
2037 2037 ns+=1
2038 2038
2039 2039
2040 2040 pt+=dataOut.p[j][l]/dataOut.sdp[j][l]
2041 2041 st+=1./dataOut.sdp[j][l]
2042 2042 ibt|=dataOut.ibad[j][l];
2043 2043 if(ns!= 0):
2044 2044 dataOut.ibd[j]=0
2045 2045 dataOut.ph2[j]=dataOut.ph2[j]/dataOut.sdp2[j]
2046 2046 dataOut.sdp2[j]=1./dataOut.sdp2[j]
2047 2047 else:
2048 2048 dataOut.ibd[j]=ibt
2049 2049 dataOut.ph2[j]=pt/st
2050 2050 dataOut.sdp2[j]=1./st
2051 2051
2052 2052 dataOut.ph2[j]=dataOut.ph2[j]*dataOut.h2[j]
2053 2053 dataOut.sdp2[j]=numpy.sqrt(dataOut.sdp2[j])*dataOut.h2[j]
2054 2054 rr=rr/dataOut.sdn2[j]
2055 2055 ri=ri/dataOut.sdn2[j]
2056 2056 #rm[j]=np.sqrt(rr*rr + ri*ri) it is not used in c program
2057 2057 dataOut.sdn2[j]=1./(dataOut.sdn2[j]*(rr*rr + ri*ri))
2058 2058 if( (ri == 0.) and (rr == 0.) ):
2059 2059 dataOut.phi[j]=0.
2060 2060 else:
2061 2061 dataOut.phi[j]=math.atan2( ri , rr )
2062 2062
2063 2063 dataOut.flagTeTiCorrection = False
2064 2064 return dataOut
2065 2065
2066 2066
2067 2067 class ElectronDensityFaraday(Operation):
2068 2068 '''
2069 2069 Written by R. Flores
2070 2070 '''
2071 2071 """Operation to calculate electron density from Faraday angle.
2072 2072
2073 2073 Parameters:
2074 2074 -----------
2075 2075 NSHTS : int
2076 2076 .*
2077 2077 RATE : float
2078 2078 .*
2079 2079
2080 2080 Example
2081 2081 --------
2082 2082
2083 2083 op = proc_unit.addOperation(name='ElectronDensityFaraday', optype='other')
2084 2084 op.addParameter(name='NSHTS', value='50', format='int')
2085 2085 op.addParameter(name='RATE', value='1.8978873e-6', format='float')
2086 2086
2087 2087 """
2088 2088
2089 2089 def __init__(self, **kwargs):
2090 2090
2091 2091 Operation.__init__(self, **kwargs)
2092 2092 self.aux=1
2093 2093
2094 2094 def run(self,dataOut,NSHTS=50,RATE=1.8978873e-6):
2095 2095
2096 2096 dataOut.NSHTS=NSHTS
2097 2097 dataOut.RATE=RATE
2098 2098
2099 2099 if self.aux==1:
2100 2100 dataOut.dphi=numpy.zeros(dataOut.NDP,'float32')
2101 2101 dataOut.sdn1=numpy.zeros(dataOut.NDP,'float32')
2102 2102 self.aux=0
2103 2103 theta=numpy.zeros(dataOut.NDP,dtype=numpy.complex_)
2104 2104 thetai=numpy.zeros(dataOut.NDP,dtype=numpy.complex_)
2105 2105 # use complex numbers for phase
2106 2106 '''
2107 2107 for i in range(dataOut.NSHTS):
2108 2108 theta[i]=math.cos(dataOut.phi[i])+math.sin(dataOut.phi[i])*1j
2109 2109 thetai[i]=-math.sin(dataOut.phi[i])+math.cos(dataOut.phi[i])*1j
2110 2110 ''' #Old Method
2111 2111
2112 2112 # differentiate and convert to number density
2113 2113 ndphi=dataOut.NSHTS-4
2114 2114 if hasattr(dataOut, 'flagSpreadF') and dataOut.flagSpreadF:
2115 2115 nanindex = numpy.argwhere(numpy.isnan(dataOut.phi))
2116 2116 i1 = nanindex[-1][0]
2117 2117 #Analizar cuando SpreadF es Pluma
2118 2118
2119 2119 dataOut.phi[i1+1:]=numpy.unwrap(dataOut.phi[i1+1:]) #Better results
2120 2120 else:
2121 2121 dataOut.phi[:]=numpy.unwrap(dataOut.phi[:]) #Better results
2122 2122 for i in range(2,dataOut.NSHTS-2):
2123 2123 fact=(-0.5/(dataOut.RATE*dataOut.DH))*dataOut.bki[i]
2124 2124 #print("fact: ", fact,dataOut.RATE,dataOut.DH,dataOut.bki[i])
2125 2125 #four-point derivative, no phase unwrapping necessary
2126 2126 #####dataOut.dphi[i]=((((theta[i+1]-theta[i-1])+(2.0*(theta[i+2]-theta[i-2])))/thetai[i])).real/10.0 #Original from C program
2127 2127
2128 2128 ##dataOut.dphi[i]=((((theta[i-2]-theta[i+2])+(8.0*(theta[i+1]-theta[i-1])))/thetai[i])).real/12.0
2129 2129 dataOut.dphi[i]=((dataOut.phi[i+1]-dataOut.phi[i-1])+(2.0*(dataOut.phi[i+2]-dataOut.phi[i-2])))/10.0 #Better results
2130 2130
2131 2131 #dataOut.dphi_uc[i] = abs(dataOut.phi[i]*dataOut.bki[i]*(-0.5)/dataOut.DH)
2132 2132 #dataOut.dphi[i]=abs(dataOut.dphi[i]*fact)
2133 2133 dataOut.dphi[i]=dataOut.dphi[i]*abs(fact)
2134 2134 dataOut.sdn1[i]=(4.*(dataOut.sdn2[i-2]+dataOut.sdn2[i+2])+dataOut.sdn2[i-1]+dataOut.sdn2[i+1])
2135 2135 dataOut.sdn1[i]=numpy.sqrt(dataOut.sdn1[i])*fact
2136 2136
2137 2137 return dataOut
2138 2138
2139 2139
2140 2140 class NormalizeDPPower(Operation):
2141 2141 '''
2142 2142 Written by R. Flores
2143 2143 '''
2144 2144 """Operation to normalize relative electron density from power with total electron density from Faraday angle.
2145 2145
2146 2146 Parameters:
2147 2147 -----------
2148 2148 None
2149 2149
2150 2150 Example
2151 2151 --------
2152 2152
2153 2153 op = proc_unit.addOperation(name='NormalizeDPPower', optype='other')
2154 2154
2155 2155 """
2156 2156
2157 2157 def __init__(self, **kwargs):
2158 2158
2159 2159 Operation.__init__(self, **kwargs)
2160 2160 self.aux=1
2161 2161
2162 2162 def normal(self,a,b,n,m):
2163 2163 chmin=1.0e30
2164 2164 chisq=numpy.zeros(150,'float32')
2165 2165 temp=numpy.zeros(150,'float32')
2166 2166
2167 2167 for i in range(2*m-1):
2168 2168 an=al=be=chisq[i]=0.0
2169 2169 for j in range(int(n/m)):
2170 2170 k=int(j+i*n/(2*m))
2171 2171 if(a[k]>0.0 and b[k]>0.0):
2172 2172 al+=a[k]*b[k]
2173 2173 be+=b[k]*b[k]
2174 2174
2175 2175 if(be>0.0):
2176 2176 temp[i]=al/be
2177 2177 else:
2178 2178 temp[i]=1.0
2179 2179
2180 2180 for j in range(int(n/m)):
2181 2181 k=int(j+i*n/(2*m))
2182 2182 if(a[k]>0.0 and b[k]>0.0):
2183 2183 chisq[i]+=(numpy.log10(b[k]*temp[i]/a[k]))**2
2184 2184 an=an+1
2185 2185
2186 2186 if(chisq[i]>0.0):
2187 2187 chisq[i]/=an
2188 2188
2189 2189 for i in range(int(2*m-1)):
2190 2190 if(chisq[i]<chmin and chisq[i]>1.0e-6):
2191 2191 chmin=chisq[i]
2192 2192 cf=temp[i]
2193 2193 return cf
2194 2194
2195 2195 def normalize(self,dataOut):
2196 2196
2197 2197 if self.aux==1:
2198 2198 dataOut.cf=numpy.zeros(1,'float32')
2199 2199 dataOut.cflast=numpy.zeros(1,'float32')
2200 2200 self.aux=0
2201 2201
2202 2202 night_first=300.0
2203 2203 night_first1= 310.0
2204 2204 night_end= 450.0
2205 2205 day_first=250.0
2206 2206 day_end=400.0
2207 2207 day_first_sunrise=190.0
2208 2208 day_end_sunrise=280.0
2209 2209
2210 2210 #print(dataOut.ut_Faraday)
2211 2211 if(dataOut.ut_Faraday>4.0 and dataOut.ut_Faraday<11.0): #early
2212 2212 #print("EARLY")
2213 2213 i2=(night_end-dataOut.range1[0])/dataOut.DH
2214 2214 i1=(night_first -dataOut.range1[0])/dataOut.DH
2215 2215 elif (dataOut.ut_Faraday>0.0 and dataOut.ut_Faraday<4.0): #night
2216 2216 #print("NIGHT")
2217 2217 i2=(night_end-dataOut.range1[0])/dataOut.DH
2218 2218 i1=(night_first1 -dataOut.range1[0])/dataOut.DH
2219 2219 elif (dataOut.ut_Faraday>=11.0 and dataOut.ut_Faraday<13.5): #sunrise
2220 2220 #print("SUNRISE")
2221 2221 i2=( day_end_sunrise-dataOut.range1[0])/dataOut.DH
2222 2222 i1=(day_first_sunrise - dataOut.range1[0])/dataOut.DH
2223 2223 else:
2224 2224 #print("ELSE")
2225 2225 i2=(day_end-dataOut.range1[0])/dataOut.DH
2226 2226 i1=(day_first -dataOut.range1[0])/dataOut.DH
2227 2227 #print(i1*dataOut.DH)
2228 2228 #print(i2*dataOut.DH)
2229 2229
2230 2230 i1=int(i1)
2231 2231 i2=int(i2)
2232 2232
2233 2233 try:
2234 2234 dataOut.cf=self.normal(dataOut.dphi[i1::], dataOut.ph2[i1::], i2-i1, 1)
2235 2235 except:
2236 2236 pass
2237 2237
2238 2238 #print(dataOut.ph2)
2239 2239 #input()
2240 2240 # in case of spread F, normalize much higher
2241 2241 if(dataOut.cf<dataOut.cflast[0]/10.0):
2242 2242 i1=(night_first1+100.-dataOut.range1[0])/dataOut.DH
2243 2243 i2=(night_end+100.0-dataOut.range1[0])/dataOut.DH
2244 2244 i1=int(i1)
2245 2245 i2=int(i2)
2246 2246 try:
2247 2247 dataOut.cf=self.normal(dataOut.dphi[int(i1)::], dataOut.ph2[int(i1)::], int(i2-i1), 1)
2248 2248 except:
2249 2249 pass
2250 2250
2251 2251 dataOut.cflast[0]=dataOut.cf
2252 2252
2253 2253 ## normalize double pulse power and error bars to Faraday
2254 2254 for i in range(dataOut.NSHTS):
2255 2255 dataOut.ph2[i]*=dataOut.cf
2256 2256 dataOut.sdp2[i]*=dataOut.cf
2257 2257 #print(dataOut.ph2)
2258 2258 #input()
2259 2259
2260 2260 for i in range(dataOut.NSHTS):
2261 2261 dataOut.ph2[i]=(max(1.0, dataOut.ph2[i]))
2262 2262 dataOut.dphi[i]=(max(1.0, dataOut.dphi[i]))
2263 2263
2264 2264
2265 2265 def run(self,dataOut):
2266 2266
2267 2267 self.normalize(dataOut)
2268 2268 #print(dataOut.ph2)
2269 2269 #print(dataOut.sdp2)
2270 2270 #input()
2271 2271
2272 2272
2273 2273 return dataOut
2274 2274
2275 2275 class NormalizeDPPowerRoberto(Operation):
2276 2276 '''
2277 2277 Written by R. Flores
2278 2278 '''
2279 2279 """Operation to normalize relative electron density from power with total electron density from Farday angle.
2280 2280
2281 2281 Parameters:
2282 2282 -----------
2283 2283 None
2284 2284
2285 2285 Example
2286 2286 --------
2287 2287
2288 2288 op = proc_unit.addOperation(name='NormalizeDPPower', optype='other')
2289 2289
2290 2290 """
2291 2291
2292 2292 def __init__(self, **kwargs):
2293 2293
2294 2294 Operation.__init__(self, **kwargs)
2295 2295 self.aux=1
2296 2296
2297 2297 def normal(self,a,b,n,m):
2298 2298 chmin=1.0e30
2299 2299 chisq=numpy.zeros(150,'float32')
2300 2300 temp=numpy.zeros(150,'float32')
2301 2301
2302 2302 for i in range(2*m-1):
2303 2303 an=al=be=chisq[i]=0.0
2304 2304 for j in range(int(n/m)):
2305 2305 k=int(j+i*n/(2*m))
2306 2306 if(a[k]>0.0 and b[k]>0.0):
2307 2307 al+=a[k]*b[k]
2308 2308 be+=b[k]*b[k]
2309 2309
2310 2310 if(be>0.0):
2311 2311 temp[i]=al/be
2312 2312 else:
2313 2313 temp[i]=1.0
2314 2314
2315 2315 for j in range(int(n/m)):
2316 2316 k=int(j+i*n/(2*m))
2317 2317 if(a[k]>0.0 and b[k]>0.0):
2318 2318 chisq[i]+=(numpy.log10(b[k]*temp[i]/a[k]))**2
2319 2319 an=an+1
2320 2320
2321 2321 if(chisq[i]>0.0):
2322 2322 chisq[i]/=an
2323 2323
2324 2324 for i in range(int(2*m-1)):
2325 2325 if(chisq[i]<chmin and chisq[i]>1.0e-6):
2326 2326 chmin=chisq[i]
2327 2327 cf=temp[i]
2328 2328 return cf
2329 2329
2330 2330 def normalize(self,dataOut):
2331 2331
2332 2332 if self.aux==1:
2333 2333 dataOut.cf=numpy.zeros(1,'float32')
2334 2334 dataOut.cflast=numpy.zeros(1,'float32')
2335 2335 self.aux=0
2336 2336
2337 2337 night_first=300.0
2338 2338 night_first1= 310.0
2339 2339 night_end= 450.0
2340 2340 day_first=250.0
2341 2341 day_end=400.0
2342 2342 day_first_sunrise=190.0
2343 2343 day_end_sunrise=350.0
2344 2344
2345 2345 print(dataOut.ut_Faraday)
2346 2346 '''
2347 2347 if(dataOut.ut_Faraday>4.0 and dataOut.ut_Faraday<11.0): #early
2348 2348 print("EARLY")
2349 2349 i2=(night_end-dataOut.range1[0])/dataOut.DH
2350 2350 i1=(night_first -dataOut.range1[0])/dataOut.DH
2351 2351 elif (dataOut.ut_Faraday>0.0 and dataOut.ut_Faraday<4.0): #night
2352 2352 print("NIGHT")
2353 2353 i2=(night_end-dataOut.range1[0])/dataOut.DH
2354 2354 i1=(night_first1 -dataOut.range1[0])/dataOut.DH
2355 2355 elif (dataOut.ut_Faraday>=11.0 and dataOut.ut_Faraday<13.5): #sunrise
2356 2356 print("SUNRISE")
2357 2357 i2=( day_end_sunrise-dataOut.range1[0])/dataOut.DH
2358 2358 i1=(day_first_sunrise - dataOut.range1[0])/dataOut.DH
2359 2359 else:
2360 2360 print("ELSE")
2361 2361 i2=(day_end-dataOut.range1[0])/dataOut.DH
2362 2362 i1=(day_first -dataOut.range1[0])/dataOut.DH
2363 2363 '''
2364 2364 i2=(420-dataOut.range1[0])/dataOut.DH
2365 2365 i1=(200 -dataOut.range1[0])/dataOut.DH
2366 2366 print(i1*dataOut.DH)
2367 2367 print(i2*dataOut.DH)
2368 2368
2369 2369 i1=int(i1)
2370 2370 i2=int(i2)
2371 2371
2372 2372 try:
2373 2373 dataOut.cf=self.normal(dataOut.dphi[i1::], dataOut.ph2[i1::], i2-i1, 1)
2374 2374 except:
2375 2375 pass
2376 2376
2377 2377 #print(dataOut.ph2)
2378 2378 #input()
2379 2379 # in case of spread F, normalize much higher
2380 2380 if(dataOut.cf<dataOut.cflast[0]/10.0):
2381 2381 i1=(night_first1+100.-dataOut.range1[0])/dataOut.DH
2382 2382 i2=(night_end+100.0-dataOut.range1[0])/dataOut.DH
2383 2383 i1=int(i1)
2384 2384 i2=int(i2)
2385 2385 try:
2386 2386 dataOut.cf=self.normal(dataOut.dphi[int(i1)::], dataOut.ph2[int(i1)::], int(i2-i1), 1)
2387 2387 except:
2388 2388 pass
2389 2389
2390 2390 dataOut.cflast[0]=dataOut.cf
2391 2391
2392 2392 ## normalize double pulse power and error bars to Faraday
2393 2393 for i in range(dataOut.NSHTS):
2394 2394 dataOut.ph2[i]*=dataOut.cf
2395 2395 dataOut.sdp2[i]*=dataOut.cf
2396 2396 #print(dataOut.ph2)
2397 2397 #input()
2398 2398
2399 2399 for i in range(dataOut.NSHTS):
2400 2400 dataOut.ph2[i]=(max(1.0, dataOut.ph2[i]))
2401 2401 dataOut.dphi[i]=(max(1.0, dataOut.dphi[i]))
2402 2402
2403 2403
2404 2404 def run(self,dataOut):
2405 2405
2406 2406 self.normalize(dataOut)
2407 2407 #print(dataOut.ph2)
2408 2408 #print(dataOut.sdp2)
2409 2409 #input()
2410 2410
2411 2411
2412 2412 return dataOut
2413 2413
2414 2414 class NormalizeDPPowerRoberto_V2(Operation):
2415 2415 '''
2416 2416 Written by R. Flores
2417 2417 '''
2418 2418 """Operation to normalize relative electron density from power with total electron density from Farday angle.
2419 2419
2420 2420 Parameters:
2421 2421 -----------
2422 2422 None
2423 2423
2424 2424 Example
2425 2425 --------
2426 2426
2427 2427 op = proc_unit.addOperation(name='NormalizeDPPower', optype='other')
2428 2428
2429 2429 """
2430 2430
2431 2431 def __init__(self, **kwargs):
2432 2432
2433 2433 Operation.__init__(self, **kwargs)
2434 2434 self.aux=1
2435 2435
2436 2436 def normal(self,a,b,n,m):
2437 2437 chmin=1.0e30
2438 2438 chisq=numpy.zeros(150,'float32')
2439 2439 temp=numpy.zeros(150,'float32')
2440 2440
2441 2441 for i in range(2*m-1):
2442 2442 an=al=be=chisq[i]=0.0
2443 2443 for j in range(int(n/m)):
2444 2444 k=int(j+i*n/(2*m))
2445 2445 if(a[k]>0.0 and b[k]>0.0):
2446 2446 al+=a[k]*b[k]
2447 2447 be+=b[k]*b[k]
2448 2448
2449 2449 if(be>0.0):
2450 2450 temp[i]=al/be
2451 2451 else:
2452 2452 temp[i]=1.0
2453 2453
2454 2454 for j in range(int(n/m)):
2455 2455 k=int(j+i*n/(2*m))
2456 2456 if(a[k]>0.0 and b[k]>0.0):
2457 2457 chisq[i]+=(numpy.log10(b[k]*temp[i]/a[k]))**2
2458 2458 an=an+1
2459 2459
2460 2460 if(chisq[i]>0.0):
2461 2461 chisq[i]/=an
2462 2462
2463 2463 for i in range(int(2*m-1)):
2464 2464 if(chisq[i]<chmin and chisq[i]>1.0e-6):
2465 2465 chmin=chisq[i]
2466 2466 cf=temp[i]
2467 2467 return cf
2468 2468
2469
2469
2470 2470 def normalize(self,dataOut):
2471 2471
2472 2472 if self.aux==1:
2473 2473 dataOut.cf=numpy.zeros(1,'float32')
2474 2474 dataOut.cflast=numpy.zeros(1,'float32')
2475 2475 self.aux=0
2476 2476
2477 2477 if (dataOut.ut_Faraday>=11.5 and dataOut.ut_Faraday<23):
2478 2478 i2=(500.-dataOut.range1[0])/dataOut.DH
2479 2479 i1=(200.-dataOut.range1[0])/dataOut.DH
2480 2480
2481 2481 else:
2482 2482 inda = numpy.where(dataOut.heightList >= 200) #200 km
2483 2483 minIndex = inda[0][0]
2484 2484 indb = numpy.where(dataOut.heightList < 700) # 700 km
2485 2485 maxIndex = indb[0][-1]
2486 2486
2487 2487 ph2max_idx = numpy.nanargmax(dataOut.ph2[minIndex:maxIndex])
2488 2488 ph2max_idx += minIndex
2489 2489
2490 2490 i2 = ph2max_idx + 6
2491 2491 i1 = ph2max_idx - 6
2492 2492
2493 2493 try:
2494 2494 dataOut.heightList[i2]
2495 2495 except:
2496 2496 i2 -= 1
2497 2497
2498 2498 i1=int(i1)
2499 2499 i2=int(i2)
2500 2500
2501 2501 if dataOut.flagTeTiCorrection:
2502 2502 for i in range(dataOut.NSHTS):
2503 2503 dataOut.ph2[i]/=dataOut.cf
2504 2504 dataOut.sdp2[i]/=dataOut.cf
2505 2505
2506 2506 if hasattr(dataOut, 'flagSpreadF') and dataOut.flagSpreadF:
2507 2507 i2=int((700-dataOut.range1[0])/dataOut.DH)
2508 2508 nanindex = numpy.argwhere(numpy.isnan(dataOut.ph2))
2509 2509 i1 = nanindex[-1][0] #VER CUANDO i1>i2
2510 2510 if i1 != numpy.shape(dataOut.heightList)[0]:
2511 2511 i1 += 1+2 #Se suma uno para no tomar el nan, se suma 2 para no tomar datos nan de "phi" debido al calculo de la derivada
2512 2512 if i1 >= i2:
2513 2513 i1 = i2-4
2514 2514
2515 2515 try:
2516 2516 dataOut.cf=self.normal(dataOut.dphi[i1::], dataOut.ph2[i1::], i2-i1, 1)
2517 2517
2518 2518 except:
2519 2519 print("except")
2520 2520 dataOut.cf = numpy.nan
2521 2521
2522 2522 night_first1= 300.0#350.0
2523 2523 night_end= 450.0
2524 2524 night_first1= 220.0#350.0
2525 2525 night_end= 400.0
2526 2526
2527 2527 if(dataOut.cf<dataOut.cflast[0]/10.0):
2528 2528 i1=(night_first1-dataOut.range1[0])/dataOut.DH
2529 2529 i2=(night_end-dataOut.range1[0])/dataOut.DH
2530 2530 i1=int(i1)
2531 2531 i2=int(i2)
2532 2532 try:
2533 2533 dataOut.cf=self.normal(dataOut.dphi[int(i1)::], dataOut.ph2[int(i1)::], int(i2-i1), 1)
2534 2534 except:
2535 2535 pass
2536 2536
2537 2537 dataOut.cflast[0]=dataOut.cf
2538 2538
2539 2539 ## normalize double pulse power and error bars to Faraday
2540 2540 for i in range(dataOut.NSHTS):
2541 2541 dataOut.ph2[i]*=dataOut.cf
2542 2542 dataOut.sdp2[i]*=dataOut.cf
2543 2543
2544 2544 for i in range(dataOut.NSHTS):
2545 2545 dataOut.ph2[i]=(max(1.0, dataOut.ph2[i]))
2546 2546 dataOut.dphi[i]=(max(1.0, dataOut.dphi[i]))
2547 2547
2548 2548 def run(self,dataOut):
2549 2549
2550 2550 self.normalize(dataOut)
2551 2551
2552 2552 return dataOut
2553 2553
2554 2554 class suppress_stdout_stderr(object):
2555 2555 '''
2556 2556 A context manager for doing a "deep suppression" of stdout and stderr in
2557 2557 Python, i.e. will suppress all print, even if the print originates in a
2558 2558 compiled C/Fortran sub-function.
2559 2559 This will not suppress raised exceptions, since exceptions are printed
2560 2560 to stderr just before a script exits, and after the context manager has
2561 2561 exited (at least, I think that is why it lets exceptions through).
2562 2562
2563 2563 '''
2564 2564 def __init__(self):
2565 2565 # Open a pair of null files
2566 2566 self.null_fds = [os.open(os.devnull,os.O_RDWR) for x in range(2)]
2567 2567 # Save the actual stdout (1) and stderr (2) file descriptors.
2568 2568 self.save_fds = [os.dup(1), os.dup(2)]
2569 2569
2570 2570 def __enter__(self):
2571 2571 # Assign the null pointers to stdout and stderr.
2572 2572 os.dup2(self.null_fds[0],1)
2573 2573 os.dup2(self.null_fds[1],2)
2574 2574
2575 2575 def __exit__(self, *_):
2576 2576 # Re-assign the real stdout/stderr back to (1) and (2)
2577 2577 os.dup2(self.save_fds[0],1)
2578 2578 os.dup2(self.save_fds[1],2)
2579 2579 # Close all file descriptors
2580 2580 for fd in self.null_fds + self.save_fds:
2581 2581 os.close(fd)
2582 2582
2583 2583
2584 2584 class DPTemperaturesEstimation(Operation):
2585 2585 '''
2586 2586 Written by R. Flores
2587 2587 '''
2588 2588 """Operation to estimate temperatures for Double Pulse data.
2589 2589
2590 2590 Parameters:
2591 2591 -----------
2592 2592 IBITS : int
2593 2593 .*
2594 2594
2595 2595 Example
2596 2596 --------
2597 2597
2598 2598 op = proc_unit.addOperation(name='DPTemperaturesEstimation', optype='other')
2599 2599 op.addParameter(name='IBITS', value='16', format='int')
2600 2600
2601 2601 """
2602 2602
2603 2603 def __init__(self, **kwargs):
2604 2604
2605 2605 Operation.__init__(self, **kwargs)
2606 2606
2607 2607 self.aux=1
2608 2608
2609 2609 def Estimation(self,dataOut):
2610 2610 #with suppress_stdout_stderr():
2611 2611
2612 2612 if self.aux==1:
2613 2613 dataOut.ifit=numpy.zeros(5,order='F',dtype='int32')
2614 2614 dataOut.m=numpy.zeros(1,order='F',dtype='int32')
2615 2615 dataOut.te2=numpy.zeros(dataOut.NSHTS,order='F',dtype='float32')
2616 2616 dataOut.ti2=numpy.zeros(dataOut.NSHTS,order='F',dtype='float32')
2617 2617 dataOut.ete2=numpy.zeros(dataOut.NSHTS,order='F',dtype='float32')
2618 2618 dataOut.eti2=numpy.zeros(dataOut.NSHTS,order='F',dtype='float32')
2619 2619
2620 2620 self.aux=0
2621 2621
2622 2622 dataOut.phy2=numpy.zeros(dataOut.NSHTS,order='F',dtype='float32')
2623 2623 dataOut.ephy2=numpy.zeros(dataOut.NSHTS,order='F',dtype='float32')
2624 2624 dataOut.info2=numpy.zeros(dataOut.NDP,order='F',dtype='float32')
2625 2625 dataOut.params=numpy.zeros(10,order='F',dtype='float32')
2626 2626 dataOut.cov=numpy.zeros(dataOut.IBITS*dataOut.IBITS,order='F',dtype='float32')
2627 2627 dataOut.covinv=numpy.zeros(dataOut.IBITS*dataOut.IBITS,order='F',dtype='float32')
2628 2628
2629 2629 #null_fd = os.open(os.devnull, os.O_RDWR)
2630 2630 #os.dup2(null_fd, 1)
2631 2631
2632 2632 for i in range(10,dataOut.NSHTS): #no point below 150 km
2633 2633
2634 2634 #some definitions
2635 2635 iflag=0 # inicializado a cero?
2636 2636 wl = 3.0
2637 2637 x=numpy.zeros(dataOut.DPL+dataOut.IBITS,order='F',dtype='float32')
2638 2638 y=numpy.zeros(dataOut.DPL+dataOut.IBITS,order='F',dtype='float32')
2639 2639 e=numpy.zeros(dataOut.DPL+dataOut.IBITS,order='F',dtype='float32')
2640 2640 eb=numpy.zeros(5,order='F',dtype='float32')
2641 2641 zero=numpy.zeros(1,order='F',dtype='float32')
2642 2642 depth=numpy.zeros(1,order='F',dtype='float32')
2643 2643 t1=numpy.zeros(1,order='F',dtype='float32')
2644 2644 t2=numpy.zeros(1,order='F',dtype='float32')
2645 2645
2646 2646 if i>10 and l1>=0:
2647 2647 if l1==0:
2648 2648 l1=1
2649 2649
2650 2650 dataOut.cov=numpy.reshape(dataOut.cov,l1*l1)
2651 2651 dataOut.cov=numpy.resize(dataOut.cov,dataOut.DPL*dataOut.DPL)
2652 2652 dataOut.covinv=numpy.reshape(dataOut.covinv,l1*l1)
2653 2653 dataOut.covinv=numpy.resize(dataOut.covinv,dataOut.DPL*dataOut.DPL)
2654 2654
2655 2655 for l in range(dataOut.DPL*dataOut.DPL):
2656 2656 dataOut.cov[l]=0.0
2657 2657 acfm= (dataOut.rhor[i][0])**2 + (dataOut.rhoi[i][0])**2
2658 2658 if acfm> 0.0:
2659 2659 cc=dataOut.rhor[i][0]/acfm
2660 2660 ss=dataOut.rhoi[i][0]/acfm
2661 2661 else:
2662 2662 cc=1.
2663 2663 ss=0.
2664 2664 # keep only uncontaminated data, don't pass zero lag to fitter
2665 2665 l1=0
2666 2666 for l in range(0+1,dataOut.DPL):
2667 2667 if dataOut.igcej[i][l]==0 and dataOut.ibad[i][l]==0:
2668 2668 y[l1]=dataOut.rhor[i][l]*cc + dataOut.rhoi[i][l]*ss
2669 2669 x[l1]=dataOut.alag[l]*1.0e-3
2670 2670 dataOut.sd[i][l]=dataOut.sd[i][l]/((acfm)**2)# important
2671 2671 e[l1]=dataOut.sd[i][l] #this is the variance, not the st. dev.
2672 2672 l1=l1+1
2673 2673
2674 2674 for l in range(l1*(l1+1)):
2675 2675 dataOut.cov[l]=0.0
2676 2676 for l in range(l1):
2677 2677 dataOut.cov[l*(1+l1)]=e[l]
2678 2678 angle=dataOut.thb[i]*0.01745
2679 2679 bm=dataOut.bfm[i]
2680 2680 dataOut.params[0]=1.0 #norm
2681 2681 dataOut.params[1]=1000.0 #te
2682 2682 dataOut.params[2]=800.0 #ti
2683 2683 dataOut.params[3]=0.00 #ph
2684 2684 dataOut.params[4]=0.00 #phe
2685 2685
2686 2686 if l1!=0:
2687 2687 x=numpy.resize(x,l1)
2688 2688 y=numpy.resize(y,l1)
2689 2689 else:
2690 2690 x=numpy.resize(x,1)
2691 2691 y=numpy.resize(y,1)
2692 2692
2693 2693 if True: #len(y)!=0:
2694 2694 with suppress_stdout_stderr():
2695 2695 fitacf_guess.guess(y,x,zero,depth,t1,t2,len(y))
2696 2696 t2=t1/t2
2697 2697
2698 2698 if (t1<5000.0 and t1> 600.0):
2699 2699 dataOut.params[1]=t1
2700 2700 dataOut.params[2]=min(t2,t1)
2701 2701 dataOut.ifit[1]=dataOut.ifit[2]=1
2702 2702 dataOut.ifit[0]=dataOut.ifit[3]=dataOut.ifit[4]=0
2703 2703
2704 2704 if dataOut.ut_Faraday<10.0 and dataOut.ut_Faraday>=0.5:
2705 2705 dataOut.ifit[2]=0
2706 2706
2707 2707 den=dataOut.ph2[i]
2708 2708
2709 2709 if l1!=0:
2710 2710 dataOut.covinv=dataOut.covinv[0:l1*l1].reshape((l1,l1))
2711 2711 dataOut.cov=dataOut.cov[0:l1*l1].reshape((l1,l1))
2712 2712 e=numpy.resize(e,l1)
2713 2713 else:
2714 2714 dataOut.covinv=numpy.resize(dataOut.covinv,1)
2715 2715 dataOut.cov=numpy.resize(dataOut.cov,1)
2716 2716 e=numpy.resize(e,1)
2717 2717
2718 2718 eb=numpy.resize(eb,10)
2719 2719 dataOut.ifit=numpy.resize(dataOut.ifit,10)
2720 2720 dataOut.covinv,e,dataOut.params,eb,dataOut.m=fitacf_fit_short.fit(wl,x,y,dataOut.cov,dataOut.covinv,e,dataOut.params,bm,angle,den,dataOut.range1[i],dataOut.year,dataOut.ifit,dataOut.m,l1) #
2721 2721 if dataOut.params[2]>dataOut.params[1]*1.05:
2722 2722 dataOut.ifit[2]=0
2723 2723 dataOut.params[1]=dataOut.params[2]=t1
2724 2724 dataOut.covinv,e,dataOut.params,eb,dataOut.m=fitacf_fit_short.fit(wl,x,y,dataOut.cov,dataOut.covinv,e,dataOut.params,bm,angle,den,dataOut.range1[i],dataOut.year,dataOut.ifit,dataOut.m,l1) #
2725 2725 if (dataOut.ifit[2]==0):
2726 2726 dataOut.params[2]=dataOut.params[1]
2727 2727 if (dataOut.ifit[3]==0 and iflag==0):
2728 2728 dataOut.params[3]=0.0
2729 2729 if (dataOut.ifit[4]==0):
2730 2730 dataOut.params[4]=0.0
2731 2731 dataOut.te2[i]=dataOut.params[1]
2732 2732 dataOut.ti2[i]=dataOut.params[2]
2733 2733 dataOut.ete2[i]=eb[1]
2734 2734 dataOut.eti2[i]=eb[2]
2735 2735
2736 2736 if dataOut.eti2[i]==0:
2737 2737 dataOut.eti2[i]=dataOut.ete2[i]
2738 2738
2739 2739 dataOut.phy2[i]=dataOut.params[3]
2740 2740 dataOut.ephy2[i]=eb[3]
2741 2741 if(iflag==1):
2742 2742 dataOut.ephy2[i]=0.0
2743 2743
2744 2744 if (dataOut.m<=3 and dataOut.m!= 0 and dataOut.te2[i]>400.0):
2745 2745 dataOut.info2[i]=1
2746 2746 else:
2747 2747 dataOut.info2[i]=0
2748 2748
2749 2749 def run(self,dataOut,IBITS=16):
2750 2750
2751 2751 dataOut.IBITS = IBITS
2752 2752 self.Estimation(dataOut)
2753 2753
2754 2754 return dataOut
2755 2755
2756 2756
2757 2757 class DenCorrection(NormalizeDPPowerRoberto_V2):
2758 2758 '''
2759 2759 Written by R. Flores
2760 2760 '''
2761 2761 def __init__(self, **kwargs):
2762 2762
2763 2763 Operation.__init__(self, **kwargs)
2764 2764 self.aux = 0
2765 2765 self.csv_flag = 1
2766 2766
2767 2767 def gaussian(self, x, a, b, c):
2768 2768 val = a * numpy.exp(-(x - b)**2 / (2*c**2))
2769 2769 return val
2770 2770
2771 2771 def TeTiEstimation(self,dataOut):
2772 2772
2773 2773 #dataOut.DPL = 2 #for MST
2774 2774 y=numpy.zeros(dataOut.DPL,order='F',dtype='float32')
2775 2775
2776 2776 for i in range(dataOut.NSHTS):
2777 2777 y[0]=y[1]=dataOut.range1[i]
2778 2778
2779 2779 y = y.astype(dtype='float64',order='F')
2780 2780 three=int(3)
2781 2781 wl = 3.0
2782 2782 tion=numpy.zeros(three,order='F',dtype='float32')
2783 2783 fion=numpy.zeros(three,order='F',dtype='float32')
2784 2784 nui=numpy.zeros(three,order='F',dtype='float32')
2785 2785 wion=numpy.zeros(three,order='F',dtype='int32')
2786 2786 bline=0.0
2787 2787 #bline=numpy.zeros(1,order='F',dtype='float32')
2788 2788 my_aux = numpy.ones(dataOut.NSHTS,order='F',dtype='float32')
2789 2789 acf_Temps = numpy.ones(dataOut.NSHTS,order='F',dtype='float32')*numpy.nan
2790 2790 acf_no_Temps = numpy.ones(dataOut.NSHTS,order='F',dtype='float32')*numpy.nan
2791 2791
2792 2792 from scipy import signal
2793 2793
2794 2794 def func(params):
2795 2795 return (ratio2-self.gaussian(dataOut.heightList[:dataOut.NSHTS],params[0],params[1],params[2]))
2796 2796
2797 2797 dataOut.info2[0] = 1
2798 2798 for i in range(dataOut.NSHTS):
2799 2799 if dataOut.info2[i]==1:
2800 2800 angle=dataOut.thb[i]*0.01745
2801 2801 nue=nui[0]=nui[1]=nui[2]=0.0#nui[3]=0.0
2802 2802 wion[0]=16 #O
2803 2803 wion[1]=1 #H
2804 2804 wion[2]=4 #He
2805 2805 tion[0]=tion[1]=tion[2]=dataOut.ti2[i]
2806 2806 #tion[0]=tion[1]=tion[2]=ti2_smooth[i]
2807 2807 fion[0]=1.0-dataOut.phy2[i] #1
2808 2808 fion[1]=dataOut.phy2[i] #0
2809 2809 fion[2]=0.0 #0
2810 2810 for j in range(dataOut.DPL):
2811 2811 tau=dataOut.alag[j]*1.0e-3
2812 2812 with suppress_stdout_stderr():#The smoothness in range of "y" depends on the smoothness of the input parameters
2813 2813 y[j]=fitacf_acf2.acf2(wl,tau,dataOut.te2[i],tion,fion,nue,nui,wion,angle,dataOut.ph2[i],dataOut.bfm[i],y[j],three)
2814 2814
2815 2815 if dataOut.ut_Faraday>11.0 and dataOut.range1[i]>150.0 and dataOut.range1[i]<300.0:
2816 tau=0.0
2816 tau=0.0
2817 2817 with suppress_stdout_stderr():
2818 2818 bline=fitacf_acf2.acf2(wl,tau,tion,tion,fion,nue,nui,wion,angle,dataOut.ph2[i],dataOut.bfm[i],bline,three)
2819 2819
2820 2820 cf=min(1.2,max(1.0,bline/y[0])) #FACTOR DE EFICIENCIA
2821 2821 my_aux[i] = cf
2822 2822 acf_Temps[i] = y[0]
2823 2823 acf_no_Temps[i] = bline
2824 2824 for j in range(1,dataOut.DPL):
2825 2825 y[j]=min(max((y[j]/y[0]),-1.0),1.0)*dataOut.DH+dataOut.range1[i]
2826 2826 y[0]=dataOut.range1[i]+dataOut.DH
2827 2827
2828 2828
2829 2829 ratio = my_aux-1
2830 2830 def lsq_func(params):
2831 2831 return (ratio-self.gaussian(dataOut.heightList[:dataOut.NSHTS],params[0],params[1],params[2]))
2832 2832
2833 2833 x0_value = numpy.array([max(ratio),250,20])
2834 2834
2835 2835 popt = least_squares(lsq_func,x0=x0_value,verbose=0)
2836 2836
2837 2837 A = popt.x[0]; B = popt.x[1]; C = popt.x[2]
2838 2838
2839 2839 aux = self.gaussian(dataOut.heightList[:dataOut.NSHTS], A, B, C) + 1 #ratio + 1
2840 2840
2841 2841 dataOut.ph2[:dataOut.NSHTS]*=aux
2842 2842 dataOut.sdp2[:dataOut.NSHTS]*=aux
2843
2843
2844 2844 def run(self,dataOut,savecf=0):
2845 2845 if gmtime(dataOut.utctime).tm_hour < 24. and gmtime(dataOut.utctime).tm_hour >= 11.:
2846 2846 if hasattr(dataOut, 'flagSpreadF') and dataOut.flagSpreadF:
2847 2847 pass
2848 2848 else:
2849 2849 self.TeTiEstimation(dataOut)
2850 2850 dataOut.flagTeTiCorrection = True
2851 2851 self.normalize(dataOut)
2852 2852
2853 2853 return dataOut
2854 2854
2855 2855
2856 2856
2857 2857 class DataSaveCleaner(Operation):
2858 2858 '''
2859 2859 Written by R. Flores
2860 2860 '''
2861 2861 def __init__(self, **kwargs):
2862 2862
2863 2863 Operation.__init__(self, **kwargs)
2864 2864 self.csv_flag = 1
2865 2865
2866 2866 def run(self,dataOut,savecfclean=0):
2867 2867 dataOut.DensityFinal=numpy.zeros((1,dataOut.NDP))
2868 2868 dataOut.dphiFinal=numpy.zeros((1,dataOut.NDP))
2869 2869 dataOut.EDensityFinal=numpy.zeros((1,dataOut.NDP))
2870 2870 dataOut.ElecTempFinal=numpy.zeros((1,dataOut.NDP))
2871 2871 dataOut.EElecTempFinal=numpy.zeros((1,dataOut.NDP))
2872 2872 dataOut.IonTempFinal=numpy.zeros((1,dataOut.NDP))
2873 2873 dataOut.EIonTempFinal=numpy.zeros((1,dataOut.NDP))
2874 2874 dataOut.PhyFinal=numpy.zeros((1,dataOut.NDP))
2875 2875 dataOut.EPhyFinal=numpy.zeros((1,dataOut.NDP))
2876 2876
2877 2877 dataOut.DensityFinal[0]=numpy.copy(dataOut.ph2)
2878 2878 dataOut.dphiFinal[0]=numpy.copy(dataOut.dphi)
2879 2879 dataOut.EDensityFinal[0]=numpy.copy(dataOut.sdp2)
2880 2880 dataOut.ElecTempFinal[0,:dataOut.NSHTS]=numpy.copy(dataOut.te2)
2881 2881 dataOut.EElecTempFinal[0,:dataOut.NSHTS]=numpy.copy(dataOut.ete2)
2882 2882 dataOut.IonTempFinal[0,:dataOut.NSHTS]=numpy.copy(dataOut.ti2)
2883 2883 dataOut.EIonTempFinal[0,:dataOut.NSHTS]=numpy.copy(dataOut.eti2)
2884 2884 dataOut.PhyFinal[0,:dataOut.NSHTS]=numpy.copy(dataOut.phy2)
2885 2885 dataOut.EPhyFinal[0,:dataOut.NSHTS]=numpy.copy(dataOut.ephy2)
2886 2886
2887 2887 missing=numpy.nan
2888 2888 temp_min=100.0
2889 2889 temp_max=3000.0#6000.0e
2890 2890 den_err_percent = 100*dataOut.EDensityFinal[0]/dataOut.DensityFinal[0]
2891 2891 max_den_err_per = 35#30 #Densidades con error mayor al 35% se setean en NaN
2892 2892 for i in range(dataOut.NSHTS):
2893 2893
2894 2894 if den_err_percent[i] >= max_den_err_per:
2895 2895 dataOut.DensityFinal[0,i]=dataOut.EDensityFinal[0,i]=missing
2896 2896 if i > 40: #Alturas mayores que 600
2897 2897 dataOut.DensityFinal[0,i:]=dataOut.EDensityFinal[0,i:]=missing
2898 2898
2899 2899 if dataOut.info2[i]!=1:
2900 2900 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2901 2901
2902 2902 if dataOut.ElecTempFinal[0,i]<=temp_min or dataOut.ElecTempFinal[0,i]>temp_max or dataOut.EElecTempFinal[0,i]>temp_max:
2903 2903
2904 2904 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=missing
2905 2905
2906 2906 if dataOut.IonTempFinal[0,i]<=temp_min or dataOut.IonTempFinal[0,i]>temp_max or dataOut.EIonTempFinal[0,i]>temp_max:
2907 2907 dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2908 2908
2909 2909 if dataOut.lags_to_plot[i,:][~numpy.isnan(dataOut.lags_to_plot[i,:])].shape[0]<6:
2910 2910 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2911 2911
2912 2912 if dataOut.ut_Faraday>4 and dataOut.ut_Faraday<11:
2913 2913 if numpy.nanmax(dataOut.acfs_error_to_plot[i,:])>=10:
2914 2914 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2915 2915
2916 2916 if dataOut.EPhyFinal[0,i]<0.0 or dataOut.EPhyFinal[0,i]>1.0:
2917 2917 dataOut.PhyFinal[0,i]=dataOut.EPhyFinal[0,i]=missing
2918 2918
2919 2919 if dataOut.EDensityFinal[0,i]>0.0 and dataOut.DensityFinal[0,i]>0.0 and dataOut.DensityFinal[0,i]<9.9e6:
2920 2920 dataOut.EDensityFinal[0,i]=max(dataOut.EDensityFinal[0,i],1000.0)
2921 2921 else:
2922 2922 dataOut.DensityFinal[0,i]=dataOut.EDensityFinal[0,i]=missing
2923 2923
2924 2924 if dataOut.PhyFinal[0,i]==0 or dataOut.PhyFinal[0,i]>0.4:
2925 2925 dataOut.PhyFinal[0,i]=dataOut.EPhyFinal[0,i]=missing
2926 2926 if dataOut.ElecTempFinal[0,i]==dataOut.IonTempFinal[0,i]:
2927 2927 dataOut.EElecTempFinal[0,i]=dataOut.EIonTempFinal[0,i]
2928 2928 if numpy.isnan(dataOut.ElecTempFinal[0,i]):
2929 2929 dataOut.EElecTempFinal[0,i]=missing
2930 2930 if numpy.isnan(dataOut.IonTempFinal[0,i]):
2931 2931 dataOut.EIonTempFinal[0,i]=missing
2932 2932 if numpy.isnan(dataOut.ElecTempFinal[0,i]) or numpy.isnan(dataOut.EElecTempFinal[0,i]):
2933 2933 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2934 2934
2935 2935 for i in range(12,dataOut.NSHTS-1):
2936 2936
2937 2937 if numpy.isnan(dataOut.ElecTempFinal[0,i-1]) and numpy.isnan(dataOut.ElecTempFinal[0,i+1]):
2938 2938 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=missing
2939 2939
2940 2940 if numpy.isnan(dataOut.IonTempFinal[0,i-1]) and numpy.isnan(dataOut.IonTempFinal[0,i+1]):
2941 2941 dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2942 2942
2943 2943 if dataOut.ut_Faraday>4 and dataOut.ut_Faraday<11:
2944 2944
2945 2945 if numpy.isnan(dataOut.ElecTempFinal[0,i-1]) and numpy.isnan(dataOut.ElecTempFinal[0,i-2]) and numpy.isnan(dataOut.ElecTempFinal[0,i+2]) and numpy.isnan(dataOut.ElecTempFinal[0,i+3]): #and numpy.isnan(dataOut.ElecTempFinal[0,i-5]):
2946 2946
2947 2947 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=missing
2948 2948 if numpy.isnan(dataOut.IonTempFinal[0,i-1]) and numpy.isnan(dataOut.IonTempFinal[0,i-2]) and numpy.isnan(dataOut.IonTempFinal[0,i+2]) and numpy.isnan(dataOut.IonTempFinal[0,i+3]): #and numpy.isnan(dataOut.IonTempFinal[0,i-5]):
2949 2949
2950 2950 dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2951 2951
2952 2952 if i>25:
2953 2953 if numpy.isnan(dataOut.ElecTempFinal[0,i-1]) and numpy.isnan(dataOut.ElecTempFinal[0,i-2]) and numpy.isnan(dataOut.ElecTempFinal[0,i-3]) and numpy.isnan(dataOut.ElecTempFinal[0,i-4]): #and numpy.isnan(dataOut.ElecTempFinal[0,i-5]):
2954 2954 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=missing
2955 2955 if numpy.isnan(dataOut.IonTempFinal[0,i-1]) and numpy.isnan(dataOut.IonTempFinal[0,i-2]) and numpy.isnan(dataOut.IonTempFinal[0,i-3]) and numpy.isnan(dataOut.IonTempFinal[0,i-4]): #and numpy.isnan(dataOut.IonTempFinal[0,i-5]):
2956 2956
2957 2957 dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2958 2958
2959 2959 if numpy.isnan(dataOut.ElecTempFinal[0,i]) or numpy.isnan(dataOut.EElecTempFinal[0,i]):
2960 2960
2961 2961 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2962 2962
2963 2963 for i in range(12,dataOut.NSHTS-1):
2964 2964
2965 2965 if numpy.isnan(dataOut.ElecTempFinal[0,i-1]) and numpy.isnan(dataOut.ElecTempFinal[0,i+1]):
2966 2966 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=missing
2967 2967
2968 2968 if numpy.isnan(dataOut.IonTempFinal[0,i-1]) and numpy.isnan(dataOut.IonTempFinal[0,i+1]):
2969 2969 dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2970 2970
2971 2971 if numpy.isnan(dataOut.DensityFinal[0,i-1]) and numpy.isnan(dataOut.DensityFinal[0,i+1]): ##NEW
2972 2972 dataOut.DensityFinal[0,i]=dataOut.EDensityFinal[0,i]=missing ##NEW
2973 2973
2974 2974 if numpy.isnan(dataOut.ElecTempFinal[0,i]) or numpy.isnan(dataOut.EElecTempFinal[0,i]):
2975 2975
2976 2976 dataOut.ElecTempFinal[0,i]=dataOut.EElecTempFinal[0,i]=dataOut.IonTempFinal[0,i]=dataOut.EIonTempFinal[0,i]=missing
2977 2977
2978 2978 if numpy.count_nonzero(~numpy.isnan(dataOut.ElecTempFinal[0,12:50]))<5:
2979 2979 dataOut.ElecTempFinal[0,:]=dataOut.EElecTempFinal[0,:]=missing
2980 2980 if numpy.count_nonzero(~numpy.isnan(dataOut.IonTempFinal[0,12:50]))<5:
2981 2981 dataOut.IonTempFinal[0,:]=dataOut.EIonTempFinal[0,:]=missing
2982 2982
2983 2983
2984 2984 if numpy.count_nonzero(~numpy.isnan(dataOut.DensityFinal[0,12:50]))<=5:
2985 2985 dataOut.DensityFinal[0,:]=dataOut.EDensityFinal[0,:]=missing
2986 2986
2987 2987 dataOut.DensityFinal[0,dataOut.NSHTS:]=missing
2988 2988 dataOut.EDensityFinal[0,dataOut.NSHTS:]=missing
2989 2989 dataOut.ElecTempFinal[0,dataOut.NSHTS:]=missing
2990 2990 dataOut.EElecTempFinal[0,dataOut.NSHTS:]=missing
2991 2991 dataOut.IonTempFinal[0,dataOut.NSHTS:]=missing
2992 2992 dataOut.EIonTempFinal[0,dataOut.NSHTS:]=missing
2993 2993 dataOut.PhyFinal[0,dataOut.NSHTS:]=missing
2994 2994 dataOut.EPhyFinal[0,dataOut.NSHTS:]=missing
2995 2995
2996 2996 if gmtime(dataOut.utctime).tm_hour >= 13. and gmtime(dataOut.utctime).tm_hour < 21.: #07-16 LT
2997 2997 dataOut.DensityFinal[0,:13]=missing
2998 2998 dataOut.EDensityFinal[0,:13]=missing
2999 2999 dataOut.ElecTempFinal[0,:13]=missing
3000 3000 dataOut.EElecTempFinal[0,:13]=missing
3001 3001 dataOut.IonTempFinal[0,:13]=missing
3002 3002 dataOut.EIonTempFinal[0,:13]=missing
3003 3003 dataOut.PhyFinal[0,:13]=missing
3004 3004 dataOut.EPhyFinal[0,:13]=missing
3005 3005
3006 3006 else:
3007 3007 if gmtime(dataOut.utctime).tm_hour == 9 and gmtime(dataOut.utctime).tm_min == 20:
3008 3008 pass
3009 3009 else:
3010 3010 dataOut.DensityFinal[0,:dataOut.min_id_eej+1]=missing
3011 3011 dataOut.EDensityFinal[0,:dataOut.min_id_eej+1]=missing
3012 3012 dataOut.ElecTempFinal[0,:dataOut.min_id_eej+1]=missing
3013 3013 dataOut.EElecTempFinal[0,:dataOut.min_id_eej+1]=missing
3014 3014 dataOut.IonTempFinal[0,:dataOut.min_id_eej+1]=missing
3015 3015 dataOut.EIonTempFinal[0,:dataOut.min_id_eej+1]=missing
3016 3016 dataOut.PhyFinal[0,:dataOut.min_id_eej+1]=missing
3017 3017 dataOut.EPhyFinal[0,:dataOut.min_id_eej+1]=missing
3018 3018
3019 3019 dataOut.flagNoData = numpy.all(numpy.isnan(dataOut.DensityFinal)) #Si todos los valores son NaN no se prosigue
3020 3020
3021 3021 if not dataOut.flagNoData:
3022 3022 if savecfclean:
3023 3023 try:
3024 3024 import pandas as pd
3025 3025 if self.csv_flag:
3026 3026 if not os.path.exists("./cfclean"):
3027 3027 os.makedirs("./cfclean")
3028 3028 self.doy_csv = datetime.datetime.fromtimestamp(dataOut.utctime).strftime('%j')
3029 3029 self.year_csv = datetime.datetime.fromtimestamp(dataOut.utctime).strftime('%Y')
3030 3030 file = open("./cfclean/cfclean{0}{1}.csv".format(self.year_csv,self.doy_csv), "x")
3031 3031 f = csv.writer(file)
3032 3032 f.writerow(numpy.array(["timestamp",'cf']))
3033 3033 self.csv_flag = 0
3034 3034 print("Creating cf clean File")
3035 3035 print("Writing cf clean File")
3036 3036 except:
3037 3037 file = open("./cfclean/cfclean{0}{1}.csv".format(self.year_csv,self.doy_csv), "a")
3038 3038 f = csv.writer(file)
3039 3039 print("Writing cf clean File")
3040 3040 cf = numpy.array([dataOut.utctime,dataOut.cf])
3041 3041 f.writerow(cf)
3042 3042 file.close()
3043 3043
3044 3044 dataOut.flagNoData = False #Descomentar solo para ploteo #Comentar para MADWriter
3045 3045
3046 3046 dataOut.DensityFinal *= 1.e6 #Convert units to m^⁻3
3047 3047 dataOut.EDensityFinal *= 1.e6 #Convert units to m^⁻3
3048 3048
3049 3049 return dataOut
3050 3050
3051 3051
3052 3052 class DataSaveCleanerHP(Operation):
3053 3053 '''
3054 3054 Written by R. Flores
3055 3055 '''
3056 3056 def __init__(self, **kwargs):
3057 3057
3058 3058 Operation.__init__(self, **kwargs)
3059 3059
3060 3060 def run(self,dataOut):
3061 3061
3062 3062 dataOut.Density_DP=numpy.zeros(dataOut.cut)
3063 3063 dataOut.EDensity_DP=numpy.zeros(dataOut.cut)
3064 3064 dataOut.ElecTemp_DP=numpy.zeros(dataOut.cut)
3065 3065 dataOut.EElecTemp_DP=numpy.zeros(dataOut.cut)
3066 3066 dataOut.IonTemp_DP=numpy.zeros(dataOut.cut)
3067 3067 dataOut.EIonTemp_DP=numpy.zeros(dataOut.cut)
3068 3068 dataOut.Phy_DP=numpy.zeros(dataOut.cut)
3069 3069 dataOut.EPhy_DP=numpy.zeros(dataOut.cut)
3070 3070 dataOut.Phe_DP=numpy.empty(dataOut.cut)
3071 3071 dataOut.EPhe_DP=numpy.empty(dataOut.cut)
3072 3072
3073 3073 dataOut.Density_DP[:]=numpy.copy(dataOut.ph2[:dataOut.cut])
3074 3074 dataOut.EDensity_DP[:]=numpy.copy(dataOut.sdp2[:dataOut.cut])
3075 3075 dataOut.ElecTemp_DP[:]=numpy.copy(dataOut.te2[:dataOut.cut])
3076 3076 dataOut.EElecTemp_DP[:]=numpy.copy(dataOut.ete2[:dataOut.cut])
3077 3077 dataOut.IonTemp_DP[:]=numpy.copy(dataOut.ti2[:dataOut.cut])
3078 3078 dataOut.EIonTemp_DP[:]=numpy.copy(dataOut.eti2[:dataOut.cut])
3079 3079 dataOut.Phy_DP[:]=numpy.copy(dataOut.phy2[:dataOut.cut])
3080 3080 dataOut.EPhy_DP[:]=numpy.copy(dataOut.ephy2[:dataOut.cut])
3081 3081 dataOut.Phe_DP[:]=numpy.nan
3082 3082 dataOut.EPhe_DP[:]=numpy.nan
3083 3083
3084 3084 missing=numpy.nan
3085 3085 temp_min=100.0
3086 3086 temp_max_dp=3000.0
3087 3087
3088 3088 for i in range(dataOut.cut):
3089 3089 if dataOut.info2[i]!=1:
3090 3090 dataOut.ElecTemp_DP[i]=dataOut.EElecTemp_DP[i]=dataOut.IonTemp_DP[i]=dataOut.EIonTemp_DP[i]=missing
3091 3091
3092 3092 if dataOut.ElecTemp_DP[i]<=temp_min or dataOut.ElecTemp_DP[i]>temp_max_dp or dataOut.EElecTemp_DP[i]>temp_max_dp:
3093 3093
3094 3094 dataOut.ElecTemp_DP[i]=dataOut.EElecTemp_DP[i]=missing
3095 3095
3096 3096 if dataOut.IonTemp_DP[i]<=temp_min or dataOut.IonTemp_DP[i]>temp_max_dp or dataOut.EIonTemp_DP[i]>temp_max_dp:
3097 3097 dataOut.IonTemp_DP[i]=dataOut.EIonTemp_DP[i]=missing
3098 3098
3099 3099 ####################################################################################### CHECK THIS
3100 3100 if dataOut.lags_to_plot[i,:][~numpy.isnan(dataOut.lags_to_plot[i,:])].shape[0]<6:
3101 3101 dataOut.ElecTemp_DP[i]=dataOut.EElecTemp_DP[i]=dataOut.IonTemp_DP[i]=dataOut.EIonTemp_DP[i]=missing
3102 3102
3103 3103 if dataOut.ut_Faraday>4 and dataOut.ut_Faraday<11:
3104 3104 if numpy.nanmax(dataOut.acfs_error_to_plot[i,:])>=10:
3105 3105 dataOut.ElecTemp_DP[i]=dataOut.EElecTemp_DP[i]=dataOut.IonTemp_DP[i]=dataOut.EIonTemp_DP[i]=missing
3106 3106 #######################################################################################
3107 3107
3108 3108 if dataOut.EPhy_DP[i]<0.0 or dataOut.EPhy_DP[i]>1.0:
3109 3109 dataOut.Phy_DP[i]=dataOut.EPhy_DP[i]=missing
3110 3110 if dataOut.EDensity_DP[i]>0.0 and dataOut.Density_DP[i]>0.0 and dataOut.Density_DP[i]<9.9e6:
3111 3111 dataOut.EDensity_DP[i]=max(dataOut.EDensity_DP[i],1000.0)
3112 3112 else:
3113 3113 dataOut.Density_DP[i]=dataOut.EDensity_DP[i]=missing
3114 3114 if dataOut.Phy_DP[i]==0 or dataOut.Phy_DP[i]>0.4:
3115 3115 dataOut.Phy_DP[i]=dataOut.EPhy_DP[i]=missing
3116 3116 if dataOut.ElecTemp_DP[i]==dataOut.IonTemp_DP[i]:
3117 3117 dataOut.EElecTemp_DP[i]=dataOut.EIonTemp_DP[i]
3118 3118 if numpy.isnan(dataOut.ElecTemp_DP[i]):
3119 3119 dataOut.EElecTemp_DP[i]=missing
3120 3120 if numpy.isnan(dataOut.IonTemp_DP[i]):
3121 3121 dataOut.EIonTemp_DP[i]=missing
3122 3122 if numpy.isnan(dataOut.ElecTemp_DP[i]) or numpy.isnan(dataOut.EElecTemp_DP[i]):
3123 3123 dataOut.ElecTemp_DP[i]=dataOut.EElecTemp_DP[i]=dataOut.IonTemp_DP[i]=dataOut.EIonTemp_DP[i]=missing
3124 3124
3125 3125
3126 3126
3127 3127 dataOut.Density_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3128 3128 dataOut.EDensity_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3129 3129 dataOut.ElecTemp_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3130 3130 dataOut.EElecTemp_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3131 3131 dataOut.IonTemp_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3132 3132 dataOut.EIonTemp_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3133 3133 dataOut.Phy_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3134 3134 dataOut.EPhy_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3135 3135 dataOut.Phe_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3136 3136 dataOut.EPhe_LP=numpy.zeros(dataOut.NACF-dataOut.cut)
3137 3137
3138 3138 dataOut.Density_LP[:]=numpy.copy(dataOut.ne[dataOut.cut:dataOut.NACF])
3139 3139 dataOut.EDensity_LP[:]=numpy.copy(dataOut.ene[dataOut.cut:dataOut.NACF])
3140 3140 dataOut.ElecTemp_LP[:]=numpy.copy(dataOut.te[dataOut.cut:dataOut.NACF])
3141 3141 dataOut.EElecTemp_LP[:]=numpy.copy(dataOut.ete[dataOut.cut:dataOut.NACF])
3142 3142 dataOut.IonTemp_LP[:]=numpy.copy(dataOut.ti[dataOut.cut:dataOut.NACF])
3143 3143 dataOut.EIonTemp_LP[:]=numpy.copy(dataOut.eti[dataOut.cut:dataOut.NACF])
3144 3144 dataOut.Phy_LP[:]=numpy.copy(dataOut.ph[dataOut.cut:dataOut.NACF])
3145 3145 dataOut.EPhy_LP[:]=numpy.copy(dataOut.eph[dataOut.cut:dataOut.NACF])
3146 3146 dataOut.Phe_LP[:]=numpy.copy(dataOut.phe[dataOut.cut:dataOut.NACF])
3147 3147 dataOut.EPhe_LP[:]=numpy.copy(dataOut.ephe[dataOut.cut:dataOut.NACF])
3148 3148
3149 3149 temp_max_lp=6000.0
3150 3150
3151 3151 for i in range(dataOut.NACF-dataOut.cut):
3152 3152
3153 3153 if dataOut.ElecTemp_LP[i]<=temp_min or dataOut.ElecTemp_LP[i]>temp_max_lp or dataOut.EElecTemp_LP[i]>temp_max_lp:
3154 3154
3155 3155 dataOut.ElecTemp_LP[i]=dataOut.EElecTemp_LP[i]=missing
3156 3156
3157 3157 if dataOut.IonTemp_LP[i]<=temp_min or dataOut.IonTemp_LP[i]>temp_max_lp or dataOut.EIonTemp_LP[i]>temp_max_lp:
3158 3158 dataOut.IonTemp_LP[i]=dataOut.EIonTemp_LP[i]=missing
3159 3159 if dataOut.EPhy_LP[i]<0.0 or dataOut.EPhy_LP[i]>1.0:
3160 3160 dataOut.Phy_LP[i]=dataOut.EPhy_LP[i]=missing
3161 3161
3162 3162 if dataOut.EPhe_LP[i]<0.0 or dataOut.EPhe_LP[i]>1.0:
3163 3163 dataOut.Phe_LP[i]=dataOut.EPhe_LP[i]=missing
3164 3164 if dataOut.EDensity_LP[i]>0.0 and dataOut.Density_LP[i]>0.0 and dataOut.Density_LP[i]<9.9e6 and dataOut.EDensity_LP[i]*dataOut.Density_LP[i]<9.9e6:
3165 3165 dataOut.EDensity_LP[i]=max(dataOut.EDensity_LP[i],1000.0/dataOut.Density_LP[i])
3166 3166 else:
3167 3167 dataOut.Density_LP[i]=missing
3168 3168 dataOut.EDensity_LP[i]=1.0
3169 3169
3170 3170 if numpy.isnan(dataOut.Phy_LP[i]):
3171 3171 dataOut.EPhy_LP[i]=missing
3172 3172
3173 3173 if numpy.isnan(dataOut.Phe_LP[i]):
3174 3174 dataOut.EPhe_LP[i]=missing
3175 3175
3176 3176
3177 3177 if dataOut.ElecTemp_LP[i]==dataOut.IonTemp_LP[i]:
3178 3178 dataOut.EElecTemp_LP[i]=dataOut.EIonTemp_LP[i]
3179 3179 if numpy.isnan(dataOut.ElecTemp_LP[i]):
3180 3180 dataOut.EElecTemp_LP[i]=missing
3181 3181 if numpy.isnan(dataOut.IonTemp_LP[i]):
3182 3182 dataOut.EIonTemp_LP[i]=missing
3183 3183 if numpy.isnan(dataOut.ElecTemp_LP[i]) or numpy.isnan(dataOut.EElecTemp_LP[i]):
3184 3184 dataOut.ElecTemp_LP[i]=dataOut.EElecTemp_LP[i]=dataOut.IonTemp_LP[i]=dataOut.EIonTemp_LP[i]=missing
3185 3185
3186 3186
3187 3187 dataOut.DensityFinal=numpy.reshape(numpy.concatenate((dataOut.Density_DP,dataOut.Density_LP)),(1,-1))
3188 3188 dataOut.EDensityFinal=numpy.reshape(numpy.concatenate((dataOut.EDensity_DP,dataOut.EDensity_LP)),(1,-1))
3189 3189 dataOut.ElecTempFinal=numpy.reshape(numpy.concatenate((dataOut.ElecTemp_DP,dataOut.ElecTemp_LP)),(1,-1))
3190 3190 dataOut.EElecTempFinal=numpy.reshape(numpy.concatenate((dataOut.EElecTemp_DP,dataOut.EElecTemp_LP)),(1,-1))
3191 3191 dataOut.IonTempFinal=numpy.reshape(numpy.concatenate((dataOut.IonTemp_DP,dataOut.IonTemp_LP)),(1,-1))
3192 3192 dataOut.EIonTempFinal=numpy.reshape(numpy.concatenate((dataOut.EIonTemp_DP,dataOut.EIonTemp_LP)),(1,-1))
3193 3193 dataOut.PhyFinal=numpy.reshape(numpy.concatenate((dataOut.Phy_DP,dataOut.Phy_LP)),(1,-1))
3194 3194 dataOut.EPhyFinal=numpy.reshape(numpy.concatenate((dataOut.EPhy_DP,dataOut.EPhy_LP)),(1,-1))
3195 3195 dataOut.PheFinal=numpy.reshape(numpy.concatenate((dataOut.Phe_DP,dataOut.Phe_LP)),(1,-1))
3196 3196 dataOut.EPheFinal=numpy.reshape(numpy.concatenate((dataOut.EPhe_DP,dataOut.EPhe_LP)),(1,-1))
3197 3197
3198 3198 nan_array_2=numpy.empty(dataOut.NACF-dataOut.NDP)
3199 3199 nan_array_2[:]=numpy.nan
3200 3200
3201 3201 dataOut.acfs_DP=numpy.zeros((dataOut.NACF,dataOut.DPL),'float32')
3202 3202 dataOut.acfs_error_DP=numpy.zeros((dataOut.NACF,dataOut.DPL),'float32')
3203 3203 acfs_dp_aux=dataOut.acfs_to_save.transpose()
3204 3204 acfs_error_dp_aux=dataOut.acfs_error_to_save.transpose()
3205 3205 for i in range(dataOut.DPL):
3206 3206 dataOut.acfs_DP[:,i]=numpy.concatenate((acfs_dp_aux[:,i],nan_array_2))
3207 3207 dataOut.acfs_error_DP[:,i]=numpy.concatenate((acfs_error_dp_aux[:,i],nan_array_2))
3208 3208 dataOut.acfs_DP=dataOut.acfs_DP.transpose()
3209 3209 dataOut.acfs_error_DP=dataOut.acfs_error_DP.transpose()
3210 3210
3211 3211 dataOut.acfs_LP=numpy.zeros((dataOut.NACF,dataOut.IBITS),'float32')
3212 3212 dataOut.acfs_error_LP=numpy.zeros((dataOut.NACF,dataOut.IBITS),'float32')
3213 3213
3214 3214 for i in range(dataOut.NACF):
3215 3215 for j in range(dataOut.IBITS):
3216 3216 if numpy.abs(dataOut.errors[j,i]/dataOut.output_LP_integrated.real[0,i,0])<1.0:
3217 3217 dataOut.acfs_LP[i,j]=dataOut.output_LP_integrated.real[j,i,0]/dataOut.output_LP_integrated.real[0,i,0]
3218 3218 dataOut.acfs_LP[i,j]=max(min(dataOut.acfs_LP[i,j],1.0),-1.0)
3219 3219
3220 3220 dataOut.acfs_error_LP[i,j]=dataOut.errors[j,i]/dataOut.output_LP_integrated.real[0,i,0]
3221 3221 else:
3222 3222 dataOut.acfs_LP[i,j]=numpy.nan
3223 3223
3224 3224 dataOut.acfs_error_LP[i,j]=numpy.nan
3225 3225
3226 3226 dataOut.acfs_LP=dataOut.acfs_LP.transpose()
3227 3227 dataOut.acfs_error_LP=dataOut.acfs_error_LP.transpose()
3228 3228
3229 3229 dataOut.DensityFinal *= 1.e6 #Convert units to m^⁻3
3230 3230 dataOut.EDensityFinal *= 1.e6 #Convert units to m^⁻3
3231 3231
3232 3232 return dataOut
3233 3233
3234 3234
3235 3235 class ACFs(Operation):
3236 3236 '''
3237 3237 Written by R. Flores
3238 3238 '''
3239 3239 def __init__(self, **kwargs):
3240 3240
3241 3241 Operation.__init__(self, **kwargs)
3242 3242
3243 3243 self.aux=1
3244 3244
3245 3245 def run(self,dataOut):
3246 3246
3247 3247 if self.aux:
3248 3248 self.taup=numpy.zeros(dataOut.DPL,'float32')
3249 3249 self.pacf=numpy.zeros(dataOut.DPL,'float32')
3250 3250 self.sacf=numpy.zeros(dataOut.DPL,'float32')
3251 3251
3252 3252 self.taup_full=numpy.zeros(dataOut.DPL,'float32')
3253 3253 self.pacf_full=numpy.zeros(dataOut.DPL,'float32')
3254 3254 self.sacf_full=numpy.zeros(dataOut.DPL,'float32')
3255 3255 self.x_igcej=numpy.zeros(dataOut.DPL,'float32')
3256 3256 self.y_igcej=numpy.zeros(dataOut.DPL,'float32')
3257 3257 self.x_ibad=numpy.zeros(dataOut.DPL,'float32')
3258 3258 self.y_ibad=numpy.zeros(dataOut.DPL,'float32')
3259 3259 self.aux=0
3260 3260
3261 3261 dataOut.acfs_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3262 3262 dataOut.acfs_to_save=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3263 3263 dataOut.acfs_error_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3264 3264 dataOut.acfs_error_to_save=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3265 3265 dataOut.lags_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3266 3266 dataOut.x_igcej_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3267 3267 dataOut.x_ibad_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3268 3268 dataOut.y_igcej_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3269 3269 dataOut.y_ibad_to_plot=numpy.zeros((dataOut.NDP,dataOut.DPL),'float32')
3270 3270
3271 3271 for i in range(dataOut.NSHTS):
3272 3272
3273 3273 acfm=dataOut.rhor[i][0]**2+dataOut.rhoi[i][0]**2
3274 3274
3275 3275 if acfm>0:
3276 3276 cc=dataOut.rhor[i][0]/acfm
3277 3277 ss=dataOut.rhoi[i][0]/acfm
3278 3278 else:
3279 3279 cc=1.
3280 3280 ss=0.
3281 3281
3282 3282 # keep only uncontaminated data
3283 3283 for l in range(dataOut.DPL):
3284 3284 fact=dataOut.DH
3285 3285 if (dataOut.igcej[i][l]==0 and dataOut.ibad[i][l]==0):
3286 3286
3287 3287 self.pacf_full[l]=min(1.0,max(-1.0,(dataOut.rhor[i][l]*cc + dataOut.rhoi[i][l]*ss)))*fact+dataOut.range1[i]
3288 3288 self.sacf_full[l]=min(1.0,numpy.sqrt(dataOut.sd[i][l]))*fact
3289 3289 self.taup_full[l]=dataOut.alag[l]
3290 3290 self.x_igcej[l]=numpy.nan
3291 3291 self.y_igcej[l]=numpy.nan
3292 3292 self.x_ibad[l]=numpy.nan
3293 3293 self.y_ibad[l]=numpy.nan
3294 3294
3295 3295 else:
3296 3296 self.pacf_full[l]=numpy.nan
3297 3297 self.sacf_full[l]=numpy.nan
3298 3298 self.taup_full[l]=numpy.nan
3299 3299
3300 3300 if dataOut.igcej[i][l]:
3301 3301 self.x_igcej[l]=dataOut.alag[l]
3302 3302 self.y_igcej[l]=dataOut.range1[i]
3303 3303 self.x_ibad[l]=numpy.nan
3304 3304 self.y_ibad[l]=numpy.nan
3305 3305
3306 3306 if dataOut.ibad[i][l]:
3307 3307 self.x_igcej[l]=numpy.nan
3308 3308 self.y_igcej[l]=numpy.nan
3309 3309 self.x_ibad[l]=dataOut.alag[l]
3310 3310 self.y_ibad[l]=dataOut.range1[i]
3311 3311
3312 3312 pacf_new=numpy.copy((self.pacf_full-dataOut.range1[i])/dataOut.DH)
3313 3313 sacf_new=numpy.copy(self.sacf_full/dataOut.DH)
3314 3314 dataOut.acfs_to_save[i,:]=numpy.copy(pacf_new)
3315 3315 dataOut.acfs_error_to_save[i,:]=numpy.copy(sacf_new)
3316 3316 dataOut.acfs_to_plot[i,:]=numpy.copy(self.pacf_full)
3317 3317 dataOut.acfs_error_to_plot[i,:]=numpy.copy(self.sacf_full)
3318 3318 dataOut.lags_to_plot[i,:]=numpy.copy(self.taup_full)
3319 3319 dataOut.x_igcej_to_plot[i,:]=numpy.copy(self.x_igcej)
3320 3320 dataOut.x_ibad_to_plot[i,:]=numpy.copy(self.x_ibad)
3321 3321 dataOut.y_igcej_to_plot[i,:]=numpy.copy(self.y_igcej)
3322 3322 dataOut.y_ibad_to_plot[i,:]=numpy.copy(self.y_ibad)
3323 3323
3324 3324 missing=numpy.nan#-32767
3325 3325
3326 3326 for i in range(dataOut.NSHTS,dataOut.NDP):
3327 3327 for j in range(dataOut.DPL):
3328 3328 dataOut.acfs_to_save[i,j]=missing
3329 3329 dataOut.acfs_error_to_save[i,j]=missing
3330 3330 dataOut.acfs_to_plot[i,j]=missing
3331 3331 dataOut.acfs_error_to_plot[i,j]=missing
3332 3332 dataOut.lags_to_plot[i,j]=missing
3333 3333 dataOut.x_igcej_to_plot[i,j]=missing
3334 3334 dataOut.x_ibad_to_plot[i,j]=missing
3335 3335 dataOut.y_igcej_to_plot[i,j]=missing
3336 3336 dataOut.y_ibad_to_plot[i,j]=missing
3337 3337
3338 3338 dataOut.acfs_to_save=dataOut.acfs_to_save.transpose()
3339 3339 dataOut.acfs_error_to_save=dataOut.acfs_error_to_save.transpose()
3340 3340
3341 3341 return dataOut
3342 3342
3343 3343
3344 3344 class CohInt(Operation):
3345 3345
3346 3346 isConfig = False
3347 3347 __profIndex = 0
3348 3348 __byTime = False
3349 3349 __initime = None
3350 3350 __lastdatatime = None
3351 3351 __integrationtime = None
3352 3352 __buffer = None
3353 3353 __bufferStride = []
3354 3354 __dataReady = False
3355 3355 __profIndexStride = 0
3356 3356 __dataToPutStride = False
3357 3357 n = None
3358 3358
3359 3359 def __init__(self, **kwargs):
3360 3360
3361 3361 Operation.__init__(self, **kwargs)
3362 3362
3363 3363 # self.isConfig = False
3364 3364
3365 3365 def setup(self, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False):
3366 3366 """
3367 3367 Set the parameters of the integration class.
3368 3368
3369 3369 Inputs:
3370 3370
3371 3371 n : Number of coherent integrations
3372 3372 timeInterval : Time of integration. If the parameter "n" is selected this one does not work
3373 3373 overlapping :
3374 3374 """
3375 3375
3376 3376 self.__initime = None
3377 3377 self.__lastdatatime = 0
3378 3378 self.__buffer = None
3379 3379 self.__dataReady = False
3380 3380 self.byblock = byblock
3381 3381 self.stride = stride
3382 3382
3383 3383 if n == None and timeInterval == None:
3384 3384 raise ValueError("n or timeInterval should be specified ...")
3385 3385
3386 3386 if n != None:
3387 3387 self.n = n
3388 3388 self.__byTime = False
3389 3389 else:
3390 3390 self.__integrationtime = timeInterval #* 60. #if (type(timeInterval)!=integer) -> change this line
3391 3391 self.n = 9999
3392 3392 self.__byTime = True
3393 3393
3394 3394 if overlapping:
3395 3395 self.__withOverlapping = True
3396 3396 self.__buffer = None
3397 3397 else:
3398 3398 self.__withOverlapping = False
3399 3399 self.__buffer = 0
3400 3400
3401 3401 self.__profIndex = 0
3402 3402
3403 3403 def putData(self, data):
3404 3404
3405 3405 """
3406 3406 Add a profile to the __buffer and increase in one the __profileIndex
3407 3407
3408 3408 """
3409 3409
3410 3410 if not self.__withOverlapping:
3411 3411 self.__buffer += data.copy()
3412 3412 self.__profIndex += 1
3413 3413 return
3414 3414
3415 3415 #Overlapping data
3416 3416 nChannels, nHeis = data.shape
3417 3417 data = numpy.reshape(data, (1, nChannels, nHeis))
3418 3418
3419 3419 #If the buffer is empty then it takes the data value
3420 3420 if self.__buffer is None:
3421 3421 self.__buffer = data
3422 3422 self.__profIndex += 1
3423 3423 return
3424 3424
3425 3425 #If the buffer length is lower than n then stakcing the data value
3426 3426 if self.__profIndex < self.n:
3427 3427 self.__buffer = numpy.vstack((self.__buffer, data))
3428 3428 self.__profIndex += 1
3429 3429 return
3430 3430
3431 3431 #If the buffer length is equal to n then replacing the last buffer value with the data value
3432 3432 self.__buffer = numpy.roll(self.__buffer, -1, axis=0)
3433 3433 self.__buffer[self.n-1] = data
3434 3434 self.__profIndex = self.n
3435 3435 return
3436 3436
3437 3437
3438 3438 def pushData(self):
3439 3439 """
3440 3440 Return the sum of the last profiles and the profiles used in the sum.
3441 3441
3442 3442 Affected:
3443 3443
3444 3444 self.__profileIndex
3445 3445
3446 3446 """
3447 3447
3448 3448 if not self.__withOverlapping:
3449 3449 data = self.__buffer
3450 3450 n = self.__profIndex
3451 3451
3452 3452 self.__buffer = 0
3453 3453 self.__profIndex = 0
3454 3454
3455 3455 return data, n
3456 3456
3457 3457 #Integration with Overlapping
3458 3458 data = numpy.sum(self.__buffer, axis=0)
3459 3459 # print data
3460 3460 # raise
3461 3461 n = self.__profIndex
3462 3462
3463 3463 return data, n
3464 3464
3465 3465 def byProfiles(self, data):
3466 3466
3467 3467 self.__dataReady = False
3468 3468 avgdata = None
3469 3469 # n = None
3470 3470 # print data
3471 3471 # raise
3472 3472 self.putData(data)
3473 3473
3474 3474 if self.__profIndex == self.n:
3475 3475 avgdata, n = self.pushData()
3476 3476 self.__dataReady = True
3477 3477
3478 3478 return avgdata
3479 3479
3480 3480 def byTime(self, data, datatime):
3481 3481
3482 3482 self.__dataReady = False
3483 3483 avgdata = None
3484 3484 n = None
3485 3485
3486 3486 self.putData(data)
3487 3487
3488 3488 if (datatime - self.__initime) >= self.__integrationtime:
3489 3489 avgdata, n = self.pushData()
3490 3490 self.n = n
3491 3491 self.__dataReady = True
3492 3492
3493 3493 return avgdata
3494 3494
3495 3495 def integrateByStride(self, data, datatime):
3496 3496 # print data
3497 3497 if self.__profIndex == 0:
3498 3498 self.__buffer = [[data.copy(), datatime]]
3499 3499 else:
3500 3500 self.__buffer.append([data.copy(),datatime])
3501 3501 self.__profIndex += 1
3502 3502 self.__dataReady = False
3503 3503
3504 3504 if self.__profIndex == self.n * self.stride :
3505 3505 self.__dataToPutStride = True
3506 3506 self.__profIndexStride = 0
3507 3507 self.__profIndex = 0
3508 3508 self.__bufferStride = []
3509 3509 for i in range(self.stride):
3510 3510 current = self.__buffer[i::self.stride]
3511 3511 data = numpy.sum([t[0] for t in current], axis=0)
3512 3512 avgdatatime = numpy.average([t[1] for t in current])
3513 3513 # print data
3514 3514 self.__bufferStride.append((data, avgdatatime))
3515 3515
3516 3516 if self.__dataToPutStride:
3517 3517 self.__dataReady = True
3518 3518 self.__profIndexStride += 1
3519 3519 if self.__profIndexStride == self.stride:
3520 3520 self.__dataToPutStride = False
3521 3521 # print self.__bufferStride[self.__profIndexStride - 1]
3522 3522 # raise
3523 3523 return self.__bufferStride[self.__profIndexStride - 1]
3524 3524
3525 3525
3526 3526 return None, None
3527 3527
3528 3528 def integrate(self, data, datatime=None):
3529 3529
3530 3530 if self.__initime == None:
3531 3531 self.__initime = datatime
3532 3532
3533 3533 if self.__byTime:
3534 3534 avgdata = self.byTime(data, datatime)
3535 3535 else:
3536 3536 avgdata = self.byProfiles(data)
3537 3537
3538 3538
3539 3539 self.__lastdatatime = datatime
3540 3540
3541 3541 if avgdata is None:
3542 3542 return None, None
3543 3543
3544 3544 avgdatatime = self.__initime
3545 3545
3546 3546 deltatime = datatime - self.__lastdatatime
3547 3547
3548 3548 if not self.__withOverlapping:
3549 3549 self.__initime = datatime
3550 3550 else:
3551 3551 self.__initime += deltatime
3552 3552
3553 3553 return avgdata, avgdatatime
3554 3554
3555 3555 def integrateByBlock(self, dataOut):
3556 3556
3557 3557 times = int(dataOut.data.shape[1]/self.n)
3558 3558 avgdata = numpy.zeros((dataOut.nChannels, times, dataOut.nHeights), dtype=complex)
3559 3559
3560 3560 id_min = 0
3561 3561 id_max = self.n
3562 3562
3563 3563 for i in range(times):
3564 3564 junk = dataOut.data[:,id_min:id_max,:]
3565 3565 avgdata[:,i,:] = junk.sum(axis=1)
3566 3566 id_min += self.n
3567 3567 id_max += self.n
3568 3568
3569 3569 timeInterval = dataOut.ippSeconds*self.n
3570 3570 avgdatatime = (times - 1) * timeInterval + dataOut.utctime
3571 3571 self.__dataReady = True
3572 3572 return avgdata, avgdatatime
3573 3573
3574 3574 def run(self, dataOut, n=None, timeInterval=None, stride=None, overlapping=False, byblock=False, **kwargs):
3575 3575
3576 3576 if not self.isConfig:
3577 3577 self.setup(n=n, stride=stride, timeInterval=timeInterval, overlapping=overlapping, byblock=byblock, **kwargs)
3578 3578 self.isConfig = True
3579 3579
3580 3580 if dataOut.flagDataAsBlock:
3581 3581 """
3582 3582 Si la data es leida por bloques, dimension = [nChannels, nProfiles, nHeis]
3583 3583 """
3584 3584
3585 3585 avgdata, avgdatatime = self.integrateByBlock(dataOut)
3586 3586 dataOut.nProfiles /= self.n
3587 3587 else:
3588 3588 if stride is None:
3589 3589 avgdata, avgdatatime = self.integrate(dataOut.data, dataOut.utctime)
3590 3590 else:
3591 3591 avgdata, avgdatatime = self.integrateByStride(dataOut.data, dataOut.utctime)
3592 3592
3593 3593
3594 3594 # dataOut.timeInterval *= n
3595 3595 dataOut.flagNoData = True
3596 3596
3597 3597 if self.__dataReady:
3598 3598 dataOut.data = avgdata
3599 3599 if not dataOut.flagCohInt:
3600 3600 dataOut.nCohInt *= self.n
3601 3601 dataOut.flagCohInt = True
3602 3602 dataOut.utctime = avgdatatime
3603 3603 # print avgdata, avgdatatime
3604 3604 # raise
3605 3605 # dataOut.timeInterval = dataOut.ippSeconds * dataOut.nCohInt
3606 3606 dataOut.flagNoData = False
3607 3607 return dataOut
3608 3608
3609 3609 class TimesCode(Operation):
3610 3610 '''
3611 3611 Written by R. Flores
3612 3612 '''
3613 3613 """
3614 3614
3615 3615 """
3616 3616
3617 3617 def __init__(self, **kwargs):
3618 3618
3619 3619 Operation.__init__(self, **kwargs)
3620 3620
3621 3621 def run(self,dataOut,code):
3622 3622
3623 3623 #code = numpy.repeat(code, repeats=osamp, axis=1)
3624 3624 nCodes = numpy.shape(code)[1]
3625 3625 #nprofcode = dataOut.nProfiles//nCodes
3626 3626 code = numpy.array(code)
3627 3627 #print("nHeights",dataOut.nHeights)
3628 3628 #print("nheicode",nheicode)
3629 3629 #print("Code.Shape",numpy.shape(code))
3630 3630 #print("Code",code[0,:])
3631 3631 nheicode = dataOut.nHeights//nCodes
3632 3632 res = dataOut.nHeights%nCodes
3633 3633 '''
3634 3634 buffer = numpy.zeros((dataOut.nChannels,
3635 3635 nprofcode,
3636 3636 nCodes,
3637 3637 ndataOut.nHeights),
3638 3638 dtype='complex')
3639 3639 '''
3640 3640 #exit(1)
3641 3641 #for ipr in range(dataOut.nProfiles):
3642 3642 #print(dataOut.nHeights)
3643 3643 #print(dataOut.data[0,384-2:])
3644 3644 #print(dataOut.profileIndex)
3645 3645 #print(dataOut.data[0,:2])
3646 3646 #print(dataOut.data[0,0:64])
3647 3647 #print(dataOut.data[0,64:64+64])
3648 3648 #exit(1)
3649 3649 for ich in range(dataOut.nChannels):
3650 3650 for ihe in range(nheicode):
3651 3651 #print(ihe*nCodes)
3652 3652 #print((ihe+1)*nCodes)
3653 3653 #dataOut.data[ich,ipr,ihe*nCodes:nCodes*(ihe+1)]
3654 3654 #code[ipr,:]
3655 3655 #print("before",dataOut.data[ich,ipr,ihe*nCodes:nCodes*(ihe+1)])
3656 3656 #dataOut.data[ich,ipr,ihe*nCodes:nCodes*(ihe+1)] = numpy.prod([dataOut.data[ich,ipr,ihe*nCodes:nCodes*(ihe+1)],code[ipr,:]],axis=0)
3657 3657 dataOut.data[ich,ihe*nCodes:nCodes*(ihe+1)] = numpy.prod([dataOut.data[ich,ihe*nCodes:nCodes*(ihe+1)],code[dataOut.profileIndex,:]],axis=0)
3658 3658
3659 3659 #print("after",dataOut.data[ich,ipr,ihe*nCodes:nCodes*(ihe+1)])
3660 3660 #exit(1)
3661 3661 #print(dataOut.data[0,:2])
3662 3662 #exit(1)
3663 3663 #print(nheicode)
3664 3664 #print((nheicode)*nCodes)
3665 3665 #print(((nheicode)*nCodes)+res)
3666 3666 if res != 0:
3667 3667 for ich in range(dataOut.nChannels):
3668 3668 dataOut.data[ich,nheicode*nCodes:] = numpy.prod([dataOut.data[ich,nheicode*nCodes:],code[dataOut.profileIndex,:res]],axis=0)
3669 3669
3670 3670 #pass
3671 3671 #print(dataOut.data[0,384-2:])
3672 3672 #exit(1)
3673 3673 #dataOut.data = numpy.mean(buffer,axis=1)
3674 3674 #print(numpy.shape(dataOut.data))
3675 3675 #print(dataOut.nHeights)
3676 3676 #dataOut.heightList = dataOut.heightList[0:nheicode]
3677 3677 #print(dataOut.nHeights)
3678 3678 #dataOut.nHeights = numpy.shape(dataOut.data)[2]
3679 3679 #print(numpy.shape(dataOut.data))
3680 3680 #exit(1)
3681 3681
3682 3682 return dataOut
3683 3683
3684 3684 '''
3685 3685 class Spectrogram(Operation):
3686 3686 """
3687 3687
3688 3688 """
3689 3689
3690 3690 def __init__(self, **kwargs):
3691 3691
3692 3692 Operation.__init__(self, **kwargs)
3693 3693
3694 3694
3695 3695
3696 3696 def run(self,dataOut):
3697 3697
3698 3698 import scipy
3699 3699
3700 3700
3701 3701
3702 3702 fs = 3200*1e-6
3703 3703 fs = fs/64
3704 3704 fs = 1/fs
3705 3705
3706 3706 nperseg=64
3707 3707 noverlap=48
3708 3708
3709 3709 f, t, Sxx = signal.spectrogram(x, fs, return_onesided=False, nperseg=nperseg, noverlap=noverlap, mode='complex')
3710 3710
3711 3711
3712 3712 for ich in range(dataOut.nChannels):
3713 3713 for ihe in range(nheicode):
3714 3714
3715 3715
3716 3716 return dataOut
3717 3717 '''
3718 3718
3719 3719
3720 3720 class RemoveDcHae(Operation):
3721 3721 '''
3722 3722 Written by R. Flores
3723 3723 '''
3724 3724 def __init__(self, **kwargs):
3725 3725
3726 3726 Operation.__init__(self, **kwargs)
3727 3727 self.DcCounter = 0
3728 3728
3729 3729 def run(self, dataOut):
3730 3730
3731 3731 if self.DcCounter == 0:
3732 3732 dataOut.DcHae = numpy.zeros((dataOut.data.shape[0],320),dtype='complex')
3733 3733 #dataOut.DcHae = []
3734 3734 self.DcCounter = 1
3735 3735
3736 3736 dataOut.dataaux = numpy.copy(dataOut.data)
3737 3737
3738 3738 #dataOut.DcHae += dataOut.dataaux[:,1666:1666+320]
3739 3739 dataOut.DcHae += dataOut.dataaux[:,0:0+320]
3740 3740 hei = 1666
3741 3741 hei = 2000
3742 3742 hei = 1000
3743 3743 hei = 0
3744 3744 #dataOut.DcHae = numpy.concatenate([dataOut.DcHae,dataOut.dataaux[0,hei]],axis = None)
3745 3745
3746 3746
3747 3747
3748 3748 return dataOut
3749 3749
3750 3750
3751 3751 class SSheightProfiles(Operation):
3752 3752
3753 3753 step = None
3754 3754 nsamples = None
3755 3755 bufferShape = None
3756 3756 profileShape = None
3757 3757 sshProfiles = None
3758 3758 profileIndex = None
3759 3759
3760 3760 def __init__(self, **kwargs):
3761 3761
3762 3762 Operation.__init__(self, **kwargs)
3763 3763 self.isConfig = False
3764 3764
3765 3765 def setup(self,dataOut ,step = None , nsamples = None):
3766 3766
3767 3767 if step == None and nsamples == None:
3768 3768 #pass
3769 3769 raise ValueError("step or nheights should be specified ...")
3770 3770
3771 3771 self.step = step
3772 3772 self.nsamples = nsamples
3773 3773 self.__nChannels = dataOut.nChannels
3774 3774 self.__nProfiles = dataOut.nProfiles
3775 3775 self.__nHeis = dataOut.nHeights
3776 3776 shape = dataOut.data.shape #nchannels, nprofiles, nsamples
3777 3777
3778 3778 residue = (shape[1] - self.nsamples) % self.step
3779 3779 if residue != 0:
3780 3780 print("The residue is %d, step=%d should be multiple of %d to avoid loss of %d samples"%(residue,step,shape[1] - self.nsamples,residue))
3781 3781
3782 3782 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
3783 3783 numberProfile = self.nsamples
3784 3784 numberSamples = (shape[1] - self.nsamples)/self.step
3785 3785
3786 3786 self.bufferShape = int(shape[0]), int(numberSamples), int(numberProfile) # nchannels, nsamples , nprofiles
3787 3787 self.profileShape = int(shape[0]), int(numberProfile), int(numberSamples) # nchannels, nprofiles, nsamples
3788 3788
3789 3789 self.buffer = numpy.zeros(self.bufferShape , dtype=complex)
3790 3790 self.sshProfiles = numpy.zeros(self.profileShape, dtype=complex)
3791 3791
3792 3792 def run(self, dataOut, step, nsamples, code = None, repeat = None):
3793 dataOut.flagNoData = True
3793 dataOut.flagNoData = True
3794 3794 profileIndex = None
3795 dataOut.flagDataAsBlock = False
3795 dataOut.flagDataAsBlock = False
3796 3796
3797 3797 if not self.isConfig:
3798 3798 self.setup(dataOut, step=step , nsamples=nsamples)
3799 3799 self.isConfig = True
3800 3800
3801 3801 if code is not None:
3802 3802 code = numpy.array(code)
3803 3803 code_block = code
3804 3804
3805 3805 if repeat is not None:
3806 3806 code_block = numpy.repeat(code_block, repeats=repeat, axis=1)
3807 3807
3808 3808 for i in range(self.buffer.shape[1]):
3809 3809 if code is not None:
3810 3810 #self.buffer[:,i] = dataOut.data[:,i*self.step:i*self.step + self.nsamples]*code_block[dataOut.profileIndex,:]
3811 3811 self.buffer[:,i] = dataOut.data[:,i*self.step:i*self.step + self.nsamples]*code_block
3812 3812 else:
3813 3813 self.buffer[:,i] = dataOut.data[:,i*self.step:i*self.step + self.nsamples]#*code[dataOut.profileIndex,:]
3814 3814
3815 3815 for j in range(self.buffer.shape[0]):
3816 3816 self.sshProfiles[j] = numpy.transpose(self.buffer[j])
3817 3817
3818 3818 profileIndex = self.nsamples
3819 3819 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
3820 3820 ippSeconds = (deltaHeight*1.0e-6)/(0.15)
3821 3821
3822 3822 try:
3823 3823 if dataOut.concat_m is not None:
3824 3824 ippSeconds= ippSeconds/float(dataOut.concat_m)
3825 3825 except:
3826 3826 pass
3827 3827
3828 3828 dataOut.data = self.sshProfiles
3829 3829 dataOut.flagNoData = False
3830 3830 dataOut.heightList = numpy.arange(self.buffer.shape[1]) *self.step*deltaHeight + dataOut.heightList[0]
3831 3831 dataOut.nProfiles = int(dataOut.nProfiles*self.nsamples)
3832 3832
3833 3833 dataOut.profileIndex = profileIndex
3834 3834 dataOut.flagDataAsBlock = True
3835 3835 dataOut.ippSeconds = ippSeconds
3836 3836 dataOut.step = self.step
3837 3837
3838 3838 return dataOut
3839 3839
3840 3840 class removeDCHAE(Operation):
3841 3841
3842 3842 def run(self, dataOut, minHei, maxHei):
3843 3843
3844 3844 heights = dataOut.heightList
3845 3845
3846 3846 inda = numpy.where(heights >= minHei)
3847 3847 indb = numpy.where(heights <= maxHei)
3848 3848
3849 3849 minIndex = inda[0][0]
3850 3850 maxIndex = indb[0][-1]
3851 3851
3852 3852 dc = numpy.average(dataOut.data[:,minIndex:maxIndex],axis=1)
3853 3853 #print(dc.shape)
3854 3854 dataOut.data = dataOut.data - dc[:,None]
3855 3855 #print(aux.shape)
3856 3856 #exit(1)
3857 3857
3858 3858 return dataOut
3859 3859
3860 3860 class Decoder(Operation):
3861 3861
3862 3862 isConfig = False
3863 3863 __profIndex = 0
3864 3864
3865 3865 code = None
3866 3866
3867 3867 nCode = None
3868 3868 nBaud = None
3869 3869
3870 3870 def __init__(self, **kwargs):
3871 3871
3872 3872 Operation.__init__(self, **kwargs)
3873 3873
3874 3874 self.times = None
3875 3875 self.osamp = None
3876 3876 # self.__setValues = False
3877 3877 self.isConfig = False
3878 3878 self.setupReq = False
3879 3879 def setup(self, code, osamp, dataOut):
3880 3880
3881 3881 self.__profIndex = 0
3882 3882
3883 3883 self.code = code
3884 3884
3885 3885 self.nCode = len(code)
3886 3886 self.nBaud = len(code[0])
3887 3887
3888 3888 if (osamp != None) and (osamp >1):
3889 3889 self.osamp = osamp
3890 3890 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
3891 3891 self.nBaud = self.nBaud*self.osamp
3892 3892
3893 3893 self.__nChannels = dataOut.nChannels
3894 3894 self.__nProfiles = dataOut.nProfiles
3895 3895 self.__nHeis = dataOut.nHeights
3896 3896
3897 3897 if self.__nHeis < self.nBaud:
3898 3898 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
3899 3899
3900 3900 #Frequency
3901 3901 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=complex)
3902 3902
3903 3903 __codeBuffer[:,0:self.nBaud] = self.code
3904 3904
3905 3905 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
3906 3906
3907 3907 if dataOut.flagDataAsBlock:
3908 3908
3909 3909 self.ndatadec = self.__nHeis #- self.nBaud + 1
3910 3910
3911 3911 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=complex)
3912 3912
3913 3913 else:
3914 3914
3915 3915 #Time
3916 3916 self.ndatadec = self.__nHeis #- self.nBaud + 1
3917 3917
3918 3918
3919 3919 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=complex)
3920 3920
3921 3921 def __convolutionInFreq(self, data):
3922 3922
3923 3923 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
3924 3924
3925 3925 fft_data = numpy.fft.fft(data, axis=1)
3926 3926
3927 3927 conv = fft_data*fft_code
3928 3928
3929 3929 data = numpy.fft.ifft(conv,axis=1)
3930 3930
3931 3931 return data
3932 3932
3933 3933 def __convolutionInFreqOpt(self, data):
3934 3934
3935 3935 raise NotImplementedError
3936 3936
3937 3937 def __convolutionInTime(self, data):
3938 3938
3939 3939 code = self.code[self.__profIndex]
3940 3940 for i in range(self.__nChannels):
3941 3941 #aux=numpy.correlate(data[i,:], code, mode='full')
3942 3942 #print(numpy.shape(aux))
3943 3943 #print(numpy.shape(data[i,:]))
3944 3944 #print(numpy.shape(code))
3945 3945 #exit(1)
3946 3946 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
3947 3947
3948 3948 return self.datadecTime
3949 3949
3950 3950 def __convolutionByBlockInTime(self, data):
3951 3951
3952 3952 repetitions = int(self.__nProfiles / self.nCode)
3953 3953 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
3954 3954 junk = junk.flatten()
3955 3955 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
3956 3956 profilesList = range(self.__nProfiles)
3957 3957 #print(numpy.shape(self.datadecTime))
3958 3958 #print(numpy.shape(data))
3959 3959 for i in range(self.__nChannels):
3960 3960 for j in profilesList:
3961 3961 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
3962 3962 return self.datadecTime
3963 3963
3964 3964 def __convolutionByBlockInFreq(self, data):
3965 3965
3966 3966 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
3967 3967
3968 3968
3969 3969 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
3970 3970
3971 3971 fft_data = numpy.fft.fft(data, axis=2)
3972 3972
3973 3973 conv = fft_data*fft_code
3974 3974
3975 3975 data = numpy.fft.ifft(conv,axis=2)
3976 3976
3977 3977 return data
3978 3978
3979 3979
3980 3980 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
3981 3981
3982 3982 if dataOut.flagDecodeData:
3983 3983 print("This data is already decoded, recoding again ...")
3984 3984
3985 3985 if not self.isConfig:
3986 3986
3987 3987 if code is None:
3988 3988 if dataOut.code is None:
3989 3989 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
3990 3990
3991 3991 code = dataOut.code
3992 3992 else:
3993 3993 code = numpy.array(code).reshape(nCode,nBaud)
3994 3994 self.setup(code, osamp, dataOut)
3995 3995
3996 3996 self.isConfig = True
3997 3997
3998 3998 if mode == 3:
3999 3999 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
4000 4000
4001 4001 if times != None:
4002 4002 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
4003 4003
4004 4004 if self.code is None:
4005 4005 print("Fail decoding: Code is not defined.")
4006 4006 return
4007 4007
4008 4008 self.__nProfiles = dataOut.nProfiles
4009 4009 datadec = None
4010 4010
4011 4011 if mode == 3:
4012 4012 mode = 0
4013 4013
4014 4014 if dataOut.flagDataAsBlock:
4015 4015 """
4016 4016 Decoding when data have been read as block,
4017 4017 """
4018 4018
4019 4019 if mode == 0:
4020 4020 datadec = self.__convolutionByBlockInTime(dataOut.data)
4021 4021 if mode == 1:
4022 4022 datadec = self.__convolutionByBlockInFreq(dataOut.data)
4023 4023 else:
4024 4024 """
4025 4025 Decoding when data have been read profile by profile
4026 4026 """
4027 4027 if mode == 0:
4028 4028 datadec = self.__convolutionInTime(dataOut.data)
4029 4029
4030 4030 if mode == 1:
4031 4031 datadec = self.__convolutionInFreq(dataOut.data)
4032 4032
4033 4033 if mode == 2:
4034 4034 datadec = self.__convolutionInFreqOpt(dataOut.data)
4035 4035
4036 4036 if datadec is None:
4037 4037 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
4038 4038
4039 4039 dataOut.code = self.code
4040 4040 dataOut.nCode = self.nCode
4041 4041 dataOut.nBaud = self.nBaud
4042 4042
4043 4043 dataOut.data = datadec
4044 4044 #print("before",dataOut.heightList)
4045 4045 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
4046 4046 #print("after",dataOut.heightList)
4047 4047
4048 4048 dataOut.flagDecodeData = True #asumo q la data esta decodificada
4049 4049
4050 4050 if self.__profIndex == self.nCode-1:
4051 4051 self.__profIndex = 0
4052 4052 return dataOut
4053 4053
4054 4054 self.__profIndex += 1
4055 4055
4056 4056 #print("SHAPE",numpy.shape(dataOut.data))
4057 4057
4058 4058 return dataOut
4059 4059 # dataOut.flagDeflipData = True #asumo q la data no esta sin flip
4060 4060
4061 4061 class DecoderRoll(Operation):
4062 4062
4063 4063 isConfig = False
4064 4064 __profIndex = 0
4065 4065
4066 4066 code = None
4067 4067
4068 4068 nCode = None
4069 4069 nBaud = None
4070 4070
4071 4071 def __init__(self, **kwargs):
4072 4072
4073 4073 Operation.__init__(self, **kwargs)
4074 4074
4075 4075 self.times = None
4076 4076 self.osamp = None
4077 4077 # self.__setValues = False
4078 4078 self.isConfig = False
4079 4079 self.setupReq = False
4080 4080 def setup(self, code, osamp, dataOut):
4081 4081
4082 4082 self.__profIndex = 0
4083 4083
4084 4084
4085 4085 self.code = code
4086 4086
4087 4087 self.nCode = len(code)
4088 4088 self.nBaud = len(code[0])
4089 4089
4090 4090 if (osamp != None) and (osamp >1):
4091 4091 self.osamp = osamp
4092 4092 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
4093 4093 self.nBaud = self.nBaud*self.osamp
4094 4094
4095 4095 self.__nChannels = dataOut.nChannels
4096 4096 self.__nProfiles = dataOut.nProfiles
4097 4097 self.__nHeis = dataOut.nHeights
4098 4098
4099 4099 if self.__nHeis < self.nBaud:
4100 4100 raise ValueError('Number of heights (%d) should be greater than number of bauds (%d)' %(self.__nHeis, self.nBaud))
4101 4101
4102 4102 #Frequency
4103 4103 __codeBuffer = numpy.zeros((self.nCode, self.__nHeis), dtype=complex)
4104 4104
4105 4105 __codeBuffer[:,0:self.nBaud] = self.code
4106 4106
4107 4107 self.fft_code = numpy.conj(numpy.fft.fft(__codeBuffer, axis=1))
4108 4108
4109 4109 if dataOut.flagDataAsBlock:
4110 4110
4111 4111 self.ndatadec = self.__nHeis #- self.nBaud + 1
4112 4112
4113 4113 self.datadecTime = numpy.zeros((self.__nChannels, self.__nProfiles, self.ndatadec), dtype=complex)
4114 4114
4115 4115 else:
4116 4116
4117 4117 #Time
4118 4118 self.ndatadec = self.__nHeis #- self.nBaud + 1
4119 4119
4120 4120
4121 4121 self.datadecTime = numpy.zeros((self.__nChannels, self.ndatadec), dtype=complex)
4122 4122
4123 4123 def __convolutionInFreq(self, data):
4124 4124
4125 4125 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
4126 4126
4127 4127 fft_data = numpy.fft.fft(data, axis=1)
4128 4128
4129 4129 conv = fft_data*fft_code
4130 4130
4131 4131 data = numpy.fft.ifft(conv,axis=1)
4132 4132
4133 4133 return data
4134 4134
4135 4135 def __convolutionInFreqOpt(self, data):
4136 4136
4137 4137 raise NotImplementedError
4138 4138
4139 4139 def __convolutionInTime(self, data):
4140 4140
4141 4141 code = self.code[self.__profIndex]
4142 4142 #print("code",code[0,0])
4143 4143 for i in range(self.__nChannels):
4144 4144 #aux=numpy.correlate(data[i,:], code, mode='full')
4145 4145 #print(numpy.shape(aux))
4146 4146 #print(numpy.shape(data[i,:]))
4147 4147 #print(numpy.shape(code))
4148 4148 #exit(1)
4149 4149 self.datadecTime[i,:] = numpy.correlate(data[i,:], code, mode='full')[self.nBaud-1:]
4150 4150
4151 4151 return self.datadecTime
4152 4152
4153 4153 def __convolutionByBlockInTime(self, data):
4154 4154
4155 4155 repetitions = int(self.__nProfiles / self.nCode)
4156 4156 junk = numpy.lib.stride_tricks.as_strided(self.code, (repetitions, self.code.size), (0, self.code.itemsize))
4157 4157 junk = junk.flatten()
4158 4158 code_block = numpy.reshape(junk, (self.nCode*repetitions, self.nBaud))
4159 4159 profilesList = range(self.__nProfiles)
4160 4160 #print(numpy.shape(self.datadecTime))
4161 4161 #print(numpy.shape(data))
4162 4162 for i in range(self.__nChannels):
4163 4163 for j in profilesList:
4164 4164 self.datadecTime[i,j,:] = numpy.correlate(data[i,j,:], code_block[j,:], mode='full')[self.nBaud-1:]
4165 4165 return self.datadecTime
4166 4166
4167 4167 def __convolutionByBlockInFreq(self, data):
4168 4168
4169 4169 raise NotImplementedError("Decoder by frequency fro Blocks not implemented")
4170 4170
4171 4171
4172 4172 fft_code = self.fft_code[self.__profIndex].reshape(1,-1)
4173 4173
4174 4174 fft_data = numpy.fft.fft(data, axis=2)
4175 4175
4176 4176 conv = fft_data*fft_code
4177 4177
4178 4178 data = numpy.fft.ifft(conv,axis=2)
4179 4179
4180 4180 return data
4181 4181
4182 4182
4183 4183 def run(self, dataOut, code=None, nCode=None, nBaud=None, mode = 0, osamp=None, times=None):
4184 4184
4185 4185 if dataOut.flagDecodeData:
4186 4186 print("This data is already decoded, recoding again ...")
4187 4187
4188 4188
4189 4189 roll = 0
4190 4190
4191 4191 if self.isConfig:
4192 4192 code = numpy.array(code)
4193 4193
4194 4194 code = numpy.roll(code,roll,axis=0)
4195 4195 code = numpy.reshape(code,(5,100,64))
4196 4196 block = dataOut.CurrentBlock%5
4197 4197 #code = code[block-1,:,:] #NormalizeDPPower
4198 4198 code = code[block-1-1,:,:] #Next Day
4199 4199 self.code = numpy.repeat(code, repeats=self.osamp, axis=1)
4200 4200
4201 4201
4202 4202 if not self.isConfig:
4203 4203
4204 4204 if code is None:
4205 4205 if dataOut.code is None:
4206 4206 raise ValueError("Code could not be read from %s instance. Enter a value in Code parameter" %dataOut.type)
4207 4207
4208 4208 code = dataOut.code
4209 4209 else:
4210 4210 code = numpy.array(code)
4211 4211
4212 4212 #roll = 29
4213 4213 code = numpy.roll(code,roll,axis=0)
4214 4214 code = numpy.reshape(code,(5,100,64))
4215 4215 block = dataOut.CurrentBlock%5
4216 4216 code = code[block-1-1,:,:]
4217 4217 #print(code.shape())
4218 4218 #exit(1)
4219 4219
4220 4220 code = numpy.array(code).reshape(nCode,nBaud)
4221 4221 self.setup(code, osamp, dataOut)
4222 4222
4223 4223 self.isConfig = True
4224 4224
4225 4225 if mode == 3:
4226 4226 sys.stderr.write("Decoder Warning: mode=%d is not valid, using mode=0\n" %mode)
4227 4227
4228 4228 if times != None:
4229 4229 sys.stderr.write("Decoder Warning: Argument 'times' in not used anymore\n")
4230 4230
4231 4231 if self.code is None:
4232 4232 print("Fail decoding: Code is not defined.")
4233 4233 return
4234 4234
4235 4235 self.__nProfiles = dataOut.nProfiles
4236 4236 datadec = None
4237 4237
4238 4238 if mode == 3:
4239 4239 mode = 0
4240 4240
4241 4241 if dataOut.flagDataAsBlock:
4242 4242 """
4243 4243 Decoding when data have been read as block,
4244 4244 """
4245 4245
4246 4246 if mode == 0:
4247 4247 datadec = self.__convolutionByBlockInTime(dataOut.data)
4248 4248 if mode == 1:
4249 4249 datadec = self.__convolutionByBlockInFreq(dataOut.data)
4250 4250 else:
4251 4251 """
4252 4252 Decoding when data have been read profile by profile
4253 4253 """
4254 4254 if mode == 0:
4255 4255 datadec = self.__convolutionInTime(dataOut.data)
4256 4256
4257 4257 if mode == 1:
4258 4258 datadec = self.__convolutionInFreq(dataOut.data)
4259 4259
4260 4260 if mode == 2:
4261 4261 datadec = self.__convolutionInFreqOpt(dataOut.data)
4262 4262
4263 4263 if datadec is None:
4264 4264 raise ValueError("Codification mode selected is not valid: mode=%d. Try selecting 0 or 1" %mode)
4265 4265
4266 4266 dataOut.code = self.code
4267 4267 dataOut.nCode = self.nCode
4268 4268 dataOut.nBaud = self.nBaud
4269 4269
4270 4270 dataOut.data = datadec
4271 4271 #print("before",dataOut.heightList)
4272 4272 dataOut.heightList = dataOut.heightList[0:datadec.shape[-1]]
4273 4273 #print("after",dataOut.heightList)
4274 4274
4275 4275 dataOut.flagDecodeData = True #asumo q la data esta decodificada
4276 4276
4277 4277 if self.__profIndex == self.nCode-1:
4278 4278 self.__profIndex = 0
4279 4279 return dataOut
4280 4280
4281 4281 self.__profIndex += 1
4282 4282
4283 4283 #print("SHAPE",numpy.shape(dataOut.data))
4284 4284
4285 4285 return dataOut
4286 4286
4287 4287
4288 4288 class ProfileConcat(Operation):
4289 4289
4290 4290 isConfig = False
4291 4291 buffer = None
4292 4292
4293 4293 def __init__(self, **kwargs):
4294 4294
4295 4295 Operation.__init__(self, **kwargs)
4296 4296 self.profileIndex = 0
4297 4297
4298 4298 def reset(self):
4299 4299 self.buffer = numpy.zeros_like(self.buffer)
4300 4300 self.start_index = 0
4301 4301 self.times = 1
4302 4302
4303 4303 def setup(self, data, m, n=1):
4304 4304 self.buffer = numpy.zeros((data.shape[0],data.shape[1]*m),dtype=type(data[0,0]))
4305 4305 self.nHeights = data.shape[1]#.nHeights
4306 4306 self.start_index = 0
4307 4307 self.times = 1
4308 4308
4309 4309 def concat(self, data):
4310 4310
4311 4311 self.buffer[:,self.start_index:self.nHeights*self.times] = data.copy()
4312 4312 self.start_index = self.start_index + self.nHeights
4313 4313
4314 4314 def run(self, dataOut, m):
4315 4315 dataOut.flagNoData = True
4316 4316
4317 4317 if not self.isConfig:
4318 4318 self.setup(dataOut.data, m, 1)
4319 4319 self.isConfig = True
4320 4320
4321 4321 if dataOut.flagDataAsBlock:
4322 4322 raise ValueError("ProfileConcat can only be used when voltage have been read profile by profile, getBlock = False")
4323 4323
4324 4324 else:
4325 4325 self.concat(dataOut.data)
4326 4326 self.times += 1
4327 4327 if self.times > m:
4328 4328 dataOut.data = self.buffer
4329 4329 self.reset()
4330 4330 dataOut.flagNoData = False
4331 4331 # se deben actualizar mas propiedades del header y del objeto dataOut, por ejemplo, las alturas
4332 4332 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
4333 4333 xf = dataOut.heightList[0] + dataOut.nHeights * deltaHeight * m
4334 4334 dataOut.heightList = numpy.arange(dataOut.heightList[0], xf, deltaHeight)
4335 4335 dataOut.ippSeconds *= m
4336 4336 return dataOut
4337 4337
4338 4338 class ProfileSelector(Operation):
4339 4339
4340 4340 profileIndex = None
4341 4341 # Tamanho total de los perfiles
4342 4342 nProfiles = None
4343 4343
4344 4344 def __init__(self, **kwargs):
4345 4345
4346 4346 Operation.__init__(self, **kwargs)
4347 4347 self.profileIndex = 0
4348 4348
4349 4349 def incProfileIndex(self):
4350 4350
4351 4351 self.profileIndex += 1
4352 4352
4353 4353 if self.profileIndex >= self.nProfiles:
4354 4354 self.profileIndex = 0
4355 4355
4356 4356 def isThisProfileInRange(self, profileIndex, minIndex, maxIndex):
4357 4357
4358 4358 if profileIndex < minIndex:
4359 4359 return False
4360 4360
4361 4361 if profileIndex > maxIndex:
4362 4362 return False
4363 4363
4364 4364 return True
4365 4365
4366 4366 def isThisProfileInList(self, profileIndex, profileList):
4367 4367
4368 4368 if profileIndex not in profileList:
4369 4369 return False
4370 4370
4371 4371 return True
4372 4372
4373 4373 def run(self, dataOut, profileList=None, profileRangeList=None, beam=None, byblock=False, rangeList = None, nProfiles=None):
4374 4374
4375 4375 """
4376 4376 ProfileSelector:
4377 4377
4378 4378 Inputs:
4379 4379 profileList : Index of profiles selected. Example: profileList = (0,1,2,7,8)
4380 4380
4381 4381 profileRangeList : Minimum and maximum profile indexes. Example: profileRangeList = (4, 30)
4382 4382
4383 4383 rangeList : List of profile ranges. Example: rangeList = ((4, 30), (32, 64), (128, 256))
4384 4384
4385 4385 """
4386 4386
4387 4387 if rangeList is not None:
4388 4388 if type(rangeList[0]) not in (tuple, list):
4389 4389 rangeList = [rangeList]
4390 4390
4391 4391 dataOut.flagNoData = True
4392 4392
4393 4393 if dataOut.flagDataAsBlock:
4394 4394 """
4395 4395 data dimension = [nChannels, nProfiles, nHeis]
4396 4396 """
4397 4397 if profileList != None:
4398 4398 dataOut.data = dataOut.data[:,profileList,:]
4399 4399
4400 4400 if profileRangeList != None:
4401 4401 minIndex = profileRangeList[0]
4402 4402 maxIndex = profileRangeList[1]
4403 4403 profileList = list(range(minIndex, maxIndex+1))
4404 4404
4405 4405 dataOut.data = dataOut.data[:,minIndex:maxIndex+1,:]
4406 4406
4407 4407 if rangeList != None:
4408 4408
4409 4409 profileList = []
4410 4410
4411 4411 for thisRange in rangeList:
4412 4412 minIndex = thisRange[0]
4413 4413 maxIndex = thisRange[1]
4414 4414
4415 4415 profileList.extend(list(range(minIndex, maxIndex+1)))
4416 4416
4417 4417 dataOut.data = dataOut.data[:,profileList,:]
4418 4418
4419 4419 dataOut.nProfiles = len(profileList)
4420 4420 dataOut.profileIndex = dataOut.nProfiles - 1
4421 4421 dataOut.flagNoData = False
4422 4422
4423 4423 return dataOut
4424 4424
4425 4425 """
4426 4426 data dimension = [nChannels, nHeis]
4427 4427 """
4428 4428
4429 4429 if profileList != None:
4430 4430
4431 4431 if self.isThisProfileInList(dataOut.profileIndex, profileList):
4432 4432
4433 4433 self.nProfiles = len(profileList)
4434 4434 dataOut.nProfiles = self.nProfiles
4435 4435 dataOut.profileIndex = self.profileIndex
4436 4436 dataOut.flagNoData = False
4437 4437
4438 4438 self.incProfileIndex()
4439 4439 return dataOut
4440 4440
4441 4441 if profileRangeList != None:
4442 4442
4443 4443 minIndex = profileRangeList[0]
4444 4444 maxIndex = profileRangeList[1]
4445 4445
4446 4446 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
4447 4447
4448 4448 self.nProfiles = maxIndex - minIndex + 1
4449 4449 dataOut.nProfiles = self.nProfiles
4450 4450 dataOut.profileIndex = self.profileIndex
4451 4451 dataOut.flagNoData = False
4452 4452
4453 4453 self.incProfileIndex()
4454 4454 return dataOut
4455 4455
4456 4456 if rangeList != None:
4457 4457
4458 4458 nProfiles = 0
4459 4459
4460 4460 for thisRange in rangeList:
4461 4461 minIndex = thisRange[0]
4462 4462 maxIndex = thisRange[1]
4463 4463
4464 4464 nProfiles += maxIndex - minIndex + 1
4465 4465
4466 4466 for thisRange in rangeList:
4467 4467
4468 4468 minIndex = thisRange[0]
4469 4469 maxIndex = thisRange[1]
4470 4470
4471 4471 if self.isThisProfileInRange(dataOut.profileIndex, minIndex, maxIndex):
4472 4472
4473 4473 self.nProfiles = nProfiles
4474 4474 dataOut.nProfiles = self.nProfiles
4475 4475 dataOut.profileIndex = self.profileIndex
4476 4476 dataOut.flagNoData = False
4477 4477
4478 4478 self.incProfileIndex()
4479 4479
4480 4480 break
4481 4481
4482 4482 return dataOut
4483 4483
4484 4484
4485 4485 if beam != None: #beam is only for AMISR data
4486 4486 if self.isThisProfileInList(dataOut.profileIndex, dataOut.beamRangeDict[beam]):
4487 4487 dataOut.flagNoData = False
4488 4488 dataOut.profileIndex = self.profileIndex
4489 4489
4490 4490 self.incProfileIndex()
4491 4491
4492 4492 return dataOut
4493 4493
4494 4494 raise ValueError("ProfileSelector needs profileList, profileRangeList or rangeList parameter")
4495 4495
4496 4496 #return False
4497 4497 return dataOut
4498 4498
4499 4499 class Reshaper(Operation):
4500 4500
4501 4501 def __init__(self, **kwargs):
4502 4502
4503 4503 Operation.__init__(self, **kwargs)
4504 4504
4505 4505 self.__buffer = None
4506 4506 self.__nitems = 0
4507 4507
4508 4508 def __appendProfile(self, dataOut, nTxs):
4509 4509
4510 4510 if self.__buffer is None:
4511 4511 shape = (dataOut.nChannels, int(dataOut.nHeights/nTxs) )
4512 4512 self.__buffer = numpy.empty(shape, dtype = dataOut.data.dtype)
4513 4513
4514 4514 ini = dataOut.nHeights * self.__nitems
4515 4515 end = ini + dataOut.nHeights
4516 4516
4517 4517 self.__buffer[:, ini:end] = dataOut.data
4518 4518
4519 4519 self.__nitems += 1
4520 4520
4521 4521 return int(self.__nitems*nTxs)
4522 4522
4523 4523 def __getBuffer(self):
4524 4524
4525 4525 if self.__nitems == int(1./self.__nTxs):
4526 4526
4527 4527 self.__nitems = 0
4528 4528
4529 4529 return self.__buffer.copy()
4530 4530
4531 4531 return None
4532 4532
4533 4533 def __checkInputs(self, dataOut, shape, nTxs):
4534 4534
4535 4535 if shape is None and nTxs is None:
4536 4536 raise ValueError("Reshaper: shape of factor should be defined")
4537 4537
4538 4538 if nTxs:
4539 4539 if nTxs < 0:
4540 4540 raise ValueError("nTxs should be greater than 0")
4541 4541
4542 4542 if nTxs < 1 and dataOut.nProfiles % (1./nTxs) != 0:
4543 4543 raise ValueError("nProfiles= %d is not divisibled by (1./nTxs) = %f" %(dataOut.nProfiles, (1./nTxs)))
4544 4544
4545 4545 shape = [dataOut.nChannels, dataOut.nProfiles*nTxs, dataOut.nHeights/nTxs]
4546 4546
4547 4547 return shape, nTxs
4548 4548
4549 4549 if len(shape) != 2 and len(shape) != 3:
4550 4550 raise ValueError("shape dimension should be equal to 2 or 3. shape = (nProfiles, nHeis) or (nChannels, nProfiles, nHeis). Actually shape = (%d, %d, %d)" %(dataOut.nChannels, dataOut.nProfiles, dataOut.nHeights))
4551 4551
4552 4552 if len(shape) == 2:
4553 4553 shape_tuple = [dataOut.nChannels]
4554 4554 shape_tuple.extend(shape)
4555 4555 else:
4556 4556 shape_tuple = list(shape)
4557 4557
4558 4558 nTxs = 1.0*shape_tuple[1]/dataOut.nProfiles
4559 4559
4560 4560 return shape_tuple, nTxs
4561 4561
4562 4562 def run(self, dataOut, shape=None, nTxs=None):
4563 4563
4564 4564 shape_tuple, self.__nTxs = self.__checkInputs(dataOut, shape, nTxs)
4565 4565
4566 4566 dataOut.flagNoData = True
4567 4567 profileIndex = None
4568 4568
4569 4569 if dataOut.flagDataAsBlock:
4570 4570
4571 4571 dataOut.data = numpy.reshape(dataOut.data, shape_tuple)
4572 4572 dataOut.flagNoData = False
4573 4573
4574 4574 profileIndex = int(dataOut.nProfiles*self.__nTxs) - 1
4575 4575
4576 4576 else:
4577 4577
4578 4578
4579 4579 if self.__nTxs < 1:
4580 4580
4581 4581 self.__appendProfile(dataOut, self.__nTxs)
4582 4582 new_data = self.__getBuffer()
4583 4583
4584 4584 if new_data is not None:
4585 4585 dataOut.data = new_data
4586 4586 dataOut.flagNoData = False
4587 4587
4588 4588 profileIndex = dataOut.profileIndex*nTxs
4589 4589
4590 4590 else:
4591 4591 raise ValueError("nTxs should be greater than 0 and lower than 1, or use VoltageReader(..., getblock=True)")
4592 4592
4593 4593 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
4594 4594
4595 4595 dataOut.heightList = numpy.arange(dataOut.nHeights/self.__nTxs) * deltaHeight + dataOut.heightList[0]
4596 4596
4597 4597 dataOut.nProfiles = int(dataOut.nProfiles*self.__nTxs)
4598 4598
4599 4599 dataOut.profileIndex = profileIndex
4600 4600
4601 4601 dataOut.ippSeconds /= self.__nTxs
4602 4602
4603 4603 return dataOut
4604 4604
4605 4605 class SplitProfiles(Operation):
4606 4606
4607 4607 def __init__(self, **kwargs):
4608 4608
4609 4609 Operation.__init__(self, **kwargs)
4610 4610
4611 4611 def run(self, dataOut, n):
4612 4612
4613 4613 dataOut.flagNoData = True
4614 4614 profileIndex = None
4615 4615
4616 4616 if dataOut.flagDataAsBlock:
4617 4617
4618 4618 #nchannels, nprofiles, nsamples
4619 4619 shape = dataOut.data.shape
4620 4620
4621 4621 if shape[2] % n != 0:
4622 4622 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[2]))
4623 4623
4624 4624 new_shape = shape[0], shape[1]*n, int(shape[2]/n)
4625 4625
4626 4626 dataOut.data = numpy.reshape(dataOut.data, new_shape)
4627 4627 dataOut.flagNoData = False
4628 4628
4629 4629 profileIndex = int(dataOut.nProfiles/n) - 1
4630 4630
4631 4631 else:
4632 4632
4633 4633 raise ValueError("Could not split the data when is read Profile by Profile. Use VoltageReader(..., getblock=True)")
4634 4634
4635 4635 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
4636 4636
4637 4637 dataOut.heightList = numpy.arange(dataOut.nHeights/n) * deltaHeight + dataOut.heightList[0]
4638 4638
4639 4639 dataOut.nProfiles = int(dataOut.nProfiles*n)
4640 4640
4641 4641 dataOut.profileIndex = profileIndex
4642 4642
4643 4643 dataOut.ippSeconds /= n
4644 4644
4645 4645 return dataOut
4646 4646
4647 4647 class CombineProfiles(Operation):
4648 4648 def __init__(self, **kwargs):
4649 4649
4650 4650 Operation.__init__(self, **kwargs)
4651 4651
4652 4652 self.__remData = None
4653 4653 self.__profileIndex = 0
4654 4654
4655 4655 def run(self, dataOut, n):
4656 4656
4657 4657 dataOut.flagNoData = True
4658 4658 profileIndex = None
4659 4659
4660 4660 if dataOut.flagDataAsBlock:
4661 4661
4662 4662 #nchannels, nprofiles, nsamples
4663 4663 shape = dataOut.data.shape
4664 4664 new_shape = shape[0], shape[1]/n, shape[2]*n
4665 4665
4666 4666 if shape[1] % n != 0:
4667 4667 raise ValueError("Could not split the data, n=%d has to be multiple of %d" %(n, shape[1]))
4668 4668
4669 4669 dataOut.data = numpy.reshape(dataOut.data, new_shape)
4670 4670 dataOut.flagNoData = False
4671 4671
4672 4672 profileIndex = int(dataOut.nProfiles*n) - 1
4673 4673
4674 4674 else:
4675 4675
4676 4676 #nchannels, nsamples
4677 4677 if self.__remData is None:
4678 4678 newData = dataOut.data
4679 4679 else:
4680 4680 newData = numpy.concatenate((self.__remData, dataOut.data), axis=1)
4681 4681
4682 4682 self.__profileIndex += 1
4683 4683
4684 4684 if self.__profileIndex < n:
4685 4685 self.__remData = newData
4686 4686 #continue
4687 4687 return
4688 4688
4689 4689 self.__profileIndex = 0
4690 4690 self.__remData = None
4691 4691
4692 4692 dataOut.data = newData
4693 4693 dataOut.flagNoData = False
4694 4694
4695 4695 profileIndex = dataOut.profileIndex/n
4696 4696
4697 4697
4698 4698 deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
4699 4699
4700 4700 dataOut.heightList = numpy.arange(dataOut.nHeights*n) * deltaHeight + dataOut.heightList[0]
4701 4701
4702 4702 dataOut.nProfiles = int(dataOut.nProfiles/n)
4703 4703
4704 4704 dataOut.profileIndex = profileIndex
4705 4705
4706 4706 dataOut.ippSeconds *= n
4707 4707
4708 4708 return dataOut
4709 4709 # import collections
4710 4710 # from scipy.stats import mode
4711 4711 #
4712 4712 # class Synchronize(Operation):
4713 4713 #
4714 4714 # isConfig = False
4715 4715 # __profIndex = 0
4716 4716 #
4717 4717 # def __init__(self, **kwargs):
4718 4718 #
4719 4719 # Operation.__init__(self, **kwargs)
4720 4720 # # self.isConfig = False
4721 4721 # self.__powBuffer = None
4722 4722 # self.__startIndex = 0
4723 4723 # self.__pulseFound = False
4724 4724 #
4725 4725 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
4726 4726 #
4727 4727 # #Read data
4728 4728 #
4729 4729 # powerdB = dataOut.getPower(channel = channel)
4730 4730 # noisedB = dataOut.getNoise(channel = channel)[0]
4731 4731 #
4732 4732 # self.__powBuffer.extend(powerdB.flatten())
4733 4733 #
4734 4734 # dataArray = numpy.array(self.__powBuffer)
4735 4735 #
4736 4736 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
4737 4737 #
4738 4738 # maxValue = numpy.nanmax(filteredPower)
4739 4739 #
4740 4740 # if maxValue < noisedB + 10:
4741 4741 # #No se encuentra ningun pulso de transmision
4742 4742 # return None
4743 4743 #
4744 4744 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
4745 4745 #
4746 4746 # if len(maxValuesIndex) < 2:
4747 4747 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
4748 4748 # return None
4749 4749 #
4750 4750 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
4751 4751 #
4752 4752 # #Seleccionar solo valores con un espaciamiento de nSamples
4753 4753 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
4754 4754 #
4755 4755 # if len(pulseIndex) < 2:
4756 4756 # #Solo se encontro un pulso de transmision con ancho mayor a 1
4757 4757 # return None
4758 4758 #
4759 4759 # spacing = pulseIndex[1:] - pulseIndex[:-1]
4760 4760 #
4761 4761 # #remover senales que se distancien menos de 10 unidades o muestras
4762 4762 # #(No deberian existir IPP menor a 10 unidades)
4763 4763 #
4764 4764 # realIndex = numpy.where(spacing > 10 )[0]
4765 4765 #
4766 4766 # if len(realIndex) < 2:
4767 4767 # #Solo se encontro un pulso de transmision con ancho mayor a 1
4768 4768 # return None
4769 4769 #
4770 4770 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
4771 4771 # realPulseIndex = pulseIndex[realIndex]
4772 4772 #
4773 4773 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
4774 4774 #
4775 4775 # print "IPP = %d samples" %period
4776 4776 #
4777 4777 # self.__newNSamples = dataOut.nHeights #int(period)
4778 4778 # self.__startIndex = int(realPulseIndex[0])
4779 4779 #
4780 4780 # return 1
4781 4781 #
4782 4782 #
4783 4783 # def setup(self, nSamples, nChannels, buffer_size = 4):
4784 4784 #
4785 4785 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
4786 4786 # maxlen = buffer_size*nSamples)
4787 4787 #
4788 4788 # bufferList = []
4789 4789 #
4790 4790 # for i in range(nChannels):
4791 4791 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=complex) + numpy.NAN,
4792 4792 # maxlen = buffer_size*nSamples)
4793 4793 #
4794 4794 # bufferList.append(bufferByChannel)
4795 4795 #
4796 4796 # self.__nSamples = nSamples
4797 4797 # self.__nChannels = nChannels
4798 4798 # self.__bufferList = bufferList
4799 4799 #
4800 4800 # def run(self, dataOut, channel = 0):
4801 4801 #
4802 4802 # if not self.isConfig:
4803 4803 # nSamples = dataOut.nHeights
4804 4804 # nChannels = dataOut.nChannels
4805 4805 # self.setup(nSamples, nChannels)
4806 4806 # self.isConfig = True
4807 4807 #
4808 4808 # #Append new data to internal buffer
4809 4809 # for thisChannel in range(self.__nChannels):
4810 4810 # bufferByChannel = self.__bufferList[thisChannel]
4811 4811 # bufferByChannel.extend(dataOut.data[thisChannel])
4812 4812 #
4813 4813 # if self.__pulseFound:
4814 4814 # self.__startIndex -= self.__nSamples
4815 4815 #
4816 4816 # #Finding Tx Pulse
4817 4817 # if not self.__pulseFound:
4818 4818 # indexFound = self.__findTxPulse(dataOut, channel)
4819 4819 #
4820 4820 # if indexFound == None:
4821 4821 # dataOut.flagNoData = True
4822 4822 # return
4823 4823 #
4824 4824 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = complex)
4825 4825 # self.__pulseFound = True
4826 4826 # self.__startIndex = indexFound
4827 4827 #
4828 4828 # #If pulse was found ...
4829 4829 # for thisChannel in range(self.__nChannels):
4830 4830 # bufferByChannel = self.__bufferList[thisChannel]
4831 4831 # #print self.__startIndex
4832 4832 # x = numpy.array(bufferByChannel)
4833 4833 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
4834 4834 #
4835 4835 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
4836 4836 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
4837 4837 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
4838 4838 #
4839 4839 # dataOut.data = self.__arrayBuffer
4840 4840 #
4841 4841 # self.__startIndex += self.__newNSamples
4842 4842 #
4843 4843 # return
4844 4844
4845 4845
4846 4846
4847 4847
4848 4848
4849 4849
4850 4850
4851 4851 ##############################LONG PULSE##############################
4852 4852
4853 4853
4854 4854
4855 4855 class CrossProdHybrid(CrossProdDP):
4856 4856 """Operation to calculate cross products of the Hybrid Experiment.
4857 4857
4858 4858 Parameters:
4859 4859 -----------
4860 4860 NLAG : int
4861 4861 Number of lags for Long Pulse.
4862 4862 NRANGE : int
4863 4863 Number of samples (heights) for Long Pulse.
4864 4864 NCAL : int
4865 4865 .*
4866 4866 DPL : int
4867 4867 Number of lags for Double Pulse.
4868 4868 NDN : int
4869 4869 .*
4870 4870 NDT : int
4871 4871 Number of heights for Double Pulse.*
4872 4872 NDP : int
4873 4873 Number of heights for Double Pulse.*
4874 4874 NSCAN : int
4875 4875 Number of profiles when the transmitter is on.
4876 4876 lagind : intlist
4877 4877 .*
4878 4878 lagfirst : intlist
4879 4879 .*
4880 4880 NAVG : int
4881 4881 Number of blocks to be "averaged".
4882 4882 nkill : int
4883 4883 Number of blocks not to be considered when averaging.
4884 4884
4885 4885 Example
4886 4886 --------
4887 4887
4888 4888 op = proc_unit.addOperation(name='CrossProdHybrid', optype='other')
4889 4889 op.addParameter(name='NLAG', value='16', format='int')
4890 4890 op.addParameter(name='NRANGE', value='200', format='int')
4891 4891 op.addParameter(name='NCAL', value='0', format='int')
4892 4892 op.addParameter(name='DPL', value='11', format='int')
4893 4893 op.addParameter(name='NDN', value='0', format='int')
4894 4894 op.addParameter(name='NDT', value='67', format='int')
4895 4895 op.addParameter(name='NDP', value='67', format='int')
4896 4896 op.addParameter(name='NSCAN', value='128', format='int')
4897 4897 op.addParameter(name='lagind', value='(0,1,2,3,4,5,6,7,0,3,4,5,6,8,9,10)', format='intlist')
4898 4898 op.addParameter(name='lagfirst', value='(1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1)', format='intlist')
4899 4899 op.addParameter(name='NAVG', value='16', format='int')
4900 4900 op.addParameter(name='nkill', value='6', format='int')
4901 4901
4902 4902 """
4903 4903
4904 4904 def __init__(self, **kwargs):
4905 4905
4906 4906 Operation.__init__(self, **kwargs)
4907 4907 self.bcounter=0
4908 4908 self.aux=1
4909 4909 self.aux_cross_lp=1
4910 4910 self.lag_products_LP_median_estimates_aux=1
4911 4911
4912 4912 def get_products_cabxys_HP(self,dataOut):
4913 4913
4914 4914 if self.aux==1:
4915 4915 self.set_header_output(dataOut)
4916 4916 self.aux=0
4917 4917
4918 4918 self.cax=numpy.zeros((dataOut.NDP,dataOut.DPL,2))# hp:67x11x2 dp: 66x11x2
4919 4919 self.cay=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4920 4920 self.cbx=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4921 4921 self.cby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4922 4922 self.cax2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4923 4923 self.cay2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4924 4924 self.cbx2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4925 4925 self.cby2=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4926 4926 self.caxbx=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4927 4927 self.caxby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4928 4928 self.caybx=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4929 4929 self.cayby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4930 4930 self.caxay=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4931 4931 self.cbxby=numpy.zeros((dataOut.NDP,dataOut.DPL,2))
4932 4932 for i in range(2): # flipped and unflipped
4933 4933 for j in range(dataOut.NDP): # loop over true ranges # 67
4934 4934 for k in range(int(dataOut.NSCAN)): # 128
4935 4935
4936 4936 n=dataOut.lagind[k%dataOut.NLAG] # 128=16x8
4937 4937
4938 4938 ax=dataOut.data[0,k,dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT].real-dataOut.dc.real[0]
4939 4939 ay=dataOut.data[0,k,dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT].imag-dataOut.dc.imag[0]
4940 4940
4941 4941 if dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n<dataOut.read_samples:
4942 4942
4943 4943 bx=dataOut.data[1,k,dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n].real-dataOut.dc.real[1]
4944 4944 by=dataOut.data[1,k,dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n].imag-dataOut.dc.imag[1]
4945 4945
4946 4946 else:
4947 4947
4948 4948 if k+1<int(dataOut.NSCAN):
4949 4949 bx=dataOut.data[1,k+1,(dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n)%dataOut.NDP].real
4950 4950 by=dataOut.data[1,k+1,(dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n)%dataOut.NDP].imag
4951 4951
4952 4952 if k+1==int(dataOut.NSCAN):## ESTO ES UN PARCHE PUES NO SE TIENE EL SIGUIENTE BLOQUE
4953 4953 bx=dataOut.data[1,k,(dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n)%dataOut.NDP].real
4954 4954 by=dataOut.data[1,k,(dataOut.NRANGE+dataOut.NCAL+j+i*dataOut.NDT+2*n)%dataOut.NDP].imag
4955 4955
4956 4956 if(k<dataOut.NLAG and dataOut.lagfirst[k%dataOut.NLAG]==1):# if(k<16 && lagfirst[k%16]==1)
4957 4957 self.cax[j][n][i]=ax
4958 4958 self.cay[j][n][i]=ay
4959 4959 self.cbx[j][n][i]=bx
4960 4960 self.cby[j][n][i]=by
4961 4961 self.cax2[j][n][i]=ax*ax
4962 4962 self.cay2[j][n][i]=ay*ay
4963 4963 self.cbx2[j][n][i]=bx*bx
4964 4964 self.cby2[j][n][i]=by*by
4965 4965 self.caxbx[j][n][i]=ax*bx
4966 4966 self.caxby[j][n][i]=ax*by
4967 4967 self.caybx[j][n][i]=ay*bx
4968 4968 self.cayby[j][n][i]=ay*by
4969 4969 self.caxay[j][n][i]=ax*ay
4970 4970 self.cbxby[j][n][i]=bx*by
4971 4971 else:
4972 4972 self.cax[j][n][i]+=ax
4973 4973 self.cay[j][n][i]+=ay
4974 4974 self.cbx[j][n][i]+=bx
4975 4975 self.cby[j][n][i]+=by
4976 4976 self.cax2[j][n][i]+=ax*ax
4977 4977 self.cay2[j][n][i]+=ay*ay
4978 4978 self.cbx2[j][n][i]+=bx*bx
4979 4979 self.cby2[j][n][i]+=by*by
4980 4980 self.caxbx[j][n][i]+=ax*bx
4981 4981 self.caxby[j][n][i]+=ax*by
4982 4982 self.caybx[j][n][i]+=ay*bx
4983 4983 self.cayby[j][n][i]+=ay*by
4984 4984 self.caxay[j][n][i]+=ax*ay
4985 4985 self.cbxby[j][n][i]+=bx*by
4986 4986
4987 4987
4988 4988 #print(self.cax2[2,0,1])
4989 4989 #input()
4990 4990
4991 4991
4992 4992 def lag_products_LP(self,dataOut):
4993 4993
4994 4994
4995 4995 buffer=dataOut.data
4996 4996 if self.aux_cross_lp==1:
4997 4997
4998 4998 #self.dataOut.nptsfft2=150
4999 4999 self.cnorm=float((dataOut.nProfiles-dataOut.NSCAN)/dataOut.NSCAN)
5000 5000 self.lagp0=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5001 5001 self.lagp1=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5002 5002 self.lagp2=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5003 5003 self.lagp3=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5004 5004
5005 5005 #self.lagp4=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5006 5006 self.aux_cross_lp=0
5007 5007
5008 5008 #print(self.dataOut.data[0,0,0])
5009 5009
5010 5010 for i in range(dataOut.NR):
5011 5011 #print("inside i",i)
5012 5012 buffer_dc=dataOut.dc[i]
5013 5013 for j in range(dataOut.NRANGE):
5014 5014
5015 5015 range_for_n=numpy.min((dataOut.NRANGE-j,dataOut.NLAG))
5016 5016
5017 5017 buffer_aux=numpy.conj(buffer[i,:dataOut.nProfiles,j]-buffer_dc)
5018 5018 for n in range(range_for_n):
5019 5019
5020 5020 c=(buffer_aux)*(buffer[i,:dataOut.nProfiles,j+n]-buffer_dc)
5021 5021
5022 5022 if i==0:
5023 5023 self.lagp0[n][j][self.bcounter-1]=numpy.sum(c[:dataOut.NSCAN])
5024 5024 self.lagp3[n][j][self.bcounter-1]=numpy.sum(c[dataOut.NSCAN:]/self.cnorm)
5025 5025 elif i==1:
5026 5026 self.lagp1[n][j][self.bcounter-1]=numpy.sum(c[:dataOut.NSCAN])
5027 5027 elif i==2:
5028 5028 self.lagp2[n][j][self.bcounter-1]=numpy.sum(c[:dataOut.NSCAN])
5029 5029
5030 5030
5031 5031 self.lagp0[:,:,self.bcounter-1]=numpy.conj(self.lagp0[:,:,self.bcounter-1])
5032 5032 self.lagp1[:,:,self.bcounter-1]=numpy.conj(self.lagp1[:,:,self.bcounter-1])
5033 5033 self.lagp2[:,:,self.bcounter-1]=numpy.conj(self.lagp2[:,:,self.bcounter-1])
5034 5034 self.lagp3[:,:,self.bcounter-1]=numpy.conj(self.lagp3[:,:,self.bcounter-1])
5035 5035
5036 5036
5037 5037 def LP_median_estimates(self,dataOut):
5038 5038
5039 5039 if self.bcounter==dataOut.NAVG:
5040 5040
5041 5041 if self.lag_products_LP_median_estimates_aux==1:
5042 5042 self.output=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NR),'complex64')
5043 5043 self.lag_products_LP_median_estimates_aux=0
5044 5044
5045 5045
5046 5046 for i in range(dataOut.NLAG):
5047 5047 for j in range(dataOut.NRANGE):
5048 5048 for l in range(4): #four outputs
5049 5049
5050 5050 for k in range(dataOut.NAVG):
5051 5051
5052 5052
5053 5053 if k==0:
5054 5054 self.output[i,j,l]=0.0+0.j
5055 5055
5056 5056 if l==0:
5057 5057 self.lagp0[i,j,:]=sorted(self.lagp0[i,j,:], key=lambda x: x.real) #sorted(self.lagp0[i,j,:].real)
5058 5058
5059 5059 if l==1:
5060 5060 self.lagp1[i,j,:]=sorted(self.lagp1[i,j,:], key=lambda x: x.real) #sorted(self.lagp1[i,j,:].real)
5061 5061
5062 5062 if l==2:
5063 5063 self.lagp2[i,j,:]=sorted(self.lagp2[i,j,:], key=lambda x: x.real) #sorted(self.lagp2[i,j,:].real)
5064 5064
5065 5065 if l==3:
5066 5066 self.lagp3[i,j,:]=sorted(self.lagp3[i,j,:], key=lambda x: x.real) #sorted(self.lagp3[i,j,:].real)
5067 5067
5068 5068
5069 5069
5070 5070 if k>=dataOut.nkill/2 and k<dataOut.NAVG-dataOut.nkill/2:
5071 5071 if l==0:
5072 5072
5073 5073 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp0[i,j,k])
5074 5074 if l==1:
5075 5075 #print("lagp1: ",self.lagp1[0,0,:])
5076 5076 #input()
5077 5077 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp1[i,j,k])
5078 5078 #print("self.lagp1[i,j,k]: ",self.lagp1[i,j,k])
5079 5079 #input()
5080 5080 if l==2:
5081 5081 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp2[i,j,k])
5082 5082 if l==3:
5083 5083
5084 5084 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp3[i,j,k])
5085 5085
5086 5086
5087 5087 dataOut.output_LP=self.output
5088 5088 dataOut.data_for_RTI_LP=numpy.zeros((4,dataOut.NRANGE))
5089 5089 dataOut.data_for_RTI_LP[0],dataOut.data_for_RTI_LP[1],dataOut.data_for_RTI_LP[2],dataOut.data_for_RTI_LP[3]=self.RTI_LP(dataOut.output_LP,dataOut.NRANGE)
5090 5090
5091 5091
5092 5092 def get_dc(self,dataOut):
5093 5093
5094 5094 if self.bcounter==0:
5095 5095 dataOut.dc=numpy.zeros(dataOut.NR,dtype='complex64')
5096 5096
5097 5097 #print(numpy.shape(dataOut.data))
5098 5098 #input()
5099 5099
5100 5100 dataOut.dc+=numpy.sum(dataOut.data[:,:,2*dataOut.NLAG:dataOut.NRANGE],axis=(1,2))
5101 5101
5102 5102 dataOut.dc=dataOut.dc/float(dataOut.nProfiles*(dataOut.NRANGE-2*dataOut.NLAG))
5103 5103
5104 5104
5105 5105 #print("dc:",dataOut.dc[0])
5106 5106
5107 5107 def get_dc_new(self,dataOut):
5108 5108
5109 5109 if self.bcounter==0:
5110 5110 dataOut.dc_dp=numpy.zeros(dataOut.NR,dtype='complex64')
5111 5111 dataOut.dc_lp=numpy.zeros(dataOut.NR,dtype='complex64')
5112 5112
5113 5113 #print(numpy.shape(dataOut.data))
5114 5114 #input()
5115 5115
5116 5116 dataOut.dc+=numpy.sum(dataOut.data[:,:,2*dataOut.NLAG:dataOut.NRANGE],axis=(1,2))
5117 5117
5118 5118 dataOut.dc=dataOut.dc/float(dataOut.nProfiles*(dataOut.NRANGE-2*dataOut.NLAG))
5119 5119
5120 5120
5121 5121 #print("dc:",dataOut.dc[0])
5122 5122
5123 5123
5124 5124 def noise_estimation4x_HP(self,dataOut):
5125 5125 if self.bcounter==dataOut.NAVG:
5126 5126 dataOut.noise_final=numpy.zeros(dataOut.NR,'float32')
5127 5127 #snoise=numpy.zeros((NR,NAVG),'float32')
5128 5128 #nvector1=numpy.zeros((NR,NAVG,MAXNRANGENDT),'float32')
5129 5129 sorted_data=numpy.zeros((dataOut.MAXNRANGENDT,dataOut.NR,dataOut.NAVG),'float32')
5130 5130 for i in range(dataOut.NR):
5131 5131 dataOut.noise_final[i]=0.0
5132 5132 for j in range(dataOut.MAXNRANGENDT):
5133 5133 sorted_data[j,i,:]=numpy.copy(sorted(dataOut.noisevector[j,i,:]))
5134 5134 #print(sorted(noisevector[j,i,:]))
5135 5135 #input()
5136 5136 l=dataOut.MAXNRANGENDT-2
5137 5137 for k in range(dataOut.NAVG):
5138 5138 if k>=dataOut.nkill/2 and k<dataOut.NAVG-dataOut.nkill/2:
5139 5139 #print(k)
5140 5140 #print(sorted_data[min(j,l),i,k])
5141 5141 dataOut.noise_final[i]+=sorted_data[min(j,l),i,k]*float(dataOut.NAVG)/float(dataOut.NAVG-dataOut.nkill)
5142 5142 #print(dataOut.noise_final[i])
5143 5143 #input()
5144 5144 #print(dataOut.noise_final)
5145 5145 #input()
5146 5146
5147 5147 def noisevectorizer(self,NSCAN,nProfiles,NR,MAXNRANGENDT,noisevector,data,dc):
5148 5148
5149 5149 #rnormalizer= 1./(float(nProfiles - NSCAN))
5150 5150 rnormalizer= float(NSCAN)/((float(nProfiles - NSCAN))*float(MAXNRANGENDT))
5151 5151 for i in range(NR):
5152 5152 for j in range(MAXNRANGENDT):
5153 5153 for k in range(NSCAN,nProfiles):
5154 5154 #TODO:integrate just 2nd quartile gates
5155 5155 if k==NSCAN:
5156 5156 noisevector[j][i][self.bcounter]=(abs(data[i][k][j]-dc[i])**2)*rnormalizer
5157 5157 ##noisevector[j][i][iavg]=(abs(cdata[k][j][i])**2)*rnormalizer
5158 5158 else:
5159 5159 noisevector[j][i][self.bcounter]+=(abs(data[i][k][j]-dc[i])**2)*rnormalizer
5160 5160
5161 5161
5162 5162 def RTI_LP(self,output,NRANGE):
5163 5163 x00=numpy.zeros(NRANGE,dtype='float32')
5164 5164 x01=numpy.zeros(NRANGE,dtype='float32')
5165 5165 x02=numpy.zeros(NRANGE,dtype='float32')
5166 5166 x03=numpy.zeros(NRANGE,dtype='float32')
5167 5167
5168 5168 for i in range(2): #first couple of lags
5169 5169 for j in range(NRANGE): #
5170 5170 #fx=numpy.sqrt((kaxbx[i,j,k]+kayby[i,j,k])**2+(kaybx[i,j,k]-kaxby[i,j,k])**2)
5171 5171 x00[j]+=numpy.abs(output[i,j,0]) #Ch0
5172 5172 x01[j]+=numpy.abs(output[i,j,1]) #Ch1
5173 5173 x02[j]+=numpy.abs(output[i,j,2]) #Ch2
5174 5174 x03[j]+=numpy.abs(output[i,j,3]) #Ch3
5175 5175 #x02[i]=x02[i]+fx
5176 5176
5177 5177 x00[j]=10.0*numpy.log10(x00[j]/4.)
5178 5178 x01[j]=10.0*numpy.log10(x01[j]/4.)
5179 5179 x02[j]=10.0*numpy.log10(x02[j]/4.)
5180 5180 x03[j]=10.0*numpy.log10(x03[j]/4.)
5181 5181 #x02[i]=10.0*numpy.log10(x02[i])
5182 5182 return x00,x01,x02,x03
5183 5183
5184 5184 def run(self, dataOut, NLAG=None, NRANGE=None, NCAL=None, DPL=None,
5185 5185 NDN=None, NDT=None, NDP=None, NSCAN=None,
5186 5186 lagind=None, lagfirst=None,
5187 5187 NAVG=None, nkill=None):
5188 5188
5189 5189 dataOut.NLAG=NLAG
5190 5190 dataOut.NR=len(dataOut.channelList)
5191 5191 dataOut.NRANGE=NRANGE
5192 5192 dataOut.NCAL=NCAL
5193 5193 dataOut.DPL=DPL
5194 5194 dataOut.NDN=NDN
5195 5195 dataOut.NDT=NDT
5196 5196 dataOut.NDP=NDP
5197 5197 dataOut.NSCAN=NSCAN
5198 5198 dataOut.DH=dataOut.heightList[1]-dataOut.heightList[0]
5199 5199 dataOut.H0=int(dataOut.heightList[0])
5200 5200 dataOut.lagind=lagind
5201 5201 dataOut.lagfirst=lagfirst
5202 5202 dataOut.NAVG=NAVG
5203 5203 dataOut.nkill=nkill
5204 5204
5205 5205 dataOut.flagNoData = True
5206 5206
5207 5207 self.get_dc(dataOut)
5208 5208 self.get_products_cabxys_HP(dataOut)
5209 5209 self.cabxys_navg(dataOut)
5210 5210 self.lag_products_LP(dataOut)
5211 5211 self.LP_median_estimates(dataOut)
5212 5212 self.noise_estimation4x_HP(dataOut)
5213 5213 self.kabxys(dataOut)
5214 5214
5215 5215 return dataOut
5216 5216
5217 5217
5218 5218 class CrossProdLP(CrossProdDP):
5219 5219 """Operation to calculate cross products of the Hybrid Experiment.
5220 5220
5221 5221 Parameters:
5222 5222 -----------
5223 5223 NLAG : int
5224 5224 Number of lags for Long Pulse.
5225 5225 NRANGE : int
5226 5226 Number of samples (heights) for Long Pulse.
5227 5227 NCAL : int
5228 5228 .*
5229 5229 DPL : int
5230 5230 Number of lags for Double Pulse.
5231 5231 NDN : int
5232 5232 .*
5233 5233 NDT : int
5234 5234 Number of heights for Double Pulse.*
5235 5235 NDP : int
5236 5236 Number of heights for Double Pulse.*
5237 5237 NSCAN : int
5238 5238 Number of profiles when the transmitter is on.
5239 5239 lagind : intlist
5240 5240 .*
5241 5241 lagfirst : intlist
5242 5242 .*
5243 5243 NAVG : int
5244 5244 Number of blocks to be "averaged".
5245 5245 nkill : int
5246 5246 Number of blocks not to be considered when averaging.
5247 5247
5248 5248 Example
5249 5249 --------
5250 5250
5251 5251 op = proc_unit.addOperation(name='CrossProdHybrid', optype='other')
5252 5252 op.addParameter(name='NLAG', value='16', format='int')
5253 5253 op.addParameter(name='NRANGE', value='200', format='int')
5254 5254 op.addParameter(name='NCAL', value='0', format='int')
5255 5255 op.addParameter(name='DPL', value='11', format='int')
5256 5256 op.addParameter(name='NDN', value='0', format='int')
5257 5257 op.addParameter(name='NDT', value='67', format='int')
5258 5258 op.addParameter(name='NDP', value='67', format='int')
5259 5259 op.addParameter(name='NSCAN', value='128', format='int')
5260 5260 op.addParameter(name='lagind', value='(0,1,2,3,4,5,6,7,0,3,4,5,6,8,9,10)', format='intlist')
5261 5261 op.addParameter(name='lagfirst', value='(1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1)', format='intlist')
5262 5262 op.addParameter(name='NAVG', value='16', format='int')
5263 5263 op.addParameter(name='nkill', value='6', format='int')
5264 5264
5265 5265 """
5266 5266
5267 5267 def __init__(self, **kwargs):
5268 5268
5269 5269 Operation.__init__(self, **kwargs)
5270 5270 self.bcounter=0
5271 5271 self.aux=1
5272 5272 self.aux_cross_lp=1
5273 5273 self.lag_products_LP_median_estimates_aux=1
5274 5274
5275 5275
5276 5276
5277 5277 #print(self.cax2[2,0,1])
5278 5278 #input()
5279 5279
5280 5280
5281 5281 def lag_products_LP(self,dataOut):
5282 5282
5283 5283
5284 5284 buffer=dataOut.data
5285 5285 if self.aux_cross_lp==1:
5286 5286
5287 5287 #self.dataOut.nptsfft2=150
5288 5288 self.cnorm=float((dataOut.nProfiles-dataOut.NSCAN)/dataOut.NSCAN)
5289 5289 self.lagp0=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5290 5290 self.lagp1=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5291 5291 self.lagp2=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5292 5292 self.lagp3=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5293 5293 self.lagp4=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5294 5294 self.lagp5=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5295 5295
5296 5296 #self.lagp4=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NAVG),'complex64')
5297 5297 self.aux_cross_lp=0
5298 5298
5299 5299 dataOut.noisevector=numpy.zeros((dataOut.MAXNRANGENDT,dataOut.NR,dataOut.NAVG),'float32')
5300 5300
5301 5301 #print(self.dataOut.data[0,0,0])
5302 5302 self.noisevectorizer(dataOut.NSCAN,dataOut.nProfiles,dataOut.NR,dataOut.MAXNRANGENDT,dataOut.noisevector,dataOut.data,dataOut.dc) #30/03/2020
5303 5303
5304 5304
5305 5305 for i in range(dataOut.NR):
5306 5306 #print("inside i",i)
5307 5307 buffer_dc=dataOut.dc[i]
5308 5308 for j in range(dataOut.NRANGE):
5309 5309
5310 5310 range_for_n=numpy.min((dataOut.NRANGE-j,dataOut.NLAG))
5311 5311
5312 5312 buffer_aux=numpy.conj(buffer[i,:dataOut.nProfiles,j]-buffer_dc)
5313 5313 for n in range(range_for_n):
5314 5314
5315 5315 c=(buffer_aux)*(buffer[i,:dataOut.nProfiles,j+n]-buffer_dc)
5316 5316
5317 5317 if i==0:
5318 5318 self.lagp0[n][j][self.bcounter]=numpy.sum(c[:dataOut.NSCAN])
5319 5319 #self.lagp3[n][j][self.bcounter-1]=numpy.sum(c[dataOut.NSCAN:]/self.cnorm)
5320 5320 elif i==1:
5321 5321 self.lagp1[n][j][self.bcounter]=numpy.sum(c[:dataOut.NSCAN])
5322 5322 elif i==2:
5323 5323 self.lagp2[n][j][self.bcounter]=numpy.sum(c[:dataOut.NSCAN])
5324 5324 elif i==3:
5325 5325 self.lagp3[n][j][self.bcounter]=numpy.sum(c[:dataOut.NSCAN])
5326 5326 elif i==4:
5327 5327 self.lagp4[n][j][self.bcounter]=numpy.sum(c[:dataOut.NSCAN])
5328 5328 elif i==5:
5329 5329 self.lagp5[n][j][self.bcounter]=numpy.sum(c[:dataOut.NSCAN])
5330 5330
5331 5331
5332 5332 self.lagp0[:,:,self.bcounter]=numpy.conj(self.lagp0[:,:,self.bcounter])
5333 5333 self.lagp1[:,:,self.bcounter]=numpy.conj(self.lagp1[:,:,self.bcounter])
5334 5334 self.lagp2[:,:,self.bcounter]=numpy.conj(self.lagp2[:,:,self.bcounter])
5335 5335 self.lagp3[:,:,self.bcounter]=numpy.conj(self.lagp3[:,:,self.bcounter])
5336 5336
5337 5337 self.bcounter += 1
5338 5338
5339 5339
5340 5340 def LP_median_estimates(self,dataOut):
5341 5341
5342 5342 if self.bcounter==dataOut.NAVG:
5343 5343 dataOut.flagNoData = False
5344 5344
5345 5345 if self.lag_products_LP_median_estimates_aux==1:
5346 5346 self.output=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NR),'complex64')
5347 5347 self.lag_products_LP_median_estimates_aux=0
5348 5348
5349 5349
5350 5350 for i in range(dataOut.NLAG):
5351 5351 for j in range(dataOut.NRANGE):
5352 5352 for l in range(4): #four outputs
5353 5353
5354 5354 for k in range(dataOut.NAVG):
5355 5355
5356 5356
5357 5357 if k==0:
5358 5358 self.output[i,j,l]=0.0+0.j
5359 5359
5360 5360 if l==0:
5361 5361 self.lagp0[i,j,:]=sorted(self.lagp0[i,j,:], key=lambda x: x.real) #sorted(self.lagp0[i,j,:].real)
5362 5362
5363 5363 if l==1:
5364 5364 self.lagp1[i,j,:]=sorted(self.lagp1[i,j,:], key=lambda x: x.real) #sorted(self.lagp1[i,j,:].real)
5365 5365
5366 5366 if l==2:
5367 5367 self.lagp2[i,j,:]=sorted(self.lagp2[i,j,:], key=lambda x: x.real) #sorted(self.lagp2[i,j,:].real)
5368 5368
5369 5369 if l==3:
5370 5370 self.lagp3[i,j,:]=sorted(self.lagp3[i,j,:], key=lambda x: x.real) #sorted(self.lagp3[i,j,:].real)
5371 5371
5372 5372
5373 5373
5374 5374 if k>=dataOut.nkill/2 and k<dataOut.NAVG-dataOut.nkill/2:
5375 5375 if l==0:
5376 5376
5377 5377 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp0[i,j,k])
5378 5378 if l==1:
5379 5379 #print("lagp1: ",self.lagp1[0,0,:])
5380 5380 #input()
5381 5381 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp1[i,j,k])
5382 5382 #print("self.lagp1[i,j,k]: ",self.lagp1[i,j,k])
5383 5383 #input()
5384 5384 if l==2:
5385 5385 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp2[i,j,k])
5386 5386 if l==3:
5387 5387
5388 5388 self.output[i,j,l]=self.output[i,j,l]+((float(dataOut.NAVG)/(float)(dataOut.NAVG-dataOut.nkill))*self.lagp3[i,j,k])
5389 5389
5390 5390
5391 5391 dataOut.output_LP=self.output
5392 5392 dataOut.data_for_RTI_LP=numpy.zeros((4,dataOut.NRANGE))
5393 5393 dataOut.data_for_RTI_LP[0],dataOut.data_for_RTI_LP[1],dataOut.data_for_RTI_LP[2],dataOut.data_for_RTI_LP[3]=self.RTI_LP(dataOut.output_LP,dataOut.NRANGE)
5394 5394
5395 5395 self.bcounter = 0
5396 5396
5397 5397 def get_dc(self,dataOut):
5398 5398
5399 5399 if self.bcounter==0:
5400 5400 dataOut.dc=numpy.zeros(dataOut.NR,dtype='complex64')
5401 5401
5402 5402 #print(numpy.shape(dataOut.data))
5403 5403 #input()
5404 5404
5405 5405 dataOut.dc+=numpy.sum(dataOut.data[:,:,2*dataOut.NLAG:dataOut.NRANGE],axis=(1,2))
5406 5406
5407 5407 dataOut.dc=dataOut.dc/float(dataOut.nProfiles*(dataOut.NRANGE-2*dataOut.NLAG))
5408 5408
5409 5409
5410 5410 #print("dc:",dataOut.dc[0])
5411 5411
5412 5412
5413 5413
5414 5414
5415 5415 def noise_estimation4x_HP(self,dataOut):
5416 5416 if self.bcounter==dataOut.NAVG:
5417 5417 dataOut.noise_final=numpy.zeros(dataOut.NR,'float32')
5418 5418 #snoise=numpy.zeros((NR,NAVG),'float32')
5419 5419 #nvector1=numpy.zeros((NR,NAVG,MAXNRANGENDT),'float32')
5420 5420 sorted_data=numpy.zeros((dataOut.MAXNRANGENDT,dataOut.NR,dataOut.NAVG),'float32')
5421 5421 for i in range(dataOut.NR):
5422 5422 dataOut.noise_final[i]=0.0
5423 5423 for j in range(dataOut.MAXNRANGENDT):
5424 5424 sorted_data[j,i,:]=numpy.copy(sorted(dataOut.noisevector[j,i,:]))
5425 5425 #print(sorted(noisevector[j,i,:]))
5426 5426 #input()
5427 5427 l=dataOut.MAXNRANGENDT-2
5428 5428 for k in range(dataOut.NAVG):
5429 5429 if k>=dataOut.nkill/2 and k<dataOut.NAVG-dataOut.nkill/2:
5430 5430 #print(k)
5431 5431 #print(sorted_data[min(j,l),i,k])
5432 5432 dataOut.noise_final[i]+=sorted_data[min(j,l),i,k]*float(dataOut.NAVG)/float(dataOut.NAVG-dataOut.nkill)
5433 5433 #print(dataOut.noise_final[i])
5434 5434 #input()
5435 5435 #print(dataOut.noise_final)
5436 5436 #input()
5437 5437
5438 5438 def noisevectorizer(self,NSCAN,nProfiles,NR,MAXNRANGENDT,noisevector,data,dc):
5439 5439
5440 5440 #rnormalizer= 1./(float(nProfiles - NSCAN))
5441 5441 #rnormalizer= float(NSCAN)/((float(nProfiles - NSCAN))*float(MAXNRANGENDT))
5442 5442 rnormalizer= float(NSCAN)/((float(1))*float(MAXNRANGENDT))
5443 5443 for i in range(NR):
5444 5444 for j in range(MAXNRANGENDT):
5445 5445 for k in range(NSCAN,nProfiles):
5446 5446 #TODO:integrate just 2nd quartile gates
5447 5447 if k==NSCAN:
5448 5448 noisevector[j][i][self.bcounter]=(abs(data[i][k][j]-dc[i])**2)*rnormalizer
5449 5449 ##noisevector[j][i][iavg]=(abs(cdata[k][j][i])**2)*rnormalizer
5450 5450 else:
5451 5451 noisevector[j][i][self.bcounter]+=(abs(data[i][k][j]-dc[i])**2)*rnormalizer
5452 5452
5453 5453
5454 5454 def RTI_LP(self,output,NRANGE):
5455 5455 x00=numpy.zeros(NRANGE,dtype='float32')
5456 5456 x01=numpy.zeros(NRANGE,dtype='float32')
5457 5457 x02=numpy.zeros(NRANGE,dtype='float32')
5458 5458 x03=numpy.zeros(NRANGE,dtype='float32')
5459 5459
5460 5460 for i in range(1): #first couple of lags
5461 5461 for j in range(NRANGE): #
5462 5462 #fx=numpy.sqrt((kaxbx[i,j,k]+kayby[i,j,k])**2+(kaybx[i,j,k]-kaxby[i,j,k])**2)
5463 5463 x00[j]+=numpy.abs(output[i,j,0]) #Ch0
5464 5464 x01[j]+=numpy.abs(output[i,j,1]) #Ch1
5465 5465 x02[j]+=numpy.abs(output[i,j,2]) #Ch2
5466 5466 x03[j]+=numpy.abs(output[i,j,3]) #Ch3
5467 5467 #x02[i]=x02[i]+fx
5468 5468
5469 5469 x00[j]=10.0*numpy.log10(x00[j]/4.)
5470 5470 x01[j]=10.0*numpy.log10(x01[j]/4.)
5471 5471 x02[j]=10.0*numpy.log10(x02[j]/4.)
5472 5472 x03[j]=10.0*numpy.log10(x03[j]/4.)
5473 5473 #x02[i]=10.0*numpy.log10(x02[i])
5474 5474 return x00,x01,x02,x03
5475 5475
5476 5476 def run(self, dataOut, NLAG=None, NRANGE=None, NCAL=None, DPL=None,
5477 5477 NDN=None, NDT=None, NDP=None, NSCAN=None,
5478 5478 lagind=None, lagfirst=None,
5479 5479 NAVG=None, nkill=None):
5480 5480
5481 5481 dataOut.NLAG=NLAG
5482 5482 dataOut.NR=len(dataOut.channelList)
5483 5483 #dataOut.NRANGE=NRANGE
5484 5484 dataOut.NRANGE=dataOut.nHeights
5485 5485 dataOut.NCAL=NCAL
5486 5486 dataOut.DPL=DPL
5487 5487 dataOut.NDN=NDN
5488 5488 dataOut.NDT=NDT
5489 5489 dataOut.NDP=NDP
5490 5490 dataOut.NSCAN=NSCAN
5491 5491 dataOut.DH=dataOut.heightList[1]-dataOut.heightList[0]
5492 5492 dataOut.H0=int(dataOut.heightList[0])
5493 5493 dataOut.lagind=lagind
5494 5494 dataOut.lagfirst=lagfirst
5495 5495 dataOut.NAVG=NAVG
5496 5496 dataOut.nkill=nkill
5497 5497
5498 5498 dataOut.MAXNRANGENDT = dataOut.NRANGE
5499 5499
5500 5500 dataOut.flagNoData = True
5501 5501
5502 5502 print(self.bcounter)
5503 5503
5504 5504 self.get_dc(dataOut)
5505 5505 self.lag_products_LP(dataOut)
5506 5506 self.noise_estimation4x_HP(dataOut)
5507 5507 self.LP_median_estimates(dataOut)
5508 5508
5509 5509 print("******************DONE******************")
5510 5510
5511 5511
5512 5512
5513 5513 return dataOut
5514 5514
5515 5515
5516 5516 class RemoveDebris(Operation):
5517 5517 """Operation to remove blocks where an outlier is found for Double (Long) Pulse.
5518 5518
5519 5519 Parameters:
5520 5520 -----------
5521 5521 None
5522 5522
5523 5523 Example
5524 5524 --------
5525 5525
5526 5526 op = proc_unit.addOperation(name='RemoveDebris', optype='other')
5527 5527
5528 5528 """
5529 5529
5530 5530 def __init__(self, **kwargs):
5531 5531
5532 5532 Operation.__init__(self, **kwargs)
5533 5533
5534 5534 def run(self,dataOut):
5535 5535 debris=numpy.zeros(dataOut.NRANGE,'float32')
5536 5536
5537 5537 for j in range(0,3):
5538 5538 for i in range(dataOut.NRANGE):
5539 5539 if j==0:
5540 5540 debris[i]=10*numpy.log10(numpy.abs(dataOut.output_LP[j,i,0]))
5541 5541 else:
5542 5542 debris[i]+=10*numpy.log10(numpy.abs(dataOut.output_LP[j,i,0]))
5543 5543
5544 5544 thresh=8.0+4+4+4
5545 5545 for i in range(47,100):
5546 5546 if ((debris[i-2]+debris[i-1]+debris[i]+debris[i+1])>
5547 5547 ((debris[i-12]+debris[i-11]+debris[i-10]+debris[i-9]+
5548 5548 debris[i+12]+debris[i+11]+debris[i+10]+debris[i+9])/2.0+
5549 5549 thresh)):
5550 5550
5551 5551 dataOut.flagNoData=True
5552 5552 print("LP Debris detected at",i*15,"km")
5553 5553
5554 5554 debris=numpy.zeros(dataOut.NDP,dtype='float32')
5555 5555 Range=numpy.arange(0,3000,15)
5556 5556 for k in range(2): #flip
5557 5557 for i in range(dataOut.NDP): #
5558 5558 debris[i]+=numpy.sqrt((dataOut.kaxbx[i,0,k]+dataOut.kayby[i,0,k])**2+(dataOut.kaybx[i,0,k]-dataOut.kaxby[i,0,k])**2)
5559 5559
5560 5560 if gmtime(dataOut.utctime).tm_hour > 11:
5561 5561 for i in range(2,dataOut.NDP-2):
5562 5562 if (debris[i]>3.0*debris[i-2] and
5563 5563 debris[i]>3.0*debris[i+2] and
5564 5564 Range[i]>200.0 and Range[i]<=540.0):
5565 5565 dataOut.flagNoData=True
5566 5566 print("DP Debris detected at",i*15,"km")
5567 5567
5568 5568 return dataOut
5569 5569
5570 5570
5571 5571 class IntegrationHP(IntegrationDP):
5572 5572 """Operation to integrate Double Pulse and Long Pulse data.
5573 5573
5574 5574 Parameters:
5575 5575 -----------
5576 5576 nint : int
5577 5577 Number of integrations.
5578 5578
5579 5579 Example
5580 5580 --------
5581 5581
5582 5582 op = proc_unit.addOperation(name='IntegrationHP', optype='other')
5583 5583 op.addParameter(name='nint', value='30', format='int')
5584 5584
5585 5585 """
5586 5586
5587 5587 def __init__(self, **kwargs):
5588 5588
5589 5589 Operation.__init__(self, **kwargs)
5590 5590
5591 5591 self.counter = 0
5592 5592 self.aux = 0
5593 5593
5594 5594 def integration_noise(self,dataOut):
5595 5595
5596 5596 if self.counter == 0:
5597 5597 dataOut.tnoise=numpy.zeros((dataOut.NR),dtype='float32')
5598 5598
5599 5599 dataOut.tnoise+=dataOut.noise_final
5600 5600
5601 5601 def integration_for_long_pulse(self,dataOut):
5602 5602
5603 5603 if self.counter == 0:
5604 5604 dataOut.output_LP_integrated=numpy.zeros((dataOut.NLAG,dataOut.NRANGE,dataOut.NR),order='F',dtype='complex64')
5605 5605
5606 5606 dataOut.output_LP_integrated+=dataOut.output_LP
5607 5607
5608 5608 def run(self,dataOut,nint=None):
5609 5609
5610 5610 dataOut.flagNoData=True
5611 5611
5612 5612 dataOut.nint=nint
5613 5613 dataOut.paramInterval=0#int(dataOut.nint*dataOut.header[7][0]*2 )
5614 5614 dataOut.lat=-11.95
5615 5615 dataOut.lon=-76.87
5616 5616
5617 5617 self.integration_for_long_pulse(dataOut)
5618 5618
5619 5619 self.integration_noise(dataOut)
5620 5620
5621 5621 if self.counter==dataOut.nint-1:
5622 5622 dataOut.nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint*10
5623 5623 dataOut.tnoise[0]*=0.995
5624 5624 dataOut.tnoise[1]*=0.995
5625 5625 dataOut.pan=dataOut.tnoise[0]/float(dataOut.NSCAN*dataOut.nint*dataOut.NAVG)
5626 5626 dataOut.pbn=dataOut.tnoise[1]/float(dataOut.NSCAN*dataOut.nint*dataOut.NAVG)
5627 5627
5628 5628 self.integration_for_double_pulse(dataOut)
5629 5629
5630 5630
5631 5631
5632 5632 return dataOut
5633 5633
5634 5634 class SumFlipsHP(SumFlips):
5635 5635 """Operation to sum the flip and unflip part of certain cross products of the Double Pulse.
5636 5636
5637 5637 Parameters:
5638 5638 -----------
5639 5639 None
5640 5640
5641 5641 Example
5642 5642 --------
5643 5643
5644 5644 op = proc_unit.addOperation(name='SumFlipsHP', optype='other')
5645 5645
5646 5646 """
5647 5647
5648 5648 def __init__(self, **kwargs):
5649 5649
5650 5650 Operation.__init__(self, **kwargs)
5651 5651
5652 5652 def rint2HP(self,dataOut):
5653 5653
5654 5654 dataOut.rnint2=numpy.zeros(dataOut.DPL,'float32')
5655 5655 #print(dataOut.nint,dataOut.NAVG)
5656 5656 for l in range(dataOut.DPL):
5657 5657 if(l==0 or (l>=3 and l <=6)):
5658 5658 dataOut.rnint2[l]=0.5/float(dataOut.nint*dataOut.NAVG*16.0)
5659 5659 else:
5660 5660 dataOut.rnint2[l]=0.5/float(dataOut.nint*dataOut.NAVG*8.0)
5661 5661
5662 5662 def run(self,dataOut):
5663 5663
5664 5664 self.rint2HP(dataOut)
5665 5665 self.SumLags(dataOut)
5666 5666
5667 5667 hei = 2
5668 5668 lag = 0
5669 5669 '''
5670 5670 for hei in range(67):
5671 5671 print("hei",hei)
5672 5672 print(dataOut.kabxys_integrated[8][hei,:,0]+dataOut.kabxys_integrated[11][hei,:,0])
5673 5673 print(dataOut.kabxys_integrated[10][hei,:,0]-dataOut.kabxys_integrated[9][hei,:,0])
5674 5674 exit(1)
5675 5675 '''
5676 5676 '''
5677 5677 print("b",(dataOut.kabxys_integrated[4][hei,lag,0]+dataOut.kabxys_integrated[5][hei,lag,0]))
5678 5678 print((dataOut.kabxys_integrated[6][hei,lag,0]+dataOut.kabxys_integrated[7][hei,lag,0]))
5679 5679 print("c",(dataOut.kabxys_integrated[8][hei,lag,0]+dataOut.kabxys_integrated[11][hei,lag,0]))
5680 5680 print((dataOut.kabxys_integrated[10][hei,lag,0]-dataOut.kabxys_integrated[9][hei,lag,0]))
5681 5681 exit(1)
5682 5682 '''
5683 5683 #print(dataOut.rnint2)
5684 5684 #print(numpy.sum(dataOut.kabxys_integrated[4][:,1,0]+dataOut.kabxys_integrated[5][:,1,0]))
5685 5685 #print(dataOut.nis)
5686 5686 #exit(1)
5687 5687 return dataOut
5688 5688
5689 5689
5690 5690 class LongPulseAnalysis(Operation):
5691 5691 """Operation to estimate ACFs, temperatures, total electron density and Hydrogen/Helium fractions from the Long Pulse data.
5692 5692
5693 5693 Parameters:
5694 5694 -----------
5695 5695 NACF : int
5696 5696 .*
5697 5697
5698 5698 Example
5699 5699 --------
5700 5700
5701 5701 op = proc_unit.addOperation(name='LongPulseAnalysis', optype='other')
5702 5702 op.addParameter(name='NACF', value='16', format='int')
5703 5703
5704 5704 """
5705 5705
5706 5706 def __init__(self, **kwargs):
5707 5707
5708 5708 Operation.__init__(self, **kwargs)
5709 5709 self.aux=1
5710 5710
5711 5711 def run(self,dataOut,NACF):
5712 5712
5713 5713 dataOut.NACF=NACF
5714 5714 dataOut.heightList=dataOut.DH*(numpy.arange(dataOut.NACF))
5715 5715 anoise0=dataOut.tnoise[0]
5716 5716 anoise1=anoise0*0.0 #seems to be noise in 1st lag 0.015 before '14
5717 5717 #print(anoise0)
5718 5718 #exit(1)
5719 5719 if self.aux:
5720 5720 #dataOut.cut=31#26#height=31*15=465
5721 5721 self.cal=numpy.zeros((dataOut.NLAG),'float32')
5722 5722 self.drift=numpy.zeros((200),'float32')
5723 5723 self.rdrift=numpy.zeros((200),'float32')
5724 5724 self.ddrift=numpy.zeros((200),'float32')
5725 5725 self.sigma=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
5726 5726 self.powera=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
5727 5727 self.powerb=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
5728 5728 self.perror=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
5729 5729 dataOut.ene=numpy.zeros((dataOut.NRANGE),'float32')
5730 5730 self.dpulse=numpy.zeros((dataOut.NACF),'float32')
5731 5731 self.lpulse=numpy.zeros((dataOut.NACF),'float32')
5732 5732 dataOut.lags_LP=numpy.zeros((dataOut.IBITS),order='F',dtype='float32')
5733 5733 self.lagp=numpy.zeros((dataOut.NACF),'float32')
5734 5734 self.u=numpy.zeros((2*dataOut.NACF,2*dataOut.NACF),'float32')
5735 5735 dataOut.ne=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
5736 5736 dataOut.te=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5737 5737 dataOut.ete=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5738 5738 dataOut.ti=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5739 5739 dataOut.eti=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5740 5740 dataOut.ph=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5741 5741 dataOut.eph=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5742 5742 dataOut.phe=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5743 5743 dataOut.ephe=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
5744 5744 dataOut.errors=numpy.zeros((dataOut.IBITS,max(dataOut.NRANGE,dataOut.NSHTS)),order='F',dtype='float32')
5745 5745 dataOut.fit_array_real=numpy.zeros((max(dataOut.NRANGE,dataOut.NSHTS),dataOut.NLAG),order='F',dtype='float32')
5746 5746 dataOut.status=numpy.zeros(1,'float32')
5747 5747 dataOut.tx=240.0 #deberΓ­a provenir del header #hybrid
5748 5748
5749 5749 for i in range(dataOut.IBITS):
5750 5750 dataOut.lags_LP[i]=float(i)*(dataOut.tx/150.0)/float(dataOut.IBITS) # (float)i*(header.tx/150.0)/(float)IBITS;
5751 5751
5752 5752 self.aux=0
5753 5753
5754 5754 dataOut.cut=30
5755 5755 for i in range(30,15,-1): #AquΓ­ se calcula en donde se unirΓ‘ DP y LP en la parte final
5756 5756 if numpy.nanmax(dataOut.acfs_error_to_plot[i,:])>=10 or dataOut.info2[i]==0:
5757 5757 dataOut.cut=i-1
5758 5758
5759 5759 for i in range(dataOut.NLAG):
5760 5760 self.cal[i]=sum(dataOut.output_LP_integrated[i,:,3].real) #Lag x Height x Channel
5761 5761
5762 5762 #print(numpy.sum(self.cal)) #Coinciden
5763 5763 #exit(1)
5764 5764 self.cal/=float(dataOut.NRANGE)
5765 5765 #print(anoise0)
5766 5766 #print(anoise1)
5767 5767 #exit(1)
5768 5768 #print("nis: ", dataOut.nis)
5769 5769 #print("pan: ", dataOut.pan)
5770 5770 #print("pbn: ", dataOut.pbn)
5771 5771 #print(numpy.sum(dataOut.output_LP_integrated[0,:,0]))
5772 5772 '''
5773 5773 import matplotlib.pyplot as plt
5774 5774 plt.plot(dataOut.output_LP_integrated[:,40,0])
5775 5775 plt.show()
5776 5776 '''
5777 5777 #print(dataOut.output_LP_integrated[0,40,0])
5778 5778 #print(numpy.sum(dataOut.output_LP_integrated[:,0,0]))
5779 5779 #exit(1)
5780 5780
5781 5781 #################### PROBAR MÁS INTEGRACIΓ“N, SINO MODIFICAR VALOR DE "NIS" ####################
5782 5782 # VER dataOut.nProfiles_LP #
5783 5783
5784 5784 '''
5785 5785 #PLOTEAR POTENCIA VS RUIDO, QUIZA SE ESTA REMOVIENDO MUCHA SEΓ‘AL
5786 5786 #print(dataOut.heightList)
5787 5787 import matplotlib.pyplot as plt
5788 5788 plt.plot(10*numpy.log10(dataOut.output_LP_integrated.real[0,:,0]),dataOut.range1)
5789 5789 #plt.plot(10*numpy.log10(dataOut.output_LP_integrated.real[0,:,0]/dataOut.nProfiles_LP),dataOut.range1)
5790 5790 plt.axvline(10*numpy.log10(anoise0),color='k',linestyle='dashed')
5791 5791 plt.grid()
5792 5792 plt.xlim(20,100)
5793 5793 plt.show()
5794 5794 '''
5795 5795
5796 5796
5797 5797 for j in range(dataOut.NACF+2*dataOut.IBITS+2):
5798 5798
5799 5799 dataOut.output_LP_integrated.real[0,j,0]-=anoise0 #lag0 ch0
5800 5800 dataOut.output_LP_integrated.real[1,j,0]-=anoise1 #lag1 ch0
5801 5801
5802 5802 for i in range(1,dataOut.NLAG): #remove cal data from certain lags
5803 5803 dataOut.output_LP_integrated.real[i,j,0]-=self.cal[i]
5804 5804 k=max(j,26) #constant power below range 26
5805 5805 self.powera[j]=dataOut.output_LP_integrated.real[0,k,0] #Lag0 and Channel 0
5806 5806
5807 5807 ## examine drifts here - based on 60 'indep.' estimates
5808 5808 #print(numpy.sum(self.powera))
5809 5809 #exit(1)
5810 5810 #nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint*10
5811 5811 nis = dataOut.nis
5812 5812 #print("nis",nis)
5813 5813 alpha=beta=delta=0.0
5814 5814 nest=0
5815 5815 gamma=3.0/(2.0*numpy.pi*dataOut.lags_LP[1]*1.0e-3)
5816 5816 beta=gamma*(math.atan2(dataOut.output_LP_integrated.imag[14,0,2],dataOut.output_LP_integrated.real[14,0,2])-math.atan2(dataOut.output_LP_integrated.imag[1,0,2],dataOut.output_LP_integrated.real[1,0,2]))/13.0
5817 5817 #print(gamma,beta)
5818 5818 #exit(1)
5819 5819 for i in range(1,3):
5820 5820 gamma=3.0/(2.0*numpy.pi*dataOut.lags_LP[i]*1.0e-3)
5821 5821 #print("gamma",gamma)
5822 5822 for j in range(34,44):
5823 5823 rho2=numpy.abs(dataOut.output_LP_integrated[i,j,0])/numpy.abs(dataOut.output_LP_integrated[0,j,0])
5824 5824 dataOut.dphi2=(1.0/rho2-1.0)/(float(2*nis))
5825 5825 dataOut.dphi2*=gamma**2
5826 5826 pest=gamma*math.atan(dataOut.output_LP_integrated.imag[i,j,0]/dataOut.output_LP_integrated.real[i,j,0])
5827 5827 #print("1",dataOut.output_LP_integrated.imag[i,j,0])
5828 5828 #print("2",dataOut.output_LP_integrated.real[i,j,0])
5829 5829 self.drift[nest]=pest
5830 5830 self.ddrift[nest]=dataOut.dphi2
5831 5831 self.rdrift[nest]=float(nest)
5832 5832 nest+=1
5833 5833
5834 5834 sorted(self.drift[:nest])
5835 5835
5836 5836 #print(dataOut.dphi2)
5837 5837 #exit(1)
5838 5838
5839 5839 for j in range(int(nest/4),int(3*nest/4)):
5840 5840 #i=int(self.rdrift[j])
5841 5841 alpha+=self.drift[j]/self.ddrift[j]
5842 5842 delta+=1.0/self.ddrift[j]
5843 5843
5844 5844 alpha/=delta
5845 5845 delta=1./numpy.sqrt(delta)
5846 5846 vdrift=alpha-beta
5847 5847 dvdrift=delta
5848 5848
5849 5849 #need to develop estimate of complete density profile using all
5850 5850 #available data
5851 5851
5852 5852 #estimate sample variances for long-pulse power profile
5853 5853
5854 5854 #nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint
5855 5855 nis = dataOut.nis/10
5856 5856 #print("nis",nis)
5857 5857
5858 5858 self.sigma[:dataOut.NACF+2*dataOut.IBITS+2]=((anoise0+self.powera[:dataOut.NACF+2*dataOut.IBITS+2])**2)/float(nis)
5859 5859 #print(self.sigma)
5860 5860 #exit(1)
5861 5861 ioff=1
5862 5862
5863 5863 #deconvolve rectangular pulse shape from profile ==> powerb, perror
5864 5864
5865 5865
5866 5866 ############# START nnlswrap#############
5867 5867
5868 5868 if dataOut.ut_Faraday>14.0:
5869 5869 alpha_nnlswrap=20.0
5870 5870 else:
5871 5871 alpha_nnlswrap=30.0
5872 5872
5873 5873 range1_nnls=dataOut.NACF
5874 5874 range2_nnls=dataOut.NACF+dataOut.IBITS-1
5875 5875
5876 5876 g_nnlswrap=numpy.zeros((range1_nnls,range2_nnls),'float32')
5877 5877 a_nnlswrap=numpy.zeros((range2_nnls,range2_nnls),'float64')
5878 5878
5879 5879 for i in range(range1_nnls):
5880 5880 for j in range(range2_nnls):
5881 5881 if j>=i and j<i+dataOut.IBITS:
5882 5882 g_nnlswrap[i,j]=1.0
5883 5883 else:
5884 5884 g_nnlswrap[i,j]=0.0
5885 5885
5886 5886 a_nnlswrap[:]=numpy.matmul(numpy.transpose(g_nnlswrap),g_nnlswrap)
5887 5887
5888 5888 numpy.fill_diagonal(a_nnlswrap,a_nnlswrap.diagonal()+alpha_nnlswrap**2)
5889 5889
5890 5890 #ERROR ANALYSIS#
5891 5891
5892 5892 self.perror[:range2_nnls]=0.0
5893 5893 self.perror[:range2_nnls]=numpy.matmul(1./(self.sigma[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff]),g_nnlswrap**2)
5894 5894 self.perror[:range1_nnls]+=(alpha_nnlswrap**2)/(self.sigma[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff])
5895 5895 self.perror[:range2_nnls]=1.00/self.perror[:range2_nnls]
5896 5896
5897 5897 b_nnlswrap=numpy.zeros(range2_nnls,'float64')
5898 5898 b_nnlswrap[:]=numpy.matmul(self.powera[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff],g_nnlswrap) #match filter alturas
5899 5899
5900 5900 x_nnlswrap=numpy.zeros(range2_nnls,'float64')
5901 5901 x_nnlswrap[:]=nnls(a_nnlswrap,b_nnlswrap)[0]
5902 5902
5903 5903 self.powerb[:range2_nnls]=x_nnlswrap
5904 5904 #print(self.powerb[40])
5905 5905 #print(self.powerb[66])
5906 5906 #exit(1)
5907 5907 #############END nnlswrap#############
5908 5908 #print(numpy.sum(numpy.sqrt(self.perror[0:dataOut.NACF])))
5909 5909 #print(self.powerb[0:dataOut.NACF])
5910 5910 #exit(1)
5911 5911 #estimate relative error for deconvolved profile (scaling irrelevant)
5912 5912 #print(dataOut.NACF)
5913 5913 dataOut.ene[0:dataOut.NACF]=numpy.sqrt(self.perror[0:dataOut.NACF])/self.powerb[0:dataOut.NACF]
5914 5914 #print(numpy.sum(dataOut.ene))
5915 5915 #exit(1)
5916 5916 aux=0
5917 5917
5918 5918 for i in range(dataOut.IBITS,dataOut.NACF):
5919 5919 self.dpulse[i]=self.lpulse[i]=0.0
5920 5920 for j in range(dataOut.IBITS):
5921 5921 k=int(i-j)
5922 5922 if k<36-aux and k>16:
5923 5923 self.dpulse[i]+=dataOut.ph2[k]/dataOut.h2[k]
5924 5924 elif k>=36-aux:
5925 5925 self.lpulse[i]+=self.powerb[k]
5926 5926 self.lagp[i]=self.powera[i]
5927 5927
5928 5928 #find scale factor that best merges profiles
5929 5929
5930 5930 qi=sum(self.dpulse[32:dataOut.NACF]**2/(self.lagp[32:dataOut.NACF]+anoise0)**2)
5931 5931 ri=sum((self.dpulse[32:dataOut.NACF]*self.lpulse[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
5932 5932 si=sum((self.dpulse[32:dataOut.NACF]*self.lagp[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
5933 5933 ui=sum(self.lpulse[32:dataOut.NACF]**2/(self.lagp[32:dataOut.NACF]+anoise0)**2)
5934 5934 vi=sum((self.lpulse[32:dataOut.NACF]*self.lagp[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
5935 5935
5936 5936 alpha=(si*ui-vi*ri)/(qi*ui-ri*ri)
5937 5937 beta=(qi*vi-ri*si)/(qi*ui-ri*ri)
5938 5938
5939 5939 #form density profile estimate, merging rescaled power profiles
5940 5940 #print(dataOut.h2)
5941 5941 #print(numpy.sum(alpha))
5942 5942 #print(numpy.sum(dataOut.ph2))
5943 5943 self.powerb[16:36-aux]=alpha*dataOut.ph2[16:36-aux]/dataOut.h2[16:36-aux]
5944 5944 self.powerb[36-aux:dataOut.NACF]*=beta
5945 5945
5946 5946 #form Ne estimate, fill in error estimate at low altitudes
5947 5947
5948 5948 dataOut.ene[0:36-aux]=dataOut.sdp2[0:36-aux]/dataOut.ph2[0:36-aux]
5949 5949 dataOut.ne[:dataOut.NACF]=self.powerb[:dataOut.NACF]*dataOut.h2[:dataOut.NACF]/alpha
5950 5950 #print(numpy.sum(self.powerb))
5951 5951 #print(numpy.sum(dataOut.ene))
5952 5952 #print(numpy.sum(dataOut.ne))
5953 5953 #exit(1)
5954 5954 #now do error propagation: store zero lag error covariance in u
5955 5955
5956 5956 nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint/1 # DLH serious debris removal
5957 5957
5958 5958 for i in range(dataOut.NACF):
5959 5959 for j in range(i,dataOut.NACF):
5960 5960 if j-i>=dataOut.IBITS:
5961 5961 self.u[i,j]=0.0
5962 5962 else:
5963 5963 self.u[i,j]=dataOut.output_LP_integrated.real[j-i,i,0]**2/float(nis)
5964 5964 self.u[i,j]*=(anoise0+dataOut.output_LP_integrated.real[0,i,0])/dataOut.output_LP_integrated.real[0,i,0]
5965 5965 self.u[i,j]*=(anoise0+dataOut.output_LP_integrated.real[0,j,0])/dataOut.output_LP_integrated.real[0,j,0]
5966 5966
5967 5967 self.u[j,i]=self.u[i,j]
5968 5968
5969 5969 #now error analyis for lag product matrix (diag), place in acf_err
5970 5970
5971 5971 for i in range(dataOut.NACF):
5972 5972 for j in range(dataOut.IBITS):
5973 5973 if j==0:
5974 5974 dataOut.errors[0,i]=numpy.sqrt(self.u[i,i])
5975 5975 else:
5976 5976 dataOut.errors[j,i]=numpy.sqrt(((dataOut.output_LP_integrated.real[0,i,0]+anoise0)*(dataOut.output_LP_integrated.real[0,i+j,0]+anoise0)+dataOut.output_LP_integrated.real[j,i,0]**2)/float(2*nis))
5977 5977 '''
5978 5978 print(numpy.sum(dataOut.output_LP_integrated))
5979 5979 print(numpy.sum(dataOut.errors))
5980 5980 print(numpy.sum(self.powerb))
5981 5981 print(numpy.sum(dataOut.ne))
5982 5982 print(numpy.sum(dataOut.lags_LP))
5983 5983 print(numpy.sum(dataOut.thb))
5984 5984 print(numpy.sum(dataOut.bfm))
5985 5985 print(numpy.sum(dataOut.te))
5986 5986 print(numpy.sum(dataOut.ete))
5987 5987 print(numpy.sum(dataOut.ti))
5988 5988 print(numpy.sum(dataOut.eti))
5989 5989 print(numpy.sum(dataOut.ph))
5990 5990 print(numpy.sum(dataOut.eph))
5991 5991 print(numpy.sum(dataOut.phe))
5992 5992 print(numpy.sum(dataOut.ephe))
5993 5993 print(numpy.sum(dataOut.range1))
5994 5994 print(numpy.sum(dataOut.ut))
5995 5995 print(numpy.sum(dataOut.NACF))
5996 5996 print(numpy.sum(dataOut.fit_array_real))
5997 5997 print(numpy.sum(dataOut.status))
5998 5998 print(numpy.sum(dataOut.NRANGE))
5999 5999 print(numpy.sum(dataOut.IBITS))
6000 6000 exit(1)
6001 6001 '''
6002 6002 '''
6003 6003 print(dataOut.te2[13:16])
6004 6004 print(numpy.sum(dataOut.te2))
6005 6005 exit(1)
6006 6006 '''
6007 6007 #print("Success 1")
6008 6008 ###################Correlation pulse and itself
6009 6009
6010 6010 #print(dataOut.NRANGE)
6011 6011 print("LP Estimation")
6012 6012 with suppress_stdout_stderr():
6013 6013 #pass
6014 6014 full_profile_profile.profile(numpy.transpose(dataOut.output_LP_integrated,(2,1,0)),numpy.transpose(dataOut.errors),self.powerb,dataOut.ne,dataOut.lags_LP,dataOut.thb,dataOut.bfm,dataOut.te,dataOut.ete,dataOut.ti,dataOut.eti,dataOut.ph,dataOut.eph,dataOut.phe,dataOut.ephe,dataOut.range1,dataOut.ut,dataOut.NACF,dataOut.fit_array_real,dataOut.status,dataOut.NRANGE,dataOut.IBITS)
6015 6015
6016 6016 print("status: ",dataOut.status)
6017 6017
6018 6018 if dataOut.status>=3.5:
6019 6019 dataOut.te[:]=numpy.nan
6020 6020 dataOut.ete[:]=numpy.nan
6021 6021 dataOut.ti[:]=numpy.nan
6022 6022 dataOut.eti[:]=numpy.nan
6023 6023 dataOut.ph[:]=numpy.nan
6024 6024 dataOut.eph[:]=numpy.nan
6025 6025 dataOut.phe[:]=numpy.nan
6026 6026 dataOut.ephe[:]=numpy.nan
6027 6027
6028 6028 return dataOut
6029 6029
6030 6030 class LongPulseAnalysisSpectra(Operation):
6031 6031 """Operation to estimate ACFs, temperatures, total electron density and Hydrogen/Helium fractions from the Long Pulse data.
6032 6032
6033 6033 Parameters:
6034 6034 -----------
6035 6035 NACF : int
6036 6036 .*
6037 6037
6038 6038 Example
6039 6039 --------
6040 6040
6041 6041 op = proc_unit.addOperation(name='LongPulseAnalysis', optype='other')
6042 6042 op.addParameter(name='NACF', value='16', format='int')
6043 6043
6044 6044 """
6045 6045
6046 6046 def __init__(self, **kwargs):
6047 6047
6048 6048 Operation.__init__(self, **kwargs)
6049 6049 self.aux=1
6050 6050
6051 6051 def run(self,dataOut,NACF):
6052 6052
6053 6053 dataOut.NACF=NACF
6054 6054 dataOut.heightList=dataOut.DH*(numpy.arange(dataOut.NACF))
6055 6055 anoise0=dataOut.tnoise[0]
6056 6056 anoise1=anoise0*0.0 #seems to be noise in 1st lag 0.015 before '14
6057 6057 #print(anoise0)
6058 6058 #exit(1)
6059 6059 if self.aux:
6060 6060 #dataOut.cut=31#26#height=31*15=465
6061 6061 self.cal=numpy.zeros((dataOut.NLAG),'float32')
6062 6062 self.drift=numpy.zeros((200),'float32')
6063 6063 self.rdrift=numpy.zeros((200),'float32')
6064 6064 self.ddrift=numpy.zeros((200),'float32')
6065 6065 self.sigma=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6066 6066 self.powera=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6067 6067 self.powerb=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6068 6068 self.perror=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6069 6069 dataOut.ene=numpy.zeros((dataOut.NRANGE),'float32')
6070 6070 self.dpulse=numpy.zeros((dataOut.NACF),'float32')
6071 6071 self.lpulse=numpy.zeros((dataOut.NACF),'float32')
6072 6072 dataOut.lags_LP=numpy.zeros((dataOut.IBITS),order='F',dtype='float32')
6073 6073 self.lagp=numpy.zeros((dataOut.NACF),'float32')
6074 6074 self.u=numpy.zeros((2*dataOut.NACF,2*dataOut.NACF),'float32')
6075 6075 dataOut.ne=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6076 6076 dataOut.te=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6077 6077 dataOut.ete=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6078 6078 dataOut.ti=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6079 6079 dataOut.eti=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6080 6080 dataOut.ph=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6081 6081 dataOut.eph=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6082 6082 dataOut.phe=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6083 6083 dataOut.ephe=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6084 6084 dataOut.errors=numpy.zeros((dataOut.IBITS,max(dataOut.NRANGE,dataOut.NSHTS)),order='F',dtype='float32')
6085 6085 dataOut.fit_array_real=numpy.zeros((max(dataOut.NRANGE,dataOut.NSHTS),dataOut.NLAG),order='F',dtype='float32')
6086 6086 dataOut.status=numpy.zeros(1,'float32')
6087 6087 dataOut.tx=240.0 #deberΓ­a provenir del header #hybrid
6088 6088
6089 6089 for i in range(dataOut.IBITS):
6090 6090 dataOut.lags_LP[i]=float(i)*(dataOut.tx/150.0)/float(dataOut.IBITS) # (float)i*(header.tx/150.0)/(float)IBITS;
6091 6091
6092 6092 self.aux=0
6093 6093
6094 6094 dataOut.cut=30
6095 6095 for i in range(30,15,-1): #AquΓ­ se calcula en donde se unirΓ‘ DP y LP en la parte final
6096 6096 if numpy.nanmax(dataOut.acfs_error_to_plot[i,:])>=10 or dataOut.info2[i]==0:
6097 6097 dataOut.cut=i-1
6098 6098
6099 6099 for i in range(dataOut.NLAG):
6100 6100 self.cal[i]=sum(dataOut.output_LP_integrated[i,:,3].real) #Lag x Height x Channel
6101 6101
6102 6102 #print(numpy.sum(self.cal)) #Coinciden
6103 6103 #exit(1)
6104 6104 self.cal/=float(dataOut.NRANGE)
6105 6105
6106 6106
6107 6107 #################### PROBAR MÁS INTEGRACIΓ“N, SINO MODIFICAR VALOR DE "NIS" ####################
6108 6108 # VER dataOut.nProfiles_LP #
6109 6109
6110 6110 '''
6111 6111 #PLOTEAR POTENCIA VS RUIDO, QUIZA SE ESTA REMOVIENDO MUCHA SEΓ‘AL
6112 6112 #print(dataOut.heightList)
6113 6113 import matplotlib.pyplot as plt
6114 6114 plt.plot(10*numpy.log10(dataOut.output_LP_integrated.real[0,:,0]),dataOut.range1)
6115 6115 #plt.plot(10*numpy.log10(dataOut.output_LP_integrated.real[0,:,0]/dataOut.nProfiles_LP),dataOut.range1)
6116 6116 plt.axvline(10*numpy.log10(anoise0),color='k',linestyle='dashed')
6117 6117 plt.grid()
6118 6118 plt.xlim(20,100)
6119 6119 plt.show()
6120 6120 '''
6121 6121
6122 6122
6123 6123 for j in range(dataOut.NACF+2*dataOut.IBITS+2):
6124 6124
6125 6125 dataOut.output_LP_integrated.real[0,j,0]-=anoise0 #lag0 ch0
6126 6126 dataOut.output_LP_integrated.real[1,j,0]-=anoise1 #lag1 ch0
6127 6127
6128 6128 for i in range(1,dataOut.NLAG): #remove cal data from certain lags
6129 6129 dataOut.output_LP_integrated.real[i,j,0]-=self.cal[i]
6130 6130 k=max(j,26) #constant power below range 26
6131 6131 self.powera[j]=dataOut.output_LP_integrated.real[0,k,0] #Lag0 and Channel 0
6132 6132
6133 6133 ## examine drifts here - based on 60 'indep.' estimates
6134 6134 #print(numpy.sum(self.powera))
6135 6135 #exit(1)
6136 6136 #nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint*10
6137 6137 nis = dataOut.nis
6138 6138 #print("nis",nis)
6139 6139 alpha=beta=delta=0.0
6140 6140 nest=0
6141 6141 gamma=3.0/(2.0*numpy.pi*dataOut.lags_LP[1]*1.0e-3)
6142 6142 beta=gamma*(math.atan2(dataOut.output_LP_integrated.imag[14,0,2],dataOut.output_LP_integrated.real[14,0,2])-math.atan2(dataOut.output_LP_integrated.imag[1,0,2],dataOut.output_LP_integrated.real[1,0,2]))/13.0
6143 6143 #print(gamma,beta)
6144 6144 #exit(1)
6145 6145 for i in range(1,3):
6146 6146 gamma=3.0/(2.0*numpy.pi*dataOut.lags_LP[i]*1.0e-3)
6147 6147 #print("gamma",gamma)
6148 6148 for j in range(34,44):
6149 6149 rho2=numpy.abs(dataOut.output_LP_integrated[i,j,0])/numpy.abs(dataOut.output_LP_integrated[0,j,0])
6150 6150 dataOut.dphi2=(1.0/rho2-1.0)/(float(2*nis))
6151 6151 dataOut.dphi2*=gamma**2
6152 6152 pest=gamma*math.atan(dataOut.output_LP_integrated.imag[i,j,0]/dataOut.output_LP_integrated.real[i,j,0])
6153 6153 #print("1",dataOut.output_LP_integrated.imag[i,j,0])
6154 6154 #print("2",dataOut.output_LP_integrated.real[i,j,0])
6155 6155 self.drift[nest]=pest
6156 6156 self.ddrift[nest]=dataOut.dphi2
6157 6157 self.rdrift[nest]=float(nest)
6158 6158 nest+=1
6159 6159
6160 6160 sorted(self.drift[:nest])
6161 6161
6162 6162 #print(dataOut.dphi2)
6163 6163 #exit(1)
6164 6164
6165 6165 for j in range(int(nest/4),int(3*nest/4)):
6166 6166 #i=int(self.rdrift[j])
6167 6167 alpha+=self.drift[j]/self.ddrift[j]
6168 6168 delta+=1.0/self.ddrift[j]
6169 6169
6170 6170 alpha/=delta
6171 6171 delta=1./numpy.sqrt(delta)
6172 6172 vdrift=alpha-beta
6173 6173 dvdrift=delta
6174 6174
6175 6175 #need to develop estimate of complete density profile using all
6176 6176 #available data
6177 6177
6178 6178 #estimate sample variances for long-pulse power profile
6179 6179
6180 6180 #nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint
6181 6181 nis = dataOut.nis/10
6182 6182 #print("nis",nis)
6183 6183
6184 6184 self.sigma[:dataOut.NACF+2*dataOut.IBITS+2]=((anoise0+self.powera[:dataOut.NACF+2*dataOut.IBITS+2])**2)/float(nis)
6185 6185 #print(self.sigma)
6186 6186 #exit(1)
6187 6187 ioff=1
6188 6188
6189 6189 #deconvolve rectangular pulse shape from profile ==> powerb, perror
6190 6190
6191 6191 '''
6192 6192 ############# START nnlswrap#############
6193 6193
6194 6194 if dataOut.ut_Faraday>14.0:
6195 6195 alpha_nnlswrap=20.0
6196 6196 else:
6197 6197 alpha_nnlswrap=30.0
6198 6198
6199 6199 range1_nnls=dataOut.NACF
6200 6200 range2_nnls=dataOut.NACF+dataOut.IBITS-1
6201 6201
6202 6202 g_nnlswrap=numpy.zeros((range1_nnls,range2_nnls),'float32')
6203 6203 a_nnlswrap=numpy.zeros((range2_nnls,range2_nnls),'float64')
6204 6204
6205 6205 for i in range(range1_nnls):
6206 6206 for j in range(range2_nnls):
6207 6207 if j>=i and j<i+dataOut.IBITS:
6208 6208 g_nnlswrap[i,j]=1.0
6209 6209 else:
6210 6210 g_nnlswrap[i,j]=0.0
6211 6211
6212 6212 a_nnlswrap[:]=numpy.matmul(numpy.transpose(g_nnlswrap),g_nnlswrap)
6213 6213
6214 6214 numpy.fill_diagonal(a_nnlswrap,a_nnlswrap.diagonal()+alpha_nnlswrap**2)
6215 6215
6216 6216 #ERROR ANALYSIS#
6217 6217
6218 6218 self.perror[:range2_nnls]=0.0
6219 6219 self.perror[:range2_nnls]=numpy.matmul(1./(self.sigma[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff]),g_nnlswrap**2)
6220 6220 self.perror[:range1_nnls]+=(alpha_nnlswrap**2)/(self.sigma[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff])
6221 6221 self.perror[:range2_nnls]=1.00/self.perror[:range2_nnls]
6222 6222
6223 6223 b_nnlswrap=numpy.zeros(range2_nnls,'float64')
6224 6224 b_nnlswrap[:]=numpy.matmul(self.powera[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff],g_nnlswrap)
6225 6225
6226 6226 x_nnlswrap=numpy.zeros(range2_nnls,'float64')
6227 6227 x_nnlswrap[:]=nnls(a_nnlswrap,b_nnlswrap)[0]
6228 6228
6229 6229 self.powerb[:range2_nnls]=x_nnlswrap
6230 6230 #print(self.powerb[40])
6231 6231 #print(self.powerb[66])
6232 6232 #exit(1)
6233 6233 #############END nnlswrap#############
6234 6234 '''
6235 6235 self.powerb[:] = self.powera
6236 6236 self.perror[:] = 0.
6237 6237 #print(numpy.sum(numpy.sqrt(self.perror[0:dataOut.NACF])))
6238 6238 #print(self.powerb[0:dataOut.NACF])
6239 6239 #exit(1)
6240 6240 #estimate relative error for deconvolved profile (scaling irrelevant)
6241 6241 #print(dataOut.NACF)
6242 6242 dataOut.ene[0:dataOut.NACF]=numpy.sqrt(self.perror[0:dataOut.NACF])/self.powerb[0:dataOut.NACF]
6243 6243 #print(numpy.sum(dataOut.ene))
6244 6244 #exit(1)
6245 6245 aux=0
6246 6246
6247 6247 for i in range(dataOut.IBITS,dataOut.NACF):
6248 6248 self.dpulse[i]=self.lpulse[i]=0.0
6249 6249 for j in range(dataOut.IBITS):
6250 6250 k=int(i-j)
6251 6251 if k<36-aux and k>16:
6252 6252 self.dpulse[i]+=dataOut.ph2[k]/dataOut.h2[k]
6253 6253 elif k>=36-aux:
6254 6254 self.lpulse[i]+=self.powerb[k]
6255 6255 self.lagp[i]=self.powera[i]
6256 6256
6257 6257 #find scale factor that best merges profiles
6258 6258
6259 6259 qi=sum(self.dpulse[32:dataOut.NACF]**2/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6260 6260 ri=sum((self.dpulse[32:dataOut.NACF]*self.lpulse[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6261 6261 si=sum((self.dpulse[32:dataOut.NACF]*self.lagp[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6262 6262 ui=sum(self.lpulse[32:dataOut.NACF]**2/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6263 6263 vi=sum((self.lpulse[32:dataOut.NACF]*self.lagp[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6264 6264
6265 6265 alpha=(si*ui-vi*ri)/(qi*ui-ri*ri)
6266 6266 beta=(qi*vi-ri*si)/(qi*ui-ri*ri)
6267 6267
6268 6268 #form density profile estimate, merging rescaled power profiles
6269 6269 #print(dataOut.h2)
6270 6270 #print(numpy.sum(alpha))
6271 6271 #print(numpy.sum(dataOut.ph2))
6272 6272 self.powerb[16:36-aux]=alpha*dataOut.ph2[16:36-aux]/dataOut.h2[16:36-aux]
6273 6273 self.powerb[36-aux:dataOut.NACF]*=beta
6274 6274
6275 6275 #form Ne estimate, fill in error estimate at low altitudes
6276 6276
6277 6277 dataOut.ene[0:36-aux]=dataOut.sdp2[0:36-aux]/dataOut.ph2[0:36-aux]
6278 6278 dataOut.ne[:dataOut.NACF]=self.powerb[:dataOut.NACF]*dataOut.h2[:dataOut.NACF]/alpha
6279 6279 #print(numpy.sum(self.powerb))
6280 6280 #print(numpy.sum(dataOut.ene))
6281 6281 #print(numpy.sum(dataOut.ne))
6282 6282 #exit(1)
6283 6283 #now do error propagation: store zero lag error covariance in u
6284 6284
6285 6285 nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint/1 # DLH serious debris removal
6286 6286
6287 6287 for i in range(dataOut.NACF):
6288 6288 for j in range(i,dataOut.NACF):
6289 6289 if j-i>=dataOut.IBITS:
6290 6290 self.u[i,j]=0.0
6291 6291 else:
6292 6292 self.u[i,j]=dataOut.output_LP_integrated.real[j-i,i,0]**2/float(nis)
6293 6293 self.u[i,j]*=(anoise0+dataOut.output_LP_integrated.real[0,i,0])/dataOut.output_LP_integrated.real[0,i,0]
6294 6294 self.u[i,j]*=(anoise0+dataOut.output_LP_integrated.real[0,j,0])/dataOut.output_LP_integrated.real[0,j,0]
6295 6295
6296 6296 self.u[j,i]=self.u[i,j]
6297 6297
6298 6298 #now error analyis for lag product matrix (diag), place in acf_err
6299 6299
6300 6300 for i in range(dataOut.NACF):
6301 6301 for j in range(dataOut.IBITS):
6302 6302 if j==0:
6303 6303 dataOut.errors[0,i]=numpy.sqrt(self.u[i,i])
6304 6304 else:
6305 6305 dataOut.errors[j,i]=numpy.sqrt(((dataOut.output_LP_integrated.real[0,i,0]+anoise0)*(dataOut.output_LP_integrated.real[0,i+j,0]+anoise0)+dataOut.output_LP_integrated.real[j,i,0]**2)/float(2*nis))
6306 6306
6307 6307 print("Success")
6308 6308 #print(dataOut.NRANGE)
6309 6309 with suppress_stdout_stderr():
6310 6310 pass
6311 6311 #full_profile_profile.profile(numpy.transpose(dataOut.output_LP_integrated,(2,1,0)),numpy.transpose(dataOut.errors),self.powerb,dataOut.ne,dataOut.lags_LP,dataOut.thb,dataOut.bfm,dataOut.te,dataOut.ete,dataOut.ti,dataOut.eti,dataOut.ph,dataOut.eph,dataOut.phe,dataOut.ephe,dataOut.range1,dataOut.ut,dataOut.NACF,dataOut.fit_array_real,dataOut.status,dataOut.NRANGE,dataOut.IBITS)
6312 6312
6313 6313 print("status: ",dataOut.status)
6314 6314
6315 6315 if dataOut.status>=3.5:
6316 6316 dataOut.te[:]=numpy.nan
6317 6317 dataOut.ete[:]=numpy.nan
6318 6318 dataOut.ti[:]=numpy.nan
6319 6319 dataOut.eti[:]=numpy.nan
6320 6320 dataOut.ph[:]=numpy.nan
6321 6321 dataOut.eph[:]=numpy.nan
6322 6322 dataOut.phe[:]=numpy.nan
6323 6323 dataOut.ephe[:]=numpy.nan
6324 6324
6325 6325 return dataOut
6326 6326
6327 6327 class LongPulseAnalysis_V2(Operation):
6328 6328 """Operation to estimate ACFs, temperatures, total electron density and Hydrogen/Helium fractions from the Long Pulse data.
6329 6329
6330 6330 Parameters:
6331 6331 -----------
6332 6332 NACF : int
6333 6333 .*
6334 6334
6335 6335 Example
6336 6336 --------
6337 6337
6338 6338 op = proc_unit.addOperation(name='LongPulseAnalysis', optype='other')
6339 6339 op.addParameter(name='NACF', value='16', format='int')
6340 6340
6341 6341 """
6342 6342
6343 6343 def __init__(self, **kwargs):
6344 6344
6345 6345 Operation.__init__(self, **kwargs)
6346 6346 self.aux=1
6347 6347
6348 6348 def run(self,dataOut,NACF):
6349 6349
6350 6350 dataOut.NACF=NACF
6351 6351 dataOut.heightList=dataOut.DH*(numpy.arange(dataOut.NACF))
6352 6352 anoise0=dataOut.tnoise[0]
6353 6353 anoise1=anoise0*0.0 #seems to be noise in 1st lag 0.015 before '14
6354 6354 #print(anoise0)
6355 6355 #exit(1)
6356 6356 if self.aux:
6357 6357 #dataOut.cut=31#26#height=31*15=465
6358 6358 self.cal=numpy.zeros((dataOut.NLAG),'float32')
6359 6359 self.drift=numpy.zeros((200),'float32')
6360 6360 self.rdrift=numpy.zeros((200),'float32')
6361 6361 self.ddrift=numpy.zeros((200),'float32')
6362 6362 self.sigma=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6363 6363 self.powera=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6364 6364 self.powerb=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6365 6365 self.perror=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6366 6366 dataOut.ene=numpy.zeros((dataOut.NRANGE),'float32')
6367 6367 self.dpulse=numpy.zeros((dataOut.NACF),'float32')
6368 6368 self.lpulse=numpy.zeros((dataOut.NACF),'float32')
6369 6369 dataOut.lags_LP=numpy.zeros((dataOut.IBITS),order='F',dtype='float32')
6370 6370 self.lagp=numpy.zeros((dataOut.NACF),'float32')
6371 6371 self.u=numpy.zeros((2*dataOut.NACF,2*dataOut.NACF),'float32')
6372 6372 dataOut.ne=numpy.zeros((dataOut.NRANGE),order='F',dtype='float32')
6373 6373 dataOut.te=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6374 6374 dataOut.ete=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6375 6375 dataOut.ti=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6376 6376 dataOut.eti=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6377 6377 dataOut.ph=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6378 6378 dataOut.eph=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6379 6379 dataOut.phe=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6380 6380 dataOut.ephe=numpy.zeros((dataOut.NACF),order='F',dtype='float32')
6381 6381 dataOut.errors=numpy.zeros((dataOut.IBITS,max(dataOut.NRANGE,dataOut.NSHTS)),order='F',dtype='float32')
6382 6382 dataOut.fit_array_real=numpy.zeros((max(dataOut.NRANGE,dataOut.NSHTS),dataOut.NLAG),order='F',dtype='float32')
6383 6383 dataOut.status=numpy.zeros(1,'float32')
6384 6384 dataOut.tx=240.0 #deberΓ­a provenir del header #hybrid
6385 6385
6386 6386 for i in range(dataOut.IBITS):
6387 6387 dataOut.lags_LP[i]=float(i)*(dataOut.tx/150.0)/float(dataOut.IBITS) # (float)i*(header.tx/150.0)/(float)IBITS;
6388 6388
6389 6389 self.aux=0
6390 6390
6391 6391 dataOut.cut=30
6392 6392 for i in range(30,15,-1):
6393 6393 if numpy.nanmax(dataOut.acfs_error_to_plot[i,:])>=10 or dataOut.info2[i]==0:
6394 6394 dataOut.cut=i-1
6395 6395
6396 6396 for i in range(dataOut.NLAG):
6397 6397 self.cal[i]=sum(dataOut.output_LP_integrated[i,:,3].real)
6398 6398
6399 6399 #print(numpy.sum(self.cal)) #Coinciden
6400 6400 #exit(1)
6401 6401 self.cal/=float(dataOut.NRANGE)
6402 6402 #print(anoise0)
6403 6403 #print(anoise1)
6404 6404 #exit(1)
6405 6405
6406 6406 for j in range(dataOut.NACF+2*dataOut.IBITS+2):
6407 6407
6408 6408 dataOut.output_LP_integrated.real[0,j,0]-=anoise0 #lag0 ch0
6409 6409 dataOut.output_LP_integrated.real[1,j,0]-=anoise1 #lag1 ch0
6410 6410
6411 6411 for i in range(1,dataOut.NLAG): #remove cal data from certain lags
6412 6412 dataOut.output_LP_integrated.real[i,j,0]-=self.cal[i]
6413 6413 k=max(j,26) #constant power below range 26
6414 6414 self.powera[j]=dataOut.output_LP_integrated.real[0,k,0]
6415 6415
6416 6416 ## examine drifts here - based on 60 'indep.' estimates
6417 6417 #print(numpy.sum(self.powera))
6418 6418 #exit(1)
6419 6419 #nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint*10
6420 6420 nis = dataOut.nis
6421 6421 #print("nis",nis)
6422 6422 alpha=beta=delta=0.0
6423 6423 nest=0
6424 6424 gamma=3.0/(2.0*numpy.pi*dataOut.lags_LP[1]*1.0e-3)
6425 6425 beta=gamma*(math.atan2(dataOut.output_LP_integrated.imag[14,0,2],dataOut.output_LP_integrated.real[14,0,2])-math.atan2(dataOut.output_LP_integrated.imag[1,0,2],dataOut.output_LP_integrated.real[1,0,2]))/13.0
6426 6426 #print(gamma,beta)
6427 6427 #exit(1)
6428 6428 for i in range(1,3):
6429 6429 gamma=3.0/(2.0*numpy.pi*dataOut.lags_LP[i]*1.0e-3)
6430 6430 #print("gamma",gamma)
6431 6431 for j in range(34,44):
6432 6432 rho2=numpy.abs(dataOut.output_LP_integrated[i,j,0])/numpy.abs(dataOut.output_LP_integrated[0,j,0])
6433 6433 dataOut.dphi2=(1.0/rho2-1.0)/(float(2*nis))
6434 6434 dataOut.dphi2*=gamma**2
6435 6435 pest=gamma*math.atan(dataOut.output_LP_integrated.imag[i,j,0]/dataOut.output_LP_integrated.real[i,j,0])
6436 6436 #print("1",dataOut.output_LP_integrated.imag[i,j,0])
6437 6437 #print("2",dataOut.output_LP_integrated.real[i,j,0])
6438 6438 self.drift[nest]=pest
6439 6439 self.ddrift[nest]=dataOut.dphi2
6440 6440 self.rdrift[nest]=float(nest)
6441 6441 nest+=1
6442 6442
6443 6443 sorted(self.drift[:nest])
6444 6444
6445 6445 #print(dataOut.dphi2)
6446 6446 #exit(1)
6447 6447
6448 6448 for j in range(int(nest/4),int(3*nest/4)):
6449 6449 #i=int(self.rdrift[j])
6450 6450 alpha+=self.drift[j]/self.ddrift[j]
6451 6451 delta+=1.0/self.ddrift[j]
6452 6452
6453 6453 alpha/=delta
6454 6454 delta=1./numpy.sqrt(delta)
6455 6455 vdrift=alpha-beta
6456 6456 dvdrift=delta
6457 6457
6458 6458 #need to develop estimate of complete density profile using all
6459 6459 #available data
6460 6460
6461 6461 #estimate sample variances for long-pulse power profile
6462 6462
6463 6463 #nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint
6464 6464 nis = dataOut.nis/10
6465 6465 #print("nis",nis)
6466 6466
6467 6467 self.sigma[:dataOut.NACF+2*dataOut.IBITS+2]=((anoise0+self.powera[:dataOut.NACF+2*dataOut.IBITS+2])**2)/float(nis)
6468 6468 #print(self.sigma)
6469 6469 #exit(1)
6470 6470 ioff=1
6471 6471
6472 6472 #deconvolve rectangular pulse shape from profile ==> powerb, perror
6473 6473
6474 6474
6475 6475 ############# START nnlswrap#############
6476 6476
6477 6477 if dataOut.ut_Faraday>14.0:
6478 6478 alpha_nnlswrap=20.0
6479 6479 else:
6480 6480 alpha_nnlswrap=30.0
6481 6481
6482 6482 range1_nnls=dataOut.NACF
6483 6483 range2_nnls=dataOut.NACF+dataOut.IBITS-1
6484 6484
6485 6485 g_nnlswrap=numpy.zeros((range1_nnls,range2_nnls),'float32')
6486 6486 a_nnlswrap=numpy.zeros((range2_nnls,range2_nnls),'float64')
6487 6487
6488 6488 for i in range(range1_nnls):
6489 6489 for j in range(range2_nnls):
6490 6490 if j>=i and j<i+dataOut.IBITS:
6491 6491 g_nnlswrap[i,j]=1.0
6492 6492 else:
6493 6493 g_nnlswrap[i,j]=0.0
6494 6494
6495 6495 a_nnlswrap[:]=numpy.matmul(numpy.transpose(g_nnlswrap),g_nnlswrap)
6496 6496
6497 6497 numpy.fill_diagonal(a_nnlswrap,a_nnlswrap.diagonal()+alpha_nnlswrap**2)
6498 6498
6499 6499 #ERROR ANALYSIS#
6500 6500
6501 6501 self.perror[:range2_nnls]=0.0
6502 6502 self.perror[:range2_nnls]=numpy.matmul(1./(self.sigma[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff]),g_nnlswrap**2)
6503 6503 self.perror[:range1_nnls]+=(alpha_nnlswrap**2)/(self.sigma[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff])
6504 6504 self.perror[:range2_nnls]=1.00/self.perror[:range2_nnls]
6505 6505
6506 6506 b_nnlswrap=numpy.zeros(range2_nnls,'float64')
6507 6507 b_nnlswrap[:]=numpy.matmul(self.powera[dataOut.IBITS+ioff:range1_nnls+dataOut.IBITS+ioff],g_nnlswrap)
6508 6508
6509 6509 x_nnlswrap=numpy.zeros(range2_nnls,'float64')
6510 6510 x_nnlswrap[:]=nnls(a_nnlswrap,b_nnlswrap)[0]
6511 6511
6512 6512 self.powerb[:range2_nnls]=x_nnlswrap
6513 6513 #print(self.powerb[40])
6514 6514 #print(self.powerb[66])
6515 6515 #exit(1)
6516 6516 #############END nnlswrap#############
6517 6517 #print(numpy.sum(numpy.sqrt(self.perror[0:dataOut.NACF])))
6518 6518 #print(self.powerb[0:dataOut.NACF])
6519 6519 #exit(1)
6520 6520 #estimate relative error for deconvolved profile (scaling irrelevant)
6521 6521 #print(dataOut.NACF)
6522 6522 dataOut.ene[0:dataOut.NACF]=numpy.sqrt(self.perror[0:dataOut.NACF])/self.powerb[0:dataOut.NACF]
6523 6523 #print(numpy.sum(dataOut.ene))
6524 6524 #exit(1)
6525 6525 aux=0
6526 6526
6527 6527 for i in range(dataOut.IBITS,dataOut.NACF):
6528 6528 self.dpulse[i]=self.lpulse[i]=0.0
6529 6529 for j in range(dataOut.IBITS):
6530 6530 k=int(i-j)
6531 6531 if k<36-aux and k>16:
6532 6532 self.dpulse[i]+=dataOut.ph2[k]/dataOut.h2[k]
6533 6533 elif k>=36-aux:
6534 6534 self.lpulse[i]+=self.powerb[k]
6535 6535 self.lagp[i]=self.powera[i]
6536 6536
6537 6537 #find scale factor that best merges profiles
6538 6538
6539 6539 qi=sum(self.dpulse[32:dataOut.NACF]**2/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6540 6540 ri=sum((self.dpulse[32:dataOut.NACF]*self.lpulse[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6541 6541 si=sum((self.dpulse[32:dataOut.NACF]*self.lagp[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6542 6542 ui=sum(self.lpulse[32:dataOut.NACF]**2/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6543 6543 vi=sum((self.lpulse[32:dataOut.NACF]*self.lagp[32:dataOut.NACF])/(self.lagp[32:dataOut.NACF]+anoise0)**2)
6544 6544
6545 6545 alpha=(si*ui-vi*ri)/(qi*ui-ri*ri)
6546 6546 beta=(qi*vi-ri*si)/(qi*ui-ri*ri)
6547 6547
6548 6548 #form density profile estimate, merging rescaled power profiles
6549 6549 #print(dataOut.h2)
6550 6550 #print(numpy.sum(alpha))
6551 6551 #print(numpy.sum(dataOut.ph2))
6552 6552 self.powerb[16:36-aux]=alpha*dataOut.ph2[16:36-aux]/dataOut.h2[16:36-aux]
6553 6553 self.powerb[36-aux:dataOut.NACF]*=beta
6554 6554
6555 6555 #form Ne estimate, fill in error estimate at low altitudes
6556 6556
6557 6557 dataOut.ene[0:36-aux]=dataOut.sdp2[0:36-aux]/dataOut.ph2[0:36-aux]
6558 6558 dataOut.ne[:dataOut.NACF]=self.powerb[:dataOut.NACF]*dataOut.h2[:dataOut.NACF]/alpha
6559 6559 #print(numpy.sum(self.powerb))
6560 6560 #print(numpy.sum(dataOut.ene))
6561 6561 #print(numpy.sum(dataOut.ne))
6562 6562 #exit(1)
6563 6563 #now do error propagation: store zero lag error covariance in u
6564 6564
6565 6565 nis=dataOut.NSCAN*dataOut.NAVG*dataOut.nint/1 # DLH serious debris removal
6566 6566
6567 6567 for i in range(dataOut.NACF):
6568 6568 for j in range(i,dataOut.NACF):
6569 6569 if j-i>=dataOut.IBITS:
6570 6570 self.u[i,j]=0.0
6571 6571 else:
6572 6572 self.u[i,j]=dataOut.output_LP_integrated.real[j-i,i,0]**2/float(nis)
6573 6573 self.u[i,j]*=(anoise0+dataOut.output_LP_integrated.real[0,i,0])/dataOut.output_LP_integrated.real[0,i,0]
6574 6574 self.u[i,j]*=(anoise0+dataOut.output_LP_integrated.real[0,j,0])/dataOut.output_LP_integrated.real[0,j,0]
6575 6575
6576 6576 self.u[j,i]=self.u[i,j]
6577 6577
6578 6578 #now error analyis for lag product matrix (diag), place in acf_err
6579 6579
6580 6580 for i in range(dataOut.NACF):
6581 6581 for j in range(dataOut.IBITS):
6582 6582 if j==0:
6583 6583 dataOut.errors[0,i]=numpy.sqrt(self.u[i,i])
6584 6584 else:
6585 6585 dataOut.errors[j,i]=numpy.sqrt(((dataOut.output_LP_integrated.real[0,i,0]+anoise0)*(dataOut.output_LP_integrated.real[0,i+j,0]+anoise0)+dataOut.output_LP_integrated.real[j,i,0]**2)/float(2*nis))
6586 6586
6587 6587 print("Success")
6588 6588 with suppress_stdout_stderr():
6589 6589 #pass
6590 6590 full_profile_profile.profile(numpy.transpose(dataOut.output_LP_integrated,(2,1,0)),numpy.transpose(dataOut.errors),self.powerb,dataOut.ne,dataOut.lags_LP,dataOut.thb,dataOut.bfm,dataOut.te,dataOut.ete,dataOut.ti,dataOut.eti,dataOut.ph,dataOut.eph,dataOut.phe,dataOut.ephe,dataOut.range1,dataOut.ut,dataOut.NACF,dataOut.fit_array_real,dataOut.status,dataOut.NRANGE,dataOut.IBITS)
6591 6591
6592 6592 if dataOut.status>=3.5:
6593 6593 dataOut.te[:]=numpy.nan
6594 6594 dataOut.ete[:]=numpy.nan
6595 6595 dataOut.ti[:]=numpy.nan
6596 6596 dataOut.eti[:]=numpy.nan
6597 6597 dataOut.ph[:]=numpy.nan
6598 6598 dataOut.eph[:]=numpy.nan
6599 6599 dataOut.phe[:]=numpy.nan
6600 6600 dataOut.ephe[:]=numpy.nan
6601 6601
6602 6602 return dataOut
6603 6603
6604 6604 class PulsePairVoltage(Operation):
6605 6605 '''
6606 6606 Function PulsePair(Signal Power, Velocity)
6607 6607 The real component of Lag[0] provides Intensity Information
6608 6608 The imag component of Lag[1] Phase provides Velocity Information
6609 6609
6610 6610 Configuration Parameters:
6611 6611 nPRF = Number of Several PRF
6612 6612 theta = Degree Azimuth angel Boundaries
6613 6613
6614 6614 Input:
6615 6615 self.dataOut
6616 6616 lag[N]
6617 6617 Affected:
6618 6618 self.dataOut.spc
6619 6619 '''
6620 6620 isConfig = False
6621 6621 __profIndex = 0
6622 6622 __initime = None
6623 6623 __lastdatatime = None
6624 6624 __buffer = None
6625 6625 noise = None
6626 6626 __dataReady = False
6627 6627 n = None
6628 6628 __nch = 0
6629 6629 __nHeis = 0
6630 6630 removeDC = False
6631 6631 ipp = None
6632 6632 lambda_ = 0
6633 6633
6634 6634 def __init__(self, **kwargs):
6635 6635 Operation.__init__(self, **kwargs)
6636 6636
6637 6637 def setup(self, dataOut, n=None, removeDC=False):
6638 6638 '''
6639 6639 n= Numero de PRF's de entrada
6640 6640 '''
6641 6641 self.__initime = None
6642 6642 self.__lastdatatime = 0
6643 6643 self.__dataReady = False
6644 6644 self.__buffer = 0
6645 6645 self.__profIndex = 0
6646 6646 self.noise = None
6647 6647 self.__nch = dataOut.nChannels
6648 6648 self.__nHeis = dataOut.nHeights
6649 6649 self.removeDC = removeDC
6650 6650 self.lambda_ = 3.0e8 / (9345.0e6)
6651 6651 self.ippSec = dataOut.ippSeconds
6652 6652 self.nCohInt = dataOut.nCohInt
6653 6653 print("IPPseconds", dataOut.ippSeconds)
6654 6654
6655 6655 print("ELVALOR DE n es:", n)
6656 6656 if n == None:
6657 6657 raise ValueError("n should be specified.")
6658 6658
6659 6659 if n != None:
6660 6660 if n < 2:
6661 6661 raise ValueError("n should be greater than 2")
6662 6662
6663 6663 self.n = n
6664 6664 self.__nProf = n
6665 6665
6666 6666 self.__buffer = numpy.zeros((dataOut.nChannels,
6667 6667 n,
6668 6668 dataOut.nHeights),
6669 6669 dtype='complex')
6670 6670
6671 6671 def putData(self, data):
6672 6672 '''
6673 6673 Add a profile to he __buffer and increase in one the __profiel Index
6674 6674 '''
6675 6675 self.__buffer[:, self.__profIndex, :] = data
6676 6676 self.__profIndex += 1
6677 6677 return
6678 6678
6679 6679 def pushData(self, dataOut):
6680 6680 '''
6681 6681 Return the PULSEPAIR and the profiles used in the operation
6682 6682 Affected : self.__profileIndex
6683 6683 '''
6684 6684 #----------------- Remove DC-----------------------------------
6685 6685 if self.removeDC == True:
6686 6686 mean = numpy.mean(self.__buffer, 1)
6687 6687 tmp = mean.reshape(self.__nch, 1, self.__nHeis)
6688 6688 dc = numpy.tile(tmp, [1, self.__nProf, 1])
6689 6689 self.__buffer = self.__buffer - dc
6690 6690 #------------------Calculo de Potencia ------------------------
6691 6691 pair0 = self.__buffer * numpy.conj(self.__buffer)
6692 6692 pair0 = pair0.real
6693 6693 lag_0 = numpy.sum(pair0, 1)
6694 6694 #------------------Calculo de Ruido x canal--------------------
6695 6695 self.noise = numpy.zeros(self.__nch)
6696 6696 for i in range(self.__nch):
6697 6697 daux = numpy.sort(pair0[i, :, :], axis=None)
6698 6698 self.noise[i] = hildebrand_sekhon(daux , self.nCohInt)
6699 6699
6700 6700 self.noise = self.noise.reshape(self.__nch, 1)
6701 6701 self.noise = numpy.tile(self.noise, [1, self.__nHeis])
6702 6702 noise_buffer = self.noise.reshape(self.__nch, 1, self.__nHeis)
6703 6703 noise_buffer = numpy.tile(noise_buffer, [1, self.__nProf, 1])
6704 6704 #------------------ Potencia recibida= P , Potencia senal = S , Ruido= N--
6705 6705 #------------------ P= S+N ,P=lag_0/N ---------------------------------
6706 6706 #-------------------- Power --------------------------------------------------
6707 6707 data_power = lag_0 / (self.n * self.nCohInt)
6708 6708 #------------------ Senal ---------------------------------------------------
6709 6709 data_intensity = pair0 - noise_buffer
6710 6710 data_intensity = numpy.sum(data_intensity, axis=1) * (self.n * self.nCohInt) # *self.nCohInt)
6711 6711 # data_intensity = (lag_0-self.noise*self.n)*(self.n*self.nCohInt)
6712 6712 for i in range(self.__nch):
6713 6713 for j in range(self.__nHeis):
6714 6714 if data_intensity[i][j] < 0:
6715 6715 data_intensity[i][j] = numpy.min(numpy.absolute(data_intensity[i][j]))
6716 6716
6717 6717 #----------------- Calculo de Frecuencia y Velocidad doppler--------
6718 6718 pair1 = self.__buffer[:, :-1, :] * numpy.conjugate(self.__buffer[:, 1:, :])
6719 6719 lag_1 = numpy.sum(pair1, 1)
6720 6720 data_freq = (-1 / (2.0 * math.pi * self.ippSec * self.nCohInt)) * numpy.angle(lag_1)
6721 6721 data_velocity = (self.lambda_ / 2.0) * data_freq
6722 6722
6723 6723 #---------------- Potencia promedio estimada de la Senal-----------
6724 6724 lag_0 = lag_0 / self.n
6725 6725 S = lag_0 - self.noise
6726 6726
6727 6727 #---------------- Frecuencia Doppler promedio ---------------------
6728 6728 lag_1 = lag_1 / (self.n - 1)
6729 6729 R1 = numpy.abs(lag_1)
6730 6730
6731 6731 #---------------- Calculo del SNR----------------------------------
6732 6732 data_snrPP = S / self.noise
6733 6733 for i in range(self.__nch):
6734 6734 for j in range(self.__nHeis):
6735 6735 if data_snrPP[i][j] < 1.e-20:
6736 6736 data_snrPP[i][j] = 1.e-20
6737 6737
6738 6738 #----------------- Calculo del ancho espectral ----------------------
6739 6739 L = S / R1
6740 6740 L = numpy.where(L < 0, 1, L)
6741 6741 L = numpy.log(L)
6742 6742 tmp = numpy.sqrt(numpy.absolute(L))
6743 6743 data_specwidth = (self.lambda_ / (2 * math.sqrt(2) * math.pi * self.ippSec * self.nCohInt)) * tmp * numpy.sign(L)
6744 6744 n = self.__profIndex
6745 6745
6746 6746 self.__buffer = numpy.zeros((self.__nch, self.__nProf, self.__nHeis), dtype='complex')
6747 6747 self.__profIndex = 0
6748 6748 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth, n
6749 6749
6750 6750
6751 6751 def pulsePairbyProfiles(self, dataOut):
6752 6752
6753 6753 self.__dataReady = False
6754 6754 data_power = None
6755 6755 data_intensity = None
6756 6756 data_velocity = None
6757 6757 data_specwidth = None
6758 6758 data_snrPP = None
6759 6759 self.putData(data=dataOut.data)
6760 6760 if self.__profIndex == self.n:
6761 6761 data_power, data_intensity, data_velocity, data_snrPP, data_specwidth, n = self.pushData(dataOut=dataOut)
6762 6762 self.__dataReady = True
6763 6763
6764 6764 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth
6765 6765
6766 6766
6767 6767 def pulsePairOp(self, dataOut, datatime=None):
6768 6768
6769 6769 if self.__initime == None:
6770 6770 self.__initime = datatime
6771 6771 data_power, data_intensity, data_velocity, data_snrPP, data_specwidth = self.pulsePairbyProfiles(dataOut)
6772 6772 self.__lastdatatime = datatime
6773 6773
6774 6774 if data_power is None:
6775 6775 return None, None, None, None, None, None
6776 6776
6777 6777 avgdatatime = self.__initime
6778 6778 deltatime = datatime - self.__lastdatatime
6779 6779 self.__initime = datatime
6780 6780
6781 6781 return data_power, data_intensity, data_velocity, data_snrPP, data_specwidth, avgdatatime
6782 6782
6783 6783 def run(self, dataOut, n=None, removeDC=False, overlapping=False, **kwargs):
6784 6784
6785 6785 if not self.isConfig:
6786 6786 self.setup(dataOut=dataOut, n=n , removeDC=removeDC , **kwargs)
6787 6787 self.isConfig = True
6788 6788 data_power, data_intensity, data_velocity, data_snrPP, data_specwidth, avgdatatime = self.pulsePairOp(dataOut, dataOut.utctime)
6789 6789 dataOut.flagNoData = True
6790 6790
6791 6791 if self.__dataReady:
6792 6792 dataOut.nCohInt *= self.n
6793 6793 dataOut.dataPP_POW = data_intensity # S
6794 6794 dataOut.dataPP_POWER = data_power # P
6795 6795 dataOut.dataPP_DOP = data_velocity
6796 6796 dataOut.dataPP_SNR = data_snrPP
6797 6797 dataOut.dataPP_WIDTH = data_specwidth
6798 6798 dataOut.PRFbyAngle = self.n # numero de PRF*cada angulo rotado que equivale a un tiempo.
6799 6799 dataOut.utctime = avgdatatime
6800 6800 dataOut.flagNoData = False
6801 6801 return dataOut
6802 6802
6803 6803
6804 6804
6805 6805 # import collections
6806 6806 # from scipy.stats import mode
6807 6807 #
6808 6808 # class Synchronize(Operation):
6809 6809 #
6810 6810 # isConfig = False
6811 6811 # __profIndex = 0
6812 6812 #
6813 6813 # def __init__(self, **kwargs):
6814 6814 #
6815 6815 # Operation.__init__(self, **kwargs)
6816 6816 # # self.isConfig = False
6817 6817 # self.__powBuffer = None
6818 6818 # self.__startIndex = 0
6819 6819 # self.__pulseFound = False
6820 6820 #
6821 6821 # def __findTxPulse(self, dataOut, channel=0, pulse_with = None):
6822 6822 #
6823 6823 # #Read data
6824 6824 #
6825 6825 # powerdB = dataOut.getPower(channel = channel)
6826 6826 # noisedB = dataOut.getNoise(channel = channel)[0]
6827 6827 #
6828 6828 # self.__powBuffer.extend(powerdB.flatten())
6829 6829 #
6830 6830 # dataArray = numpy.array(self.__powBuffer)
6831 6831 #
6832 6832 # filteredPower = numpy.correlate(dataArray, dataArray[0:self.__nSamples], "same")
6833 6833 #
6834 6834 # maxValue = numpy.nanmax(filteredPower)
6835 6835 #
6836 6836 # if maxValue < noisedB + 10:
6837 6837 # #No se encuentra ningun pulso de transmision
6838 6838 # return None
6839 6839 #
6840 6840 # maxValuesIndex = numpy.where(filteredPower > maxValue - 0.1*abs(maxValue))[0]
6841 6841 #
6842 6842 # if len(maxValuesIndex) < 2:
6843 6843 # #Solo se encontro un solo pulso de transmision de un baudio, esperando por el siguiente TX
6844 6844 # return None
6845 6845 #
6846 6846 # phasedMaxValuesIndex = maxValuesIndex - self.__nSamples
6847 6847 #
6848 6848 # #Seleccionar solo valores con un espaciamiento de nSamples
6849 6849 # pulseIndex = numpy.intersect1d(maxValuesIndex, phasedMaxValuesIndex)
6850 6850 #
6851 6851 # if len(pulseIndex) < 2:
6852 6852 # #Solo se encontro un pulso de transmision con ancho mayor a 1
6853 6853 # return None
6854 6854 #
6855 6855 # spacing = pulseIndex[1:] - pulseIndex[:-1]
6856 6856 #
6857 6857 # #remover senales que se distancien menos de 10 unidades o muestras
6858 6858 # #(No deberian existir IPP menor a 10 unidades)
6859 6859 #
6860 6860 # realIndex = numpy.where(spacing > 10 )[0]
6861 6861 #
6862 6862 # if len(realIndex) < 2:
6863 6863 # #Solo se encontro un pulso de transmision con ancho mayor a 1
6864 6864 # return None
6865 6865 #
6866 6866 # #Eliminar pulsos anchos (deja solo la diferencia entre IPPs)
6867 6867 # realPulseIndex = pulseIndex[realIndex]
6868 6868 #
6869 6869 # period = mode(realPulseIndex[1:] - realPulseIndex[:-1])[0][0]
6870 6870 #
6871 6871 # print "IPP = %d samples" %period
6872 6872 #
6873 6873 # self.__newNSamples = dataOut.nHeights #int(period)
6874 6874 # self.__startIndex = int(realPulseIndex[0])
6875 6875 #
6876 6876 # return 1
6877 6877 #
6878 6878 #
6879 6879 # def setup(self, nSamples, nChannels, buffer_size = 4):
6880 6880 #
6881 6881 # self.__powBuffer = collections.deque(numpy.zeros( buffer_size*nSamples,dtype=numpy.float),
6882 6882 # maxlen = buffer_size*nSamples)
6883 6883 #
6884 6884 # bufferList = []
6885 6885 #
6886 6886 # for i in range(nChannels):
6887 6887 # bufferByChannel = collections.deque(numpy.zeros( buffer_size*nSamples, dtype=complex) + numpy.NAN,
6888 6888 # maxlen = buffer_size*nSamples)
6889 6889 #
6890 6890 # bufferList.append(bufferByChannel)
6891 6891 #
6892 6892 # self.__nSamples = nSamples
6893 6893 # self.__nChannels = nChannels
6894 6894 # self.__bufferList = bufferList
6895 6895 #
6896 6896 # def run(self, dataOut, channel = 0):
6897 6897 #
6898 6898 # if not self.isConfig:
6899 6899 # nSamples = dataOut.nHeights
6900 6900 # nChannels = dataOut.nChannels
6901 6901 # self.setup(nSamples, nChannels)
6902 6902 # self.isConfig = True
6903 6903 #
6904 6904 # #Append new data to internal buffer
6905 6905 # for thisChannel in range(self.__nChannels):
6906 6906 # bufferByChannel = self.__bufferList[thisChannel]
6907 6907 # bufferByChannel.extend(dataOut.data[thisChannel])
6908 6908 #
6909 6909 # if self.__pulseFound:
6910 6910 # self.__startIndex -= self.__nSamples
6911 6911 #
6912 6912 # #Finding Tx Pulse
6913 6913 # if not self.__pulseFound:
6914 6914 # indexFound = self.__findTxPulse(dataOut, channel)
6915 6915 #
6916 6916 # if indexFound == None:
6917 6917 # dataOut.flagNoData = True
6918 6918 # return
6919 6919 #
6920 6920 # self.__arrayBuffer = numpy.zeros((self.__nChannels, self.__newNSamples), dtype = complex)
6921 6921 # self.__pulseFound = True
6922 6922 # self.__startIndex = indexFound
6923 6923 #
6924 6924 # #If pulse was found ...
6925 6925 # for thisChannel in range(self.__nChannels):
6926 6926 # bufferByChannel = self.__bufferList[thisChannel]
6927 6927 # #print self.__startIndex
6928 6928 # x = numpy.array(bufferByChannel)
6929 6929 # self.__arrayBuffer[thisChannel] = x[self.__startIndex:self.__startIndex+self.__newNSamples]
6930 6930 #
6931 6931 # deltaHeight = dataOut.heightList[1] - dataOut.heightList[0]
6932 6932 # dataOut.heightList = numpy.arange(self.__newNSamples)*deltaHeight
6933 6933 # # dataOut.ippSeconds = (self.__newNSamples / deltaHeight)/1e6
6934 6934 #
6935 6935 # dataOut.data = self.__arrayBuffer
6936 6936 #
6937 6937 # self.__startIndex += self.__newNSamples
6938 6938 #
6939 6939 # return
General Comments 0
You need to be logged in to leave comments. Login now