Second Round of Full Day RFI Flagging¶

by Josh Dillon, last updated October 13, 2024

This notebook is synthesizes information from individual delay_filtered_average_zscore notebooks to find low-level RFI and flag it. That notebook takes smooth_calibrated data, redundantly averages it, performs a high-pass delay filter, and then incoherently averages across baselines, creating a per-polarization z-score. This notebook then takes that whole night of z-scores and finds a new set of flags to both add to the smooth_cal files, which are updated in place, and to write down as new UVFlag waterfall-type .h5 files.

Here's a set of links to skip to particular figures and tables:

• Figure 1: Waterfall of Maximum z-Score of Either Polarization Before Round 2 Flagging¶

• Figure 2: Histogram of z-scores¶

• Figure 3: Waterfall of Maximum z-Score of Either Polarization After Round 2 Flagging¶

• Figure 4: Spectra of Time-Averaged z-Scores¶

• Figure 5: Summary of Flags Before and After Round 2 Flagging¶

In [1]:
import time
tstart = time.time()
In [2]:
import os
os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE'
import h5py
import hdf5plugin  # REQUIRED to have the compression plugins available
import numpy as np
import glob
import matplotlib.pyplot as plt
import matplotlib
import copy
import warnings
from pyuvdata import UVFlag, UVCal
from hera_cal import utils
from hera_qm import xrfi
from hera_qm.time_series_metrics import true_stretches
from hera_filters import dspec

from IPython.display import display, HTML
%matplotlib inline
display(HTML("<style>.container { width:100% !important; }</style>"))
_ = np.seterr(all='ignore')  # get rid of red warnings
%config InlineBackend.figure_format = 'retina'
In [3]:
# get input data file names
SUM_FILE = os.environ.get("SUM_FILE", None)
# SUM_FILE = '/lustre/aoc/projects/hera/h6c-analysis/IDR2/2459861/zen.2459861.25297.sum.uvh5'
SUM_SUFFIX = os.environ.get("SUM_SUFFIX", 'sum.uvh5')

# get input and output suffixes
SMOOTH_CAL_SUFFIX = os.environ.get("SMOOTH_CAL_SUFFIX", 'sum.smooth.calfits')
ZSCORE_SUFFIX =  os.environ.get("ZSCORE_SUFFIX", 'sum.red_avg_zscore.h5')
FLAG_WATERFALL2_SUFFIX = os.environ.get("FLAG_WATERFALL2_SUFFIX", 'sum.flag_waterfall_round_2.h5')
OUT_YAML_SUFFIX = os.environ.get("OUT_YAML_SUFFIX", '_aposteriori_flags.yaml')
OUT_YAML_DIR = os.environ.get("OUT_YAML_DIR", None)

# build globs
sum_glob = '.'.join(SUM_FILE.split('.')[:-3]) + '.*.' + SUM_SUFFIX
cal_files_glob = sum_glob.replace(SUM_SUFFIX, SMOOTH_CAL_SUFFIX)
zscore_glob = sum_glob.replace(SUM_SUFFIX, ZSCORE_SUFFIX)

# build out yaml file
if OUT_YAML_DIR is None:
    OUT_YAML_DIR = os.path.dirname(SUM_FILE)
out_yaml_file = os.path.join(OUT_YAML_DIR, SUM_FILE.split('.')[-4] + OUT_YAML_SUFFIX)    

# get flagging parameters
Z_THRESH = float(os.environ.get("Z_THRESH", 4))
WS_Z_THRESH = float(os.environ.get("WS_Z_THRESH", 2))
AVG_Z_THRESH = float(os.environ.get("AVG_Z_THRESH", 1))
MAX_FREQ_FLAG_FRAC = float(os.environ.get("MAX_FREQ_FLAG_FRAC", .25))
MAX_TIME_FLAG_FRAC = float(os.environ.get("MAX_TIME_FLAG_FRAC", .1))
AVG_SPECTRUM_FILTER_DELAY = float(os.environ.get("AVG_SPECTRUM_FILTER_DELAY", 250)) # in ns
EIGENVAL_CUTOFF = float(os.environ.get("EIGENVAL_CUTOFF", 1e-12))
TIME_AVG_DELAY_FILT_SNR_THRESH = float(os.environ.get("TIME_AVG_DELAY_FILT_SNR_THRESH", 4.0))
TIME_AVG_DELAY_FILT_SNR_DYNAMIC_RANGE = float(os.environ.get("TIME_AVG_DELAY_FILT_SNR_DYNAMIC_RANGE", 1.5))

for setting in ['Z_THRESH', 'WS_Z_THRESH', 'AVG_Z_THRESH', 'MAX_FREQ_FLAG_FRAC', 'MAX_TIME_FLAG_FRAC', 'AVG_SPECTRUM_FILTER_DELAY',
               'EIGENVAL_CUTOFF', 'TIME_AVG_DELAY_FILT_SNR_THRESH', 'TIME_AVG_DELAY_FILT_SNR_DYNAMIC_RANGE']:
    print(f'{setting} = {eval(setting)}')
Z_THRESH = 4.0
WS_Z_THRESH = 2.0
AVG_Z_THRESH = 1.0
MAX_FREQ_FLAG_FRAC = 0.25
MAX_TIME_FLAG_FRAC = 0.1
AVG_SPECTRUM_FILTER_DELAY = 250.0
EIGENVAL_CUTOFF = 1e-12
TIME_AVG_DELAY_FILT_SNR_THRESH = 4.0
TIME_AVG_DELAY_FILT_SNR_DYNAMIC_RANGE = 1.5

Load z-scores¶

