-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_funcs.py
1476 lines (1175 loc) · 43.4 KB
/
helper_funcs.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 copy
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from matplotlib.colors import LogNorm, ListedColormap
from mpl_toolkits.axes_grid1 import make_axes_locatable
from pathlib import Path
from skyfield import almanac
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
from caput import weighted_median
from caput.tools import invert_no_zero
from caput import time as ctime
from draco.core import containers
from draco.util import tools
from draco.analysis.sidereal import _search_nearest
from ch_util import cal_utils, ephemeris, rfi
from chimedb import core, dataflag as df
from ch_pipeline.analysis.flagging import compute_cumulative_rainfall
eph = ephemeris.skyfield_wrapper.ephemeris
chime_obs = ephemeris.chime
sf_obs = chime_obs.skyfield_obs()
# ==== Plot color defaults ====
_BAD_VALUE_COLOR = "#1a1a1a"
_SOURCES = ["sun", "moon", "CAS_A", "CYG_A", "TAU_A", "VIR_A", "B0329+54"]
# ==== Locations and helper functions for loading files ====
base_path = Path("/project/rpp-chime/chime/chime_processed/daily")
template_path = Path("/project/rpp-chime/chime/validation/templates")
_file_spec = {
"ringmap": ("ringmap_", ".zarr.zip"),
"delayspectrum": ("delayspectrum_", ".h5"),
"delayspectrum_hpf": ("delayspectrum_hpf_", ".h5"),
"sensitivity": ("sensitivity_", ".h5"),
"chisq": ("chisq_", ".h5"),
"power": ("lowpass_power_2cyl_", ".h5"),
"chisq_mask": ("rfi_mask_chisq_", ".h5"),
"stokesi_mask": ("rfi_mask_stokesi_", ".h5"),
"sens_mask": ("rfi_mask_sensitivity_", ".h5"),
"freq_mask": ("rfi_mask_freq_", ".h5"),
"fact_mask": ("rfi_mask_factorized_", ".h5"),
"sourceflux": ("sourceflux_", "_bright.h5"),
}
def _fail_quietly(func):
"""Just log any exceptions."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as err:
logger.debug(f"Function {func.__name__} failed with error:\n{err}")
return None
return wrapper
def _get_rev_path(type_: str, rev: int, lsd: int) -> Path:
if type_ not in _file_spec:
raise ValueError(f"Unknown file type {type_}.")
prefix, suffix = _file_spec[type_]
return base_path / f"rev_{rev:02d}" / f"{lsd:d}" / f"{prefix}lsd_{lsd:d}{suffix}"
def get_csd(day: int | str = None, num_days: int = 0, lag: int = 0) -> int:
"""Get a csd from an integer or a string with format yyyy/mm/dd.
If None, return the current CSD.
"""
if day is None:
return int(ephemeris.chime.get_current_lsd() - num_days - lag)
if isinstance(day, str):
day = datetime.strptime(day, "%Y/%m/%d").timestamp()
return int(ephemeris.unix_to_csd(day))
return int(day)
def _format_title(rev, LSD):
"""Return a title string for plots."""
return f"rev_{int(rev):02d}, CSD {int(LSD):04d}"
def _select_CSD_bounds(times, LSD, obs=chime_obs):
"""Return indices representing the times found within the LSD"""
ra = obs.unix_to_lsd(times) - LSD
return (ra >= 0.0) & (ra < 1.0)
# ==========================================================================
def _mask_baselines(baseline_vec, single_mask=False):
"""Mask long baselines in a delay spectrum."""
bl_mask = np.zeros((4, baseline_vec.shape[0]), dtype=bool)
bl_mask[0] = baseline_vec[:, 0] < 10
bl_mask[1] = (baseline_vec[:, 0] > 10) & (baseline_vec[:, 0] < 30)
bl_mask[2] = (baseline_vec[:, 0] > 30) & (baseline_vec[:, 0] < 50)
bl_mask[3] = baseline_vec[:, 0] > 50
if single_mask:
bl_mask = np.any(bl_mask, axis=0)
return bl_mask
def _hide_axis(ax):
"""Hide axis ticks and frame without removing axis."""
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.tick_params(left=False, bottom=False)
@_fail_quietly
def plotDS(
rev,
LSD,
hpf=False,
clim=[[1e-4, 1e2], [1e-4, 1e-2]],
cmap="inferno",
dynamic_clim=False,
):
"""
Plots the delay spectrum for a given LSD.
Show the delay spectrum in two different color ranges.
Parameters
----------
rev : int
Revision number
LSD : int
Day number
hpf : bool, optional (default False)
with/without high pass filter (True/False)
clim : list[list], optional (default [[1e-3, 1e2], [1e-3, 1e-2]])
min, max values in the colorscale for each plot
cmap : colormap, optional (default 'inferno')
dynamic_clim : bool, optional
If true, clim will be adjusted to try to compress
the upper limit without saturating
"""
type_ = "delayspectrum_hpf" if hpf else "delayspectrum"
path = _get_rev_path(type_, rev, LSD)
DS = containers.DelaySpectrum.from_file(path)
tau = DS.index_map["delay"] * 1e3
DS_Spec = DS.spectrum
if dynamic_clim:
# Order of magnitude of the mean of the 2 cyl sep high-delay region
# This is fairly arbitrary and not very robust, so it should be
# improved
# Only modify the second clims
spec_m = np.floor(np.log10(np.median(DS_Spec)))
delta = np.floor(np.log10(clim[1][0])) - spec_m
clim[1][1] = 10 ** (np.floor(np.log10(clim[1][1])) - delta)
baseline_vec = DS.index_map["baseline"]
bl_mask = _mask_baselines(baseline_vec)
# Make the master figure
mfig = plt.figure(layout="constrained", figsize=(35, 12))
# Make the two sub-figures
subfigs = mfig.subfigures(1, 2, wspace=0.1)
for ii, fig in enumerate(subfigs):
ax = fig.subplots(1, 4, sharey=True, gridspec_kw={"width_ratios": [1, 2, 2, 2]})
imshow_params = {
"origin": "lower",
"aspect": "auto",
"interpolation": "nearest",
"norm": LogNorm(vmin=clim[ii][0], vmax=clim[ii][1]),
"cmap": cmap,
}
for i in range(4):
baseline_idx_sorted = baseline_vec[bl_mask[i], 1].argsort()
extent = [
baseline_vec[bl_mask[i], 1].min(),
baseline_vec[bl_mask[i], 1].max(),
tau[0],
tau[-1],
]
im = ax[i].imshow(
DS_Spec[bl_mask[i]][baseline_idx_sorted].T.real,
extent=extent,
**imshow_params,
)
ax[i].xaxis.set_tick_params(labelsize=18)
ax[i].yaxis.set_tick_params(labelsize=18)
ax[i].set_title(f"{i}-cyl", fontsize=20)
fig.supxlabel("NS baseline length [m]", fontsize=20)
fig.supylabel("Delay [ns]", fontsize=20)
title = _format_title(rev, LSD) + ", hpf = " + str(hpf)
fig.suptitle(title, fontsize=20)
fig.colorbar(
im, ax=ax, orientation="vertical", label="Signal Power", pad=0.02, aspect=40
)
plt.show()
@_fail_quietly
def plotMultipleDS(
rev,
csd_start,
num_days,
reverse=True,
hpf=False,
clim=[1e-4, 1e0],
cmap="inferno",
):
"""Plot multiple delay spectra in a given range.
Parameters
----------
rev : int
Revision number
csd_start : int
First csd in the range
num_days : int
Number of days to plot, starting at `csd_start`
reverse : bool, optional (default True)
If true, display days in decreasing order
hpf : bool, optional (default False)
with/without high pass filter (True/False)
clim : list, optional (default [1e-3, 1e2])
min, max values in the colorscale
cmap : colormap, optional (default 'inferno')
"""
if num_days < 1:
# Why would we want this
print("No days requested")
return
# Accumulate the number of days available
count = 0
csds = list(range(csd_start, csd_start + num_days))
if reverse:
csds = csds[::-1]
type_ = "delayspectrum_hpf" if hpf else "delayspectrum"
# Sort out the grid shape
if not bool(num_days % 2):
# Day number is divisible by 2
plt_shape_ = (num_days // 2, 2)
else:
# Otherwise use a 3x3 grid
extra_row = int(bool(num_days % 3))
plt_shape_ = (num_days // 3 + extra_row, 3)
# Set up a grid
extra_row = int(num_days % 3 != 0)
fig, ax = plt.subplots(
*plt_shape_,
figsize=(int(10 * plt_shape_[1]), int(10 * plt_shape_[0])),
sharey=True,
sharex=True,
layout="constrained",
)
# The is for consistency of indexing axes
ax = np.atleast_2d(ax)
# If no data is plotted, we probably shouldn't display anything
im = None
imshow_params = {
"origin": "lower",
"aspect": "auto",
"interpolation": "nearest",
"norm": LogNorm(),
"clim": clim,
"cmap": cmap,
}
for i, csd in enumerate(csds):
ax_row = i // plt_shape_[1]
ax_col = i % plt_shape_[1]
path = _get_rev_path(type_, rev, csd)
try:
DS = containers.DelaySpectrum.from_file(path)
except FileNotFoundError:
# Hide this axis, but don't actually disable it
_hide_axis(ax[ax_row, ax_col])
# grey out this subplot
ax[ax_row, ax_col].set_facecolor("#686868")
count += 1
continue
# Get the axis extent and any masking
tau = DS.index_map["delay"] * 1e3
baseline_vec = DS.index_map["baseline"]
bl_mask = _mask_baselines(baseline_vec, single_mask=True)
bl_mask = np.tile(bl_mask, (len(tau), 1))
extent = [0, baseline_vec.shape[0], tau[0], tau[-1]]
im = ax[ax_row, ax_col].imshow(
np.ma.masked_array(DS.spectrum[:].T.real, mask=~bl_mask.T),
extent=extent,
**imshow_params,
)
date = ephemeris.csd_to_unix(int(csd))
date = datetime.utcfromtimestamp(date).strftime("%Y-%m-%d")
ax[ax_row, ax_col].set_title(f"{csd} ({date})")
if im is None:
# We never actually plotted any data
print("No data available in this range")
del fig
return
fig.colorbar(im, ax=ax, location="top", aspect=40, pad=0.01)
fig.supxlabel("NS baseline", fontsize=40)
fig.supylabel("Delay [ns]", fontsize=40)
title = f"Signal Power - rev {rev:02d}, CSD range {csd_start}-{csd_start+num_days-1}, hpf = {hpf}"
fig.suptitle(title, fontsize=40)
# Remove the extra unused subplots
for i in range(ax.size - num_days):
_hide_axis(ax[-1, -i - 1])
# set the axis labelsize everywhere
for _ax in ax.flatten():
_ax.xaxis.set_tick_params(labelsize=18)
_ax.yaxis.set_tick_params(labelsize=18)
del DS
print(f"Data products found for {num_days - count}/{num_days} days.")
# ========================================================================
@_fail_quietly
def plotRingmap(rev, LSD, vmin=-5, vmax=20, fi=400, flag_mask=True):
"""
Plots the delay spectrum for a given LSD.
Parameters
----------
rev : int
Revision number
LSD : int
Day number
vmin, vmax : min, max values in the colorscale, optional
fi : freq index, optional
cmap : colormap, optional (default 'inferno')
Returns
-------
Ringmap
"""
path = _get_rev_path("ringmap", rev, LSD)
ringmap = containers.RingMap.from_file(path, freq_sel=slice(fi, fi + 1))
freq = ringmap.freq
m = ringmap.map[0, 0, 0].T[::-1]
w = ringmap.weight[0, 0].T[::-1]
nanmask = np.where(w == 0, np.nan, 1)
nanmask *= np.where(
_mask_flags(ephemeris.csd_to_unix(LSD + ringmap.ra / 360.0), LSD), np.nan, 1
)
m -= np.nanmedian(m * nanmask, axis=1)[:, np.newaxis]
fig, ax = plt.subplots(1, 1, figsize=(15, 10))
cmap = copy.copy(matplotlib.cm.inferno)
cmap.set_bad("grey")
extent_ts = ephemeris.csd_to_unix(LSD + ringmap.ra[:] / 360.0)
extent = (*_get_extent(extent_ts, LSD), -1, 1)
if flag_mask:
im = ax.imshow(
m * nanmask,
vmin=vmin,
vmax=vmax,
aspect="auto",
interpolation="nearest",
extent=extent,
cmap=cmap,
)
else:
im = ax.imshow(m, vmin=vmin, vmax=vmax, aspect="auto", extent=extent, cmap=cmap)
ax.set_xlabel("RA [degrees]")
ax.set_ylabel("sin(ZA)")
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="1.5%", pad=0.25)
fig.colorbar(im, cax=cax)
title = _format_title(rev, LSD) + f", {freq[0]:.2f}" + " MHz"
ax.set_title(title, fontsize=20)
# ========================================================================
def events(observer, lsd):
# Start and end times of the CSD
st = observer.lsd_to_unix(lsd)
et = observer.lsd_to_unix(lsd + 1)
e = {}
return_sources = []
u2l = observer.unix_to_lsd
sources = [src for src in _SOURCES if src not in {"sun", "moon"}]
bodies = {src: ephemeris.source_dictionary[src] for src in sources}
bodies["moon"] = eph["moon"]
# Sun is handled differently because we care about rise/set
# rather than just transit
tt = observer.transit_times(eph["sun"], st, et)
if tt:
e["sun_transit"] = u2l(tt[0])
# Calculate the sun rise/set times on this sidereal day (it's not clear to me there
# is exactly one of each per day, I think not (Richard))
times, rises = observer.rise_set_times(eph["sun"], st, et, diameter=-1)
for t, r in zip(times, rises):
if r:
e["sun_rise"] = u2l(t)
else:
e["sun_set"] = u2l(t)
for name, body in bodies.items():
tt = observer.transit_times(body, st, et)
if tt:
tt = tt[0]
else:
continue
sf_time = ephemeris.unix_to_skyfield_time(tt)
pos = observer.skyfield_obs().at(sf_time).observe(body)
alt = pos.apparent().altaz()[0]
dec = pos.cirs_radec(sf_time)[1]
e[f"{name}_dec"] = dec.degrees
# Make sure body is above the horizon
if alt.radians > 0.0:
# Estimate the amount of time that the body is in the primary
# beam to 2 sigma
window_deg = 2.0 * cal_utils.guess_fwhm(
800.0, pol="X", dec=dec.radians, sigma=True
)
window_sec = window_deg * 240.0 * ephemeris.SIDEREAL_S
# Enter the transit timings in the output dict
e[f"{name}_transit"] = u2l(tt)
e[f"{name}_transit_start"] = u2l(tt - window_sec)
e[f"{name}_transit_end"] = u2l(tt + window_sec)
# Record that there is transit information for this body
return_sources.append(name)
return e, ["sun"] + return_sources
def flag_time_spans(LSD):
core.connect()
ut_start = ephemeris.csd_to_unix(LSD)
ut_end = ephemeris.csd_to_unix(LSD + 1)
bad_flags = [
"bad_calibration_fpga_restart",
#'globalflag',
#'acjump',
"acjump_sd",
#'rain',
#'rain_sd',
"bad_calibration_acquisition_restart",
#'misc',
#'rain1mm',
"rain1mm_sd",
"srs/bad_ringmap_broadband",
"bad_calibration_gains",
"snow",
"decorrelated_cylinder",
]
flags = (
df.DataFlag.select()
.where(df.DataFlag.start_time < ut_end, df.DataFlag.finish_time > ut_start)
.join(df.DataFlagType)
.where(df.DataFlagType.name << bad_flags)
)
flag_time_spans = [(f.type.name, f.start_time, f.finish_time) for f in flags]
return flag_time_spans
def _mask_flags(times, LSD):
flag_mask = np.zeros_like(times, dtype=bool)
for type_, ca, cb in flag_time_spans(LSD):
flag_mask[(times > ca) & (times < cb)] = True
return flag_mask
def _highlight_sources(LSD, axobj, sources=_SOURCES, obs=chime_obs):
"""Add shaded regions over source objects."""
ev, srcs = events(obs, LSD)
for src in sources:
if src not in srcs:
# No data was available for this source
continue
if src == "sun":
start = (ev[f"sun_rise"] % 1) * 360.0 if "sun_rise" in ev else 0
finish = (ev[f"sun_set"] % 1) * 360.0 if "sun_set" in ev else 360
else:
start = (ev[f"{src}_transit_start"] % 1) * 360.0
finish = (ev[f"{src}_transit_end"] % 1) * 360.0
if start < finish:
axobj.axvspan(start, finish, color="grey", alpha=0.4)
else:
axobj.axvspan(0, finish, color="grey", alpha=0.4)
axobj.axvspan(start, 360, color="grey", alpha=0.4)
axobj.axvline(start, color="k", ls="--", lw=1)
axobj.axvline(finish, color="k", ls="--", lw=1)
def _get_extent(times, LSD):
# Convert the times to fractional CSD
ra = 360 * (ephemeris.unix_to_csd(times) - LSD)
return ra[0], ra[-1]
@_fail_quietly
def plotSens(rev, LSD, vmin=0.995, vmax=1.005):
path = _get_rev_path("sensitivity", rev, LSD)
sens = containers.SystemSensitivity.from_file(path)
# Load the relevant mask
rfm = np.zeros((sens.measured[:].shape[0], sens.measured.shape[2]), dtype=bool)
for name in {"sens_mask"}:
rfi_path = _get_rev_path(name, rev, LSD)
try:
file = containers.RFIMask.from_file(rfi_path)
except FileNotFoundError:
continue
rfm |= file.mask[:]
sp = 0
sensrat = sens.measured[:, sp] * tools.invert_no_zero(sens.radiometer[:, sp])
sensrat *= invert_no_zero(np.median(sensrat, axis=1))[:, np.newaxis]
sensrat_mask = sensrat * np.where(rfm == 0, 1, np.nan)
sensrat_mask *= np.where(_mask_flags(sens.time, LSD), np.nan, 1)
# Select only the times that fall within the actual CSD
sel = _select_CSD_bounds(sens.time, LSD)
sensrat = sensrat[:, sel]
sensrat_mask = sensrat_mask[:, sel]
cmap = copy.copy(matplotlib.cm.viridis)
cmap.set_bad(_BAD_VALUE_COLOR)
# Make the master figure
mfig = plt.figure(layout="constrained", figsize=(50, 20))
# MAke the two sub-figures
subfigs = mfig.subfigures(1, 2, wspace=0.1)
# Make label patches for the masked plot
mask_patch = mpatches.Patch(
color=_BAD_VALUE_COLOR,
label=f"sensitivity mask: {100.0 * np.isnan(sensrat_mask).mean():.2f}% masked",
)
patches = [None, mask_patch]
for ii, (fig, sim) in enumerate(zip(subfigs, (sensrat, sensrat_mask))):
axis = fig.subplots(1, 1)
extent = (*_get_extent(sens.time[sel], LSD), 400, 800)
im = axis.imshow(
sim,
extent=extent,
cmap=cmap,
aspect="auto",
interpolation="nearest",
vmin=vmin,
vmax=vmax,
)
divider = make_axes_locatable(axis)
cax = divider.append_axes("right", size="1.5%", pad=0.25)
fig.colorbar(im, cax=cax)
axis.set_xlabel("RA [deg]", fontsize=30)
axis.set_ylabel("Freq [MHz]", fontsize=30)
# Highlight relevant sources
_highlight_sources(LSD, axis, ["sun"])
title = _format_title(rev, LSD)
axis.set_title(title, fontsize=50)
_ = axis.set_xticks(np.arange(0, 361, 45))
# Show the entire day even if there isn't data
axis.set_xbound(0, 360)
# If there is a patch, add a legend
if patches[ii] is not None:
axis.legend(
handles=[patches[ii]],
loc=1,
bbox_to_anchor=(1.0, -0.05),
fancybox=True,
shadow=True,
)
def plotChisq(rev, LSD, vmin=0.9, vmax=1.4):
path = _get_rev_path("chisq", rev, LSD)
chisq = containers.TimeStream.from_file(path)
vis = chisq.vis[:, 0].real
# Load all input masks
rfm = np.zeros(vis.shape, dtype=bool)
for name in {"stokesi_mask", "sens_mask", "freq_mask"}:
rfi_path = _get_rev_path(name, rev, LSD)
try:
file = containers.RFIMask.from_file(rfi_path)
except FileNotFoundError:
continue
rfm |= file.mask[:]
# Load the chisq mask
chim = np.zeros_like(rfm)
for name in {"chisq_mask"}:
rfi_path = _get_rev_path(name, rev, LSD)
try:
file = containers.RFIMask.from_file(rfi_path)
except FileNotFoundError:
continue
chim |= file.mask[:]
vis *= np.where(rfm == 0, 1, np.nan)
vis_mask = vis * np.where(chim == 0, 1, np.nan)
vis_mask *= np.where(_mask_flags(chisq.time, LSD), np.nan, 1)
# Select only the times that fall within the actual CSD
sel = _select_CSD_bounds(chisq.time, LSD)
vis = vis[:, sel]
vis_mask = vis_mask[:, sel]
cmap = copy.copy(matplotlib.cm.viridis)
cmap.set_bad(_BAD_VALUE_COLOR)
# Make the master figure
mfig = plt.figure(layout="constrained", figsize=(50, 20))
# Make the two sub-figures
subfigs = mfig.subfigures(1, 2, wspace=0.1)
# Make label patches for the different masks
patch1 = mpatches.Patch(
color=_BAD_VALUE_COLOR,
label=f"all masks: {100.0 * np.isnan(vis).mean():.2f}% masked",
)
patch2 = mpatches.Patch(
color=_BAD_VALUE_COLOR,
label=f"full pipeline mask (all masks and chi-squared mask): {100.0 * np.isnan(vis_mask).mean():.2f}% masked",
)
patches = [patch1, patch2]
for ii, (fig, sim) in enumerate(zip(subfigs, (vis, vis_mask))):
axis = fig.subplots(1, 1)
extent = (*_get_extent(chisq.time[sel], LSD), 400, 800)
im = axis.imshow(
sim,
extent=extent,
cmap=cmap,
aspect="auto",
interpolation="nearest",
norm=LogNorm(vmin=vmin, vmax=vmax),
)
divider = make_axes_locatable(axis)
cax = divider.append_axes("right", size="1.5%", pad=0.25)
fig.colorbar(im, cax=cax)
axis.set_xlabel("RA [deg]", fontsize=30)
axis.set_ylabel("Freq [MHz]", fontsize=30)
# Highlight relevant sources
_highlight_sources(LSD, axis)
title = _format_title(rev, LSD)
axis.set_title(title, fontsize=50)
_ = axis.set_xticks(np.arange(0, 361, 45))
# Show the entire day even if there isn't data
axis.set_xbound(0, 360)
# If there is a patch, add a legend
if patches[ii] is not None:
axis.legend(
handles=[patches[ii]],
loc=1,
bbox_to_anchor=(1.0, -0.05),
fancybox=True,
shadow=True,
)
@_fail_quietly
def plotVisPwr(rev, LSD, vmin=0, vmax=5e1):
path = _get_rev_path("power", rev, LSD)
power = containers.TimeStream.from_file(path)
vis = power.vis[:, 0].real
# Load the relevant RFI mask
rfm = np.zeros(vis.shape, dtype=bool)
for name in {"stokesi_mask"}:
rfi_path = _get_rev_path(name, rev, LSD)
try:
file = containers.RFIMask.from_file(rfi_path)
except FileNotFoundError:
continue
rfm |= file.mask[:]
# Apply the initial weight mask
vis *= np.where(power.weight[:, 0] == 0, 1, np.nan)
# Apply the full mask
vis_mask = vis * np.where(rfm == 0, 1, np.nan)
vis_mask *= np.where(_mask_flags(power.time, LSD), np.nan, 1)
# Select only the times that fall within the actual CSD
sel = _select_CSD_bounds(power.time, LSD)
vis = vis[:, sel]
vis_mask = vis_mask[:, sel]
cmap = copy.copy(matplotlib.cm.viridis)
cmap.set_bad(_BAD_VALUE_COLOR)
# Make the master figure
mfig = plt.figure(layout="constrained", figsize=(50, 20))
# MAke the two sub-figures
subfigs = mfig.subfigures(1, 2, wspace=0.1)
# Make label patches for the different masks
patch1 = mpatches.Patch(
color=_BAD_VALUE_COLOR,
label=f"stokes I high-pass filter mask: {100.0 * np.isnan(vis).mean():.2f}% masked",
)
patch2 = mpatches.Patch(
color=_BAD_VALUE_COLOR,
label=f"stokes I high-pass filter and sumthreshold masks: {100.0 * np.isnan(vis_mask).mean():.2f}% masked",
)
patches = [patch1, patch2]
for ii, (fig, sim) in enumerate(zip(subfigs, (vis, vis_mask))):
axis = fig.subplots(1, 1)
extent = (*_get_extent(power.time[sel], LSD), 400, 800)
im = axis.imshow(
sim,
extent=extent,
cmap=cmap,
aspect="auto",
interpolation="nearest",
vmin=vmin,
vmax=vmax,
)
divider = make_axes_locatable(axis)
cax = divider.append_axes("right", size="1.5%", pad=0.25)
fig.colorbar(im, cax=cax)
axis.set_xlabel("RA [deg]", fontsize=30)
axis.set_ylabel("Freq [MHz]", fontsize=30)
# Highlight relevant sources
sources = ["sun", "CAS_A", "CYG_A"]
_highlight_sources(LSD, axis, sources)
title = _format_title(rev, LSD)
axis.set_title(title, fontsize=50)
_ = axis.set_xticks(np.arange(0, 361, 45))
# Show the entire day even if there isn't data
axis.set_xbound(0, 360)
# If there is a patch, add a legend
if patches[ii] is not None:
axis.legend(
handles=[patches[ii]],
loc=1,
bbox_to_anchor=(1.0, -0.05),
fancybox=True,
shadow=True,
)
@_fail_quietly
def plotFactMask(rev, LSD):
path = _get_rev_path("fact_mask", rev, LSD)
fmask = containers.RFIMask.from_file(path)
mask = fmask.mask[:]
mask = np.ma.masked_where(mask == 0, mask)
# Get the static mask that was active for this CSD
timestamp = ephemeris.csd_to_unix(fmask.attrs.get("csd", fmask.attrs.get("lsd")))
static_mask = np.zeros(mask.shape, mask.dtype)
static_mask |= rfi.frequency_mask(fmask.freq, timestamp=timestamp)[:, np.newaxis]
# Ensure that the static mask will be transparent anywhere that is not flagged
static_mask = np.ma.masked_where(static_mask == 0, static_mask)
# Load all the RFI masks
for name in {"stokesi_mask", "sens_mask", "chisq_mask", "freq_mask"}:
rfi_path = _get_rev_path(name, rev, LSD)
try:
file = containers.RFIMask.from_file(rfi_path)
except FileNotFoundError:
continue
try:
rfm |= file.mask[:]
except NameError:
# First mask to be loaded
rfm = file.mask[:].copy()
# Make the master figure
fig = plt.figure(layout="constrained", figsize=(18, 15))
axis = fig.subplots(1, 1)
patches = []
# Overlay the full mask if it exists
if "rfm" in locals():
# Include fully flagged regions
rfm |= _mask_flags(file.time, LSD)[np.newaxis]
# Trim the padded time regions
sel = _select_CSD_bounds(file.time, LSD)
rfm = rfm[:, sel]
extent = (*_get_extent(file.time[sel], LSD), 400, 800)
cmap = ListedColormap(["white", "tab:pink"])
axis.imshow(
rfm,
extent=extent,
cmap=cmap,
aspect="auto",
alpha=1.0,
interpolation="nearest",
)
rfm_patch = mpatches.Patch(
color=cmap(cmap.N), label=f"daily mask: {100.0 * rfm.mean():.2f}% masked"
)
patches.append(rfm_patch)
# Plot the factorized mask
extent_ts = ephemeris.csd_to_unix(LSD + fmask.ra[:] / 360.0)
extent = (*_get_extent(extent_ts, LSD), 400, 800)
cmap = matplotlib.colormaps["binary_r"]
axis.imshow(
mask,
extent=extent,
cmap=cmap,
aspect="auto",
alpha=0.6,
interpolation="nearest",
)
mask_patch = mpatches.Patch(
color=cmap(0), label=f"factorized mask: {100.0 * mask.data.mean():.2f}% masked"
)
patches.append(mask_patch)
# Overlay the static mask
cmap = ListedColormap(["tab:cyan", "white"])
axis.imshow(
static_mask,
extent=extent,
cmap=cmap,
aspect="auto",
alpha=1.0,
interpolation="nearest",
)
static_patch = mpatches.Patch(
color=cmap(0),
label=f"static mask: {100.0 * static_mask.data.mean():.2f}% masked",
)
patches.append(static_patch)
# Set the axes
axis.set_xlabel("RA [deg]", fontsize=20)
axis.set_ylabel("Freq [MHz]", fontsize=20)
title = _format_title(rev, LSD)
axis.set_title(title, fontsize=20)
_ = axis.set_xticks(np.arange(0, 361, 45))
axis.set_xbound(0, 360)
# Add the legend
axis.legend(
handles=patches,
loc=1,
bbox_to_anchor=(1.0, -0.05),
fancybox=True,
ncol=2,
shadow=True,
)
@_fail_quietly
def plot_rainfall(rev, LSD):
# Plot cumulative rainfall throughout the day
start_time = ephemeris.csd_to_unix(LSD)
finish_time = ephemeris.csd_to_unix(LSD + 1)
times = np.linspace(start_time, finish_time, 4096, endpoint=False)
rain = compute_cumulative_rainfall(times)
fig = plt.figure(layout="constrained", figsize=(18, 5))
axis = fig.subplots(1, 1)
axis.plot(
np.linspace(0, 360, 4096, endpoint=False),
rain,
color="tab:blue",
marker=".",
ls=":",
label="cumulative rainfall",
)
axis.axhline(1.0, color="tab:red", ls="-", label="flagging threshold")
axis.set_xbound(0, 360)
if np.all(rain == 0):
axis.set_ybound(0, 2)
# Set labels
axis.set_xlabel("RA [deg]", fontsize=20)
axis.set_ylabel("Cumulative rainfall [mm]", fontsize=20)
title = _format_title(rev, LSD)
axis.set_title(title, fontsize=20)
axis.legend(fancybox=True, ncol=2, shadow=True)
# ========================================================================
@_fail_quietly
def plot_stability(
rev,
lsd,
pol=None,
min_dec=0.0,
min_nfreq=100,
norm_sigma=False,
max_val=None,
flag_daytime=True,
flag_bad_data=True,