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.

In [1]:
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 os
import h5py
from copy import deepcopy
from IPython.display import display, HTML
from hera_notebook_templates.utils import status_colors

%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_'
# 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
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']
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}"')
JD = "2459774"
data_path = "/mnt/sn1/2459774"
ant_metrics_ext = ".ant_metrics.hdf5"
redcal_ext = ".known_good.omni.calfits"
nb_outdir = "/home/obs/src/H5C_Notebooks/_rtp_summary_"
In [4]:
from astropy.time import Time
utc = Time(JD, format='jd').datetime
print(f'Date: {utc.month}-{utc.day}-{utc.year}')
Date: 7-13-2022
In [5]:
# Per-season options
def ant_to_report_url(ant):
    return f'https://htmlpreview.github.io/?https://github.com/HERA-Team/H5C_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.')
No files found matching glob /mnt/sn1/2459774/zen.2459774*.auto_metrics.h5. Skipping auto_metrics.

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 1926 ant_metrics files matching glob /mnt/sn1/2459774/zen.2459774.?????.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/2459774/zen.2459774.?????.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
hd = io.HERAData(sorted(glob.glob(os.path.join(data_path, 'zen.*.sum.uvh5')))[0])
unused_ants = [ant for ant in hd.antpos if ant not in ants]    

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}

Build DataFrame¶

In [14]:
# build dataframe
to_show = {'Ant': [f'<a href="{ant_to_report_url(ant)}" target="_blank">{ant}</a>' for ant in ants],
           'Node': [nodes[ant] 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 1: 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 [15]:
HTML(table.render())
Out[15]:
Ant Node A Priori Status Dead Fraction in Ant Metrics (Jee) Dead Fraction in Ant Metrics (Jnn) Crossed Fraction in Ant Metrics Average Dead Ant Metric (Jee) Average Dead Ant Metric (Jnn) Average Crossed Ant Metric
3 1 RF_maintenance 0.52% 0.00% 0.00% 0.699733 0.604752 0.404629
4 1 RF_maintenance 0.52% 0.00% 0.00% 0.714955 0.605049 0.406404
5 1 digital_ok 0.52% 0.00% 0.00% 0.722995 0.617440 0.405349
7 2 digital_ok 0.52% 0.00% 0.00% 0.715628 0.612359 0.403310
8 2 RF_maintenance 1.56% 0.00% 0.00% 0.707572 0.589988 0.403534
9 2 digital_ok 2.08% 0.00% 0.00% 0.701905 0.603411 0.404723
10 2 digital_ok 2.08% 2.60% 0.00% 0.695242 0.575981 0.417389
15 1 digital_ok 0.52% 0.00% 0.00% 0.711121 0.601609 0.407147
16 1 digital_ok 0.52% 0.00% 0.00% 0.728425 0.626143 0.402592
17 1 digital_ok 0.52% 0.00% 0.00% 0.724713 0.626310 0.400674
18 1 RF_maintenance 2.60% 88.58% 0.00% 0.655328 0.321581 0.436193
19 2 digital_ok 0.52% 0.00% 0.00% 0.724940 0.620733 0.399815
20 2 digital_ok 2.08% 0.00% 0.00% 0.686362 0.599089 0.392547
21 2 digital_ok 4.67% 2.60% 0.00% 0.664783 0.580646 0.398726
27 1 RF_maintenance 100.00% 100.00% 0.00% 0.042379 0.045672 0.001534
28 1 RF_maintenance 50.16% 100.00% 0.00% 0.385700 0.114915 0.222268
29 1 digital_ok 0.52% 0.00% 0.00% 0.733564 0.625819 0.405953
30 1 digital_ok 0.52% 0.00% 0.00% 0.716528 0.607945 0.397187
31 2 digital_ok 0.52% 0.00% 0.00% 0.714595 0.585831 0.407528
32 2 RF_maintenance 7.79% 7.27% 0.00% 0.614882 0.570997 0.267142
33 2 RF_maintenance 1.04% 49.12% 0.00% 0.711295 0.416746 0.498268
36 3 RF_maintenance 0.00% 0.00% 0.00% 0.723334 0.603443 0.406085
37 3 digital_ok 96.88% 96.88% 0.00% 0.555163 0.549518 0.343087
38 3 RF_maintenance 96.88% 96.88% 0.00% 0.550468 0.551175 0.348843
40 4 digital_ok 100.00% 100.00% 0.00% 0.082863 0.103375 0.012868
41 4 digital_ok 100.00% 100.00% 0.00% 0.069144 0.089153 0.007584
42 4 digital_ok 100.00% 100.00% 0.00% 0.092594 0.102069 0.014481
45 5 RF_maintenance 0.52% 0.00% 0.00% 0.722715 0.587708 0.409885
46 5 digital_ok 0.52% 0.00% 0.00% 0.722767 0.611762 0.405386
50 3 digital_ok 0.00% 0.00% 0.00% 0.722660 0.580619 0.377562
51 3 digital_ok 0.00% 100.00% 0.00% 0.732796 0.056819 0.458292
52 3 RF_maintenance 0.00% 100.00% 0.00% 0.702656 0.044638 0.424339
53 3 digital_ok 0.00% 0.00% 0.00% 0.735166 0.634080 0.409398
54 4 digital_ok 100.00% 100.00% 0.00% 0.089742 0.087564 0.011518
55 4 digital_ok 100.00% 100.00% 0.00% 0.089639 0.077390 0.009491
56 4 digital_ok 100.00% 100.00% 0.00% 0.065683 0.077215 0.004889
57 4 digital_ok 100.00% 100.00% 0.00% 0.039336 0.098935 0.063713
65 3 digital_ok 0.00% 0.00% 0.00% 0.729206 0.628574 0.392845
66 3 digital_ok 0.00% 0.00% 0.00% 0.740387 0.640741 0.388329
67 3 RF_maintenance 0.00% 0.00% 0.00% 0.742580 0.570801 0.413255
68 3 digital_ok 96.88% 96.88% 0.00% 0.574440 0.570728 0.340720
69 4 digital_ok 100.00% 100.00% 0.00% 0.097797 0.097446 0.017841
70 4 RF_maintenance 100.00% 100.00% 0.00% 0.084229 0.078901 0.009423
71 4 digital_ok 100.00% 100.00% 0.00% 0.088819 0.084583 0.010708
72 4 digital_ok 100.00% 100.00% 0.00% 0.078671 0.086241 0.010189
73 5 RF_maintenance 0.00% 0.00% 0.00% 0.722934 0.584811 0.431240
81 7 digital_ok 0.00% 0.00% 0.00% 0.704976 0.633276 0.385896
82 7 RF_maintenance 0.00% 0.00% 0.00% 0.717212 0.633515 0.386443
83 7 digital_ok 80.27% 0.00% 0.00% 0.361016 0.661964 0.465022
84 8 digital_ok 0.00% 0.52% 0.00% 0.663269 0.575654 0.356224
85 8 RF_maintenance 100.00% 100.00% 0.00% 0.032357 0.031782 0.001234
86 8 RF_maintenance 100.00% 100.00% 0.00% 0.034186 0.032323 0.001816
87 8 RF_maintenance 4.15% 4.67% 0.00% 0.655516 0.548530 0.382627
88 9 digital_ok 100.00% 100.00% 0.00% 0.044807 0.045731 0.000350
90 9 RF_maintenance 6.75% 0.00% 0.00% 0.647542 0.631375 0.429651
92 10 digital_ok 66.77% 89.62% 0.00% 0.358945 0.323344 0.170486
93 10 RF_maintenance 70.92% 100.00% 0.00% 0.342329 0.043740 0.195669
94 10 RF_maintenance 2.08% 0.00% 0.00% 0.704064 0.590830 0.415239
98 7 digital_maintenance 0.00% 0.00% 0.00% 0.711855 0.565741 0.405191
99 7 digital_ok 0.00% 0.00% 0.00% 0.731200 0.630675 0.387311
100 7 RF_maintenance 0.00% 0.00% 0.00% 0.740971 0.658286 0.388457
101 8 digital_ok 0.00% 0.00% 0.00% 0.664420 0.583713 0.359777
102 8 RF_maintenance 100.00% 100.00% 0.00% 0.033295 0.032348 0.001582
103 8 digital_ok 0.00% 2.08% 0.00% 0.664478 0.576887 0.370032
104 8 RF_maintenance 11.94% 11.94% 88.06% 0.296430 0.283886 -0.232479
106 9 digital_ok 0.00% 0.00% 0.00% 0.730352 0.641996 0.411507
107 9 digital_ok 100.00% 100.00% 0.00% 0.042912 0.047618 0.005440
109 10 digital_ok 96.88% 96.88% 0.00% 0.560638 0.540346 0.353682
110 10 RF_maintenance 96.88% 96.88% 0.00% 0.489689 0.551589 0.343186
111 10 digital_ok 96.88% 96.88% 0.00% 0.544346 0.533390 0.347265
112 10 RF_maintenance 2.60% 0.00% 0.00% 0.701813 0.601283 0.410450
116 7 RF_maintenance 0.00% 0.00% 0.00% 0.688231 0.631263 0.391564
117 7 digital_ok 0.00% 0.00% 0.00% 0.731041 0.650292 0.394905
118 7 digital_ok 0.00% 0.00% 0.00% 0.735011 0.655293 0.390382
119 7 RF_maintenance 0.00% 0.00% 0.00% 0.745702 0.660547 0.393110
120 8 RF_maintenance 75.08% 100.00% 0.00% 0.361090 0.052475 0.263884
121 8 RF_maintenance 0.00% 2.08% 0.00% 0.668255 0.586899 0.360776
122 8 digital_ok 0.00% 2.08% 0.00% 0.665013 0.574796 0.367055
123 8 digital_ok 0.00% 2.08% 0.00% 0.664655 0.576157 0.367788
125 9 RF_maintenance 100.00% 100.00% 0.00% 0.030271 0.032531 0.002073
126 9 RF_maintenance 100.00% 100.00% 0.00% 0.036709 0.034993 0.000430
127 10 RF_maintenance 0.00% 0.00% 0.00% 0.717588 0.636058 0.403852
128 10 digital_ok 0.00% 0.00% 0.00% 0.724846 0.622880 0.402899
129 10 digital_ok 2.08% 0.00% 0.00% 0.711726 0.618201 0.405984
130 10 digital_maintenance 100.00% 89.62% 0.00% 0.052575 0.336772 0.176579
135 12 digital_ok 3.63% 3.63% 0.00% 0.708215 0.621204 0.396219
136 12 RF_maintenance 3.63% 3.63% 0.00% 0.716216 0.611167 0.387972
137 7 RF_maintenance 100.00% 100.00% 0.00% 0.069021 0.048900 0.018463
138 7 digital_ok 100.00% 0.00% 0.00% 0.053665 0.640461 0.430567
140 13 digital_ok 0.00% 0.00% 0.00% 0.736879 0.661484 0.388265
141 13 digital_ok 0.00% 57.42% 0.00% 0.729254 0.419487 0.467724
142 13 digital_ok 76.64% 100.00% 0.00% 0.355764 0.045988 0.197543
143 14 digital_ok 0.00% 0.00% 0.00% 0.734829 0.672347 0.389504
144 14 digital_ok 0.00% 0.00% 0.00% 0.682307 0.610315 0.394115
145 14 digital_ok 100.00% 100.00% 0.00% 0.034229 0.034897 0.000893
150 15 RF_maintenance 100.00% 100.00% 0.00% 0.057446 0.060390 0.001652
155 12 RF_maintenance 100.00% 100.00% 0.00% 0.047310 0.045801 0.001077
156 12 RF_maintenance 0.00% 0.00% 0.00% 0.716609 0.614906 0.400165
157 12 RF_maintenance 0.00% 0.00% 0.00% 0.718754 0.633269 0.398391
158 12 RF_maintenance 0.00% 0.00% 0.00% 0.711556 0.636226 0.397128
160 13 digital_ok 100.00% 100.00% 0.00% 0.050444 0.052196 0.002182
161 13 digital_ok 0.00% 3.63% 0.00% 0.737460 0.533305 0.386213
162 13 digital_ok 0.00% 0.00% 0.00% 0.736316 0.660232 0.391288
163 14 digital_ok 0.00% 0.00% 0.00% 0.735664 0.652630 0.386620
164 14 digital_ok 0.00% 0.00% 0.00% 0.736545 0.652951 0.389128
165 14 digital_ok 0.00% 0.00% 0.00% 0.740135 0.649088 0.387970
166 14 RF_maintenance 0.52% 0.00% 0.00% 0.679062 0.586766 0.342341
167 15 digital_ok 10.90% 3.63% 0.00% 0.581337 0.553628 0.311736
168 15 RF_maintenance 5.71% 3.63% 0.00% 0.708968 0.602881 0.393249
169 15 digital_ok 6.23% 4.15% 0.00% 0.697258 0.590693 0.399696
170 15 digital_ok 7.79% 6.23% 0.00% 0.683383 0.593301 0.403997
176 12 digital_ok 0.00% 0.00% 0.00% 0.710103 0.609392 0.407206
177 12 digital_ok 0.00% 0.00% 0.00% 0.714499 0.579608 0.415011
178 12 digital_ok 0.00% 0.00% 0.00% 0.720613 0.628689 0.404807
179 12 digital_ok 0.00% 0.00% 0.00% 0.722237 0.630757 0.407617
180 13 RF_maintenance 0.00% 100.00% 0.00% 0.733161 0.121642 0.506266
181 13 digital_ok 100.00% 100.00% 0.00% 0.053489 0.213827 0.106742
182 13 RF_maintenance 0.00% 44.13% 0.00% 0.724497 0.405156 0.411060
183 13 digital_ok 0.00% 0.00% 0.00% 0.734685 0.634369 0.400008
184 14 digital_ok 0.00% 0.00% 0.00% 0.728876 0.636052 0.386824
185 14 digital_ok 3.63% 3.63% 0.00% 0.745956 0.653914 0.384887
186 14 digital_ok 3.63% 3.63% 0.00% 0.715121 0.622031 0.381018
187 14 digital_ok 3.63% 3.63% 0.00% 0.712697 0.651313 0.386996
189 15 digital_ok 2.08% 0.00% 0.00% 0.701879 0.614694 0.401466
190 15 digital_ok 12.46% 100.00% 0.00% 0.564434 0.053801 0.400112
191 15 digital_ok 4.67% 3.12% 0.00% 0.692719 0.596252 0.416487
205 19 RF_ok 0.00% 0.00% 0.00% 0.710032 0.621801 0.385725
206 19 RF_ok 3.12% 0.00% 0.00% 0.655958 0.610563 0.394794
207 19 RF_ok 3.12% 0.00% 0.00% 0.682681 0.595786 0.381709
223 19 RF_ok 0.00% 0.00% 0.00% 0.708753 0.588251 0.403208
224 19 RF_ok 3.12% 2.60% 0.00% 0.669357 0.565875 0.385072
320 3 dish_maintenance 100.00% 100.00% 0.00% 0.074238 0.065973 -0.002675
321 2 not_connected 9.87% 28.04% 0.00% 0.631186 0.478845 0.396090
323 2 not_connected 34.58% 30.63% 0.00% 0.467236 0.458630 0.304436
324 4 not_connected 100.00% 100.00% 0.00% 0.100361 0.092837 0.038210
329 12 dish_maintenance 14.02% 28.56% 0.00% 0.569770 0.488283 0.370500
333 12 dish_maintenance 51.71% 31.15% 0.00% 0.374812 0.468538 0.314806
In [16]:
# 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] > .1 for col in bar_cols.values()])]
print('ex_ants: [' + ", ".join(str(ant) for ant in proposed_ex_ants) + ']')
ex_ants: [18, 27, 28, 33, 37, 38, 40, 41, 42, 51, 52, 54, 55, 56, 57, 68, 69, 70, 71, 72, 83, 85, 86, 88, 92, 93, 102, 104, 107, 109, 110, 111, 120, 125, 126, 130, 137, 138, 141, 142, 145, 150, 155, 160, 167, 180, 181, 182, 190, 320, 321, 323, 324, 329, 333]
In [17]:
# write to csv
outpath = os.path.join(nb_outdir, f'rtp_summary_table_{JD}.csv')
print(f'Now saving Table 1 to a csv at {outpath}')
df.to_csv(outpath)
Now saving Table 1 to a csv at /home/obs/src/H5C_Notebooks/_rtp_summary_/rtp_summary_table_2459774.csv
In [18]:
# 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 [19]:
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 [20]:
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 [21]:
from hera_qm import __version__
print(__version__)
from hera_cal import __version__
print(__version__)
2.0.2
3.1.1.dev2+g1b5039f
In [ ]: