code stringlengths 1 18.2k |
|---|
pos heap[pos].key = new_key |
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 KeyError pos1, pos2 = position[key1], position[key2] heap[pos1].key, h... |
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)): self._sink(pos) else: try: pos = self._position[key] except KeyError... |
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) |
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 = ret[1:-1] return ret |
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=True ) else: found = helpers.regex_in_packa... |
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_content = version_file_... |
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.InvalidVersion: return False return True |
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 == 200: return r... |
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_url[:len(suffix) * -1] + '/api/... |
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 |
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) + 'not sure what to do with it, refusing to convert' ) elif fil... |
== 'readme.md': rst_filename = 'README.rst' logger.info('converting {} to {}'.format(filename, rst_filename)) try: rst_content = pypandoc.convert(filename, 'rst') with open('README.rst', 'w') as rst_file: rst_file.write(rst_content) return except OSError as e: raise ProjectError( 'could not convert readme to rst due to... |
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')] |
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) if version: versions.add(version)... |
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 in km threshold: intensity of exceedance stride: ... |
neighbor_y.ravel())).T) neighbor_prob = np.zeros((self.data.shape[0], neighbor_x.shape[0], neighbor_x.shape[1])) print('Forecast Hours: {0}-{1}'.format(start_time, end_time)) for m in range(len(self.members)): period_max = self.data[m,start_time:end_time,:,:].max(axis=0) valid_i, valid_j = np.where(period_max >= thresh... |
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('Resposta nao possui pipes ' 'separando os campos: {!r}'.f... |
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 entre si através de pipes e... |
dois elementos: o nome do campo e uma função de conversão a partir de uma string unicode. Por exemplo: .. sourcecode:: python >>> retorno = '123456|08000|SAT em operacao||' >>> resposta = analisar_retorno(retorno, funcao='ConsultarSAT') >>> resposta.numeroSessao 123456 >>> resposta.EEEEE u'08000' >>> resposta.mensagem ... |
da resposta retornada pela função da DLL SAT. :param type classe_resposta: O tipo :class:`RespostaSAT` ou especialização que irá representar o retorno, após sua decomposição em campos. :param tuple campos: Especificação dos campos (nomes) e seus conversores a a partir do tipo ``unicode``. :param list campos_alternativo... |
o número de campos especificados em ``campos``. Para que a relação alternativa de campos funcione, é importante que cada relação de campos alternativos tenha um número diferente de campos. :param str funcao: Nome da função da DLL SAT que gerou o retorno, que estará disponível nos atributos adicionais à resposta. :param... |
adicionais à resposta. :raises ErroRespostaSATInvalida: Se o retorno não estiver em conformidade com o padrão esperado ou se não possuir os campos especificados. :return: Uma instância de :class:`RespostaSAT` ou especialização. :rtype: satcfe.resposta.padrao.RespostaSAT """ if '|' not in retorno: raise ErroRespostaSATI... |
campos do retorno for relacao_alternativa in campos_alternativos: if len(partes) == len(relacao_alternativa): relacao_campos = relacao_alternativa break else: raise ErroRespostaSATInvalida('Resposta nao possui o numero ' 'esperado de campos. Esperados %d campos, mas ' 'contem %d: "%s"' % ( len(campos), len(partes), as_... |
= conversor(partes[indice]) resposta = classe_resposta(**resultado) resposta.atributos.funcao = funcao resposta.atributos.verbatim = retorno if manter_verbatim else None return resposta |
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='ComunicarCertificadoICPBRASIL') if resposta.EEEEE not in ('05000',): rai... |
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',): raise ExcecaoRespostaSAT(resposta) return resposta |
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') if resposta.EEEEE not in ('12000',): raise Excecao... |
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 not in ('13000',): raise ExcecaoRespostaSAT(resposta) ret... |
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.EEEEE not in ('14000',): raise ExcecaoRespostaSAT(respo... |
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',): raise ExcecaoRespostaSAT(resposta) return resposta |
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 ('17000',): raise ExcecaoRespostaSAT(resposta) return resposta |
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 resposta.EEEEE not in ('18000',): raise ExcecaoRespostaS... |
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"] relh_vals = {} for var in relh_vars: mg = SSEFModelGrid(self.member_name, self.run... |
elif self.variable == "melth": input_vars = ["hgtsfc", "hgt700", "hgt500", "tmp700", "tmp500"] input_vals = {} for var in input_vars: mg = SSEFModelGrid(self.member_name, self.run_date, var, self.start_date, self.end_date, self.path, single_step=self.single_step) input_vals[var], units = mg.load_data() mg.close() self.... |
self.run_date, self.variable, self.start_date, self.end_date, self.path, single_step=self.single_step) self.data, self.units = mg.load_data() mg.close() elif self.ensemble_name.upper() == "HREFV2": proj_dict, grid_dict = read_ncar_map_file(self.map_file) mapping_data = make_proj_grids(proj_dict, grid_dict) mg = HREFv2M... |
self.start_date, self.end_date, self.path) self.data, self.units = mg.load_data() mg.close() elif self.ensemble_name.upper() == "NCARSTORM": mg = NCARStormEventModelGrid(self.run_date, self.variable, self.start_date, self.end_date, self.path) self.data, self.units = mg.load_data() mg.close() else: print(self.ensemble_n... |
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_dict, grid_dict = read_arps_map_file(map_file) self.dx = int(grid_... |
"HRRR", "VSE", "HREFV2"]: proj_dict, grid_dict = read_ncar_map_file(map_file) if self.member_name[0:7] == "1km_pbl": # Don't just look at the first 3 characters. You have to differentiate '1km_pbl1' and '1km_on_3km_pbl1' grid_dict["dx"] = 1000 grid_dict["dy"] = 1000 grid_dict["sw_lon"] = 258.697 grid_dict["sw_lat"] = 2... |
self.proj = get_proj_obj(proj_dict) |
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_file.close() times = data["properties"]["times"] main... |
v in feature["properties"]["attributes"].items(): if k not in attribute_data.keys(): attribute_data[k] = [np.array(v)] else: attribute_data[k].append(np.array(v)) kwargs = {} for kw in ["dx", "step", "u", "v"]: if kw in data["properties"].keys(): kwargs[kw] = data["properties"][kw] sto = STObject(main_data["timesteps"]... |
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 <= self.end_time: diff = time - self.start_time valid = np.flatnonzero(self.... |
self.x[diff].ravel()[valid]) com_y = 1.0 / self.timesteps[diff].ravel()[valid].sum() * np.sum(self.timesteps[diff].ravel()[valid] * self.y[diff].ravel()[valid]) else: com_x = np.mean(self.x[diff]) com_y = np.mean(self.y[diff]) else: com_x = None com_y = None return com_x, com_y |
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 |
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 index. """ if self.start_time <= time <= self.end_time: diff = time - sel... |
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_time].sum() else: return 0 |
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() |
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() |
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.x) self.y.extend(step.y) self.i.extend(step.i) self.j.extend(step.j) self.end... |
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_boundaries() works. # But if all perimeter points are m... |
the padded array. padded_mask = np.pad(self.masks[ti], 1, 'constant', constant_values=0) chull = convex_hull_image(padded_mask) boundary_image = find_boundaries(chull, mode='inner', background=0) # Now remove the padding. boundary_image = boundary_image[1:-1,1:-1] boundary_x = self.x[ti].ravel()[boundary_image.ravel()]... |
in range(r.size)], dtype=[('r', 'f4'), ('theta', 'f4')]) coord_order = np.argsort(polar_coords, order=['theta', 'r']) ordered_coords = np.vstack([boundary_x[coord_order], boundary_y[coord_order]]) return ordered_coords |
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 correlation. max_u: Maximum x-component of motion. Used... |
error. """ ti = np.where(time == self.times)[0][0] mask_vals = np.where(self.masks[ti].ravel() == 1) i_vals = self.i[ti].ravel()[mask_vals] j_vals = self.j[ti].ravel()[mask_vals] obj_vals = self.timesteps[ti].ravel()[mask_vals] u_shifts = np.arange(-max_u, max_u + 1) v_shifts = np.arange(-max_v, max_v + 1) min_error = ... |
& (i_shift < intensity_grid.shape[0]) & (0 <= j_shift) & (j_shift < intensity_grid.shape[1])): shift_vals = intensity_grid[i_shift, j_shift] else: shift_vals = np.zeros(i_shift.shape) # This isn't correlation; it is mean absolute error. error = np.abs(shift_vals - obj_vals).mean() if error < min_error: min_error = erro... |
# best_v = 0 self.u[ti] = best_u self.v[ti] = best_v return best_u, best_v, min_error |
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_time == other_object.times)[0] obj_coords = np.... |
= other_object.j[oti][other_object.masks[oti] == 1] return float(np.intersect1d(obj_coords, other_obj_coords).size) / np.maximum(self.masks[ti].sum(), other_object.masks[oti].sum()) |
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 the time before instead of the same time as the object ""... |
"-future" timesteps = np.arange(self.start_time + 1, self.end_time + 2) else: var_name = model_grid.variable timesteps = np.arange(self.start_time, self.end_time + 1) self.attributes[var_name] = [] for ti, t in enumerate(timesteps): self.attributes[var_name].append( model_grid.data[t - model_grid.start_hour, self.i[ti]... |
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.attributes[var_name] = [] for t in range(self.times.size): self.attributes... |
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.start_time, self.end_time + 1) for ti, t in enumerate(timesteps): t_inde... |
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. """ stats = {} for var, grids in self.attributes.items(): if len(gr... |
0), statistic_name)() return stats |
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: attribute: Attribute extracted from model grid st... |
== time)[0][0] ma = np.where(self.masks[ti].ravel() == 1) if statistic in ['mean', 'max', 'min', 'std', 'ptp']: stat_val = getattr(self.attributes[attribute][ti].ravel()[ma], statistic)() elif statistic == 'median': stat_val = np.median(self.attributes[attribute][ti].ravel()[ma]) elif statistic == "skew": stat_val = np... |
self.calc_attribute_statistic(attribute, stat_name, time) \ - self.calc_attribute_statistic(attribute, stat_name, time - 1) else: stat_val = np.nan return stat_val |
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 """ ti = np.where(self.times == time)[0][0] ma = np.where(self.masks[ti].ravel() == 1) if... |
int(statistic.split("_")[1]) stat_val = np.percentile(self.timesteps[ti].ravel()[ma], per) elif 'dt' in statistic: stat_name = statistic[:-3] if ti == 0: stat_val = 0 else: stat_val = self.calc_timestep_statistic(stat_name, time) -\ self.calc_timestep_statistic(stat_name, time - 1) else: stat_val = np.nan return stat_v... |
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 """ stats = {} try: all_props = [regionprops(m) for m in self.masks... |
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 """ ti = np.where(self.times == time)[0][0] props = regionprops(self.masks[ti], self.... |
shape_stats.append(0) else: shape_stats.append(hu_val) else: shape_stats.append(props[stat_name]) return shape_stats |
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 describing the object to be included in the top-level propertie... |
"properties": {}} json_obj['properties']['times'] = self.times.tolist() json_obj['properties']['dx'] = self.dx json_obj['properties']['step'] = self.step json_obj['properties']['u'] = self.u.tolist() json_obj['properties']['v'] = self.v.tolist() for k, v in metadata.items(): json_obj['properties'][k] = v for t, time in... |
"y", "i", "j"]: feature["properties"][attr] = getattr(self, attr)[t].tolist() feature["properties"]["attributes"] = {} for attr_name, steps in self.attributes.items(): feature["properties"]["attributes"][attr_name] = steps[t].tolist() json_obj['features'].append(feature) file_obj = open(filename, "w") json.dump(json_ob... |
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) |
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 = np.array([x.full_array() for x in node.hy]).T y = np.array(self._base._y_klass.full_array()) ... |
m = Model(trace, hist, nvar=self._base._nvar, classifier=self._classifier, labels=self._labels, probability_calibration=ins, nclasses=nclasses) return m |
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 |
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: return self.random_selection(negative=negativ... |
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 = SelectNumbers([]) used_inputs_naive = SelectNumbers([x for x in range(base... |
nb_input = Inputs(base, used_inputs_naive, functions=base._input_functions) while ((base._all_inputs and not base.stopping_criteria_tl()) or (self.popsize < base.popsize and not base.stopping_criteria())): if base._all_inputs and used_inputs_var.empty() and used_inputs_naive.empty(): base._init_popsize = self.popsize b... |
and used_inputs_naive.empty(): base._pr_variable = 1 if v is None: used_inputs_naive.pos = used_inputs_naive.size if not used_inputs_var.empty(): base._pr_variable = 1 continue else: gen = self.generation self.generation = 0 v = base.random_offspring() self.generation = gen self.add(v) |
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) |
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.position = len(self._hist) self._hist.append(v) self.bsf = v self.e... |
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) |
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 level_str = args['--log-level'] try: le... |
not in ORDERED_TASKS: logger.info('starting task: check') logger.error('received invalid task: ' + task) return 1 for task in CHECK_TASKS: if task in task_list: task_check(args) break if 'package' in task_list and not args['--release-version']: logger.error('--release-version is required for the package task') return 1... |
if they fail # check will have already been run for task in ORDERED_TASKS: if task in task_list and task != 'check': logger.info('starting task: ' + task) globals()['task_' + task](args) logger.info("all's well that ends well...hatchery out") return 0 |
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', 'notreal']) >>> result.exitval ... |
= call_request.run() if call_result.exitval: logger.error('`{}` returned error code {}'.format(' '.join(cmd_args), call_result.exitval)) return call_result |
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): cmd_args = shlex.split(cmd_args) cmd... |
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] for m_file in mrms_files]) old_mrms_file = None file_obj = None... |
is not None: file_obj.close() file_obj = Dataset(self.path + self.variable + "/" + mrms_file) #old_mrms_file = mrms_file if "time" in file_obj.variables.keys(): time_var = "time" else: time_var = "date" file_valid_dates = pd.DatetimeIndex(num2date(file_obj.variables[time_var][:], file_obj.variables[time_var].units)) el... |
150 self.valid_dates = pd.DatetimeIndex(valid_dates) |
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 data_max: maximum value of input d... |
Linearly scaled ndarray """ return (out_max - out_min) / (data_max - data_min) * (data - data_min) + out_min |
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.where(marked >= 0, 1, 0) # splabel returns two things in a tuple: an array and an inte... |
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_grid) centers = OrderedDict() for p in pixels.keys(): centers[p] = [] marke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.