-
Notifications
You must be signed in to change notification settings - Fork 0
/
tmUtils.py
1190 lines (973 loc) · 41 KB
/
tmUtils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utilities for getting TMCDB data and plotting time-series data.
2013-09-16 thunter: added support for vector quantities, such as IFProc0 GAINS, including showing
the requested index in the title and in the plot filename
2013-01-08 pmerino: changes for the definitive structure of directories of monitordata.
changes on: def get_root_url_for_date(date) and def get_root_url_for_curl(date)
2012-12-27 pmerino: changes for the new monitordata URL
2011-04-11 tsawada: change the host name of the TMCDB web site (R8.0).
2011-01-25 tsawada: change the directory name in the TMCDB web site (R8.0).
2010-12-30 tsawada: bug fixes
2010-06-21 tsawada: cope with the change of the directory name in the TMCDB
web site.
2010-05-27 tsawada: changed symbol size (removed 'ms=0.5');
changed default 'removefile' to False in some methods;
added options to remove discontinuities and outliers.
2010-05-18 tsawada: added remove_outlier method
2010-05-17 tsawada: added remove_discontinuity method;
added get_available_antennas_on_date method;
added 'showxticklabels' option in some methods.
2010-05-12 tsawada: added a method to resample data;
show legends if 'label' option is given.
2010-05-11 tsawada: fixed a bug that 'ylabel' option was ignored
in some methods.
2010-04-30 tsawada
$Id: tmUtils.py,v 1.49 2015/10/15 20:47:29 thunter Exp $
"""
import os
import math
import datetime
import urllib2
import re
import pylab as pl
import numpy as np
allAntennas = ['DV%02d'%x for x in range(1,26)] + ['DA%02d'%x for x in range(40,66)] + \
['PM%02d'%x for x in range(1,5)] + ['CM%02d'%x for x in range(1,13)]
def get_host_name():
"""
Returns the hostname
"""
hostname = 'http://monitordata.osf.alma.cl'
return hostname
def get_root_url_for_date(date):
"""
Returns the root URL of the TMCDB web I/F for the given date.
The argument date should be an ISO-8601 date string (YYYY-MM-DD).
The returned URL already contains the date.
"""
year = date[:4]
mm = date[5:7]
hostname = get_host_name()
return "%s/index.php?dir=%s/%s/%s/" % (hostname, year, mm, date)
def get_root_url_for_curl(date):
"""
Returns the root URL of the new monitordata TMCDB web I/F for the given date.
The argument date should be an ISO-8601 date string (YYYY-MM-DD).
The returned URL already contains the date.
"""
year = date[:4]
mm = date[5:7]
hostname = get_host_name()
return "%s/monitordata/%s/%s/%s/" % (hostname, year, mm, date)
def get_available_antennas_on_date(date, device=None):
"""
Return a list of antennas that were available on the date.
The argument date should be an ISO-8601 date string (YYYY-MM-DD).
This method searchs "CONTROL_XX99_" in TMCDB directory list via HTTP.
If no antenna matched, returns an empty list.
"""
rooturl = get_root_url_for_date(date)
try:
furl = urllib2.urlopen(rooturl)
except:
print 'Failed to open URL %s' % rooturl
raise
if device == None:
regexp = 'CONTROL_([A-Z][A-Z][0-9][0-9])_'
else:
regexp = 'CONTROL_([A-Z][A-Z][0-9][0-9])_%s' % device
result = []
for line in furl:
mount = re.search(regexp, line)
if mount != None:
result.append(mount.group(1))
if len(result) > 0:
result = list(set(result))
result.sort()
return result
def get_available_monitorpoints_in_device_on_date(date, antenna, device):
"""
Return a list of MPs that were available on the date for a certain device.
The argument date should be an ISO-8601 date string (YYYY-MM-DD).
This method searchs "CONTROL_XX99_" in TMCDB directory list via HTTP.
If no antenna matched, returns an empty list.
"""
rooturl = get_root_url_for_date(date)
targeturl = 'CONTROL_%s_%s' % (antenna, device)
completeurl = '%s/%s' % (rooturl, targeturl)
try:
furl = urllib2.urlopen(completeurl)
except:
print 'Failed to open URL %s' % completeurl
raise
regexp = 'CONTROL_([A-Z][A-Z][0-9][0-9])'
regexp = 'href=".*txt'
result = []
for line in furl:
mount = re.search(regexp, line)
if mount != None:
monpoint_name=mount.group(0).split('.txt')[0].split('download=')[1]
result.append(monpoint_name)
if len(result) > 0:
result = list(set(result))
result.sort()
return result
def retrieve_daily_tmc_data_file(antenna, device, monitorpoint, date,
verbose = True, outpath='./'):
"""
Retrieve TMC monitor data via HTTP.
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
date = '2010-04-24' # ISO-8601 date or datetime string
outpath = set this if you don't want to write the result to the working directory
Return the name of the file if succeeded, otherwise '_CURL_FAILED_'.
"""
isodate = get_datetime_from_isodatetime(date).date().strftime('%Y-%m-%d')
inputdate = datetime.datetime.strptime(date, '%Y-%m-%d')
rooturl = get_root_url_for_curl(date)
extension = 'txt'
targeturl = 'CONTROL_%s_%s/%s.%s' % (antenna, device, monitorpoint, extension)
completeurl = '%s/%s' % (rooturl, targeturl)
outfile = '%s%s_%s_%s_%s.%s' % (outpath,isodate, antenna, device, monitorpoint, extension)
if verbose == True: print date, rooturl,targeturl,completeurl
exitcode = os.system('curl -s -f %s -o %s' % (completeurl, outfile))
if exitcode == 0:
return outfile
else:
extension = 'txt.bz2'
targeturl = 'CONTROL_%s_%s/%s.%s' % (antenna, device, monitorpoint, extension)
completeurl = '%s/%s' % (rooturl, targeturl)
outfile = '%s%s_%s_%s_%s.%s' % (outpath,isodate, antenna, device, monitorpoint, extension)
if verbose == True: print date, rooturl,targeturl,completeurl
exitcode = os.system('curl -s -f %s -o %s' % (completeurl, outfile))
if exitcode == 0:
os.system('bunzip2 %s' %outfile)
outfile = outfile[0:-4]
return outfile
else:
if verbose == True: print 'Retrieval failed. Check permissions on directory and set outpath if necessary'
return '_CURL_FAILED_'
def retrieve_daily_tmc_data_file_name_only(antenna, device, monitorpoint,
date, outpath='./'):
"""
Retrieve name of file that would be created by retrieve_daily_tmc_data_file()
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
date = '2010-04-24' # ISO-8601 date or datetime string
outpath = set this if you don't want to write the result to the working directory
Return the name of the file if succeeded, otherwise '_CURL_FAILED_'.
"""
isodate = get_datetime_from_isodatetime(date).date().strftime('%Y-%m-%d')
inputdate = datetime.datetime.strptime(date, '%Y-%m-%d')
rooturl = get_root_url_for_curl(date)
extension = 'txt'
targeturl = 'CONTROL_%s_%s/%s.%s' % (antenna, device, monitorpoint, extension)
completeurl = '%s/%s' % (rooturl, targeturl)
outfile = '%s%s_%s_%s_%s.%s' % (outpath,isodate, antenna, device, monitorpoint, extension)
return(outfile)
def get_datetime_from_isodatetime(isodatetime):
"""
Return a datetime.datetime object for given ISO-8601 date/datetime string.
The argument isodatetime should be in YYYY-MM-DDThh:mm:ss or YYYY-MM-DD
(in the latter case, 00:00:00 is assumed).
Return 0001-01-01T00:00:00 if an invalid string is given.
"""
datelist = isodatetime.split('T')
if len(datelist) == 1: # date only
timelist = [0, 0, 0]
datelist = datelist[0].split('-')
elif len(datelist) == 2: # date and time
timelist = datelist[1].split(':')
datelist = datelist[0].split('-')
else:
print "Date %s is invalid." % isodatetime
return datetime.date(1, 1, 1)
if (len(datelist) == 3) and (len(timelist) == 3):
microsec = int(1e6 * (float(timelist[2]) - int(float(timelist[2]))))
timelist[2] = int(float(timelist[2]))
return datetime.datetime( \
int(datelist[0]), int(datelist[1]), int(datelist[2]), \
int(timelist[0]), int(timelist[1]), int(timelist[2]), microsec )
else:
print "Date '%s' is invalid." % isodatetime
return datetime.date(1, 1, 1)
def retrieve_tmc_data_files(antenna, device, monitorpoint, startdate, enddate,
verbose = True, outpath='./'):
"""
Retrieve TMC monitor data files for given antenna, device, and period.
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
startdate = '2010-04-24' # ISO-8601 date or datetime string
enddate = '2010-04-24' # ISO-8601 date or datetime string
Return a list of filenames.
"""
sdate = get_datetime_from_isodatetime(startdate).date()
edate = get_datetime_from_isodatetime(enddate).date()
y1900 = datetime.date(1900, 1, 1)
if ((sdate-y1900).days < 0) or ((edate-y1900).days < 0):
raise ValueError, "Startdate and/or enddate are invalid."
if ((edate-sdate).days < 0):
raise ValueError, "Startdate is later than enddate."
ndays = (edate-sdate).days + 1
files = []
for i in range(ndays):
targetdate = sdate + datetime.timedelta(i)
filename = retrieve_daily_tmc_data_file( \
antenna=antenna, \
device=device, \
monitorpoint=monitorpoint, \
date=targetdate.strftime('%Y-%m-%d'),
verbose = verbose,
outpath=outpath)
if filename != '_CURL_FAILED_':
files.append(filename)
return files
def read_tmc_data_file(filename, removefile=False):
"""
Read given TMC data file.
Set removefile to False in order to keep files, otherwise removed.
Return is a dictionary of lists of datetime.datetime and float values:
{'datetime': [datetime], 'value': [value]}
"""
# import os
if not os.path.exists(filename):
raise Exception, ("File %s not found." % filename)
datetimelist = []
valuelist = []
for line in open(filename, 'r'):
if line[0] == '#':
continue
# (strdatetime, value) = line.split()
tokens = line.split()
dt = get_datetime_from_isodatetime(tokens[0])
# check that the date was valid
if dt == datetime.date(1,1,1):
continue
datetimelist.append(get_datetime_from_isodatetime(tokens[0]))
valuelist.append([float(x) for x in tokens[1:]])
if removefile:
os.system('rm %s' % filename)
return {'datetime': datetimelist, 'value': valuelist}
def get_tmc_data(antenna, device, monitorpoint, startdate, enddate, \
removefile=False, verbose = True, outpath='./'):
"""
Obtain monitor values recorded in TMCDB for given set of parameters.
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
startdate = '2010-04-24' # ISO-8601 date or datetime string
enddate = '2010-04-24' # ISO-8601 date or datetime string
removefile = False # optional: set True to delete files once read
Files are automatically retrieved via HTTP, read, and deleted.
Return is a dictionary of lists of datetime.datetime and float values:
{'datetime': [datetime], 'value': [value]}
"""
# import os
files = retrieve_tmc_data_files(antenna, device, monitorpoint, \
startdate, enddate, verbose = verbose , outpath=outpath)
if len(files) == 0:
raise Exception, "Failed to retrieve data files."
datetimelist = []
valuelist = []
for filename in files:
tmcdata = read_tmc_data_file(filename, removefile)
datetimelist += tmcdata['datetime']
valuelist += tmcdata['value']
return {'datetime': datetimelist, 'value': valuelist, 'files': files}
def show_time_series_in_subplot(subpl, datetimelist, datalist, \
startdatetime, enddatetime=None, yrange=None, ylabel=None, tickmark='.',label=None, \
title=None, showxticklabels=True, col='b', removediscontinuity=False, \
removeoutlier=False, index=0):
"""
Plot a time series of any data in a pylab.figure.subplot instance.
You need to create a subplot instance in advance by, e.g.:
import pylab as pl
plf = pl.figure()
subpl = plf.add_subplot(1, 1, 1)
and to show it:
plf.show()
The other parameters are something like:
datetimelist # a list of datetime.datetime instances
datalist # a list of numbers
startdate = '2010-04-24T00:00:00' # ISO-8601 date or datetime string
enddate = '2010-04-25T12:00:00' # ISO-8601 date or datetime (optional)
yrange = [-33000, 33000] # optional
ylabel = 'Value [unknown unit]' # optional
label = 'Legend of the symbol' # optional
title = 'Title of the plot' # optional
col = matplotlib color # optional
index = 0 # only necessary to set this for vector quantities (to choose which channel)
No return values.
"""
# import pylab as pl
if enddatetime == None:
enddatetime = startdatetime
trange = [get_datetime_from_isodatetime(startdatetime), \
get_datetime_from_isodatetime(enddatetime)]
# extend upper limit of datetime to 24:00 when needed
if ((trange[1]-trange[0]) <= datetime.timedelta(0)) or \
(len(enddatetime.split('T')) == 1):
trange[1] += datetime.timedelta(1)
# trim the time series in order to optimize y-axis range (and speed)
datetimearray = pl.array(datetimelist)
dataarray = pl.array(datalist)
try:
dataarray = dataarray[:,index]
except:
print "Invalid index (%d) for this monitor point. Using 0 instead."
dataarray = dataarray[:,0]
timeinrange = (((datetimearray-trange[0]) > datetime.timedelta(0)) & \
((datetimearray-trange[1]) < datetime.timedelta(0)))
thedata = dataarray[timeinrange]
# remove discontinuity and outliers
if removediscontinuity:
thedata = remove_discontinuity(thedata)
if removeoutlier:
thedata = remove_outlier(thedata)
subpl.plot_date(datetimearray[timeinrange], thedata, \
tickmark, ms=2.4, label=label, color=col)
if title != None:
subpl.set_title(title)
subpl.set_xticklabels( \
[litem.get_text() for litem in subpl.get_xticklabels()], \
fontsize='small', rotation=30, ha='right')
if ylabel == None:
subpl.set_ylabel('Value')
else:
subpl.set_ylabel(ylabel)
subpl.set_yticklabels( \
[litem.get_text() for litem in subpl.get_yticklabels()], \
fontsize='small')
subpl.set_xlim(trange)
if yrange != None:
subpl.set_ylim(yrange)
if (trange[1]-trange[0]) < datetime.timedelta(0, 300):
subpl.xaxis.set_major_formatter( \
pl.matplotlib.dates.DateFormatter('%m-%d %H:%M:%S'))
else:
subpl.xaxis.set_major_formatter( \
pl.matplotlib.dates.DateFormatter('%m-%d %H:%M'))
subpl.yaxis.set_major_formatter( \
pl.matplotlib.ticker.ScalarFormatter(useOffset=False))
# pl.matplotlib.ticker.ScalarFormatter('%f'))
if not showxticklabels:
subpl.set_xticklabels('')
if label != None:
subpl.legend(prop=pl.matplotlib.font_manager.FontProperties(size=10))
subpl.grid()
def show_monitor_data_in_subplot(subpl, antenna, device, monitorpoint, \
startdatetime, enddatetime=None, yrange=None, ylabel=None, tickmark='.',label=None, \
title=None, showxticklabels=True, col='b', removediscontinuity=False, \
removeoutlier=False, index=0):
"""
Plot a time series of TMC monitor data in a pylab.figure.subplot instance.
The TMC monitor data are retrieved, read, and removed automatically.
You need to create a subplot instance in advance by, e.g.:
import pylab as pl
plf = pl.figure()
subpl = plf.add_subplot(1, 1, 1)
and to show it:
plf.show()
The other parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
startdate = '2010-04-24T00:00:00' # ISO-8601 date or datetime string
enddate = '2010-04-25T12:00:00' # ISO-8601 date or datetime (optional)
yrange = [-33000, 33000] # optional
ylabel = 'Value [unknown unit]' # optional
label = 'Legend of the symbol' # optional
title = 'Title of the plot' # optional
col = a matplotlib color ('r','b'...) # optional
index = 0 # only necessary to set this for vector quantities (to choose which channel)
No return values.
"""
if enddatetime == None:
enddatetime = startdatetime
trange = [get_datetime_from_isodatetime(startdatetime), \
get_datetime_from_isodatetime(enddatetime)]
# range of dates for which the TMC data are obtained
startdate = trange[0].date().strftime('%Y-%m-%d')
enddate = trange[1].date().strftime('%Y-%m-%d')
tmcdata = get_tmc_data(antenna=antenna, device=device, \
monitorpoint=monitorpoint, startdate=startdate, enddate=enddate, \
removefile=True, verbose=False)
if title == None:
indices = len(tmcdata['value'][0])
if (indices > 1): # this is a vector of values, so show the index
title = '%s %s %s:%d/%d %s' % (antenna, device, monitorpoint, index, indices-1, startdate)
else:
title = '%s %s %s %s' % (antenna, device, monitorpoint, startdate)
if ylabel == None:
ylabel = '%s' % (monitorpoint)
show_time_series_in_subplot(subpl, \
tmcdata['datetime'], tmcdata['value'], \
startdatetime, enddatetime, yrange, ylabel, tickmark,label, title, \
showxticklabels, col,removediscontinuity, removeoutlier, index)
def check_for_time_gaps(antenna='DV01', device='IFProc0', monitorpoint='GAINS',
startdate=None, enddate=None, sigma=5,
showFirstGap=False, outpath='./',removefile=True, debug=False):
"""
Check for gaps in the time series data for a specific monitor point
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
startdate = '2010-04-24T00:00:00' # ISO-8601 date or datetime string (default=yesterday)
enddate = '2010-04-25T12:00:00' # ISO-8601 date or datetime (optional)
sigma: the factor by which an interval must me larger than the median to be declared a gap
"""
if (startdate==None):
startdate = datetime.date.today() + datetime.timedelta(-1)
startdate = startdate.strftime('%Y-%m-%dT00:00:00')
if (enddate==None):
enddate= datetime.date.today()+ datetime.timedelta(-1)
enddate=enddate.strftime('%Y-%m-%dT23:59:59')
fsrTimeList = check_for_FSR(startdate, enddate, verbose = False)
if debug: print fsrTimeList
try:
tmcdata = get_tmc_data(antenna=antenna, device=device, \
monitorpoint=monitorpoint, startdate=startdate, enddate=enddate, \
removefile=removefile, outpath=outpath, verbose=False)
unixtime = []
dateTimeList = tmcdata['datetime']
except:
return 1,[],100
for d in dateTimeList:
unixtime.append(int(d.strftime("%s")))
unixtime = np.array(unixtime)
successiveDifferences = unixtime[1:] - unixtime[:-1]
medianInterval = np.median(successiveDifferences)
madInterval = MAD(successiveDifferences)
print "Median Interval = %f seconds" % (medianInterval)
idelta = datetime.timedelta(seconds = 600)
gaps = []
for i in range(len(successiveDifferences)):
if (successiveDifferences[i] > medianInterval*sigma):
if debug: print "gap %d is at %s" % (len(gaps),str(dateTimeList[i]))
if (len(gaps) == 0 and showFirstGap):
print "First gap is at %s" % (str(dateTimeList[i]))
gaps.append(successiveDifferences[i])
# check if this belongs to an FSR
for fsrt in fsrTimeList:
if (dateTimeList[i] < fsrt+idelta) and (dateTimeList[i] > fsrt-idelta):
# this gap is within an FSR
if debug: print dateTimeList[i], fsrt+idelta, fsrt-idelta
gaps.pop(-1)
break
if (len(gaps) > 0):
print " %d gaps (not due to FSR) of median size = %f seconds" % (len(gaps), np.median(gaps))
percentLost = sum(gaps)*100.0/(unixtime[-1]-unixtime[0]+medianInterval)
print "Lost data = %f seconds = %f percent of total dataset" % (sum(gaps), percentLost)
else:
print "Found NO gaps in this time range"
percentLost = 0
return len(gaps), gaps, percentLost
def check_for_FSR(startdate, enddate, verbose = True):
# this assumes we are on osf-red or scops
print "### Querying SLT for list of FSR from %s to %s"%(startdate,enddate)
tmpfile1 = 'tmp_query1.txt'
owd = os.getcwd()
cmd = 'shiftlog-query -it OTHER -ib %s -ie %s -l OSF-AOS -t CMDLN -s \"FullSystemRestart\" > %s/%s '%(startdate, enddate,owd, tmpfile1)
if verbose: print cmd
#raw_input()
os.system(cmd)
fsrTimes = []
f = open(tmpfile1,'r')
lines = f.readlines()
f.close()
for line in lines:
if line.startswith('"CMDLN'):
sline = line.split('"')
fsr = sline[17]
x = fsr.split()
date = '%s %s %s %s %s'%(x[4],x[5],x[6],x[7],x[8])
if verbose: print 'FSR # %d at %s'%(len(fsrTimes),date)
fsrTimes.append(datetime.datetime.strptime(date,'%a %b %d %H:%M:%S %Y'))
print 'Found %d FSRs in this time range'%(len(fsrTimes))
os.system('rm -Rf tmp_query1.txt')
return fsrTimes
def plot_monitor_data_to_png(antenna, device, monitorpoint, \
startdatetime, enddatetime=None, yrange=None, showplot=False, \
removediscontinuity=False, removeoutlier=False, index=0):
"""
Plot a time series of TMC monitor data and save as a PNG image.
If you want to plot all the monitor points in a given antenna/device,
keep monitorpoint=''
Parameters are something like:
antenna = 'DV01'
device = 'LLC'
monitorpoint = 'CNTR_0'
startdate = '2010-04-24T00:00:00' # ISO-8601 date or datetime string
enddate = '2010-04-25T12:00:00' # ISO-8601 date or datetime (optional)
yrange = [-33000, 33000] # optional
showplot = True
index = 0 # only necessary to set this for vector quantities (to choose which channel)
Return the name of the PNG image.
"""
sdate = get_datetime_from_isodatetime( \
startdatetime).date().strftime('%Y-%m-%d')
if monitorpoint == '' :
monitorpointlist = \
get_available_monitorpoints_in_device_on_date \
(sdate, antenna, device)
else :
monitorpointlist = [monitorpoint]
outfiles = []
for mp in monitorpointlist:
print mp
plf = pl.figure()
subpl = plf.add_subplot(1, 1, 1)
show_monitor_data_in_subplot(subpl, antenna, device, mp, \
startdatetime, enddatetime, yrange, \
removediscontinuity=removediscontinuity, \
removeoutlier=removeoutlier, index=index)
# just determining output file name here ...
if os.path.exists('plots') == False:
os.system('mkdir plots')
startdate = get_datetime_from_isodatetime( \
startdatetime).date().strftime('%Y%m%d')
if enddatetime == None:
enddate = startdate
else:
enddate = get_datetime_from_isodatetime( \
enddatetime).date().strftime('%Y%m%d')
if (index == 0):
outfile = '%s-%s_%s_%s_%s.png' % \
(startdate, enddate, antenna, device, mp)
else:
outfile = '%s-%s_%s_%s_%d_%s.png' % \
(startdate, enddate, antenna, device, index, mp)
plf.savefig(outfile, form='png')
os.system('mv %s plots/' % outfile)
outfiles.append(outfile)
if showplot:
plf.show()
dummy = raw_input('Hit return to proceed: ')
pl.close()
pl.close('all')
return outfiles
################################
### for weather station data ###
################################
def retrieve_daily_weather_data_file(date, station):
"""
Retrieve AOS temperature data via HTTP.
date = '2010-04-24' # ISO-8601 date or datetime string
Return the name of the file if succeeded, otherwise '_CURL_FAILED_'.
"""
isodate = get_datetime_from_isodatetime(date).date().strftime('%Y-%m-%d')
rooturl = 'http://weather.aiv.alma.cl/data/data/files/'
outfile = '%s_%s.dat'%(station,date)
targeturl = '%s/%s/%s'%(date[0:4],date[5:7], outfile)
completeurl = '"%s/%s"' % (rooturl, targeturl)
print 'Retrieving %s weather: %s' % (isodate, completeurl)
exitcode = os.system('curl -s -f %s -o %s' % (completeurl, outfile))
if exitcode == 0:
return outfile
else:
print 'Retrieval failed.'
return '_CURL_FAILED_'
def retrieve_weather_data_files(startdate, enddate, station):
"""
Retrieve weather data files for given period.
Parameters are something like:
startdate = '2010-04-24' # ISO-8601 date or datetime string
enddate = '2010-04-24' # ISO-8601 date or datetime string
Return a list of filenames.
"""
sdate = get_datetime_from_isodatetime(startdate).date()
edate = get_datetime_from_isodatetime(enddate).date()
y1900 = datetime.date(1900, 1, 1)
if ((sdate-y1900).days < 0) or ((edate-y1900).days < 0):
raise ValueError, "Startdate and/or enddate are invalid."
if ((edate-sdate).days < 0):
raise ValueError, "Startdate is later than enddate."
ndays = (edate-sdate).days + 1
files = []
for i in range(ndays):
targetdate = sdate + datetime.timedelta(i)
filename = retrieve_daily_weather_data_file(date=targetdate.strftime('%Y-%m-%d'), station=station)
if filename != '_CURL_FAILED_':
files.append(filename)
return files
def read_weather_data_file(filename, removefile=True):
"""
Read given weather data file.
Set removefile to True in order to remove files once it was read.
Return is a dictionary of lists of datetime.datetime and float values:
{'datetime': [datetime], 'value': [value]}
"""
if not os.path.exists(filename):
raise Exception, ("File %s not found." % filename)
datetimelist = []
H = [] # Humidity
T = [] # Temp
D = [] #Dewpoint
WD = [] # Wind direction
WS = [] # Wind Speed
P = [] # Pressure
for line in open(filename, 'r'):
if line[0] == '#':
continue
(strdatetime, h, t, d, wd, ws, p) = line.split(';')
datetimelist.append(get_datetime_from_isodatetime(strdatetime))
H.append(float(h))
T.append(float(t))
D.append(float(d))
WD.append(float(wd))
WS.append(float(ws))
P.append(float(p))
if removefile:
os.system('rm %s' % filename)
return {'datetime': datetimelist, 'H': H, 'T':T,'D':D,'WD':WD,'WS':WS, 'P':P}
def get_weather_data(startdate, enddate, station = 'Meteo1',removefile=False):
"""
Obtain monitor values recorded in weather monitoring for given set of parameters.
Parameters are something like:
startdate = '2010-04-24' # ISO-8601 date or datetime string
enddate = '2010-04-24' # ISO-8601 date or datetime string
station = 'Meteo1' # can be Meteo1 or Meteo2 for AOS
removefile = False # optional: set True to delete files once read
Files are automatically retrieved via HTTP, read, and deleted.
Return is a dictionary of lists of datetime.datetime and float values:
{'datetime': [datetime], 'value': [value]}
"""
if (station is not 'Meteo1') and (station is not 'Meteo2'):
raise Exception, 'Station must be Meteo1 or Meteo2. check again...'
files = retrieve_weather_data_files(startdate, enddate, station)
if len(files) == 0:
raise Exception, "Failed to retrieve data files."
datalist = {}
for filename in files:
weatherdata = read_weather_data_file(filename, removefile)
for k in weatherdata.keys():
try:
datalist[k] += weatherdata[k]
except:
datalist[k]=[]
datalist[k] += weatherdata[k]
return datalist
def get_ASTE_weather_data(startdate, enddate):
"""
retrieves the Aste weather data and returns it in a dictionnary.
startdate should be format 2014-10-02
end date should be format 2014-10-02
"""
import datetime
sdate = get_datetime_from_isodatetime(startdate).date()
edate = get_datetime_from_isodatetime(enddate).date()
ndays = (edate-sdate).days + 1
fileList = []
for i in range(ndays):
targetdate = sdate + datetime.timedelta(i)
date=targetdate.strftime('%Y%m%d')
print date
filename = '/data/dbarkats/meteo_data/aste_meteo/weather_%s_0000.log'%(date)
fileList.append(filename)
datetimelist = []
H = [] # Humidity
T = [] # Temp
WD = [] # Wind direction
WS = [] # Wind Speed
P = [] # Pressure
for filename in fileList:
for line in open(filename, 'r'):
if line[0] == '#' or line[0] == '\n':
continue
l = line.split()
y = l[0].split('/')[0]
m = l[0].split('/')[1]
d = l[0].split('/')[2]
strdatetime = '%s-%s-%sT%s:00'%(y,m,d,l[1])
datetimelist.append(get_datetime_from_isodatetime(strdatetime))
if l[5] != '---':
H.append(float(l[5]))
else:
H.append(np.nan)
if l[4] != '---':
T.append(float(l[4]))
else:
T.append(np.nan)
if l[10] != '---':
WD.append(float(l[10]))
else:
WD.append(np.nan)
if l[9] != '---':
WS.append(float(l[9]))
else:
WS.append(np.nan)
if l[8] != '---':
P.append(float(l[8]))
else:
P.append(np.nan)
return {'datetime': datetimelist, 'H': H, 'T':T,'WD':WD,'WS':WS, 'P':P}
def get_Nanten_weather_data(startdate, enddate):
"""
retrieves the Nanten weather data and returns it in a dictionnary.
"""
import datetime
sdate = get_datetime_from_isodatetime(startdate).date()
edate = get_datetime_from_isodatetime(enddate).date()
ndays = (edate-sdate).days + 1
fileList = []
for i in range(ndays):
targetdate = sdate + datetime.timedelta(i)
date=targetdate.strftime('%Y%m%d')
print date
filename = '/users/dbarkats/nanten_meteo/%s%s/%s.nwd'%(date[0:4],date[4:6],date)
fileList.append(filename)
datetimelist = []
H = [] # Humidity
T = [] # Temp
WD = [] # Wind direction
WS = [] # Wind Speed
P = [] # Pressure
for filename in fileList:
for line in open(filename, 'r'):
if line[0] == '#' or line[0] == '\n':
continue
l = line.split(',')
strdatetime = '%s-%s-%sT%s:%s:%s'%(l[0].strip(),l[1].strip(),l[2].strip(),l[3].strip(),l[4].strip(),l[5].strip())
datetimelist.append(get_datetime_from_isodatetime(strdatetime))
H.append(float(l[9]))
T.append(float(l[7]))
WD.append(float(l[10]))
WS.append(float(l[11]))
P.append(float(l[12]))
return {'datetime': datetimelist, 'H': H, 'T':T,'WD':WD,'WS':WS, 'P':P}
#### 20141111 These next two function are not funtionnal after recent changes by dB to
# read_weather_data_files
#####
def show_weather_data_in_subplot(subpl, \
startdatetime, enddatetime=None, yrange=None, ylabel=None, label=None, \
title=None, showxticklabels=True, \
removediscontinuity=False, removeoutlier=False):
"""
Plot a time series of weather data in a pylab.figure.subplot instance.
You need to create a subplot instance in advance by, e.g.:
import pylab as pl
plf = pl.figure()
subpl = plf.add_subplot(1, 1, 1)
and to show it:
plf.show()
The other parameters are something like:
startdate = '2010-04-24T00:00:00' # ISO-8601 date or datetime string
enddate = '2010-04-25T12:00:00' # ISO-8601 date or datetime (optional)
yrange = [-10, 10] # optional
ylabel = 'Value [unknown unit]' # optional
label = 'Legend of the symbol' # optional
title = 'Title of the plot' # optional
No return values.
"""
# import datetime
# import pylab as pl
if enddatetime == None:
enddatetime = startdatetime
trange = [get_datetime_from_isodatetime(startdatetime), \
get_datetime_from_isodatetime(enddatetime)]
# range of dates for which the TMC data are obtained
startdate = trange[0].date().strftime('%Y-%m-%d')
enddate = trange[1].date().strftime('%Y-%m-%d')
weatherdata = get_weather_data(startdate=startdate, enddate=enddate, \
removefile=True)
if title == None:
title = '%s' % (startdate)
if ylabel == None:
ylabel = '%s' % ('Temperature [C]')
show_time_series_in_subplot(subpl, \
weatherdata['datetime'], weatherdata['value'], \
startdatetime, enddatetime, yrange, ylabel, label, title, \
showxticklabels, removediscontinuity, removeoutlier)
### data resampling ###
def resample_data_in_dict(datadict, targetkey, \
samp_begin, samp_end, samp_step, nullvalue=0.):
"""
Resample the data in a dictionary.
The data should be given as a dictionary: something like
{'key1': [list1], 'key2': [list2], ...}.
The sampling of the original data is datadict[targetkey], which can be
a list of int/float values or datetime.datetime instances. It should be
sorted in advance, otherwise the result will be incorrect.
The new sampling is determined by the begin/end values (samp_begin and
samp_end: int/float or datetime.datetime) and the step (samp_step: give it
as seconds if samp_begin/samp_end are datetime).
Caveat: this method linearly interpolates the data no matter how much
the original sampling is sparse.
"""
if not isinstance(datadict, dict):
raise ValueError, 'datadict should be a dictionary.'
keys = datadict.keys()
if not (targetkey in keys):
raise ValueError, "targetkey '%s' is not found in keys." % targetkey
target = datadict[targetkey]
### if the original sampling is datetime, convert it to float (seconds)
targetisdatetime = False
if isinstance(target[0], datetime.datetime):
targetisdatetime = True
target = [datetime_to_seconds_from_origin(item) for item in target]
samp_begin = datetime_to_seconds_from_origin(samp_begin)