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 = "2459835"
data_path = "/mnt/sn1/2459835"
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-12-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/2459835/zen.2459835.25323.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/2459835/zen.2459835.?????.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/2459835/zen.2459835.?????.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 2459835
Date 9-12-2022
LST Range 18.953 -- 20.953 hours
X-Engine Status ✅ ✅ ✅ ✅ ✅ ✅ ✅ ✅
Number of Files 372
Total Number of Antennas 132
OPERATIONAL STATUS SUMMARY
Antenna A Priori Status Count dish_maintenance: 3
RF_maintenance: 31
digital_maintenance: 3
digital_ok: 92
not_connected: 3
Commanded Signal Source None
Antennas in Commanded State 0 / 132 (0.0%)
Cross-Polarized Antennas
Total Number of Nodes 13
Nodes Registering 0s
Nodes Not Correlating N01, N03, N05, N08, N09, N12
NIGHTLY ANALYSIS SUMMARY
Ant Metrics Done? ✅
Ant Metrics Flagged Antennas 122 / 132 (92.4%)
Auto Metrics Done? ✅
Auto Metrics Flagged Antennas 64 / 132 (48.5%)
Redcal Done? ❌
Never Flagged Antennas 0 / 132 (0.0%)
A Priori Good Antennas Flagged 92 / 92 total a priori good antennas:
3, 5, 7, 9, 10, 15, 16, 17, 19, 20, 21, 29,
30, 31, 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, 127, 128, 129, 130, 140,
141, 142, 143, 144, 156, 157, 158, 160, 161,
162, 163, 164, 165, 167, 169, 170, 176, 177,
178, 179, 181, 183, 184, 185, 186, 187, 189,
190, 191
A Priori Bad Antennas Not Flagged 0 / 40 total a priori bad antennas:
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_2459835.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% -0.314803 0.275690 -1.068169 -0.503510 -1.410140 0.740483 -0.375719 1.966680 0.031557 0.032542 0.001060
4 N01 RF_maintenance 0.00% 100.00% 100.00% 0.00% -1.248017 -0.698351 -0.237655 -0.839702 -0.228755 -1.041803 0.612680 -0.461070 0.043403 0.037101 0.001776
5 N01 digital_ok 0.00% 100.00% 100.00% 0.00% -1.009774 0.307782 -0.525901 0.238746 -1.037627 0.893941 -0.077749 -1.092140 0.048161 0.041488 0.002620
7 N02 digital_ok 100.00% 100.00% 100.00% 0.00% -0.023014 -0.472209 -0.621317 -0.931943 5.405208 6.810993 30.328178 35.403296 0.094332 0.064900 0.013753
8 N02 RF_maintenance 100.00% 0.00% 91.40% 0.00% 4.878797 5.236485 11.794119 11.904256 13.348861 10.280058 -5.155753 -4.833586 0.699932 0.313014 0.568365
9 N02 digital_ok 0.00% 100.00% 100.00% 0.00% -1.186336 0.194380 -0.265817 -0.229587 0.713995 0.282532 -0.313215 -0.950662 0.095479 0.061825 0.015041
10 N02 digital_ok 100.00% 100.00% 100.00% 0.00% 0.517114 -1.008364 -0.031023 -0.975258 5.765379 7.973955 39.721364 28.566460 0.033023 0.052159 0.001877
15 N01 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
16 N01 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
17 N01 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
18 N01 RF_maintenance 100.00% 100.00% 100.00% 0.00% -0.309809 -0.787098 5.313627 0.553619 24.787145 8.397554 94.512990 6.441134 0.036483 0.042258 0.000665
19 N02 digital_ok 100.00% 100.00% 100.00% 0.00% -1.239793 1.409567 -0.689738 1.898526 2.961686 1.236390 36.828084 0.573209 0.036741 0.036773 0.006552
20 N02 digital_ok 0.00% 100.00% 100.00% 0.00% 0.135688 -0.694580 3.303743 -1.066323 0.855901 -0.581896 0.723216 -1.169955 0.035970 0.050462 0.001697
21 N02 digital_ok 100.00% 100.00% 100.00% 0.00% 0.310011 -0.974529 1.347213 -0.226102 0.368999 0.478034 1.202016 6.874856 0.033510 0.036817 0.002535
27 N01 RF_maintenance 0.00% 100.00% 100.00% 0.00% 2.255009 2.476446 2.327024 2.612209 0.597191 0.596385 1.563059 0.106871 0.034325 0.035738 0.000605
28 N01 RF_maintenance 0.00% 100.00% 100.00% 0.00% -1.383931 -0.602437 -0.746871 -0.895874 -0.394244 2.484462 3.178977 2.798801 0.037891 0.040375 0.001516
29 N01 digital_ok 0.00% 100.00% 100.00% 0.00% 0.395066 -0.465600 0.090351 -1.067630 2.126154 1.520710 0.194102 0.000775 0.035729 0.039250 0.000470
30 N01 digital_ok 100.00% 100.00% 100.00% 0.00% -1.266579 -1.300783 -0.455075 -0.010309 6.222181 6.311743 35.845686 22.802739 0.036987 0.037143 0.002298
31 N02 digital_ok 100.00% 100.00% 100.00% 0.00% -0.871517 0.209646 4.682359 0.940237 -0.454905 3.496883 0.005283 0.782203 0.032022 0.035721 0.002342
32 N02 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.691824 -0.777760 -0.650646 -0.466687 -0.352360 -0.598096 -0.133660 0.557886 0.032309 0.036839 0.000990
33 N02 RF_maintenance 100.00% 100.00% 100.00% 0.00% -0.538552 0.336472 -0.895952 2.157077 0.127977 8.199165 0.174644 8.075354 0.079425 0.053320 0.011226
36 N03 RF_maintenance 0.00% 100.00% 100.00% 0.00% 1.129556 0.035389 -0.404428 -0.087797 -0.148537 0.087338 -0.531358 0.183003 0.031140 0.031234 0.000890
37 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 0.528861 1.225718 1.363501 -0.495868 -0.323368 1.310653 0.905812 16.316542 0.030657 0.031931 0.002475
38 N03 digital_ok 100.00% 100.00% 100.00% 0.00% -0.198331 0.792989 2.227135 -0.540975 0.828671 3.448771 4.812982 5.908732 0.029907 0.031686 0.001294
40 N04 digital_ok 100.00% 0.00% 83.33% 0.00% 4.977442 5.546085 9.710349 8.208266 38.361549 52.010219 -2.171771 1.463265 0.714904 0.376331 0.551495
41 N04 digital_ok 0.00% 100.00% 100.00% 0.00% 0.466456 -0.835190 0.015552 -1.170792 1.171444 -1.548085 -0.683615 -0.287436 0.035281 0.036915 0.001851
45 N05 digital_ok 100.00% 100.00% 100.00% 0.00% -1.389460 -0.043912 -0.638038 0.745013 14.719252 6.003578 15.661335 27.371574 0.031934 0.035798 0.003401
46 N05 digital_ok 100.00% 100.00% 100.00% 0.00% 0.313467 -0.428325 2.516889 0.342344 5.007060 4.531111 14.333239 12.636050 0.030316 0.032097 0.000439
50 N03 RF_maintenance 0.00% 100.00% 100.00% 0.00% 1.642140 1.209220 -0.360722 -0.396940 0.617003 -0.945537 -0.328565 -1.662724 0.030860 0.030710 0.000451
51 N03 digital_ok 100.00% 100.00% 100.00% 0.00% -0.107961 1.033424 1.811337 -0.551988 3.241200 4.087965 5.819019 10.177399 0.030921 0.031092 0.000951
52 N03 RF_maintenance 100.00% 100.00% 100.00% 0.00% -0.997738 -0.517669 2.253785 0.575359 5.068024 -0.547627 3.679457 1.469349 0.031314 0.030976 0.000760
53 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 0.335056 -0.247687 0.746040 0.578595 3.444294 4.393018 30.350521 37.095437 0.032688 0.031198 0.001152
55 N04 digital_ok 0.00% 100.00% 100.00% 0.00% -0.092047 0.593786 1.222709 0.230043 1.416150 -0.519946 0.355104 -0.705381 0.039044 0.039892 0.002261
56 N04 digital_ok 0.00% 100.00% 100.00% 0.00% 0.226277 0.102113 -0.456075 -0.638804 0.250321 -0.023600 -0.239707 -0.669478 0.040564 0.038786 0.001533
57 N04 RF_maintenance 0.00% 100.00% 100.00% 0.00% 1.979614 -1.362596 1.422190 -0.318234 -0.466979 -0.386789 -0.385043 -0.014130 0.041166 0.035068 0.003337
65 N03 digital_ok 0.00% 100.00% 100.00% 0.00% 0.770940 -0.501308 0.452759 1.048607 1.128945 1.186641 0.350287 1.760346 0.031150 0.032579 0.001140
66 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 0.529995 -0.495363 1.902543 -0.877460 23.767892 22.906235 97.885564 87.500123 0.031402 0.030818 0.001992
67 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 1.371886 1.020379 -0.190976 5.004482 0.568545 0.905462 0.951665 2.107056 0.031675 0.032779 0.001919
68 N03 digital_ok 100.00% 100.00% 100.00% 0.00% 1.308012 -0.932991 0.054261 3.882416 0.356295 3.824567 0.548759 3.075567 0.032223 0.031321 0.001489
69 N04 digital_ok 100.00% 100.00% 100.00% 0.00% 0.620091 0.247225 0.172116 -0.455679 1.476151 8.505494 0.424813 3.619893 0.037611 0.037574 0.002464
70 N04 RF_maintenance 100.00% 0.00% 83.33% 0.00% 5.715348 5.348576 9.445975 10.874766 48.368973 23.798494 -1.700472 -4.319967 0.721885 0.370659 0.557224
71 N04 digital_ok 0.00% 100.00% 100.00% 0.00% 0.247278 0.277100 0.465180 0.685258 1.028009 1.822607 -0.166935 -0.693650 0.040578 0.045577 0.013634
73 N05 digital_ok 100.00% 100.00% 100.00% 0.00% 2.424388 -0.925550 2.173977 -0.880037 0.591320 2.207272 1.557881 6.285234 0.033013 0.036417 0.002053
81 N07 digital_ok 0.00% 100.00% 100.00% 0.00% -0.620525 -0.091470 -0.724078 1.745882 -1.709813 0.500449 -0.649482 0.021456 0.042099 0.038769 0.006625
82 N07 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.576189 0.010174 -0.606531 -0.444311 -0.785669 -1.276246 1.179609 3.150143 0.061831 0.035363 0.001892
83 N07 digital_ok 0.00% 100.00% 100.00% 0.00% -0.058612 -0.089545 1.415524 1.812162 -0.510581 1.151851 -0.559309 -0.877750 0.041417 0.037184 0.000454
84 N08 digital_ok 0.00% 100.00% 100.00% 0.00% 0.181494 -0.384611 -0.846630 2.163925 1.055729 -0.539755 0.927359 1.331589 0.033513 0.032018 0.000783
85 N08 digital_ok 0.00% 100.00% 100.00% 0.00% -1.319108 -1.360946 -0.709159 -0.486577 -0.623559 -1.352756 -0.290917 0.632656 0.055779 0.037993 0.002281
86 N08 digital_ok 100.00% 100.00% 100.00% 0.00% -0.945403 -0.918239 -0.815707 0.518947 4.518587 3.239229 7.119530 17.255480 0.046168 0.037482 0.002047
87 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
88 N09 digital_ok 100.00% 100.00% 100.00% 0.00% 0.012722 -0.857533 4.002715 0.630383 49.511728 37.205759 184.418995 140.269339 0.037207 0.038797 0.000569
90 N09 RF_maintenance 0.00% 100.00% 100.00% 0.00% -1.415216 -1.408622 -0.447433 -0.369129 -0.141311 3.510797 0.427044 0.095556 0.039887 0.044955 0.003767
91 N09 digital_ok 0.00% 100.00% 100.00% 0.00% -1.006725 -0.581110 0.284991 0.569698 -0.579113 -0.793915 0.441705 -0.356623 0.031261 0.032625 0.000869
92 N10 RF_maintenance 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
93 N10 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
94 N10 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
98 N07 digital_ok 0.00% 100.00% 100.00% 0.00% -1.023772 -0.307577 -0.206926 -0.654591 -0.407953 -1.031147 0.964769 0.958052 0.058523 0.079466 0.017944
99 N07 digital_ok 100.00% 0.00% 0.00% 0.00% 4.980817 5.533252 11.256454 9.593314 20.433028 40.582860 -5.617977 -1.875132 0.794711 0.523151 0.577121
100 N07 digital_ok 100.00% 0.00% 0.00% 0.00% 4.937856 5.410607 10.979450 10.384416 21.113330 27.823580 -4.951589 -3.310051 0.795469 0.532939 0.567854
101 N08 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
102 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% -1.027986 -0.483611 3.824951 2.462045 1211.366858 1261.228060 4753.209068 6275.748012 0.035106 0.032028 0.001358
103 N08 digital_ok 0.00% 100.00% 100.00% 0.00% -0.650129 -0.689833 1.131208 -0.092078 1.150661 0.199686 3.194103 0.599908 0.034306 0.033540 0.000835
104 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% -0.374322 1.190479 0.034776 9.403874 -0.995924 6.776779 0.279023 48.557920 0.034797 0.029007 0.005231
105 N09 digital_ok 0.00% 100.00% 100.00% 0.00% -0.659148 -1.119035 -0.752450 -0.198649 -0.399832 -0.185926 0.096805 -0.475936 0.036575 0.039004 0.003199
106 N09 digital_ok 0.00% 100.00% 100.00% 0.00% 1.691827 -1.142355 0.085558 0.230426 0.058621 0.941705 1.586343 -0.807803 0.036537 0.038705 0.001672
107 N09 digital_ok 100.00% 100.00% 100.00% 0.00% -1.043225 0.128702 -0.081996 -0.538543 0.433479 -0.443923 3.873448 4.469717 0.034263 0.032665 0.001116
108 N09 digital_ok 0.00% 100.00% 100.00% 0.00% 1.883243 -0.810104 0.260853 0.909631 0.109731 -0.417011 1.769131 0.026208 0.033371 0.033153 0.001086
109 N10 digital_ok 0.00% 100.00% 100.00% 0.00% 0.840910 -0.611411 -0.031276 -1.127335 -0.005665 -0.279339 -0.766062 -0.891921 0.034755 0.035412 0.000960
110 N10 RF_maintenance 0.00% 100.00% 100.00% 0.00% 2.252740 1.690931 0.278431 -0.089468 0.642263 1.253783 -1.203543 -1.428217 0.031899 0.037541 0.002943
111 N10 digital_ok 100.00% 100.00% 100.00% 0.00% -1.050369 -0.371517 -0.669281 -0.827905 -0.873132 12.927967 -0.412683 4.328343 0.033917 0.036616 0.000952
112 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.223842 0.000016 -0.926048 -0.663723 2.752180 1.780128 -0.835322 -1.155651 0.033019 0.036179 0.001249
116 N07 digital_ok 0.00% 100.00% 100.00% 0.00% 0.327715 -1.014292 -0.290010 -0.780746 0.125219 0.732537 -0.017533 -0.456860 0.070309 0.093306 0.015382
117 N07 digital_ok 0.00% 100.00% 100.00% 0.00% 0.331087 0.057206 2.177874 1.998812 0.561404 -0.458385 -0.623265 -1.492391 0.061105 0.062808 -0.001482
118 N07 digital_ok 0.00% 100.00% 100.00% 0.00% -0.305481 1.917891 0.937175 0.847889 -0.760713 -1.146657 -0.390397 -0.022096 0.049441 0.093252 0.013809
119 N07 RF_maintenance 0.00% 100.00% 100.00% 0.00% 0.346538 -0.871019 2.541907 0.172333 0.393339 -0.984978 -1.082650 -1.136712 0.041065 0.060169 0.001910
120 N08 RF_maintenance 100.00% 100.00% 100.00% 0.00% -0.776355 1.785120 0.352486 4.189826 76.008720 -0.727505 203.982575 0.925816 0.037458 0.033741 0.001648
121 N08 digital_ok 100.00% 100.00% 100.00% 0.00% -0.182444 1.092034 1.444073 4.796260 20.483641 3.775337 87.572870 20.100264 0.033471 0.032710 -0.000624
122 N08 digital_ok 100.00% 100.00% 100.00% 0.00% nan nan inf inf nan nan nan nan nan nan nan
123 N08 digital_ok 0.00% 100.00% 100.00% 0.00% 0.233785 -0.774739 -0.820229 0.140334 1.119764 -1.038249 0.197331 1.031067 0.032927 0.033830 0.001803
125 N09 RF_maintenance 0.00% 100.00% 100.00% 0.00% -1.101870 -0.111773 0.146859 1.376846 -1.009854 -0.386831 -0.823657 -0.601764 0.033101 0.033091 0.000465
126 N09 RF_maintenance 0.00% 100.00% 100.00% 0.00% -1.045895 0.287057 -0.601882 -0.149562 3.112804 0.123760 0.150085 0.963513 0.033033 0.035670 0.002925
127 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.697412 -1.350613 0.525053 -0.233338 -0.768499 1.538662 -0.865765 -0.337650 0.041591 0.042849 0.001900
128 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.353991 0.103012 -1.025258 -0.345496 -0.148533 0.706188 -0.484917 -0.735396 0.044400 0.048070 0.003887
129 N10 digital_ok 100.00% 0.00% 0.00% 0.00% 4.954651 5.441765 10.189596 10.548553 36.054003 27.982187 -3.254283 -3.584673 0.736946 0.487049 0.501762
130 N10 digital_ok 0.00% 100.00% 100.00% 0.00% -0.649875 -0.192062 -0.978384 -0.663221 0.710706 0.982526 -0.624783 1.018157 0.035177 0.046870 0.002061
135 N12 digital_maintenance 0.00% 100.00% 100.00% 0.00% -1.001498 -0.239844 -0.456043 -1.012562 -0.634340 -1.048671 0.609285 -0.470720 0.036112 0.033335 0.001470
136 N12 digital_maintenance 0.00% 100.00% 100.00% 0.00% 0.186248 0.021635 -0.086769 0.179485 1.434843 -0.201349 0.526553 -0.149968 0.037933 0.034875 0.000811
137 N07 RF_maintenance 100.00% 0.00% 0.00% 0.00% 4.981373 5.662762 11.023864 8.230705 20.905781 55.697424 -4.910455 2.021261 0.793105 0.497904 0.582452
138 N07 RF_maintenance 0.00% 100.00% 100.00% 0.00% 0.523138 -1.381900 1.271631 0.050595 -1.238888 -0.720539 0.008995 -1.125071 0.032879 0.032836 0.000481
140 N13 digital_ok 0.00% 100.00% 100.00% 0.00% 2.448965 2.585855 2.104096 2.739772 0.337440 0.681731 1.070690 0.820855 0.034004 0.031248 0.002690
141 N13 digital_ok 100.00% 100.00% 100.00% 0.00% -0.821672 2.205879 0.632639 2.771556 -0.419382 1.553314 0.218252 4.875010 0.053896 0.055337 0.002988
142 N13 digital_ok 0.00% 100.00% 100.00% 0.00% 0.510908 2.274409 1.447380 2.777908 1.806757 -0.113859 1.484343 -0.598383 0.061245 0.067036 0.002054
143 N14 digital_ok 100.00% 0.00% 0.00% 0.00% 4.986194 5.346482 9.859963 11.046389 39.365519 20.842917 -2.496708 -4.880729 0.797549 0.507969 0.613504
144 N14 digital_ok 0.00% 100.00% 100.00% 0.00% 0.647518 0.960903 1.322164 1.702971 0.826174 3.008385 0.737786 1.728453 0.036398 0.042423 0.001208
145 N14 RF_maintenance 0.00% 100.00% 100.00% 0.00% 2.236223 2.540156 2.417118 2.871184 0.005665 1.013407 0.453573 1.422648 0.036753 0.039086 0.001393
150 N15 RF_maintenance 0.00% 100.00% 100.00% 0.00% 2.018997 2.407534 2.500978 3.222856 -0.070914 0.445156 2.748045 3.368709 0.139222 0.143050 0.012957
155 N12 digital_maintenance 0.00% 100.00% 100.00% 0.00% 2.398490 2.982539 2.040550 2.550466 0.251452 0.384770 1.220968 1.324842 0.037772 0.034646 0.000584
156 N12 digital_ok 100.00% 100.00% 100.00% 0.00% -0.645984 -0.356256 -1.065332 -0.633777 0.021167 0.310236 -0.505089 6.734077 0.033058 0.033039 0.001315
157 N12 digital_ok 0.00% 100.00% 100.00% 0.00% -1.299248 -0.104440 -0.578163 0.296121 -0.754036 1.463021 0.073925 -1.176793 0.039133 0.034581 0.002812
158 N12 digital_ok 0.00% 100.00% 100.00% 0.00% 2.401479 -0.612687 2.457294 1.214887 -0.756874 -0.667250 -0.679504 1.793226 0.033151 0.031647 0.001432
160 N13 digital_ok 0.00% 100.00% 100.00% 0.00% 2.416998 2.902812 2.268922 2.665449 -0.136663 0.887985 0.599845 1.081130 0.059954 0.067415 0.014650
161 N13 digital_ok 0.00% 100.00% 100.00% 0.00% -0.136696 -1.449721 -0.979244 0.146251 1.175174 -0.476172 -0.105997 -0.313076 0.051734 0.039070 0.003562
162 N13 digital_ok 0.00% 100.00% 100.00% 0.00% 0.116571 0.463498 -0.645780 -0.328588 0.286736 0.551780 -0.610843 -0.339747 0.087010 0.038787 0.014375
163 N14 digital_ok 100.00% 100.00% 100.00% 0.00% -1.284801 -0.557182 -0.117510 0.787945 0.822232 0.393600 5.678911 4.989273 0.038844 0.070932 0.009328
164 N14 digital_ok 0.00% 100.00% 100.00% 0.00% -0.392521 -1.096534 -1.083761 0.302748 -0.554057 0.861682 0.219525 0.073985 0.038743 0.067335 0.007040
165 N14 digital_ok 0.00% 100.00% 100.00% 0.00% 1.139173 -1.103415 1.909787 -0.171654 -0.191177 -0.247191 -1.516650 0.089924 0.033565 0.041774 0.000506
166 N14 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.133182 -0.562859 -0.452623 -0.534125 1.310154 -0.758677 -0.528190 -1.101743 0.033826 0.041728 0.004212
167 N15 digital_ok 100.00% 0.00% 0.00% 0.00% 4.023747 4.352303 11.684606 11.917262 29.334704 21.007882 13.011978 12.178071 0.672360 0.509141 0.383289
168 N15 RF_maintenance 100.00% 0.00% 0.00% 0.00% 4.910369 5.258035 11.838137 12.292004 13.469460 6.925469 -6.740012 -5.916684 0.805593 0.631759 0.467204
169 N15 digital_ok 100.00% 0.00% 0.00% 0.00% 4.869021 5.205427 12.211016 12.066701 8.549322 8.854112 -7.039172 -5.812032 0.806640 0.600609 0.487338
170 N15 digital_ok 100.00% 0.00% 0.00% 0.00% 4.831937 5.180566 12.257460 11.895307 8.050137 11.208232 -7.117552 -5.149016 0.789993 0.584409 0.497660
176 N12 digital_ok 0.00% 100.00% 100.00% 0.00% 0.251288 0.316854 -0.162538 -0.015552 0.641165 -1.212492 -1.054547 -1.881725 0.036469 0.031583 0.000979
177 N12 digital_ok 0.00% 100.00% 100.00% 0.00% 0.245521 -1.212970 -0.323727 -0.039260 -0.593029 2.393393 -0.216566 2.260733 0.038691 0.033989 0.001100
178 N12 digital_ok 100.00% 100.00% 100.00% 0.00% 0.350392 -0.004468 2.620435 3.067261 11.693067 11.565044 29.354471 29.316030 0.036918 0.034763 0.001963
179 N12 digital_ok 100.00% 100.00% 100.00% 0.00% -1.063875 -0.760086 -0.287293 -0.273706 12.557950 -1.272740 1.296011 -0.913938 0.035791 0.035242 0.002840
180 N13 RF_maintenance 0.00% 100.00% 100.00% 0.00% -0.000016 2.460828 -0.688467 2.917185 1.792927 -0.321100 -0.181886 0.217141 0.059026 0.065986 0.006942
181 N13 digital_ok 100.00% 100.00% 100.00% 0.00% 2.331202 -0.528327 2.494696 1.034823 0.025540 2.908447 0.494014 10.847785 0.038959 0.072130 0.001141
182 N13 RF_maintenance 100.00% 0.00% 0.00% 0.00% 4.922677 4.954974 11.826375 0.705760 13.980431 69.797707 -6.498965 72.737726 0.781889 0.442173 0.605858
183 N13 digital_ok 100.00% 100.00% 100.00% 0.00% -0.232870 -1.076867 -0.980618 -0.495800 -1.088467 -0.235400 -0.975306 4.533834 0.046170 0.040812 0.003487
184 N14 digital_ok 100.00% 100.00% 100.00% 0.00% -1.050764 -1.113363 -1.135698 -0.932414 13.643366 10.528144 41.343540 41.729002 0.033461 0.035400 0.001454
185 N14 digital_ok 100.00% 100.00% 100.00% 0.00% 0.471252 -0.928180 0.650005 -1.171660 44.510791 34.414444 225.090979 179.382071 0.037039 0.042676 0.001322
186 N14 digital_ok 0.00% 100.00% 100.00% 0.00% 0.180815 0.576558 0.948472 1.385731 -0.483240 -0.496325 1.388733 0.494190 0.035414 0.048230 0.002536
187 N14 digital_ok 0.00% 100.00% 100.00% 0.00% -0.758458 0.108011 0.268574 0.033760 0.204464 -0.276997 1.529936 1.118867 0.035917 0.038319 0.005616
189 N15 digital_ok 100.00% 100.00% 100.00% 0.00% -1.177426 -1.332406 -0.526807 -0.462404 3.839438 0.309132 20.972032 3.165402 0.042010 0.050420 0.004521
190 N15 digital_ok 0.00% 100.00% 100.00% 0.00% 0.203921 2.352664 -0.799446 2.887510 -0.947157 -0.273532 -0.949515 1.395427 0.038501 0.048281 0.009112
191 N15 digital_ok 100.00% 100.00% 100.00% 0.00% -1.179683 -0.969773 -0.102051 -0.477727 -0.416814 -0.320300 0.318987 4.420945 0.042867 0.053543 0.004582
320 N03 dish_maintenance 100.00% 100.00% 100.00% 0.00% 1.809203 2.485317 5.512781 5.612899 1.408376 0.630311 4.783092 0.890248 0.031464 0.030836 -0.000408
321 N02 not_connected 100.00% 0.00% 100.00% 0.00% 5.075818 5.530325 10.335894 10.098623 33.434045 32.327697 2.630729 3.982438 0.690665 0.302029 0.576381
323 N02 not_connected 100.00% 100.00% 100.00% 0.00% -0.462225 0.459328 1.075803 0.925303 0.503979 6.865176 3.043935 5.435312 0.084403 0.051886 0.015850
324 N04 not_connected 0.00% 100.00% 100.00% 0.00% 1.287377 -0.824675 1.543852 -1.040536 0.599659 -0.278067 -1.345434 1.003967 0.037617 0.037551 0.000836
329 N12 dish_maintenance 0.00% 100.00% 100.00% 0.00% 0.619261 -0.065684 1.601227 -0.946605 -0.971907 0.719507 0.428223 2.301236 0.037969 0.034279 0.001585
333 N12 dish_maintenance 0.00% 100.00% 100.00% 0.00% 1.925102 -1.482587 2.306851 0.223595 -0.227525 0.101783 0.686768 -0.000775 0.038704 0.035261 -0.000009
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, 7, 8, 9, 10, 15, 16, 17, 18, 19, 20, 21, 27, 28, 29, 30, 31, 32, 33, 36, 37, 38, 40, 41, 45, 46, 50, 51, 52, 53, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 73, 81, 82, 83, 84, 85, 86, 87, 88, 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, 125, 126, 127, 128, 129, 130, 135, 136, 137, 138, 140, 141, 142, 143, 144, 145, 150, 155, 156, 157, 158, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 189, 190, 191, 320, 321, 323, 324, 329, 333]

unflagged_ants: []

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_2459835.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.3.dev47+ga570afb
3.1.4.dev14+g122e1cb
In [ ]: