Nightly Per-Antenna Quality Summary Notebook¶

Josh Dillon, Last Revised February 2021

This notebooks brings together as much information as possible from ant_metrics, auto_metrics and redcal to help figure out which antennas are working properly and summarizes it in a single giant table. It is meant to be lightweight and re-run as often as necessary over the night, so it can be run when any of those is done and then be updated when another one completes.

Contents:¶

  • Table 1: Overall Array Health
  • Table 2: RTP Per-Antenna Metrics Summary Table
  • Figure 1: Array Plot of Flags and A Priori Statuses
In [1]:
import os
os.environ['HDF5_USE_FILE_LOCKING'] = 'FALSE'
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
pd.set_option('display.max_rows', 1000)
from hera_qm.metrics_io import load_metric_file
from hera_cal import utils, io, redcal
import glob
import h5py
from copy import deepcopy
from IPython.display import display, HTML
from hera_notebook_templates.utils import status_colors
from hera_mc import mc
from pyuvdata import UVData

%matplotlib inline
%config InlineBackend.figure_format = 'retina'
display(HTML("<style>.container { width:100% !important; }</style>"))
In [2]:
# If you want to run this notebook locally, copy the output of the next cell into the first few lines of this cell.

# JD = "2459122"
# data_path = '/lustre/aoc/projects/hera/H4C/2459122'
# ant_metrics_ext = ".ant_metrics.hdf5"
# redcal_ext = ".maybe_good.omni.calfits"
# nb_outdir = '/lustre/aoc/projects/hera/H4C/h4c_software/H4C_Notebooks/_rtp_summary_'
# good_statuses = "digital_ok,calibration_maintenance,calibration_triage,calibration_ok"
# os.environ["JULIANDATE"] = JD
# os.environ["DATA_PATH"] = data_path
# os.environ["ANT_METRICS_EXT"] = ant_metrics_ext
# os.environ["REDCAL_EXT"] = redcal_ext
# os.environ["NB_OUTDIR"] = nb_outdir
# os.environ["GOOD_STATUSES"] = good_statuses
In [3]:
# Use environment variables to figure out path to data
JD = os.environ['JULIANDATE']
data_path = os.environ['DATA_PATH']
ant_metrics_ext = os.environ['ANT_METRICS_EXT']
redcal_ext = os.environ['REDCAL_EXT']
nb_outdir = os.environ['NB_OUTDIR']
good_statuses = os.environ['GOOD_STATUSES']
print(f'JD = "{JD}"')
print(f'data_path = "{data_path}"')
print(f'ant_metrics_ext = "{ant_metrics_ext}"')
print(f'redcal_ext = "{redcal_ext}"')
print(f'nb_outdir = "{nb_outdir}"')
print(f'good_statuses = "{good_statuses}"')
JD = "2459840"
data_path = "/mnt/sn1/2459840"
ant_metrics_ext = ".ant_metrics.hdf5"
redcal_ext = ".known_good.omni.calfits"
nb_outdir = "/home/obs/src/H6C_Notebooks/_rtp_summary_"
good_statuses = "digital_ok,calibration_maintenance,calibration_triage,calibration_ok"
In [4]:
from astropy.time import Time
utc = Time(JD, format='jd').datetime
print(f'Date: {utc.month}-{utc.day}-{utc.year}')
Date: 9-17-2022
In [5]:
# Per-season options
def ant_to_report_url(ant):
    return f'https://htmlpreview.github.io/?https://github.com/HERA-Team/H6C_Notebooks/blob/main/antenna_report/antenna_{ant}_report.html'

Load Auto Metrics¶

In [6]:
use_auto_metrics = False

# find the auto_metrics file
glob_str = os.path.join(data_path, f'zen.{JD}*.auto_metrics.h5')
auto_metrics_file = sorted(glob.glob(glob_str))

# if it exists, load and extract relevant information
if len(auto_metrics_file) > 0:
    auto_metrics_file = auto_metrics_file[0]
    print(f'Found auto_metrics results file at {auto_metrics_file}.')
    
    auto_metrics = load_metric_file(auto_metrics_file)
    mean_round_modz_cut = auto_metrics['parameters']['mean_round_modz_cut']
    auto_ex_ants = auto_metrics['ex_ants']['r2_ex_ants']
    
    use_auto_metrics = True
else:
    print(f'No files found matching glob {glob_str}. Skipping auto_metrics.')
Found auto_metrics results file at /mnt/sn1/2459840/zen.2459840.25319.sum.auto_metrics.h5.

Load Ant Metrics¶

In [7]:
use_ant_metrics = False

# get a list of all ant_metrics files
glob_str = os.path.join(data_path, f'zen.{JD}.?????.sum{ant_metrics_ext}')
ant_metrics_files = sorted(glob.glob(glob_str))

# if they exist, load as many of them as possible
if len(ant_metrics_files) > 0:
    print(f'Found {len(ant_metrics_files)} ant_metrics files matching glob {glob_str}')
    ant_metrics_apriori_exants = {}
    ant_metrics_xants_dict = {}
    ant_metrics_dead_ants_dict = {}
    ant_metrics_crossed_ants_dict = {}
    ant_metrics_dead_metrics = {}
    ant_metrics_crossed_metrics = {}
    dead_cuts = {}
    crossed_cuts = {}
    for amf in ant_metrics_files:
        with h5py.File(amf, "r") as infile: # use h5py directly since it's much faster than load_metric_file
            # get out results for this file
            dead_cuts[amf] = infile['Metrics']['dead_ant_cut'][()]
            crossed_cuts[amf] = infile['Metrics']['cross_pol_cut'][()]
            xants = infile['Metrics']['xants'][:]
            dead_ants = infile['Metrics']['dead_ants'][:]
            crossed_ants = infile['Metrics']['crossed_ants'][:]        
            try:
                # look for ex_ants in history
                ex_ants_string = infile['Header']['history'][()].decode()
                ex_ants_string = ex_ants_string.split('--apriori_xants')[1]
                ex_ants_string = ex_ants_string.split('--')[0].strip()
            except:
                ex_ants_string = ''
                    
            # This only works for the new correlation-matrix-based ant_metrics
            if 'corr' in infile['Metrics']['final_metrics'] and 'corrXPol' in infile['Metrics']['final_metrics']:
                ant_metrics_dead_metrics[amf] = {eval(ant): infile['Metrics']['final_metrics']['corr'][ant][()]
                                                 for ant in infile['Metrics']['final_metrics']['corr']}
                ant_metrics_crossed_metrics[amf] = {eval(ant): infile['Metrics']['final_metrics']['corrXPol'][ant][()]
                                                    for ant in infile['Metrics']['final_metrics']['corrXPol']}                       
            else:
                raise(KeywordError)
        
        # organize results by file
        ant_metrics_xants_dict[amf] = [(int(ant[0]), ant[1].decode()) for ant in xants]
        ant_metrics_dead_ants_dict[amf] = [(int(ant[0]), ant[1].decode()) for ant in dead_ants]
        ant_metrics_crossed_ants_dict[amf] = [(int(ant[0]), ant[1].decode()) for ant in crossed_ants]
        ant_metrics_apriori_exants[amf] = [int(ant) for ant in ex_ants_string.split()]
    
    dead_cut = np.median(list(dead_cuts.values()))
    crossed_cut = np.median(list(crossed_cuts.values()))
        
    use_ant_metrics = True
else:
    print(f'No files found matching glob {glob_str}. Skipping ant_metrics.')
Found 372 ant_metrics files matching glob /mnt/sn1/2459840/zen.2459840.?????.sum.ant_metrics.hdf5

Load chi^2 info from redcal¶

In [8]:
use_redcal = False
glob_str = os.path.join(data_path, f'zen.{JD}.?????.sum{redcal_ext}')

redcal_files = sorted(glob.glob(glob_str))
if len(redcal_files) > 0:
    print(f'Found {len(redcal_files)} ant_metrics files matching glob {glob_str}')
    post_redcal_ant_flags_dict = {}
    flagged_by_redcal_dict = {}
    cspa_med_dict = {}
    for cal in redcal_files:
        hc = io.HERACal(cal)
        _, flags, cspa, chisq = hc.read()
        cspa_med_dict[cal] = {ant: np.nanmedian(cspa[ant], axis=1) for ant in cspa}

        post_redcal_ant_flags_dict[cal] = {ant: np.all(flags[ant]) for ant in flags}
        # check history to distinguish antennas flagged going into redcal from ones flagged during redcal
        tossed_antenna_lines =  hc.history.replace('\n','').split('Throwing out antenna ')[1:]
        flagged_by_redcal_dict[cal] = sorted([int(line.split(' ')[0]) for line in tossed_antenna_lines])
        
    use_redcal = True
else:
    print(f'No files found matching glob {glob_str}. Skipping redcal chisq.')
No files found matching glob /mnt/sn1/2459840/zen.2459840.?????.sum.known_good.omni.calfits. Skipping redcal chisq.

Figure out some general properties¶

In [9]:
# Parse some general array properties, taking into account the fact that we might be missing some of the metrics
ants = []
pols = []
antpol_pairs = []

if use_auto_metrics:
    ants = sorted(set(bl[0] for bl in auto_metrics['modzs']['r2_shape_modzs']))
    pols = sorted(set(bl[2] for bl in auto_metrics['modzs']['r2_shape_modzs']))
if use_ant_metrics:
    antpol_pairs = sorted(set([antpol for dms in ant_metrics_dead_metrics.values() for antpol in dms.keys()]))
    antpols = sorted(set(antpol[1] for antpol in antpol_pairs))
    ants = sorted(set(antpol[0] for antpol in antpol_pairs) | set(ants))
    pols = sorted(set(utils.join_pol(ap, ap) for ap in antpols) | set(pols))
if use_redcal:
    antpol_pairs = sorted(set([ant for cspa in cspa_med_dict.values() for ant in cspa.keys()]) | set(antpol_pairs))
    antpols = sorted(set(antpol[1] for antpol in antpol_pairs))
    ants = sorted(set(antpol[0] for antpol in antpol_pairs) | set(ants))
    pols = sorted(set(utils.join_pol(ap, ap) for ap in antpols) | set(pols))

# Figure out remaining antennas not in data and also LST range
data_files = sorted(glob.glob(os.path.join(data_path, 'zen.*.sum.uvh5')))
hd = io.HERAData(data_files[0])
unused_ants = [ant for ant in hd.antpos if ant not in ants]    
hd_last = io.HERAData(data_files[-1])

Load a priori antenna statuses and node numbers¶

In [10]:
# try to load a priori antenna statusesm but fail gracefully if this doesn't work.
a_priori_statuses = {ant: 'Not Found' for ant in ants}
nodes = {ant: np.nan for ant in ants + unused_ants}
try:
    from hera_mc import cm_hookup

    # get node numbers
    hookup = cm_hookup.get_hookup('default')
    for ant_name in hookup:
        ant = int("".join(filter(str.isdigit, ant_name)))
        if ant in nodes:
            if hookup[ant_name].get_part_from_type('node')['E<ground'] is not None:
                nodes[ant] = int(hookup[ant_name].get_part_from_type('node')['E<ground'][1:])
    
    # get apriori antenna status
    for ant_name, data in hookup.items():
        ant = int("".join(filter(str.isdigit, ant_name)))
        if ant in a_priori_statuses:
            a_priori_statuses[ant] = data.apriori

except Exception as err:
    print(f'Could not load node numbers and a priori antenna statuses.\nEncountered {type(err)} with message: {err}')

Summarize auto metrics¶

In [11]:
if use_auto_metrics:
    # Parse modzs
    modzs_to_check = {'Shape': 'r2_shape_modzs', 'Power': 'r2_power_modzs', 
                      'Temporal Variability': 'r2_temp_var_modzs', 'Temporal Discontinuties': 'r2_temp_diff_modzs'}
    worst_metrics = []
    worst_zs = []
    all_modzs = {}
    binary_flags = {rationale: [] for rationale in modzs_to_check}

    for ant in ants:
        # parse modzs and figure out flag counts
        modzs = {f'{pol} {rationale}': auto_metrics['modzs'][dict_name][(ant, ant, pol)] 
                 for rationale, dict_name in modzs_to_check.items() for pol in pols}
        for pol in pols:
            for rationale, dict_name in modzs_to_check.items():
                binary_flags[rationale].append(auto_metrics['modzs'][dict_name][(ant, ant, pol)] > mean_round_modz_cut)

        # parse out all metrics for dataframe
        for k in modzs:
            col_label = k + ' Modified Z-Score'
            if col_label in all_modzs:
                all_modzs[col_label].append(modzs[k])
            else:
                all_modzs[col_label] = [modzs[k]]
                
    mean_round_modz_cut = auto_metrics['parameters']['mean_round_modz_cut']
else:
    mean_round_modz_cut = 0

Summarize ant metrics¶

In [12]:
if use_ant_metrics:
    a_priori_flag_frac = {ant: np.mean([ant in apxa for apxa in ant_metrics_apriori_exants.values()]) for ant in ants}
    dead_ant_frac = {ap: {ant: np.mean([(ant, ap) in das for das in ant_metrics_dead_ants_dict.values()])
                                 for ant in ants} for ap in antpols}
    crossed_ant_frac = {ant: np.mean([np.any([(ant, ap) in cas for ap in antpols])
                                      for cas in ant_metrics_crossed_ants_dict.values()]) for ant in ants}
    ant_metrics_xants_frac_by_antpol = {antpol: np.mean([antpol in amx for amx in ant_metrics_xants_dict.values()]) for antpol in antpol_pairs}
    ant_metrics_xants_frac_by_ant = {ant: np.mean([np.any([(ant, ap) in amx for ap in antpols])
                                     for amx in ant_metrics_xants_dict.values()]) for ant in ants}
    average_dead_metrics = {ap: {ant: np.nanmean([dm.get((ant, ap), np.nan) for dm in ant_metrics_dead_metrics.values()]) 
                                 for ant in ants} for ap in antpols}
    average_crossed_metrics = {ant: np.nanmean([cm.get((ant, ap), np.nan) for ap in antpols 
                                                for cm in ant_metrics_crossed_metrics.values()]) for ant in ants}
else:
    dead_cut = 0.4
    crossed_cut = 0.0

Summarize redcal chi^2 metrics¶

In [13]:
if use_redcal:
    cspa = {ant: np.nanmedian(np.hstack([cspa_med_dict[cal][ant] for cal in redcal_files])) for ant in antpol_pairs}
    redcal_prior_flag_frac = {ant: np.mean([np.any([afd[ant, ap] and not ant in flagged_by_redcal_dict[cal] for ap in antpols])
                                            for cal, afd in post_redcal_ant_flags_dict.items()]) for ant in ants}
    redcal_flagged_frac = {ant: np.mean([ant in fbr for fbr in flagged_by_redcal_dict.values()]) for ant in ants}

Get FEM switch states¶

In [14]:
HHautos = sorted(glob.glob(f"{data_path}/zen.{JD}.*.sum.autos.uvh5"))
diffautos = sorted(glob.glob(f"{data_path}/zen.{JD}.*.diff.autos.uvh5"))

try:
    db = mc.connect_to_mc_db(None)
    session = db.sessionmaker()
    startJD = float(HHautos[0].split('zen.')[1].split('.sum')[0])
    stopJD = float(HHautos[-1].split('zen.')[1].split('.sum')[0])
    startTime = Time(startJD,format='jd')
    stopTime = Time(stopJD,format='jd')
    res = session.get_antenna_status(starttime=startTime, stoptime=stopTime)
    fem_switches = {}
    if len(res) == 0:
        femState = None
    else:
        for antpol in res:
            fem_switches[(antpol.antenna_number, antpol.antenna_feed_pol)] = antpol.fem_switch
    femState = (max(set(list(fem_switches.values())), key = list(fem_switches.values()).count)) 
except Exception as e:
    print(e)
    femState = None

Find X-engine Failures¶