In [4]:
# load z-scores
zscore_files = sorted(glob.glob(zscore_glob))
print(f'Found {len(zscore_files)} *.{ZSCORE_SUFFIX} files starting with {zscore_files[0]}.')
uvf = UVFlag(zscore_files, use_future_array_shapes=True)
Found 1849 *.sum.red_avg_zscore.h5 files starting with /mnt/sn1/data1/2460767/zen.2460767.25233.sum.red_avg_zscore.h5.
In [5]:
# get calibration solution files
cal_files = sorted(glob.glob(cal_files_glob))
print(f'Found {len(cal_files)} *.{SMOOTH_CAL_SUFFIX} files starting with {cal_files[0]}.')
Found 1849 *.sum.smooth.calfits files starting with /mnt/sn1/data1/2460767/zen.2460767.25233.sum.smooth.calfits.
In [6]:
assert len(zscore_files) == len(cal_files)
In [7]:
# extract z-scores and correct by a single number per polarization to account for biases created by filtering
zscore = {pol: uvf.metric_array[:, :, np.argwhere(uvf.polarization_array == utils.polstr2num(pol, x_orientation=uvf.x_orientation))[0][0]] for pol in ['ee', 'nn']}
zscore = {pol: zscore[pol] - np.nanmedian(zscore[pol]) for pol in zscore}
In [8]:
freqs = uvf.freq_array
times = uvf.time_array
In [9]:
extent = [freqs[0] / 1e6, freqs[-1] / 1e6, times[-1] - int(times[0]), times[0] - int(times[0])]
In [10]:
def plot_max_z_score(zscore, flags=None, vmin=-5, vmax=5):
    if flags is None:
        flags = np.any(~np.isfinite(list(zscore.values())), axis=0)
    plt.figure(figsize=(14,10), dpi=100)
    plt.imshow(np.where(flags, np.nan, np.nanmax([zscore['ee'], zscore['nn']], axis=0)), aspect='auto', 
               cmap='coolwarm', interpolation='none', vmin=vmin, vmax=vmax, extent=extent)
    plt.colorbar(location='top', label='Max z-score of either polarization', extend='both', aspect=40, pad=.02)
    plt.xlabel('Frequency (MHz)')
    plt.ylabel(f'JD - {int(times[0])}')
    plt.tight_layout()

Figure 1: Waterfall of Maximum z-Score of Either Polarization Before Round 2 Flagging¶

Shows the worse of the two results from delay_filtered_average_zscore from either polarization. Dips near flagged channels are expected, due to overfitting of noise. Positive-going excursions are problematic and likely evidence of RFI.

In [11]:
plot_max_z_score(zscore)
All-NaN axis encountered
No description has been provided for this image
In [12]:
def plot_histogram():
    plt.figure(figsize=(14,4), dpi=100)
    bins = np.arange(-50, 100, .1)
    hist_ee = plt.hist(np.ravel(zscore['ee']), bins=bins, density=True, label='ee-polarized z-scores', alpha=.5)
    hist_nn = plt.hist(np.ravel(zscore['nn']), bins=bins, density=True, label='nn-polarized z-scores', alpha=.5)
    plt.plot(bins, (2*np.pi)**-.5 * np.exp(-bins**2 / 2), 'k:', label='Gaussian approximate\nnoise-only distribution')
    plt.axvline(WS_Z_THRESH, c='r', ls='--', label='Watershed z-score')
    plt.axvline(Z_THRESH, c='r', ls='-', label='Threshold z-score')
    plt.yscale('log')
    all_densities = np.concatenate([hist_ee[0][hist_ee[0] > 0], hist_nn[0][hist_nn[0] > 0]]) 
    plt.ylim(np.min(all_densities) / 2, np.max(all_densities) * 2)
    plt.xlim([-50, 100])
    plt.legend()
    plt.xlabel('z-score')
    plt.ylabel('Density')
    plt.tight_layout()

Figure 2: Histogram of z-scores¶

Shows a comparison of the histogram of z-scores in this file (one per polarization) to a Gaussian approximation of what one might expect from thermal noise. Without filtering, the actual distribution is a weighted sum of Rayleigh distributions. Filtering further complicates this. To make the z-scores more reliable, a single per-polarization median is subtracted from each waterfall, which allows us to flag low-level outliers with more confidence. Any points beyond the solid red line are flagged. Any points neighboring a flag beyond the dashed red line are also flagged. Finally, flagging is performed for low-level outliers in whole times or channels.

In [13]:
plot_histogram()
No description has been provided for this image

Perform flagging¶

In [14]:
def iteratively_flag_on_averaged_zscore(flags, zscore, avg_func=np.nanmean, avg_z_thresh=AVG_Z_THRESH, verbose=True):
    '''Flag whole integrations or channels based on average z-score. This is done
    iteratively to prevent bad times affecting channel averages or vice versa.'''
    flagged_chan_count = 0
    flagged_int_count = 0
    while True:
        zspec = avg_func(np.where(flags, np.nan, zscore), axis=0)
        ztseries = avg_func(np.where(flags, np.nan, zscore), axis=1)

        if (np.nanmax(zspec) < avg_z_thresh) and (np.nanmax(ztseries) < avg_z_thresh):
            break

        if np.nanmax(zspec) >= np.nanmax(ztseries):
            flagged_chan_count += np.sum((zspec >= np.nanmax(ztseries)) & (zspec >= avg_z_thresh))
            flags[:, (zspec >= np.nanmax(ztseries)) & (zspec >= avg_z_thresh)] = True
        else:
            flagged_int_count += np.sum((ztseries >= np.nanmax(zspec)) & (ztseries >= avg_z_thresh))
            flags[(ztseries >= np.nanmax(zspec)) & (ztseries >= avg_z_thresh), :] = True

    if verbose:
        print(f'\tFlagging an additional {flagged_int_count} integrations and {flagged_chan_count} channels.')

def impose_max_chan_flag_frac(flags, max_flag_frac=MAX_FREQ_FLAG_FRAC, verbose=True):
    '''Flag channels already flagged more than max_flag_frac (excluding completely flagged times).'''
    unflagged_times = ~np.all(flags, axis=1)
    frequently_flagged_chans =  np.mean(flags[unflagged_times, :], axis=0) >= max_flag_frac
    if verbose:
        print(f'\tFlagging {np.sum(frequently_flagged_chans) - np.sum(np.all(flags, axis=0))} channels previously flagged {max_flag_frac:.2%} or more.')        
    flags[:, frequently_flagged_chans] = True 
        
