class AntennaMetrics(): """Container for holding data and meta-data for ant metrics calculations. This class creates an object for holding relevant visibility data and metadata, and provides interfaces to four antenna metrics: two identify dead antennas, and two identify cross-polarized antennas. These metrics can be used iteratively to identify bad antennas. The object handles all stroage of metrics, and supports writing metrics to an HDF5 filetype. The analysis functions are designed to work on raw data from a single observation with all four polarizations. """ def __init__(self, dataFileList, reds, fileformat='miriad'): """Initilize an AntennaMetrics object. Parameters ---------- dataFileList : list of str List of data filenames of the four different visibility polarizations for the same observation. reds : list of tuples of ints List of lists of tuples of antenna numbers that make up redundant baseline groups. format : str, optional File type of data. Must be one of: 'miriad', 'uvh5', 'uvfits', 'fhd', 'ms' (see pyuvdata docs). Default is 'miriad'. Attributes ---------- hd : HERAData HERAData object generated from dataFileList. data : array Data contained in HERAData object. flags : array Flags contained in HERAData object. nsamples : array Nsamples contained in HERAData object. ants : list of ints List of antennas in HERAData object. pols : list of str List of polarizations in HERAData object. bls : list of ints List of baselines in HERAData object. dataFileList : list of str List of data filenames of the four different visibility polarizations for the same observation. reds : list of tuples of ints List of lists of tuples of antenna numbers that make up redundant baseline groups. version_str : str The version of the hera_qm module used to generate these metrics. history : str History to append to the metrics files when writing out files. """ from hera_cal.io import HERAData self.hd = HERAData(dataFileList, filetype=fileformat) self.data, self.flags, self.nsamples = self.hd.read() self.ants = self.hd.get_ants() self.pols = [pol.lower() for pol in self.hd.get_pols()] self.antpols = [antpol.lower() for antpol in self.hd.get_feedpols()] self.bls = self.hd.get_antpairs() self.dataFileList = dataFileList self.reds = reds self.version_str = hera_qm_version_str self.history = '' if len(self.antpols) != 2 or len(self.pols) != 4: raise ValueError('Missing polarization information. pols =' + str(self.pols) + ' and antpols = ' + str(self.antpols)) def mean_Vij_metrics(self, pols=None, xants=[], rawMetric=False): """Calculate how an antennas's average |Vij| deviates from others. Local wrapper for mean_Vij_metrics in hera_qm.ant_metrics module Parameters ---------- pols : list of str, optional List of visibility polarizations (e.g. ['xx','xy','yx','yy']). Default is self.pols. xants : list of tuples, optional List of antenna-polarization tuples that should be ignored. The expected format is (ant, antpol). Default is empty list. rawMetric : bool, optional If True, return the raw mean Vij metric instead of the modified z-score. Default is False. Returns ------- meanMetrics : dict Dictionary indexed by (ant, antpol) keys. Contains the modified z-score of the mean of the absolute value of all visibilities associated with an antenna. Very small or very large numbers are probably bad antennas. """ if pols is None: pols = self.pols return mean_Vij_metrics(self.data, pols, self.antpols, self.ants, self.bls, xants=xants, rawMetric=rawMetric) def red_corr_metrics(self, pols=None, xants=[], rawMetric=False, crossPol=False): """Calculate modified Z-Score over all redundant groups for each antenna. This method is a local wrapper for red_corr_metrics. It calculates the extent to which baselines involving an antenna do not correlate with others they are nominmally redundant with. Parameters ---------- data : array or HERAData Data for all polarizations, stored in a format that supports indexing as data[i,j,pol]. pols : list of str, optional List of visibility polarizations (e.g. ['xx','xy','yx','yy']). Default is self.pols. xants : list of tuples, optional List of antenna-polarization tuples that should be ignored. The expected format is (ant, antpol). Default is empty list. rawMetric : bool, optional If True, return the raw power correlations instead of the modified z-score. Default is False. crossPol : bool, optional If True, return results only when the two visibility polarizations differ by a single flip. Default is False. Returns ------- powerRedMetric : dict Dictionary indexed by (ant,antpol) keys. Contains the modified z-scores of the mean power correlations inside redundant baseline groups associated with each antenna. Very small numbers are probably bad antennas. """ if pols is None: pols = self.pols return red_corr_metrics(self.data, pols, self.antpols, self.ants, self.reds, xants=xants, rawMetric=rawMetric, crossPol=crossPol) def mean_Vij_cross_pol_metrics(self, xants=[], rawMetric=False): """Calculate the ratio of cross-pol visibilities to same-pol visibilities. This method is a local wrapper for mean_Vij_cross_pol_metrics. It finds which antennas are outliers based on the ratio of mean cross-pol visibilities to mean same-pol visibilities: (Vxy+Vyx)/(Vxx+Vyy). Parameters ---------- xants : list of tuples, optional List of antenna-polarization tuples that should be ignored. The expected format is (ant, antpol). Default is empty list. rawMetric : bool, optional If True, return the raw power correlations instead of the modified z-score. Default is False. Returns ------- mean_Vij_cross_pol_metrics : dict Dictionary indexed by (ant,antpol) keys. Contains the modified z-scores of the ratio of mean visibilities, (Vxy+Vyx)/(Vxx+Vyy). Results are duplicated in both antpols. Very large values are likely cross-polarized. """ return mean_Vij_cross_pol_metrics(self.data, self.pols, self.antpols, self.ants, self.bls, xants=xants, rawMetric=rawMetric) def red_corr_cross_pol_metrics(self, xants=[], rawMetric=False): """Calculate modified Z-Score over redundant groups; assume cross-polarized. This method is a local wrapper for red_corr_cross_pol_metrics. It finds which antennas are part of visibilities that are significantly better correlated with polarization-flipped visibilities in a redundant group. It returns the modified z-score. Parameters ---------- xants : list of tuples, optional List of antenna-polarization tuples that should be ignored. The expected format is (ant, antpol). Default is empty list. rawMetric : bool, optional If True, return the raw power correlations instead of the modified z-score. Default is False. Returns ------- redCorrCrossPolMetrics : dict Dictionary indexed by (ant,antpol) keys. Contains the modified z-scores of the mean correlation ratio between redundant visibilities and singly- polarization flipped ones. Very large values are probably cross-polarized. """ return red_corr_cross_pol_metrics(self.data, self.pols, self.antpols, self.ants, self.reds, xants=xants, rawMetric=rawMetric) def reset_summary_stats(self): """Reset all the internal summary statistics back to empty.""" self.xants, self.crossedAntsRemoved, self.deadAntsRemoved = [], [], [] self.iter = 0 self.removalIter = {} self.allMetrics, self.allModzScores = OrderedDict(), OrderedDict() self.finalMetrics, self.finalModzScores = {}, {} def find_totally_dead_ants(self): """Flag antennas whose median autoPower is 0.0. These antennas are marked as dead. They do not appear in recorded antenna metrics or zscores. Their removal iteration is -1 (i.e. before iterative flagging). """ autoPowers = compute_median_auto_power_dict(self.data, self.pols, self.reds) power_list_by_ant = {(ant, antpol): [] for ant in self.ants for antpol in self.antpols if (ant, antpol) not in self.xants} for ((ant0, ant1, pol), power) in autoPowers.items(): if ((ant0, pol[0]) not in self.xants and (ant1, pol[1]) not in self.xants): power_list_by_ant[(ant0, pol[0])].append(power) power_list_by_ant[(ant1, pol[1])].append(power) for (key, val) in power_list_by_ant.items(): if np.median(val) == 0: self.xants.append(key) self.deadAntsRemoved.append(key) self.removalIter[key] = -1 def _run_all_metrics(self, run_mean_vij=True, run_red_corr=True, run_cross_pols=True, run_cross_pols_only=False): """Local call for all metrics as part of iterative flagging method. Parameters ---------- run_mean_vij : bool, optional Define if mean_Vij_metrics or mean_Vij_cross_pol_metrics are executed. Default is True. run_red_corr : bool, optional Define if red_corr_metrics or red_corr_cross_pol_metrics are executed. Default is True. run_cross_pols : bool, optional Define if mean_Vij_cross_pol_metrics and red_corr_cross_pol_metrics are executed. Default is True. Individual rules are inherited from run_mean_vij and run_red_corr. run_cross_pols_only : bool, optional Define if cross pol metrics are the *only* metrics to be run. Default is False. """ # Compute all raw metrics metNames = [] metVals = [] if run_mean_vij and not run_cross_pols_only: metNames.append('meanVij') meanVij = self.mean_Vij_metrics(pols=self.pols, xants=self.xants, rawMetric=True) metVals.append(meanVij) if run_red_corr and not run_cross_pols_only: metNames.append('redCorr') pols = [pol for pol in self.pols if pol[0] == pol[1]] redCorr = self.red_corr_metrics(pols=pols, xants=self.xants, rawMetric=True) metVals.append(redCorr) if run_cross_pols: if run_mean_vij: metNames.append('meanVijXPol') meanVijXPol = self.mean_Vij_cross_pol_metrics(xants=self.xants, rawMetric=True) metVals.append(meanVijXPol) if run_red_corr: metNames.append('redCorrXPol') redCorrXPol = self.red_corr_cross_pol_metrics(xants=self.xants, rawMetric=True) metVals.append(redCorrXPol) # Save all metrics and zscores metrics, modzScores = {}, {} for metric, metName in zip(metVals, metNames): metrics[metName] = metric modz = per_antenna_modified_z_scores(metric) modzScores[metName] = modz for key in metric: if metName in self.finalMetrics: self.finalMetrics[metName][key] = metric[key] self.finalModzScores[metName][key] = modz[key] else: self.finalMetrics[metName] = {key: metric[key]} self.finalModzScores[metName] = {key: modz[key]} self.allMetrics.update({self.iter: metrics}) self.allModzScores.update({self.iter: modzScores}) def iterative_antenna_metrics_and_flagging(self, crossCut=5, deadCut=5, alwaysDeadCut=10, verbose=False, run_mean_vij=True, run_red_corr=True, run_cross_pols=True, run_cross_pols_only=False): """Run all four antenna metrics and stores results in self. Runs all four metrics: two for dead antennas, two for cross-polarized antennas. Saves the results internally to this this antenna metrics object. Parameters ---------- crossCut : float, optional Modified z-score cut for most cross-polarized antennas. Default is 5 "sigmas". deadCut : float, optional Modified z-score cut for most likely dead antennas. Default is 5 "sigmas". alwaysDeadCut : float, optional Modified z-score cut for definitely dead antennas. Default is 10 "sigmas". These are all thrown away at once without waiting to iteratively throw away only the worst offender. run_mean_vij : bool, optional Define if mean_Vij_metrics or mean_Vij_cross_pol_metrics are executed. Default is True. run_red_corr : bool, optional Define if red_corr_metrics or red_corr_cross_pol_metrics are executed. Default is True. run_cross_pols : bool, optional Define if mean_Vij_cross_pol_metrics and red_corr_cross_pol_metrics are executed. Default is True. Individual rules are inherited from run_mean_vij and run_red_corr. run_cross_pols_only : bool, optional Define if cross pol metrics are the *only* metrics to be run. Default is False. """ self.reset_summary_stats() self.find_totally_dead_ants() self.crossCut, self.deadCut = crossCut, deadCut self.alwaysDeadCut = alwaysDeadCut # Loop over for iter in range(len(self.antpols) * len(self.ants)): self.iter = iter self._run_all_metrics(run_mean_vij=run_mean_vij, run_red_corr=run_red_corr, run_cross_pols=run_cross_pols, run_cross_pols_only=run_cross_pols_only) # Mostly likely dead antenna last_iter = list(self.allModzScores)[-1] worstDeadCutRatio = -1 worstCrossCutRatio = -1 if run_mean_vij and run_red_corr and not run_cross_pols_only: deadMetrics = average_abs_metrics(self.allModzScores[last_iter]['meanVij'], self.allModzScores[last_iter]['redCorr']) else: if run_mean_vij and not run_cross_pols_only: deadMetrics = self.allModzScores[last_iter]['meanVij'].copy() elif run_red_corr and not run_cross_pols_only: deadMetrics = self.allModzScores[last_iter]['redCorr'].copy() try: worstDeadAnt = max(deadMetrics, key=deadMetrics.get) worstDeadCutRatio = np.abs(deadMetrics[worstDeadAnt]) / deadCut except NameError: # Dead metrics weren't run, but that's fine. pass if run_cross_pols: # Most likely cross-polarized antenna if run_mean_vij and run_red_corr: crossMetrics = average_abs_metrics(self.allModzScores[last_iter]['meanVijXPol'], self.allModzScores[last_iter]['redCorrXPol']) elif run_mean_vij: crossMetrics = self.allModzScores[last_iter]['meanVijXPol'].copy() elif run_red_corr: crossMetrics = self.allModzScores[last_iter]['redCorrXPol'].copy() worstCrossAnt = max(crossMetrics, key=crossMetrics.get) worstCrossCutRatio = (np.abs(crossMetrics[worstCrossAnt]) / crossCut) # Find the single worst antenna, remove it, log it, and run again if (worstCrossCutRatio >= worstDeadCutRatio and worstCrossCutRatio >= 1.0): for antpol in self.antpols: self.xants.append((worstCrossAnt[0], antpol)) self.crossedAntsRemoved.append((worstCrossAnt[0], antpol)) self.removalIter[(worstCrossAnt[0], antpol)] = iter if verbose: print('On iteration', iter, 'we flag\t', end='') print((worstCrossAnt[0], antpol)) elif (worstDeadCutRatio > worstCrossCutRatio and worstDeadCutRatio > 1.0): dead_ants = set([worstDeadAnt]) for (ant, metric) in deadMetrics.items(): if metric > alwaysDeadCut: dead_ants.add(ant) for dead_ant in dead_ants: self.xants.append(dead_ant) self.deadAntsRemoved.append(dead_ant) self.removalIter[dead_ant] = iter if verbose: print('On iteration', iter, 'we flag', dead_ant) else: break def save_antenna_metrics(self, filename, overwrite=False): """Output all meta-metrics and cut decisions to HDF5 file. Saves all cut decisions and meta-metrics in an HDF5 that can be loaded back into a dictionary using hera_qm.ant_metrics.load_antenna_metrics() Parameters ---------- filename : str The file into which metrics will be written. overwrite: bool, optional Whether to overwrite an existing file. Default is False. """ if not hasattr(self, 'xants'): raise KeyError(('Must run AntennaMetrics.' 'iterative_antenna_metrics_and_flagging() first.')) out_dict = {'xants': self.xants} out_dict['crossed_ants'] = self.crossedAntsRemoved out_dict['dead_ants'] = self.deadAntsRemoved out_dict['final_metrics'] = self.finalMetrics out_dict['all_metrics'] = self.allMetrics out_dict['final_mod_z_scores'] = self.finalModzScores out_dict['all_mod_z_scores'] = self.allModzScores out_dict['removal_iteration'] = self.removalIter out_dict['cross_pol_z_cut'] = self.crossCut out_dict['dead_ant_z_cut'] = self.deadCut out_dict['always_dead_ant_z_cut'] = self.alwaysDeadCut out_dict['datafile_list'] = self.dataFileList out_dict['reds'] = self.reds metrics_io.write_metric_file(filename, out_dict, overwrite=overwrite)
class AntennaMetrics(): """Container for holding data and meta-data for ant metrics calculations. Object for holding relevant visibility data and metadata interfaces to four antenna metrics: Two each for identifying dead or cross-polarized antennas. Can iteratively identifying bad antennas Handles all metrics stroage, and supports writing metrics to HDF5. Works on raw data from a single observation with all four polarizations. """ def __init__(self, dataFileList, reds, fileformat='miriad'): """Initilize an AntennaMetrics object. Arguments: dataFileList: List of data filenames of the four different visibility polarizations for the same observation reds: List of lists of tuples of antenna numbers that make up redundant baseline groups. format: File type of data Supports: 'miriad','uvfits', 'fhd', 'ms ' (see pyuvdata docs) Default: 'miriad'. """ from hera_cal.io import HERAData if fileformat == 'miriad': self.hd = HERAData(dataFileList, filetype='miriad') elif fileformat == 'uvfits': self.hd = HERAData(dataFileList, filetype='uvfits') elif fileformat == 'fhd': raise NotImplemented(str(fileformat) + 'not supported') else: raise ValueError('Unrecognized file format ' + str(fileformat)) self.data, self.flags, self.nsamples = self.hd.read() self.ants = self.hd.get_ants() self.pols = [pol.lower() for pol in self.hd.get_pols()] self.antpols = [antpol.lower() for antpol in self.hd.get_feedpols()] self.bls = self.hd.get_antpairs() self.dataFileList = dataFileList self.reds = reds self.version_str = hera_qm_version_str self.history = '' if len(self.antpols) is not 2 or len(self.pols) is not 4: raise ValueError('Missing polarization information. pols =' + str(self.pols) + ' and antpols = ' + str(self.antpols)) def mean_Vij_metrics(self, pols=None, xants=[], rawMetric=False): """Calculate how an antennas's average |Vij| deviates from others. Local wrapper for mean_Vij_metrics in hera_qm.ant_metrics module Arguments: pols : List of visibility polarizations (e.g. ['xx','xy','yx','yy']) Default: self.pols xants: List of antennas ithat should be ignored. format: (ant,antpol) rawMetric:return the raw mean Vij metric instead of the modified z-score Returns: meanMetrics: Dictionary indexed by (ant,antpol) of the modified z-score of the mean of the absolute value of all visibilities associated with an antenna. Very small or very large numbers are probably bad antennas. """ if pols is None: pols = self.pols return mean_Vij_metrics(self.data, pols, self.antpols, self.ants, self.bls, xants=xants, rawMetric=rawMetric) def red_corr_metrics(self, pols=None, xants=[], rawMetric=False, crossPol=False): """Calculate modified Z-Score over all redundant groups for each antenna. Local wrapper for red_corr_metrics in hera_qm.ant_metrics module. Calculates the extent to which baselines involving an antenna do not correlate with others they are nominmally redundant with. Arguments: data: data for all polarizations format must support data[i,j,pol] pols: List of visibility polarizations (e.g. ['xx','xy','yx','yy']). Default: self.pols xants: List of antennas that should be ignored. format: (ant, antpol) rawMetric: return the raw power correlations instead of the modified z-score crossPol: return results only when the two visibility polarizations differ by a single flip Returns: powerRedMetric: Dictionary indexed by (ant,antpol) of the modified z-scores of the mean power correlations inside redundant baseline groups associated with each antenna. Very small numbers are probably bad antennas. """ if pols is None: pols = self.pols return red_corr_metrics(self.data, pols, self.antpols, self.ants, self.reds, xants=xants, rawMetric=rawMetric, crossPol=crossPol) def mean_Vij_cross_pol_metrics(self, xants=[], rawMetric=False): """Calculate the ratio of cross-pol visibilities to same-pol visibilities. Local wrapper for mean_Vij_cross_pol_metrics. Find which antennas are outliers based on the ratio of mean cross-pol visibilities to mean same-pol visibilities: (Vxy+Vyx)/(Vxx+Vyy). Arguments: xants: List of antennas that should be ignored. format (ant,antpol) format e.g., if (81,'y') is excluded, (81,'x') cannot be identified as cross-polarized and will be excluded. rawMetric: return the raw power ratio instead of the modified z-score Returns: mean_Vij_cross_pol_metrics: Dictionary indexed by (ant,antpol) The modified z-scores of the ratio of mean visibilities, (Vxy+Vyx)/(Vxx+Vyy). Results duplicated in both antpols. Very large values are likely cross-polarized. """ return mean_Vij_cross_pol_metrics(self.data, self.pols, self.antpols, self.ants, self.bls, xants=xants, rawMetric=rawMetric) def red_corr_cross_pol_metrics(self, xants=[], rawMetric=False): """Calculate modified Z-Score over redundant groups; assume cross-polarized. Local wrapper for red_corr_cross_pol_metrics. Find which antennas are part of visibilities that are significantly better correlated with polarization-flipped visibilities in a redundant groupself. Returns the modified z-score. Arguments: xants: List of antennas that should be ignored. format (ant,antpol) format e.g., if (81,'y') is excluded, (81,'x') cannot be identified as cross-polarized and will be excluded. rawMetric: return the raw power ratio instead of the modified z-score type: Boolean Default: False Returns: redCorrCrossPolMetrics: Dictionary indexed by (ant,antpol) The modified z-scores of the mean correlation ratio between redundant visibilities and singlely-polarization flipped ones. Very large values are probably cross-polarized. """ return red_corr_cross_pol_metrics(self.data, self.pols, self.antpols, self.ants, self.reds, xants=xants, rawMetric=rawMetric) def reset_summary_stats(self): """Reset all the internal summary statistics back to empty.""" self.xants, self.crossedAntsRemoved, self.deadAntsRemoved = [], [], [] self.iter = 0 self.removalIter = {} self.allMetrics, self.allModzScores = OrderedDict(), OrderedDict() self.finalMetrics, self.finalModzScores = {}, {} def find_totally_dead_ants(self): """Flag antennas whose median autoPower is 0.0. These antennas are marked as dead They do not appear in recorded antenna metrics or zscores. Their removal iteration is -1 (i.e. before iterative flagging). """ autoPowers = compute_median_auto_power_dict(self.data, self.pols, self.reds) power_list_by_ant = {(ant, antpol): [] for ant in self.ants for antpol in self.antpols if (ant, antpol) not in self.xants} for ((ant0, ant1, pol), power) in autoPowers.items(): if ((ant0, pol[0]) not in self.xants and (ant1, pol[1]) not in self.xants): power_list_by_ant[(ant0, pol[0])].append(power) power_list_by_ant[(ant1, pol[1])].append(power) for (key, val) in power_list_by_ant.items(): if np.median(val) == 0: self.xants.append(key) self.deadAntsRemoved.append(key) self.removalIter[key] = -1 def _run_all_metrics(self, run_mean_vij=True, run_red_corr=True, run_cross_pols=True): """Local call for all metrics as part of iterative flagging method. Arguments: run_mean_vij: Boolean flag which determines if mean_Vij_metrics is executed. Default is True run_red_corr: Boolean flag which determines if red_corr_metrics is executed. Default is True run_cross_pols: Boolean flag which determines if mean_Vij_cross_pol_metrics and red_corr_cross_pol_metrics are executed. Default is True """ # Compute all raw metrics metNames = [] metVals = [] if run_mean_vij: metNames.append('meanVij') meanVij = self.mean_Vij_metrics(pols=self.pols, xants=self.xants, rawMetric=True) metVals.append(meanVij) if run_red_corr: metNames.append('redCorr') redCorr = self.red_corr_metrics(pols=['xx', 'yy'], xants=self.xants, rawMetric=True) metVals.append(redCorr) if run_cross_pols: metNames.append('meanVijXPol') metNames.append('redCorrXPol') meanVijXPol = self.mean_Vij_cross_pol_metrics(xants=self.xants, rawMetric=True) redCorrXPol = self.red_corr_cross_pol_metrics(xants=self.xants, rawMetric=True) metVals.append(meanVijXPol) metVals.append(redCorrXPol) # Save all metrics and zscores metrics, modzScores = {}, {} for metric, metName in zip(metVals, metNames): metrics[metName] = metric modz = per_antenna_modified_z_scores(metric) modzScores[metName] = modz for key in metric: if metName in self.finalMetrics: self.finalMetrics[metName][key] = metric[key] self.finalModzScores[metName][key] = modz[key] else: self.finalMetrics[metName] = {key: metric[key]} self.finalModzScores[metName] = {key: modz[key]} self.allMetrics.update({self.iter: metrics}) self.allModzScores.update({self.iter: modzScores}) def iterative_antenna_metrics_and_flagging(self, crossCut=5, deadCut=5, alwaysDeadCut=10, verbose=False, run_mean_vij=True, run_red_corr=True, run_cross_pols=True): """Run all four antenna metrics and stores results in self. Runs all four metrics: Two for dead antennas Two for cross-polarized antennas Saves the results internally to this this antenna metrics object. Arguments: crossCut: Modified z-score cut for most cross-polarized antennas. Default 5 "sigmas". deadCut: Modified z-score cut for most likely dead antennas. Default 5 "sigmas". alwaysDeadCut: Modified z-score cut for definitely dead antennas. Default 10 "sigmas". These are all thrown away at once without waiting to iteratively throw away only the worst offender. run_mean_vij: Boolean flag which determines if mean_Vij_metrics is executed. Default is True run_red_corr: Boolean flag which determines if red_corr_metrics is executed. Default is True run_cross_pols: Boolean flag which determines if mean_Vij_cross_pol_metrics and red_corr_cross_pol_metrics are executed. Default is True """ self.reset_summary_stats() self.find_totally_dead_ants() self.crossCut, self.deadCut = crossCut, deadCut self.alwaysDeadCut = alwaysDeadCut # Loop over for n in range(len(self.antpols) * len(self.ants)): self.iter = n self._run_all_metrics(run_mean_vij=run_mean_vij, run_red_corr=run_red_corr, run_cross_pols=run_cross_pols) # Mostly likely dead antenna last_iter = list(self.allModzScores)[-1] worstDeadCutRatio = None worstCrossCutRatio = None if run_mean_vij and run_red_corr: deadMetrics = average_abs_metrics(self.allModzScores[last_iter]['meanVij'], self.allModzScores[last_iter]['redCorr']) worstDeadAnt = max(deadMetrics, key=deadMetrics.get) worstDeadCutRatio = np.abs(deadMetrics[worstDeadAnt]) / deadCut else: if run_mean_vij: deadMetrics = self.allModzScores[last_iter]['meanVij'].copy() worstDeadAnt = max(deadMetrics, key=deadMetrics.get) worstDeadCutRatio = (np.abs(deadMetrics[worstDeadAnt]) / deadCut) elif run_red_corr: deadMetrics = self.allModzScores[last_iter]['redCorr'].copy() worstDeadAnt = max(deadMetrics, key=deadMetrics.get) worstDeadCutRatio = (np.abs(deadMetrics[worstDeadAnt]) / deadCut) if run_cross_pols: # Most likely cross-polarized antenna crossMetrics = average_abs_metrics(self.allModzScores[last_iter]['meanVijXPol'], self.allModzScores[last_iter]['redCorrXPol']) worstCrossAnt = max(crossMetrics, key=crossMetrics.get) worstCrossCutRatio = (np.abs(crossMetrics[worstCrossAnt]) / crossCut) # Find the single worst antenna, remove it, log it, and run again if (worstCrossCutRatio >= worstDeadCutRatio and worstCrossCutRatio >= 1.0): for antpol in self.antpols: self.xants.append((worstCrossAnt[0], antpol)) self.crossedAntsRemoved.append((worstCrossAnt[0], antpol)) self.removalIter[(worstCrossAnt[0], antpol)] = n if verbose: print('On iteration', n, 'we flag\t', end='') print((worstCrossAnt[0], antpol)) elif (worstDeadCutRatio > worstCrossCutRatio and worstDeadCutRatio > 1.0): dead_ants = set([worstDeadAnt]) for (ant, metric) in deadMetrics.items(): if metric > alwaysDeadCut: dead_ants.add(ant) for dead_ant in dead_ants: self.xants.append(dead_ant) self.deadAntsRemoved.append(dead_ant) self.removalIter[dead_ant] = n if verbose: print('On iteration', n, 'we flag', dead_ant) else: break def save_antenna_metrics(self, filename): """Output all meta-metrics and cut decisions to HDF5 file. Saves all cut decisions and meta-metrics in an HDF5 that can be loaded back into a dictionary using hera_qm.ant_metrics.load_antenna_metrics() Arguments: filename: The file into which metrics will be written. """ if not hasattr(self, 'xants'): raise KeyError(('Must run AntennaMetrics.' 'iterative_antenna_metrics_and_flagging() first.')) out_dict = {'xants': self.xants} out_dict['crossed_ants'] = self.crossedAntsRemoved out_dict['dead_ants'] = self.deadAntsRemoved out_dict['final_metrics'] = self.finalMetrics out_dict['all_metrics'] = self.allMetrics out_dict['final_mod_z_scores'] = self.finalModzScores out_dict['all_mod_z_scores'] = self.allModzScores out_dict['removal_iteration'] = self.removalIter out_dict['cross_pol_z_cut'] = self.crossCut out_dict['dead_ant_z_cut'] = self.deadCut out_dict['always_dead_ant_z_cut'] = self.alwaysDeadCut out_dict['datafile_list'] = self.dataFileList out_dict['reds'] = self.reds metrics_io.write_metric_file(filename, out_dict)