code stringlengths 1 18.2k |
|---|
data_row is not None: label = "Data {}:{}".format(data_index, data_row) elif data_index is not None: label = "Data {}".format(data_index) else: label = "Unknown" fill_color = display_layer.get("fill_color") stroke_color = display_layer.get("stroke_color") legend_entries.append(LegendEntry(label, fill_color, stroke_colo... |
def __update_cursor_info(self): """ Map the mouse to the 1-d position within the line graph. """ if not self.delegate: # allow display to work without delegate return if self.__mouse_in and self.__last_mouse: pos_1d = None axes = self.__axes line_graph_canvas_item = self.line_graph_canvas_item if axes and axes.is_valid... |
px = axes.drawn_left_channel + x * (axes.drawn_right_channel - axes.drawn_left_channel) pos_1d = px, self.delegate.cursor_changed(pos_1d) |
def find_model_patch_tracks(self): """ Identify storms in gridded model output and extract uniform sized patches around the storm centers of mass. Returns: """ self.model_grid.load_data() tracked_model_objects = [] model_objects = [] if self.model_grid.data is None: print("No model output found") return tracked_model_o... |
storms at each time step and apply size filter print("Finding {0} objects for run {1} Hour: {2:02d}".format(self.ensemble_member, self.run_date.strftime("%Y%m%d%H"), hour)) if self.mask is not None: model_data = self.model_grid.data[h] * self.mask else: model_data = self.model_grid.data[h] model_data[:self.patch_radius... |
model_data, self.model_grid.x, self.model_grid.y, [hour], dx=self.model_grid.dx, patch_radius=self.patch_radius)) for model_obj in model_objects[-1]: dims = model_obj.timesteps[-1].shape if h > 0: model_obj.estimate_motion(hour, self.model_grid.data[h-1], dims[1], dims[0]) del scaled_data del model_data del hour_labels... |
def find_model_tracks(self): """ Identify storms at each model time step and link them together with object matching. Returns: List of STObjects containing model track information. """ self.model_grid.load_data() model_objects = [] tracked_model_objects = [] if self.model_grid.data is None: print("No model output found... |
{1} Hour: {2:02d}".format(self.ensemble_member, self.run_date.strftime("%Y%m%d%H"), hour)) if self.mask is not None: model_data = self.model_grid.data[h] * self.mask else: model_data = self.model_grid.data[h] # remember orig values min_orig = self.model_ew.min_thresh max_orig = self.model_ew.max_thresh data_increment_o... |
self.size_filter) # Return to orig values self.model_ew.min_thresh = min_orig self.model_ew.max_thresh = max_orig self.model_ew.data_increment = data_increment_orig obj_slices = find_objects(hour_labels) num_slices = len(obj_slices) model_objects.append([]) if num_slices > 0: for s, sl in enumerate(obj_slices): model_o... |
h, hour in enumerate(self.hours): past_time_objs = [] for obj in tracked_model_objects: # Potential trackable objects are identified if obj.end_time == hour - 1: past_time_objs.append(obj) # If no objects existed in the last time step, then consider objects in current time step all new if len(past_time_objs) == 0: trac... |
> 0: assignments = self.object_matcher.match_objects(past_time_objs, model_objects[h], hour - 1, hour) unpaired = list(range(len(model_objects[h]))) for pair in assignments: past_time_objs[pair[0]].extend(model_objects[h][pair[1]]) unpaired.remove(pair[1]) if len(unpaired) > 0: for up in unpaired: tracked_model_objects... |
def find_mrms_tracks(self): """ Identify objects from MRMS timesteps and link them together with object matching. Returns: List of STObjects containing MESH track information. """ obs_objects = [] tracked_obs_objects = [] if self.mrms_ew is not None: self.mrms_grid.load_data() if len(self.mrms_grid.data) != len(self.ho... |
= 0 hour_labels = self.mrms_ew.size_filter(self.mrms_ew.label(gaussian_filter(mrms_data, self.gaussian_window)), self.size_filter) hour_labels[mrms_data < self.mrms_ew.min_thresh] = 0 obj_slices = find_objects(hour_labels) num_slices = len(obj_slices) obs_objects.append([]) if num_slices > 0: for sl in obj_slices: obs_... |
obj.end_time == hour - 1: past_time_objs.append(obj) if len(past_time_objs) == 0: tracked_obs_objects.extend(obs_objects[h]) elif len(past_time_objs) > 0 and len(obs_objects[h]) > 0: assignments = self.object_matcher.match_objects(past_time_objs, obs_objects[h], hour - 1, hour) unpaired = list(range(len(obs_objects[h])... |
def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False): """ Match forecast and observed tracks. Args: model_tracks: obs_tracks: unique_matches: closest_matches: Returns: """ if unique_matches: pairings = self.track_matcher.match_tracks(model_tracks, obs_tracks, closest_matches=clos... |
def extract_model_attributes(self, tracked_model_objects, storm_variables, potential_variables, tendency_variables=None, future_variables=None): """ Extract model attribute data for each model track. Storm variables are those that describe the model storm directly, such as radar reflectivity or updraft helicity. Potent... |
values. Examples of potential variables include CAPE, shear, temperature, and dewpoint. Future variables are fields that occur in the hour after the extracted field. Args: tracked_model_objects: List of STObjects describing each forecasted storm storm_variables: List of storm variable names potential_variables: List of... |
[] model_grids = {} for l_var in ["lon", "lat"]: for model_obj in tracked_model_objects: model_obj.extract_attribute_array(getattr(self.model_grid, l_var), l_var) for storm_var in storm_variables: print("Storm {0} {1} {2}".format(storm_var,self.ensemble_member, self.run_date.strftime("%Y%m%d"))) model_grids[storm_var] ... |
self.run_date.strftime("%Y%m%d"))) if potential_var not in model_grids.keys(): model_grids[potential_var] = ModelOutput(self.ensemble_name, self.ensemble_member, self.run_date, potential_var, self.start_date - timedelta(hours=1), self.end_date + timedelta(hours=1), self.model_path, self.model_map_file, self.sector_ind_... |
self.model_path, self.model_map_file, self.sector_ind_path,self.single_step) model_grids[future_var].load_data() for model_obj in tracked_model_objects: model_obj.extract_attribute_grid(model_grids[future_var], future=True) if future_var not in tendency_variables: del model_grids[future_var] for tendency_var in tendenc... |
def match_hail_sizes(model_tracks, obs_tracks, track_pairings): """ Given forecast and observed track pairings, maximum hail sizes are associated with each paired forecast storm track timestep. If the duration of the forecast and observed tracks differ, then interpolation is used for the intermediate timesteps. Args: m... |
observed) tracks """ unpaired = list(range(len(model_tracks))) for p, pair in enumerate(track_pairings): model_track = model_tracks[pair[0]] unpaired.remove(pair[0]) obs_track = obs_tracks[pair[1]] obs_hail_sizes = np.array([step[obs_track.masks[t] == 1].max() for t, step in enumerate(obs_track.timesteps)]) if obs_trac... |
fill_value=0) model_track.observations = hail_interp(normalized_model_times) elif obs_track.times.size == 1: model_track.observations = np.ones(model_track.times.shape) * obs_hail_sizes[0] elif model_track.times.size == 1: model_track.observations = np.array([obs_hail_sizes.max()]) print(pair[0], "obs", obs_hail_sizes)... |
def match_hail_size_step_distributions(self, model_tracks, obs_tracks, track_pairings): """ Given a matching set of observed tracks for each model track, Args: model_tracks: obs_tracks: track_pairings: Returns: """ label_columns = ["Matched", "Max_Hail_Size", "Num_Matches", "Shape", "Location", "Scale"] s = 0 for m, mo... |
> 0: all_hail_sizes = [] step_pairs = track_pairings.loc[s, "Pairings"] for step_pair in step_pairs: obs_step = obs_tracks[step_pair[0]].timesteps[step_pair[1]].ravel() obs_mask = obs_tracks[step_pair[0]].masks[step_pair[1]].ravel() all_hail_sizes.append(obs_step[(obs_mask == 1) & (obs_step >= self.mrms_ew.min_thresh)]... |
def calc_track_errors(model_tracks, obs_tracks, track_pairings): """ Calculates spatial and temporal translation errors between matched forecast and observed tracks. Args: model_tracks: List of model track STObjects obs_tracks: List of observed track STObjects track_pairings: List of tuples pairing forecast and observe... |
model_track = model_tracks[pair[0]] if type(pair[1]) in [int, np.int64]: obs_track = obs_tracks[pair[1]] else: obs_track = obs_tracks[pair[1][0]] model_com = model_track.center_of_mass(model_track.start_time) obs_com = obs_track.center_of_mass(obs_track.start_time) track_errors.loc[pair[0], 'obs_track_id'] = pair[1] if... |
def persistent_object_context_changed(self): """ Override from PersistentObject. """ super().persistent_object_context_changed() def change_registration(registered_object, unregistered_object): if registered_object and registered_object.uuid == self.parent_uuid: self.__parent = registered_object if self.persistent_obje... |
def persistent_object_context_changed(self): """ Override from PersistentObject. """ super().persistent_object_context_changed() def register(): if self.__source is not None and self.__target is not None: assert not self.__binding self.__binding = Binding.PropertyBinding(self.__source, self.source_property) self.__bind... |
self.__source = source register() def target_registered(target): self.__target = target def property_changed(target, property_name): if property_name == self.target_property: self.__set_source_from_target(getattr(target, property_name)) assert self.__target_property_changed_listener is None self.__target_property_chang... |
if registered_object and registered_object.uuid == self.source_uuid: source_registered(registered_object) if registered_object and registered_object.uuid == self.target_uuid: target_registered(registered_object) if unregistered_object and unregistered_object in (self._source, self._target): unregistered(unregistered_ob... |
def persistent_object_context_changed(self): """ Override from PersistentObject. """ super().persistent_object_context_changed() def detach(): for listener in self.__interval_mutated_listeners: listener.close() self.__interval_mutated_listeners = list() def reattach(): detach() interval_descriptors = list() if self.__s... |
key == "graphics" and self.__target: reattach() def source_registered(source): self.__source = source self.__item_inserted_event_listener = self.__source.item_inserted_event.listen(item_inserted) self.__item_removed_event_listener = self.__source.item_removed_event.listen(item_removed) reattach() def target_registered(... |
def __display_for_tree_node(self, tree_node): """ Return the text display for the given tree node. Based on number of keys associated with tree node. """ keys = tree_node.keys if len(keys) == 1: return "{0} ({1})".format(tree_node.keys[-1], tree_node.count) elif len(keys) == 2: months = (_("January"), _("February"), _(... |
_("Thursday"), _("Friday"), _("Saturday"), _("Sunday")) date = datetime.date(tree_node.keys[0], tree_node.keys[1], tree_node.keys[2]) return "{0} - {1} ({2})".format(tree_node.keys[2], weekdays[date.weekday()], tree_node.count) |
def __insert_child(self, parent_tree_node, index, tree_node): """ Called from the root tree node when a new node is inserted into tree. This method creates properties to represent the node for display and inserts it into the item model controller. """ # manage the item model parent_item = self.__mapping[id(parent_tree_... |
lookup } item = self.item_model_controller.create_item(properties) parent_item.insert_child(index, item) self.__mapping[id(tree_node)] = item self.item_model_controller.end_insert() |
def __remove_child(self, parent_tree_node, index): """ Called from the root tree node when a node is removed from the tree. This method removes it into the item model controller. """ # get parent and item parent_item = self.__mapping[id(parent_tree_node)] # manage the item model self.item_model_controller.begin_remove(... |
def update_all_nodes(self): """ Update all tree item displays if needed. Usually for count updates. """ item_model_controller = self.item_model_controller if item_model_controller: if self.__node_counts_dirty: for item in self.__mapping.values(): if "tree_node" in item.data: # don't update the root node tree_node = ite... |
def date_browser_selection_changed(self, selected_indexes): """ Called to handle selection changes in the tree widget. This method should be connected to the on_selection_changed event. This method builds a list of keys represented by all selected items. It then provides date_filter to filter data items based on the li... |
list of ints """ partial_date_filters = list() for index, parent_row, parent_id in selected_indexes: item_model_controller = self.item_model_controller tree_node = item_model_controller.item_value("tree_node", index, parent_id) partial_date_filters.append(ListModel.PartialDateFilter("created_local", *tree_node.keys)) i... |
def text_filter_changed(self, text): """ Called to handle changes to the text filter. :param text: The text for the filter. """ text = text.strip() if text else None if text is not None: self.__text_filter = ListModel.TextFilter("text_for_filter", text) else: self.__text_filter = None self.__update_filter() |
def __update_filter(self): """ Create a combined filter. Set the resulting filter into the document controller. """ filters = list() if self.__date_filter: filters.append(self.__date_filter) if self.__text_filter: filters.append(self.__text_filter) self.document_controller.display_filter = ListModel.AndFilter(filters) |
def __get_keys(self): """ Return the keys associated with this node by adding its key and then adding parent keys recursively. """ keys = list() tree_node = self while tree_node is not None and tree_node.key is not None: keys.insert(0, tree_node.key) tree_node = tree_node.parent return keys |
def insert_value(self, keys, value): """ Insert a value (data item) into this tree node and then its children. This will be called in response to a new data item being inserted into the document. Also updates the tree node's cumulative child count. """ self.count += 1 if not self.key: self.__value_reverse_mapping[value... |
TreeNode(key, reversed=self.reversed)) if index == len(self.children) or self.children[index].key != key: new_tree_node = TreeNode(key, list(), reversed=self.reversed) new_tree_node.child_inserted = self.child_inserted new_tree_node.child_removed = self.child_removed new_tree_node.tree_node_updated = self.tree_node_upd... |
def remove_value(self, keys, value): """ Remove a value (data item) from this tree node and its children. Also updates the tree node's cumulative child count. """ self.count -= 1 if not self.key: keys = self.__value_reverse_mapping[value] del self.__value_reverse_mapping[value] if len(keys) == 0: self.values.remove(val... |
if self.children[index].count == 0: del self.children[index] if self.child_removed: self.child_removed(self, index) |
def label_storm_objects(data, method, min_intensity, max_intensity, min_area=1, max_area=100, max_range=1, increment=1, gaussian_sd=0): """ From a 2D grid or time series of 2D grids, this method labels storm objects with either the Enhanced Watershed or Hysteresis methods. Args: data: the gridded data to be labeled. Sh... |
method: "ew" or "watershed" for Enhanced Watershed or "hyst" for hysteresis min_intensity: Minimum intensity threshold for gridpoints contained within any objects max_intensity: For watershed, any points above max_intensity are considered as the same value as max intensity. For hysteresis, all objects have to contain a... |
pixels. max_area: (default 100) The area threshold in pixels at which the enhanced watershed ends growth. Object area may exceed this threshold if the pixels at the last watershed level exceed the object area. max_range: Maximum difference between the maximum and minimum value in an enhanced watershed object before gro... |
filter applied to data Returns: label_grid: an ndarray with the same shape as data in which each pixel is labeled with a positive integer value. """ if method.lower() in ["ew", "watershed"]: labeler = EnhancedWatershed(min_intensity, increment, max_intensity, max_area, max_range) else: labeler = Hysteresis(min_intensit... |
else: label_grid = np.zeros(data.shape, dtype=int) for t in range(data.shape[0]): label_grid[t] = labeler.label(gaussian_filter(data[t], gaussian_sd)) label_grid[t][data[t] < min_intensity] = 0 if min_area > 1: label_grid[t] = labeler.size_filter(label_grid[t], min_area) return label_grid |
def extract_storm_objects(label_grid, data, x_grid, y_grid, times, dx=1, dt=1, obj_buffer=0): """ After storms are labeled, this method extracts the storm objects from the grid and places them into STObjects. The STObjects contain intensity, location, and shape information about each storm at each timestep. Args: label... |
of x-coordinate data, preferably on a uniform spatial grid with units of length. y_grid: 2D array of y-coordinate data. times: List or array of time values, preferably as integers dx: grid spacing in same units as x_grid and y_grid. dt: period elapsed between times obj_buffer: number of extra pixels beyond bounding box... |
containing STObjects identified at each time. """ storm_objects = [] if len(label_grid.shape) == 3: ij_grid = np.indices(label_grid.shape[1:]) for t, time in enumerate(times): storm_objects.append([]) object_slices = list(find_objects(label_grid[t], label_grid[t].max())) if len(object_slices) > 0: for o, obj_slice in e... |
o + 1, 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], time, time, dx=dx, step=dt)) if t > 0: dims = storm_objects[-1][-1].timesteps[0].shape storm_objects[-1][-1].estimate_motion(time, data[t - 1], dims[1], dims[0]) else: ij_grid = np.indices(label_grid.sh... |
enumerate(obj_slice)] else: obj_slice_buff = obj_slice storm_objects[-1].append(STObject(data[obj_slice_buff], np.where(label_grid[obj_slice_buff] == o + 1, 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], times, times, dx=dx, step=dt)) return storm_objects |
def extract_storm_patches(label_grid, data, x_grid, y_grid, times, dx=1, dt=1, patch_radius=16): """ After storms are labeled, this method extracts boxes of equal size centered on each storm from the grid and places them into STObjects. The STObjects contain intensity, location, and shape information about each storm a... |
to label_storm_objects. x_grid: 2D array of x-coordinate data, preferably on a uniform spatial grid with units of length. y_grid: 2D array of y-coordinate data. times: List or array of time values, preferably as integers dx: grid spacing in same units as x_grid and y_grid. dt: period elapsed between times patch_radius:... |
lists containing STObjects identified at each time. """ storm_objects = [] if len(label_grid.shape) == 3: ij_grid = np.indices(label_grid.shape[1:]) for t, time in enumerate(times): storm_objects.append([]) # object_slices = find_objects(label_grid[t], label_grid[t].max()) centers = list(center_of_mass(data[t], labels=... |
np.where(label_grid[t][obj_slice_buff] == o + 1, 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], time, time, dx=dx, step=dt)) if t > 0: dims = storm_objects[-1][-1].timesteps[0].shape storm_objects[-1][-1].estimate_motion(time, data[t - 1], dims[1], dims[0]... |
int_center[1] + patch_radius)) storm_objects[-1].append(STObject(data[obj_slice_buff], np.where(label_grid[obj_slice_buff] == o + 1, 1, 0), x_grid[obj_slice_buff], y_grid[obj_slice_buff], ij_grid[0][obj_slice_buff], ij_grid[1][obj_slice_buff], times[0], times[0], dx=dx, step=dt)) return storm_objects |
def track_storms(storm_objects, times, distance_components, distance_maxima, distance_weights, tracked_objects=None): """ Given the output of extract_storm_objects, this method tracks storms through time and merges individual STObjects into a set of tracks. Args: storm_objects: list of list of STObjects that have not b... |
of maximum values for each distance for normalization purposes distance_weights: weight given to each component of the distance function. Should add to 1. tracked_objects: List of STObjects that have already been tracked. Returns: tracked_objects: """ obj_matcher = ObjectMatcher(distance_components, distance_weights, d... |
obj.step: past_time_objects.append(obj) if len(past_time_objects) == 0: tracked_objects.extend(storm_objects[t]) elif len(past_time_objects) > 0 and len(storm_objects[t]) > 0: assignments = obj_matcher.match_objects(past_time_objects, storm_objects[t], times[t-1], times[t]) unpaired = list(range(len(storm_objects[t])))... |
def peirce_skill_score(self): """ Multiclass Peirce Skill Score (also Hanssen and Kuipers score, True Skill Score) """ n = float(self.table.sum()) nf = self.table.sum(axis=1) no = self.table.sum(axis=0) correct = float(self.table.trace()) return (correct / n - (nf * no).sum() / n ** 2) / (1 - (no * no).sum() / n ** 2) |
def gerrity_score(self): """ Gerrity Score, which weights each cell in the contingency table by its observed relative frequency. :return: """ k = self.table.shape[0] n = float(self.table.sum()) p_o = self.table.sum(axis=0) / n p_sum = np.cumsum(p_o)[:-1] a = (1.0 - p_sum) / p_sum s = np.zeros(self.table.shape, dtype=fl... |
/ a[0:j]) + np.sum(a[j:k-1])) elif i < j: s[i, j] = 1.0 / (k - 1.0) * (np.sum(1.0 / a[0:i]) - (j - i) + np.sum(a[j:k-1])) else: s[i, j] = s[j, i] return np.sum(self.table / float(self.table.sum()) * s) |
def centroid_distance(item_a, time_a, item_b, time_b, max_value): """ Euclidean distance between the centroids of item_a and item_b. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated ... |
= item_a.center_of_mass(time_a) bx, by = item_b.center_of_mass(time_b) return np.minimum(np.sqrt((ax - bx) ** 2 + (ay - by) ** 2), max_value) / float(max_value) |
def shifted_centroid_distance(item_a, time_a, item_b, time_b, max_value): """ Centroid distance with motion corrections. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: M... |
= item_b.center_of_mass(time_b) if time_a < time_b: bx = bx - item_b.u by = by - item_b.v else: ax = ax - item_a.u ay = ay - item_a.v return np.minimum(np.sqrt((ax - bx) ** 2 + (ay - by) ** 2), max_value) / float(max_value) |
def closest_distance(item_a, time_a, item_b, time_b, max_value): """ Euclidean distance between the pixels in item_a and item_b closest to each other. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time intege... |
1. """ return np.minimum(item_a.closest_distance(time_a, item_b, time_b), max_value) / float(max_value) |
def ellipse_distance(item_a, time_a, item_b, time_b, max_value): """ Calculate differences in the properties of ellipses fitted to each object. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being... |
ts = np.array([0, np.pi]) ell_a = item_a.get_ellipse_model(time_a) ell_b = item_b.get_ellipse_model(time_b) ends_a = ell_a.predict_xy(ts) ends_b = ell_b.predict_xy(ts) distances = np.sqrt((ends_a[:, 0:1] - ends_b[:, 0:1].T) ** 2 + (ends_a[:, 1:] - ends_b[:, 1:].T) ** 2) return np.minimum(distances[0, 1], max_value) / f... |
def nonoverlap(item_a, time_a, item_b, time_b, max_value): """ Percentage of pixels in each object that do not overlap with the other object Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being ev... |
and 1. """ return np.minimum(1 - item_a.count_overlap(time_a, item_b, time_b), max_value) / float(max_value) |
def max_intensity(item_a, time_a, item_b, time_b, max_value): """ RMS difference in maximum intensity Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distance val... |
diff = np.sqrt((intensity_a - intensity_b) ** 2) return np.minimum(diff, max_value) / float(max_value) |
def area_difference(item_a, time_a, item_b, time_b, max_value): """ RMS Difference in object areas. Args: item_a: STObject from the first set in ObjectMatcher time_a: Time integer being evaluated item_b: STObject from the second set in ObjectMatcher time_b: Time integer being evaluated max_value: Maximum distance value... |
diff = np.sqrt((size_a - size_b) ** 2) return np.minimum(diff, max_value) / float(max_value) |
def mean_minimum_centroid_distance(item_a, item_b, max_value): """ RMS difference in the minimum distances from the centroids of one track to the centroids of another track Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value us... |
in item_a.times]) centroids_b = np.array([item_b.center_of_mass(t) for t in item_b.times]) distance_matrix = (centroids_a[:, 0:1] - centroids_b.T[0:1]) ** 2 + (centroids_a[:, 1:] - centroids_b.T[1:]) ** 2 mean_min_distances = np.sqrt(distance_matrix.min(axis=0).mean() + distance_matrix.min(axis=1).mean()) return np.min... |
def mean_min_time_distance(item_a, item_b, max_value): """ Calculate the mean time difference among the time steps in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. ... |
- times_b) ** 2 mean_min_distances = np.sqrt(distance_matrix.min(axis=0).mean() + distance_matrix.min(axis=1).mean()) return np.minimum(mean_min_distances, max_value) / float(max_value) |
def start_centroid_distance(item_a, item_b, max_value): """ Distance between the centroids of the first step in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Return... |
2 + (start_a[1] - start_b[1]) ** 2) return np.minimum(start_distance, max_value) / float(max_value) |
def start_time_distance(item_a, item_b, max_value): """ Absolute difference between the starting times of each item. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Returns: Dista... |
def duration_distance(item_a, item_b, max_value): """ Absolute difference in the duration of two items Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Returns: Distance value betw... |
def mean_area_distance(item_a, item_b, max_value): """ Absolute difference in the means of the areas of each track over time. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scaling value and upper constraint. Retur... |
for t in item_b.times]) return np.abs(mean_area_a - mean_area_b) / float(max_value) |
def match_objects(self, set_a, set_b, time_a, time_b): """ Match two sets of objects at particular times. Args: set_a: list of STObjects set_b: list of STObjects time_a: time at which set_a is being evaluated for matching time_b: time at which set_b is being evaluated for matching Returns: List of tuples containing (se... |
100 min_row_costs = costs.min(axis=1) min_col_costs = costs.min(axis=0) good_rows = np.where(min_row_costs < 100)[0] good_cols = np.where(min_col_costs < 100)[0] assignments = [] if len(good_rows) > 0 and len(good_cols) > 0: munk = Munkres() initial_assignments = munk.compute(costs[tuple(np.meshgrid(good_rows, good_col... |
def cost_matrix(self, set_a, set_b, time_a, time_b): """ Calculates the costs (distances) between the items in set a and set b at the specified times. Args: set_a: List of STObjects set_b: List of STObjects time_a: time at which objects in set_a are evaluated time_b: time at whcih object in set_b are evaluated Returns:... |
the items in set a and the items in set b. """ costs = np.zeros((len(set_a), len(set_b))) for a, item_a in enumerate(set_a): for b, item_b in enumerate(set_b): costs[a, b] = self.total_cost_function(item_a, item_b, time_a, time_b) return costs |
def total_cost_function(self, item_a, item_b, time_a, time_b): """ Calculate total cost function between two items. Args: item_a: STObject item_b: STObject time_a: Timestep in item_a at which cost function is evaluated time_b: Timestep in item_b at which cost function is evaluated Returns: The total weighted distance b... |
total_distance = np.sum(self.weights * distances) return total_distance |
def match_tracks(self, set_a, set_b, closest_matches=False): """ Find the optimal set of matching assignments between set a and set b. This function supports optimal 1:1 matching using the Munkres method and matching from every object in set a to the closest object in set b. In this situation set b accepts multiple mat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.