def impose_max_time_flag_frac(flags, max_flag_frac=MAX_TIME_FLAG_FRAC, verbose=True):
    '''Flag times already flagged more than max_flag_frac (excluding completely flagged channels).'''
    unflagged_chans = ~np.all(flags, axis=0)
    frequently_flagged_times =  np.mean(flags[:, unflagged_chans], axis=1) >= max_flag_frac
    if verbose:
        print(f'\tFlagging {np.sum(frequently_flagged_times) - np.sum(np.all(flags, axis=1))} times previously flagged {max_flag_frac:.2%} or more.')
    flags[frequently_flagged_times, :] = True

def time_avg_zscore_dly_filt_SNRs(flags, filter_delay=AVG_SPECTRUM_FILTER_DELAY, eigenval_cutoff=EIGENVAL_CUTOFF):
    """Produces SNRs after time-averaging z-scores and delay filtering, accounting for flagging's effect on the filter."""
    # figure out high and low band based on FM gap at 100 MHz
    flagged_stretches = true_stretches(np.all(flags, axis=0))
    FM_gap = [fs for fs in flagged_stretches if fs.start <= np.argmin(np.abs(freqs - 100e6)) < fs.stop][0]
    low_band = slice((0 if flagged_stretches[0].start != 0 else flagged_stretches[0].stop), FM_gap.start)
    high_band = slice(FM_gap.stop, (len(freqs) if flagged_stretches[-1].stop != len(freqs) else flagged_stretches[-1].start))
    
    filt_SNR = {}
    for pol in zscore:
        # calculate timeavg_SNR and filter
        noise_prediction = 1.0 / np.sum(~flags, axis=0)**.5
        timeavg_SNR = np.nanmean(np.where(flags, np.nan, zscore[pol] / noise_prediction), axis=0) 
        wgts = np.where(np.isfinite(timeavg_SNR), 1, 0)
        model = np.zeros_like(timeavg_SNR)
        for band in [low_band, high_band]:
            model[band], _, _ = dspec.fourier_filter(freqs[band], np.where(np.isfinite(timeavg_SNR[band]), timeavg_SNR[band], 0),
                                                     wgts[band], [0], [AVG_SPECTRUM_FILTER_DELAY / 1e9], mode="dpss_solve", 
                                                     eigenval_cutoff=[EIGENVAL_CUTOFF], suppression_factors=[EIGENVAL_CUTOFF])
        filt_SNR[pol] = timeavg_SNR - model

        # correct for impact of filter
        correction_factors = np.ones_like(wgts) * np.nan
        for band in [low_band, high_band]:
            X = dspec.dpss_operator(freqs[band], [0], filter_half_widths=[AVG_SPECTRUM_FILTER_DELAY / 1e9], eigenval_cutoff=[EIGENVAL_CUTOFF])[0]
            W = wgts[band]
            leverage = np.diag(X @ np.linalg.pinv(np.dot(X.T * W, X)) @ (X.T * W))
            correction_factors[band] = np.where(leverage > 0, (1 - leverage)**.5, np.nan) # because the underlying data should be gaussian
        filt_SNR[pol] /= correction_factors
    
    return filt_SNR

def iteratively_flag_on_delay_filtered_time_avg_zscore(flags, thresh=TIME_AVG_DELAY_FILT_SNR_THRESH, dynamic_range=TIME_AVG_DELAY_FILT_SNR_DYNAMIC_RANGE,
                                                       filter_delay=AVG_SPECTRUM_FILTER_DELAY, eigenval_cutoff=EIGENVAL_CUTOFF):
    """Flag whole channels based on their outlierness after delay-filterd time-averaged zscores.
    This is done iteratively since the delay filter can be unduly influenced by large outliers."""
    filt_SNR = time_avg_zscore_dly_filt_SNRs(flags, filter_delay=AVG_SPECTRUM_FILTER_DELAY, eigenval_cutoff=EIGENVAL_CUTOFF)
    while True:
        largest_SNR = np.nanmax(list(filt_SNR.values()))
        if largest_SNR < thresh:
            break
        # 
        cut = np.max([thresh, largest_SNR / dynamic_range])
        for pol in filt_SNR:
            flags[:, filt_SNR[pol] > cut] = True
        filt_SNR = time_avg_zscore_dly_filt_SNRs(flags, filter_delay=AVG_SPECTRUM_FILTER_DELAY, eigenval_cutoff=EIGENVAL_CUTOFF)
In [15]:
flags = np.any(~np.isfinite(list(zscore.values())), axis=0)
print(f'{np.mean(flags):.3%} of waterfall flagged to start.')

# flag whole integrations or channels using outliers in median
while True:
    nflags = np.sum(flags)
    for pol in ['ee', 'nn']:    
        iteratively_flag_on_averaged_zscore(flags, zscore[pol], avg_func=np.nanmedian, avg_z_thresh=AVG_Z_THRESH, verbose=True)
        impose_max_chan_flag_frac(flags, max_flag_frac=MAX_FREQ_FLAG_FRAC, verbose=True)
        impose_max_time_flag_frac(flags, max_flag_frac=MAX_TIME_FLAG_FRAC, verbose=True)
    if np.sum(flags) == nflags:
        break  
print(f'{np.mean(flags):.3%} of waterfall flagged after flagging whole times and channels with median z > {AVG_Z_THRESH}.')

# flag largest outliers
for pol in ['ee', 'nn']:
    flags |= (zscore[pol] > Z_THRESH) 
print(f'{np.mean(flags):.3%} of waterfall flagged after flagging z > {Z_THRESH} outliers.')
    
# watershed flagging
while True:
    nflags = np.sum(flags)
    for pol in ['ee', 'nn']:
        flags |= xrfi._ws_flag_waterfall(zscore[pol], flags, WS_Z_THRESH)
    if np.sum(flags) == nflags:
        break
print(f'{np.mean(flags):.3%} of waterfall flagged after watershed flagging on z > {WS_Z_THRESH} neighbors of prior flags.')
        
