-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhdf5_functions.py
executable file
·2291 lines (1942 loc) · 104 KB
/
hdf5_functions.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
#!/usr/bin/env python2.7
"""A collection of functions for modifying HDF5 files. These functions form
loop 2 of the LOFAR long-baseline pipeline, which can be found at
https://github.com/lmorabit/long_baseline_pipeline.
"""
from __future__ import print_function
from multiprocessing import Pool
import argparse
import csv
import datetime
import fnmatch
import os
import subprocess
import uuid
import numpy as np
from astropy.coordinates import SkyCoord
from scipy.interpolate import interp1d
from losoto.lib_operations import reorderAxes
import losoto.h5parm as lh5 # on CEP3, "module load losoto"
import pyrap.tables as pt
__author__ = 'Sean Mooney'
__date__ = '01 June 2019'
# TODO switch to interpolating LoSoTo solutions with NaN
# TODO is there an easier way to add soltabs?
# TODO remove repeated code, swap range(len()) to enumerate, etc
# TODO tidy docstrings
# TODO https://github.com/mooneyse/lb-loop-2/issues/11
# TODO https://github.com/mooneyse/lb-loop-2/issues/10
# TODO https://github.com/mooneyse/lb-loop-2/issues/9
# TODO https://github.com/mooneyse/lb-loop-2/issues/6
# TODO https://github.com/mooneyse/lb-loop-2/issues/5
def dir_from_ms(ms, verbose=False):
"""Gets the pointing centre (right ascension and declination) from the
measurement set.
Parameters
----------
ms : string
File path of the measurement set.
Returns
-------
list
Pointing centre from the measurement set.
"""
# previously using this casacore one liner
# np.squeeze(tb.table(ms + '::POINTING')[0]['DIRECTION'].tolist())
if verbose:
print('Getting direction from {}.'.format(ms))
t = pt.table(ms, readonly=True, ack=False)
field = pt.table(t.getkeyword('FIELD'), readonly=True, ack=False)
directions = field.getcell('PHASE_DIR', 0)[0].tolist() # radians
field.close()
t.close()
return directions
def combine_h5s(phase_h5='', amplitude_h5='', tec_h5='', loop3_dir=''):
"""A function that takes a HDF5 with phase000 and a HDF5 with amplitude000
and phase000 for a particular direction and combines them into one HDF5.
This is necessary for the way loop 2 works. The dir2phasesol function
includes amplitude (and also TEC) but it reads the files from working_data
which is the list of HDF5s that have the desired phase solutions. So this
function allows the amplitudes to be brought into the fold. I only copy
across the solution tables; the source and antenna tables should come along
too.
The next steps for expanding this function would be to take a list of HDF5
files which can include TEC too (and anything else) and combines them. Then
the thing to have would be for this to search the loop 3 output and take
the latest phase and amplitude HDF5s and combine them (given just the
directory), with any specified TEC. Finally, add a flag to say whether to
take the solutions from loop 3 or the diagonal solutions from an initial
calibrator.
Parameters
----------
phase_h5 : string (default = '')
Name of the HDF5 file with the phase solutions.
amplitude_h5 : string (default = '')
Name of the HDF5 file with the diagonal solutions.
tec_h5 : string (default = '')
Name of the HDF5 file with the TEC solutions.
loop3_dir : string (default = '')
Instead of a phase_h5 and an amplitude_h5, the directory of the loop 3
run can be given, and the function will use the phase and amplitude
HDF5 files relating to the furthest progress. This loop 3 directory
will take priority if it is given with phase_h5 and amplitude_h5.
Returns
-------
string
Name of the new HDF5 file containing both phase and amplitude/phase
solutions.
"""
if loop3_dir:
loop3_files = [loop3_dir + '/' + f for f in os.listdir(loop3_dir) if os.path.isfile(os.path.join(loop3_dir, f))]
only_h5s = [f for f in loop3_files if f.endswith('.h5')]
amplitude_h5s = fnmatch.filter(only_h5s, '*_A_*.h5')
for h5 in amplitude_h5s:
while h5 in only_h5s:
only_h5s.remove(h5)
phase_h5s = only_h5s
amplitude_h5s.sort()
phase_h5s.sort()
amplitude_h5 = amplitude_h5s[-1]
phase_h5 = phase_h5s[-1]
print('Using {} and {}.'.format(phase_h5, amplitude_h5))
# get data from the h5parms
p = lh5.h5parm(phase_h5)
p_soltab = p.getSolset('sol000').getSoltab('phase000')
p_source = p.getSolset('sol000').getSou().items()
p_antenna = p.getSolset('sol000').getAnt().items()
a = lh5.h5parm(amplitude_h5)
a_soltab_A = a.getSolset('sol000').getSoltab('amplitude000')
a_soltab_theta = a.getSolset('sol000').getSoltab('phase000')
a_source = a.getSolset('sol000').getSou().items()
a_antenna = a.getSolset('sol000').getAnt().items()
# reorder axes
desired_axesNames = ['time', 'freq', 'ant', 'pol'] # NOTE no 'dir' axis
p_val_reordered = reorderAxes(p_soltab.val, p_soltab.getAxesNames(), desired_axesNames)
p_weight_reordered = reorderAxes(p_soltab.weight, p_soltab.getAxesNames(), desired_axesNames)
a_A_val_reordered = reorderAxes(a_soltab_A.val, a_soltab_A.getAxesNames(), desired_axesNames)
a_A_weight_reordered = reorderAxes(a_soltab_A.weight, a_soltab_A.getAxesNames(), desired_axesNames)
a_theta_val_reordered = reorderAxes(a_soltab_theta.val, a_soltab_theta.getAxesNames(), desired_axesNames)
a_theta_weight_reordered = reorderAxes(a_soltab_theta.weight, a_soltab_theta.getAxesNames(), desired_axesNames)
# make new solution tables in the new h5parm
new_h5 = phase_h5[:-3] + '_P_A.h5' # lazy method
new_h5 = phase_h5[:-3] + '_phase_diag.h5' if not tec_h5 else phase_h5[:-3] + '_phase_diag_tec.h5'
n = lh5.h5parm(new_h5, readonly=False)
n_phase_solset = n.makeSolset(solsetName='sol000')
source_table = n_phase_solset.obj._f_get_child('source')
source_table.append(p_source) # populate source and antenna tables
antenna_table = n_phase_solset.obj._f_get_child('antenna')
antenna_table.append(p_antenna)
n_phase_solset.makeSoltab('phase',
axesNames=desired_axesNames,
axesVals=[p_soltab.time, p_soltab.freq,
p_soltab.ant, p_soltab.pol],
vals=p_val_reordered,
weights=p_weight_reordered)
n_amplitude_solset = n.makeSolset(solsetName='sol001')
source_table = n_amplitude_solset.obj._f_get_child('source')
source_table.append(a_source) # populate source and antenna tables
antenna_table = n_amplitude_solset.obj._f_get_child('antenna')
antenna_table.append(a_antenna)
n_amplitude_solset.makeSoltab('amplitude',
axesNames=desired_axesNames,
axesVals=[a_soltab_A.time, a_soltab_A.freq,
a_soltab_A.ant, a_soltab_A.pol],
vals=a_A_val_reordered,
weights=a_A_weight_reordered)
n_amplitude_solset.makeSoltab('phase',
axesNames=desired_axesNames,
axesVals=[a_soltab_theta.time,
a_soltab_theta.freq,
a_soltab_theta.ant,
a_soltab_theta.pol],
vals=a_theta_val_reordered,
weights=a_theta_weight_reordered)
if tec_h5: # if a hdf5 with tec solutions is given too, put this in the
# new hdf5 also
t = lh5.h5parm(tec_h5)
t_soltab = t.getSolset('sol000').getSoltab('tec000')
t_val = reorderAxes(t_soltab.val, t_soltab.getAxesNames(),
['time', 'freq', 'ant']) # NOTE no 'dir' axis
t_weight = reorderAxes(t_soltab.weight, t_soltab.getAxesNames(),
['time', 'freq', 'ant']) # NOTE no 'dir' axis
t_solset = n.makeSolset(solsetName='sol002') # in new h5parm
t_source = t_solset.obj._f_get_child('source')
t_source.append(t.getSolset('sol000').getSou().items())
t_antenna = t_solset.obj._f_get_child('antenna')
t_antenna.append(t.getSolset('sol000').getAnt().items())
t_solset.makeSoltab('tec',
axesNames=['time', 'freq', 'ant'],
axesVals=[t_soltab.time, t_soltab.freq,
t_soltab.ant],
vals=t_val,
weights=t_weight)
t.close()
# tidy up
p.close()
a.close()
n.close()
return new_h5
def make_blank_mtf(mtf):
"""Create an empty master text file containing all of the LOFAR core,
remote, and international stations, and ST001.
Args:
mtf (str): The master text file to be created.
Returns:
The name of the master text file (str).
"""
mtf_header = ('# h5parm, ra, dec, ST001, RS106HBA, RS205HBA, RS208HBA, '
'RS210HBA, RS305HBA, RS306HBA, RS307HBA, RS310HBA, RS404HBA,'
' RS406HBA, RS407HBA, RS409HBA, RS410HBA, RS503HBA, '
'RS508HBA, RS509HBA, DE601HBA, DE602HBA, DE603HBA, DE604HBA,'
' DE605HBA, FR606HBA, SE607HBA, UK608HBA, DE609HBA, '
'PL610HBA, PL611HBA, PL612HBA, IE613HBA, '
'CS001HBA0, CS001HBA1, CS002HBA0, CS002HBA1, '
'CS003HBA0, CS003HBA1, CS004HBA0, CS004HBA1, '
'CS005HBA0, CS005HBA1, CS006HBA0, CS006HBA1, '
'CS007HBA0, CS007HBA1, CS011HBA0, CS011HBA1, '
'CS013HBA0, CS013HBA1, CS017HBA0, CS017HBA1, '
'CS021HBA0, CS021HBA1, CS024HBA0, CS024HBA1, '
'CS026HBA0, CS026HBA1, CS028HBA0, CS028HBA1, '
'CS030HBA0, CS030HBA1, CS031HBA0, CS031HBA1, '
'CS032HBA0, CS032HBA1, CS101HBA0, CS101HBA1, '
'CS103HBA0, CS103HBA1, CS201HBA0, CS201HBA1, '
'CS301HBA0, CS301HBA1, CS302HBA0, CS302HBA1, '
'CS401HBA0, CS401HBA1, CS501HBA0, CS501HBA1\n')
if not os.path.isfile(mtf): # if it does not already exist
with open(mtf, 'w+') as the_file:
the_file.write(mtf_header)
return mtf
def interpolate_nan(x_):
"""Interpolate NaN values using this answer from Stack Overflow:
https://stackoverflow.com/a/6520696/6386612. This works even if the first
or last value is nan or if there are multiple nans. It raises an error if
all values are nan.
Args:
x_ (list or NumPy array): Values to interpolate.
Returns:
The interpolated values. (NumPy array)
"""
x_ = np.array(x_)
if np.isnan(x_).all(): # if all values are nan
raise ValueError('All values in the array are nan, so interpolation is'
' not possible.')
nans, x = np.isnan(x_), lambda z: z.nonzero()[0]
x_[nans] = np.interp(x(nans), x(~nans), x_[~nans])
return x_
def coherence_metric(xx, yy):
"""Calculates the coherence metric by comparing the XX and YY phases.
Args:
xx (list or NumPy array): One set of phase solutions.
yy (list or NumPy array): The other set of phase solutions.
Returns:
The coherence metric. (float)
"""
try:
xx, yy = interpolate_nan(xx), interpolate_nan(yy)
except: # TODO which exception is this?
# if the values are all nan, they cannot be interpolated so return a
# coherence value of nan also
return np.nan
return np.nanmean(np.gradient(abs(np.unwrap(xx - yy))) ** 2)
def evaluate_solutions(h5parm, mtf, threshold=0.25, verbose=False):
"""Get the direction from the h5parm. Evaluate the phase solutions in the
h5parm for each station using the coherence metric. Determine the validity
of each coherence metric that was calculated. Append the right ascension,
declination, and validity to the master text file.
Args:
h5parm (str): LOFAR HDF5 parameter file.
mtf (str): Master text file.
threshold (float; default=0.25): threshold to determine the goodness of
the coherence metric.
Returns:
The coherence metric for each station. (dict)
"""
h = lh5.h5parm(h5parm)
solname = h.getSolsetNames()[0] # set to -1 to use only the last solset
solset = h.getSolset(solname)
soltab = solset.getSoltab('phase000')
stations = soltab.ant
source = solset.getSou() # dictionary
direction = np.degrees(np.array(source[list(source.keys())[0]])) # degrees
generator = soltab.getValuesIter(returnAxes=['freq', 'time'])
evaluations, temporary = {}, {} # evaluations holds the coherence metrics
for g in generator:
temporary[g[1]['pol'] + '_' + g[1]['ant']] = np.squeeze(g[0])
for station in stations:
xx = temporary['XX_' + station]
yy = temporary['YY_' + station]
# try/except block facilitates one or many frequency axes in the hdf5
try: # if there are multiple frequency axes
cohs = []
num_solns, num_freqs = xx.shape # this unpack will fail if there is only one frequency axis
for i in range(num_freqs):
cohs.append(coherence_metric(xx[:, i], yy[:, i]))
coh = np.mean(cohs)
print('{} {} coherence: {:.3f} ({} frequency axes)'.format(h5parm, station, coh, num_freqs)) if verbose else None
evaluations[station] = coh # 0 = best
except: # if there is one frequency axis only
coh = coherence_metric(xx, yy)
print('{} {} coherence: {:.3f}'.format(h5parm, station, coh)) if verbose else None
evaluations[station] = coh # 0 = best
with open(mtf) as f:
mtf_stations = list(csv.reader(f))[0][3:] # get stations from the mtf
with open(mtf, 'a') as f:
f.write('{}, {}, {}'.format(h5parm, direction[0], direction[1]))
for mtf_station in mtf_stations:
# look up the statistic for a station and determine if it is good
try:
value = evaluations[mtf_station[1:]]
except KeyError:
value = float('nan')
if np.isnan(value):
f.write(', {}'.format('nan'))
elif value < threshold: # success
f.write(', {}'.format(int(True)))
else: # fail
f.write(', {}'.format(int(False)))
f.write('\n')
h.close()
return evaluations
def dir2phasesol_wrapper(mtf, ms, directions=[], cores=4):
"""Book-keeping to get the multiprocessing set up and running.
Args:
mtf (str): The master text file.
ms (str): The measurement set.
directions (list; default = []): Directions in radians, of the form RA1,
Dec1, RA2, Dec2, etc.
cores (float; default = 4): Number of cores to use.
Returns:
The names of the newly created h5parms in the directions specified. (list)
"""
if not directions:
directions = dir_from_ms(ms)
mtf_list, ms_list = [], []
for i in range(int(len(directions) / 2)):
mtf_list.append(mtf)
ms_list.append(ms)
directions_paired = list(zip(directions[::2], directions[1::2]))
multiprocessing = list(zip(mtf_list, ms_list, directions_paired))
pool = Pool(cores) # specify cores
new_h5parms = pool.map(dir2phasesol_multiprocessing, multiprocessing)
return new_h5parms
def interpolate_time(the_array, the_times, new_times, tec=False):
"""Given a h5parm array, it will interpolate the values in the time axis
from whatever it is to a given value.
Args:
the_array (NumPy array): The array of values or weights from the h5parm.
the_times (NumPy array): The 1D array of values along the time axis.
new_times (NumPy array): The 1D time axis that the values will be mapped
to.
Returns:
The array of values or weights for a h5parm expanded to fit the new time
axis. (NumPy array)
"""
if tec:
# get the original data
time, freq, ant, dir_ = the_array.shape # axes were reordered earlier
# make the new array
interpolated_array = np.ones(shape=(len(new_times), freq, ant, dir_))
for a in range(ant): # for one antenna only
old_values = the_array[:, 0, a, 0] # xx
# calculate the interpolated values
f = interp1d(the_times, old_values, kind='nearest', bounds_error=False)
new_values = f(new_times)
# assign the interpolated values to the new array
interpolated_array[:, 0, a, 0] = new_values # new values
else:
# get the original data
time, freq, ant, pol, dir_ = the_array.shape # axes were reordered earlier
# make the new array
interpolated_array = np.ones(shape=(len(new_times), freq, ant, pol, dir_))
for a in range(ant): # for one antenna only
old_x_values = the_array[:, 0, a, 0, 0] # xx
old_y_values = the_array[:, 0, a, 1, 0] # yy
# calculate the interpolated values
x1 = interp1d(the_times, old_x_values, kind='nearest', bounds_error=False)
y1 = interp1d(the_times, old_y_values, kind='nearest', bounds_error=False)
new_x_values = x1(new_times)
new_y_values = y1(new_times)
# assign the interpolated values to the new array
interpolated_array[:, 0, a, 0, 0] = new_x_values # new x values
interpolated_array[:, 0, a, 1, 0] = new_y_values # new y values
return interpolated_array
def dir2phasesol_multiprocessing(args):
"""Wrapper to parallelise make_h5parm.
Args:
args (list or tuple): Parameters to be passed to the dir2phasesol
function.
Returns:
The output of the dir2phasesol function, which is the name of a new
h5parm file. (str)
"""
mtf, ms, directions = args
return dir2phasesol(mtf=mtf, ms=ms, directions=directions)
def build_soltab(soltab, working_data, solset):
"""Creates a solution table from many h5parms using data from the
temporary working file.
Parameters
----------
soltab : string
The name of the solution table to copy solutions from.
working_data : NumPy array
Data providing the list of good and bad stations, which was taken from
the temporary working file, and the goodness relates to the coherence
metric on the phase solutions.
solset : string
The solution set in the HDF5 files given in the working_data that have
the relevant solution tables. The stardard I am going with is to have
phase000 in sol000, amplitude000/phase000 in sol001, and tec000 in
sol002.
Returns
-------
NumPy array
Values to populate the solution table.
NumPy array
Weights to populate the solution table.
NumPy array
Time axis to populate the solution table.
NumPy array
Frequency axis to populate the solution table.
NumPy array
Antenna axis to populate the solution table.
"""
time_mins, time_maxs, time_intervals, frequencies = [], [], [], []
# looping through the h5parms to build a new time axis; this has to be done
# before getting the solutions from the h5parms so they are being looped
# over twice
for my_line in range(len(working_data)): # one line per station
my_station = working_data[my_line][0]
my_h5parm = working_data[my_line][len(working_data[my_line]) - 1]
lo = lh5.h5parm(my_h5parm, readonly=False)
tab = lo.getSolset(solset).getSoltab(soltab + '000')
time_mins.append(np.min(tab.time[:]))
time_maxs.append(np.max(tab.time[:]))
time_intervals.append((np.max(tab.time[:]) - np.min(tab.time[:])) / (len(tab.time[:]) - 1))
frequencies.append(tab.freq[:])
lo.close()
# the time ranges from the lowest to the highest on the smallest interval
num_of_steps = 1 + ((np.max(time_maxs) - np.min(time_mins)) / np.min(time_intervals))
new_time = np.linspace(np.min(time_mins), np.max(time_maxs), num_of_steps)
# looping through the h5parms to get the solutions for the good stations
val, weight = [], []
for my_line in range(len(working_data)): # one line per station
my_station = working_data[my_line][0]
my_h5parm = working_data[my_line][len(working_data[my_line]) - 1]
lo = lh5.h5parm(my_h5parm, readonly=False)
tab = lo.getSolset(solset).getSoltab(soltab + '000')
axes_names = tab.getAxesNames()
values = tab.val
weights = tab.weight
if 'dir' not in axes_names: # add the direction dimension
axes_names = ['dir'] + axes_names
values = np.expand_dims(tab.val, 0)
weights = np.expand_dims(tab.weight, 0)
if soltab == 'tec': # tec will not have a polarisation axis
reordered_values = reorderAxes(values, axes_names, ['time', 'freq', 'ant', 'dir'])
reordered_weights = reorderAxes(weights, axes_names, ['time', 'freq', 'ant', 'dir'])
for s in range(len(tab.ant[:])): # stations
if tab.ant[s] == my_station.strip():
v = reordered_values[:, :, s, :] # time, freq, ant, dir
w = reordered_weights[:, :, s, :]
v_expanded = np.expand_dims(v, axis=2)
w_expanded = np.expand_dims(w, axis=2)
v_interpolated = interpolate_time(the_array=v_expanded, the_times=tab.time[:], new_times=new_time, tec=True)
w_interpolated = interpolate_time(the_array=w_expanded, the_times=tab.time[:], new_times=new_time, tec=True)
val.append(v_interpolated)
weight.append(w_interpolated)
lo.close()
else:
reordered_values = reorderAxes(values, axes_names, ['time', 'freq', 'ant', 'pol', 'dir'])
reordered_weights = reorderAxes(weights, axes_names, ['time', 'freq', 'ant', 'pol', 'dir'])
for s in range(len(tab.ant[:])): # stations
if tab.ant[s] == my_station.strip():
v = reordered_values[:, :, s, :, :] # time, freq, ant, pol, dir
w = reordered_weights[:, :, s, :, :]
v_expanded = np.expand_dims(v, axis=2)
w_expanded = np.expand_dims(w, axis=2)
v_interpolated = interpolate_time(the_array=v_expanded, the_times=tab.time[:], new_times=new_time)
w_interpolated = interpolate_time(the_array=w_expanded, the_times=tab.time[:], new_times=new_time)
val.append(v_interpolated)
weight.append(w_interpolated)
lo.close()
vals = np.concatenate(val, axis=2)
weights = np.concatenate(weight, axis=2)
# if there is only one frequency, avearging will return a float, where we
# want it as a list, but if there are >1 frequency it is fine
if isinstance(np.average(frequencies, axis=0), float):
my_freqs = [np.average(frequencies)]
else:
my_freqs = np.average(frequencies, axis=0)
return vals, weights, new_time, my_freqs
def dir2phasesol(mtf, ms='', directions=[]):
'''Get the directions of the h5parms from the master text file. Calculate
the separation between a list of given directions and the h5parm
directions. For each station, find the h5parm of smallest separation which
has valid phase solutions. Create a new h5parm. Write these phase solutions
to this new h5parm.
Args:
mtf (str): Master text file with list of h5parms.
ms (str; default=''): Measurement set to be self-calibrated, used for
getting a sensible name for the new HDF5.
directions (list; default=[]): Right ascension and declination of one
source in radians.
Returns:
The new h5parm to be applied to the measurement set. (str)
'''
# get the direction from the master text file
# HACK genfromtxt gives empty string for h5parms when names=True is used
# importing them separately as a work around
data = np.genfromtxt(mtf, delimiter=',', unpack=True, dtype=float,
names=True)
h5parms = np.genfromtxt(mtf, delimiter=',', unpack=True, dtype=str,
usecols=0)
# calculate the distance betweeen the ms and the h5parm directions
# there is one entry in mtf_directions for each unique line in the mtf
directions = SkyCoord(directions[0], directions[1], unit='rad')
mtf_directions = {}
if h5parms.size == 1:
# to handle mtf files with one row which cannot be iterated over
mtf_direction = SkyCoord(float(data['ra']), float(data['dec']),
unit='deg')
separation = directions.separation(mtf_direction)
mtf_directions[separation] = h5parms
else:
for h5parm, ra, dec in zip(h5parms, data['ra'], data['dec']):
mtf_direction = SkyCoord(float(ra), float(dec), unit='deg')
separation = directions.separation(mtf_direction)
mtf_directions[separation] = h5parm # distances from ms to h5parms
# read in the stations from the master text file
with open(mtf) as f:
mtf_stations = list(csv.reader(f))[0][3:] # skip h5parm, ra, and dec
mtf_stations = [x.lstrip() for x in mtf_stations] # remove first space
# find the closest h5parm which has an acceptable solution for each station
# a forward slash is added to the ms name in case it does not end in one
parts = {'prefix': os.path.dirname(os.path.dirname(ms + '/')),
'ra': directions.ra.deg,
'dec': directions.dec.deg}
working_file = '{prefix}/make_h5parm_{ra}_{dec}.txt'.format(**parts)
f = open(working_file, 'w')
successful_stations = []
for mtf_station in mtf_stations: # for each station
for key in sorted(mtf_directions.keys()): # shortest separation first
# if there are multiple h5parms for one direction, the best
# solutions will be at the bottom (but this should never be the
# case)
h5parm = mtf_directions[key]
# this try/except block is necessary because otherwise this crashes
# when the master text file only has one h5parm in it
try:
row = list(h5parms).index(h5parm) # row in mtf
value = data[mtf_station][row] # boolean for h5parm and station
except:
row = 0
value = data[mtf_station]
if value == 1 and mtf_station not in successful_stations:
w = '{}\t{}\t{}\t{}\t{}'.format(mtf_station.ljust(8),
round(key.deg, 6), int(value),
row, h5parm)
f.write('{}\n'.format(w))
successful_stations.append(mtf_station)
f.close()
# create a new h5parm
ms = os.path.splitext(os.path.normpath(ms))[0]
new_h5parm = '{}_{}_{}.h5'.format(ms, np.round(directions.ra.deg, 3),
np.round(directions.dec.deg, 3))
h = lh5.h5parm(new_h5parm, readonly=False)
table = h.makeSolset() # creates sol000
solset = h.getSolset('sol000') # on the new h5parm
# get data to be copied from the working file
working_data = np.genfromtxt(working_file, delimiter='\t', dtype=str)
working_data = sorted(working_data.tolist()) # stations are alphabetised
# working_data is the list of nearest stations with good solutions; if for
# a station there is no good solution in any h5parm the new h5parm will
# exclude that station
val, weight = [], []
time_mins, time_maxs, time_intervals = [], [], []
frequencies = []
# looping through the h5parms that will be used in the new h5parm to find
# the shortest time interval of all h5parms being copied, and the longest
# time span
for my_line in range(len(working_data)): # one line per station
my_station = working_data[my_line][0]
my_h5parm = working_data[my_line][len(working_data[my_line]) - 1]
# use the station to get the relevant data to be copied from the h5parm
lo = lh5.h5parm(my_h5parm, readonly=False) # NB change this to True
# NB combine_h5s puts phase in sol000 and amplitude in sol001
phase = lo.getSolset('sol000').getSoltab('phase000')
time = phase.time[:]
time_mins.append(np.min(time))
time_maxs.append(np.max(time))
time_intervals.append((np.max(time) - np.min(time)) / (len(time) - 1))
frequencies.append(phase.freq[:])
lo.close()
# the time ranges from the lowest to the highest on the smallest interval
num_of_steps = 1 + ((np.max(time_maxs) - np.min(time_mins)) /
np.min(time_intervals))
new_time = np.linspace(np.min(time_mins), np.max(time_maxs), num_of_steps)
stations_in_correct_order = []
# looping through the h5parms again to get the solutions for the good
# stations needed to build the new h5parm
for my_line in range(len(working_data)): # one line per station
my_station = working_data[my_line][0]
my_h5parm = working_data[my_line][len(working_data[my_line]) - 1]
# use the station to get the relevant data to be copied from the h5parm
lo = lh5.h5parm(my_h5parm, readonly=False) # NB change this to True
phase = lo.getSolset('sol000').getSoltab('phase000')
axes_names = phase.getAxesNames()
values = phase.val
weights = phase.weight
if 'dir' not in axes_names: # add the direction dimension
axes_names = ['dir'] + axes_names
values = np.expand_dims(phase.val, 0)
weights = np.expand_dims(phase.weight, 0)
reordered_values = reorderAxes(values, axes_names,
['time', 'freq', 'ant', 'pol', 'dir'])
reordered_weights = reorderAxes(weights, axes_names,
['time', 'freq', 'ant', 'pol', 'dir'])
for s in range(len(phase.ant[:])): # stations
if phase.ant[s] == my_station.strip():
stations_in_correct_order.append(phase.ant[s])
# copy values and weights
v = reordered_values[:, :, s, :, :] # time, freq, ant, pol, dr
w = reordered_weights[:, :, s, :, :] # same order as v
v_expanded = np.expand_dims(v, axis=2)
w_expanded = np.expand_dims(w, axis=2)
v_interpolated = interpolate_time(the_array=v_expanded,
the_times=phase.time[:],
new_times=new_time)
w_interpolated = interpolate_time(the_array=w_expanded,
the_times=phase.time[:],
new_times=new_time)
val.append(v_interpolated)
weight.append(w_interpolated)
lo.close()
# properties of the new h5parm
freq = np.average(frequencies, axis=0) # all items in the list are equal
ant = stations_in_correct_order # antennas that will be in the new h5parm
pol = ['XX', 'YY'] # as standard
dir_ = [str(directions.ra.rad) + ', ' + str(directions.dec.rad)] # given
vals = np.concatenate(val, axis=2)
weights = np.concatenate(weight, axis=2)
# write these best phase solutions to the new h5parm
print('Putting phase soltuions in sol000 in {}.'.format(new_h5parm))
solset.makeSoltab('phase',
axesNames=['time', 'freq', 'ant', 'pol', 'dir'],
axesVals=[new_time, freq, ant, pol, dir_],
vals=vals,
weights=weights) # creates phase000
# copy source and antenna tables into the new h5parm
source_soltab = {'POINTING':
np.array([directions.ra.rad, directions.dec.rad],
dtype='float32')}
# the x, y, z coordinates of the stations should be in these arrays
tied = {'ST001': np.array([3826557.5, 461029.06, 5064908],
dtype='float32')}
core = {'CS001HBA0': np.array([3826896.235, 460979.455, 5064658.203],
dtype='float32'),
'CS001HBA1': np.array([3826979.384, 460897.597, 5064603.189],
dtype='float32'),
'CS002HBA0': np.array([3826600.961, 460953.402, 5064881.136],
dtype='float32'),
'CS002HBA1': np.array([3826565.594, 460958.110, 5064907.258],
dtype='float32'),
'CS003HBA0': np.array([3826471.348, 461000.138, 5064974.201],
dtype='float32'),
'CS003HBA1': np.array([3826517.812, 461035.258, 5064936.15],
dtype='float32'),
'CS004HBA0': np.array([3826585.626, 460865.844, 5064900.561],
dtype='float32'),
'CS004HBA1': np.array([3826579.486, 460917.48, 5064900.502],
dtype='float32'),
'CS005HBA0': np.array([3826701.16, 460989.25, 5064802.685],
dtype='float32'),
'CS005HBA1': np.array([3826631.194, 461021.815, 5064852.259],
dtype='float32'),
'CS006HBA0': np.array([3826653.783, 461136.440, 5064824.943],
dtype='float32'),
'CS006HBA1': np.array([3826612.499, 461080.298, 5064861.006],
dtype='float32'),
'CS007HBA0': np.array([3826478.715, 461083.720, 5064961.117],
dtype='float32'),
'CS007HBA1': np.array([3826538.021, 461169.731, 5064908.827],
dtype='float32'),
'CS011HBA0': np.array([3826637.421, 461227.345, 5064829.134],
dtype='float32'),
'CS011HBA1': np.array([3826648.961, 461354.241, 5064809.003],
dtype='float32'),
'CS013HBA0': np.array([3826318.954, 460856.125, 5065101.85],
dtype='float32'),
'CS013HBA1': np.array([3826402.103, 460774.267, 5065046.836],
dtype='float32'),
'CS017HBA0': np.array([3826405.095, 461507.460, 5064978.083],
dtype='float32'),
'CS017HBA1': np.array([3826499.783, 461552.498, 5064902.938],
dtype='float32'),
'CS021HBA0': np.array([3826463.502, 460533.094, 5065022.614],
dtype='float32'),
'CS021HBA1': np.array([3826368.813, 460488.057, 5065097.759],
dtype='float32'),
'CS024HBA0': np.array([3827218.193, 461403.898, 5064378.79],
dtype='float32'),
'CS024HBA1': np.array([3827123.504, 461358.861, 5064453.935],
dtype='float32'),
'CS026HBA0': np.array([3826418.227, 461805.837, 5064941.199],
dtype='float32'),
'CS026HBA1': np.array([3826335.078, 461887.696, 5064996.213],
dtype='float32'),
'CS028HBA0': np.array([3825573.134, 461324.607, 5065619.039],
dtype='float32'),
'CS028HBA1': np.array([3825656.283, 461242.749, 5065564.025],
dtype='float32'),
'CS030HBA0': np.array([3826041.577, 460323.374, 5065357.614],
dtype='float32'),
'CS030HBA1': np.array([3825958.428, 460405.233, 5065412.628],
dtype='float32'),
'CS031HBA0': np.array([3826383.037, 460279.343, 5065105.85],
dtype='float32'),
'CS031HBA1': np.array([3826477.725, 460324.381, 5065030.705],
dtype='float32'),
'CS032HBA0': np.array([3826864.262, 460451.924, 5064730.006],
dtype='float32'),
'CS032HBA1': np.array([3826947.411, 460370.066, 5064674.992],
dtype='float32'),
'CS101HBA0': np.array([3825899.977, 461698.906, 5065339.205],
dtype='float32'),
'CS101HBA1': np.array([3825805.288, 461653.869, 5065414.35],
dtype='float32'),
'CS103HBA0': np.array([3826331.59, 462759.074, 5064919.62],
dtype='float32'),
'CS103HBA1': np.array([3826248.441, 462840.933, 5064974.634],
dtype='float32'),
'CS201HBA0': np.array([3826679.281, 461855.243, 5064741.38],
dtype='float32'),
'CS201HBA1': np.array([3826690.821, 461982.139, 5064721.249],
dtype='float32'),
'CS301HBA0': np.array([3827442.564, 461050.814, 5064242.391],
dtype='float32'),
'CS301HBA1': np.array([3827431.025, 460923.919, 5064262.521],
dtype='float32'),
'CS302HBA0': np.array([3827973.226, 459728.624, 5063975.3],
dtype='float32'),
'CS302HBA1': np.array([3827890.077, 459810.483, 5064030.313],
dtype='float32'),
'CS401HBA0': np.array([3826795.752, 460158.894, 5064808.929],
dtype='float32'),
'CS401HBA1': np.array([3826784.211, 460031.993, 5064829.062],
dtype='float32'),
'CS501HBA0': np.array([3825568.82, 460647.62, 5065683.028],
dtype='float32'),
'CS501HBA1': np.array([3825663.508, 460692.658, 5065607.883],
dtype='float32')}
antenna_soltab = {'RS106HBA': np.array([3829205.598, 469142.533000,
5062181.002], dtype='float32'),
'RS205HBA': np.array([3831479.67, 463487.529000,
5060989.903], dtype='float32'),
'RS208HBA': np.array([3847753.31, 466962.809000,
5048397.244], dtype='float32'),
'RS210HBA': np.array([3877827.56186, 467536.604956,
5025445.584], dtype='float32'),
'RS305HBA': np.array([3828732.721, 454692.421000,
5063850.334], dtype='float32'),
'RS306HBA': np.array([3829771.249, 452761.702000,
5063243.181], dtype='float32'),
'RS307HBA': np.array([3837964.52, 449627.261000,
5057357.585], dtype='float32'),
'RS310HBA': np.array([3845376.29, 413616.564000,
5054796.341], dtype='float32'),
'RS404HBA': np.array([0.0, 0.0, 0.0],
dtype='float32'), # not operational
'RS406HBA': np.array([3818424.939, 452020.269000,
5071817.644], dtype='float32'),
'RS407HBA': np.array([3811649.455, 453459.894000,
5076728.952], dtype='float32'),
'RS409HBA': np.array([3824812.621, 426130.330000,
5069251.754], dtype='float32'),
'RS410HBA': np.array([0.0, 0.0, 0.0],
dtype='float32'), # not operational
'RS503HBA': np.array([3824138.566, 459476.972,
5066858.578], dtype='float32'),
'RS508HBA': np.array([3797136.484, 463114.447,
5086651.286], dtype='float32'),
'RS509HBA': np.array([3783537.525, 450130.064,
5097866.146], dtype='float32'),
'DE601HBA': np.array([4034101.522, 487012.757,
4900230.499], dtype='float32'),
'DE602HBA': np.array([4152568.006, 828789.153,
4754362.203], dtype='float32'),
'DE603HBA': np.array([3940295.706, 816722.865,
4932394.416], dtype='float32'),
'DE604HBA': np.array([3796379.823, 877614.13,
5032712.528], dtype='float32'),
'DE605HBA': np.array([4005681.02, 450968.643,
4926458.211], dtype='float32'),
'FR606HBA': np.array([4324016.708, 165545.525,
4670271.363], dtype='float32'),
'SE607HBA': np.array([3370271.657, 712125.881,
5349991.165], dtype='float32'),
'UK608HBA': np.array([4008461.941, -100376.609,
4943716.874], dtype='float32'),
'DE609HBA': np.array([3727217.673, 655109.175,
5117003.123], dtype='float32'),
'PL610HBA': np.array([3738462.416, 1148244.316,
5021710.658], dtype='float32'),
'PL611HBA': np.array([3850980.881, 1438994.879,
4860498.993], dtype='float32'),
'PL612HBA': np.array([3551481.817, 1334203.573,
5110157.41], dtype='float32'),
'IE613HBA': np.array([3801692.0, -528983.94,
5076958.0], dtype='float32')}
# delete a key, value pair from the antenna table if it does not exist in
# the antenna axis
keys_to_remove = []
for key in antenna_soltab:
if key not in ant:
keys_to_remove.append(key)
for k in keys_to_remove:
antenna_soltab.pop(k, None)
for a in ant:
if a[:2] == 'ST':
antenna_soltab.update(tied) # there will only be the tied station
if a[:2] == 'CS':
antenna_soltab.update(core)
break # only add the core stations to the antenna table once
source_table = table.obj._f_get_child('source')
source_table.append(source_soltab.items()) # from dictionary to list
antenna_table = table.obj._f_get_child('antenna')
antenna_table.append(antenna_soltab.items()) # from dictionary to list
try: # bring across amplitude solutions if there are any
vals, weights, time, freq = build_soltab(soltab='amplitude',
working_data=working_data,
solset='sol001')
q = new_h5parm
print('Putting amplitude soltuions in sol001 in {}.'.format(q))
amp_solset = h.makeSolset('sol001')
amp_solset.makeSoltab('amplitude',
axesNames=['time', 'freq', 'ant', 'pol', 'dir'],
axesVals=[time, freq, ant, pol, dir_],
vals=vals,
weights=weights) # creates amplitude000
# amplitude solutions have a phase component too
vals, weights, time, freq = build_soltab(soltab='phase',
working_data=working_data,
solset='sol001')
amp_solset.makeSoltab('phase',
axesNames=['time', 'freq', 'ant', 'pol', 'dir'],
axesVals=[time, freq, ant, pol, dir_],
vals=vals,
weights=weights) # creates phase000
# make source and antenna tables
# using the source and antenna tables from phase as they should be the
# same (where a station is included is based on the phase coherences
# per station)
amp_source = amp_solset.obj._f_get_child('source')
amp_source.append(source_soltab.items()) # from dictionary to list
amp_antenna = amp_solset.obj._f_get_child('antenna')
amp_antenna.append(antenna_soltab.items()) # from dictionary to list
except:
print('No amplitude solutions found.')
pass
# try: # bring across tec solutions if there are any
vals, weights, time, freq = build_soltab(soltab='tec',
working_data=working_data,
solset='sol002')
print('Putting TEC soltuions in sol002 in {}.'.format(new_h5parm))
tec_solset = h.makeSolset('sol002')