sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def load_data(self): """ Loads data from MRMS GRIB2 files and handles compression duties if files are compressed. """ data = [] loaded_dates = [] loaded_indices = [] for t, timestamp in enumerate(self.all_dates): date_str = timestamp.date().strftime("%...
Loads data from MRMS GRIB2 files and handles compression duties if files are compressed.
entailment
def interpolate_grid(self, in_lon, in_lat): """ Interpolates MRMS data to a different grid using cubic bivariate splines """ out_data = np.zeros((self.data.shape[0], in_lon.shape[0], in_lon.shape[1])) for d in range(self.data.shape[0]): print("Loading ", d, self.varia...
Interpolates MRMS data to a different grid using cubic bivariate splines
entailment
def max_neighbor(self, in_lon, in_lat, radius=0.05): """ Finds the largest value within a given radius of a point on the interpolated grid. Args: in_lon: 2D array of longitude values in_lat: 2D array of latitude values radius: radius of influence for largest ...
Finds the largest value within a given radius of a point on the interpolated grid. Args: in_lon: 2D array of longitude values in_lat: 2D array of latitude values radius: radius of influence for largest neighbor search in degrees Returns: Array of interpo...
entailment
def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00", interp_type="spline"): """ Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create separate directories for each variab...
Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create separate directories for each variable if they are not already available.
entailment
def get_data_generator_by_id(hardware_source_id, sync=True): """ Return a generator for data. :param bool sync: whether to wait for current frame to finish then collect next frame NOTE: a new ndarray is created for each call. """ hardware_source = HardwareSourceManager().get_hardwa...
Return a generator for data. :param bool sync: whether to wait for current frame to finish then collect next frame NOTE: a new ndarray is created for each call.
entailment
def parse_hardware_aliases_config_file(config_path): """ Parse config file for aliases and automatically register them. Returns True if alias file was found and parsed (successfully or unsuccessfully). Returns False if alias file was not found. Config file is a standard .ini file ...
Parse config file for aliases and automatically register them. Returns True if alias file was found and parsed (successfully or unsuccessfully). Returns False if alias file was not found. Config file is a standard .ini file with a section
entailment
def make_instrument_alias(self, instrument_id, alias_instrument_id, display_name): """ Configure an alias. Callers can use the alias to refer to the instrument or hardware source. The alias should be lowercase, no spaces. The display name may be used to display alias to the ...
Configure an alias. Callers can use the alias to refer to the instrument or hardware source. The alias should be lowercase, no spaces. The display name may be used to display alias to the user. Neither the original instrument or hardware source id and the alias id should ever ...
entailment
def update(self, data_and_metadata: DataAndMetadata.DataAndMetadata, state: str, sub_area, view_id) -> None: """Called from hardware source when new data arrives.""" self.__state = state self.__sub_area = sub_area hardware_source_id = self.__hardware_source.hardware_source_id ch...
Called from hardware source when new data arrives.
entailment
def start(self): """Called from hardware source when data starts streaming.""" old_start_count = self.__start_count self.__start_count += 1 if old_start_count == 0: self.data_channel_start_event.fire()
Called from hardware source when data starts streaming.
entailment
def connect_data_item_reference(self, data_item_reference): """Connect to the data item reference, creating a crop graphic if necessary. If the data item reference does not yet have an associated data item, add a listener and wait for the data item to be set, then connect. """ d...
Connect to the data item reference, creating a crop graphic if necessary. If the data item reference does not yet have an associated data item, add a listener and wait for the data item to be set, then connect.
entailment
def grab_earliest(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the earliest data from the buffer, blocking until one is available.""" timeout = timeout if timeout is not None else 10.0 with self.__buffer_lock: if len(self.__buffer) == 0: ...
Grab the earliest data from the buffer, blocking until one is available.
entailment
def grab_next(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the next data to finish from the buffer, blocking until one is available.""" with self.__buffer_lock: self.__buffer = list() return self.grab_latest(timeout)
Grab the next data to finish from the buffer, blocking until one is available.
entailment
def grab_following(self, timeout: float=None) -> typing.List[DataAndMetadata.DataAndMetadata]: """Grab the next data to start from the buffer, blocking until one is available.""" self.grab_next(timeout) return self.grab_next(timeout)
Grab the next data to start from the buffer, blocking until one is available.
entailment
def pause(self) -> None: """Pause recording. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.started: self.__state = DataChannelBuffer.State.paused
Pause recording. Thread safe and UI safe.
entailment
def resume(self) -> None: """Resume recording after pause. Thread safe and UI safe.""" with self.__state_lock: if self.__state == DataChannelBuffer.State.paused: self.__state = DataChannelBuffer.State.started
Resume recording after pause. Thread safe and UI safe.
entailment
def nlargest(n, mapping): """ Takes a mapping and returns the n keys associated with the largest values in descending order. If the mapping has fewer than n items, all its keys are returned. Equivalent to: ``next(zip(*heapq.nlargest(mapping.items(), key=lambda x: x[1])))`` Returns ...
Takes a mapping and returns the n keys associated with the largest values in descending order. If the mapping has fewer than n items, all its keys are returned. Equivalent to: ``next(zip(*heapq.nlargest(mapping.items(), key=lambda x: x[1])))`` Returns ------- list of up to n keys from ...
entailment
def fromkeys(cls, iterable, value, **kwargs): """ Return a new pqict mapping keys from an iterable to the same value. """ return cls(((k, value) for k in iterable), **kwargs)
Return a new pqict mapping keys from an iterable to the same value.
entailment
def copy(self): """ Return a shallow copy of a pqdict. """ return self.__class__(self, key=self._keyfn, precedes=self._precedes)
Return a shallow copy of a pqdict.
entailment
def pop(self, key=__marker, default=__marker): """ If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` is not provided and ``key`` is not in the pqdict, raise a ``KeyError``. If ``key`` is not provided, remove the top ite...
If ``key`` is in the pqdict, remove it and return its priority value, else return ``default``. If ``default`` is not provided and ``key`` is not in the pqdict, raise a ``KeyError``. If ``key`` is not provided, remove the top item and return its key, or raise ``KeyError`` if the pqdict i...
entailment
def popitem(self): """ Remove and return the item with highest priority. Raises ``KeyError`` if pqdict is empty. """ heap = self._heap position = self._position try: end = heap.pop(-1) except IndexError: raise KeyError('pqdict is ...
Remove and return the item with highest priority. Raises ``KeyError`` if pqdict is empty.
entailment
def topitem(self): """ Return the item with highest priority. Raises ``KeyError`` if pqdict is empty. """ try: node = self._heap[0] except IndexError: raise KeyError('pqdict is empty') return node.key, node.value
Return the item with highest priority. Raises ``KeyError`` if pqdict is empty.
entailment
def additem(self, key, value): """ Add a new item. Raises ``KeyError`` if key is already in the pqdict. """ if key in self._position: raise KeyError('%s is already in the queue' % repr(key)) self[key] = value
Add a new item. Raises ``KeyError`` if key is already in the pqdict.
entailment
def pushpopitem(self, key, value, node_factory=_Node): """ Equivalent to inserting a new item followed by removing the top priority item, but faster. Raises ``KeyError`` if the new key is already in the pqdict. """ heap = self._heap position = self._position ...
Equivalent to inserting a new item followed by removing the top priority item, but faster. Raises ``KeyError`` if the new key is already in the pqdict.
entailment
def updateitem(self, key, new_val): """ Update the priority value of an existing item. Raises ``KeyError`` if key is not in the pqdict. """ if key not in self._position: raise KeyError(key) self[key] = new_val
Update the priority value of an existing item. Raises ``KeyError`` if key is not in the pqdict.
entailment
def replace_key(self, key, new_key): """ Replace the key of an existing heap node in place. Raises ``KeyError`` if the key to replace does not exist or if the new key is already in the pqdict. """ heap = self._heap position = self._position if new_key in ...
Replace the key of an existing heap node in place. Raises ``KeyError`` if the key to replace does not exist or if the new key is already in the pqdict.
entailment
def swap_priority(self, key1, key2): """ Fast way to swap the priority level of two items in the pqdict. Raises ``KeyError`` if either key does not exist. """ heap = self._heap position = self._position if key1 not in self or key2 not in self: raise K...
Fast way to swap the priority level of two items in the pqdict. Raises ``KeyError`` if either key does not exist.
entailment
def heapify(self, key=__marker): """ Repair a broken heap. If the state of an item's priority value changes you can re-sort the relevant item only by providing ``key``. """ if key is self.__marker: n = len(self._heap) for pos in reversed(range(n//2)): ...
Repair a broken heap. If the state of an item's priority value changes you can re-sort the relevant item only by providing ``key``.
entailment
def package_has_version_file(package_name): """ Check to make sure _version.py is contained in the package """ version_file_path = helpers.package_file_path('_version.py', package_name) return os.path.isfile(version_file_path)
Check to make sure _version.py is contained in the package
entailment
def get_project_name(): """ Grab the project name out of setup.py """ setup_py_content = helpers.get_file_content('setup.py') ret = helpers.value_of_named_argument_in_function( 'name', 'setup', setup_py_content, resolve_varname=True ) if ret and ret[0] == ret[-1] in ('"', "'"): ret =...
Grab the project name out of setup.py
entailment
def get_version(package_name, ignore_cache=False): """ Get the version which is currently configured by the package """ if ignore_cache: with microcache.temporarily_disabled(): found = helpers.regex_in_package_file( VERSION_SET_REGEX, '_version.py', package_name, return_match...
Get the version which is currently configured by the package
entailment
def set_version(package_name, version_str): """ Set the version in _version.py to version_str """ current_version = get_version(package_name) version_file_path = helpers.package_file_path('_version.py', package_name) version_file_content = helpers.get_file_content(version_file_path) version_file_con...
Set the version in _version.py to version_str
entailment
def version_is_valid(version_str): """ Check to see if the version specified is a valid as far as pkg_resources is concerned >>> version_is_valid('blah') False >>> version_is_valid('1.2.3') True """ try: packaging.version.Version(version_str) except packaging.version.InvalidVers...
Check to see if the version specified is a valid as far as pkg_resources is concerned >>> version_is_valid('blah') False >>> version_is_valid('1.2.3') True
entailment
def _get_uploaded_versions_warehouse(project_name, index_url, requests_verify=True): """ Query the pypi index at index_url using warehouse api to find all of the "releases" """ url = '/'.join((index_url, project_name, 'json')) response = requests.get(url, verify=requests_verify) if response.status_code ...
Query the pypi index at index_url using warehouse api to find all of the "releases"
entailment
def _get_uploaded_versions_pypicloud(project_name, index_url, requests_verify=True): """ Query the pypi index at index_url using pypicloud api to find all versions """ api_url = index_url for suffix in ('/pypi', '/pypi/', '/simple', '/simple/'): if api_url.endswith(suffix): api_url = api...
Query the pypi index at index_url using pypicloud api to find all versions
entailment
def version_already_uploaded(project_name, version_str, index_url, requests_verify=True): """ Check to see if the version specified has already been uploaded to the configured index """ all_versions = _get_uploaded_versions(project_name, index_url, requests_verify) return version_str in all_versions
Check to see if the version specified has already been uploaded to the configured index
entailment
def convert_readme_to_rst(): """ Attempt to convert a README.md file into README.rst """ project_files = os.listdir('.') for filename in project_files: if filename.lower() == 'readme': raise ProjectError( 'found {} in project directory...'.format(filename) + ...
Attempt to convert a README.md file into README.rst
entailment
def get_packaged_files(package_name): """ Collect relative paths to all files which have already been packaged """ if not os.path.isdir('dist'): return [] return [os.path.join('dist', filename) for filename in os.listdir('dist')]
Collect relative paths to all files which have already been packaged
entailment
def multiple_packaged_versions(package_name): """ Look through built package directory and see if there are multiple versions there """ dist_files = os.listdir('dist') versions = set() for filename in dist_files: version = funcy.re_find(r'{}-(.+).tar.gz'.format(package_name), filename) i...
Look through built package directory and see if there are multiple versions there
entailment
def period_neighborhood_probability(self, radius, smoothing, threshold, stride,start_time,end_time): """ Calculate the neighborhood probability over the full period of the forecast Args: radius: circular radius from each point in km smoothing: width of Gaussian smoother ...
Calculate the neighborhood probability over the full period of the forecast Args: radius: circular radius from each point in km smoothing: width of Gaussian smoother in km threshold: intensity of exceedance stride: number of grid points to skip for reduced neighb...
entailment
def analisar(retorno): """Constrói uma :class:`RespostaSAT` ou especialização dependendo da função SAT encontrada na sessão consultada. :param unicode retorno: Retorno da função ``ConsultarNumeroSessao``. """ if '|' not in retorno: raise ErroRespostaSATInvalida('Resp...
Constrói uma :class:`RespostaSAT` ou especialização dependendo da função SAT encontrada na sessão consultada. :param unicode retorno: Retorno da função ``ConsultarNumeroSessao``.
entailment
def analisar_retorno(retorno, classe_resposta=RespostaSAT, campos=RespostaSAT.CAMPOS, campos_alternativos=[], funcao=None, manter_verbatim=True): """Analisa o retorno (supostamente um retorno de uma função do SAT) conforme o padrão e campos esperados. O retorno deverá possuir dados separados ent...
Analisa o retorno (supostamente um retorno de uma função do SAT) conforme o padrão e campos esperados. O retorno deverá possuir dados separados entre si através de pipes e o número de campos deverá coincidir com os campos especificados. O campos devem ser especificados como uma tupla onde cada elemento...
entailment
def comunicar_certificado_icpbrasil(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='ComunicarCertificadoICPB...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`.
entailment
def consultar_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.consultar_sat`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='ConsultarSAT') if resposta.EEEEE not in ('08000',): ...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.consultar_sat`.
entailment
def configurar_interface_de_rede(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='ConfigurarInterfaceDeRede') ...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.configurar_interface_de_rede`.
entailment
def associar_assinatura(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.associar_assinatura`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='AssociarAssinatura') if resposta.EEEEE n...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.associar_assinatura`.
entailment
def atualizar_software_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='AtualizarSoftwareSAT') if resposta...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.atualizar_software_sat`.
entailment
def bloquear_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='BloquearSAT') if resposta.EEEEE not in ('16000',): ...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`.
entailment
def desbloquear_sat(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='DesbloquearSAT') if resposta.EEEEE not in ('1700...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.desbloquear_sat`.
entailment
def trocar_codigo_de_ativacao(retorno): """Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='TrocarCodigoDeAtivacao') if ...
Constrói uma :class:`RespostaSAT` para o retorno (unicode) da função :meth:`~satcfe.base.FuncoesSAT.trocar_codigo_de_ativacao`.
entailment
def load_data(self): """ Load the specified variable from the ensemble files, then close the files. """ if self.ensemble_name.upper() == "SSEF": if self.variable[0:2] == "rh": pressure_level = self.variable[2:] relh_vars = ["sph", "tmp"] ...
Load the specified variable from the ensemble files, then close the files.
entailment
def load_map_info(self, map_file): """ Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection. Args: map_file: File specifying the projection information. """ if self.ensemble_name.upper() == "SSEF": proj_d...
Load map projection information and create latitude, longitude, x, y, i, and j grids for the projection. Args: map_file: File specifying the projection information.
entailment
def read_geojson(filename): """ Reads a geojson file containing an STObject and initializes a new STObject from the information in the file. Args: filename: Name of the geojson file Returns: an STObject """ json_file = open(filename) data = json.load(json_file) json_fil...
Reads a geojson file containing an STObject and initializes a new STObject from the information in the file. Args: filename: Name of the geojson file Returns: an STObject
entailment
def center_of_mass(self, time): """ Calculate the center of mass at a given timestep. Args: time: Time at which the center of mass calculation is performed Returns: The x- and y-coordinates of the center of mass. """ if self.start_time <= time <=...
Calculate the center of mass at a given timestep. Args: time: Time at which the center of mass calculation is performed Returns: The x- and y-coordinates of the center of mass.
entailment
def trajectory(self): """ Calculates the center of mass for each time step and outputs an array Returns: """ traj = np.zeros((2, self.times.size)) for t, time in enumerate(self.times): traj[:, t] = self.center_of_mass(time) return traj
Calculates the center of mass for each time step and outputs an array Returns:
entailment
def get_corner(self, time): """ Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for the STObject. Args: time: time at which the corner is being extracted. Returns: corner inde...
Gets the corner array indices of the STObject at a given time that corresponds to the upper left corner of the bounding box for the STObject. Args: time: time at which the corner is being extracted. Returns: corner index.
entailment
def size(self, time): """ Gets the size of the object at a given time. Args: time: Time value being queried. Returns: size of the object in pixels """ if self.start_time <= time <= self.end_time: return self.masks[time - self.start_ti...
Gets the size of the object at a given time. Args: time: Time value being queried. Returns: size of the object in pixels
entailment
def max_size(self): """ Gets the largest size of the object over all timesteps. Returns: Maximum size of the object in pixels """ sizes = np.array([m.sum() for m in self.masks]) return sizes.max()
Gets the largest size of the object over all timesteps. Returns: Maximum size of the object in pixels
entailment
def max_intensity(self, time): """ Calculate the maximum intensity found at a timestep. """ ti = np.where(time == self.times)[0][0] return self.timesteps[ti].max()
Calculate the maximum intensity found at a timestep.
entailment
def extend(self, step): """ Adds the data from another STObject to this object. Args: step: another STObject being added after the current one in time. """ self.timesteps.extend(step.timesteps) self.masks.extend(step.masks) self.x.extend(step....
Adds the data from another STObject to this object. Args: step: another STObject being added after the current one in time.
entailment
def boundary_polygon(self, time): """ Get coordinates of object boundary in counter-clockwise order """ ti = np.where(time == self.times)[0][0] com_x, com_y = self.center_of_mass(time) # If at least one point along perimeter of the mask rectangle is unmasked, find_boundar...
Get coordinates of object boundary in counter-clockwise order
entailment
def estimate_motion(self, time, intensity_grid, max_u, max_v): """ Estimate the motion of the object with cross-correlation on the intensity values from the previous time step. Args: time: time being evaluated. intensity_grid: 2D array of intensities used in cross correl...
Estimate the motion of the object with cross-correlation on the intensity values from the previous time step. Args: time: time being evaluated. intensity_grid: 2D array of intensities used in cross correlation. max_u: Maximum x-component of motion. Used to limit search area....
entailment
def count_overlap(self, time, other_object, other_time): """ Counts the number of points that overlap between this STObject and another STObject. Used for tracking. """ ti = np.where(time == self.times)[0][0] ma = np.where(self.masks[ti].ravel() == 1) oti = np.where(other...
Counts the number of points that overlap between this STObject and another STObject. Used for tracking.
entailment
def extract_attribute_grid(self, model_grid, potential=False, future=False): """ Extracts the data from a ModelOutput or ModelGrid object within the bounding box region of the STObject. Args: model_grid: A ModelGrid or ModelOutput Object potential: Extracts from ...
Extracts the data from a ModelOutput or ModelGrid object within the bounding box region of the STObject. Args: model_grid: A ModelGrid or ModelOutput Object potential: Extracts from the time before instead of the same time as the object
entailment
def extract_attribute_array(self, data_array, var_name): """ Extracts data from a 2D array that has the same dimensions as the grid used to identify the object. Args: data_array: 2D numpy array """ if var_name not in self.attributes.keys(): self.attribut...
Extracts data from a 2D array that has the same dimensions as the grid used to identify the object. Args: data_array: 2D numpy array
entailment
def extract_tendency_grid(self, model_grid): """ Extracts the difference in model outputs Args: model_grid: ModelOutput or ModelGrid object. """ var_name = model_grid.variable + "-tendency" self.attributes[var_name] = [] timesteps = np.arange(self.st...
Extracts the difference in model outputs Args: model_grid: ModelOutput or ModelGrid object.
entailment
def calc_attribute_statistics(self, statistic_name): """ Calculates summary statistics over the domains of each attribute. Args: statistic_name (string): numpy statistic, such as mean, std, max, min Returns: dict of statistics from each attribute grid. ...
Calculates summary statistics over the domains of each attribute. Args: statistic_name (string): numpy statistic, such as mean, std, max, min Returns: dict of statistics from each attribute grid.
entailment
def calc_attribute_statistic(self, attribute, statistic, time): """ Calculate statistics based on the values of an attribute. The following statistics are supported: mean, max, min, std, ptp (range), median, skew (mean - median), and percentile_(percentile value). Args: attr...
Calculate statistics based on the values of an attribute. The following statistics are supported: mean, max, min, std, ptp (range), median, skew (mean - median), and percentile_(percentile value). Args: attribute: Attribute extracted from model grid statistic: Name of statistic ...
entailment
def calc_timestep_statistic(self, statistic, time): """ Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calculated time: Timestep being investigated Returns: Value of the statistic """ ...
Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calculated time: Timestep being investigated Returns: Value of the statistic
entailment
def calc_shape_statistics(self, stat_names): """ Calculate shape statistics using regionprops applied to the object mask. Args: stat_names: List of statistics to be extracted from those calculated by regionprops. Returns: Dictionary of shape statistics ...
Calculate shape statistics using regionprops applied to the object mask. Args: stat_names: List of statistics to be extracted from those calculated by regionprops. Returns: Dictionary of shape statistics
entailment
def calc_shape_step(self, stat_names, time): """ Calculate shape statistics for a single time step Args: stat_names: List of shape statistics calculated from region props time: Time being investigated Returns: List of shape statistics """ ...
Calculate shape statistics for a single time step Args: stat_names: List of shape statistics calculated from region props time: Time being investigated Returns: List of shape statistics
entailment
def to_geojson(self, filename, proj, metadata=None): """ Output the data in the STObject to a geoJSON file. Args: filename: Name of the file proj: PyProj object for converting the x and y coordinates back to latitude and longitue values. metadata: Metadata de...
Output the data in the STObject to a geoJSON file. Args: filename: Name of the file proj: PyProj object for converting the x and y coordinates back to latitude and longitue values. metadata: Metadata describing the object to be included in the top-level properties.
entailment
def rewrite_properties(self, properties): """Set the properties and write to disk.""" with self.__library_storage_lock: self.__library_storage = properties self.__write_properties(None)
Set the properties and write to disk.
entailment
def model(self, v=None): "Returns the model of node v" if v is None: v = self.estopping hist = self.hist trace = self.trace(v) ins = None if self._base._probability_calibration is not None: node = hist[-1] node.normalize() X...
Returns the model of node v
entailment
def trace(self, n): "Restore the position in the history of individual v's nodes" trace_map = {} self._trace(n, trace_map) s = list(trace_map.keys()) s.sort() return s
Restore the position in the history of individual v's nodes
entailment
def tournament(self, negative=False): """Tournament selection and when negative is True it performs negative tournament selection""" if self.generation <= self._random_generations and not negative: return self.random_selection() if not self._negative_selection and negative: ...
Tournament selection and when negative is True it performs negative tournament selection
entailment
def create_population(self): "Create the initial population" base = self._base if base._share_inputs: used_inputs_var = SelectNumbers([x for x in range(base.nvar)]) used_inputs_naive = used_inputs_var if base._pr_variable == 0: used_inputs_var = Select...
Create the initial population
entailment
def add(self, v): "Add an individual to the population" self.population.append(v) self._current_popsize += 1 v.position = len(self._hist) self._hist.append(v) self.bsf = v self.estopping = v self._density += self.get_density(v)
Add an individual to the population
entailment
def replace(self, v): """Replace an individual selected by negative tournament selection with individual v""" if self.popsize < self._popsize: return self.add(v) k = self.tournament(negative=True) self.clean(self.population[k]) self.population[k] = v v...
Replace an individual selected by negative tournament selection with individual v
entailment
def make_directory_if_needed(directory_path): """ Make the directory path, if needed. """ if os.path.exists(directory_path): if not os.path.isdir(directory_path): raise OSError("Path is not a directory:", directory_path) else: os.makedirs(directory_path)
Make the directory path, if needed.
entailment
def hatchery(): """ Main entry point for the hatchery program """ args = docopt.docopt(__doc__) task_list = args['<task>'] if not task_list or 'help' in task_list or args['--help']: print(__doc__.format(version=_version.__version__, config_files=config.CONFIG_LOCATIONS)) return 0 l...
Main entry point for the hatchery program
entailment
def call(cmd_args, suppress_output=False): """ Call an arbitary command and return the exit value, stdout, and stderr as a tuple Command can be passed in as either a string or iterable >>> result = call('hatchery', suppress_output=True) >>> result.exitval 0 >>> result = call(['hatchery', 'notr...
Call an arbitary command and return the exit value, stdout, and stderr as a tuple Command can be passed in as either a string or iterable >>> result = call('hatchery', suppress_output=True) >>> result.exitval 0 >>> result = call(['hatchery', 'notreal']) >>> result.exitval 1
entailment
def setup(cmd_args, suppress_output=False): """ Call a setup.py command or list of commands >>> result = setup('--name', suppress_output=True) >>> result.exitval 0 >>> result = setup('notreal') >>> result.exitval 1 """ if not funcy.is_list(cmd_args) and not funcy.is_tuple(cmd_args):...
Call a setup.py command or list of commands >>> result = setup('--name', suppress_output=True) >>> result.exitval 0 >>> result = setup('notreal') >>> result.exitval 1
entailment
def load_data(self): """ Loads data files and stores the output in the data attribute. """ data = [] valid_dates = [] mrms_files = np.array(sorted(os.listdir(self.path + self.variable + "/"))) mrms_file_dates = np.array([m_file.split("_")[-2].split("-")[0] ...
Loads data files and stores the output in the data attribute.
entailment
def rescale_data(data, data_min, data_max, out_min=0.0, out_max=100.0): """ Rescale your input data so that is ranges over integer values, which will perform better in the watershed. Args: data: 2D or 3D ndarray being rescaled data_min: minimum value of input data for scaling purposes ...
Rescale your input data so that is ranges over integer values, which will perform better in the watershed. Args: data: 2D or 3D ndarray being rescaled data_min: minimum value of input data for scaling purposes data_max: maximum value of input data for scaling purposes out_min: minim...
entailment
def label(self, input_grid): """ Labels input grid using enhanced watershed algorithm. Args: input_grid (numpy.ndarray): Grid to be labeled. Returns: Array of labeled pixels """ marked = self.find_local_maxima(input_grid) marked = np.wher...
Labels input grid using enhanced watershed algorithm. Args: input_grid (numpy.ndarray): Grid to be labeled. Returns: Array of labeled pixels
entailment
def find_local_maxima(self, input_grid): """ Finds the local maxima in the inputGrid and perform region growing to identify objects. Args: input_grid: Raw input data. Returns: array with labeled objects. """ pixels, q_data = self.quantize(input_g...
Finds the local maxima in the inputGrid and perform region growing to identify objects. Args: input_grid: Raw input data. Returns: array with labeled objects.
entailment
def set_maximum(self, q_data, marked, center, bin_lower, foothills): """ Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordi...
Grow a region at a certain bin level and check if the region has reached the maximum size. Args: q_data: Quantized data array marked: Array marking points that are objects center: Coordinates of the center pixel of the region being grown bin_lower: Intensity leve...
entailment
def remove_foothills(self, q_data, marked, bin_num, bin_lower, centers, foothills): """ Mark points determined to be foothills as globbed, so that they are not included in future searches. Also searches neighboring points to foothill points to determine if they should also be considered ...
Mark points determined to be foothills as globbed, so that they are not included in future searches. Also searches neighboring points to foothill points to determine if they should also be considered foothills. Args: q_data: Quantized data marked: Marked bin_...
entailment
def quantize(self, input_grid): """ Quantize a grid into discrete steps based on input parameters. Args: input_grid: 2-d array of values Returns: Dictionary of value pointing to pixel locations, and quantized 2-d array of data """ pixels = {} ...
Quantize a grid into discrete steps based on input parameters. Args: input_grid: 2-d array of values Returns: Dictionary of value pointing to pixel locations, and quantized 2-d array of data
entailment
def listall(self): ''' will display all the filenames. Result can be stored in an array for easy fetching of gistNames for future purposes. eg. a = Gist().mygists().listall() print a[0] #to fetch first gistName ''' file_name = [] r = requests.get( '%s/users/%s/gists' % (BASE_URL, self.user), ...
will display all the filenames. Result can be stored in an array for easy fetching of gistNames for future purposes. eg. a = Gist().mygists().listall() print a[0] #to fetch first gistName
entailment
def content(self, **args): ''' Doesn't require manual fetching of gistID of a gist passing gistName will return the content of gist. In case, names are ambigious, provide GistID or it will return the contents of recent ambigious gistname ''' self.gist_name = '' if 'name' in args: self.gist_name = arg...
Doesn't require manual fetching of gistID of a gist passing gistName will return the content of gist. In case, names are ambigious, provide GistID or it will return the contents of recent ambigious gistname
entailment
def edit(self, **args): ''' Doesn't require manual fetching of gistID of a gist passing gistName will return edit the gist ''' self.gist_name = '' if 'description' in args: self.description = args['description'] else: self.description = '' if 'name' in args and 'id' in args: self.gist_name = ...
Doesn't require manual fetching of gistID of a gist passing gistName will return edit the gist
entailment
def delete(self, **args): ''' Delete a gist by gistname/gistID ''' 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('Provide GistName to delete') url = 'gists' if self.gist_id: ...
Delete a gist by gistname/gistID
entailment
def starred(self, **args): ''' List the authenticated user's starred gists ''' ids =[] r = requests.get( '%s/gists/starred'%BASE_URL, headers=self.gist.header ) if 'limit' in args: limit = args['limit'] else: limit = len(r.json()) if (r.status_code == 200): for g in range(0,limit ): ...
List the authenticated user's starred gists
entailment
def links(self,**args): ''' Return Gist URL-Link, Clone-Link and Script-Link to embed ''' 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('Gist Name/ID must be provided') if self.gis...
Return Gist URL-Link, Clone-Link and Script-Link to embed
entailment
def load_forecasts(self): """ Load neighborhood probability forecasts. """ run_date_str = self.run_date.strftime("%Y%m%d") forecast_file = self.forecast_path + "{0}/{1}_{2}_{3}_consensus_{0}.nc".format(run_date_str, ...
Load neighborhood probability forecasts.
entailment
def load_obs(self, mask_threshold=0.5): """ Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked. """ print("Loading obs ", self.run_date, self.model_name, self.forecast_variable) ...
Loads observations and masking grid (if needed). Args: mask_threshold: Values greater than the threshold are kept, others are masked.
entailment
def load_coordinates(self): """ Loads lat-lon coordinates from a netCDF file. """ coord_file = Dataset(self.coordinate_file) if "lon" in coord_file.variables.keys(): self.coordinates["lon"] = coord_file.variables["lon"][:] self.coordinates["lat"] = coord_f...
Loads lat-lon coordinates from a netCDF file.
entailment
def evaluate_hourly_forecasts(self): """ Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects. """ score_columns = ["Run_Date", "Forecast_Hour",...
Calculates ROC curves and Reliability scores for each forecast hour. Returns: A pandas DataFrame containing forecast metadata as well as DistributedROC and Reliability objects.
entailment
def evaluate_period_forecasts(self): """ Evaluates ROC and Reliability scores for forecasts over the full period from start hour to end hour Returns: A pandas DataFrame with full-period metadata and verification statistics """ score_columns = ["Run_Date", "Ensemble N...
Evaluates ROC and Reliability scores for forecasts over the full period from start hour to end hour Returns: A pandas DataFrame with full-period metadata and verification statistics
entailment