# flag whole integrations or channels using outliers in mean
while True:
    nflags = np.sum(flags)
    for pol in ['ee', 'nn']:    
        iteratively_flag_on_averaged_zscore(flags, zscore[pol], avg_func=np.nanmean, avg_z_thresh=AVG_Z_THRESH, verbose=True)
        impose_max_chan_flag_frac(flags, max_flag_frac=MAX_FREQ_FLAG_FRAC, verbose=True)
        impose_max_time_flag_frac(flags, max_flag_frac=MAX_TIME_FLAG_FRAC, verbose=True)
    if np.sum(flags) == nflags:
        break  
print(f'{np.mean(flags):.3%} of waterfall flagged after flagging whole times and channels with average z > {AVG_Z_THRESH}.')

# flag channels based on delay filter
iteratively_flag_on_delay_filtered_time_avg_zscore(flags, thresh=TIME_AVG_DELAY_FILT_SNR_THRESH, dynamic_range=TIME_AVG_DELAY_FILT_SNR_DYNAMIC_RANGE,
                                                   filter_delay=AVG_SPECTRUM_FILTER_DELAY, eigenval_cutoff=EIGENVAL_CUTOFF)
print(f'{np.mean(flags):.3%} of flagging channels that are {TIME_AVG_DELAY_FILT_SNR_THRESH}σ outliers after delay filtering the time average.')

# watershed flagging again
while True:
    nflags = np.sum(flags)
    for pol in ['ee', 'nn']:
        flags |= xrfi._ws_flag_waterfall(zscore[pol], flags, WS_Z_THRESH)
    if np.sum(flags) == nflags:
        break
print(f'{np.mean(flags):.3%} of waterfall flagged after another round of watershed flagging on z > {WS_Z_THRESH} neighbors of prior flags.')
27.488% of waterfall flagged to start.
All-NaN slice encountered
	Flagging an additional 0 integrations and 8 channels.
	Flagging 0 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
	Flagging an additional 24 integrations and 7 channels.
	Flagging 0 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
	Flagging an additional 0 integrations and 0 channels.
	Flagging 0 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
	Flagging an additional 0 integrations and 0 channels.
	Flagging 0 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
28.823% of waterfall flagged after flagging whole times and channels with median z > 1.0.
31.477% of waterfall flagged after flagging z > 4.0 outliers.
33.725% of waterfall flagged after watershed flagging on z > 2.0 neighbors of prior flags.
	Flagging an additional 0 integrations and 0 channels.
	Flagging 35 channels previously flagged 25.00% or more.
Mean of empty slice
Mean of empty slice
	Flagging 666 times previously flagged 10.00% or more.
	Flagging an additional 0 integrations and 0 channels.
	Flagging 3 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
	Flagging an additional 0 integrations and 0 channels.
	Flagging 0 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
	Flagging an additional 0 integrations and 0 channels.
	Flagging 0 channels previously flagged 25.00% or more.
	Flagging 0 times previously flagged 10.00% or more.
46.238% of waterfall flagged after flagging whole times and channels with average z > 1.0.
Mean of empty slice
Casting complex values to real discards the imaginary part
Casting complex values to real discards the imaginary part
48.760% of flagging channels that are 4.0σ outliers after delay filtering the time average.
49.061% of waterfall flagged after another round of watershed flagging on z > 2.0 neighbors of prior flags.

Show results of flagging¶

Figure 3: Waterfall of Maximum z-Score of Either Polarization After Round 2 Flagging¶

The same as Figure 1, but after the flagging performed in this notebook.

In [16]:
plot_max_z_score(zscore, flags=flags)
All-NaN axis encountered
No description has been provided for this image
In [17]:
def zscore_spectra(ylim=[-3, 3], flags=flags):
    fig, axes = plt.subplots(2, 1, figsize=(14,6), dpi=100, sharex=True, sharey=True, gridspec_kw={'hspace': 0})
    for ax, pol in zip(axes, ['ee', 'nn']):

        ax.plot(freqs / 1e6, np.nanmean(zscore[pol], axis=0),'r', label=f'{pol}-Polarization Before Round 2 Flagging', lw=.5)
        ax.plot(freqs / 1e6, np.nanmean(np.where(flags, np.nan, zscore[pol]), axis=0), label=f'{pol}-Polarization After Round 2 Flagging')
        ax.legend(loc='lower right')
        ax.set_ylabel('Time-Averged Z-Score\n(Excluding Flags)')
        ax.set_ylim(ylim)
    axes[1].set_xlabel('Frequency (MHz)')
    plt.tight_layout()

Figure 4: Spectra of Time-Averaged z-Scores¶

The average along the time axis of Figures 1 and 3 (though now separated per-polarization). This plot is useful for showing channels with repeated low-level RFI.

In [18]:
zscore_spectra()
Mean of empty slice
Mean of empty slice
No description has been provided for this image
In [19]:
def summarize_flagging(flags=flags):
    plt.figure(figsize=(14,10), dpi=100)
    cmap = matplotlib.colors.ListedColormap(((0, 0, 0),) + matplotlib.cm.get_cmap("Set2").colors[0:2])
    plt.imshow(np.where(np.any(~np.isfinite(list(zscore.values())), axis=0), 1, np.where(flags, 2, 0)), 
               aspect='auto', cmap=cmap, interpolation='none', extent=extent)
    plt.clim([-.5, 2.5])
    cbar = plt.colorbar(location='top', aspect=40, pad=.02)
    cbar.set_ticks([0, 1, 2])
    cbar.set_ticklabels(['Unflagged', 'Previously Flagged', 'Flagged Here Using Delayed Filtered z-Scores'])
    plt.xlabel('Frequency (MHz)')
    plt.ylabel(f'JD - {int(times[0])}')
    plt.tight_layout()

Figure 5: Summary of Flags Before and After Round 2 Flagging¶

This plot shows which times and frequencies were flagged before and after this notebook. It is directly comparable to Figure 5 of the first round full_day_rfi notebook.

In [20]:
summarize_flagging()
The get_cmap function was deprecated in Matplotlib 3.7 and will be removed in 3.11. Use ``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()`` or ``pyplot.get_cmap()`` instead.
No description has been provided for this image

Save results¶

In [21]:
add_to_history = 'by full_day_rfi_round_2 notebook with the following environment:\n' + '=' * 65 + '\n' + os.popen('conda env export').read() + '=' * 65
In [22]:
tind = 0
always_flagged_ants = set()
ever_unflagged_ants = set()
for cal_file in cal_files:
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")    
        
        # update cal_file
        uvc = UVCal()
        uvc.read(cal_file, use_future_array_shapes=True)
        uvc.flag_array |= (flags[tind:tind + len(uvc.time_array), :].T)[None, :, :, None]
        uvc.history += 'Modified ' + add_to_history
        uvc.write_calfits(cal_file, clobber=True)
        
        # keep track of flagged antennas
        for antnum in uvc.ant_array:
            for antpol in ['Jee', 'Jnn']:
                if np.all(uvc.get_flags(antnum, antpol)):
                    if (antnum, antpol) not in ever_unflagged_ants:
                        always_flagged_ants.add((antnum, antpol))
                else:
                    ever_unflagged_ants.add((antnum, antpol))
                    always_flagged_ants.discard((antnum, antpol))
                

        # Create new flag object
        uvf_out = UVFlag(uvc, waterfall=True, mode='flag')
        uvf_out.flag_array |= flags[tind:tind + len(uvc.time_array), :, None]
        uvf_out.history += 'Produced ' + add_to_history
        uvf_out.write(cal_file.replace(SMOOTH_CAL_SUFFIX, FLAG_WATERFALL2_SUFFIX), clobber=True)
        
        # increment time index
        tind += len(uvc.time_array)

print(f'Saved {len(cal_files)} *.{FLAG_WATERFALL2_SUFFIX} files starting with {cal_files[0].replace(SMOOTH_CAL_SUFFIX, FLAG_WATERFALL2_SUFFIX)}.')
Saved 1849 *.sum.flag_waterfall_round_2.h5 files starting with /mnt/sn1/data1/2460767/zen.2460767.25233.sum.flag_waterfall_round_2.h5.
In [23]:
# write summary of entirely flagged times/freqs/ants to yaml
all_flagged_times = np.all(flags, axis=1)
all_flagged_freqs = np.all(flags, axis=0)
all_flagged_ants = [(int(ant[0]), ant[1]) for ant in sorted(always_flagged_ants)]

dt = np.median(np.diff(times))
out_yml_str = 'JD_flags: ' + str([[float(times[flag_stretch][0] - dt / 2), float(times[flag_stretch][-1] + dt / 2)] 
                                  for flag_stretch in true_stretches(all_flagged_times)])
df = np.median(np.diff(freqs))
out_yml_str += '\n\nfreq_flags: ' + str([[float(freqs[flag_stretch][0] - df / 2), float(freqs[flag_stretch][-1] + df / 2)] 
                                         for flag_stretch in true_stretches(all_flagged_freqs)])
out_yml_str += '\n\nex_ants: ' + str(all_flagged_ants).replace("'", "").replace('(', '[').replace(')', ']')

print(f'Writing the following to {out_yaml_file}\n' + '-' * (25 + len(out_yaml_file)))
print(out_yml_str)
with open(out_yaml_file, 'w') as outfile:
    outfile.writelines(out_yml_str)
