-
Notifications
You must be signed in to change notification settings - Fork 1
/
VLBI_pipe_functions_MPI.py
2691 lines (2491 loc) · 94.8 KB
/
VLBI_pipe_functions_MPI.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
import re, os, json, inspect, sys, copy, glob, tarfile, random, math, shutil, ast
import collections
from collections import OrderedDict
try:
from collections import Mapping, Iterable
except:
from collections.abc import Mapping, Iterable
## Numerical routines
import numpy as np
## Plotting routines
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib import gridspec
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.lines as mlines
## Sci-py dependencies
from scipy.interpolate import interp1d
from scipy import signal
from scipy.constants import c as speed_light
from itertools import cycle
from scipy.special import j1
try:
# CASA 6
import casatools
from casatasks import *
casalog.showconsole(True)
casa6=True
except:
# CASA 5
from casac import casac as casatools
from taskinit import *
from bandpass_cli import bandpass_cli as bandpass
from importfitsidi_cli import importfitsidi_cli as importfitsidi
from flagdata_cli import flagdata_cli as flagdata
from applycal_cli import applycal_cli as applycal
from split_cli import split_cli as split
from gencal_cli import gencal_cli as gencal
from partition_cli import partition_cli as partition
from tclean_cli import tclean_cli as tclean
from statwt_cli import statwt_cli as statwt
casa6=False
try:
from astropy.io import fits
except:
import pyfits as fits
class NpEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return super(NpEncoder, self).default(obj)
def json_load_byteified(file_handle):
return _byteify(
json.load(file_handle, object_hook=_byteify),
ignore_dicts=True
)
def json_loads_byteified(json_text):
return _byteify(
json.loads(json_text, object_hook=_byteify),
ignore_dicts=True
)
def json_load_byteified_dict(file_handle,casa6):
if casa6==True:
return convert_temp(_byteify(
json.load(file_handle, object_hook=_byteify, object_pairs_hook=OrderedDict),
ignore_dicts=True))
else:
return convert(_byteify(
json.load(file_handle, object_hook=_byteify, object_pairs_hook=OrderedDict),
ignore_dicts=True))
def json_loads_byteified_dict(json_text,casa6):
if casa6==True:
return convert_temp(_byteify(
json.loads(json_text, object_hook=_byteify, object_pairs_hook=OrderedDict),
ignore_dicts=True))
else:
return convert(_byteify(
json.loads(json_text, object_hook=_byteify, object_pairs_hook=OrderedDict),
ignore_dicts=True))
def convert(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, Mapping):
return OrderedDict(map(convert, data.iteritems()))
elif isinstance(data, Iterable):
return type(data)(map(convert, data))
else:
return data
def convert_temp(data):
if isinstance(data, str):
return str(data)
elif isinstance(data, Mapping):
return OrderedDict(map(convert_temp, data.items()))
elif isinstance(data, Iterable):
return type(data)(map(convert_temp, data))
else:
return data
def _byteify(data, ignore_dicts=False):
# if this is a unicode string, return its string representation
try:
if isinstance(data, unicode):
return data.encode('utf-8')
except:
if isinstance(data, str):
return data
# if this is a list of values, return list of byteified values
if isinstance(data, list):
return [ _byteify(item, ignore_dicts=True) for item in data ]
# if this is a dictionary, return dictionary of byteified keys and values
# but only if we haven't already byteified it
if isinstance(data, dict) and not ignore_dicts:
try:
return {
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
for key, value in data.iteritems()
}
except:
return {
_byteify(key, ignore_dicts=True): _byteify(value, ignore_dicts=True)
for key, value in data.items()
}
# if it's anything else, return it in its original form
return data
def load_json(filename,Odict=False,casa6=False):
if Odict==False:
with open(filename, "r") as f:
json_data = json_load_byteified(f)
f.close()
else:
with open(filename, "r") as f:
json_data = json_load_byteified_dict(f,casa6)
f.close()
return json_data
def save_json(filename,array,append=False):
if append==False:
write_mode='w'
else:
write_mode='a'
with open(filename, write_mode) as f:
json.dump(array, f,indent=4, separators=(',', ': '),cls=NpEncoder)
f.close()
def headless(inputfile):
''' Parse the list of inputs given in the specified file. (Modified from evn_funcs.py)'''
INPUTFILE = open(inputfile, "r")
control=collections.OrderedDict()
# a few useful regular expressions
newline = re.compile(r'\n')
space = re.compile(r'\s')
char = re.compile(r'\w')
comment = re.compile(r'#.*')
# parse the input file assuming '=' is used to separate names from values
for line in INPUTFILE:
if char.match(line):
line = comment.sub(r'', line)
line = line.replace("'", '')
(param, value) = line.split('=')
param = newline.sub(r'', param)
param = param.strip()
param = space.sub(r'', param)
value = newline.sub(r'', value)
value = value.replace(' ','').strip()
valuelist = value.split(',')
if len(valuelist) == 1:
if valuelist[0] == '0' or valuelist[0]=='1' or valuelist[0]=='2':
control[param] = int(valuelist[0])
else:
control[param] = str(valuelist[0])
else:
control[param] = ','.join(valuelist)
return control
def rmfiles(files):
func_name = inspect.stack()[0][3]
for i in files:
if "*" in i:
files_to_die = glob.glob(i)
casalog.post(priority="INFO",origin=func_name,message='Files matching with %s - deleting'% i)
for j in files_to_die:
if os.path.exists(j) == True:
casalog.post(priority="INFO",origin=func_name,message='File %s found - deleting'% j)
os.system('rm %s'%j)
else:
pass
elif os.path.exists(i) == True:
casalog.post(priority="INFO",origin=func_name,message='File %s found - deleting'% i)
os.system('rm %s'%i)
else:
casalog.post(priority="INFO",origin=func_name,message='No file found - %s'% i)
return
def rmdirs(dirs):
func_name = inspect.stack()[0][3]
for i in dirs:
if "*" in i:
files_to_die = glob.glob(i)
casalog.post(priority="INFO",origin=func_name,message='Directories matching with %s - deleting'% i)
for j in files_to_die:
if os.path.exists(j) == True:
casalog.post(priority="INFO",origin=func_name,message='Directory/table %s found - deleting'% j)
os.system('rm -r %s'%j)
else:
pass
elif os.path.exists(i) == True:
casalog.post(priority="INFO",origin=func_name,message='Directory/table %s found - deleting'% i)
os.system('rm -r %s'%i)
else:
casalog.post(priority="INFO",origin=func_name,message='No file found - %s'% i)
return
def init_pipe_run(inputs,params):
inputs2=OrderedDict({})
for a,b in zip(inputs.keys(),inputs.values()):
inputs2[a]=b
for i in inputs2.keys():
inputs2[i] = 0
save_json(filename='%s/vp_steps_run.json'%params['global']['cwd'],array=inputs2,append=False)
gaintables=OrderedDict({})
for a,b in zip(('gaintable','gainfield','spwmap','interp','parang'), ([],[],[],[],params['global']['do_parang'])):
gaintables[a]=b
save_json(filename='%s/vp_gaintables.json'%params['global']['cwd'],array=gaintables,append=False)
save_json(filename='%s/vp_gaintables.last.json'%(params['global']['cwd']), array=OrderedDict({}), append=False)
def find_fitsidi(idifilepath="",cwd="",project_code=""):
func_name = inspect.stack()[0][3]
casalog.post(priority="INFO",origin=func_name,message='Will attempt to find fitsidifiles in %s'%idifilepath)
### Try first with project code and end
fitsidifiles=[]
for i in os.listdir(idifilepath):
if (i.startswith(project_code.lower())|i.startswith(project_code.upper()))&(('IDI' in i)|(i.endswith("idifits"))):
fitsidifiles.append('%s/%s'%(idifilepath,i))
casalog.post(priority="INFO",origin=func_name,message='FOUND - %s'% i)
if fitsidifiles == []:
for i in os.listdir(idifilepath):
if ('IDI' in i)|i.endswith('idifits'):
fitsidifiles.append('%s/%s'%(idifilepath,i))
casalog.post(priority="INFO",origin=func_name,message='FOUND - %s'% i)
if fitsidifiles == []:
casalog.post(priority="SEVERE",origin=func_name,message='Cannot find any fitsidifiles in %s.. exiting'%idifilepath)
sys.exit()
else:
return fitsidifiles
def write_hpc_headers(step,params):
func_name = inspect.stack()[0][3]
hpc_opts = {}
hpc_opts['job_manager'] = params['global']['job_manager']
hpc_opts['job_name'] = 'vp_%s'%step
hpc_opts['email_progress'] = params['global']["email_progress"]
hpc_opts['hpc_account'] = params['global']['HPC_project_code']
hpc_opts['error'] = step
if ((hpc_opts['job_manager'] == 'pbs')|(hpc_opts['job_manager'] == 'bash')|(hpc_opts['job_manager'] == 'slurm')):
pass
else:
casalog.post(priority='SEVERE',origin=func_name, message='Incorrect job manager, please select from pbs, slurm or bash')
sys.exit()
for i in ['partition','walltime','nodetype']:
if params[step]["hpc_options"][i] == 'default':
hpc_opts[i] = params['global']['default_%s'%i]
else:
hpc_opts[i] = params[step]["hpc_options"][i]
for i in ['nodes','cpus','mpiprocs','mem']:
if params[step]["hpc_options"][i] == -1:
hpc_opts[i] = params['global']['default_%s'%i]
else:
hpc_opts[i] = params[step]["hpc_options"][i]
hpc_dict = {'slurm':{
'partition' :'#SBATCH --partition=%s'%hpc_opts['partition'],
'nodetype' :'',
'cpus' :'#SBATCH -n %s'%hpc_opts['cpus'],
'nodes' :'#SBATCH -N %s'%(hpc_opts['nodes']),
'mpiprocs' :'',
'walltime' :'#SBATCH --time=%s'%hpc_opts['walltime'],
'job_name' :'#SBATCH -J %s'%hpc_opts['job_name'],
'hpc_account' :'#SBATCH --account %s'%hpc_opts['hpc_account'],
'mem' :'#SBATCH --mem=%s'%hpc_opts['mem'],
'email_progress':'#SBATCH --mail-type=BEGIN,END,FAIL\n#SBATCH --mail-user=%s'%hpc_opts['email_progress'],
'error':'#SBATCH -o logs/%s.sh.stdout.log\n#SBATCH -e logs/%s.sh.stderr.log'%(hpc_opts['error'],hpc_opts['error'])
},
'pbs':{
'partition' :'#PBS -q %s'%hpc_opts['partition'],
'nodetype' :'',
'cpus' :'#PBS -l select=%s:ncpus=%s:mpiprocs=%s:nodetype=%s'%(hpc_opts['nodes'],hpc_opts['cpus'],hpc_opts['mpiprocs'],hpc_opts['nodetype']),
'nodes' :'',
'mpiprocs' :'',
'mem' :'',
'walltime' :'#PBS -l walltime=%s'%hpc_opts['walltime'],
'job_name' :'#PBS -N %s'%hpc_opts['job_name'],
'hpc_account' :'#PBS -P %s'%hpc_opts['hpc_account'],
'email_progress':'#PBS -m abe -M %s'%hpc_opts['email_progress'],
'error':'#PBS -o logs/%s.sh.stdout.log\n#PBS -e logs/%s.sh.stderr.log'%(hpc_opts['error'],hpc_opts['error'])
},
'bash':{
'partition' :'',
'nodetype' :'',
'cpus' :'',
'nodes' :'',
'mpiprocs' :'',
'walltime' :'',
'job_name' :'',
'hpc_account' :'',
'mem' :'',
'email_progress':'',
'error':''
}
}
hpc_header= ['#!/bin/bash']
if step == 'apply_to_all':
file = open("%s/target_files.txt"%params['global']['cwd'], "r")
nonempty_lines = [line.strip("\n") for line in file if line != "\n"]
line_count = len(nonempty_lines)
file.close()
if params[step]['hpc_options']['max_jobs'] == -1:
tasks = '0-'+str(line_count-1)
else:
if (line_count-1) > params[step]['hpc_options']['max_jobs']:
tasks = '0-'+str(line_count-1)+'%'+str(params[step]['hpc_options']['max_jobs'])
else:
tasks = '0-'+str(line_count-1)
hpc_dict['slurm']['array_job'] = '#SBATCH --array='+tasks
hpc_dict['pbs']['array_job'] = '#PBS -t '+tasks
hpc_dict['bash']['array_job'] = ''
hpc_opts['array_job'] = -1
hpc_job = hpc_opts['job_manager']
for i in hpc_opts.keys():
if i != 'job_manager':
if hpc_opts[i] != '':
if hpc_dict[hpc_opts['job_manager']][i] !='':
hpc_header.append(hpc_dict[hpc_job][i])
with open('job_%s.%s'%(step,hpc_job), 'w') as filehandle:
for listitem in hpc_header:
filehandle.write('%s\n' % listitem)
def write_commands(step,inputs,params,parallel,aoflag,casa6):
func_name = inspect.stack()[0][3]
commands=[]
casapath=params['global']['casapath']
vlbipipepath=params['global']["vlbipipe_path"]
if aoflag==False:
if parallel == True:
mpicasapath = params['global']['mpicasapath']
else:
mpicasapath = ''
if params['global']['singularity'] == True:
singularity='singularity exec'
else:
singularity=''
if (params['global']['job_manager'] == 'pbs'):
job_commands=''
commands.append('cd %s'%params['global']['cwd'])
if (parallel == True):
job_commands='--map-by node -hostfile $PBS_NODEFILE'
else:
job_commands=''
if casa6 == False:
commands.append('%s %s %s %s --nologger --log2term -c %s/run_%s.py'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step))
else:
commands.append('%s %s %s %s %s/run_%s.py'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step))
elif aoflag=='both':
strategies = params[step]['AO_flag_strategy']
fields=params[step]['AO_flag_fields']
if os.path.exists('%s/%s_msinfo.json'%(params['global']['cwd'],params['global']['project_code']))==False:
msinfo = get_ms_info(msfile)
save_json(filename='%s/%s_msinfo.json'%(params['global']['cwd'],params['global']['project_code']), array=get_ms_info('%s/%s.ms'%(params['global']['cwd'],params['global']['project_code'])), append=False)
else:
msinfo = load_json('%s/%s_msinfo.json'%(params['global']['cwd'],params['global']['project_code']))
for i in range(len(fields)):
if (params['global']['job_manager'] == 'pbs'):
commands.append('cd %s'%params['global']['cwd'])
for k in params['global']['AOflag_command']:
commands.append(k)
msfile='%s.ms'%params['global']['project_code']
ids = []
for j in fields[i]:
ids.append(str(msinfo['FIELD']['fieldtoID'][j]))
commands[-1] = commands[-1]+' -fields %s '%(",".join(ids))
commands[-1] = commands[-1]+'-strategy %s %s'%(params[step]['AO_flag_strategy'][i],msfile)
msfile='%s.ms'%params['global']['project_code']
if parallel == True:
mpicasapath = params['global']['mpicasapath']
else:
mpicasapath = ''
if params['global']['singularity'] == True:
singularity='singularity exec'
else:
singularity=''
if (params['global']['job_manager'] == 'pbs'):
job_commands=''
commands.append('cd %s'%params['global']['cwd'])
if (parallel == True):
job_commands='--map-by node -hostfile $PBS_NODEFILE'
else:
job_commands=''
if casa6 == False:
commands.append('%s %s %s %s --nologger --log2term -c %s/run_%s.py'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step))
else:
commands.append('%s %s %s %s %s/run_%s.py'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step))
elif aoflag==True:
strategies = params[step]['AO_flag_strategy']
fields=params[step]['AO_flag_fields']
if os.path.exists('%s/%s_msinfo.json'%(params['global']['cwd'],params['global']['project_code']))==False:
msinfo = get_ms_info(msfile)
save_json(filename='%s/%s_msinfo.json'%(params['global']['cwd'],params['global']['project_code']), array=get_ms_info('%s/%s.ms'%(params['global']['cwd'],params['global']['project_code'])), append=False)
else:
msinfo = load_json('%s/%s_msinfo.json'%(params['global']['cwd'],params['global']['project_code']))
for i in range(len(fields)):
if (params['global']['job_manager'] == 'pbs'):
commands.append('cd %s'%params['global']['cwd'])
for k in params['global']['AOflag_command']:
commands.append(k)
msfile='%s.ms'%params['global']['project_code']
ids = []
for j in fields[i]:
ids.append(str(msinfo['FIELD']['fieldtoID'][j]))
commands[-1] = commands[-1]+' -fields %s '%(",".join(ids))
commands[-1] = commands[-1]+'-strategy %s %s'%(params[step]['AO_flag_strategy'][i],msfile)
elif aoflag=='apply_to_all':
if (params['global']['job_manager'] == 'pbs'):
commands.append('cd %s'%params['global']['cwd'])
variable='${array[$a]}'
elif (params['global']['job_manager'] == 'slurm'):
commands.append('a=$SLURM_ARRAY_TASK_ID')
variable='${array[$a]}'
commands.append('readarray array < %s/target_files.txt'%params['global']['cwd'])
if (params['global']['job_manager'] == 'bash'):
variable=''
if parallel == True:
mpicasapath = params['global']['mpicasapath']
else:
mpicasapath = ''
if params['global']['singularity'] == True:
singularity='singularity exec'
else:
singularity=''
if (params['global']['job_manager'] == 'pbs'):
job_commands=''
commands.append('cd %s'%params['global']['cwd'])
if (parallel == True):
job_commands='--map-by node -hostfile $PBS_NODEFILE'
else:
job_commands=''
if casa6 == False:
commands.append('%s %s %s %s --nologger --log2term -c %s/run_%s.py 0 %s'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step,variable))
else:
commands.append('%s %s %s %s %s/run_%s.py 0 %s'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step,variable))
if params["init_flag"]["run_AOflag"] == True:
if (params['global']['job_manager'] == 'bash'):
commands.append('for a in \"${array[@]}\"')
commands.append('do')
variable="$a"
commands.append("IFS=' ' read -r -a arrays <<< \"%s\""%variable)
for i in params['global']['AOflag_command']:
commands.append(i)
tar_idx = find_nestlist(params['init_flag']['AO_flag_fields'], params['global']['targets'][0])[0]
commands[-1] = commands[-1]+' -strategy %s ${arrays[1]}_presplit.ms'%(params['init_flag']['AO_flag_strategy'][tar_idx])
if (params['global']['job_manager'] == 'bash'):
commands.append('done')
variable=""
if casa6 == False:
commands.append('%s %s %s %s --nologger --log2term -c %s/run_%s.py 1 %s'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step,variable))
else:
commands.append('%s %s %s %s %s/run_%s.py 1 %s'%(mpicasapath,job_commands,singularity,casapath,vlbipipepath,step,variable))
else:
casalog.post(priority='SEVERE',origin=func_name,message='Error with writing commands.')
sys.exit()
commands.append('mv "casa"*"log" "logs"')
job_m = params['global']['job_manager']
with open('job_%s.%s'%(step,job_m), 'a') as filehandle:
for listitem in commands:
filehandle.write('%s\n' % listitem)
def find_nestlist(mylist, char):
for sub_list in mylist:
if char in sub_list:
return (mylist.index(sub_list), sub_list.index(char))
raise ValueError("'{char}' is not in list".format(char = char))
def write_job_script(steps,job_manager):
commands=['#!/bin/bash', 'set -e']
for i,j in enumerate(steps):
if i==0:
depend=''
else:
if job_manager=='pbs':
depend='-W depend=afterany:$%s'%(steps[i-1])
if job_manager=='slurm':
depend='--dependency=afterany:$%s'%(steps[i-1])
if job_manager=='bash':
depend=''
if job_manager=='pbs':
commands.append("%s=$(qsub %s job_%s.pbs)"%(j,depend,j))
if job_manager=='slurm':
commands.append('%s=$(sbatch --parsable %s job_%s.slurm)'%(j,depend,j))
if job_manager=='bash':
commands.append('bash job_%s.bash'%(j))
with open('vp_runfile.bash','w') as f:
for listitem in commands:
f.write('%s\n' % listitem)
f.close()
def get_ms_info(msfile):
tb = casatools.table()
ms = casatools.ms()
msinfo={}
## antenna information
tb.open('%s/ANTENNA'%msfile)
ants = tb.getcol('NAME')
ant={}
ant['anttoID'] =dict(zip(ants, np.arange(0,len(ants),1)))
ant['IDtoant'] = dict(zip(np.arange(0,len(ants),1).astype(str),ants))
msinfo['ANTENNAS']=ant
tb.close()
## get spw information
tb.open('%s/SPECTRAL_WINDOW'%msfile)
spw={}
spw['nspws'] = len(tb.getcol('TOTAL_BANDWIDTH'))
spw['bwidth'] = np.sum(tb.getcol('TOTAL_BANDWIDTH'))
spw['spw_bw'] = spw['bwidth']/spw['nspws']
spw['freq_range'] = [tb.getcol('CHAN_FREQ')[0][0],tb.getcol('CHAN_FREQ')[0][0]+spw['bwidth']]
spw['cfreq'] = np.average(spw['freq_range'])
if ((np.max(tb.getcol('CHAN_WIDTH')) == np.min(tb.getcol('CHAN_WIDTH')))&(np.max(tb.getcol('NUM_CHAN')) == np.min(tb.getcol('NUM_CHAN')))) == True:
spw['same_spws'] = True
spw['nchan'] = np.max(tb.getcol('NUM_CHAN'))
else:
spw['same_spws'] = False
spw['nchan'] = tb.getcol('NUM_CHAN')
if spw['same_spws'] == True:
spw['chan_width'] = tb.getcol('CHAN_WIDTH')[0][0]
else:
spw['chan_width'] = np.average(tb.getcol('CHAN_WIDTH'))
tb.close()
tb.open('%s/POLARIZATION'%msfile)
spw['npol'] = tb.getcol('NUM_CORR')[0]
polariz = tb.getcol('CORR_TYPE').flatten()
ID_to_pol={'0': 'Undefined',
'1': 'I',
'2': 'Q',
'3': 'U',
'4': 'V',
'5': 'RR',
'6': 'RL',
'7': 'LR',
'8': 'LL',
'9': 'XX',
'10': 'XY',
'11': 'YX',
'12': 'YY',
'13': 'RX',
'14': 'RY',
'15': 'LX',
'16': 'LY',
'17': 'XR',
'18': 'XL',
'19': 'YR',
'20': 'YL',
'21': 'PP',
'22': 'PQ',
'23': 'QP',
'24': 'QQ',
'25': 'RCircular',
'26': 'LCircular',
'27': 'Linear',
'28': 'Ptotal',
'29': 'Plinear',
'30': 'PFtotal',
'31': 'PFlinear',
'32': 'Pangle'}
pol2=[]
for i,j in enumerate(polariz):
pol2.append(ID_to_pol[str(j)])
spw['spw_pols'] = pol2
tb.close()
msinfo['SPECTRAL_WINDOW'] = spw
## Get field information
tb.open('%s/FIELD'%msfile)
fields = tb.getcol('NAME')
field = {}
field['fieldtoID'] =dict(zip(fields, np.arange(0,len(fields),1)))
field['IDtofield'] = dict(zip(np.arange(0,len(fields),1).astype(str),fields))
tb.close()
## scans
ms.open(msfile)
scans = ms.getscansummary()
ms.close()
scan = {}
for i in list(scans.keys()):
fieldid = scans[i]['0']['FieldId']
if fieldid not in list(scan.keys()):
scan[fieldid] = [i]
else:
vals = scan[fieldid]
scan[fieldid].append(i)
msinfo['SCANS'] = scan
## Get telescope_name
tb.open('%s/OBSERVATION'%msfile)
msinfo['TELE_NAME'] = tb.getcol('TELESCOPE_NAME')[0]
tb.close()
image_params = {}
high_freq = spw['freq_range'][1]
ms.open(msfile)
f = []
indx = []
for i in field['fieldtoID'].keys():
ms.selecttaql('FIELD_ID==%s'%field['fieldtoID'][i])
try:
max_uv = ms.getdata('uvdist')['uvdist'].max()
image_params[i] = ((speed_light/high_freq)/max_uv)*(180./np.pi)*(3.6e6/5.)
f.append(i)
indx.append(field['fieldtoID'][i])
except:
pass
ms.reset()
ms.close()
field = {}
field['fieldtoID'] =dict(zip(f, indx))
field['IDtofield'] =dict(zip(np.array(indx).astype(str),f))
msinfo['FIELD'] = field
msinfo["IMAGE_PARAMS"] = image_params
return msinfo
def fill_flagged_soln(caltable='', fringecal=False):
"""
This is to replace the gaincal solution of flagged/failed solutions by the nearest valid
one.
If you do not do that and applycal blindly with the table your data gets
flagged between calibration runs that have a bad/flagged solution at one edge.
Can be pretty bad when you calibrate every hour or more
(when you are betting on self-cal) of observation (e.g L-band of the EVLA)..one can
lose the whole hour of good data without realizing !
"""
if fringecal==False:
gaincol='CPARAM'
else:
gaincol='FPARAM'
tb = casatools.table()
tb.open(caltable, nomodify=False)
flg=tb.getcol('FLAG')
#sol=tb.getcol('SOLUTION_OK')
ant=tb.getcol('ANTENNA1')
gain=tb.getcol(gaincol)
t=tb.getcol('TIME')
dd=tb.getcol('SPECTRAL_WINDOW_ID')
#dd=tb.getcol('CAL_DESC_ID')
maxant=np.max(ant)
maxdd=np.max(dd)
npol=len(gain[:,0,0])
nchan=len(gain[0,:,0])
k=1
numflag=0.0
for k in range(maxant+1):
for j in range (maxdd+1):
subflg=flg[:,:,(ant==k) & (dd==j)]
subt=t[(ant==k) & (dd==j)]
#subsol=sol[:,:,(ant==k) & (dd==j)]
subgain=gain[:,:,(ant==k) & (dd==j)]
for kk in range(1, len(subt)):
for chan in range(nchan):
for pol in range(npol):
if(subflg[pol,chan,kk] and not subflg[pol,chan,kk-1]):
numflag += 1.0
subflg[pol,chan,kk]=False
#subsol[pol, chan, kk]=True
subgain[pol,chan,kk]=subgain[pol,chan,kk-1]
if(subflg[pol,chan,kk-1] and not subflg[pol,chan,kk]):
numflag += 1.0
subflg[pol,chan,kk-1]=False
#subsol[pol, chan, kk-1]=True
subgain[pol,chan,kk-1]=subgain[pol,chan,kk]
flg[:,:,(ant==k) & (dd==j)]=subflg
#sol[:,:,(ant==k) & (dd==j)]=subsol
gain[:,:,(ant==k) & (dd==j)]=subgain
###
tb.putcol('FLAG', flg)
#tb.putcol('SOLUTION_OK', sol)
tb.putcol(gaincol, gain)
tb.done()
def fill_flagged_soln2(caltable='', fringecal=False):
"""
This is to replace the gaincal solution of flagged/failed solutions by the nearest valid
one.
If you do not do that and applycal blindly with the table your data gets
flagged between calibration runs that have a bad/flagged solution at one edge.
Can be pretty bad when you calibrate every hour or more
(when you are betting on self-cal) of observation (e.g L-band of the EVLA)..one can
lose the whole hour of good data without realizing !
"""
if fringecal==False:
gaincol='CPARAM'
else:
gaincol='FPARAM'
tb=casatools.table()
tb.open(caltable, nomodify=False)
flg=tb.getcol('FLAG')
#sol=tb.getcol('SOLUTION_OK')
ant=tb.getcol('ANTENNA1')
gain=tb.getcol(gaincol)
t=tb.getcol('TIME')
dd=tb.getcol('SPECTRAL_WINDOW_ID')
#dd=tb.getcol('CAL_DESC_ID')
maxant=np.max(ant)
maxdd=np.max(dd)
npol=len(gain[:,0,0])
nchan=len(gain[0,:,0])
k=1
numflag=0.0
for k in range(maxant+1):
for j in range (maxdd+1):
subflg=flg[:,:,(ant==k) & (dd==j)]
subt=t[(ant==k) & (dd==j)]
#subsol=sol[:,:,(ant==k) & (dd==j)]
subgain=gain[:,:,(ant==k) & (dd==j)]
#print 'subgain', subgain.shape
for kk in range(1, len(subt)):
for chan in range(nchan):
for pol in range(npol):
if(subflg[pol,chan,kk] and not subflg[pol,chan,kk-1]):
numflag += 1.0
subflg[pol,chan,kk]=False
#subsol[pol, chan, kk]=True
subgain[pol,chan,kk]=subgain[pol,chan,kk-1]
if(subflg[pol,chan,kk-1] and not subflg[pol,chan,kk]):
numflag += 1.0
subflg[pol,chan,kk-1]=False
#subsol[pol, chan, kk-1]=True
subgain[pol,chan,kk-1]=subgain[pol,chan,kk]
for kk in range(len(subt)-2,-1, -1):
for chan in range(nchan):
for pol in range(npol):
if(subflg[pol,chan,kk] and not subflg[pol,chan,kk+1]):
numflag += 1.0
subflg[pol,chan,kk]=False
#subsol[pol, chan, kk]=True
subgain[pol,chan,kk]=subgain[pol,chan,kk+1]
if(subflg[pol,chan,kk] and not subflg[pol,chan,kk]):
numflag += 1.0
subflg[pol,chan,kk+1]=False
#subsol[pol, chan, kk-1]=True
subgain[pol,chan,kk+1]=subgain[pol,chan,kk]
flg[:,:,(ant==k) & (dd==j)]=subflg
#sol[:,:,(ant==k) & (dd==j)]=subsol
gain[:,:,(ant==k) & (dd==j)]=subgain
###
tb.putcol('FLAG', flg)
#tb.putcol('SOLUTION_OK', sol)
tb.putcol(gaincol, gain)
tb.done()
def filter_tsys_auto(caltable,nsig=[2.5,2.],jump_pc=20):
func_name = inspect.stack()[0][3]
tb=casatools.table()
tb.open(caltable, nomodify=False)
flg=tb.getcol('FLAG')
#sol=tb.getcol('SOLUTION_OK')
gaincol='FPARAM'
ant=tb.getcol('ANTENNA1')
gain=tb.getcol(gaincol)
gain_edit = copy.deepcopy(gain)*0
t=tb.getcol('TIME')
dd=tb.getcol('SPECTRAL_WINDOW_ID')
npol=gain.shape[0]
casalog.post(priority="INFO",origin=func_name,message='Editing and smoothing the tsys table')
for k in range(npol):
for i in np.unique(ant):
for j in np.unique(dd):
flg_temp=flg[k,0,((ant==i)&(dd==j))]
gain_uflg2=gain[k,0,((ant==i)&(dd==j))]
gain_uflg = gain_uflg2[flg_temp==0]
if len(gain_uflg) != 0:
t_temp=t[((ant==i)&(dd==j))][flg_temp==0]
gain_uflg,detected_outliers = hampel_filter(np.array([t_temp,gain_uflg]), 41 ,n_sigmas=nsig[0])
gain_uflg,detected_outliers = hampel_filter(np.array([t_temp,gain_uflg]), 10 ,n_sigmas=nsig[1])
#gain_uflg,detected_outliers = hampel_filter(np.array([t_temp,gain_uflg]), 5 ,n_sigmas=2.5)
gain_uflg, jump = detect_jump_and_smooth(gain_uflg,jump_pc=jump_pc)
if jump == False:
gain_uflg = smooth_series(gain_uflg, 21)
gain_uflg2[flg_temp==0] = gain_uflg
ind = np.where(np.isnan(gain_uflg2[flg_temp==0]))[0]
flg_temp2 = flg_temp[flg_temp==0]
flg_temp2[ind] = 1
flg_temp[flg_temp==0] = flg_temp2
flg[k,0,((ant==i)&(dd==j))] = flg_temp
gain_edit[k,0,((ant==i)&(dd==j))]= gain_uflg2
tb.putcol('FPARAM',gain_edit)
tb.putcol('FLAG',flg)
tb.close()
def smooth_series(y, box_pts):
box = np.ones(box_pts)/box_pts
y_smooth = np.convolve(y, box, mode='valid')
y_smooth = np.hstack([np.ones(np.floor(box_pts/2.).astype(int))*y_smooth[0],y_smooth])
y_smooth = np.hstack([y_smooth,np.ones(np.floor(box_pts/2.).astype(int))*y_smooth[-1]])
return y_smooth
def hampel_filter(input_series, window_size, n_sigmas=3):
n = len(input_series[1])
new_series = input_series.copy()
k = 1.4826 # scale factor for Gaussian distribution
indices = []
# possibly use np.nanmedian
for i in range((window_size),(n - window_size)):
x0 = np.median(input_series[1][(i - window_size):(i + window_size)])
S0 = k * np.median(np.abs(input_series[1][(i - window_size):(i + window_size)] - x0))
if i == window_size:
for j in range(0,window_size):
if (np.abs(input_series[1][j] - x0) > n_sigmas * S0):
new_series[1][j] = x0
indices.append(j)
elif i == ((n - window_size)-1):
for j in range(n-window_size,n):
if (np.abs(input_series[1][j] - x0) > n_sigmas * S0):
new_series[1][j] = x0
indices.append(j)
else:
if (np.abs(input_series[1][i] - x0) > n_sigmas * S0):
new_series[1][i] = x0
indices.append(i)
detected_outliers = np.array(indices)
already_tagged=[]
for i in range(len(input_series[1])):
if ((i<input_series[0].shape[0]-1)&(i>0)):
if i in detected_outliers:
if i not in already_tagged:
low=i-1
t_low=input_series[0][low]
while i+1 in detected_outliers:
i+=1
already_tagged.append(i)
if i < (input_series[0].shape[0]-1):
high=i+1
t_high=input_series[0][high]
f = interp1d(x=[t_low,t_high], y=[input_series[1][low],input_series[1][high]])
input_series[1][low:high]= f(input_series[0][np.arange(low,high,1)])
if 0 in detected_outliers:
input_series[1][0] = input_series[1][1]
if (input_series[0].shape[0]-1) in detected_outliers:
i = (input_series[0].shape[0]-1)
while i-1 in detected_outliers:
i-=1
input_series[1][i:input_series[0].shape[0]] = input_series[1][input_series[0].shape[0]-(i-2)]
return input_series[1],detected_outliers
def detect_jump_and_smooth(array,jump_pc):
jump_pc=jump_pc/100.
try:
for i,j in enumerate(array):
if i<array.shape[0]-2:
if (array[i+1] > 1.1*array[i])|(array[i+1]<0.9*array[i]):
jump=True
low=i
if i < len(array)-1:
i+=1
while ((array[i+1] > (1+jump_pc)*array[i])==False)&((array[i+1]<(1-jump_pc)*array[i])==False):
if i > (len(array)-3):
break
else:
i+=1
high=i+1
diff=int((high-low)/2.)
if diff%2 == 0:
diff=diff+1
array[low:high] = smooth_series(array[low:high],diff)
else:
jump=False
else:
jump=False
return array, jump
except:
jump=False
return array, jump
def append_gaintable(gaintables,caltable_params):
for i,j in enumerate(gaintables.keys()):
if j != 'parang':
gaintables[j].append(caltable_params[i])
return gaintables
def load_gaintables(params,casa6):
cwd=params['global']['cwd']
if os.path.exists('%s/vp_gaintables.json'%(cwd)) == False:
gaintables=OrderedDict({})
for a,b in zip(('gaintable','gainfield','spwmap','interp','parang'), ([],[],[],[],params['global']['do_parang'])):
gaintables[a]=b
else:
gaintables=load_json('%s/vp_gaintables.json'%(cwd),Odict=True,casa6=casa6)
return gaintables
def find_refants(pref_ant,msinfo):
antennas = msinfo['ANTENNAS']['anttoID'].keys()
refant=[]
for i in pref_ant:
if i in antennas:
refant.append(i)
return ",".join(refant)
def calc_edge_channels(value,nspw,nchan):
func_name = inspect.stack()[0][3]
if (type(value) == str):
if value.endswith('%'):
value=np.round((float(value.split('%')[0])/100.)*float(nchan),0).astype(int)
else:
casalog.post(priority='SEVERE',origin=func_name,message='Edge channels either needs to be an integer (number of channels) or a string with a percentage i.e. 5%')
sys.exit()
elif (type(value)==int):
value=value
else:
casalog.post(priority='SEVERE',origin=func_name,message='Edge channels either needs to be an integer (number of channels) or a string with a percentage i.e. 5%')
sys.exit()
flag_chans=[]
for i in range(nspw):
flag_chans.append('%d:0~%d;%d~%d'%(i,value-1,(nchan-1)-(value-1),(nchan-1)))
return ",".join(flag_chans)
def time_convert(mytime, myunit='s'):
qa = casatools.quanta()
if type(mytime) != list:
mytime=[mytime]
myTimestr = []
for i,time in enumerate(mytime):
q1=qa.quantity(time,myunit)
time1=qa.time(q1,form='ymd')[0]
z=0
if i!=0:
if split_str(time1,'/',3)[0] == split_str(myTimestr[z],'/',3)[0]:
time1 = split_str(time1,'/',3)[1]
else:
z=i
myTimestr.append(time1)
return myTimestr
def split_str(strng, sep, pos):
strng = strng.split(sep)
return sep.join(strng[:pos]), sep.join(strng[pos:])
def clip_bad_solutions(fid, table_array, caltable, solint, passmark):
TOL=solint/2.01
tb = casatools.table()
tb.open(caltable)
ant = tb.getcol('ANTENNA1')
value = tb.getcol('FPARAM')
flag = tb.getcol('FLAG')
time_a = tb.getcol('TIME')
time = np.unique(tb.getcol('TIME'))
time = np.unique(np.floor(time/TOL).astype(int))*TOL
field_id = tb.getcol('FIELD_ID')
solns = np.sum(table_array[0],axis=0)
for z in fid.keys():
maxsoln = np.max(solns[fid[z][0]:fid[z][1]])
for j in range(fid[z][0],fid[z][1]+1):
result = np.isclose(time_a, time[j], atol=TOL,rtol=1e-10)
if solns[j] < passmark*maxsoln:
flag[:,0,(result)] = True
tb.open(caltable, nomodify=False)
tb.putcol('FLAG',np.multiply(flag, 1).astype(int))
tb.close()