-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.nf
6939 lines (6332 loc) · 263 KB
/
main.nf
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 nextflow
nextflow.enable.dsl=2
include {
birli_argstr_suffix;
calqa_pass;
cmt_imgqa_pass_sub;
cmt_imgqa_pass;
cmt_ps_metrics_pass_sub;
cmt_ps_metrics_pass;
coerceList;
contigRanges;
decomposeImg;
deepcopy;
displayInts;
displayRange;
exitCodes;
firstFail;
get_seconds;
getFailReason;
groovy2bashAssocArray;
groupMeta;
hyp_apply_name;
is_multichannel;
is_multiinterval;
isNaN;
mapMerge;
obsids_file;
openWithDelay;
parseCsv;
parseFloatOrNaN;
parseJson;
prepqa_pass;
results_dir;
wrap_angle;
wscleanDConvParams;
wscleanParams;
wsSummarize;
} from './modules/utils.nf'
// default entrypoint: get preprocessed vis from asvo and run qa
workflow {
// get obsids from csv
obsCSV = channel.of(obsids_file())
.splitCsv()
.filter { line -> !line[0].startsWith('#') }
.map { line ->
def (obsid, cluster) = line
def meta = [:]
if (cluster != null) {
meta.cluster = cluster
}
[obsid, deepcopy(meta)]
}
obsids = obsCSV.map { obsid, _m -> obsid }
// analyse obsids with web services
obsids | ws
ws.out.obsMetafits
.map { obsid, _metafits -> obsid }
.collectFile(
name: "ws_obs_pass.csv", newLine: true, sort: true,
storeDir: "${results_dir()}"
)
| view { [it, it.readLines().size()] }
// download preprocessed, unless noprep is set
if (params.noprep) {
prep(channel.empty())
} else {
prep(ws.out.obsMeta.join(ws.out.obsMetafits))
}
// channel of obsids that pass the flag gate
prep.out.subobsMetaVisPass
.map { obsid, meta, vis -> [obsid, meta.subobs?:'', meta.name?:'', vis].join('\t') }
.collectFile(
name: "prep_subobs_name_pass.csv", newLine: true, sort: true,
storeDir: "${results_dir()}"
)
| view { [it, it.readLines().size()] }
qaPrep( prep.out.subobsMetaVisPass, ws.out.obsMetafits )
if (!params.novideo) {
ws.out.frame
.mix(prep.out.frame)
.mix(qaPrep.out.frame)
| makeVideos
}
// make zips
if (params.tarchive) {
prep.out.zip.mix(qaPrep.out.zip) | makeTarchives
}
all_fail_codes = ws.out.fail_codes
.join(prep.out.fail_codes, remainder: true)
.join(qaPrep.out.fail_codes, remainder: true)
.map { obsid, ws_code, prep_code, prepqa_code ->
def codes = [ws_code, prep_code, prepqa_code].findAll { it != null }
def aFailCode = coerceList(firstFail([codes]))[0]
[obsid, aFailCode]
}
// do lst counts, scatterplot
all_fail_codes
.filter { _o, fail_code -> fail_code == getFailReason(0x00) }
.join(ws.out.obsMeta)
.map { obsid, _fail_code, meta ->
[obsid, meta.lst.round().intValue()]
}
.groupTuple(by: 1)
.map { obsids_, lst ->
[
String.format("%+03d", lst),
obsids_.size(),
].join("\t")
}
.collectFile(
name: "lst_counts_all.tsv", newLine: true, sort: true,
seed: ([ "LST", "COUNT" ]).join("\t"),
storeDir: "${results_dir()}${params.img_suffix}${params.cal_suffix}"
)
.view { it.readLines().size() }
.map { tsv ->
def meta = [
name: "lst_counts_all", title: "lst counts after qa",
x: "LST", y: "COUNT"
]
[meta, tsv]
}
| tsvScatterPlot
// do ewp counts
all_fail_codes
.filter { _o, fail_code -> fail_code == getFailReason(0x00) }
.join(ws.out.obsMeta)
.map { obsid, _fail_code, meta ->
[obsid, meta.ew_pointing]
}
.groupTuple(by: 1)
.map { obsids_, ewp ->
[
ewp == null ? "" : String.format("%+1d", ewp),
obsids_.size(),
].join("\t")
}
.collectFile(
name: "ewp_counts_all.tsv", newLine: true, sort: true,
seed: ([ "LST", "COUNT" ]).join("\t"),
storeDir: "${results_dir()}${params.img_suffix}${params.cal_suffix}"
)
all_fail_codes.groupTuple(by: 1)
.map { obsids_, fail_code ->
[
fail_code,
obsids_.size(),
].join("\t")
}
.collectFile(
name: "fail_counts_all.tsv", newLine: true, sort: true,
seed: ([ "FAIL CODE", "COUNT" ]).join("\t"),
storeDir: "${results_dir()}${params.img_suffix}${params.cal_suffix}"
)
}
// download observation metadata from webservices in json format
process wsMeta {
// persist results in outdir, process will be skipped if files already present.
storeDir "${params.outdir}/meta"
// tag to identify job in squeue and nf logs
tag "${obsid}"
time {5.minute * task.attempt * params.scratchFactor}
// allow multiple retries
maxRetries 2
errorStrategy {
if (task.attempt > 2) {
return 'ignore'
}
return (task.exitStatus == 8 ? 'retry' : 'ignore')
}
input:
val(obsid)
output:
tuple val(obsid), path(wsmeta), path(wsfiles)
script:
wsmeta = "${obsid}_wsmeta.json"
wsfiles = "${obsid}_files.json"
"""
#!/bin/bash -eux
${params.proxy_prelude} # ensure proxy is set if needed
wget -O "${wsmeta}" "http://ws.mwatelescope.org/metadata/obs?obs_id=${obsid}&extended=1&dict=1"
wget -O "${wsfiles}" "http://ws.mwatelescope.org/metadata/data_ready?obs_id=${obsid}"
"""
}
process tapMeta {
storeDir "${params.outdir}/meta"
label "tap"
tag "${obsid}"
input:
val(obsid)
output:
tuple val(obsid), path(tapmeta)
script:
tapmeta = "${obsid}_tapmeta.json"
template "tapmeta.py"
}
// download observation metadata from webservices in metafits format
process wsMetafits {
storeDir "${params.outdir}/${obsid}/raw"
label "rate_limit"
tag "${obsid}"
input:
val(obsid)
output:
tuple val(obsid), path(metafits)
script:
metafits = "${obsid}.metafits"
"""
#!/bin/bash -eux
${params.proxy_prelude} # ensure proxy is set if needed
wget -O "${metafits}" "http://ws.mwatelescope.org/metadata/fits?obs_id=${obsid}&include_ppds=${params.metafits_incl_ppds}"
"""
}
process wsSkyMap {
storeDir "${params.outdir}/${obsid}/meta"
label "rate_limit"
tag "${obsid}"
input:
val(obsid)
output:
tuple val(obsid), path(skymap)
script:
skymap = "${obsid}_skymap.png"
"""
#!/bin/bash -eux
${params.proxy_prelude} # ensure proxy is set if needed
wget -O "${skymap}" "http://ws.mwatelescope.org/observation/skymap/?obs_id=${obsid}"
"""
}
process wsPPDs {
storeDir "${params.outdir}/${obsid}/meta"
tag "${obsid}"
label "rate_limit"
input:
val(obsid)
output:
tuple val(obsid), path(ppds)
when: !params.noppds
script:
ppds = "${obsid}_ppds.png"
"""
#!/bin/bash -eux
${params.proxy_prelude} # ensure proxy is set if needed
curl "http://ws.mwatelescope.org/observation/ppds/?replot=replot&obs_id=${obsid}&merge=on&corgains=on&adu=on&plotscale=1.0"
wget -O "${ppds}" "http://ws.mwatelescope.org/observation/powerplot/?obs_id=${obsid}&group=False&plotscale=1.0&merge=1&corgains=1&adu=1&waterfall=False"
"""
}
process metaJson {
storeDir "${params.outdir}/${obsid}/meta"
tag "${obsid}"
errorStrategy 'ignore'
label "python"
input:
tuple val(obsid), path(metafits)
output:
tuple val(obsid), path(json), path(tsv)
script:
// metrics = "${obsid}_occupancy.json"
json = "${obsid}_meta.json"
tsv = "${obsid}_inputs.tsv"
txt = "${obsid}_inputs.txt"
template "metajson.py"
}
// temporary ASVO workaround, raw files from mwacache
process cacheBoxRaw {
storeDir "${params.outdir}/${obsid}/raw"
tag "${obsid}"
input:
tuple val(obsid), val(meta)
output:
tuple val(obsid), val(meta), path(metafits), path(raw)
script:
metafits = "${obsid}_metafits*.fits"
raw = "${obsid}_2*.fits"
"""
#!/bin/bash -eux
for i in {01..08}; do
for j in {1..3}; do
rsync -auz --info=progress2 \
mwacache\${i}:/volume\${j}/incoming/${obsid}'*'.fits . \
|| true
done
done
ls -al
"""
}
process birliPrepUV {
storeDir "${params.outdir}/${obsid}/prep"
label "birli"
label "cpu_half"
time { params.scratchFactor * 1.hour * Math.pow(task.attempt, 2) }
disk { 50.GB * Math.pow(task.attempt, 2) }
stageInMode "symlink"
memory { 200.GB * task.attempt }
errorStrategy { task.exitStatus in 137..140 ? 'retry' : 'ignore' }
tag "${obsid}${birli_argstr_suffix()[2]?:''}"
input:
tuple val(obsid), val(meta_), path(metafits), path(raw)
output:
tuple val(obsid), val(meta), path(uvfits)
// , path("${obsid}${spw}*.mwaf"), path("birli_prep.log")
when: !params.noprep
script:
meta = deepcopy(meta_)
prefix = "birli_"
def (_argstr_asvo, argstr_cli, suffix) = birli_argstr_suffix()
if (meta.freq_res != null && meta.freq_res > params.prep_freq_res_khz) {
throw new Exception("error: target freq_res ${params.prep_freq_res_khz} < obs freq res ${meta.freq_res}. \nmeta=${meta}")
}
meta.prep_freq_res = params.prep_freq_res_khz?:meta.freq_res
meta.prep_time_res = params.prep_time_res_s?:meta.time_res
def coarse_chans = (meta.coarse_chans?:[]).sort(false)
def not_contiguous = (coarse_chans.size > 1 && coarse_chans.size < coarse_chans[-1] - coarse_chans[0])
def channel_glob = ""
if (not_contiguous) {
channel_glob = "_ch{??,???,??-??,??-???,???-???}"
} else if (meta['subobs']) {
subobs = meta['subobs']
if (subobs =~ /ch[\d-]+/) {
suffix += "_${subobs}"
}
}
meta['channel_glob'] = channel_glob
meta['birli_suffix'] = suffix
uvfits = ''+"${prefix}${obsid}${suffix}${channel_glob}.uvfits"
"""
set -eux
${params.birli} \
${argstr_cli} \
-u "${prefix}${obsid}${suffix}.uvfits" \
-m "${metafits}" \
${raw}
"""
}
process hypPrepVisConvert {
storeDir "${params.outdir}/${obsid}/prep"
label "hyperdrive_cpu"
time { params.scratchFactor * 1.hour * Math.pow(task.attempt, 2) }
disk { 50.GB * Math.pow(task.attempt, 2) }
stageInMode "symlink"
memory { 200.GB * task.attempt }
// errorStrategy { task.exitStatus in 137..140 ? 'retry' : 'ignore' }
errorStrategy 'terminate'
tag "${obsid}${suffix}"
input:
tuple val(obsid), val(meta_), path(metafits), path(uvfits)
output:
tuple val(obsid), val(meta), path(vis)
when: (params.prep_export_time_res_s != null || params.prep_export_freq_res_khz != null)
script:
meta = deepcopy(meta_)
prefix = "birli_"
suffix = '' + (params.prep_suffix ?: '')
args = [:]
if (meta['subobs'] != null) {
suffix += "_${subobs}"
}
if (params.prep_export_time_res_s != null) {
if (meta.prep_time_res != null && meta.prep_time_res > params.prep_export_time_res_s) {
throw new Exception("error: target time_res ${params.prep_export_time_res_s} < prep time res ${meta.prep_time_res}. \nmeta=${meta}")
}
suffix += "_${params.prep_export_time_res_s}s"
args['time-average'] = params.prep_export_time_res_s
}
if (params.prep_export_freq_res_khz != null) {
if (meta.prep_freq_res != null && meta.prep_freq_res > params.prep_export_freq_res_khz) {
throw new Exception("error: target freq_res ${params.prep_export_freq_res_khz} < prep freq res ${meta.prep_freq_res}. \nmeta=${meta}")
}
suffix += "_${params.prep_export_freq_res_khz}kHz"
args['freq-average'] = params.prep_export_freq_res_khz
}
if (params.ssins_apply) {
suffix += ".ssins"
}
prepFlags = meta.prepFlags?:[]
fineChanFlags = meta.fineChanFlags?:[]
if (prepFlags.size() > 0) {
args["tile-flags"] = "${prepFlags.join(' ')}"
}
if (prepFlags.size() > 0) {
args["tile-flags"] = "${prepFlags.join(' ')}"
}
if (fineChanFlags.size() > 0) {
args["fine-chan-flags-per-coarse-chan"] = "${fineChanFlags.join(' ')}"
}
argstr = args
.collect { k, v ->
if (v == null) {
['--' + k]
}
else {
['--' + k] + v
}
}
.flatten()
.join(' ')
vis = ''+"${prefix}${obsid}${suffix}.${params.prep_export_ext}"
"""
set -eux
${params.hyperdrive_cpu} vis-convert \
${argstr} \
-d $metafits $uvfits \
-o "${vis}"
"""
}
process demo03_mwalib {
stageInMode "symlink"
storeDir "${params.outdir}/${obsid}/raw_qa"
label "mwa_demo"
tag "${metafits.baseName}"
input:
tuple val(obsid), val(meta), path(metafits)
output:
tuple val(obsid), val(meta), path("${metafits.baseName}-antennas.tsv"), path("${metafits.baseName}-channels.tsv")
when: !params.nodemo
script:
"""
${params.demo_prelude?:''}
/demo/03_mwalib.py ${metafits}
"""
}
process demo04_ssins {
stageInMode "copy"
storeDir "${params.outdir}/${obsid}/${qa}_qa"
label "mwa_demo"
label "mem_super"
time 3.hour
tag "${base}${meta.plot_base?:''}"
input:
tuple val(obsid), val(meta), path(metafits), path(vis)
output:
tuple val(obsid), val(meta), path("${base}${meta.plot_base?:''}.png"), path("${base}${meta.mask_base?:''}*_SSINS_mask.h5")
when: !params.nodemo
script:
firstVis = coerceList(vis)[0]
if (firstVis.extension == "uvfits") {
base = firstVis.baseName
qa = "prep"
} else {
base = obsid
qa = "raw"
}
"""
${params.demo_prelude?:''}
/demo/04_ssins.py ${meta.argstr?:''} ${metafits} ${coerceList(vis).join(' ')}
"""
}
process demo11_allsky {
stageInMode "copy"
storeDir "${params.outdir}/${obsid}/img"
label "mwa_demo"
label "mem_super"
tag "${base}${meta.plot_base?:''}"
time 8.hours
input:
tuple val(obsid), val(meta), path(vis)
output:
tuple val(obsid), val(meta), path("${base}${meta.plot_base?:''}*.fits")
when: !params.nodemo
script:
base = coerceList(vis)[0].baseName
"""
${params.demo_prelude?:''}
/demo/11_allsky.py ${meta.argstr?:''} ${coerceList(vis).join(' ')}
"""
}
workflow extRaw {
channel.of(obsids_file())
.splitCsv()
.filter { line -> !line[0].startsWith('#') }
.map { line ->
def (obsid, _comment) = line
obsid
}
.unique()
.map { obsid_ ->
def obsid = coerceList(obsid_)[0]
def meta = [obsid: obsid]
// def raw = file("${params.outdir}/../raw/${obsid}_2?????????????_ch???_???.fits")
def raw = file("${params.outdir}/${obsid}/raw/${obsid}_2*.fits")
[ obsid, deepcopy(meta), raw ]
}
.filter { _o, _m, raw_ ->
def raw = coerceList(raw_)
raw.size() && raw.every{
if (!it.exists()) { print("raw does not exist: ${it}") }
it.exists()
}
}
.tap { obsMetaRaw }
.map { obsid, _m, _raw -> obsid }
.tap { obsids }
obsids | ws
obsMetaRaw.join(ws.out.obsMeta).join(ws.out.obsMetafits)
.map { obsid, meta, vis, wsMeta, metafits ->
[ obsid, mapMerge(meta, wsMeta), metafits, vis ]
}
| birliPrepUV
birliPrepUV.out.flatMap { obsid, meta, uvfits_ ->
def uvfits = coerceList(uvfits_)
if (uvfits.size > 1) {
uvfits.collect { f ->
def newMeta = [:]
def last_token = '' + f.baseName.split('_')[-1]
if (last_token =~ /ch[\d-]+/) {
newMeta.subobs = last_token
}
[obsid, mapMerge(meta, newMeta), f]
}
} else {
[[obsid, meta, uvfits_]]
}
}
.tap { subobsVis }
| uvMeta
ws.out.obsMeta.cross(uvMeta.out) { it[0] }
.map { obsMeta_, uvMeta_ ->
def (obsid, wsMeta) = obsMeta_
def (_o, meta_, uvJson) = uvMeta_
def uvmeta = parseJson(uvJson)
def newMeta = [
lowfreq: uvmeta.freqs[0],
freq_res: (uvmeta.freqs[1] - uvmeta.freqs[0]),
nchans: (uvmeta.freqs?:[]).size(),
ntimes: (uvmeta.times?:[]).size(),
]
['config', 'eorband', 'num_ants', 'total_weight'].each { key ->
if (uvmeta[key] != null) {
newMeta[key] = uvmeta[key]
}
}
if (newMeta.ntimes > 0) {
newMeta.lst = Math.toDegrees(uvmeta.times[0].lst_rad)
}
[obsid, mapMerge(mapMerge(meta_, wsMeta), newMeta)]
}
.tap { subobsMeta }
.cross(subobsVis) { def (obsid, meta) = it; [obsid, meta.subobs?:''] }
.map { subobsMeta_, subobsVis_ ->
def (obsid, meta) = subobsMeta_
def (_o, _m, uvfits) = subobsVis_
[obsid, meta, uvfits]
}
.tap { subobsMetaVis }
flag(subobsMetaVis, ws.out.obsMetafits)
// for all obs that pass flag:
flag.out.subobsFlagmetaPass.map { obsid, meta, flagMeta ->
// update meta with flagMeta
[[obsid, meta.subobs?:''], mapMerge(meta, flagMeta)]
}
// join with vis from subobsMetaVis
.join(subobsMetaVis.map { obsid, meta, uvfits ->
[[obsid, meta.subobs?:''], uvfits]
})
.map { obsSubobs, meta, uvfits ->
def (obsid, _subobs) = obsSubobs
[obsid, meta, uvfits]
}
| ssinsQA
qaPrep( ssinsQA.out.subobsMetaVisSSINs, ws.out.obsMetafits )
ws.out.frame.mix(flag.out.frame)
.mix(ssinsQA.out.frame)
.mix(qaPrep.out.frame)
.map { n, l -> [n, l as ArrayList] }
| makeVideos
}
workflow asvoRawFlow {
channel.of(obsids_file())
.splitCsv()
.filter { line -> !line[0].startsWith('#') }
.map { line ->
def (obsid, _comment) = line
obsid
}
.unique()
| asvoRaw
asvoRaw.out
.filter { _o, _metafits, raw_ ->
def raw = coerceList(raw_)
raw.size() && raw.every{
if (!it.exists()) { print("raw does not exist: ${it}") }
it.exists()
}
}
.map { obsid, _m, raw ->
def meta = [:]
[obsid, meta, raw]
}
.tap { obsMetaRaw }
.map { obsid, _m, _raw -> obsid }
.tap { obsids }
// todo combine with extRaw
// }
// workflow raw {
// take:
// obsMetaRaw
// main:
obsids | ws
obsMetaRaw.join(ws.out.obsMeta).join(ws.out.obsMetafits)
.map { obsid, meta, vis_, wsMeta, metafits ->
[ obsid, mapMerge(meta, wsMeta), metafits, coerceList(vis_) ]
}
.tap { obsMetaMetafitsRaw }
if (params.prepByCh) {
rawByCh = obsMetaMetafitsRaw.join(ws.out.mwalibMeta)
.flatMap { obsid, _m, _metafits, vis, mwalibMeta ->
vis.collect { f ->
def channels = (mwalibMeta.channels?:[]).withIndex().collect { chan, idx ->
chan['idx'] = idx;
chan
}
def (obsid_, _datestamp, chan, _batch) = f.baseName.split('_')
if ((obsid_ as Integer) != (obsid as Integer)) {
throw new Exception("obsid mismatch in ${f}: ${obsid_} != ${obsid}")
}
def gpuboxMatch = chan =~ /gpubox([\d]+)/
def chMatch = chan =~ /ch([\d]+)/
def channelInfo = null
if (gpuboxMatch) {
channelInfo = channels.findAll { it['gpubox_number'] as Integer == gpuboxMatch[0][1] as Integer }[0]
} else if (chMatch) {
channelInfo = channels.findAll { it['rec_chan_number'] as Integer == chMatch[0][1] as Integer }[0]
} else {
throw new Exception("unknown channel in ${f}")
}
[obsid, channelInfo.rec_chan_number, channelInfo.idx, f]
}
}
.groupTuple(by: 0..2)
obsWsmetaVis = obsMetaMetafitsRaw.cross(rawByCh).map { obsMetaMetafitsRaw_, rawByCh_ ->
def (obsid, meta, metafits, _raw) = obsMetaMetafitsRaw_
def (_o, chan, chanIdx, vis) = rawByCh_
def newMeta = [subobs:"ch${chan}", coarse_chans:[chan], birli_chan_ranges:["${chanIdx}"]]
[obsid, mapMerge(meta, newMeta), metafits, vis]
}
.tap { obsMetafitsRawByCh }
| birliPrepUV
} else {
obsMetafitsRawByCh = obsMetaMetafitsRaw
obsWsmetaVis = obsMetaMetafitsRaw | birliPrepUV
}
obsMetafitsRawByCh.flatMap { obsid, meta, metafits, vis ->
[
['--autos', '.diff.auto', '.spectrum'],
['--no-diff --autos', '.auto', '.spectrum'],
['--crosses', '.diff.cross', '.spectrum'],
['--crosses --no-diff', '.cross', '.spectrum'],
// ['--sigchain --autos', '.diff.auto', '.sigchain'],
// ['--sigchain --no-diff --autos', '.auto', '.sigchain'],
// ['--sigchain --crosses', '.diff.cross', '.sigchain'],
// ['--sigchain --no-diff --crosses', '.cross', '.sigchain'],
].collect { argstr, plot_prefix, plot_suffix ->
def newMeta = [argstr:argstr, plot_base:"${plot_prefix}${plot_suffix}"]
if (meta.subobs != null) {
newMeta.argstr += " --suffix=${meta.subobs}"
newMeta.mask_base = "${plot_prefix}${meta.subobs}"
newMeta.plot_base = "${plot_prefix}${meta.subobs}${plot_suffix}"
}
[obsid, mapMerge(meta, newMeta), metafits, vis]
}
}
.tap { obsMetaMetafitsRawSsins }
birliPrepUV.out.flatMap { obsid, meta, uvfits_ ->
def uvfits = coerceList(uvfits_)
if (uvfits.size > 1) {
uvfits.collect { f ->
def newMeta = [:]
def last_token = '' + f.baseName.split('_')[-1]
if (last_token =~ /ch[\d-]+/) {
newMeta.subobs = last_token
}
[obsid, mapMerge(meta, newMeta), f]
}
} else {
[[obsid, meta, uvfits_]]
}
}
.tap { subobsVis }
| uvMeta
subobsVis.join(ws.out.obsMetafits)
.flatMap { obsid, meta, vis, metafits ->
[
['--autos', '.diff.auto', '.spectrum'],
['--autos --no-diff', '.auto', '.spectrum'],
['--crosses', '.diff.cross', '.spectrum'],
['--crosses --no-diff', '.cross', '.spectrum'],
// ['--sigchain --autos', '.diff.auto', '.sigchain'],
// ['--sigchain --autos --no-diff', '.auto', '.sigchain'],
// ['--sigchain --crosses', '.diff.cross', '.sigchain'],
// ['--sigchain --no-diff --crosses', '.cross', '.sigchain'],
// ['--flags --autos --no-diff', '.auto', '.flags'],
// ['--flags --no-diff --crosses', '.cross', '.flags'],
].collect { argstr, plot_prefix, plot_suffix ->
def newMeta = [argstr:argstr, plot_base:"${plot_prefix}${plot_suffix}"]
if (meta.subobs != null) {
newMeta.argstr += " --suffix=${meta.subobs}"
newMeta.mask_base = "${plot_prefix}${meta.subobs}"
newMeta.plot_base = "${plot_prefix}${meta.subobs}${plot_suffix}"
}
[obsid, mapMerge(meta, newMeta), metafits, vis]
}
}
.tap { obsMetaMetafitsPrepSsins }
obsMetaMetafitsRawSsins.mix(obsMetaMetafitsPrepSsins)
| demo04_ssins
ws.out.obsMeta.cross(uvMeta.out) { it[0] }
.map { obsMeta_, uvMeta_ ->
def (obsid, wsMeta) = obsMeta_
def (_o, meta_, uvJson) = uvMeta_
def uvmeta = parseJson(uvJson)
def newMeta = [
lowfreq: uvmeta.freqs[0],
freq_res: (uvmeta.freqs[1] - uvmeta.freqs[0]),
nchans: (uvmeta.freqs?:[]).size(),
ntimes: (uvmeta.times?:[]).size(),
]
['config', 'eorband', 'num_ants', 'total_weight'].each { key ->
if (uvmeta[key] != null) {
newMeta[key] = uvmeta[key]
}
}
if (newMeta.ntimes > 0) {
newMeta.lst = Math.toDegrees(uvmeta.times[0].lst_rad)
}
[obsid, mapMerge(mapMerge(meta_, wsMeta), newMeta)]
}
.tap { subobsMeta }
.cross(subobsVis) { def (obsid, meta) = it; [obsid, meta.subobs?:''] }
.map { subobsMeta_, subobsVis_ ->
def (obsid, meta) = subobsMeta_
def (_o, _m, uvfits) = subobsVis_
[obsid, meta, uvfits]
}
.tap { subobsMetaVis }
flag(subobsMetaVis, ws.out.obsMetafits)
// for all obs that pass flag:
flag.out.subobsFlagmetaPass.map { obsid, meta, flagMeta ->
// update meta with flagMeta
[[obsid, meta.subobs?:''], mapMerge(meta, flagMeta)]
}
// join with vis from subobsMetaVis
.join(subobsMetaVis.map { obsid, meta, uvfits ->
[[obsid, meta.subobs?:''], uvfits]
})
.map { obsSubobs, meta, uvfits ->
def (obsid, _subobs) = obsSubobs
[obsid, meta, uvfits]
}
| ssinsQA
qaPrep( ssinsQA.out.subobsMetaVisSSINs, ws.out.obsMetafits )
ws.out.frame.mix(flag.out.frame)
.mix(ssinsQA.out.frame)
.mix(qaPrep.out.frame)
.map { n, l -> [n, l as ArrayList] }
| makeVideos
}
// workflow extCache {
// def name = params.visName ?: "ssins"
// channel.of(obsids_file())
// .splitCsv()
// .filter { line -> !line[0].startsWith('#') }
// .map { line ->
// def (obsid, _comment) = line
// obsid
// }
// | ws
// ws.out.obsMetafits.map { obsid, _metafits ->
// def meta = [:]
// [ obsid, deepcopy(meta) ]
// }
// | cacheBoxRaw
// .tap { obsMetaMetafitsRaw }
// | birliPrepUV
// obsMetaMetafitsRaw | demo04_ssins
// birliPrepUV.out.flatMap { obsid, meta, uvfits_ ->
// def uvfits = coerceList(uvfits_)
// if (uvfits.size > 1) {
// uvfits.collect { f ->
// def newMeta = [:]
// def last_token = '' + f.baseName.split('_')[-1]
// if (last_token =~ /ch[\d-]+/) {
// newMeta.subobs = last_token
// }
// [obsid, mapMerge(meta, newMeta), f]
// }
// } else {
// [[obsid, meta, metafits, uvfits_]]
// }
// }
// .tap { subobsVis }
// | uvMeta
// subobsMetaVis = ws.out.obsMeta.cross(uvMeta.out) { it[0] }
// .map { obsMeta_, uvMeta_ ->
// def (obsid, wsMeta) = obsMeta_
// def (_, meta_, uvJson) = uvMeta_
// def uvmeta = parseJson(uvJson)
// def newMeta = [
// lowfreq: uvmeta.freqs[0],
// freq_res: (uvmeta.freqs[1] - uvmeta.freqs[0]),
// nchans: (uvmeta.freqs?:[]).size(),
// ntimes: (uvmeta.times?:[]).size(),
// ]
// ['config', 'eorband', 'num_ants', 'total_weight'].each { key ->
// if (uvmeta[key] != null) {
// newMeta[key] = uvmeta[key]
// }
// }
// if (newMeta.ntimes > 0) {
// newMeta.lst = Math.toDegrees(uvmeta.times[0].lst_rad)
// }
// [obsid, mapMerge(mapMerge(meta_, wsMeta), newMeta)]
// }
// .tap { subobsMeta }
// .cross(subobsVis) { def (obsid, meta) = it; [obsid, meta.subobs?:''] }
// .map { subobsMeta_, subobsVis_ ->
// def (obsid, meta) = subobsMeta_
// def (_, __, uvfits) = subobsVis_
// [obsid, meta, uvfits]
// }
// qaPrep( subobsMetaVis, ws.out.obsMetafits )
// qaPrep.out.frame | makeVideos
// }
// Ensure the raw visibility files are present, or download via ASVO
process asvoRaw {
storeDir "${params.outdir}/${obsid}/raw"
tag "${obsid}"
time { 1.hour * Math.pow(task.attempt, 4) * params.scratchFactor }
disk { 100.GB * Math.pow(task.attempt, 4) }
memory { 60.GB * Math.pow(task.attempt, 4) }
label "giant_squid"
label "rate_limit"
maxRetries 2
errorStrategy {
return 'ignore'
// TODO: copy from asvoPrep, exponential backoff: sleep for 2^attempt hours after each fail
// failure_reason = [
// 5: "I/O error or hash mitch",
// 28: "No space left on device",
// ][task.exitStatus]
// if (failure_reason) {
// println "task ${task.hash} failed with code ${task.exitStatus}: ${failure_reason}"
// return 'ignore'
// }
// retry_reason = [
// 1: "general or permission",
// 11: "Resource temporarily unavailable",
// 75: "Temporary failure, try again"
// ][task.exitStatus] ?: "unknown"
// wait_hours = Math.pow(2, task.attempt)
// println "sleeping for ${wait_hours} hours and retrying task ${task.hash}, which failed with code ${task.exitStatus}: ${retry_reason}"
// sleep(wait_hours * 60*60*1000 as long)
// return 'retry'
}
input:
val obsid
output:
tuple val(obsid), path("${obsid}.metafits"), path("${obsid}_2*.fits")
script:
"""
# echo commands, exit on any failures
set -eux
export MWA_ASVO_API_KEY="${params.asvo_api_key}"
${params.proxy_prelude} # ensure proxy is set if needed
# submit a job to ASVO, suppress failure if a job already exists.
${params.giant_squid} submit-vis --delivery "acacia" $obsid || true
# extract id and state from pending download vis jobs
${params.giant_squid} list -j --types download_visibilities --states queued,processing,error -- $obsid \
| ${params.jq} -r '.[]|[.jobId,.jobState]|@tsv' \
| tee pending.tsv
# extract id url size hash from any ready download vis jobs for this obsid
${params.giant_squid} list -j --types download_visibilities --states ready -- $obsid \
| tee /dev/stderr \
| ${params.jq} -r '.[]|[.jobId,.files[0].fileUrl//"",.files[0].fileSize//"",.files[0].fileHash//""]|@tsv' \
| tee ready.tsv
# download the most recent ready job
if read -r jobid url size hash < ready.tsv; then
if read -r avail < <(df --output=avail -B1 . | tail -n 1); then
if [[ \$avail -lt \$size ]]; then
echo "Not enough disk space available in \$PWD, need \$size B, have \$avail B"
exit 28 # No space left on device
fi
else
echo "Warning: Could not determine disk space in \$PWD"
fi
# wget into two pipes:
# - first pipe untars the archive to disk
# - second pipe validates the sha sum
wget \$url -O- --progress=dot:giga --wait=60 --random-wait \
| tee >(tar -x) \
| sha1sum -c <(echo "\$hash -")
ps=("\${PIPESTATUS[@]}")
if [ \${ps[0]} -ne 0 ]; then
echo "Download failed. status=\${ps[0]}"
exit \${ps[0]}
elif [ \${ps[1]} -ne 0 ]; then
echo "Untar failed. status=\${ps[1]}"
exit \${ps[1]}
elif [ \${ps[2]} -ne 0 ]; then
echo "Hash check failed. status=\${ps[2]}"
exit \${ps[2]}
fi
exit 0 # success
fi
echo "no ready jobs"
exit 75 # temporary
"""
}
// asvoRaw was here: https://github.com/MWATelescope/MWAEoR-Pipeline/commit/e49ac2765c0fcb6bada9d3245d59a65b702f5707
// Download preprocessed files from asvo