Writing the following to /mnt/sn1/data1/2460767/2460767_aposteriori_flags.yaml
------------------------------------------------------------------------------
JD_flags: [[2460767.252555066, 2460767.252666914], [2460767.2562460536, 2460767.256581598], [2460767.2597133447, 2460767.260160737], [2460767.2602725853, 2460767.260943674], [2460767.261055522, 2460767.2615029146], [2460767.261726611, 2460767.261950307], [2460767.264187269, 2460767.264410965], [2460767.2676545605, 2460767.2677664086], [2460767.268101953, 2460767.2686611935], [2460767.2708981554, 2460767.2711218516], [2460767.271345548, 2460767.271457396], [2460767.272240333, 2460767.272464029], [2460767.2727995734, 2460767.273246966], [2460767.273470662, 2460767.27358251], [2460767.2736943583, 2460767.2739180545], [2460767.276602409, 2460767.276826105], [2460767.2782801306, 2460767.278503827], [2460767.2789512193, 2460767.279622308], [2460767.279846004, 2460767.2801815486], [2460767.2823066623, 2460767.2825303585], [2460767.283201447, 2460767.283760688], [2460767.2844317765, 2460767.2845436246], [2460767.2846554727, 2460767.2861094982], [2460767.2868924346, 2460767.2876753714], [2460767.2880109157, 2460767.288122764], [2460767.288458308, 2460767.2885701563], [2460767.289017549, 2460767.289241245], [2460767.29248484, 2460767.292708536], [2460767.2930440805, 2460767.293715169], [2460767.2938270173, 2460767.2939388654], [2460767.2960639796, 2460767.2961758277], [2460767.2968469164, 2460767.2970706127], [2460767.297182461, 2460767.297853549], [2460767.3031104105, 2460767.303334106], [2460767.3037814987, 2460767.304005195], [2460767.305011828, 2460767.305235524], [2460767.3062421572, 2460767.3065777016], [2460767.306913246, 2460767.307025094], [2460767.307136942, 2460767.3073606384], [2460767.3074724865, 2460767.3075843346], [2460767.3097094484, 2460767.3099331446], [2460767.3117227145, 2460767.3119464107], [2460767.3125056513, 2460767.3127293475], [2460767.3151900056, 2460767.31552555], [2460767.3159729424, 2460767.3160847905], [2460767.316532183, 2460767.316755879], [2460767.3169795754, 2460767.3172032717], [2460767.31731512, 2460767.317426968], [2460767.317538816, 2460767.317650664], [2460767.3187691453, 2460767.3188809934], [2460767.3199994746, 2460767.3203350184], [2460767.321006107, 2460767.3211179553], [2460767.3215653477, 2460767.3222364364], [2460767.3231312213, 2460767.3233549176], [2460767.324585247, 2460767.324697095], [2460767.324808943, 2460767.324920791], [2460767.3251444874, 2460767.325703728], [2460767.32615112, 2460767.3264866644], [2460767.3277169936, 2460767.3278288417], [2460767.32794069, 2460767.328164386], [2460767.328835475, 2460767.328947323], [2460767.3293947154, 2460767.3295065635], [2460767.3302895003, 2460767.3305131965], [2460767.331184285, 2460767.331407981], [2460767.331519829, 2460767.3317435253], [2460767.332190918, 2460767.332302766], [2460767.3326383103, 2460767.3327501584], [2460767.3336449433, 2460767.3339804877], [2460767.334092336, 2460767.335210817], [2460767.336105602, 2460767.33621745], [2460767.3371122344, 2460767.3378951713], [2460767.3380070194, 2460767.3381188675], [2460767.338789956, 2460767.3389018043], [2460767.3393491968, 2460767.339684741], [2460767.3400202855, 2460767.3401321336], [2460767.340467678, 2460767.340579526], [2460767.340691374, 2460767.3408032223], [2460767.3409150704, 2460767.3411387666], [2460767.341362463, 2460767.341474311], [2460767.341586159, 2460767.341698007], [2460767.3418098553, 2460767.3419217034], [2460767.3420335515, 2460767.3421453997], [2460767.342257248, 2460767.342369096], [2460767.3425927917, 2460767.34270464], [2460767.342816488, 2460767.342928336], [2460767.3432638803, 2460767.3433757285], [2460767.343711273, 2460767.343823121], [2460767.3441586653, 2460767.3443823615], [2460767.3444942096, 2460767.344717906], [2460767.3451652983, 2460767.3453889946], [2460767.3455008427, 2460767.345612691], [2460767.345724539, 2460767.345836387], [2460767.345948235, 2460767.3460600832], [2460767.3461719314, 2460767.3462837795], [2460767.3465074757, 2460767.346731172], [2460767.34684302, 2460767.346954868], [2460767.3470667163, 2460767.3472904125], [2460767.3474022606, 2460767.3475141088], [2460767.347737805, 2460767.348408893], [2460767.3486325894, 2460767.3487444376], [2460767.3488562857, 2460767.348968134], [2460767.349079982, 2460767.349303678], [2460767.3495273744, 2460767.3496392225], [2460767.349974767, 2460767.350086615], [2460767.350198463, 2460767.351205096], [2460767.3515406405, 2460767.351876185], [2460767.351988033, 2460767.3525472735], [2460767.352882818, 2460767.353106514], [2460767.3534420584, 2460767.3535539065], [2460767.3538894504, 2460767.3540012985], [2460767.354336843, 2460767.354448691], [2460767.3547842354, 2460767.3548960835], [2460767.3550079316, 2460767.355343476], [2460767.355455324, 2460767.355567172], [2460767.3556790203, 2460767.3560145646], [2460767.3561264127, 2460767.356350109], [2460767.356461957, 2460767.3566856533], [2460767.3567975014, 2460767.3570211977], [2460767.357133046, 2460767.357244894], [2460767.357356742, 2460767.3575804383], [2460767.3579159826, 2460767.358475223], [2460767.3585870713, 2460767.3586989194], [2460767.35925816, 2460767.359370008], [2460767.359929248, 2460767.360600337], [2460767.360712185, 2460767.3610477294], [2460767.3611595775, 2460767.361495122], [2460767.36160697, 2460767.361718818], [2460767.361830666, 2460767.3619425143], [2460767.3620543624, 2460767.362389907], [2460767.362725451, 2460767.3629491474], [2460767.3632846917, 2460767.36339654], [2460767.363508388, 2460767.3638439323], [2460767.3639557804, 2460767.3641794766], [2460767.364403173, 2460767.364515021], [2460767.364626869, 2460767.3655216536], [2460767.3656335017, 2460767.36574535], [2460767.366080894, 2460767.3661927423], [2460767.3664164385, 2460767.366863831], [2460767.366975679, 2460767.3671993753], [2460767.3673112234, 2460767.3675349196], [2460767.367758616, 2460767.367982312], [2460767.36809416, 2460767.3685415527], [2460767.368653401, 2460767.368765249], [2460767.368877097, 2460767.3693244895], [2460767.3695481857, 2460767.369660034], [2460767.36988373, 2460767.370778515], [2460767.3708903627, 2460767.371002211], [2460767.371225907, 2460767.3714496032], [2460767.3716732995, 2460767.3717851476], [2460767.372008844, 2460767.372344388], [2460767.3724562363, 2460767.3726799325], [2460767.3727917806, 2460767.3729036287], [2460767.373015477, 2460767.373239173], [2460767.373351021, 2460767.37402211], [2460767.374133958, 2460767.3744695024], [2460767.3745813505, 2460767.375028743], [2460767.375252439, 2460767.3753642873], [2460767.3754761354, 2460767.3758116798], [2460767.375923528, 2460767.376147224], [2460767.376594616, 2460767.3769301604], [2460767.3771538567, 2460767.3779367935], [2460767.378384186, 2460767.378496034], [2460767.3787197303, 2460767.3789434265], [2460767.379614515, 2460767.3798382115], [2460767.380397452, 2460767.3805093], [2460767.3808448445, 2460767.3809566926], [2460767.382522566, 2460767.38285811], [2460767.383529199, 2460767.383752895], [2460767.3840884394, 2460767.3844239837], [2460767.384535832, 2460767.384759528], [2460767.3884505155, 2460767.3885623636], [2460767.390128237, 2460767.3905756297], [2460767.392700744, 2460767.393036288], [2460767.3957206425, 2460767.396168035], [2460767.396391731, 2460767.3967272756], [2460767.397174668, 2460767.3978457567], [2460767.3985168454, 2460767.3987405417], [2460767.3999708705, 2460767.4000827186], [2460767.401424896, 2460767.401536744], [2460767.4020959847, 2460767.402207833], [2460767.4027670734, 2460767.4031026177], [2460767.4062343645, 2460767.406569909], [2460767.4082476306, 2460767.4083594787], [2460767.409813504, 2460767.4099253523], [2460767.4204390743, 2460767.420998315], [2460767.421110163, 2460767.421333859], [2460767.424353758, 2460767.424577454], [2460767.4267025683, 2460767.4269262645], [2460767.4283802896, 2460767.4284921377], [2460767.4291632264, 2460767.4293869226], [2460767.4311764925, 2460767.4314001887], [2460767.4322949736, 2460767.4324068218], [2460767.437104442, 2460767.4372162903], [2460767.439229556, 2460767.439341404], [2460767.4405717333, 2460767.4407954295], [2460767.4426968475, 2460767.4429205437], [2460767.4514209996, 2460767.451644696], [2460767.4565660125, 2460767.4566778606], [2460767.461375481, 2460767.461487329], [2460767.4628295065, 2460767.4630532027], [2460767.464507228, 2460767.4647309245], [2460767.4664086457, 2460767.466632342], [2460767.4673034307, 2460767.467527127], [2460767.4707707223, 2460767.4709944185], [2460767.4741261653, 2460767.4744617096], [2460767.475580191, 2460767.475803887], [2460767.4892256595, 2460767.489561204], [2460767.493699584, 2460767.4939232804], [2460767.501417103, 2460767.5016407995], [2460767.5018644957, 2460767.501976344], [2460767.504996243, 2460767.505108091], [2460767.5062265717, 2460767.506450268], [2460767.5096938633, 2460767.5099175596], [2460767.5131611545, 2460767.5133848507], [2460767.5290435855, 2460767.5291554336], [2460767.5317279403, 2460767.5318397884], [2460767.5425772066, 2460767.542800903], [2460767.544814169, 2460767.544926017], [2460767.548057764, 2460767.548169612], [2460767.5620387774, 2460767.5621506255], [2460767.566065309, 2460767.5662890053], [2460767.568414119, 2460767.568525967], [2460767.5741183725, 2460767.5743420688], [2460767.6000671335, 2460767.6001789817], [2460767.604876602, 2460767.60498845], [2460767.6051002983, 2460767.6052121464], [2460767.6053239945, 2460767.6662812126]]