In [15]:
read_inds = [1, len(HHautos)//2, -2]
x_status = [1,1,1,1,1,1,1,1]
s = UVData()
s.read(HHautos[1])

nants = len(s.get_ants())
freqs = s.freq_array[0]*1e-6
nfreqs = len(freqs)

antCon = {a: None for a in ants}
rightAnts = []
for i in read_inds:
    s = UVData()
    d = UVData()
    s.read(HHautos[i])
    d.read(diffautos[i])
    for pol in [0,1]:
        sm = np.abs(s.data_array[:,0,:,pol])
        df = np.abs(d.data_array[:,0,:,pol])
        sm = np.r_[sm, np.nan + np.zeros((-len(sm) % nants,len(freqs)))]
        sm = np.nanmean(sm.reshape(-1,nants,nfreqs),axis=1)
        df = np.r_[df, np.nan + np.zeros((-len(df) % nants,len(freqs)))]
        df = np.nanmean(df.reshape(-1,nants,nfreqs),axis=1)

        evens = (sm + df)/2
        odds = (sm - df)/2
        rat = np.divide(evens,odds)
        rat = np.nan_to_num(rat)
        for xbox in range(0,8):
            xavg = np.nanmean(rat[:,xbox*192:(xbox+1)*192],axis=1)
            if np.nanmax(xavg)>1.5 or np.nanmin(xavg)<0.5:
                x_status[xbox] = 0
    for ant in ants:
        for pol in ["xx", "yy"]:
            if antCon[ant] is False:
                continue
            spectrum = s.get_data(ant, ant, pol)
            stdev = np.std(spectrum)
            med = np.median(np.abs(spectrum))
            if (femState == "load" or femState == 'noise') and 80000 < stdev <= 4000000 and antCon[ant] is not False:
                antCon[ant] = True
            elif femState == "antenna" and stdev > 500000 and med > 950000 and antCon[ant] is not False:
                antCon[ant] = True
            else:
                antCon[ant] = False
            if np.min(np.abs(spectrum)) < 100000:
                antCon[ant] = False
for ant in ants:
    if antCon[ant] is True:
        rightAnts.append(ant)
            
x_status_str = ''
for i,x in enumerate(x_status):
    if x==0:
        x_status_str += '\u274C '
    else:
        x_status_str += '\u2705 '

Build Overall Health DataFrame¶

In [16]:
def comma_sep_paragraph(vals, chars_per_line=40):
    outstrs = []
    for val in vals:
        if (len(outstrs) == 0) or (len(outstrs[-1]) > chars_per_line):
            outstrs.append(str(val))
        else:
            outstrs[-1] += ', ' + str(val)
    return ',<br>'.join(outstrs)
In [17]:
# Time data
to_show = {'JD': [JD]}
to_show['Date'] = f'{utc.month}-{utc.day}-{utc.year}'
to_show['LST Range'] = f'{hd.lsts[0] * 12 / np.pi:.3f} -- {hd_last.lsts[-1] * 12 / np.pi:.3f} hours'

# X-engine status
to_show['X-Engine Status'] = x_status_str

# Files
to_show['Number of Files'] = len(data_files)

# Antenna Calculations
to_show['Total Number of Antennas'] = len(ants)

to_show[' '] = ''
to_show['OPERATIONAL STATUS SUMMARY'] = ''

status_count = {status: 0 for status in status_colors}
for ant, status in a_priori_statuses.items():
    if status in status_count:
        status_count[status] = status_count[status] + 1
    else:
        status_count[status] = 1
to_show['Antenna A Priori Status Count'] = '<br>'.join([f'{status}: {status_count[status]}' for status in status_colors if status in status_count and status_count[status] > 0])

to_show['Commanded Signal Source'] = femState
to_show['Antennas in Commanded State'] = f'{len(rightAnts)} / {len(ants)} ({len(rightAnts) / len(ants):.1%})'

if use_ant_metrics:
    to_show['Cross-Polarized Antennas'] = ', '.join([str(ant) for ant in ants if (np.max([dead_ant_frac[ap][ant] for ap in antpols]) + crossed_ant_frac[ant] == 1) 
                                                                                 and (crossed_ant_frac[ant] > .5)])

# Node calculations
nodes_used = set([nodes[ant] for ant in ants if np.isfinite(nodes[ant])])
to_show['Total Number of Nodes'] = len(nodes_used)
if use_ant_metrics:
    node_off = {node: True for node in nodes_used}
    not_correlating = {node: True for node in nodes_used}
    for ant in ants:
        for ap in antpols:
            if np.isfinite(nodes[ant]):
                if np.isfinite(average_dead_metrics[ap][ant]):
                    node_off[nodes[ant]] = False
                if dead_ant_frac[ap][ant] < 1:
                    not_correlating[nodes[ant]] = False
    to_show['Nodes Registering 0s'] = ', '.join([f'N{n:02}' for n in sorted([node for node in node_off if node_off[node]])])
    to_show['Nodes Not Correlating'] = ', '.join([f'N{n:02}' for n in sorted([node for node in not_correlating if not_correlating[node] and not node_off[node]])])

# Pipeline calculations    
to_show['  '] = ''
to_show['NIGHTLY ANALYSIS SUMMARY'] = ''
    
all_flagged_ants = []
if use_ant_metrics:
    to_show['Ant Metrics Done?'] = '\u2705'
    ant_metrics_flagged_ants = [ant for ant in ants if ant_metrics_xants_frac_by_ant[ant] > 0]
    all_flagged_ants.extend(ant_metrics_flagged_ants)
    to_show['Ant Metrics Flagged Antennas'] = f'{len(ant_metrics_flagged_ants)} / {len(ants)} ({len(ant_metrics_flagged_ants) / len(ants):.1%})' 
else:
    to_show['Ant Metrics Done?'] = '\u274C'
if use_auto_metrics:
    to_show['Auto Metrics Done?'] = '\u2705'
    auto_metrics_flagged_ants = [ant for ant in ants if ant in auto_ex_ants]
    all_flagged_ants.extend(auto_metrics_flagged_ants)    
    to_show['Auto Metrics Flagged Antennas'] = f'{len(auto_metrics_flagged_ants)} / {len(ants)} ({len(auto_metrics_flagged_ants) / len(ants):.1%})' 
else:
    to_show['Auto Metrics Done?'] = '\u274C'
if use_redcal:
    to_show['Redcal Done?'] = '\u2705'    
    redcal_flagged_ants = [ant for ant in ants if redcal_flagged_frac[ant] > 0]
    all_flagged_ants.extend(redcal_flagged_ants)    
    to_show['Redcal Flagged Antennas'] = f'{len(redcal_flagged_ants)} / {len(ants)} ({len(redcal_flagged_ants) / len(ants):.1%})' 
else:
    to_show['Redcal Done?'] = '\u274C' 
to_show['Never Flagged Antennas'] = f'{len(ants) - len(set(all_flagged_ants))} / {len(ants)} ({(len(ants) - len(set(all_flagged_ants))) / len(ants):.1%})'

# Count bad antennas with good statuses and vice versa
n_apriori_good = len([ant for ant in ants if a_priori_statuses[ant] in good_statuses.split(',')])
apriori_good_flagged = []
aprior_bad_unflagged = []
for ant in ants:
    if ant in set(all_flagged_ants) and a_priori_statuses[ant] in good_statuses.split(','):
        apriori_good_flagged.append(ant)
    elif ant not in set(all_flagged_ants) and a_priori_statuses[ant] not in good_statuses.split(','):
        aprior_bad_unflagged.append(ant)
to_show['A Priori Good Antennas Flagged'] = f'{len(apriori_good_flagged)} / {n_apriori_good} total a priori good antennas:<br>' + \
                                            comma_sep_paragraph(apriori_good_flagged)
to_show['A Priori Bad Antennas Not Flagged'] = f'{len(aprior_bad_unflagged)} / {len(ants) - n_apriori_good} total a priori bad antennas:<br>' + \
                                            comma_sep_paragraph(aprior_bad_unflagged)

# Apply Styling
df = pd.DataFrame(to_show)
divider_cols = [df.columns.get_loc(col) for col in ['NIGHTLY ANALYSIS SUMMARY', 'OPERATIONAL STATUS SUMMARY']]
try:
    to_red_columns = [df.columns.get_loc(col) for col in ['Cross-Polarized Antennas', 'Nodes Registering 0s', 
                                                          'Nodes Not Correlating', 'A Priori Good Antennas Flagged']]
except:
    to_red_columns = []
def red_specific_cells(x):
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    for col in to_red_columns:
        df1.iloc[col] = 'color: red'
    return df1

df = df.T
table = df.style.hide_columns().apply(red_specific_cells, axis=None)
for col in divider_cols:
    table = table.set_table_styles([{"selector":f"tr:nth-child({col+1})", "props": [("background-color", "black"), ("color", "white")]}], overwrite=False)

Table 1: Overall Array Health¶

In [18]:
HTML(table.render())
Out[18]:
JD 2459840
Date 9-17-2022
LST Range 19.281 -- 21.280 hours
X-Engine Status ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅
Number of Files 372
Total Number of Antennas 105
OPERATIONAL STATUS SUMMARY
Antenna A Priori Status Count dish_maintenance: 3
dish_ok: 1
RF_maintenance: 25
digital_maintenance: 3
digital_ok: 72
not_connected: 1
Commanded Signal Source None
Antennas in Commanded State 0 / 105 (0.0%)
Cross-Polarized Antennas
Total Number of Nodes 10
Nodes Registering 0s
Nodes Not Correlating N01, N03, N05, N07, N08, N09, N10, N12, N14
NIGHTLY ANALYSIS SUMMARY
Ant Metrics Done? ✅
Ant Metrics Flagged Antennas 103 / 105 (98.1%)
Auto Metrics Done? ✅
Auto Metrics Flagged Antennas 65 / 105 (61.9%)
Redcal Done? ❌
Never Flagged Antennas 1 / 105 (1.0%)
A Priori Good Antennas Flagged 72 / 72 total a priori good antennas:
3, 5, 15, 16, 17, 29, 30, 37, 38, 40, 41, 45,
46, 51, 53, 55, 56, 65, 66, 67, 68, 69, 71,
73, 81, 83, 84, 85, 86, 88, 91, 93, 94, 98,
99, 100, 101, 103, 105, 106, 107, 108, 109,
111, 112, 116, 117, 118, 121, 122, 123, 124,
127, 128, 129, 130, 143, 144, 156, 157, 158,
163, 164, 165, 176, 177, 178, 179, 184, 185,
186, 187
A Priori Bad Antennas Not Flagged 1 / 33 total a priori bad antennas:
57
In [19]:
# write to csv
outpath = os.path.join(nb_outdir, f'array_health_table_{JD}.csv')
print(f'Now saving Table 2 to a csv at {outpath}')
df.replace({'\u2705': 'Y'}, regex=True).replace({'\u274C': 'N'}, regex=True).replace({'<br>': ' '}, regex=True).to_csv(outpath)
Now saving Table 2 to a csv at /home/obs/src/H6C_Notebooks/_rtp_summary_/array_health_table_2459840.csv

Build DataFrame¶

In [20]:
# build dataframe
to_show = {'Ant': [f'<a href="{ant_to_report_url(ant)}" target="_blank">{ant}</a>' for ant in ants],
           'Node': [f'N{nodes[ant]:02}' for ant in ants], 
           'A Priori Status': [a_priori_statuses[ant] for ant in ants]}
           #'Worst Metric': worst_metrics, 'Worst Modified Z-Score': worst_zs}
df = pd.DataFrame(to_show)

# create bar chart columns for flagging percentages:
bar_cols = {}
if use_auto_metrics:
    bar_cols['Auto Metrics Flags'] = [float(ant in auto_ex_ants) for ant in ants]
if use_ant_metrics:
    if np.sum(list(a_priori_flag_frac.values())) > 0:  # only include this col if there are any a priori flags
        bar_cols['A Priori Flag Fraction in Ant Metrics'] = [a_priori_flag_frac[ant] for ant in ants]
    for ap in antpols:
        bar_cols[f'Dead Fraction in Ant Metrics ({ap})'] = [dead_ant_frac[ap][ant] for ant in ants]
    bar_cols['Crossed Fraction in Ant Metrics'] = [crossed_ant_frac[ant] for ant in ants]
if use_redcal:
    bar_cols['Flag Fraction Before Redcal'] = [redcal_prior_flag_frac[ant] for ant in ants]
    bar_cols['Flagged By Redcal chi^2 Fraction'] = [redcal_flagged_frac[ant] for ant in ants]  
for col in bar_cols:
    df[col] = bar_cols[col]

# add auto_metrics
if use_auto_metrics:
    for label, modz in all_modzs.items():
        df[label] = modz
z_score_cols = [col for col in df.columns if 'Modified Z-Score' in col]        
        
# add ant_metrics
ant_metrics_cols = {}
if use_ant_metrics:
    for ap in antpols:
        ant_metrics_cols[f'Average Dead Ant Metric ({ap})'] = [average_dead_metrics[ap][ant] for ant in ants]
    ant_metrics_cols['Average Crossed Ant Metric'] = [average_crossed_metrics[ant] for ant in ants]
    for col in ant_metrics_cols:
        df[col] = ant_metrics_cols[col]   

# add redcal chisq
redcal_cols = []
if use_redcal:
    for ap in antpols:
        col_title = f'Median chi^2 Per Antenna ({ap})'
        df[col_title] = [cspa[ant, ap] for ant in ants]
        redcal_cols.append(col_title)

# sort by node number and then by antenna number within nodes
df.sort_values(['Node', 'Ant'], ascending=True)

# style dataframe
table = df.style.hide_index()\
          .applymap(lambda val: f'background-color: {status_colors[val]}' if val in status_colors else '', subset=['A Priori Status']) \
          .background_gradient(cmap='viridis', vmax=mean_round_modz_cut * 3, vmin=0, axis=None, subset=z_score_cols) \
          .background_gradient(cmap='bwr_r', vmin=dead_cut-.25, vmax=dead_cut+.25, axis=0, subset=list([col for col in ant_metrics_cols if 'dead' in col.lower()])) \
          .background_gradient(cmap='bwr_r', vmin=crossed_cut-.25, vmax=crossed_cut+.25, axis=0, subset=list([col for col in ant_metrics_cols if 'crossed' in col.lower()])) \
          .background_gradient(cmap='plasma', vmax=4, vmin=1, axis=None, subset=redcal_cols) \
          .applymap(lambda val: 'font-weight: bold' if val < dead_cut else '', subset=list([col for col in ant_metrics_cols if 'dead' in col.lower()])) \
          .applymap(lambda val: 'font-weight: bold' if val < crossed_cut else '', subset=list([col for col in ant_metrics_cols if 'crossed' in col.lower()])) \
          .applymap(lambda val: 'font-weight: bold' if val > mean_round_modz_cut else '', subset=z_score_cols) \
          .applymap(lambda val: 'color: red' if val > mean_round_modz_cut else '', subset=z_score_cols) \
          .bar(subset=list(bar_cols.keys()), vmin=0, vmax=1) \
          .format({col: '{:,.4f}'.format for col in z_score_cols}) \
          .format({col: '{:,.4f}'.format for col in ant_metrics_cols}) \
          .format({col: '{:,.2%}'.format for col in bar_cols}) \
          .applymap(lambda val: 'font-weight: bold', subset=['Ant']) \
          .set_table_styles([dict(selector="th",props=[('max-width', f'70pt')])])

Table 2: RTP Per-Antenna Metrics Summary Table¶

This admittedly very busy table incorporates summary information about all antennas in the array. Its columns depend on what information is available when the notebook is run (i.e. whether auto_metrics, ant_metrics, and/or redcal is done). These can be divided into 5 sections:

Basic Antenna Info: antenna number, node, and its a priori status.

Flag Fractions: Fraction of the night that an antenna was flagged for various reasons. Note that auto_metrics flags antennas for the whole night, so it'll be 0% or 100%.

auto_metrics Details: If auto_metrics is included, this section shows the modified Z-score signifying how much of an outlier each antenna and polarization is in each of four categories: bandpass shape, overall power, temporal variability, and temporal discontinuities. Bold red text indicates that this is a reason for flagging the antenna. It is reproduced from the auto_metrics_inspect.ipynb nightly notebook, so check that out for more details on the precise metrics.

ant_metrics Details: If ant_metrics is included, this section shows the average correlation-based metrics for antennas over the whole night. Low "dead ant" metrics (nominally below 0.4) indicate antennas not correlating with the rest of the array. Negative "crossed ant" metrics indicate antennas that show stronger correlations in their cross-pols than their same-pols, indicating that the two polarizations are probably swapped. Bold text indicates that the average is below the threshold for flagging.

redcal chi^2 Details: If redcal is included, this shows the median chi^2 per antenna. This would be 1 in an ideal array. Antennas are thrown out when they they are outliers in their median chi^2, usually greater than 4-sigma outliers in modified Z-score.

In [21]:
HTML(table.render())
Out[21]:
Ant Node A Priori Status Auto Metrics Flags Dead Fraction in Ant Metrics (Jee) Dead Fraction in Ant Metrics (Jnn) Crossed Fraction in Ant Metrics ee Shape Modified Z-Score nn Shape Modified Z-Score ee Power Modified Z-Score nn Power Modified Z-Score ee Temporal Variability Modified Z-Score nn Temporal Variability Modified Z-Score ee Temporal Discontinuties Modified Z-Score nn Temporal Discontinuties Modified Z-Score Average Dead Ant Metric (Jee) Average Dead Ant Metric (Jnn) Average Crossed Ant Metric
3 N01 digital_ok 0.00% 100.00% 100.00% 0.00% -1.092125 -0.793135 -0.164026 0.154233 0.822334 -0.478821 1.261926 0.500024 0.027126 0.023348 0.002087
4 N01 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.922209 -0.877785 0.708135 0.166848 -0.151059 -1.006785 1.795258 0.128260 0.023716 0.023201 0.000779
5 N01 digital_ok 0.00% 100.00% 100.00% 0.00% 0.164662 -1.294864 -0.368403 -1.203610 0.682988 -0.296768 -0.161431 -1.015663 0.023738 0.023485 0.000706
15 N01 digital_ok 0.00% 100.00% 100.00% 0.00% -1.238629 0.175288 -0.420644 -0.153806 -0.297488 0.577284 -0.214277 0.373281 0.025794 0.023165 0.001740
16 N01 digital_ok 0.00% 100.00% 100.00% 0.00% -1.967483 -0.393088 -0.319456 -0.053811 -0.685003 -0.789584 0.346241 0.010017 0.023303 0.023087 0.000624
17 N01 digital_ok 0.00% 100.00% 100.00% 0.00% -1.546091 -1.365760 -0.265439 0.221547 -0.725246 0.061279 -0.375797 0.328969 0.023400 0.023092 0.000716
18 N01 RF_maintenance 0.00% 100.00% 100.00% 0.00% 1.805548 2.971842 -0.150358 0.033514 0.980433 1.310628 0.598599 0.781683 0.025524 0.023596 0.001570
27 N01 RF_maintenance 100.00% 100.00% 100.00% 0.00% 2.396144 2.605048 0.025032 -0.797913 3.519174 2.654022 9.372518 4.795947 0.023468 0.024195 0.000674
28 N01 RF_maintenance 100.00% 100.00% 100.00% 0.00% -0.762083 4.845766 -1.151536 -0.889352 0.282118 9.436810 -0.152209 9.198430 0.023786 0.024171 0.000630
29 N01 digital_ok 0.00% 100.00% 100.00% 0.00% 0.139807 1.126279 -1.946161 -2.718100 0.570628 -0.132843 0.130120 -1.173133 0.026258 0.023884 0.001603
30 N01 digital_ok 0.00% 100.00% 100.00% 0.00% -0.863699 -0.286343 -1.317203 -1.444304 1.616618 1.413163 -0.124628 2.059455 0.023647 0.023622 0.000579
36 N03 RF_maintenance 100.00% 100.00% 100.00% 0.00% 75.057894 68.959674 16.281945 12.944516 6.592986 5.715997 13.889925 15.066901 0.020358 0.020139 0.000689
37 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 70.315765 53.546450 14.974431 13.745885 8.958693 3.222647 18.036792 11.615292 0.019981 0.019526 0.000510
38 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 72.364929 53.992115 15.971979 13.783817 6.888480 6.288886 15.390992 17.117067 0.019538 0.019503 0.000444
40 N04 digital_ok 100.00% 100.00% 100.00% 0.00% 2.171809 5.794705 -1.681691 -2.322895 0.221640 1.485961 0.482856 2.143593 0.024230 0.023535 0.000801
41 N04 digital_ok 100.00% 0.00% 0.00% 0.00% 2.190313 2.343826 -0.921319 -0.472868 -0.035525 3.851391 -0.059314 6.026347 0.740385 0.830744 0.800934
45 N05 digital_ok 0.00% 100.00% 100.00% 0.00% 0.018233 2.163239 -1.693799 -1.914457 1.605644 2.442053 0.657040 0.931361 0.024601 0.023569 0.001311
46 N05 digital_ok 0.00% 100.00% 100.00% 0.00% -0.876741 -0.493142 -0.538075 -0.902363 -0.615874 0.731730 -0.895027 0.997842 0.023276 0.023916 0.000878
50 N03 RF_maintenance 100.00% 100.00% 100.00% 0.00% 68.566233 47.270100 14.385257 14.113439 3.980511 5.567254 13.453444 16.024536 0.020207 0.019595 0.000660
51 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 63.222308 47.740049 13.520923 13.483560 12.445347 7.549446 22.438779 15.767540 0.021530 0.019816 0.001399
52 N03 RF_maintenance 100.00% 100.00% 100.00% 0.00% 76.036534 59.781583 16.425332 14.210240 8.396959 4.757040 20.873789 15.423021 0.022244 0.020160 0.001371
53 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 61.114539 41.937735 13.592522 13.509986 298.405514 332.375640 108.560225 123.089860 0.024446 0.021009 0.001216
55 N04 digital_ok 0.00% 100.00% 100.00% 0.00% -0.939998 0.358478 0.238752 -0.033514 1.180098 0.299694 0.619582 1.249238 0.026113 0.023093 0.001747
56 N04 digital_ok 0.00% 100.00% 100.00% 0.00% -0.253109 2.853372 0.078761 0.851898 -0.082405 -0.468862 0.539005 1.025696 0.027614 0.024593 0.001747
57 N04 RF_maintenance 0.00% 0.00% 0.00% 0.00% 2.272253 2.619958 -0.499442 0.342779 -0.950273 -1.049960 -0.010017 -0.258839 0.740385 0.830744 0.800934
65 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 63.364609 43.732215 15.097443 12.420945 5.591395 10.238367 14.987285 19.358546 0.021172 0.019958 0.001147
66 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 65.646825 47.254281 14.995430 13.405704 6.342115 6.390632 14.500856 19.054897 0.019645 0.019752 0.000399
67 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 55.583767 46.791540 11.052645 10.569058 2.734432 9.159022 9.127367 18.871446 0.020393 0.020324 0.000537
68 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 71.117882 65.005327 15.515848 16.260656 5.023532 9.282003 17.090199 24.399617 0.022700 0.019763 0.001621
69 N04 digital_ok 0.00% 100.00% 100.00% 0.00% -1.077491 1.008693 -0.769090 0.557295 -0.436914 -0.686589 0.691941 0.361987 0.027745 0.024522 0.002708
70 N04 RF_maintenance 100.00% 100.00% 100.00% 0.00% 59.868823 -0.646397 15.423634 -0.389525 9.168082 0.158602 22.480464 0.569161 0.019613 0.023135 0.001184
71 N04 digital_ok 0.00% 100.00% 100.00% 0.00% 3.696035 -0.048183 -0.284804 0.222733 -0.665993 -0.693998 0.046016 -0.128424 0.023472 0.023215 0.000898
73 N05 digital_ok 0.00% 100.00% 100.00% 0.00% 3.610704 3.074700 -1.083308 -1.316501 1.232822 1.675584 1.199968 0.737452 0.023227 0.023901 0.000970
81 N07 digital_ok 0.00% 100.00% 100.00% 0.00% 3.646771 0.273471 1.232211 0.689897 -0.942004 -0.061279 -1.940424 0.031844 0.027025 0.025160 0.001578
82 N07 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.505394 0.581834 2.190293 1.475255 -0.283766 -0.170012 -0.588026 1.485713 0.025455 0.025383 0.001218
83 N07 digital_ok 0.00% 100.00% 100.00% 0.00% -0.537190 0.560437 0.653897 1.236908 0.892992 0.086882 -1.509530 -2.347300 0.025197 0.025644 0.001659
84 N08 digital_ok 100.00% 100.00% 100.00% 0.00% 55.814014 53.118482 7.711764 6.612724 2.632276 6.341523 10.191682 16.220769 0.027045 0.022240 0.001888
85 N08 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
86 N08 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
87 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% 61.166784 43.956306 8.356342 6.818865 4.831914 3.214189 13.378367 8.369975 0.026385 0.022488 0.001261
88 N09 digital_ok 100.00% 100.00% 100.00% 0.00% 8.503826 3.299094 0.839034 1.365384 7.614804 4.121919 14.319460 6.003963 0.058475 0.042955 0.013356
89 N09 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.155540 -0.150777 1.159810 1.859852 0.355214 -0.599158 0.758915 -2.008197 0.052862 0.043890 0.014708
90 N09 RF_maintenance 100.00% 100.00% 100.00% 0.00% 1.135312 5.244995 0.868252 1.594987 -0.211098 -0.368067 -1.312320 -2.052383 0.043456 0.050290 0.010790
91 N09 digital_ok 100.00% 100.00% 100.00% 0.00% 4.889306 2.613951 0.934540 0.417717 8.321966 5.787604 8.448420 7.822057 0.025099 0.027763 0.002353
92 N10 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.409204 0.210133 -0.390100 -1.005296 0.431667 0.565836 0.143450 0.932489 0.026716 0.023215 0.001757
93 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -1.488385 -0.895806 -0.431976 0.175047 -0.437239 0.169686 0.187106 2.081512 0.023383 0.022807 0.000838
94 N10 digital_ok 100.00% 100.00% 100.00% 0.00% 2.929791 0.126945 0.704404 -0.782771 5.112549 0.001445 2.384589 0.739032 0.022883 0.022909 0.000455
98 N07 digital_ok 0.00% 100.00% 100.00% 0.00% 0.911876 0.823245 2.539580 3.071302 0.071377 -0.654228 -1.315640 -2.050489 0.028977 0.027067 0.002483
99 N07 digital_ok 100.00% 100.00% 100.00% 0.00% 5.575041 3.687452 1.793130 2.459755 -0.531247 1.356306 -1.313021 -0.094042 0.027181 0.029693 0.002774
100 N07 digital_ok 100.00% 100.00% 100.00% 0.00% 4.238016 0.493881 4.198622 2.769923 1.013613 0.722872 -0.393724 -0.845865 0.029010 0.025896 0.002536
101 N08 digital_ok 100.00% 100.00% 100.00% 0.00% 51.417313 44.717983 6.384591 5.501882 2.176893 2.418420 8.215671 8.608276 0.025666 0.021972 0.001491
102 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% -2.189432 -1.334814 21.319910 21.239287 5933.720270 5934.873320 13865.730943 13931.286388 nan nan nan
103 N08 digital_ok 100.00% 100.00% 100.00% 0.00% 56.400654 57.831256 6.814740 6.515494 3.698504 3.616103 12.175784 8.739020 0.021499 0.021297 0.000520
104 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% 61.438823 451.806976 6.471740 61.394471 1.109197 385.632517 5.314811 821.239648 0.021980 0.016487 0.004339
105 N09 digital_ok 0.00% 100.00% 100.00% 0.00% 0.512864 -0.352885 0.949620 0.503282 1.090433 1.394977 0.323006 -1.210077 0.028997 0.027754 0.003544
106 N09 digital_ok 0.00% 100.00% 100.00% 0.00% -0.422148 1.900713 2.266088 0.713733 -0.292360 0.702208 -0.382242 -0.308184 0.027962 0.026133 0.002542
107 N09 digital_ok 100.00% 100.00% 100.00% 0.00% 3.279645 1.844611 3.075635 3.668781 1.353248 2.152555 1.095618 1.892927 0.045788 0.046925 0.009908
108 N09 digital_ok 0.00% 100.00% 100.00% 0.00% 0.188527 -0.217211 1.416269 0.921504 -0.138692 -0.512602 -1.497545 -1.911183 0.025143 0.029283 0.003522
109 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.900478 0.134596 -0.046888 -1.659686 1.022786 -0.614660 0.488936 -1.022406 0.026523 0.023610 0.001777
110 N10 RF_maintenance 100.00% 100.00% 100.00% 0.00% 70.763713 61.151213 15.993527 14.754118 3.734956 5.096691 14.665683 14.238675 0.020009 0.019583 0.000336
111 N10 digital_ok 0.00% 100.00% 100.00% 0.00% 1.369561 1.660710 -0.297959 -1.209964 -0.411194 -0.565542 -0.495591 -0.713127 0.023260 0.023144 0.000626
112 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.546314 -0.368849 -1.166454 -0.086734 -0.809782 0.109561 -1.126519 -0.154687 0.026616 0.023207 0.001937
116 N07 digital_ok 0.00% 100.00% 100.00% 0.00% 3.886629 -0.018233 0.430248 0.752301 1.215636 1.212602 -1.198901 -2.178307 0.029912 0.029606 0.006407
117 N07 digital_ok 0.00% 100.00% 100.00% 0.00% 1.209421 0.680139 1.134739 1.212265 1.008307 0.314623 -0.650405 -2.263332 0.027638 0.024840 0.002164
118 N07 digital_ok 0.00% 100.00% 100.00% 0.00% -0.588002 -0.235800 1.117857 0.653016 1.217803 0.346862 -2.018898 -2.977530 0.024659 0.024556 0.000837
119 N07 RF_maintenance 100.00% 100.00% 100.00% 0.00% 3.853418 4.373873 3.947919 2.883461 1.271603 0.443870 -0.458776 -2.348965 0.029324 0.024928 0.002773
120 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% 51.727958 39.919329 6.588999 5.657462 7.037733 6.136073 14.987178 16.302383 0.024441 0.021700 0.001310
121 N08 digital_ok 100.00% 100.00% 100.00% 0.00% 70.371340 56.718877 16.250758 16.559742 8.291598 9.227950 23.789167 25.684471 0.021023 0.019673 0.001118
122 N08 digital_ok 100.00% 100.00% 100.00% 0.00% 64.397293 66.179567 8.436532 5.938757 3.403010 2.963029 10.946259 8.305605 0.021300 0.021352 0.000438
123 N08 digital_ok 100.00% 100.00% 100.00% 0.00% 65.679330 50.699200 6.660757 7.378229 1.849084 5.059819 6.769161 9.591688 0.026108 0.021688 0.001691
124 N09 digital_ok 100.00% 100.00% 100.00% 0.00% 4.282887 3.854691 0.878401 -1.311800 5.579513 6.494461 5.434546 6.081148 0.036580 0.042942 0.013068
125 N09 RF_maintenance 0.00% 100.00% 100.00% 0.00% 0.175720 0.261655 0.314954 0.526279 2.053932 2.144768 -0.736345 2.310802 0.024763 0.025737 0.001168
126 N09 RF_maintenance 100.00% 100.00% 100.00% 0.00% 4.937073 1.425805 1.124967 0.161001 1.472558 1.350182 1.371414 2.504796 0.025325 0.026519 0.001570
127 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.386357 -0.450437 -0.560368 -0.945356 -0.251669 1.103215 -0.640509 0.187271 0.023645 0.023108 0.000702
128 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.292921 1.063117 0.201471 -0.376208 -1.000739 -0.883248 -0.235253 -0.056071 0.023119 0.023219 0.000662
129 N10 digital_ok 0.00% 100.00% 100.00% 0.00% 0.625338 0.873293 -0.254161 -0.659085 -0.120124 -0.246974 0.575717 0.110407 0.026691 0.023380 0.001802
130 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.476003 0.288035 0.057743 -0.288050 -0.835130 2.005366 0.116935 1.520524 0.023866 0.023197 0.001044
135 N12 digital_maintenance 100.00% 100.00% 100.00% 0.00% 123.370365 178.189959 62.792671 95.196935 1714.561851 10095.822977 1903.011361 5348.794008 0.019578 0.016313 0.002254
136 N12 digital_maintenance 100.00% 100.00% 100.00% 0.00% 153.214480 259.911916 76.528393 113.227711 840.841664 3178.525593 1614.807083 4151.019620 0.017454 0.016252 0.000841
137 N07 RF_maintenance 0.00% 100.00% 100.00% 0.00% 2.061719 0.668843 2.048888 2.357226 0.425273 0.187864 0.300302 -0.640642 0.024779 0.024747 0.000941
138 N07 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.772016 -0.121039 -2.830810 -3.077273 -0.824078 -1.423991 -1.024337 -2.089515 0.023812 0.023835 0.000649
143 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 110.088461 181.003283 49.855496 89.754554 362.163927 946.872216 722.123522 2173.348044 0.017639 0.016072 0.000948
144 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 125.519916 180.870301 74.350045 90.170868 1097.864084 1121.705082 2213.672390 2621.729007 0.019216 0.016485 0.001852
145 N14 RF_maintenance 100.00% 100.00% 100.00% 0.00% 138.974675 248.321622 82.641541 63.090882 834.849376 436.648437 1895.115839 960.565159 0.017387 0.016388 0.000895
155 N12 digital_maintenance 100.00% 100.00% 100.00% 0.00% 115.642187 452.434900 57.764477 289.618177 500.076931 10603.451949 1214.009716 22635.666338 0.017411 nan nan
156 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 388.858850 291.489197 102.116939 101.920447 1080.086909 1654.532582 2476.727870 3348.311388 0.020131 0.017231 0.002261
157 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 122.669262 227.079434 61.524115 76.991125 861.531663 843.284316 1432.279147 1740.517765 0.019961 0.016701 0.001844
158 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 116.175208 209.869168 55.975966 70.030588 461.030416 808.371503 1025.792991 1512.064191 0.017741 0.016183 0.001128
163 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 335.981025 169.197096 121.036866 54.694165 1639.914237 305.932091 3819.395527 852.414096 0.020701 0.017207 0.002106
164 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 134.737310 190.919882 62.943153 89.521803 439.824918 1050.477833 1118.496177 2231.503197 0.017625 0.016209 0.000992
165 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 717.238260 420.158059 inf 239.264163 41275.226229 4628.365491 28341.950700 12595.491559 nan 0.014501 nan
166 N14 RF_maintenance 100.00% 100.00% 100.00% 0.00% 601.511017 515.683738 266.964717 229.105877 6206.206686 4220.303591 14424.452539 9581.360193 0.005854 0.018509 0.004277
176 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 268.305142 212.345338 93.968541 61.669659 1122.260800 829.619845 2240.567094 1745.346277 0.020830 0.017292 0.001499
177 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 137.108832 280.673534 71.181813 79.738579 768.966471 1076.132774 1793.234222 2541.315523 0.018516 0.016396 0.001464
178 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 129.303827 213.094143 64.357804 62.640400 563.512071 663.805235 1263.840219 1417.562936 0.017283 0.016333 0.000784
179 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 110.604897 312.120939 50.278546 206.291940 320.639267 6594.876550 697.918286 10379.717033 0.045040 0.021413 0.006504
184 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 233.239785 638.478181 129.755054 248.266629 1685.360470 4190.869258 3873.667600 10738.583623 0.016924 0.012047 0.005659
185 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 243.569197 173.808059 84.238685 86.357512 1022.419072 1239.804010 1994.363387 2319.178674 0.020470 0.017305 0.001913
186 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 163.769929 165.441404 109.200839 66.181679 1961.035366 343.372450 4234.515363 832.170921 0.018952 0.016894 0.001522
187 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 168.883330 237.996824 93.713100 83.561292 1352.485190 1057.726833 2884.468947 2625.130231 0.016969 0.016156 0.000675
320 N03 dish_maintenance 100.00% 100.00% 100.00% 0.00% 19.922576 12.099923 9.661790 11.131513 10.014946 5.205498 16.894751 7.444958 0.029394 0.026731 0.001973
324 N04 not_connected 100.00% 100.00% 100.00% 0.00% 4.280926 2.167138 22.181166 23.216458 -0.781827 -0.073941 -1.600786 -0.435355 0.028172 0.029093 0.001796
325 N09 dish_ok 100.00% 100.00% 100.00% 0.00% 5.808437 0.218235 22.791702 21.237343 0.606869 -0.020819 1.789402 -1.207606 0.034522 0.037292 0.006521
329 N12 dish_maintenance 100.00% 100.00% 100.00% 0.00% 69.729985 81.119124 1.212446 2.091473 126.292904 126.346388 335.283051 297.307135 0.042355 0.051688 0.011883
333 N12 dish_maintenance 100.00% 100.00% 100.00% 0.00% 72.541876 98.038753 6.564700 5.767279 237.203056 277.714230 480.120707 529.662788 0.095705 0.056336 0.014271
In [22]:
# print ex_ants for easy copy-pasting to YAML file
proposed_ex_ants = [ant for i, ant in enumerate(ants) if np.any([col[i] > 0 for col in bar_cols.values()])]
print('ex_ants: [' + ", ".join(str(ant) for ant in proposed_ex_ants) + ']')
print(f'\nunflagged_ants: [{", ".join([str(ant) for ant in ants if ant not in proposed_ex_ants])}]')
# "golden" means no flags and good a priori status
golden_ants = ", ".join([str(ant) for ant in ants if ((ant not in proposed_ex_ants) and (a_priori_statuses[ant] in good_statuses.split(',')))])
print(f'\ngolden_ants: [{golden_ants}]')
ex_ants: [3, 4, 5, 15, 16, 17, 18, 27, 28, 29, 30, 36, 37, 38, 40, 41, 45, 46, 50, 51, 52, 53, 55, 56, 65, 66, 67, 68, 69, 70, 71, 73, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 135, 136, 137, 138, 143, 144, 145, 155, 156, 157, 158, 163, 164, 165, 166, 176, 177, 178, 179, 184, 185, 186, 187, 320, 324, 325, 329, 333]

unflagged_ants: [57]

golden_ants: []
In [23]:
# write to csv
outpath = os.path.join(nb_outdir, f'rtp_summary_table_{JD}.csv')
print(f'Now saving Table 2 to a csv at {outpath}')
df.to_csv(outpath)
Now saving Table 2 to a csv at /home/obs/src/H6C_Notebooks/_rtp_summary_/rtp_summary_table_2459840.csv
In [24]:
# Load antenna positions
data_list = sorted(glob.glob(os.path.join(data_path, f'zen.{JD}.?????.sum.uvh5')))
hd = io.HERAData(data_list[len(data_list) // 2])

# Figure out where to draw the nodes
node_centers = {}
for node in sorted(set(list(nodes.values()))):
    if np.isfinite(node):
        this_node_ants = [ant for ant in ants + unused_ants if nodes[ant] == node]
        if len(this_node_ants) == 1:
            # put the node label just to the west of the lone antenna 
            node_centers[node] = hd.antpos[ant][node] + np.array([-14.6 / 2, 0, 0])
        else:
            # put the node label between the two antennas closest to the node center
            node_centers[node] = np.mean([hd.antpos[ant] for ant in this_node_ants], axis=0)
            closest_two_pos = sorted([hd.antpos[ant] for ant in this_node_ants], 
                                     key=lambda pos: np.linalg.norm(pos - node_centers[node]))[0:2]
            node_centers[node] = np.mean(closest_two_pos, axis=0)
In [25]:
def Plot_Array(ants, unused_ants, outriggers):
    plt.figure(figsize=(16,16))
    
    plt.scatter(np.array([hd.antpos[ant][0] for ant in hd.data_ants if ant in ants]), 
                np.array([hd.antpos[ant][1] for ant in hd.data_ants if ant in ants]), c='w', s=0)

    # connect every antenna to their node
    for ant in ants:
        if nodes[ant] in node_centers:
            plt.plot([hd.antpos[ant][0], node_centers[nodes[ant]][0]], 
                     [hd.antpos[ant][1], node_centers[nodes[ant]][1]], 'k', zorder=0)

    rc_color = '#0000ff'
    antm_color = '#ffa500'
    autom_color = '#ff1493'

    # Plot 
    unflagged_ants = []
    for i, ant in enumerate(ants):
        ant_has_flag = False
        # plot large blue annuli for redcal flags
        if use_redcal:
            if redcal_flagged_frac[ant] > 0:
                ant_has_flag = True
                plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=7 * (2 - 1 * float(not outriggers)), fill=True, lw=0,
                                                color=rc_color, alpha=redcal_flagged_frac[ant]))
                plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=6 * (2 - 1 * float(not outriggers)), fill=True, color='w'))
        
        # plot medium green annuli for ant_metrics flags
        if use_ant_metrics: 
            if ant_metrics_xants_frac_by_ant[ant] > 0:
                ant_has_flag = True
                plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=6 * (2 - 1 * float(not outriggers)), fill=True, lw=0,
                                                color=antm_color, alpha=ant_metrics_xants_frac_by_ant[ant]))
                plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=5 * (2 - 1 * float(not outriggers)), fill=True, color='w'))
        
        # plot small red annuli for auto_metrics
        if use_auto_metrics:
            if ant in auto_ex_ants:
                ant_has_flag = True                
                plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=5 * (2 - 1 * float(not outriggers)), fill=True, lw=0, color=autom_color)) 
        
        # plot black/white circles with black outlines for antennas
        plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=4 * (2 - 1 * float(not outriggers)), fill=True, color=['w', 'k'][ant_has_flag], ec='k'))
        if not ant_has_flag:
            unflagged_ants.append(ant)

        # label antennas, using apriori statuses if available
        try:
            bgc = matplotlib.colors.to_rgb(status_colors[a_priori_statuses[ant]])
            c = 'black' if (bgc[0]*0.299 + bgc[1]*0.587 + bgc[2]*0.114) > 186 / 256 else 'white'
        except:
            c = 'k'
            bgc='white'
        plt.text(hd.antpos[ant][0], hd.antpos[ant][1], str(ant), va='center', ha='center', color=c, backgroundcolor=bgc)

    # label nodes
    for node in sorted(set(list(nodes.values()))):
        if not np.isnan(node) and not np.all(np.isnan(node_centers[node])):
            plt.text(node_centers[node][0], node_centers[node][1], str(node), va='center', ha='center', bbox={'color': 'w', 'ec': 'k'})
    
    # build legend 
    legend_objs = []
    legend_labels = []
    
    # use circles for annuli 
    legend_objs.append(matplotlib.lines.Line2D([0], [0], marker='o', color='w', markeredgecolor='k', markerfacecolor='w', markersize=13))
    legend_labels.append(f'{len(unflagged_ants)} / {len(ants)} Total {["Core", "Outrigger"][outriggers]} Antennas Never Flagged')
    legend_objs.append(matplotlib.lines.Line2D([0], [0], marker='o', color='w', markerfacecolor='k', markersize=15))
    legend_labels.append(f'{len(ants) - len(unflagged_ants)} Antennas {["Core", "Outrigger"][outriggers]} Flagged for Any Reason')

    if use_auto_metrics:
        legend_objs.append(matplotlib.lines.Line2D([0], [0], marker='o', color='w', markeredgewidth=2, markeredgecolor=autom_color, markersize=15))
        legend_labels.append(f'{len([ant for ant in auto_ex_ants if ant in ants])} {["Core", "Outrigger"][outriggers]} Antennas Flagged by Auto Metrics')
    if use_ant_metrics: 
        legend_objs.append(matplotlib.lines.Line2D([0], [0], marker='o', color='w', markeredgewidth=2, markeredgecolor=antm_color, markersize=15))
        legend_labels.append(f'{np.round(np.sum([frac for ant, frac in ant_metrics_xants_frac_by_ant.items() if ant in ants]), 2)} Antenna-Nights on' 
                             f'\n{np.sum([frac > 0 for ant, frac in ant_metrics_xants_frac_by_ant.items() if ant in ants])} {["Core", "Outrigger"][outriggers]} Antennas '
                             'Flagged by Ant Metrics\n(alpha indicates fraction of time)')        
    if use_redcal:
        legend_objs.append(matplotlib.lines.Line2D([0], [0], marker='o', color='w', markeredgewidth=2, markeredgecolor=rc_color, markersize=15))
        legend_labels.append(f'{np.round(np.sum(list(redcal_flagged_frac.values())), 2)} Antenna-Nights on' 
                             f'\n{np.sum([frac > 0 for ant, frac in redcal_flagged_frac.items() if ant in ants])} {["Core", "Outrigger"][outriggers]} Antennas '
                             'Flagged by Redcal\n(alpha indicates fraction of time)')

    # use rectangular patches for a priori statuses that appear in the array
    for aps in sorted(list(set(list(a_priori_statuses.values())))):
        if aps != 'Not Found':
            legend_objs.append(plt.Circle((0, 0), radius=7, fill=True, color=status_colors[aps]))
            legend_labels.append(f'A Priori Status:\n{aps} ({[status for ant, status in a_priori_statuses.items() if ant in ants].count(aps)} {["Core", "Outrigger"][outriggers]} Antennas)')

    # label nodes as a white box with black outline
    if len(node_centers) > 0:
        legend_objs.append(matplotlib.patches.Patch(facecolor='w', edgecolor='k'))
        legend_labels.append('Node Number')

    if len(unused_ants) > 0:
        legend_objs.append(matplotlib.lines.Line2D([0], [0], marker='o', color='w', markerfacecolor='grey', markersize=15, alpha=.2))
        legend_labels.append(f'Anntenna Not In Data')
        
    
    plt.legend(legend_objs, legend_labels, ncol=2, fontsize='large', framealpha=1)
    
    if outriggers:
        pass
    else:
        plt.xlim([-200, 150])
        plt.ylim([-150, 150])        
       
    # set axis equal and label everything
    plt.axis('equal')
    plt.tight_layout()
    plt.title(f'Summary of {["Core", "Outrigger"][outriggers]} Antenna Statuses and Metrics on {JD}', size=20)    
    plt.xlabel("Antenna East-West Position (meters)", size=12)
    plt.ylabel("Antenna North-South Position (meters)", size=12)
    plt.xticks(fontsize=12)
    plt.yticks(fontsize=12)
    xlim = plt.gca().get_xlim()
    ylim = plt.gca().get_ylim()    
        
    # plot unused antennas
    plt.autoscale(False)    
    for ant in unused_ants:
        if nodes[ant] in node_centers:
            plt.plot([hd.antpos[ant][0], node_centers[nodes[ant]][0]], 
                     [hd.antpos[ant][1], node_centers[nodes[ant]][1]], 'k', alpha=.2, zorder=0)
        
        plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=4, fill=True, color='w', ec=None, alpha=1, zorder=0))
        plt.gca().add_artist(plt.Circle(tuple(hd.antpos[ant][0:2]), radius=4, fill=True, color='grey', ec=None, alpha=.2, zorder=0))
        if hd.antpos[ant][0] < xlim[1] and hd.antpos[ant][0] > xlim[0]:
            if hd.antpos[ant][1] < ylim[1] and hd.antpos[ant][1] > ylim[0]:
                plt.text(hd.antpos[ant][0], hd.antpos[ant][1], str(ant), va='center', ha='center', color='k', alpha=.2) 

