code stringlengths 1 18.2k |
|---|
-= minval return 2 |
def __step2(self): """ Find a zero (Z) in the resulting matrix. If there is no starred zero in its row or column, star Z. Repeat for each element in the matrix. Go to Step 3. """ n = self.n for i in range(n): for j in range(n): if (self.C[i][j] == 0) and \ (not self.col_covered[j]) and \ (not self.row_covered[i]): self... |
True self.row_covered[i] = True self.__clear_covers() return 3 |
def __step3(self): """ Cover each column containing a starred zero. If K columns are covered, the starred zeros describe a complete set of unique assignments. In this case, Go to DONE, otherwise, Go to Step 4. """ n = self.n count = 0 for i in range(n): for j in range(n): if self.marked[i][j] == 1: self.col_covered[j] ... |
n: step = 7 # done else: step = 4 return step |
def __step4(self): """ Find a noncovered zero and prime it. If there is no starred zero in the row containing this primed zero, Go to Step 5. Otherwise, cover this row and uncover the column containing the starred zero. Continue in this manner until there are no uncovered zeros left. Save the smallest uncovered value a... |
done = False row = -1 col = -1 star_col = -1 while not done: (row, col) = self.__find_a_zero() if row < 0: done = True step = 6 else: self.marked[row][col] = 2 star_col = self.__find_star_in_row(row) if star_col >= 0: col = star_col self.row_covered[row] = True self.col_covered[col] = False else: done = True self.Z0_r ... |
def __step5(self): """ Construct a series of alternating primed and starred zeros as follows. Let Z0 represent the uncovered primed zero found in Step 4. Let Z1 denote the starred zero in the column of Z0 (if any). Let Z2 denote the primed zero in the row of Z1 (there will always be one). Continue until the series term... |
has no starred zero in its column. Unstar each starred zero of the series, star each primed zero of the series, erase all primes and uncover every line in the matrix. Return to Step 3 """ count = 0 path = self.path path[count][0] = self.Z0_r path[count][1] = self.Z0_c done = False while not done: row = self.__find_star... |
path[count][0] = row path[count][1] = path[count-1][1] else: done = True if not done: col = self.__find_prime_in_row(path[count][0]) count += 1 path[count][0] = path[count-1][0] path[count][1] = col self.__convert_path(path, count) self.__clear_covers() self.__erase_primes() return 3 |
def __step6(self): """ Add the value found in Step 4 to every element of each covered row, and subtract it from every element of each uncovered column. Return to Step 4 without altering any stars, primes, or covered lines. """ minval = self.__find_smallest() for i in range(self.n): for j in range(self.n): if self.row_c... |
def __find_smallest(self): """Find the smallest uncovered value in the matrix.""" minval = sys.maxsize for i in range(self.n): for j in range(self.n): if (not self.row_covered[i]) and (not self.col_covered[j]): if minval > self.C[i][j]: minval = self.C[i][j] return minval |
def __find_a_zero(self): """Find the first uncovered element with value 0""" row = -1 col = -1 i = 0 n = self.n done = False while not done: j = 0 while True: if (self.C[i][j] == 0) and \ (not self.row_covered[i]) and \ (not self.col_covered[j]): row = i col = j done = True j += 1 if j >= n: break i += |
1 if i >= n: done = True return (row, col) |
def __find_star_in_row(self, row): """ Find the first starred element in the specified row. Returns the column index, or -1 if no starred element was found. """ col = -1 for j in range(self.n): if self.marked[row][j] == 1: col = j break return col |
def __find_star_in_col(self, col): """ Find the first starred element in the specified row. Returns the row index, or -1 if no starred element was found. """ row = -1 for i in range(self.n): if self.marked[i][col] == 1: row = i break return row |
def __find_prime_in_row(self, row): """ Find the first prime element in the specified row. Returns the column index, or -1 if no starred element was found. """ col = -1 for j in range(self.n): if self.marked[row][j] == 2: col = j break return col |
def __clear_covers(self): """Clear all covered matrix cells""" for i in range(self.n): self.row_covered[i] = False self.col_covered[i] = False |
def __erase_primes(self): """Erase all prime markings""" for i in range(self.n): for j in range(self.n): if self.marked[i][j] == 2: self.marked[i][j] = 0 |
def update(self, a, b, c, d): """ Update contingency table with new values without creating a new object. """ self.table.ravel()[:] = [a, b, c, d] self.N = self.table.sum() |
def bias(self): """ Frequency Bias. Formula: (a+b)/(a+c)""" return (self.table[0, 0] + self.table[0, 1]) / (self.table[0, 0] + self.table[1, 0]) |
def csi(self): """Gilbert's Score or Threat Score or Critical Success Index a/(a+b+c)""" return self.table[0, 0] / (self.table[0, 0] + self.table[0, 1] + self.table[1, 0]) |
def ets(self): """Equitable Threat Score, Gilbert Skill Score, v, (a - R)/(a + b + c - R), R=(a+b)(a+c)/N""" r = (self.table[0, 0] + self.table[0, 1]) * (self.table[0, 0] + self.table[1, 0]) / self.N return (self.table[0, 0] - r) / (self.table[0, 0] + self.table[0, 1] + self.table[1, 0] - r) |
def hss(self): """Doolittle (Heidke) Skill Score. 2(ad-bc)/((a+b)(b+d) + (a+c)(c+d))""" return 2 * (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / ( (self.table[0, 0] + self.table[0, 1]) * (self.table[0, 1] + self.table[1, 1]) + (self.table[0, 0] + self.table[1, 0]) * (self.table[1, 0] + s... |
def pss(self): """Peirce (Hansen-Kuipers, True) Skill Score (ad - bc)/((a+c)(b+d))""" return (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / \ ((self.table[0, 0] + self.table[1, 0]) * (self.table[0, 1] + self.table[1, 1])) |
def css(self): """Clayton Skill Score (ad - bc)/((a+b)(c+d))""" return (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / \ ((self.table[0, 0] + self.table[0, 1]) * (self.table[1, 0] + self.table[1, 1])) |
def load_tree_object(filename): """ Load scikit-learn decision tree ensemble object from file. Parameters ---------- filename : str Name of the pickle file containing the tree object. Returns ------- tree ensemble object """ with open(filename) as file_obj: tree_ensemble_obj = pickle.load(file_obj) return tree_ensemble... |
def output_tree_ensemble(tree_ensemble_obj, output_filename, attribute_names=None): """ Write each decision tree in an ensemble to a file. Parameters ---------- tree_ensemble_obj : sklearn.ensemble object Random Forest or Gradient Boosted Regression object output_filename : str File where trees are written attribute_na... |
+ ".{0:d}.tree", "w") #out_file.write("Tree {0:d}\n".format(t)) tree_str = print_tree_recursive(tree.tree_, 0, attribute_names) out_file.write(tree_str) #out_file.write("\n") out_file.close() return |
def print_tree_recursive(tree_obj, node_index, attribute_names=None): """ Recursively writes a string representation of a decision tree object. Parameters ---------- tree_obj : sklearn.tree._tree.Tree object A base decision tree object node_index : int Index of the node being printed attribute_names : list List of attr... |
if node_index == 0: tree_str += "{0:d}\n".format(tree_obj.node_count) if tree_obj.feature[node_index] >= 0: if attribute_names is None: attr_val = "{0:d}".format(tree_obj.feature[node_index]) else: attr_val = attribute_names[tree_obj.feature[node_index]] tree_str += "b {0:d} {1} {2:0.4f} {3:d} {4:1.5e}\n".format(node_i... |
attribute_names) if tree_obj.children_right[node_index] > 0: tree_str += print_tree_recursive(tree_obj, tree_obj.children_right[node_index], attribute_names) return tree_str |
def set_classifier_mask(self, v, base_mask=True): """Computes the mask used to create the training and validation set""" base = self._base v = tonparray(v) a = np.unique(v) if a[0] != -1 or a[1] != 1: raise RuntimeError("The labels must be -1 and 1 (%s)" % a) mask = np.zeros_like(v) cnt = min([(v == x).sum() for x in a... |
index = np.where((v == i) & base_mask)[0] np.random.shuffle(index) mask[index[:cnt]] = True base._mask = SparseArray.fromlist(mask) return SparseArray.fromlist(v) |
def set_regression_mask(self, v): """Computes the mask used to create the training and validation set""" base = self._base index = np.arange(v.size()) np.random.shuffle(index) ones = np.ones(v.size()) ones[index[int(base._tr_fraction * v.size()):]] = 0 base._mask = SparseArray.fromlist(ones) |
def fitness(self, v): "Fitness function in the training set" base = self._base if base._classifier: if base._multiple_outputs: hy = SparseArray.argmax(v.hy) fit_func = base._fitness_function if fit_func == 'macro-F1' or fit_func == 'a_F1': f1_score = self.score mf1, mf1_v = f1_score.a_F1(base._y_klass, hy, base._mask_t... |
hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 elif fit_func == 'DotRecallDotPrecision' or fit_func == 'g_g_recall_precision': f1_score = self.score mf1, mf1_v = f1_score.g_g_recall_precision(base._y_klass, hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 elif fit_func == 'BER' or fi... |
- 1 elif fit_func == 'DotRecall' or fit_func == 'g_recall': f1_score = self.score mf1, mf1_v = f1_score.g_recall(base._y_klass, hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 elif fit_func == 'macro-Precision' or fit_func == 'a_precision': f1_score = self.score mf1, mf1_v = f1_score.a_precision(base.... |
f1_score = self.score mf1, mf1_v = f1_score.g_precision(base._y_klass, hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 elif fit_func == 'accDotMacroF1': f1_score = self.score mf1, mf1_v = f1_score.accDotMacroF1(base._y_klass, hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 elif fit_f... |
1 elif fit_func == 'F1': f1_score = self.score f1_index = self._base._F1_index index = self.min_class if f1_index < 0 else f1_index mf1, mf1_v = f1_score.F1(index, base._y_klass, hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 elif fit_func == 'RecallDotPrecision' or fit_func == 'g_recall_precision': ... |
1 elif fit_func == 'ER' or fit_func == 'accuracy': f1_score = self.score mf1, mf1_v = f1_score.accuracy(base._y_klass, hy, base._mask_ts.index) v._error = mf1_v - 1 v.fitness = mf1 - 1 else: raise RuntimeError('Unknown fitness function %s' % base._fitness_function) else: v.fitness = -base._ytr.SSE(v.hy * base._mask) el... |
* base._mask) |
def fitness_vs(self, v): """Fitness function in the validation set In classification it uses BER and RSE in regression""" base = self._base if base._classifier: if base._multiple_outputs: v.fitness_vs = v._error # if base._fitness_function == 'macro-F1': # v.fitness_vs = v._error # elif base._fitness_function == 'BER':... |
# elif base._fitness_function == 'macro-RecallF1': # v.fitness_vs = v._error # elif base._fitness_function == 'F1': # v.fitness_vs = v._error # else: # v.fitness_vs = - v._error.dot(base._mask_vs) / base._mask_vs.sum() else: v.fitness_vs = -((base.y - v.hy.sign()).sign().fabs() * base._mask_vs).sum() else: mask = base.... |
_hy in zip(mask, y, hy): m = (_mask + -1).fabs() x = _y * m y = _hy * m a = (x - y).sq().sum() b = (x + -x.sum() / x.size()).sq().sum() fit.append(-a / b) v.fitness_vs = np.mean(fit) |
def set_fitness(self, v): """Set the fitness to a new node. Returns false in case fitness is not finite""" base = self._base self.fitness(v) if not np.isfinite(v.fitness): self.del_error(v) return False if base._tr_fraction < 1: self.fitness_vs(v) if not np.isfinite(v.fitness_vs): self.del_error(v) return False self.de... |
def analisar(retorno): """Constrói uma :class:`RespostaCancelarUltimaVenda` a partir do retorno informado. :param unicode retorno: Retorno da função ``CancelarUltimaVenda``. """ resposta = analisar_retorno(forcar_unicode(retorno), funcao='EnviarDadosVenda', classe_resposta=RespostaCancelarUltimaVenda, campos=( ('numero... |
deverão ser retornados... ( ('numeroSessao', int), ('EEEEE', unicode), ('CCCC', unicode), ('mensagem', unicode), ('cod', unicode), ('mensagemSEFAZ', unicode), ), # por via das dúvidas, considera o padrão de campos, # caso não haja nenhuma coincidência... RespostaSAT.CAMPOS, ] ) if resposta.EEEEE not in ('07000',): rais... |
def convert_data_element_to_data_and_metadata_1(data_element) -> DataAndMetadata.DataAndMetadata: """Convert a data element to xdata. No data copying occurs. The data element can have the following keys: data (required) is_sequence, collection_dimension_count, datum_dimension_count (optional description of the data) sp... |
datetime_modified (dst, tz) it is converted and used as timestamp then timezone gets stored into metadata.description.timezone. """ # data. takes ownership. data = data_element["data"] dimensional_shape = Image.dimensional_shape_from_data(data) is_sequence = data_element.get("is_sequence", False) dimension_count = len(... |
datum_dimension_count) # dimensional calibrations dimensional_calibrations = None if "spatial_calibrations" in data_element: dimensional_calibrations_list = data_element.get("spatial_calibrations") if len(dimensional_calibrations_list) == len(dimensional_shape): dimensional_calibrations = list() for dimension_calibrati... |
in data_element: intensity_calibration_dict = data_element.get("intensity_calibration") offset = float(intensity_calibration_dict.get("offset", 0.0)) scale = float(intensity_calibration_dict.get("scale", 1.0)) units = intensity_calibration_dict.get("units", "") units = str(units) if units is not None else str() if scal... |
and must use this specific ISO 8601 format. 2013-11-17T08:43:21.389391 # time zones are offsets (east of UTC) in the following format "+HHMM" or "-HHMM" # daylight savings times are time offset (east of UTC) in format "+MM" or "-MM" # timezone is for conversion and is the Olson timezone string. # datetime.datetime.strp... |
this image was modified. # datetime_original, datetime_original_tz, datetime_original_dst, datetime_original_tzname is the time at which this image was created. timestamp = data_element.get("timestamp", datetime.datetime.utcnow()) datetime_item = data_element.get("datetime_modified", Utility.get_datetime_item_from_utc_... |
dst tz_adjust = (int(tz_value[1:3]) * 60 + int(tz_value[3:5])) * (-1 if tz_value[0] == '-' else 1) utc_datetime = local_datetime - datetime.timedelta(minutes=tz_adjust) # tz_adjust already contains dst_adjust timestamp = utc_datetime return DataAndMetadata.new_data_and_metadata(data, intensity_calibration=intensity_cal... |
def output_sector_csv(self,csv_path,file_dict_key,out_path): """ Segment forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: csv_path(str): Path to the full CONUS csv file. file_dict_key(str): Dictionary key for the csv files, currently either 'track_step' or 'tra... |
+ "{0}_{1}_{2}_{3}.csv".format( file_dict_key, self.ensemble_name, self.member, self.run_date.strftime(self.date_format)) if exists(csv_file): csv_data = pd.read_csv(csv_file) if self.inds is None: lon_obj = csv_data.loc[:,"Centroid_Lon"] lat_obj = csv_data.loc[:,"Centroid_Lat"] self.inds = np.where((self.ne_lat>=lat_o... |
{0} {1} csv file found'.format(self.member, self.run_date.strftime("%Y%m%d"))) return |
def output_sector_netcdf(self,netcdf_path,out_path,patch_radius,config): """ Segment patches of forecast tracks to only output data contined within a region in the CONUS, as defined by the mapfile. Args: netcdf_path (str): Path to the full CONUS netcdf patch file. out_path (str): Path to output new segmented netcdf fil... |
netcdf files. """ nc_data = self.load_netcdf_data(netcdf_path,patch_radius) if nc_data is not None: out_filename = out_path + "{0}_{1}_{2}_model_patches.nc".format( self.ensemble_name, self.run_date.strftime(self.date_format), self.member) out_file = Dataset(out_filename, "w") out_file.createDimension("p", np.shape(nc_... |
config.watershed_variable meta_variables = ["lon", "lat", "i", "j", "x", "y", "masks"] meta_units = ["degrees_east", "degrees_north", "", "", "m", "m", ""] center_vars = ["time", "centroid_lon", "centroid_lat", "centroid_i", "centroid_j", "track_id", "track_step"] center_units = ["hours since {0}".format(self.run_date.... |
= "f4" m_var = out_file.createVariable(meta_variable, dtype, ("p", "row", "col"), complevel=1, zlib=True) m_var.long_name = meta_variable m_var.units = meta_units[m] for c, center_var in enumerate(center_vars): if center_var in ["time", "track_id", "track_step"]: dtype = "i4" else: dtype = "f4" c_var = out_file.createV... |
storm_variable s_var.units = "" for potential_variable in config.potential_variables: p_var = out_file.createVariable(potential_variable + "_prev", "f4", ("p", "row", "col"), complevel=1, zlib=True) p_var.long_name = potential_variable p_var.units = "" if config.train: for label_column in label_columns: if label_column... |
out_file.variables["centroid_" + c_var][:] = nc_data.variables['centroid_' + c_var][:] for c_var in ["i", "j"]: out_file.variables["centroid_" + c_var][:] = nc_data.variables["centroid_" + c_var][:] out_file.variables["track_id"][:] = nc_data.variables['track_id'][:] out_file.variables["track_step"][:] = nc_data.variab... |
config.train: for label_column in label_columns: try: out_file.variables[label_column][:] = nc_data.variables[label_column][:] except: out_file.variables[label_column][:] = 0 out_file.close() print("Output sector nc file " + out_filename) else: print('No {0} {1} netcdf file/sector data found'.format(self.member, self.r... |
def clean_dict(d0, clean_item_fn=None): """ Return a json-clean dict. Will log info message for failures. """ clean_item_fn = clean_item_fn if clean_item_fn else clean_item d = dict() for key in d0: cleaned_item = clean_item_fn(d0[key]) if cleaned_item is not None: d[key] = cleaned_item return d |
def clean_list(l0, clean_item_fn=None): """ Return a json-clean list. Will log info message for failures. """ clean_item_fn = clean_item_fn if clean_item_fn else clean_item l = list() for index, item in enumerate(l0): cleaned_item = clean_item_fn(item) l.append(cleaned_item) return l |
def clean_tuple(t0, clean_item_fn=None): """ Return a json-clean tuple. Will log info message for failures. """ clean_item_fn = clean_item_fn if clean_item_fn else clean_item l = list() for index, item in enumerate(t0): cleaned_item = clean_item_fn(item) l.append(cleaned_item) return tuple(l) |
def clean_item(i): """ Return a json-clean item or None. Will log info message for failure. """ itype = type(i) if itype == dict: return clean_dict(i) elif itype == list: return clean_list(i) elif itype == tuple: return clean_tuple(i) elif itype == numpy.float32: return float(i) elif itype == numpy.float64: return floa... |
numpy.int32: return int(i) elif itype == numpy.uint32: return int(i) elif itype == numpy.int64: return int(i) elif itype == numpy.uint64: return int(i) elif itype == float: return i elif itype == str: return i elif itype == int: return i elif itype == bool: return i elif itype == type(None): return i logging.info("[1] ... |
def clean_item_no_list(i): """ Return a json-clean item or None. Will log info message for failure. """ itype = type(i) if itype == dict: return clean_dict(i, clean_item_no_list) elif itype == list: return clean_tuple(i, clean_item_no_list) elif itype == tuple: return clean_tuple(i, clean_item_no_list) elif itype == nu... |
elif itype == numpy.int32: return int(i) elif itype == numpy.uint32: return int(i) elif itype == float: return i elif itype == str: return i elif itype == int: return i elif itype == bool: return i elif itype == type(None): return i logging.info("[2] Unable to handle type %s", itype) return None |
def sample_stack_all(count=10, interval=0.1): """Sample the stack in a thread and print it at regular intervals.""" def print_stack_all(l, ll): l1 = list() l1.append("*** STACKTRACE - START ***") code = [] for threadId, stack in sys._current_frames().items(): sub_code = [] sub_code.append("# ThreadID: %s" % threadId) f... |
(line.strip())) if not "in select" in sub_code[-2] and \ not "in wait" in sub_code[-2] and \ not "in print_stack_all" in sub_code[-2] and \ not "in sample_stack_all" in sub_code[-2] and \ not "in checkcache" in sub_code[-2] and \ not "do_sleep" in sub_code[-2] and \ not "sleep" in sub_code[-1] and \ not any(["in do_sam... |
l1.append("*** STACKTRACE - END ***") with l: ll.extend(l1) def do_sample(): l = threading.RLock() ll = list() for i in range(count): print_stack_all(l, ll) time.sleep(interval) with l: print("\n".join(ll)) threading.Thread(target=do_sample).start() |
def decision_function(self, X): "Decision function i.e. the raw data of the prediction" self._X = Model.convert_features(X) self._eval() return self._ind[0].hy |
def _eval(self): "Evaluates a individual using recursion and self._pos as pointer" pos = self._pos self._pos += 1 node = self._ind[pos] if isinstance(node, Function): args = [self._eval() for x in range(node.nargs)] node.eval(args) for x in args: x.hy = None x.hy_test = None else: node.eval(self._X) return node |
def create_random_ind_full(self, depth=0): "Random individual using full method" lst = [] self._create_random_ind_full(depth=depth, output=lst) return lst |
def grow_use_function(self, depth=0): "Select either function or terminal in grow method" if depth == 0: return False if depth == self._depth: return True return np.random.random() < 0.5 |
def create_random_ind_grow(self, depth=0): "Random individual using grow method" lst = [] self._depth = depth self._create_random_ind_grow(depth=depth, output=lst) return lst |
def create_population(self, popsize=1000, min_depth=2, max_depth=4, X=None): "Creates random population using ramped half-and-half method" import itertools args = [x for x in itertools.product(range(min_depth, max_depth+1), [True, False])] index = 0 output = [] while len(output) < popsize: depth, full = args[index] ind... |
not None: x = Individual(ind) x.decision_function(X) flag = x.individual[0].isfinite() l_vars = (flag, len(output), full, depth, len(ind)) l_str = " flag: %s len(output): %s full: %s depth: %s len(ind): %s" self._logger.debug(l_str % l_vars) if flag: output.append(ind) return output |
def decision_function(self, X, **kwargs): "Decision function i.e. the raw data of the prediction" if X is None: return self._hy_test X = self.convert_features(X) if len(X) < self.nvar: _ = 'Number of variables differ, trained with %s given %s' % (self.nvar, len(X)) raise RuntimeError(_) hist = self._hist for node in hi... |
None i.hy_test = None gc.collect() return r |
def fitness_vs(self): "Median Fitness in the validation set" l = [x.fitness_vs for x in self.models] return np.median(l) |
def graphviz(self, directory, **kwargs): "Directory to store the graphviz models" import os if not os.path.isdir(directory): os.mkdir(directory) output = os.path.join(directory, 'evodag-%s') for k, m in enumerate(self.models): m.graphviz(output % k, **kwargs) |
def load_data(self, num_samples=1000, percentiles=None): """ Args: num_samples: Number of random samples at each grid point percentiles: Which percentiles to extract from the random samples Returns: """ self.percentiles = percentiles self.num_samples = num_samples if self.model_name.lower() in ["wrf"]: mo = ModelOutput... |
mo.units else: if self.track_forecasts is None: self.load_track_data() self.units = "mm" self.data = np.zeros((self.forecast_hours.size, self.mapping_data["lon"].shape[0], self.mapping_data["lon"].shape[1]), dtype=np.float32) if self.percentiles is not None: self.percentile_data = np.zeros([len(self.percentiles)] + lis... |
step["properties"][full_condition_name] else: condition = None forecast_time = self.run_date + timedelta(hours=times[s]) if forecast_time in self.times: t = np.where(self.times == forecast_time)[0][0] mask = np.array(step["properties"]["masks"], dtype=int).ravel() rankings = np.argsort(np.array(step["properties"]["time... |
samples = raw_samples.mean(axis=0) if condition >= self.condition_threshold: self.data[t, i, j] = samples else: for p, percentile in enumerate(self.percentiles): if percentile != "mean": if condition >= self.condition_threshold: self.percentile_data[p, t, i, j] = np.percentile(raw_samples, percentile, axis=0) else: if ... |
def neighborhood_probability(self, threshold, radius): """ Calculate a probability based on the number of grid points in an area that exceed a threshold. Args: threshold: radius: Returns: """ weights = disk(radius, dtype=np.uint8) thresh_data = np.zeros(self.data.shape[1:], dtype=np.uint8) neighbor_prob = np.zeros(self... |
= fftconvolve(maximized, weights, mode="same") thresh_data[:] = 0 neighbor_prob[neighbor_prob < 1] = 0 neighbor_prob /= weights.sum() return neighbor_prob |
def encode_grib2_percentile(self): """ Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages """ lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32) lon_0 = self.proj_dict["lon_0"] sw_lon = self.grid_dict["sw_lon"... |
self.data.shape[-2], self.grid_dict["sw_lat"] * lscale, sw_lon * lscale, 0, self.proj_dict["lat_0"] * lscale, lon_0 * lscale, self.grid_dict["dx"] * 1e3, self.grid_dict["dy"] * 1e3, 0b00000000, 0b01000000, self.proj_dict["lat_1"] * lscale, self.proj_dict["lat_2"] * lscale, -90 * lscale, 0] pdtmp1 = np.array([1, # param... |
from NCEP 0, # Hours after reference time data cutoff 0, # Minutes after reference time data cutoff 1, # Forecast time units Hours 0, # Forecast time 1, # Type of first fixed surface Ground 1, # Scale value of first fixed surface 0, # Value of first fixed surface 1, # Type of second fixed surface 1, # Scale value of 2n... |
fixed surface 0, # Value of 2nd fixed surface 0, # Derived forecast type self.num_samples # Number of ensemble members ], dtype=np.int32) grib_objects = pd.Series(index=self.times, data=[None] * self.times.size, dtype=object) drtmp1 = np.array([0, 0, 4, 8, 0], dtype=np.int32) for t, time in enumerate(self.times): time_... |
- self.run_date).total_seconds() / 3600.0 data = self.percentile_data[:, t] / 1000.0 masked_data = np.ma.array(data, mask=data <= 0) for p, percentile in enumerate(self.percentiles): print("GRIB {3} Percentile {0}. Max: {1} Min: {2}".format(percentile, masked_data[p].max(), masked_data[p].min(), time)) if percentile in... |
def encode_grib2_data(self): """ Encodes member percentile data to GRIB2 format. Returns: Series of GRIB2 messages """ lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] gdsinfo = np.array([0, np.product(self.data.shape[-2:]), 0, 0, 30], dtype=np.int32) lon_0 = self.proj_dict["lon_0"] sw_lon = self.grid_dict["sw_lon"] if l... |
self.data.shape[-2], self.grid_dict["sw_lat"] * lscale, sw_lon * lscale, 0, self.proj_dict["lat_0"] * lscale, lon_0 * lscale, self.grid_dict["dx"] * 1e3, self.grid_dict["dy"] * 1e3, 0b00000000, 0b01000000, self.proj_dict["lat_1"] * lscale, self.proj_dict["lat_2"] * lscale, -90 * lscale, 0] pdtmp1 = np.array([1, # param... |
from NCEP 0, # Hours after reference time data cutoff 0, # Minutes after reference time data cutoff 1, # Forecast time units Hours 0, # Forecast time 1, # Type of first fixed surface Ground 1, # Scale value of first fixed surface 0, # Value of first fixed surface 1, # Type of second fixed surface 1, # Scale value of 2n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.