sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def __clear_covers(self): """Clear all covered matrix cells""" for i in range(self.n): self.row_covered[i] = False self.col_covered[i] = False
Clear all covered matrix cells
entailment
def __erase_primes(self): """Erase all prime markings""" for i in range(self.n): for j in range(self.n): if self.marked[i][j] == 2: self.marked[i][j] = 0
Erase all prime markings
entailment
def update(self, a, b, c, d): """ Update contingency table with new values without creating a new object. """ self.table.ravel()[:] = [a, b, c, d] self.N = self.table.sum()
Update contingency table with new values without creating a new object.
entailment
def bias(self): """ Frequency Bias. Formula: (a+b)/(a+c)""" return (self.table[0, 0] + self.table[0, 1]) / (self.table[0, 0] + self.table[1, 0])
Frequency Bias. Formula: (a+b)/(a+c)
entailment
def csi(self): """Gilbert's Score or Threat Score or Critical Success Index a/(a+b+c)""" return self.table[0, 0] / (self.table[0, 0] + self.table[0, 1] + self.table[1, 0])
Gilbert's Score or Threat Score or Critical Success Index a/(a+b+c)
entailment
def ets(self): """Equitable Threat Score, Gilbert Skill Score, v, (a - R)/(a + b + c - R), R=(a+b)(a+c)/N""" r = (self.table[0, 0] + self.table[0, 1]) * (self.table[0, 0] + self.table[1, 0]) / self.N return (self.table[0, 0] - r) / (self.table[0, 0] + self.table[0, 1] + self.table[1, 0] - r)
Equitable Threat Score, Gilbert Skill Score, v, (a - R)/(a + b + c - R), R=(a+b)(a+c)/N
entailment
def hss(self): """Doolittle (Heidke) Skill Score. 2(ad-bc)/((a+b)(b+d) + (a+c)(c+d))""" return 2 * (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / ( (self.table[0, 0] + self.table[0, 1]) * (self.table[0, 1] + self.table[1, 1]) + (self.table[0, 0] + ...
Doolittle (Heidke) Skill Score. 2(ad-bc)/((a+b)(b+d) + (a+c)(c+d))
entailment
def pss(self): """Peirce (Hansen-Kuipers, True) Skill Score (ad - bc)/((a+c)(b+d))""" return (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / \ ((self.table[0, 0] + self.table[1, 0]) * (self.table[0, 1] + self.table[1, 1]))
Peirce (Hansen-Kuipers, True) Skill Score (ad - bc)/((a+c)(b+d))
entailment
def css(self): """Clayton Skill Score (ad - bc)/((a+b)(c+d))""" return (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / \ ((self.table[0, 0] + self.table[0, 1]) * (self.table[1, 0] + self.table[1, 1]))
Clayton Skill Score (ad - bc)/((a+b)(c+d))
entailment
def load_tree_object(filename): """ Load scikit-learn decision tree ensemble object from file. Parameters ---------- filename : str Name of the pickle file containing the tree object. Returns ------- tree ensemble object """ with open(filename) as file_obj: ...
Load scikit-learn decision tree ensemble object from file. Parameters ---------- filename : str Name of the pickle file containing the tree object. Returns ------- tree ensemble object
entailment
def output_tree_ensemble(tree_ensemble_obj, output_filename, attribute_names=None): """ Write each decision tree in an ensemble to a file. Parameters ---------- tree_ensemble_obj : sklearn.ensemble object Random Forest or Gradient Boosted Regression object output_filename : str ...
Write each decision tree in an ensemble to a file. Parameters ---------- tree_ensemble_obj : sklearn.ensemble object Random Forest or Gradient Boosted Regression object output_filename : str File where trees are written attribute_names : list List of attribute names to be us...
entailment
def print_tree_recursive(tree_obj, node_index, attribute_names=None): """ Recursively writes a string representation of a decision tree object. Parameters ---------- tree_obj : sklearn.tree._tree.Tree object A base decision tree object node_index : int Index of the node being pr...
Recursively writes a string representation of a decision tree object. Parameters ---------- tree_obj : sklearn.tree._tree.Tree object A base decision tree object node_index : int Index of the node being printed attribute_names : list List of attribute names Returns ...
entailment
def set_classifier_mask(self, v, base_mask=True): """Computes the mask used to create the training and validation set""" base = self._base v = tonparray(v) a = np.unique(v) if a[0] != -1 or a[1] != 1: raise RuntimeError("The labels must be -1 and 1 (%s)" % a) ...
Computes the mask used to create the training and validation set
entailment
def set_regression_mask(self, v): """Computes the mask used to create the training and validation set""" base = self._base index = np.arange(v.size()) np.random.shuffle(index) ones = np.ones(v.size()) ones[index[int(base._tr_fraction * v.size()):]] = 0 base._mask ...
Computes the mask used to create the training and validation set
entailment
def fitness(self, v): "Fitness function in the training set" base = self._base if base._classifier: if base._multiple_outputs: hy = SparseArray.argmax(v.hy) fit_func = base._fitness_function if fit_func == 'macro-F1' or fit_func == 'a_F...
Fitness function in the training set
entailment
def fitness_vs(self, v): """Fitness function in the validation set In classification it uses BER and RSE in regression""" base = self._base if base._classifier: if base._multiple_outputs: v.fitness_vs = v._error # if base._fitness_function == '...
Fitness function in the validation set In classification it uses BER and RSE in regression
entailment
def set_fitness(self, v): """Set the fitness to a new node. Returns false in case fitness is not finite""" base = self._base self.fitness(v) if not np.isfinite(v.fitness): self.del_error(v) return False if base._tr_fraction < 1: self.fi...
Set the fitness to a new node. Returns false in case fitness is not finite
entailment
def analisar(retorno): """Constrói uma :class:`RespostaCancelarUltimaVenda` a partir do retorno informado. :param unicode retorno: Retorno da função ``CancelarUltimaVenda``. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='EnviarDadosVenda', ...
Constrói uma :class:`RespostaCancelarUltimaVenda` a partir do retorno informado. :param unicode retorno: Retorno da função ``CancelarUltimaVenda``.
entailment
def convert_data_element_to_data_and_metadata_1(data_element) -> DataAndMetadata.DataAndMetadata: """Convert a data element to xdata. No data copying occurs. The data element can have the following keys: data (required) is_sequence, collection_dimension_count, datum_dimension_count (optional de...
Convert a data element to xdata. No data copying occurs. The data element can have the following keys: data (required) is_sequence, collection_dimension_count, datum_dimension_count (optional description of the data) spatial_calibrations (optional list of spatial calibration dicts, scale, o...
entailment
def output_sector_csv(self,csv_path,file_dict_key,out_path): """ Segment forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: csv_path(str): Path to the full CONUS csv file. file_dict_key(str): Dictionary ke...
Segment forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: csv_path(str): Path to the full CONUS csv file. file_dict_key(str): Dictionary key for the csv files, currently either 'track_step' or 'track_tot...
entailment
def output_sector_netcdf(self,netcdf_path,out_path,patch_radius,config): """ Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. ...
Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. out_path (str): Path to output new segmented netcdf files. patch_radius (int):...
entailment
def clean_dict(d0, clean_item_fn=None): """ Return a json-clean dict. Will log info message for failures. """ clean_item_fn = clean_item_fn if clean_item_fn else clean_item d = dict() for key in d0: cleaned_item = clean_item_fn(d0[key]) if cleaned_item is not None: ...
Return a json-clean dict. Will log info message for failures.
entailment
def clean_list(l0, clean_item_fn=None): """ Return a json-clean list. Will log info message for failures. """ clean_item_fn = clean_item_fn if clean_item_fn else clean_item l = list() for index, item in enumerate(l0): cleaned_item = clean_item_fn(item) l.append(cleaned_item) ...
Return a json-clean list. Will log info message for failures.
entailment
def clean_tuple(t0, clean_item_fn=None): """ Return a json-clean tuple. Will log info message for failures. """ clean_item_fn = clean_item_fn if clean_item_fn else clean_item l = list() for index, item in enumerate(t0): cleaned_item = clean_item_fn(item) l.append(cleaned_item...
Return a json-clean tuple. Will log info message for failures.
entailment
def clean_item(i): """ Return a json-clean item or None. Will log info message for failure. """ itype = type(i) if itype == dict: return clean_dict(i) elif itype == list: return clean_list(i) elif itype == tuple: return clean_tuple(i) elif itype == numpy.float...
Return a json-clean item or None. Will log info message for failure.
entailment
def clean_item_no_list(i): """ Return a json-clean item or None. Will log info message for failure. """ itype = type(i) if itype == dict: return clean_dict(i, clean_item_no_list) elif itype == list: return clean_tuple(i, clean_item_no_list) elif itype == tuple: re...
Return a json-clean item or None. Will log info message for failure.
entailment
def sample_stack_all(count=10, interval=0.1): """Sample the stack in a thread and print it at regular intervals.""" def print_stack_all(l, ll): l1 = list() l1.append("*** STACKTRACE - START ***") code = [] for threadId, stack in sys._current_frames().items(): sub_cod...
Sample the stack in a thread and print it at regular intervals.
entailment
def decision_function(self, X): "Decision function i.e. the raw data of the prediction" self._X = Model.convert_features(X) self._eval() return self._ind[0].hy
Decision function i.e. the raw data of the prediction
entailment
def _eval(self): "Evaluates a individual using recursion and self._pos as pointer" pos = self._pos self._pos += 1 node = self._ind[pos] if isinstance(node, Function): args = [self._eval() for x in range(node.nargs)] node.eval(args) for x in arg...
Evaluates a individual using recursion and self._pos as pointer
entailment
def create_random_ind_full(self, depth=0): "Random individual using full method" lst = [] self._create_random_ind_full(depth=depth, output=lst) return lst
Random individual using full method
entailment
def grow_use_function(self, depth=0): "Select either function or terminal in grow method" if depth == 0: return False if depth == self._depth: return True return np.random.random() < 0.5
Select either function or terminal in grow method
entailment
def create_random_ind_grow(self, depth=0): "Random individual using grow method" lst = [] self._depth = depth self._create_random_ind_grow(depth=depth, output=lst) return lst
Random individual using grow method
entailment
def create_population(self, popsize=1000, min_depth=2, max_depth=4, X=None): "Creates random population using ramped half-and-half method" import itertools args = [x for x in itertools.product(range(min_depth, ...
Creates random population using ramped half-and-half method
entailment
def decision_function(self, X, **kwargs): "Decision function i.e. the raw data of the prediction" if X is None: return self._hy_test X = self.convert_features(X) if len(X) < self.nvar: _ = 'Number of variables differ, trained with %s given %s' % (self.nvar, len(X)...
Decision function i.e. the raw data of the prediction
entailment
def fitness_vs(self): "Median Fitness in the validation set" l = [x.fitness_vs for x in self.models] return np.median(l)
Median Fitness in the validation set
entailment
def graphviz(self, directory, **kwargs): "Directory to store the graphviz models" import os if not os.path.isdir(directory): os.mkdir(directory) output = os.path.join(directory, 'evodag-%s') for k, m in enumerate(self.models): m.graphviz(output % k, **kwar...
Directory to store the graphviz models
entailment
def load_data(self, num_samples=1000, percentiles=None): """ Args: num_samples: Number of random samples at each grid point percentiles: Which percentiles to extract from the random samples Returns: """ self.percentiles = percentiles self.num_samp...
Args: num_samples: Number of random samples at each grid point percentiles: Which percentiles to extract from the random samples Returns:
entailment
def neighborhood_probability(self, threshold, radius): """ Calculate a probability based on the number of grid points in an area that exceed a threshold. Args: threshold: radius: Returns: """ weights = disk(radius, dtype=np.uint8) thresh...
Calculate a probability based on the number of grid points in an area that exceed a threshold. Args: threshold: radius: Returns:
entailment
def encode_grib2_percentile(self): """ Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages """ lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.in...
Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages
entailment
def encode_grib2_data(self): """ Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages """ lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32) ...
Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages
entailment
def load_data(self): """ Loads data from each ensemble member. """ for m, member in enumerate(self.members): mo = ModelOutput(self.ensemble_name, member, self.run_date, self.variable, self.start_date, self.end_date, self.path, self.map_file, self....
Loads data from each ensemble member.
entailment
def point_consensus(self, consensus_type): """ Calculate grid-point statistics across ensemble members. Args: consensus_type: mean, std, median, max, or percentile_nn Returns: EnsembleConsensus containing point statistic """ if "mean" in consensu...
Calculate grid-point statistics across ensemble members. Args: consensus_type: mean, std, median, max, or percentile_nn Returns: EnsembleConsensus containing point statistic
entailment
def point_probability(self, threshold): """ Determine the probability of exceeding a threshold at a grid point based on the ensemble forecasts at that point. Args: threshold: If >= threshold assigns a 1 to member, otherwise 0. Returns: EnsembleConsensus ...
Determine the probability of exceeding a threshold at a grid point based on the ensemble forecasts at that point. Args: threshold: If >= threshold assigns a 1 to member, otherwise 0. Returns: EnsembleConsensus
entailment
def neighborhood_probability(self, threshold, radius, sigmas=None): """ Hourly probability of exceeding a threshold based on model values within a specified radius of a point. Args: threshold (float): probability of exceeding this threshold radius (int): distance from po...
Hourly probability of exceeding a threshold based on model values within a specified radius of a point. Args: threshold (float): probability of exceeding this threshold radius (int): distance from point in number of grid points to include in neighborhood calculation. sigmas ...
entailment
def period_max_neighborhood_probability(self, threshold, radius, sigmas=None): """ Calculates the neighborhood probability of exceeding a threshold at any time over the period loaded. Args: threshold (float): splitting threshold for probability calculatations radius (int...
Calculates the neighborhood probability of exceeding a threshold at any time over the period loaded. Args: threshold (float): splitting threshold for probability calculatations radius (int): distance from point in number of grid points to include in neighborhood calculation. ...
entailment
def load_data(self, grid_method="gamma", num_samples=1000, condition_threshold=0.5, zero_inflate=False, percentile=None): """ Reads the track forecasts and converts them to grid point values based on random sampling. Args: grid_method: "gamma" by default ...
Reads the track forecasts and converts them to grid point values based on random sampling. Args: grid_method: "gamma" by default num_samples: Number of samples drawn from predicted pdf condition_threshold: Objects are not written to the grid if condition model probability is...
entailment
def write_grib2(self, path): """ Writes data to grib2 file. Currently, grib codes are set by hand to hail. Args: path: Path to directory containing grib2 files. Returns: """ if self.percentile is None: var_type = "mean" else: ...
Writes data to grib2 file. Currently, grib codes are set by hand to hail. Args: path: Path to directory containing grib2 files. Returns:
entailment
def init_file(self, filename, time_units="seconds since 1970-01-01T00:00"): """ Initializes netCDF file for writing Args: filename: Name of the netCDF file time_units: Units for the time variable in format "<time> since <date string>" Returns: Dataset...
Initializes netCDF file for writing Args: filename: Name of the netCDF file time_units: Units for the time variable in format "<time> since <date string>" Returns: Dataset object
entailment
def write_to_file(self, out_data): """ Outputs data to a netCDF file. If the file does not exist, it will be created. Otherwise, additional variables are appended to the current file Args: out_data: Full-path and name of output netCDF file """ full_var_name =...
Outputs data to a netCDF file. If the file does not exist, it will be created. Otherwise, additional variables are appended to the current file Args: out_data: Full-path and name of output netCDF file
entailment
def restore(self, workspace_uuid): """ Restore the workspace to the given workspace_uuid. If workspace_uuid is None then create a new workspace and use it. """ workspace = next((workspace for workspace in self.document_model.workspaces if workspace.uuid == workspace_uuid...
Restore the workspace to the given workspace_uuid. If workspace_uuid is None then create a new workspace and use it.
entailment
def new_workspace(self, name=None, layout=None, workspace_id=None, index=None) -> WorkspaceLayout.WorkspaceLayout: """ Create a new workspace, insert into document_model, and return it. """ workspace = WorkspaceLayout.WorkspaceLayout() self.document_model.insert_workspace(index if index is not N...
Create a new workspace, insert into document_model, and return it.
entailment
def ensure_workspace(self, name, layout, workspace_id): """Looks for a workspace with workspace_id. If none is found, create a new one, add it, and change to it. """ workspace = next((workspace for workspace in self.document_model.workspaces if workspace.workspace_id == workspace_id), N...
Looks for a workspace with workspace_id. If none is found, create a new one, add it, and change to it.
entailment
def create_workspace(self) -> None: """ Pose a dialog to name and create a workspace. """ def create_clicked(text): if text: command = Workspace.CreateWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(co...
Pose a dialog to name and create a workspace.
entailment
def rename_workspace(self) -> None: """ Pose a dialog to rename the workspace. """ def rename_clicked(text): if len(text) > 0: command = Workspace.RenameWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(...
Pose a dialog to rename the workspace.
entailment
def remove_workspace(self): """ Pose a dialog to confirm removal then remove workspace. """ def confirm_clicked(): if len(self.document_model.workspaces) > 1: command = Workspace.RemoveWorkspaceCommand(self) command.perform() self.document_con...
Pose a dialog to confirm removal then remove workspace.
entailment
def clone_workspace(self) -> None: """ Pose a dialog to name and clone a workspace. """ def clone_clicked(text): if text: command = Workspace.CloneWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(comman...
Pose a dialog to name and clone a workspace.
entailment
def __replace_displayed_display_item(self, display_panel, display_item, d=None) -> Undo.UndoableCommand: """ Used in drag/drop support. """ self.document_controller.replaced_display_panel_content = display_panel.save_contents() command = DisplayPanel.ReplaceDisplayPanelCommand(self) if d...
Used in drag/drop support.
entailment
def bootstrap(score_objs, n_boot=1000): """ Given a set of DistributedROC or DistributedReliability objects, this function performs a bootstrap resampling of the objects and returns n_boot aggregations of them. Args: score_objs: A list of DistributedROC or DistributedReliability objects. Object...
Given a set of DistributedROC or DistributedReliability objects, this function performs a bootstrap resampling of the objects and returns n_boot aggregations of them. Args: score_objs: A list of DistributedROC or DistributedReliability objects. Objects must have an __add__ method n_boot (int): ...
entailment
def update(self, forecasts, observations): """ Update the ROC curve with a set of forecasts and observations Args: forecasts: 1D array of forecast values observations: 1D array of observation values. """ for t, threshold in enumerate(self.thresholds): ...
Update the ROC curve with a set of forecasts and observations Args: forecasts: 1D array of forecast values observations: 1D array of observation values.
entailment
def merge(self, other_roc): """ Ingest the values of another DistributedROC object into this one and update the statistics inplace. Args: other_roc: another DistributedROC object. """ if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.threshold...
Ingest the values of another DistributedROC object into this one and update the statistics inplace. Args: other_roc: another DistributedROC object.
entailment
def roc_curve(self): """ Generate a ROC curve from the contingency table by calculating the probability of detection (TP/(TP+FN)) and the probability of false detection (FP/(FP+TN)). Returns: A pandas.DataFrame containing the POD, POFD, and the corresponding probability thre...
Generate a ROC curve from the contingency table by calculating the probability of detection (TP/(TP+FN)) and the probability of false detection (FP/(FP+TN)). Returns: A pandas.DataFrame containing the POD, POFD, and the corresponding probability thresholds.
entailment
def performance_curve(self): """ Calculate the Probability of Detection and False Alarm Ratio in order to output a performance diagram. Returns: pandas.DataFrame containing POD, FAR, and probability thresholds. """ pod = self.contingency_tables["TP"] / (self.continge...
Calculate the Probability of Detection and False Alarm Ratio in order to output a performance diagram. Returns: pandas.DataFrame containing POD, FAR, and probability thresholds.
entailment
def auc(self): """ Calculate the Area Under the ROC Curve (AUC). """ roc_curve = self.roc_curve() return np.abs(np.trapz(roc_curve['POD'], x=roc_curve['POFD']))
Calculate the Area Under the ROC Curve (AUC).
entailment
def max_csi(self): """ Calculate the maximum Critical Success Index across all probability thresholds Returns: The maximum CSI as a float """ csi = self.contingency_tables["TP"] / (self.contingency_tables["TP"] + self.contingency_tables["FN"] + ...
Calculate the maximum Critical Success Index across all probability thresholds Returns: The maximum CSI as a float
entailment
def get_contingency_tables(self): """ Create an Array of ContingencyTable objects for each probability threshold. Returns: Array of ContingencyTable objects """ return np.array([ContingencyTable(*ct) for ct in self.contingency_tables.values])
Create an Array of ContingencyTable objects for each probability threshold. Returns: Array of ContingencyTable objects
entailment
def from_str(self, in_str): """ Read the DistributedROC string and parse the contingency table values from it. Args: in_str (str): The string output from the __str__ method """ parts = in_str.split(";") for part in parts: var_name, value = part.sp...
Read the DistributedROC string and parse the contingency table values from it. Args: in_str (str): The string output from the __str__ method
entailment
def update(self, forecasts, observations): """ Update the statistics with a set of forecasts and observations. Args: forecasts (numpy.ndarray): Array of forecast probability values observations (numpy.ndarray): Array of observation values """ for t, thres...
Update the statistics with a set of forecasts and observations. Args: forecasts (numpy.ndarray): Array of forecast probability values observations (numpy.ndarray): Array of observation values
entailment
def merge(self, other_rel): """ Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability object. """ if other_rel.thresholds.size == self.thresholds.size and np.all(other_rel.thresholds == self.thres...
Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability object.
entailment
def reliability_curve(self): """ Calculates the reliability diagram statistics. The key columns are Bin_Start and Positive_Relative_Freq Returns: pandas.DataFrame """ total = self.frequencies["Total_Freq"].sum() curve = pd.DataFrame(columns=["Bin_Start", "Bin...
Calculates the reliability diagram statistics. The key columns are Bin_Start and Positive_Relative_Freq Returns: pandas.DataFrame
entailment
def brier_score_components(self): """ Calculate the components of the Brier score decomposition: reliability, resolution, and uncertainty. """ rel_curve = self.reliability_curve() total = self.frequencies["Total_Freq"].sum() climo_freq = float(self.frequencies["Positive_F...
Calculate the components of the Brier score decomposition: reliability, resolution, and uncertainty.
entailment
def brier_score(self): """ Calculate the Brier Score """ reliability, resolution, uncertainty = self.brier_score_components() return reliability - resolution + uncertainty
Calculate the Brier Score
entailment
def brier_skill_score(self): """ Calculate the Brier Skill Score """ reliability, resolution, uncertainty = self.brier_score_components() return (resolution - reliability) / uncertainty
Calculate the Brier Skill Score
entailment
def update(self, forecasts, observations): """ Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Functions of observations: """ if len(observations.shape) == 1: obs_cdfs = np.zeros((ob...
Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Functions of observations:
entailment
def crps(self): """ Calculates the continuous ranked probability score. """ return np.sum(self.errors["F_2"].values - self.errors["F_O"].values * 2.0 + self.errors["O_2"].values) / \ (self.thresholds.size * self.num_forecasts)
Calculates the continuous ranked probability score.
entailment
def crps_climo(self): """ Calculate the climatological CRPS. """ o_bar = self.errors["O"].values / float(self.num_forecasts) crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors["O"].values * 2.0 + self.errors["O_2"].values) / float(self...
Calculate the climatological CRPS.
entailment
def crpss(self): """ Calculate the continous ranked probability skill score from existing data. """ crps_f = self.crps() crps_c = self.crps_climo() return 1.0 - float(crps_f) / float(crps_c)
Calculate the continous ranked probability skill score from existing data.
entailment
def checar(cliente_sat): """ Checa em sequência os alertas registrados (veja :func:`registrar`) contra os dados da consulta ao status operacional do equipamento SAT. Este método irá então resultar em uma lista dos alertas ativos. :param cliente_sat: Uma instância de :class:`satcfe.clientelo...
Checa em sequência os alertas registrados (veja :func:`registrar`) contra os dados da consulta ao status operacional do equipamento SAT. Este método irá então resultar em uma lista dos alertas ativos. :param cliente_sat: Uma instância de :class:`satcfe.clientelocal.ClienteSATLocal` ou :clas...
entailment
def has_metadata_value(metadata_source, key: str) -> bool: """Return whether the metadata value for the given key exists. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If usi...
Return whether the metadata value for the given key exists. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, we recommend structuring your keys in the '<group...
entailment
def get_metadata_value(metadata_source, key: str) -> typing.Any: """Get the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom ...
Get the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, we recommend structuring your keys in the '<group>.<attribute>' for...
entailment
def set_metadata_value(metadata_source, key: str, value: typing.Any) -> None: """Set the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If us...
Set the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, we recommend structuring your keys in the '<group>.<attribute>' for...
entailment
def delete_metadata_value(metadata_source, key: str) -> None: """Delete the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom ...
Delete the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, we recommend structuring your keys in the '<dotted>.<group>.<att...
entailment
def calculate_y_ticks(self, plot_height): """Calculate the y-axis items dependent on the plot height.""" calibrated_data_min = self.calibrated_data_min calibrated_data_max = self.calibrated_data_max calibrated_data_range = calibrated_data_max - calibrated_data_min ticker = self...
Calculate the y-axis items dependent on the plot height.
entailment
def calculate_x_ticks(self, plot_width): """Calculate the x-axis items dependent on the plot width.""" x_calibration = self.x_calibration uncalibrated_data_left = self.__uncalibrated_left_channel uncalibrated_data_right = self.__uncalibrated_right_channel calibrated_data_left ...
Calculate the x-axis items dependent on the plot width.
entailment
def size_to_content(self): """ Size the canvas item to the proper height. """ new_sizing = self.copy_sizing() new_sizing.minimum_height = 0 new_sizing.maximum_height = 0 axes = self.__axes if axes and axes.is_valid: if axes.x_calibration and axes.x_calibration...
Size the canvas item to the proper height.
entailment
def size_to_content(self, get_font_metrics_fn): """ Size the canvas item to the proper width, the maximum of any label. """ new_sizing = self.copy_sizing() new_sizing.minimum_width = 0 new_sizing.maximum_width = 0 axes = self.__axes if axes and axes.is_valid: ...
Size the canvas item to the proper width, the maximum of any label.
entailment
def size_to_content(self): """ Size the canvas item to the proper width. """ new_sizing = self.copy_sizing() new_sizing.minimum_width = 0 new_sizing.maximum_width = 0 axes = self.__axes if axes and axes.is_valid: if axes.y_calibration and axes.y_calibration.un...
Size the canvas item to the proper width.
entailment
def get_snippet_content(snippet_name, **format_kwargs): """ Load the content from a snippet file which exists in SNIPPETS_ROOT """ filename = snippet_name + '.snippet' snippet_file = os.path.join(SNIPPETS_ROOT, filename) if not os.path.isfile(snippet_file): raise ValueError('could not find snipp...
Load the content from a snippet file which exists in SNIPPETS_ROOT
entailment
def update_display_properties(self, display_calibration_info, display_properties: typing.Mapping, display_layers: typing.Sequence[typing.Mapping]) -> None: """Update the display values. Called from display panel. This method saves the display values and data and triggers an update. It should be as fast...
Update the display values. Called from display panel. This method saves the display values and data and triggers an update. It should be as fast as possible. As a layer, this canvas item will respond to the update by calling prepare_render on the layer's rendering thread. Prepare render will c...
entailment
def __view_to_intervals(self, data_and_metadata: DataAndMetadata.DataAndMetadata, intervals: typing.List[typing.Tuple[float, float]]) -> None: """Change the view to encompass the channels and data represented by the given intervals.""" left = None right = None for interval in intervals: ...
Change the view to encompass the channels and data represented by the given intervals.
entailment
def __view_to_selected_graphics(self, data_and_metadata: DataAndMetadata.DataAndMetadata) -> None: """Change the view to encompass the selected graphic intervals.""" all_graphics = self.__graphics graphics = [graphic for graphic_index, graphic in enumerate(all_graphics) if self.__graphic_selecti...
Change the view to encompass the selected graphic intervals.
entailment
def prepare_display(self): """Prepare the display. This method gets called by the canvas layout/draw engine after being triggered by a call to `update`. When data or display parameters change, the internal state of the line plot gets updated. This method takes that internal state and u...
Prepare the display. This method gets called by the canvas layout/draw engine after being triggered by a call to `update`. When data or display parameters change, the internal state of the line plot gets updated. This method takes that internal state and updates the child canvas items. ...
entailment
def __update_cursor_info(self): """ Map the mouse to the 1-d position within the line graph. """ if not self.delegate: # allow display to work without delegate return if self.__mouse_in and self.__last_mouse: pos_1d = None axes = self.__axes lin...
Map the mouse to the 1-d position within the line graph.
entailment
def find_model_patch_tracks(self): """ Identify storms in gridded model output and extract uniform sized patches around the storm centers of mass. Returns: """ self.model_grid.load_data() tracked_model_objects = [] model_objects = [] if self.model_grid.d...
Identify storms in gridded model output and extract uniform sized patches around the storm centers of mass. Returns:
entailment
def find_model_tracks(self): """ Identify storms at each model time step and link them together with object matching. Returns: List of STObjects containing model track information. """ self.model_grid.load_data() model_objects = [] tracked_model_objec...
Identify storms at each model time step and link them together with object matching. Returns: List of STObjects containing model track information.
entailment
def find_mrms_tracks(self): """ Identify objects from MRMS timesteps and link them together with object matching. Returns: List of STObjects containing MESH track information. """ obs_objects = [] tracked_obs_objects = [] if self.mrms_ew is not None: ...
Identify objects from MRMS timesteps and link them together with object matching. Returns: List of STObjects containing MESH track information.
entailment
def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False): """ Match forecast and observed tracks. Args: model_tracks: obs_tracks: unique_matches: closest_matches: Returns: """ if unique...
Match forecast and observed tracks. Args: model_tracks: obs_tracks: unique_matches: closest_matches: Returns:
entailment
def extract_model_attributes(self, tracked_model_objects, storm_variables, potential_variables, tendency_variables=None, future_variables=None): """ Extract model attribute data for each model track. Storm variables are those that describe the model storm directl...
Extract model attribute data for each model track. Storm variables are those that describe the model storm directly, such as radar reflectivity or updraft helicity. Potential variables describe the surrounding environmental conditions of the storm, and should be extracted from the timestep before the st...
entailment
def match_hail_sizes(model_tracks, obs_tracks, track_pairings): """ Given forecast and observed track pairings, maximum hail sizes are associated with each paired forecast storm track timestep. If the duration of the forecast and observed tracks differ, then interpolation is used for the ...
Given forecast and observed track pairings, maximum hail sizes are associated with each paired forecast storm track timestep. If the duration of the forecast and observed tracks differ, then interpolation is used for the intermediate timesteps. Args: model_tracks: List of model trac...
entailment
def match_hail_size_step_distributions(self, model_tracks, obs_tracks, track_pairings): """ Given a matching set of observed tracks for each model track, Args: model_tracks: obs_tracks: track_pairings: Returns: """ label_...
Given a matching set of observed tracks for each model track, Args: model_tracks: obs_tracks: track_pairings: Returns:
entailment
def calc_track_errors(model_tracks, obs_tracks, track_pairings): """ Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects ...
Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects track_pairings: List of tuples pairing forecast and observed tracks. ...
entailment