Figure 1: Array Plot of Flags and A Priori Statuses¶

This plot shows all antennas, which nodes they are connected to, and their a priori statuses (as the highlight text of their antenna numbers). It may also show (depending on what is finished running):

  • Whether they were flagged by auto_metrics (red circle) for bandpass shape, overall power, temporal variability, or temporal discontinuities. This is done in a binary fashion for the whole night.
  • Whether they were flagged by ant_metrics (green circle) as either dead (on either polarization) or crossed, with the transparency indicating the fraction of the night (i.e. number of files) that were flagged.
  • Whether they were flagged by redcal (blue circle) for high chi^2, with the transparency indicating the fraction of the night (i.e. number of files) that were flagged.

Note that the last fraction does not include antennas that were flagged before going into redcal due to their a priori status, for example.

In [26]:
core_ants = [ant for ant in ants if ant < 320]
outrigger_ants = [ant for ant in ants if ant >= 320]
Plot_Array(ants=core_ants, unused_ants=unused_ants, outriggers=False)
if len(outrigger_ants) > 0:
    Plot_Array(ants=outrigger_ants, unused_ants=sorted(set(unused_ants + core_ants)), outriggers=True)

Metadata¶

In [27]:
from hera_qm import __version__
print(__version__)
from hera_cal import __version__
print(__version__)
2.0.4.dev7+g7e32def
3.1.5.dev72+g3641fe9
In [ ]: