code
stringlengths
1
18.2k
of __remove_data_item that doesn't cascade again index = getattr(container, name).index(item) item_dict = item.write_to_dict() # NOTE: __remove_display_item will notify_remove_item undelete_log.extend(self.__remove_display_item(item, safe=safe)) undelete_log.append({"type": name, "index": index, "properties": item_dict...
notifications for data structures, computations, and display items here # since they're not handled elsewhere. if container == self and name in ("data_structures", "computations"): self.notify_remove_item(name, item, index) except Exception as e: import sys, traceback traceback.print_exc() traceback.format_exception(*s...
undelete_log
def get_dependent_items(self, item) -> typing.List: """Return the list of data items containing data that directly depends on data in this item.""" with self.__dependency_tree_lock: return copy.copy(self.__dependency_tree_source_to_target_map.get(weakref.ref(item), list()))
def __get_deep_dependent_item_set(self, item, item_set) -> None: """Return the list of data items containing data that directly depends on data in this item.""" if not item in item_set: item_set.add(item) with self.__dependency_tree_lock: for dependent in self.get_dependent_items(item): self.__get_deep_dependent_item_s...
def get_dependent_data_items(self, data_item: DataItem.DataItem) -> typing.List[DataItem.DataItem]: """Return the list of data items containing data that directly depends on data in this item.""" with self.__dependency_tree_lock: return [data_item for data_item in self.__dependency_tree_source_to_target_map.get(weakref...
def transaction_context(self): """Return a context object for a document-wide transaction.""" class DocumentModelTransaction: def __init__(self, document_model): self.__document_model = document_model def __enter__(self): self.__document_model.persistent_object_context.enter_write_delay(self.__document_model) return se...
def data_item_live(self, data_item): """ Return a context manager to put the data item in a 'live state'. """ class LiveContextManager: def __init__(self, manager, object): self.__manager = manager self.__object = object def __enter__(self): self.__manager.begin_data_item_live(self.__object) return self def __exit__(se...
def begin_data_item_live(self, data_item): """Begins a live state for the data item. The live state is propagated to dependent data items. This method is thread safe. See slow_test_dependent_data_item_removed_while_live_data_item_becomes_unlive. """ with self.__live_data_items_lock: old_live_count = self.__live_data_it...
def end_data_item_live(self, data_item): """Ends a live state for the data item. The live-ness property is propagated to dependent data items, similar to the transactions. This method is thread safe. """ with self.__live_data_items_lock: live_count = self.__live_data_items.get(data_item.uuid, 0) - 1 assert live_count >...
def __construct_data_item_reference(self, hardware_source: HardwareSource.HardwareSource, data_channel: HardwareSource.DataChannel): """Construct a data item reference. Construct a data item reference and assign a data item to it. Update data item session id and session metadata. Also connect the data channel processor...
a data item, create it. if data_item is None: data_item = DataItem.DataItem() data_item.ensure_data_source() data_item.title = "%s (%s)" % (hardware_source.display_name, data_channel.name) if data_channel.name else hardware_source.display_name data_item.category = "temporary" data_item_reference.data_item = data_item d...
ApplicationData.get_session_metadata_dict() if data_item.session_metadata != session_metadata: data_item.session_metadata = session_metadata if data_channel.processor: src_data_channel = hardware_source.data_channels[data_channel.src_channel_index] src_data_item_reference = self.get_data_item_reference(self.make_data_i...
def __make_computation(self, processing_id: str, inputs: typing.List[typing.Tuple[DisplayItem.DisplayItem, typing.Optional[Graphics.Graphic]]], region_list_map: typing.Mapping[str, typing.List[Graphics.Graphic]]=None, parameters: typing.Mapping[str, typing.Any]=None) -> DataItem.DataItem: """Create a new data item with...
process the sources in the description. match them to the inputs (which are data item/crop graphic tuples) src_dicts = processing_description.get("sources", list()) assert len(inputs) == len(src_dicts) src_names = list() src_texts = list() src_labels = list() regions = list() region_map = dict() for i, (src_dict, input...
return None # each source can have a list of requirements, check through them requirements = src_dict.get("requirements", list()) for requirement in requirements: requirement_type = requirement["type"] if requirement_type == "dimensionality": min_dimension = requirement.get("min") max_dimension = requirement.get("max")...
if not data_item.is_sequence: return None src_name = src_dict["name"] src_label = src_dict["label"] use_display_data = src_dict.get("use_display_data", True) xdata_property = "display_xdata" if use_display_data else "xdata" if src_dict.get("croppable"): xdata_property = "cropped_" + xdata_property elif src_dict.get("us...
= src_dict.get("regions", list()) src_region_list = region_list_map.get(src_name, list()) assert len(region_dict_list) == len(src_region_list) for region_dict, region in zip(region_dict_list, src_region_list): region_params = region_dict.get("params", dict()) region_type = region_dict["type"] region_name = region_dict[...
region_type == "line": if region: assert isinstance(region, Graphics.LineProfileGraphic) line_region = region else: line_region = Graphics.LineProfileGraphic() line_region.start = 0.25, 0.25 line_region.end = 0.75, 0.75 for k, v in region_params.items(): setattr(line_region, k, v) if display_item: display_item.add_grap...
for k, v in region_params.items(): setattr(rect_region, k, v) if display_item: display_item.add_graphic(rect_region) regions.append((region_name, rect_region, region_params.get("label"))) region_map[region_name] = rect_region elif region_type == "ellipse": if region: assert isinstance(region, Graphics.EllipseGraphic) e...
assert isinstance(region, Graphics.SpotGraphic) spot_region = region else: spot_region = Graphics.SpotGraphic() spot_region.center = 0.25, 0.75 spot_region.size = 0.1, 0.1 for k, v in region_params.items(): setattr(spot_region, k, v) if display_item: display_item.add_graphic(spot_region) regions.append((region_name, sp...
region_params.get("label"))) region_map[region_name] = interval_region elif region_type == "channel": if region: assert isinstance(region, Graphics.ChannelGraphic) channel_region = region else: channel_region = Graphics.ChannelGraphic() for k, v in region_params.items(): setattr(channel_region, k, v) if display_item: d...
Symbolic.xdata_expression(expression) assert script # construct the computation script = script.format(**dict(zip(src_names, src_texts))) computation = self.create_computation(script) computation.label = processing_description["title"] computation.processing_id = processing_id # process the data item inputs for src_dic...
regions: computation.create_object(region_name, self.get_object_specifier(region), label=region_label) # next process the parameters for param_dict in processing_description.get("parameters", list()): parameter_value = parameters.get(param_dict["name"], param_dict["value"]) computation.create_variable(param_dict["name"...
dict() for out_region_dict in processing_description.get("out_regions", list()): region_type = out_region_dict["type"] region_name = out_region_dict["name"] region_params = out_region_dict.get("params", dict()) if region_type == "interval": interval_region = Graphics.IntervalGraphic() for k, v in region_params.items():...
connection_dict.get("dst_prop") if connection_type == "property": if connection_src == "display_data_channel": # TODO: how to refer to the data_items? hardcode to data_item0 for now. display_item0 = self.get_display_item_for_data_item(data_item0) display_data_channel0 = display_item0.display_data_channel if display_ite...
# the bug is that setting the computation triggers the recompute to occur on a thread. # the recompute clones the data item and runs the operation. meanwhile this thread # updates the connection. now the recompute finishes and merges back the data item # which was cloned before the connection was established, effective...
the slice interval on the display. # the result is that the slice interval on the display would get set to the default # value of the graphic interval. so don't actually update the computation until after # everything is configured. permanent solution would be to improve the clone/merge to # only update data that had b...
changes to the data item and then apply them again to the original during merge. self.set_data_item_computation(new_data_item, computation) return new_data_item
def interpolate_colors(array: numpy.ndarray, x: int) -> numpy.ndarray: """ Creates a color map for values in array :param array: color map to interpolate :param x: number of colors :return: interpolated color map """ out_array = [] for i in range(x): if i % (x / (len(array) - 1)) == 0: index = i / (x / (len(array) - 1)...
(x / (len(array) - 1)))] stop_marker = array[math.ceil(i / (x / (len(array) - 1)))] interp_amount = i % (x / (len(array) - 1)) / (x / (len(array) - 1)) interp_color = numpy.rint(start_marker + ((stop_marker - start_marker) * interp_amount)) out_array.append(interp_color) out_array[-1] = array[-1] return numpy.array(out...
def star(self, **args): ''' star any gist by providing gistID or gistname(for authenticated user) ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Either provide authenticated user\'s Unambigious Gistname...
} return response raise Exception('Gist can\'t be starred')
def fork(self, **args): ''' fork any gist by providing gistID or gistname(for authenticated user) ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Either provide authenticated user\'s Unambigious Gistname...
'description': r.json()['description'], 'public': r.json()['public'], 'comments': r.json()['comments'] } return response raise Exception('Gist can\'t be forked')
def checkifstar(self, **args): ''' Check a gist if starred by providing gistID or gistname(for authenticated user) ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Either provide authenticated user\'s Una...
= { 'starred': 'True', 'id': self.gist_id } else: response = { 'starred': 'False' } return response
def salvar(self, destino=None, prefix='tmp', suffix='-sat.log'): """Salva o arquivo de log decodificado. :param str destino: (Opcional) Caminho completo para o arquivo onde os dados dos logs deverão ser salvos. Se não informado, será criado um arquivo temporário via :func:`tempfile.mkstemp`. :param str prefix: (Opciona...
Se não informado será usado ``"-sat.log"``. :return: Retorna o caminho completo para o arquivo salvo. :rtype: str :raises IOError: Se o destino for informado e o arquivo já existir. """ if destino: if os.path.exists(destino): raise IOError((errno.EEXIST, 'File exists', destino,)) destino = os.path.abspath(destino) fd =...
def analisar(retorno): """Constrói uma :class:`RespostaExtrairLogs` a partir do retorno informado. :param unicode retorno: Retorno da função ``ExtrairLogs``. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='ExtrairLogs', classe_resposta=RespostaExtrairLogs, campos=RespostaSAT.CAMPOS + ( ('arquivoLog', u...
def load_data_old(self): """ Loads time series of 2D data grids from each opened file. The code handles loading a full time series from one file or individual time steps from multiple files. Missing files are supported. """ units = "" if len(self.file_objects) == 1 and self.file_objects[0] is not None: data = self.file...
[len(self.file_objects), 1, 1] for file_object in self.file_objects: if file_object is not None: if self.variable in file_object.variables.keys(): grid_shape = file_object.variables[self.variable].shape elif self.variable.ljust(6, "_") in file_object.variables.keys(): grid_shape = file_object.variables[self.variable.lj...
self.variable.ljust(6, "_") else: print("{0} not found".format(self.variable)) raise KeyError data[f] = file_object.variables[var_name][0] if units == "" and hasattr(file_object.variables[var_name], "units"): units = file_object.variables[var_name].units else: data = None return data, units
def load_data(self): """ Load data from netCDF file objects or list of netCDF file objects. Handles special variable name formats. Returns: Array of data loaded from files in (time, y, x) dimensions, Units """ units = "" if self.file_objects[0] is None: raise IOError() var_name, z_index = self.format_var_name(self.vari...
is None: data = self.file_objects[0].variables[var_name][self.forecast_hours].astype(np.float32) else: data = self.file_objects[0].variables[var_name][self.forecast_hours, z_index].astype(np.float32) else: y_dim, x_dim = self.file_objects[0].variables[var_name].shape[-2:] data = np.zeros((len(self.valid_dates), y_dim, ...
def format_var_name(variable, var_list): """ Searches var list for variable name, checks other variable name format options. Args: variable (str): Variable being loaded var_list (list): List of variables in file. Returns: Name of variable in file containing relevant data, and index of variable z-level if multiple varia...
variable.ljust(6, "_") in var_list: var_name = variable.ljust(6, "_") elif any([variable in v_sub.split("_") for v_sub in var_list]): var_name = var_list[[variable in v_sub.split("_") for v_sub in var_list].index(True)] z_index = var_name.split("_").index(variable) else: raise KeyError("{0} not found in {1}".format(var...
def load_data(self, mode="train", format="csv"): """ Load data from flat data files containing total track information and information about each timestep. The two sets are combined using merge operations on the Track IDs. Additional member information is gathered from the appropriate member file. Args: mode: "train" o...
run_date_str = [d.strftime("%Y%m%d-%H%M") for d in run_dates.date] print(run_date_str) all_total_track_files = sorted(glob(getattr(self, mode + "_data_path") + "*total_" + self.ensemble_name + "*." + format)) all_step_track_files = sorted(glob(getattr(self, mode + "_data_path") + "*step_" + self.ensemble_name + "*." + ...
run_date_str: step_track_files.append(step_file) self.data[mode]["total"] = pd.concat(map(pd.read_csv, total_track_files), ignore_index=True) self.data[mode]["total"] = self.data[mode]["total"].fillna(value=0) self.data[mode]["total"] = self.data[mode]["total"].replace([np.inf, -np.inf], 0) self.data[mode]["step"] = pd...
def calc_copulas(self, output_file, model_names=("start-time", "translation-x", "translation-y"), label_columns=("Start_Time_Error", "Translation_Error_X", "Translation_Error_Y")): """ Calculate a copula multivariate normal distribution from the training data for each group of ensemble members. Distributions are writte...
self.data["train"]["member"][self.group_col].unique() copulas = {} label_columns = list(label_columns) for group in groups: print(group) group_data = self.data["train"]["total_group"].loc[ self.data["train"]["total_group"][self.group_col] == group] group_data = group_data.dropna() group_data.reset_index(drop=True, inpl...
def fit_condition_models(self, model_names, model_objs, input_columns, output_column="Matched", output_threshold=0.0): """ Fit machine learning models to predict whether or not hail will occur. Args: model_names: List of strings with the names for the particular machine learning models model_objs: scikit-learn style ma...
labeling whether or not the event occurs output_threshold: splitting threshold to determine if event has occurred. Default 0.0 """ print("Fitting condition models") groups = self.data["train"]["member"][self.group_col].unique() weights = None for group in groups: print(group) group_data = self.data["train"]["combo"].lo...
print("Ones: ", np.count_nonzero(output_data > 0), "Zeros: ", np.count_nonzero(output_data == 0)) self.condition_models[group] = {} for m, model_name in enumerate(model_names): print(model_name) self.condition_models[group][model_name] = deepcopy(model_objs[m]) try: self.condition_models[group][model_name].fit(group_da...
def fit_condition_threshold_models(self, model_names, model_objs, input_columns, output_column="Matched", output_threshold=0.5, num_folds=5, threshold_score="ets"): """ Fit models to predict hail/no-hail and use cross-validation to determine the probaility threshold that maximizes a skill score. Args: model_names: List...
events; below are nulls num_folds: Number of folds in the cross-validation procedure threshold_score: Score available in ContingencyTable used for determining the best probability threshold Returns: None """ print("Fitting condition models") groups = self.data["train"]["member"][self.group_col].unique() weights=None fo...
for (x, y) in conus_lat_lon_points]) min_dist, max_minus_min = min(distances),max(distances)-min(distances) distance_0_1 = [1.0-((d - min_dist)/(max_minus_min)) for d in distances] weights = np.array(distance_0_1) output_data = np.where(group_data.loc[:, output_column] > output_threshold, 1, 0) ones = np.count_nonzero(...
= KFold(n_splits=num_folds) for train_index, test_index in kf.split(group_data[input_columns].values): if np.count_nonzero(output_data[train_index]) > 0: try: self.condition_models[group][model_name].fit( group_data.iloc[train_index][input_columns], output_data[train_index],sample_weight=weights[train_index]) except: s...
roc.max_threshold_score(threshold_score) print(model_name + " condition threshold: {0:0.3f}".format( self.condition_models[group][model_name + "_condition_threshold"])) self.condition_models[group][model_name].fit(group_data[input_columns], output_data)
def predict_condition_models(self, model_names, input_columns, metadata_cols, data_mode="forecast", ): """ Apply condition modelsto forecast data. Args: model_names: List of names associated with each condition model used for prediction input_columns: List of columns in data used as input into the model metadata_cols: ...
"forecast" by default Returns: A dictionary of data frames containing probabilities of the event and specified metadata """ groups = self.condition_models.keys() predictions = pd.DataFrame(self.data[data_mode]["combo"][metadata_cols]) for group in groups: print(group) print(self.condition_models[group]) g_idxs = self.d...
+ "_conditionthresh"] = np.where(predictions.loc[g_idxs, mn + "_conditionprob"] >= self.condition_models[group][ model_name + "_condition_threshold"], 1, 0) return predictions
def fit_size_distribution_models(self, model_names, model_objs, input_columns, output_columns=None, calibrate=False): """ Fits multitask machine learning models to predict the parameters of a size distribution Args: model_names: List of machine learning model names model_objs: scikit-learn style machine learning model ...
from ML model """ if output_columns is None: output_columns = ["Shape", "Location", "Scale"] groups = np.unique(self.data["train"]["member"][self.group_col]) weights=None for group in groups: group_data = self.data["train"]["combo"].loc[self.data["train"]["combo"][self.group_col] == group] group_data = group_data.dropn...
[1.0-((d - min_dist)/(max_minus_min)) for d in distances] weights = np.array(distance_0_1) self.size_distribution_models[group] = {"multi": {}, "lognorm": {}} if calibrate: self.size_distribution_models[group]["calshape"] = {} self.size_distribution_models[group]["calscale"] = {} log_labels = np.log(group_data[output_c...
if calibrate: training_predictions = self.size_distribution_models[ group]["multi"][model_name].predict(group_data[input_columns]) self.size_distribution_models[group]["calshape"][model_name] = LinearRegression() self.size_distribution_models[group]["calshape"][model_name].fit(training_predictions[:, 0:1], (log_labels[...
def fit_size_distribution_component_models(self, model_names, model_objs, input_columns, output_columns): """ This calculates 2 principal components for the hail size distribution between the shape and scale parameters. Separate machine learning models are fit to predict each component. Args: model_names: List of machi...
= np.unique(self.data["train"]["member"][self.group_col]) weights=None for group in groups: print(group) group_data = self.data["train"]["combo"].loc[self.data["train"]["combo"][self.group_col] == group] group_data = group_data.dropna() group_data = group_data.loc[group_data[output_columns[-1]] > 0] if self.sector: lon...
{}} self.size_distribution_models[group]["lognorm"]["pca"] = PCA(n_components=len(output_columns)) log_labels = np.log(group_data[output_columns].values) log_labels[:, np.where(output_columns == "Shape")[0]] *= -1 log_means = log_labels.mean(axis=0) log_sds = log_labels.std(axis=0) log_norm_labels = (log_labels - log_m...
return
def predict_size_distribution_models(self, model_names, input_columns, metadata_cols, data_mode="forecast", location=6, calibrate=False): """ Make predictions using fitted size distribution models. Args: model_names: Name of the models for predictions input_columns: Data columns used for input into ML models metadata_c...
parameter calibrate: Whether or not to apply calibration model Returns: Predictions in dictionary of data frames grouped by group type """ groups = self.size_distribution_models.keys() predictions = {} for group in groups: group_data = self.data[data_mode]["combo"].loc[self.data[data_mode]["combo"][self.group_col] == g...
multi_predictions[:, 0:1]) multi_predictions[:, 1] = self.size_distribution_models[group]["calscale"][model_name].predict( multi_predictions[:, 1:]) multi_predictions = np.exp(multi_predictions * log_sd + log_mean) if multi_predictions.shape[1] == 2: multi_predictions_temp = np.zeros((multi_predictions.shape[0], 3)) mu...
def predict_size_distribution_component_models(self, model_names, input_columns, output_columns, metadata_cols, data_mode="forecast", location=6): """ Make predictions using fitted size distribution models. Args: model_names: Name of the models for predictions input_columns: Data columns used for input into ML models o...
location: Value of fixed location parameter Returns: Predictions in dictionary of data frames grouped by group type """ groups = self.size_distribution_models.keys() predictions = pd.DataFrame(self.data[data_mode]["combo"][metadata_cols]) for group in groups: group_idxs = self.data[data_mode]["combo"][self.group_col] =...
"pc_{0:d}".format(c)][model_name].predict(self.data[data_mode]["combo"].loc[group_idxs, input_columns]) log_norm_preds = self.size_distribution_models[group]["lognorm"]["pca"].inverse_transform(raw_preds) log_norm_preds[:, 0] *= -1 multi_predictions = np.exp(log_norm_preds * log_sd + log_mean) if multi_predictions.shap...
def fit_size_models(self, model_names, model_objs, input_columns, output_column="Hail_Size", output_start=5, output_step=5, output_stop=100): """ Fit size models to produce discrete pdfs of forecast hail sizes. Args: model_names: List of model names model_objs: List of model objects input_columns: List of input variabl...
= int(output_start) output_step = int(output_step) output_stop = int(output_stop) for group in groups: group_data = self.data["train"]["combo"].loc[self.data["train"]["combo"][self.group_col] == group] group_data.dropna(inplace=True) group_data = group_data[group_data[output_column] >= output_start] output_data = group...
self.size_models[group][model_name].fit(group_data[input_columns], discrete_data)
def predict_size_models(self, model_names, input_columns, metadata_cols, data_mode="forecast"): """ Apply size models to forecast data. Args: model_names: input_columns: metadata_cols: data_mode: """ groups = self.size_models.keys() predictions = {} for group in groups: group_data = self.data[data_mode]["combo"].loc[se...
= group_data[metadata_cols] pred_vals = self.size_models[group][model_name].predict_proba(group_data[input_columns]) pred_classes = self.size_models[group][model_name].classes_ pred_pdf = np.zeros((pred_vals.shape[0], output_values.size)) for pcv, pc in enumerate(pred_classes): idx = np.where(output_values == pc)[0][0]...
def fit_track_models(self, model_names, model_objs, input_columns, output_columns, output_ranges, ): """ Fit machine learning models to predict track error offsets. model_names: model_objs: input_columns: output_columns: output_ranges: """ print("Fitting track models") groups = self.data["train"]["member"][self.group_c...
> output_ranges[model_type][1]] = output_ranges[model_type][1] discrete_data = (output_data - output_ranges[model_type][0]) // output_ranges[model_type][2] * \ output_ranges[model_type][2] + output_ranges[model_type][0] model_dict[group]["outputvalues"] = np.arange(output_ranges[model_type][0], output_ranges[model_type...
def save_models(self, model_path): """ Save machine learning models to pickle files. """ for group, condition_model_set in self.condition_models.items(): for model_name, model_obj in condition_model_set.items(): out_filename = model_path + \ "{0}_{1}_condition.pkl".format(group, model_name.replace(" ", "-")) with open(...
pickle_file, pickle.HIGHEST_PROTOCOL) for group, dist_model_set in self.size_distribution_models.items(): for model_type, model_objs in dist_model_set.items(): for model_name, model_obj in model_objs.items(): out_filename = model_path + \ "{0}_{1}_{2}_sizedist.pkl".format(group, model_name.replace(" ", "-"), model_type...
pickle_file: pickle.dump(model_obj, pickle_file, pickle.HIGHEST_PROTOCOL) return
def load_models(self, model_path): """ Load models from pickle files. """ condition_model_files = sorted(glob(model_path + "*_condition.pkl")) if len(condition_model_files) > 0: for condition_model_file in condition_model_files: model_comps = condition_model_file.split("/")[-1][:-4].split("_") if model_comps[0] not in ...
> 0: for size_model_file in size_model_files: model_comps = size_model_file.split("/")[-1][:-4].split("_") if model_comps[0] not in self.size_models.keys(): self.size_models[model_comps[0]] = {} model_name = model_comps[1].replace("-", " ") with open(size_model_file, "rb") as smf: self.size_models[model_comps[0]][model...
model_comps[1].replace("-", " ") with open(dist_model_file, "rb") as dmf: self.size_distribution_models[model_comps[0]]["_".join(model_comps[2:-1])][ model_name] = pickle.load(dmf) track_model_files = sorted(glob(model_path + "*_track.pkl")) if len(track_model_files) > 0: for track_model_file in track_model_files: mode...
def output_forecasts_json(self, forecasts, condition_model_names, size_model_names, dist_model_names, track_model_names, json_data_path, out_path): """ Output forecast values to geoJSON file format. :param forecasts: :param condition_model_names: :param size_model_names: :param track_model_names: :param json_data_path:...
= {} for ml_model in condition_model_names: step_forecasts["condition_" + ml_model.replace(" ", "-")] = forecasts["condition"][group].loc[ forecasts["condition"][group]["Track_ID"] == track_id, ml_model] for ml_model in size_model_names: step_forecasts["size_" + ml_model.replace(" ", "-")] = forecasts["size"][group][ml...
mframe.loc[ mframe["Track_ID"] == track_id] json_file_name = "{0}_{1}_{2}_model_track_{3}.json".format(ensemble_name, run_date, member, track_num) full_json_path = json_data_path + "/".join([run_date, member]) + "/" + json_file_name with open(full_json_path) as json_file_obj: try: track_obj = json.load(json_file_obj) e...
in fdata.columns: if ml_model_name in col: predcols.append(col) feature['properties'][model_name] = fdata.loc[:, predcols].values[f].tolist() full_path = [] for part in [run_date, member]: full_path.append(part) if not os.access(out_path + "/".join(full_path), os.R_OK): try: os.mkdir(out_path + "/".join(full_path)) exc...
def output_forecasts_csv(self, forecasts, mode, csv_path, run_date_format="%Y%m%d-%H%M"): """ Output hail forecast values to csv files by run date and ensemble member. Args: forecasts: mode: csv_path: Returns: """ merged_forecasts = pd.merge(forecasts["condition"], forecasts["dist"], on=["Step_ID","Track_ID","Ensemble_...
member_forecast.to_csv(join(csv_path, "hail_forecasts_{0}_{1}_{2}.csv".format(self.ensemble_name, member, run_date.strftime (run_date_format)))) return
def _carregar(self): """Carrega (ou recarrega) a biblioteca SAT. Se a convenção de chamada ainda não tiver sido definida, será determinada pela extensão do arquivo da biblioteca. :raises ValueError: Se a convenção de chamada não puder ser determinada ou se não for um valor válido. """ if self._convencao is None: if sel...
= ctypes.CDLL elif self._convencao == constantes.WINDOWS_STDCALL: loader = ctypes.WinDLL else: raise ValueError('Convencao de chamada desconhecida: {!r}'.format( self._convencao)) self._libsat = loader(self._caminho)
def ativar_sat(self, tipo_certificado, cnpj, codigo_uf): """Função ``AtivarSAT`` conforme ER SAT, item 6.1.1. Ativação do equipamento SAT. Dependendo do tipo do certificado, o procedimento de ativação é complementado enviando-se o certificado emitido pela ICP-Brasil (:meth:`comunicar_certificado_icpbrasil`). :param int...
do CNPJ do estabelecimento contribuinte, contendo apenas os dígitos. Nenhuma validação do número do CNPJ será realizada antes que a função de ativação seja efetivamente invocada. :param int codigo_uf: Código da unidade federativa onde o equipamento SAT será ativado (eg. ``35`` para o Estado de São Paulo). Nenhuma valid...