sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def get_user_by_username(self, username): """ Returns details for user of the given username. If there is more than one match will only return the first. Use get_users() for full result set. """ results = self.get_users(filter='username eq "%s"' % (username)) if...
Returns details for user of the given username. If there is more than one match will only return the first. Use get_users() for full result set.
entailment
def get_user_by_email(self, email): """ Returns details for user with the given email address. If there is more than one match will only return the first. Use get_users() for full result set. """ results = self.get_users(filter='email eq "%s"' % (email)) if resu...
Returns details for user with the given email address. If there is more than one match will only return the first. Use get_users() for full result set.
entailment
def get_user(self, id): """ Returns details about the user for the given id. Use get_user_by_email() or get_user_by_username() for help identifiying the id. """ self.assert_has_permission('scim.read') return self._get(self.uri + '/Users/%s' % (id))
Returns details about the user for the given id. Use get_user_by_email() or get_user_by_username() for help identifiying the id.
entailment
def create(self): """ Create an instance of the Time Series Service with the typical starting settings. """ self.service.create() predix.config.set_env_value(self.use_class, 'ingest_uri', self.get_ingest_uri()) predix.config.set_env_value(self.use...
Create an instance of the Time Series Service with the typical starting settings.
entailment
def grant_client(self, client_id, read=True, write=True): """ Grant the given client id all the scopes and authorities needed to work with the timeseries service. """ scopes = ['openid'] authorities = ['uaa.resource'] if write: for zone in self.servic...
Grant the given client id all the scopes and authorities needed to work with the timeseries service.
entailment
def get_query_uri(self): """ Return the uri used for queries on time series data. """ # Query URI has extra path we don't want so strip it off here query_uri = self.service.settings.data['query']['uri'] query_uri = urlparse(query_uri) return query_uri.scheme + ':/...
Return the uri used for queries on time series data.
entailment
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
entailment
def find_requirements(path): """ This method tries to determine the requirements of a particular project by inspecting the possible places that they could be defined. It will attempt, in order: 1) to parse setup.py in the root for an install_requires value 2) to read a requirements.txt file or...
This method tries to determine the requirements of a particular project by inspecting the possible places that they could be defined. It will attempt, in order: 1) to parse setup.py in the root for an install_requires value 2) to read a requirements.txt file or a requirements.pip in the root 3) to...
entailment
def get_app_guid(self, app_name): """ Returns the GUID for the app instance with the given name. """ summary = self.space.get_space_summary() for app in summary['apps']: if app['name'] == app_name: return app['guid']
Returns the GUID for the app instance with the given name.
entailment
def delete_app(self, app_name): """ Delete the given app. Will fail intentionally if there are any service bindings. You must delete those first. """ if app_name not in self.space.get_apps(): logging.warning("App not found so... succeeded?") retu...
Delete the given app. Will fail intentionally if there are any service bindings. You must delete those first.
entailment
def _get_service_config(self): """ Reads in config file of UAA credential information or generates one as a side-effect if not yet initialized. """ # Should work for windows, osx, and linux environments if not os.path.exists(self.config_path): try: ...
Reads in config file of UAA credential information or generates one as a side-effect if not yet initialized.
entailment
def _write_service_config(self): """ Will write the config out to disk. """ with open(self.config_path, 'w') as output: output.write(json.dumps(self.data, sort_keys=True, indent=4))
Will write the config out to disk.
entailment
def create(self, **kwargs): """ Create an instance of the Blob Store Service with the typical starting settings. """ self.service.create(**kwargs) predix.config.set_env_value(self.use_class, 'url', self.service.settings.data['url']) predix.config....
Create an instance of the Blob Store Service with the typical starting settings.
entailment
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
entailment
def subscribe(self): """ return a generator for all subscribe messages :return: None """ while self.run_subscribe_generator: if len(self._rx_messages) != 0: yield self._rx_messages.pop(0) return
return a generator for all subscribe messages :return: None
entailment
def send_acks(self, message): """ send acks to the service :param message: EventHub_pb2.Message :return: None """ if isinstance(message, EventHub_pb2.Message): ack = EventHub_pb2.Ack(partition=message.partition, offset=message.offset) self.grpc_man...
send acks to the service :param message: EventHub_pb2.Message :return: None
entailment
def _generate_subscribe_headers(self): """ generate the subscribe stub headers based on the supplied config :return: i """ headers =[] headers.append(('predix-zone-id', self.eventhub_client.zone_id)) token = self.eventhub_client.service._get_bearer_token() ...
generate the subscribe stub headers based on the supplied config :return: i
entailment
def _get_assets(self, bbox, size=None, page=None, asset_type=None, device_type=None, event_type=None, media_type=None): """ Returns the raw results of an asset search for a given bounding box. """ uri = self.uri + '/v1/assets/search' headers = self._get_header...
Returns the raw results of an asset search for a given bounding box.
entailment
def get_assets(self, bbox, **kwargs): """ Query the assets stored in the intelligent environment for a given bounding box and query. Assets can be filtered by type of asset, event, or media available. - device_type=['DATASIM'] - asset_type=['CAMERA'] ...
Query the assets stored in the intelligent environment for a given bounding box and query. Assets can be filtered by type of asset, event, or media available. - device_type=['DATASIM'] - asset_type=['CAMERA'] - event_type=['PKIN'] - media_type=['IMAGE'] ...
entailment
def _get_asset(self, asset_uid): """ Returns raw response for an given asset by its unique id. """ uri = self.uri + '/v2/assets/' + asset_uid headers = self._get_headers() return self.service._get(uri, headers=headers)
Returns raw response for an given asset by its unique id.
entailment
def label(self, input_grid): """ Label input grid with hysteresis method. Args: input_grid: 2D array of values. Returns: Labeled output grid. """ unset = 0 high_labels, num_labels = label(input_grid > self.high_thresh) region_rank...
Label input grid with hysteresis method. Args: input_grid: 2D array of values. Returns: Labeled output grid.
entailment
def size_filter(labeled_grid, min_size): """ Remove labeled objects that do not meet size threshold criteria. Args: labeled_grid: 2D output from label method. min_size: minimum size of object in pixels. Returns: labeled grid with smaller objects remo...
Remove labeled objects that do not meet size threshold criteria. Args: labeled_grid: 2D output from label method. min_size: minimum size of object in pixels. Returns: labeled grid with smaller objects removed.
entailment
def roc_curve(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Probability of False Detection", ylabel="Probability of Detection", title="ROC Curve", ticks=np.arange(0, 1.1, 0.1), dpi=300, legend_params=None, bootstrap_sets=None, ci=(2.5, 9...
Plots a set receiver/relative operating characteristic (ROC) curves from DistributedROC objects. The ROC curve shows how well a forecast discriminates between two outcomes over a series of thresholds. It features Probability of Detection (True Positive Rate) on the y-axis and Probability of False Detection ...
entailment
def performance_diagram(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Success Ratio (1-FAR)", ylabel="Probability of Detection", ticks=np.arange(0, 1.1, 0.1), dpi=300, csi_cmap="Blues", csi_label="...
Draws a performance diagram from a set of DistributedROC objects. A performance diagram is a variation on the ROC curve in which the Probability of False Detection on the x-axis has been replaced with the Success Ratio (1-False Alarm Ratio or Precision). The diagram also shows the Critical Success Index (C...
entailment
def reliability_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability", ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, inset_size=1.5, title="Reliability Diagram", legend_params=None, bootstra...
Plot reliability curves against a 1:1 diagonal to determine if probability forecasts are consistent with their observed relative frequency. Args: rel_objs (list): List of DistributedReliability objects. obj_labels (list): List of labels describing the forecast model associated with each curve. ...
entailment
def attributes_diagram(rel_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Forecast Probability", ylabel="Observed Relative Frequency", ticks=np.arange(0, 1.05, 0.05), dpi=300, title="Attributes Diagram", legend_params=None, inset_params=None, ...
Plot reliability curves against a 1:1 diagonal to determine if probability forecasts are consistent with their observed relative frequency. Also adds gray areas to show where the climatological probabilities lie and what areas result in a positive Brier Skill Score. Args: rel_objs (list): List of D...
entailment
def get_string(self, prompt, default_str=None) -> str: """Return a string value that the user enters. Raises exception for cancel.""" accept_event = threading.Event() value_ref = [None] def perform(): def accepted(text): value_ref[0] = text ac...
Return a string value that the user enters. Raises exception for cancel.
entailment
def __accept_reject(self, prompt, accepted_text, rejected_text, display_rejected): """Return a boolean value for accept/reject.""" accept_event = threading.Event() result_ref = [False] def perform(): def accepted(): result_ref[0] = True accept...
Return a boolean value for accept/reject.
entailment
def compute_weight(self, r, ytr=None, mask=None): """Returns the weight (w) using OLS of r * w = gp._ytr """ ytr = self._ytr if ytr is None else ytr mask = self._mask if mask is None else mask return compute_weight(r, ytr, mask)
Returns the weight (w) using OLS of r * w = gp._ytr
entailment
def isfinite(self): "Test whether the predicted values are finite" if self._multiple_outputs: if self.hy_test is not None: r = [(hy.isfinite() and (hyt is None or hyt.isfinite())) for hy, hyt in zip(self.hy, self.hy_test)] else: ...
Test whether the predicted values are finite
entailment
def value_of_named_argument_in_function(argument_name, function_name, search_str, resolve_varname=False): """ Parse an arbitrary block of python code to get the value of a named argument from inside a function call """ try: search_str = unicode(search_...
Parse an arbitrary block of python code to get the value of a named argument from inside a function call
entailment
def regex_in_file(regex, filepath, return_match=False): """ Search for a regex in a file If return_match is True, return the found object instead of a boolean """ file_content = get_file_content(filepath) re_method = funcy.re_find if return_match else funcy.re_test return re_method(regex, file_...
Search for a regex in a file If return_match is True, return the found object instead of a boolean
entailment
def regex_in_package_file(regex, filename, package_name, return_match=False): """ Search for a regex in a file contained within the package directory If return_match is True, return the found object instead of a boolean """ filepath = package_file_path(filename, package_name) return regex_in_file(r...
Search for a regex in a file contained within the package directory If return_match is True, return the found object instead of a boolean
entailment
def string_is_url(test_str): """ Test to see if a string is a URL or not, defined in this case as a string for which urlparse returns a scheme component >>> string_is_url('somestring') False >>> string_is_url('https://some.domain.org/path') True """ parsed = urlparse.urlparse(test_str) ...
Test to see if a string is a URL or not, defined in this case as a string for which urlparse returns a scheme component >>> string_is_url('somestring') False >>> string_is_url('https://some.domain.org/path') True
entailment
def item_transaction(self, item) -> Transaction: """Begin transaction state for item. A transaction state is exists to prevent writing out to disk, mainly for performance reasons. All changes to the object are delayed until the transaction state exits. This method is thread safe. ...
Begin transaction state for item. A transaction state is exists to prevent writing out to disk, mainly for performance reasons. All changes to the object are delayed until the transaction state exits. This method is thread safe.
entailment
def insert_data_item(self, before_index, data_item, auto_display: bool = True) -> None: """Insert a new data item into document model. This method is NOT threadsafe. """ assert data_item is not None assert data_item not in self.data_items assert before_index <= len(self....
Insert a new data item into document model. This method is NOT threadsafe.
entailment
def remove_data_item(self, data_item: DataItem.DataItem, *, safe: bool=False) -> typing.Optional[typing.Sequence]: """Remove data item from document model. This method is NOT threadsafe. """ # remove data item from any computations return self.__cascade_delete(data_item, safe=sa...
Remove data item from document model. This method is NOT threadsafe.
entailment
def __cascade_delete_inner(self, master_item, safe: bool=False) -> typing.Optional[typing.Sequence]: """Cascade delete an item. Returns an undelete log that can be used to undo the cascade deletion. Builds a cascade of items to be deleted and dependencies to be removed when the passed item is ...
Cascade delete an item. Returns an undelete log that can be used to undo the cascade deletion. Builds a cascade of items to be deleted and dependencies to be removed when the passed item is deleted. Then removes computations that are no longer valid. Removing a computation may result in more d...
entailment
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()))
Return the list of data items containing data that directly depends on data in this item.
entailment
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...
Return the list of data items containing data that directly depends on data in this item.
entailment
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_sour...
Return the list of data items containing data that directly depends on data in this item.
entailment
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.per...
Return a context object for a document-wide transaction.
entailment
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): ...
Return a context manager to put the data item in a 'live state'.
entailment
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_...
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.
entailment
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_dat...
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.
entailment
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 t...
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. This method is thread safe.
entailment
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 i...
Create a new data item with computation specified by processing_id, inputs, and region_list_map. The region_list_map associates a list of graphics corresponding to the required regions with a computation source (key).
entailment
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))...
Creates a color map for values in array :param array: color map to interpolate :param x: number of colors :return: interpolated color map
entailment
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...
star any gist by providing gistID or gistname(for authenticated user)
entailment
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...
fork any gist by providing gistID or gistname(for authenticated user)
entailment
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 ...
Check a gist if starred by providing gistID or gistname(for authenticated user)
entailment
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:`tempf...
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: (Opcional) Prefixo para o nome do ...
entailment
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_res...
Constrói uma :class:`RespostaExtrairLogs` a partir do retorno informado. :param unicode retorno: Retorno da função ``ExtrairLogs``.
entailment
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) ==...
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.
entailment
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: ...
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
entailment
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 con...
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 multi...
entailment
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 me...
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" or "forecast" ...
entailment
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...
Calculate a copula multivariate normal distribution from the training data for each group of ensemble members. Distributions are written to a pickle file for later use. Args: output_file: Pickle file model_names: Names of the tracking models label_columns: Names of th...
entailment
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 o...
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 machine learning model objects. input_columns: list of the names of the columns u...
entailment
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 threshol...
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 of machine learning model names model_objs: List of Scikit-learn ML models input_columns: List of input variables i...
entailment
def predict_condition_models(self, model_names, input_columns, metadata_cols, data_mode="forecast", ): """ Apply condition modelsto forecast data. Args: ...
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: Columns from input data that should be included in the data fra...
entailment
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 le...
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 objects input_columns: Training data columns used as input for ML model ...
entailment
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. ...
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 machine learning model names model_objs: List of machine learning model ob...
entailment
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 pre...
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_cols: Columns from input data that should be included in the data frame with the predictions. ...
entailment
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...
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 output_columns: Names of output columns metadata_cols: Columns from input data that should be in...
entailment
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 model...
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 variables output_column: Output variable name output_start: Hail size bin start ...
entailment
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: metada...
Apply size models to forecast data. Args: model_names: input_columns: metadata_cols: data_mode:
entailment
def fit_track_models(self, model_names, model_objs, input_columns, output_columns, output_ranges, ): """ Fit machine learning models to predict track erro...
Fit machine learning models to predict track error offsets. model_names: model_objs: input_columns: output_columns: output_ranges:
entailment
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 + \ ...
Save machine learning models to pickle files.
entailment
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...
Load models from pickle files.
entailment
def output_forecasts_json(self, forecasts, condition_model_names, size_model_names, dist_model_names, track_model_names, json_data_path, out...
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: :param out_path: :return:
entailment
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...
Output hail forecast values to csv files by run date and ensemble member. Args: forecasts: mode: csv_path: Returns:
entailment
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...
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.
entailment
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_cer...
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 tipo_certificado: Deverá s...
entailment
def comunicar_certificado_icpbrasil(self, certificado): """Função ``ComunicarCertificadoICPBRASIL`` conforme ER SAT, item 6.1.2. Envio do certificado criado pela ICP-Brasil. :param str certificado: Conteúdo do certificado digital criado pela autoridade certificadora ICP-Brasil. ...
Função ``ComunicarCertificadoICPBRASIL`` conforme ER SAT, item 6.1.2. Envio do certificado criado pela ICP-Brasil. :param str certificado: Conteúdo do certificado digital criado pela autoridade certificadora ICP-Brasil. :return: Retorna *verbatim* a resposta da função SAT. ...
entailment
def enviar_dados_venda(self, dados_venda): """Função ``EnviarDadosVenda`` conforme ER SAT, item 6.1.3. Envia o CF-e de venda para o equipamento SAT, que o enviará para autorização pela SEFAZ. :param dados_venda: Uma instância de :class:`~satcfe.entidades.CFeVenda` ou uma str...
Função ``EnviarDadosVenda`` conforme ER SAT, item 6.1.3. Envia o CF-e de venda para o equipamento SAT, que o enviará para autorização pela SEFAZ. :param dados_venda: Uma instância de :class:`~satcfe.entidades.CFeVenda` ou uma string contendo o XML do CF-e de venda. :return:...
entailment
def cancelar_ultima_venda(self, chave_cfe, dados_cancelamento): """Função ``CancelarUltimaVenda`` conforme ER SAT, item 6.1.4. Envia o CF-e de cancelamento para o equipamento SAT, que o enviará para autorização e cancelamento do CF-e pela SEFAZ. :param chave_cfe: String contendo a chave...
Função ``CancelarUltimaVenda`` conforme ER SAT, item 6.1.4. Envia o CF-e de cancelamento para o equipamento SAT, que o enviará para autorização e cancelamento do CF-e pela SEFAZ. :param chave_cfe: String contendo a chave do CF-e a ser cancelado, prefixada com o literal ``CFe``. ...
entailment
def consultar_numero_sessao(self, numero_sessao): """Função ``ConsultarNumeroSessao`` conforme ER SAT, item 6.1.8. Consulta o equipamento SAT por um número de sessão específico. :param int numero_sessao: Número da sessão que se quer consultar. :return: Retorna *verbatim* a resposta da ...
Função ``ConsultarNumeroSessao`` conforme ER SAT, item 6.1.8. Consulta o equipamento SAT por um número de sessão específico. :param int numero_sessao: Número da sessão que se quer consultar. :return: Retorna *verbatim* a resposta da função SAT. :rtype: string
entailment
def configurar_interface_de_rede(self, configuracao): """Função ``ConfigurarInterfaceDeRede`` conforme ER SAT, item 6.1.9. Configurção da interface de comunicação do equipamento SAT. :param configuracao: Instância de :class:`~satcfe.rede.ConfiguracaoRede` ou uma string contendo o XM...
Função ``ConfigurarInterfaceDeRede`` conforme ER SAT, item 6.1.9. Configurção da interface de comunicação do equipamento SAT. :param configuracao: Instância de :class:`~satcfe.rede.ConfiguracaoRede` ou uma string contendo o XML com as configurações de rede. :return: Retorna *verbat...
entailment
def associar_assinatura(self, sequencia_cnpj, assinatura_ac): """Função ``AssociarAssinatura`` conforme ER SAT, item 6.1.10. Associação da assinatura do aplicativo comercial. :param sequencia_cnpj: Sequência string de 28 dígitos composta do CNPJ do desenvolvedor da AC e do CNPJ do e...
Função ``AssociarAssinatura`` conforme ER SAT, item 6.1.10. Associação da assinatura do aplicativo comercial. :param sequencia_cnpj: Sequência string de 28 dígitos composta do CNPJ do desenvolvedor da AC e do CNPJ do estabelecimento comercial contribuinte, conforme ER SAT, item ...
entailment
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao, opcao=constantes.CODIGO_ATIVACAO_REGULAR, codigo_emergencia=None): """Função ``TrocarCodigoDeAtivacao`` conforme ER SAT, item 6.1.15. Troca do código de ativação do equipamento SAT. :param str novo_codigo_ativacao...
Função ``TrocarCodigoDeAtivacao`` conforme ER SAT, item 6.1.15. Troca do código de ativação do equipamento SAT. :param str novo_codigo_ativacao: O novo código de ativação escolhido pelo contribuinte. :param int opcao: Indica se deverá ser utilizado o código de ativação ...
entailment
def load_forecasts(self): """ Loads the forecast files and gathers the forecast information into pandas DataFrames. """ forecast_path = self.forecast_json_path + "/{0}/{1}/".format(self.run_date.strftime("%Y%m%d"), self...
Loads the forecast files and gathers the forecast information into pandas DataFrames.
entailment
def load_obs(self): """ Loads the track total and step files and merges the information into a single data frame. """ track_total_file = self.track_data_csv_path + \ "track_total_{0}_{1}_{2}.csv".format(self.ensemble_name, self...
Loads the track total and step files and merges the information into a single data frame.
entailment
def merge_obs(self): """ Match forecasts and observations. """ for model_type in self.model_types: self.matched_forecasts[model_type] = {} for model_name in self.model_names[model_type]: self.matched_forecasts[model_type][model_name] = pd.merge(sel...
Match forecasts and observations.
entailment
def crps(self, model_type, model_name, condition_model_name, condition_threshold, query=None): """ Calculates the cumulative ranked probability score (CRPS) on the forecast data. Args: model_type: model type being evaluated. model_name: machine learning model being evalu...
Calculates the cumulative ranked probability score (CRPS) on the forecast data. Args: model_type: model type being evaluated. model_name: machine learning model being evaluated. condition_model_name: Name of the hail/no-hail model being evaluated condition_thresh...
entailment
def roc(self, model_type, model_name, intensity_threshold, prob_thresholds, query=None): """ Calculates a ROC curve at a specified intensity threshold. Args: model_type: type of model being evaluated (e.g. size). model_name: machine learning model being evaluated ...
Calculates a ROC curve at a specified intensity threshold. Args: model_type: type of model being evaluated (e.g. size). model_name: machine learning model being evaluated intensity_threshold: forecast bin used as the split point for evaluation prob_thresholds: Ar...
entailment
def sample_forecast_max_hail(self, dist_model_name, condition_model_name, num_samples, condition_threshold=0.5, query=None): """ Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes. Hail sizes are sampled from ...
Samples every forecast hail object and returns an empirical distribution of possible maximum hail sizes. Hail sizes are sampled from each predicted gamma distribution. The total number of samples equals num_samples * area of the hail object. To get the maximum hail size for each realization, the maximu...
entailment
def get_params(self): """Get signature and params """ params = { 'key': self.get_app_key(), 'uid': self.user_id, 'widget': self.widget_code } products_number = len(self.products) if self.get_api_type() == self.API_GOODS: ...
Get signature and params
entailment
def hms(segundos): # TODO: mover para util.py """ Retorna o número de horas, minutos e segundos a partir do total de segundos informado. .. sourcecode:: python >>> hms(1) (0, 0, 1) >>> hms(60) (0, 1, 0) >>> hms(3600) (1, 0, 0) >>> hms(3601) ...
Retorna o número de horas, minutos e segundos a partir do total de segundos informado. .. sourcecode:: python >>> hms(1) (0, 0, 1) >>> hms(60) (0, 1, 0) >>> hms(3600) (1, 0, 0) >>> hms(3601) (1, 0, 1) >>> hms(3661) (1, 1, 1) ...
entailment
def hms_humanizado(segundos): # TODO: mover para util.py """ Retorna um texto legível que descreve o total de horas, minutos e segundos calculados a partir do total de segundos informados. .. sourcecode:: python >>> hms_humanizado(0) 'zero segundos' >>> hms_humanizado(1) ...
Retorna um texto legível que descreve o total de horas, minutos e segundos calculados a partir do total de segundos informados. .. sourcecode:: python >>> hms_humanizado(0) 'zero segundos' >>> hms_humanizado(1) '1 segundo' >>> hms_humanizado(2) '2 segundos' ...
entailment
def format_grib_name(self, selected_variable): """ Assigns name to grib2 message number with name 'unknown'. Names based on NOAA grib2 abbreviations. Args: selected_variable(str): name of selected variable for loading Names: 3: LCDC: Low Cloud Cover 4:...
Assigns name to grib2 message number with name 'unknown'. Names based on NOAA grib2 abbreviations. Args: selected_variable(str): name of selected variable for loading Names: 3: LCDC: Low Cloud Cover 4: MCDC: Medium Cloud Cover 5: HCDC: High Cloud Cover ...
entailment
def load_data(self): """ Loads data from grib2 file objects or list of grib2 file objects. Handles specific grib2 variable names and grib2 message numbers. Returns: Array of data loaded from files in (time, y, x) dimensions, Units """ file_...
Loads data from grib2 file objects or list of grib2 file objects. Handles specific grib2 variable names and grib2 message numbers. Returns: Array of data loaded from files in (time, y, x) dimensions, Units
entailment
def load_forecasts(self): """ Load the forecast files into memory. """ run_date_str = self.run_date.strftime("%Y%m%d") for model_name in self.model_names: self.raw_forecasts[model_name] = {} forecast_file = self.forecast_path + run_date_str + "/" + \ ...
Load the forecast files into memory.
entailment
def get_window_forecasts(self): """ Aggregate the forecasts within the specified time windows. """ for model_name in self.model_names: self.window_forecasts[model_name] = {} for size_threshold in self.size_thresholds: self.window_forecasts[model_na...
Aggregate the forecasts within the specified time windows.
entailment
def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). :param mask_threshold: Values greater than the threshold are kept, others are masked. :return: """ start_date = self.run_date + timedelta(hours=self.start_hour) end_date...
Loads observations and masking grid (if needed). :param mask_threshold: Values greater than the threshold are kept, others are masked. :return:
entailment
def dilate_obs(self, dilation_radius): """ Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: Number of times to dilate the grid. :return: """ for s in self.size_thresholds: self.dilated_obs[s...
Use a dilation filter to grow positive observation areas by a specified number of grid points :param dilation_radius: Number of times to dilate the grid. :return:
entailment
def roc_curves(self, prob_thresholds): """ Generate ROC Curve objects for each machine learning model, size threshold, and time window. :param prob_thresholds: Probability thresholds for the ROC Curve :param dilation_radius: Number of times to dilate the observation grid. :retur...
Generate ROC Curve objects for each machine learning model, size threshold, and time window. :param prob_thresholds: Probability thresholds for the ROC Curve :param dilation_radius: Number of times to dilate the observation grid. :return: a dictionary of DistributedROC objects.
entailment
def reliability_curves(self, prob_thresholds): """ Output reliability curves for each machine learning model, size threshold, and time window. :param prob_thresholds: :param dilation_radius: :return: """ all_rel_curves = {} for model_name in self.model_na...
Output reliability curves for each machine learning model, size threshold, and time window. :param prob_thresholds: :param dilation_radius: :return:
entailment
def load_map_coordinates(map_file): """ Loads map coordinates from netCDF or pickle file created by util.makeMapGrids. Args: map_file: Filename for the file containing coordinate information. Returns: Latitude and longitude grids as numpy arrays. """ if map_file[-4:] == ".pkl":...
Loads map coordinates from netCDF or pickle file created by util.makeMapGrids. Args: map_file: Filename for the file containing coordinate information. Returns: Latitude and longitude grids as numpy arrays.
entailment
def interpolate_mrms_day(start_date, variable, interp_type, mrms_path, map_filename, out_path): """ For a given day, this module interpolates hourly MRMS data to a specified latitude and longitude grid, and saves the interpolated grids to CF-compliant netCDF4 files. Args: start_date (datet...
For a given day, this module interpolates hourly MRMS data to a specified latitude and longitude grid, and saves the interpolated grids to CF-compliant netCDF4 files. Args: start_date (datetime.datetime): Date of data being interpolated variable (str): MRMS variable interp_type (st...
entailment