freq_flags: [[49179077.1484375, 49301147.4609375], [49911499.0234375, 50155639.6484375], [62118530.2734375, 63217163.0859375], [64071655.2734375, 64193725.5859375], [66390991.2109375, 66757202.1484375], [69931030.2734375, 70053100.5859375], [74081420.8984375, 75180053.7109375], [77499389.6484375, 78353881.8359375], [80062866.2109375, 80184936.5234375], [85189819.3359375, 85556030.2734375], [86776733.3984375, 86898803.7109375], [87265014.6484375, 108261108.3984375], [109970092.7734375, 110092163.0859375], [112167358.3984375, 112289428.7109375], [112655639.6484375, 112777709.9609375], [112899780.2734375, 113021850.5859375], [113265991.2109375, 113510131.8359375], [113632202.1484375, 113754272.4609375], [116073608.3984375, 116195678.7109375], [116439819.3359375, 116561889.6484375], [116683959.9609375, 116806030.2734375], [124862670.8984375, 125228881.8359375], [127548217.7734375, 127670288.0859375], [129745483.3984375, 129867553.7109375], [129989624.0234375, 130111694.3359375], [130233764.6484375, 130355834.9609375], [132308959.9609375, 132431030.2734375], [136215209.9609375, 136459350.5859375], [136825561.5234375, 138412475.5859375], [138656616.2109375, 138778686.5234375], [141464233.3984375, 141586303.7109375], [141708374.0234375, 141830444.3359375], [142074584.9609375, 142318725.5859375], [142562866.2109375, 143661499.0234375], [143783569.3359375, 144027709.9609375], [144638061.5234375, 144760131.8359375], [145492553.7109375, 145736694.3359375], [145858764.6484375, 145980834.9609375], [146224975.5859375, 146347045.8984375], [147445678.7109375, 147567749.0234375], [148178100.5859375, 148544311.5234375], [149154663.0859375, 149276733.3984375], [149887084.9609375, 150009155.2734375], [153427124.0234375, 153549194.3359375], [154159545.8984375, 154403686.5234375], [155014038.0859375, 155380249.0234375], [155502319.3359375, 155624389.6484375], [155868530.2734375, 156112670.8984375], [157577514.6484375, 157699584.9609375], [158187866.2109375, 158309936.5234375], [158432006.8359375, 158554077.1484375], [158676147.4609375, 158798217.7734375], [159164428.7109375, 159286499.0234375], [160140991.2109375, 160385131.8359375], [161361694.3359375, 161483764.6484375], [169906616.2109375, 170639038.0859375], [170883178.7109375, 171005249.0234375], [171249389.6484375, 171615600.5859375], [171737670.8984375, 171859741.2109375], [171981811.5234375, 172103881.8359375], [174911499.0234375, 175033569.3359375], [175155639.6484375, 175399780.2734375], [175521850.5859375, 175643920.8984375], [181015014.6484375, 181625366.2109375], [182479858.3984375, 182601928.7109375], [183212280.2734375, 183334350.5859375], [185653686.5234375, 185775756.8359375], [186386108.3984375, 186630249.0234375], [187362670.8984375, 187606811.5234375], [188827514.6484375, 188949584.9609375], [189315795.8984375, 189437866.2109375], [189682006.8359375, 189804077.1484375], [189926147.4609375, 190048217.7734375], [190536499.0234375, 190658569.3359375], [190780639.6484375, 191757202.1484375], [192001342.7734375, 192123413.0859375], [192489624.0234375, 192611694.3359375], [192977905.2734375, 193099975.5859375], [193222045.8984375, 193344116.2109375], [194686889.6484375, 194808959.9609375], [195175170.8984375, 195419311.5234375], [195541381.8359375, 195785522.4609375], [196029663.0859375, 196151733.3984375], [196395874.0234375, 196640014.6484375], [196884155.2734375, 197006225.5859375], [197128295.8984375, 197372436.5234375], [197982788.0859375, 198715209.9609375], [199203491.2109375, 199325561.5234375], [200057983.3984375, 200180053.7109375], [201644897.4609375, 201889038.0859375], [203231811.5234375, 203353881.8359375], [203964233.3984375, 204086303.7109375], [204940795.8984375, 205062866.2109375], [205184936.5234375, 205307006.8359375], [206039428.7109375, 206161499.0234375], [206771850.5859375, 207015991.2109375], [207138061.5234375, 207382202.1484375], [208480834.9609375, 208724975.5859375], [209945678.7109375, 210067749.0234375], [210433959.9609375, 210556030.2734375], [212142944.3359375, 212265014.6484375], [215194702.1484375, 215316772.4609375], [215682983.3984375, 215805053.7109375], [216659545.8984375, 216781616.2109375], [218978881.8359375, 219100952.1484375], [219833374.0234375, 219955444.3359375], [220565795.8984375, 220809936.5234375], [221176147.4609375, 221298217.7734375], [222763061.5234375, 223739624.0234375], [224349975.5859375, 224472045.8984375], [225692749.0234375, 225814819.3359375], [226669311.5234375, 226791381.8359375], [227279663.0859375, 227523803.7109375], [227645874.0234375, 227767944.3359375], [227890014.6484375, 228134155.2734375], [229110717.7734375, 229476928.7109375], [229965209.9609375, 230087280.2734375], [231063842.7734375, 231185913.0859375], [233993530.2734375, 234359741.2109375]]

ex_ants: [[4, Jee], [8, Jee], [8, Jnn], [9, Jee], [10, Jee], [10, Jnn], [17, Jnn], [18, Jee], [18, Jnn], [20, Jee], [20, Jnn], [21, Jee], [22, Jee], [22, Jnn], [27, Jee], [27, Jnn], [28, Jee], [28, Jnn], [29, Jee], [29, Jnn], [30, Jee], [31, Jnn], [32, Jnn], [33, Jee], [33, Jnn], [34, Jee], [34, Jnn], [36, Jee], [37, Jee], [37, Jnn], [40, Jnn], [42, Jee], [42, Jnn], [44, Jee], [45, Jee], [45, Jnn], [46, Jee], [49, Jnn], [51, Jee], [59, Jnn], [60, Jee], [60, Jnn], [65, Jee], [66, Jnn], [67, Jnn], [71, Jnn], [72, Jnn], [75, Jee], [75, Jnn], [77, Jnn], [78, Jee], [80, Jee], [80, Jnn], [81, Jnn], [82, Jee], [82, Jnn], [84, Jee], [87, Jee], [90, Jee], [90, Jnn], [91, Jee], [94, Jee], [96, Jee], [96, Jnn], [97, Jnn], [99, Jnn], [102, Jnn], [103, Jee], [104, Jee], [104, Jnn], [105, Jee], [106, Jee], [107, Jee], [107, Jnn], [108, Jnn], [109, Jnn], [110, Jee], [112, Jee], [113, Jnn], [114, Jee], [114, Jnn], [115, Jee], [116, Jee], [116, Jnn], [117, Jee], [120, Jee], [120, Jnn], [121, Jee], [121, Jnn], [127, Jee], [130, Jee], [130, Jnn], [135, Jee], [136, Jnn], [137, Jee], [137, Jnn], [143, Jee], [143, Jnn], [149, Jee], [154, Jnn], [155, Jnn], [160, Jnn], [161, Jnn], [164, Jee], [167, Jnn], [170, Jee], [171, Jnn], [172, Jnn], [173, Jnn], [174, Jnn], [176, Jnn], [180, Jee], [180, Jnn], [187, Jnn], [188, Jnn], [189, Jee], [189, Jnn], [195, Jnn], [197, Jnn], [199, Jnn], [200, Jee], [200, Jnn], [202, Jnn], [204, Jnn], [206, Jnn], [209, Jnn], [212, Jnn], [213, Jee], [214, Jnn], [215, Jnn], [216, Jee], [216, Jnn], [218, Jnn], [227, Jee], [227, Jnn], [231, Jnn], [232, Jee], [238, Jnn], [239, Jee], [244, Jee], [244, Jnn], [245, Jnn], [246, Jee], [246, Jnn], [250, Jee], [251, Jee], [252, Jnn], [253, Jnn], [255, Jee], [255, Jnn], [261, Jee], [261, Jnn], [262, Jee], [262, Jnn], [266, Jee], [266, Jnn], [268, Jee], [268, Jnn], [283, Jnn], [320, Jee], [320, Jnn], [321, Jee], [321, Jnn], [322, Jee], [322, Jnn], [323, Jee], [323, Jnn], [324, Jee], [324, Jnn], [325, Jee], [325, Jnn], [326, Jee], [326, Jnn], [327, Jee], [327, Jnn], [328, Jee], [328, Jnn], [329, Jee], [329, Jnn], [331, Jee], [331, Jnn], [332, Jee], [332, Jnn], [333, Jee], [333, Jnn], [336, Jee], [336, Jnn], [340, Jee], [340, Jnn]]

Metadata¶

In [24]:
for repo in ['hera_cal', 'hera_qm', 'hera_filters', 'hera_notebook_templates', 'pyuvdata']:
    exec(f'from {repo} import __version__')
    print(f'{repo}: {__version__}')
hera_cal: 3.7.1.dev45+g4a0c6f1
hera_qm: 2.2.1.dev2+ga535e9e
hera_filters: 0.1.6.dev9+gf165ec1
hera_notebook_templates: 0.1.dev989+gee0995d
pyuvdata: 3.1.3
In [25]:
print(f'Finished execution in {(time.time() - tstart) / 60:.2f} minutes.')
Finished execution in 61.65 minutes.