text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_file(self, filename, time_units="seconds since 1970-01-01T00:00"): """ Initializes netCDF file for writing Args: filename: Name of the netCDF file time_...
if os.access(filename, os.R_OK): out_data = Dataset(filename, "r+") else: out_data = Dataset(filename, "w") if len(self.data.shape) == 2: for d, dim in enumerate(["y", "x"]): out_data.createDimension(dim, self.data.shape[d]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_to_file(self, out_data): """ Outputs data to a netCDF file. If the file does not exist, it will be created. Otherwise, additional variables are appende...
full_var_name = self.consensus_type + "_" + self.variable if "-hour" in self.consensus_type: if full_var_name not in out_data.variables.keys(): var = out_data.createVariable(full_var_name, "f4", ("y", "x"), zlib=True, least_sign...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def restore(self, workspace_uuid): """ Restore the workspace to the given workspace_uuid. If workspace_uuid is None then create a new workspace and use it. """
workspace = next((workspace for workspace in self.document_model.workspaces if workspace.uuid == workspace_uuid), None) if workspace is None: workspace = self.new_workspace() self._change_workspace(workspace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_workspace(self, name=None, layout=None, workspace_id=None, index=None) -> WorkspaceLayout.WorkspaceLayout: """ Create a new workspace, insert into documen...
workspace = WorkspaceLayout.WorkspaceLayout() self.document_model.insert_workspace(index if index is not None else len(self.document_model.workspaces), workspace) d = create_image_desc() d["selected"] = True workspace.layout = layout if layout is not None else d workspac...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_workspace(self, name, layout, workspace_id): """Looks for a workspace with workspace_id. If none is found, create a new one, add it, and change to it....
workspace = next((workspace for workspace in self.document_model.workspaces if workspace.workspace_id == workspace_id), None) if not workspace: workspace = self.new_workspace(name=name, layout=layout, workspace_id=workspace_id) self._change_workspace(workspace)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_workspace(self) -> None: """ Pose a dialog to name and create a workspace. """
def create_clicked(text): if text: command = Workspace.CreateWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(command) self.pose_get_string_message_box(caption=_("Enter a name for the workspace"), tex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rename_workspace(self) -> None: """ Pose a dialog to rename the workspace. """
def rename_clicked(text): if len(text) > 0: command = Workspace.RenameWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(command) self.pose_get_string_message_box(caption=_("Enter new name for workspace...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_workspace(self): """ Pose a dialog to confirm removal then remove workspace. """
def confirm_clicked(): if len(self.document_model.workspaces) > 1: command = Workspace.RemoveWorkspaceCommand(self) command.perform() self.document_controller.push_undo_command(command) caption = _("Remove workspace named '{0}'?").format(sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clone_workspace(self) -> None: """ Pose a dialog to name and clone a workspace. """
def clone_clicked(text): if text: command = Workspace.CloneWorkspaceCommand(self, text) command.perform() self.document_controller.push_undo_command(command) self.pose_get_string_message_box(caption=_("Enter a name for the workspace"), text=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bootstrap(score_objs, n_boot=1000): """ Given a set of DistributedROC or DistributedReliability objects, this function performs a bootstrap resampling of the...
all_samples = np.random.choice(score_objs, size=(n_boot, len(score_objs)), replace=True) return all_samples.sum(axis=1)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, forecasts, observations): """ Update the ROC curve with a set of forecasts and observations Args: forecasts: 1D array of forecast values observa...
for t, threshold in enumerate(self.thresholds): tp = np.count_nonzero((forecasts >= threshold) & (observations >= self.obs_threshold)) fp = np.count_nonzero((forecasts >= threshold) & (observations < self.obs_threshold)) fn = np.count_nonzer...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(self, other_roc): """ Ingest the values of another DistributedROC object into this one and update the statistics inplace. Args: other_roc: another Dist...
if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.thresholds == self.thresholds): self.contingency_tables += other_roc.contingency_tables else: print("Input table thresholds do not match.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def performance_curve(self): """ Calculate the Probability of Detection and False Alarm Ratio in order to output a performance diagram. Returns: pandas.DataFrame...
pod = self.contingency_tables["TP"] / (self.contingency_tables["TP"] + self.contingency_tables["FN"]) far = self.contingency_tables["FP"] / (self.contingency_tables["FP"] + self.contingency_tables["TP"]) far[(self.contingency_tables["FP"] + self.contingency_tables["TP"]) == 0] = np.nan ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_csi(self): """ Calculate the maximum Critical Success Index across all probability thresholds Returns: The maximum CSI as a float """
csi = self.contingency_tables["TP"] / (self.contingency_tables["TP"] + self.contingency_tables["FN"] + self.contingency_tables["FP"]) return csi.max()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_contingency_tables(self): """ Create an Array of ContingencyTable objects for each probability threshold. Returns: Array of ContingencyTable objects """
return np.array([ContingencyTable(*ct) for ct in self.contingency_tables.values])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def from_str(self, in_str): """ Read the DistributedROC string and parse the contingency table values from it. Args: in_str (str): The string output from the __...
parts = in_str.split(";") for part in parts: var_name, value = part.split(":") if var_name == "Obs_Threshold": self.obs_threshold = float(value) elif var_name == "Thresholds": self.thresholds = np.array(value.split(), dtype=float) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, forecasts, observations): """ Update the statistics with a set of forecasts and observations. Args: forecasts (numpy.ndarray): Array of forecas...
for t, threshold in enumerate(self.thresholds[:-1]): self.frequencies.loc[t, "Positive_Freq"] += np.count_nonzero((threshold <= forecasts) & (forecasts < self.thresholds[t+1]) & ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(self, other_rel): """ Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability obje...
if other_rel.thresholds.size == self.thresholds.size and np.all(other_rel.thresholds == self.thresholds): self.frequencies += other_rel.frequencies else: print("Input table thresholds do not match.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reliability_curve(self): """ Calculates the reliability diagram statistics. The key columns are Bin_Start and Positive_Relative_Freq Returns: pandas.DataFram...
total = self.frequencies["Total_Freq"].sum() curve = pd.DataFrame(columns=["Bin_Start", "Bin_End", "Bin_Center", "Positive_Relative_Freq", "Total_Relative_Freq"]) curve["Bin_Start"] = self.thresholds[:-1] curve["Bin_End"] = self.thresholds[1:] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brier_score(self): """ Calculate the Brier Score """
reliability, resolution, uncertainty = self.brier_score_components() return reliability - resolution + uncertainty
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def brier_skill_score(self): """ Calculate the Brier Skill Score """
reliability, resolution, uncertainty = self.brier_score_components() return (resolution - reliability) / uncertainty
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, forecasts, observations): """ Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Funct...
if len(observations.shape) == 1: obs_cdfs = np.zeros((observations.size, self.thresholds.size)) for o, observation in enumerate(observations): obs_cdfs[o, self.thresholds >= observation] = 1 else: obs_cdfs = observations self.errors["F_2"] += ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crps(self): """ Calculates the continuous ranked probability score. """
return np.sum(self.errors["F_2"].values - self.errors["F_O"].values * 2.0 + self.errors["O_2"].values) / \ (self.thresholds.size * self.num_forecasts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crps_climo(self): """ Calculate the climatological CRPS. """
o_bar = self.errors["O"].values / float(self.num_forecasts) crps_c = np.sum(self.num_forecasts * (o_bar ** 2) - o_bar * self.errors["O"].values * 2.0 + self.errors["O_2"].values) / float(self.thresholds.size * self.num_forecasts) return crps_c
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crpss(self): """ Calculate the continous ranked probability skill score from existing data. """
crps_f = self.crps() crps_c = self.crps_climo() return 1.0 - float(crps_f) / float(crps_c)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def has_metadata_value(metadata_source, key: str) -> bool: """Return whether the metadata value for the given key exists. There are a set of predefined keys that,...
desc = session_key_map.get(key) if desc is not None: d = getattr(metadata_source, "session_metadata", dict()) for k in desc['path'][:-1]: d = d.setdefault(k, dict()) if d is not None else None if d is not None: return desc['path'][-1] in d desc = key_map.get...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete_metadata_value(metadata_source, key: str) -> None: """Delete the metadata value for the given key. There are a set of predefined keys that, when used, ...
desc = session_key_map.get(key) if desc is not None: d0 = getattr(metadata_source, "session_metadata", dict()) d = d0 for k in desc['path'][:-1]: d = d.setdefault(k, dict()) if d is not None else None if d is not None and desc['path'][-1] in d: d.pop(des...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_y_ticks(self, plot_height): """Calculate the y-axis items dependent on the plot height."""
calibrated_data_min = self.calibrated_data_min calibrated_data_max = self.calibrated_data_max calibrated_data_range = calibrated_data_max - calibrated_data_min ticker = self.y_ticker y_ticks = list() for tick_value, tick_label in zip(ticker.values, ticker.labels): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calculate_x_ticks(self, plot_width): """Calculate the x-axis items dependent on the plot width."""
x_calibration = self.x_calibration uncalibrated_data_left = self.__uncalibrated_left_channel uncalibrated_data_right = self.__uncalibrated_right_channel calibrated_data_left = x_calibration.convert_to_calibrated_value(uncalibrated_data_left) if x_calibration is not None else uncalibr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size_to_content(self): """ Size the canvas item to the proper height. """
new_sizing = self.copy_sizing() new_sizing.minimum_height = 0 new_sizing.maximum_height = 0 axes = self.__axes if axes and axes.is_valid: if axes.x_calibration and axes.x_calibration.units: new_sizing.minimum_height = self.font_size + 4 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size_to_content(self, get_font_metrics_fn): """ Size the canvas item to the proper width, the maximum of any label. """
new_sizing = self.copy_sizing() new_sizing.minimum_width = 0 new_sizing.maximum_width = 0 axes = self.__axes if axes and axes.is_valid: # calculate the width based on the label lengths font = "{0:d}px".format(self.font_size) max_width = 0 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size_to_content(self): """ Size the canvas item to the proper width. """
new_sizing = self.copy_sizing() new_sizing.minimum_width = 0 new_sizing.maximum_width = 0 axes = self.__axes if axes and axes.is_valid: if axes.y_calibration and axes.y_calibration.units: new_sizing.minimum_width = self.font_size + 4 n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_snippet_content(snippet_name, **format_kwargs): """ Load the content from a snippet file which exists in SNIPPETS_ROOT """
filename = snippet_name + '.snippet' snippet_file = os.path.join(SNIPPETS_ROOT, filename) if not os.path.isfile(snippet_file): raise ValueError('could not find snippet with name ' + filename) ret = helpers.get_file_content(snippet_file) if format_kwargs: ret = ret.format(**format_kw...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_display_properties(self, display_calibration_info, display_properties: typing.Mapping, display_layers: typing.Sequence[typing.Mapping]) -> None: """Upd...
# may be called from thread; prevent a race condition with closing. with self.__closing_lock: if self.__closed: return displayed_dimensional_scales = display_calibration_info.displayed_dimensional_scales displayed_dimensional_calibrations = display_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __view_to_selected_graphics(self, data_and_metadata: DataAndMetadata.DataAndMetadata) -> None: """Change the view to encompass the selected graphic intervals....
all_graphics = self.__graphics graphics = [graphic for graphic_index, graphic in enumerate(all_graphics) if self.__graphic_selection.contains(graphic_index)] intervals = list() for graphic in graphics: if isinstance(graphic, Graphics.IntervalGraphic): interva...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 and line_graph_c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_objects min_orig = self.model_ew.min_thresh max_orig = self.model_ew.max_thresh ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_mrms_tracks(self): """ Identify objects from MRMS timesteps and link them together with object matching. Returns: List of STObjects containing MESH trac...
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.hours): print('Less than 24 hours of observation data found') return tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False): """ Match forecast and observed tracks. Args: model_tracks: obs_tra...
if unique_matches: pairings = self.track_matcher.match_tracks(model_tracks, obs_tracks, closest_matches=closest_matches) else: pairings = self.track_matcher.neighbor_matches(model_tracks, obs_tracks) return pairings
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def match_hail_sizes(model_tracks, obs_tracks, track_pairings): """ Given forecast and observed track pairings, maximum hail sizes are associated with each paire...
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() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_track_errors(model_tracks, obs_tracks, track_pairings): """ Calculates spatial and temporal translation errors between matched forecast and observed tra...
columns = ['obs_track_id', 'translation_error_x', 'translation_error_y', 'start_time_difference', 'end_time_difference', ] track_errors = pd.DataFrame(index=list(range(len(model_tracks))), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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"), _("March"), _("April"), _("May"), _("June"), _("July"), _("August"), _("September"), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 prope...
# manage the item model parent_item = self.__mapping[id(parent_tree_node)] self.item_model_controller.begin_insert(index, index, parent_item.row, parent_item.id) properties = { "display": self.__display_for_tree_node(tree_node), "tree_node": tree_node # used for...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
# get parent and item parent_item = self.__mapping[id(parent_tree_node)] # manage the item model self.item_model_controller.begin_remove(index, index, parent_item.row, parent_item.id) child_item = parent_item.children[index] parent_item.remove_child(child_item) s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = item.data["tree_n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 tim...
if method.lower() in ["ew", "watershed"]: labeler = EnhancedWatershed(min_intensity, increment, max_intensity, max_area, max_range) else: labeler = Hysteresis(min_intensity, max_intensity) if len(data.shape) == 2: label_grid = labeler.label(gaussian_filter(data, gaussian_sd)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 object...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 equa...
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], la...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def track_storms(storm_objects, times, distance_components, distance_maxima, distance_weights, tracked_objects=None): """ Given the output of extract_storm_objec...
obj_matcher = ObjectMatcher(distance_components, distance_weights, distance_maxima) if tracked_objects is None: tracked_objects = [] for t, time in enumerate(times): past_time_objects = [] for obj in tracked_objects: if obj.end_time == time - obj.step: pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
ax, ay = 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 se...
ax, ay = item_a.center_of_mass(time_a) bx, by = 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_valu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
return np.minimum(item_a.closest_distance(time_a, item_b, time_b), max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: STO...
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(di...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: STObje...
return np.minimum(1 - item_a.count_overlap(time_a, item_b, time_b), max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
intensity_a = item_a.max_intensity(time_a) intensity_b = item_b.max_intensity(time_b) diff = np.sqrt((intensity_a - intensity_b) ** 2) return np.minimum(diff, max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ti...
size_a = item_a.size(time_a) size_b = item_b.size(time_b) diff = np.sqrt((size_a - size_b) ** 2) return np.minimum(diff, max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 an...
centroids_a = np.array([item_a.center_of_mass(t) for t 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_matri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 th...
times_a = item_a.times.reshape((item_a.times.size, 1)) times_b = item_b.times.reshape((1, item_b.times.size)) distance_matrix = (times_a - 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_va...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 firs...
start_a = item_a.center_of_mass(item_a.times[0]) start_b = item_b.center_of_mass(item_b.times[0]) start_distance = np.sqrt((start_a[0] - start_b[0]) ** 2 + (start_a[1] - start_b[1]) ** 2) return np.minimum(start_distance, max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
start_time_diff = np.abs(item_a.times[0] - item_b.times[0]) return np.minimum(start_time_diff, max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
duration_a = item_a.times.size duration_b = item_b.times.size return np.minimum(np.abs(duration_a - duration_b), max_value) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 fir...
mean_area_a = np.mean([item_a.size(t) for t in item_a.times]) mean_area_b = np.mean([item_b.size(t) for t in item_b.times]) return np.abs(mean_area_a - mean_area_b) / float(max_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
costs = self.cost_matrix(set_a, set_b, time_a, time_b) * 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 l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_...
distances = np.zeros(len(self.weights)) for c, component in enumerate(self.cost_function_components): distances[c] = component(item_a, time_a, item_b, time_b, self.max_values[c]) total_distance = np.sum(self.weights * distances) return total_distance
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def variable_specifier(self) -> dict: """Return the variable specifier for this variable. The specifier can be used to lookup the value of this variable in a comp...
if self.value_type is not None: return {"type": "variable", "version": 1, "uuid": str(self.uuid), "x-name": self.name, "x-value": self.value} else: return self.specifier
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bound_variable(self): """Return an object with a value property and a changed_event. The value property returns the value of the variable. The changed_event ...
class BoundVariable: def __init__(self, variable): self.__variable = variable self.changed_event = Event.Event() self.needs_rebind_event = Event.Event() def property_changed(key): if key == "value": ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resolve_object_specifier(self, object_specifier, secondary_specifier=None, property_name=None, objects_model=None): """Resolve the object specifier. First lo...
variable = self.__computation().resolve_variable(object_specifier) if not variable: return self.__context.resolve_object_specifier(object_specifier, secondary_specifier, property_name, objects_model) elif variable.specifier is None: return variable.bound_variable ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_names(cls, expression): """Return the list of identifiers used in the expression."""
names = set() try: ast_node = ast.parse(expression, "ast") class Visitor(ast.NodeVisitor): def visit_Name(self, node): names.add(node.id) Visitor().visit(ast_node) except Exception: pass return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind(self, context) -> None: """Bind a context to this computation. The context allows the computation to convert object specifiers to actual objects. """
# make a computation context based on the enclosing context. self.__computation_context = ComputationContext(self, context) # re-bind is not valid. be careful to set the computation after the data item is already in document. for variable in self.variables: assert variable...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unbind(self): """Unlisten and close each bound item."""
for variable in self.variables: self.__unbind_variable(variable) for result in self.results: self.__unbind_result(result)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sort_by_date_key(data_item): """ A sort key to for the created field of a data item. The sort by uuid makes it determinate. """
return data_item.title + str(data_item.uuid) if data_item.is_live else str(), data_item.date_for_sorting, str(data_item.uuid)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_r_value(self, r_var: str, *, notify_changed=True) -> None: """Used to signal changes to the ref var, which are kept in document controller. ugh."""
self.r_var = r_var self._description_changed() if notify_changed: # set to False to set the r-value at startup; avoid marking it as a change self.__notify_description_changed()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data_and_metadata(self, data_and_metadata, data_modified=None): """Sets the underlying data and data-metadata to the data_and_metadata. Note: this does n...
self.increment_data_ref_count() try: if data_and_metadata: data = data_and_metadata.data data_shape_and_dtype = data_and_metadata.data_shape_and_dtype intensity_calibration = data_and_metadata.intensity_calibration dimensional_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_calculated_display_values(self, immediate: bool=False) -> DisplayValues: """Return the display values. Return the current (possibly uncalculated) display ...
if not immediate or not self.__is_master or not self.__last_display_values: if not self.__current_display_values and self.__data_item: self.__current_display_values = DisplayValues(self.__data_item.xdata, self.sequence_index, self.collection_index, self.slice_center, self.slice_widt...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_display_limits(self): """Calculate best display limits and set them."""
display_data_and_metadata = self.get_calculated_display_values(True).display_data_and_metadata data = display_data_and_metadata.data if display_data_and_metadata else None if data is not None: # The old algorithm was a problem during EELS where the signal data # is a sma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_graphic(self, graphic: Graphics.Graphic, *, safe: bool=False) -> typing.Optional[typing.Sequence]: """Remove a graphic, but do it through the container...
return self.remove_model_item(self, "graphics", graphic, safe=safe)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: """Shape of the underlying data, if only one."""
if not self.__data_and_metadata: return None return self.__data_and_metadata.dimensional_shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_local_file(fp, name_bytes, writer, dt): """ Writes a zip file local file header structure at the current file position. Returns data_len, crc32 for the...
fp.write(struct.pack('I', 0x04034b50)) # local file header fp.write(struct.pack('H', 10)) # extract version (default) fp.write(struct.pack('H', 0)) # general purpose bits fp.write(struct.pack('H', 0)) # compression method msdos_date = int(dt.year - 1980) << 9 | int(dt....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_directory_data(fp, offset, name_bytes, data_len, crc32, dt): """ Write a zip fie directory entry at the current file position :param fp: the file point...
fp.write(struct.pack('I', 0x02014b50)) # central directory header fp.write(struct.pack('H', 10)) # made by version (default) fp.write(struct.pack('H', 10)) # extract version (default) fp.write(struct.pack('H', 0)) # general purpose bits fp.write(struct.pack('H', 0)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_end_of_directory(fp, dir_size, dir_offset, count): """ Write zip file end of directory header at the current file position :param fp: the file point to...
fp.write(struct.pack('I', 0x06054b50)) # central directory header fp.write(struct.pack('H', 0)) # disk number fp.write(struct.pack('H', 0)) # disk number fp.write(struct.pack('H', count)) # number of files fp.write(struct.pack('H', count)) # number of files fp.w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_zip_fp(fp, data, properties, dir_data_list=None): """ Write custom zip file of data and properties to fp :param fp: the file point to which to write th...
assert data is not None or properties is not None # dir_data_list has the format: local file record offset, name, data length, crc32 dir_data_list = list() if dir_data_list is None else dir_data_list dt = datetime.datetime.now() if data is not None: offset_data = fp.tell() def write...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_zip(file_path, data, properties): """ Write custom zip file to the file path :param file_path: the file to which to write the zip file :param data: the...
with open(file_path, "w+b") as fp: write_zip_fp(fp, data, properties)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_zip(fp): """ Parse the zip file headers at fp :param fp: the file pointer from which to parse the zip file :return: A tuple of local files, directory h...
local_files = {} dir_files = {} eocd = None fp.seek(0) while True: pos = fp.tell() signature = struct.unpack('I', fp.read(4))[0] if signature == 0x04034b50: fp.seek(pos + 14) crc32 = struct.unpack('I', fp.read(4))[0] fp.seek(pos + 18) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_data(fp, local_files, dir_files, name_bytes): """ Read a numpy data array from the zip file :param fp: a file pointer :param local_files: the local file...
if name_bytes in dir_files: fp.seek(local_files[dir_files[name_bytes][1]][1]) return numpy.load(fp) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_json(fp, local_files, dir_files, name_bytes): """ Read json properties from the zip file :param fp: a file pointer :param local_files: the local files s...
if name_bytes in dir_files: json_pos = local_files[dir_files[name_bytes][1]][1] json_len = local_files[dir_files[name_bytes][1]][2] fp.seek(json_pos) json_properties = fp.read(json_len) return json.loads(json_properties.decode("utf-8")) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rewrite_zip(file_path, properties): """ Rewrite the json properties in the zip file :param file_path: the file path to the zip file :param properties: the up...
with open(file_path, "r+b") as fp: local_files, dir_files, eocd = parse_zip(fp) # check to make sure directory has two files, named data.npy and metadata.json, and that data.npy is first # TODO: check compression, etc. if len(dir_files) == 2 and b"data.npy" in dir_files and b"metada...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_matching(cls, file_path): """ Return whether the given absolute file path is an ndata file. """
if file_path.endswith(".ndata") and os.path.exists(file_path): try: with open(file_path, "r+b") as fp: local_files, dir_files, eocd = parse_zip(fp) contains_data = b"data.npy" in dir_files contains_metadata = b"metadata.jso...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_data(self, data, file_datetime): """ Write data to the ndata file specified by reference. :param data: the numpy array data to write :param file_dateti...
with self.__lock: assert data is not None absolute_file_path = self.__file_path #logging.debug("WRITE data file %s for %s", absolute_file_path, key) make_directory_if_needed(os.path.dirname(absolute_file_path)) properties = self.read_properties() if o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_properties(self, properties, file_datetime): """ Write properties to the ndata file specified by reference. :param reference: the reference to which to...
with self.__lock: absolute_file_path = self.__file_path #logging.debug("WRITE properties %s for %s", absolute_file_path, key) make_directory_if_needed(os.path.dirname(absolute_file_path)) exists = os.path.exists(absolute_file_path) if exists: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_properties(self): """ Read properties from the ndata file reference :param reference: the reference from which to read :return: a tuple of the item_uuid...
with self.__lock: absolute_file_path = self.__file_path with open(absolute_file_path, "rb") as fp: local_files, dir_files, eocd = parse_zip(fp) properties = read_json(fp, local_files, dir_files, b"metadata.json") return properties
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_data(self): """ Read data from the ndata file reference :param reference: the reference from which to read :return: a numpy array of the data; maybe Non...
with self.__lock: absolute_file_path = self.__file_path #logging.debug("READ data file %s", absolute_file_path) with open(absolute_file_path, "rb") as fp: local_files, dir_files, eocd = parse_zip(fp) return read_data(fp, local_files, dir_files...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove(self): """ Remove the ndata file reference :param reference: the reference to remove """
with self.__lock: absolute_file_path = self.__file_path #logging.debug("DELETE data file %s", absolute_file_path) if os.path.isfile(absolute_file_path): os.remove(absolute_file_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def build_menu(self, display_type_menu, document_controller, display_panel): """Build the dynamic menu for the selected display panel. The user accesses this men...
dynamic_live_actions = list() def switch_to_display_content(display_panel_type): self.switch_to_display_content(document_controller, display_panel, display_panel_type, display_panel.display_item) empty_action = display_type_menu.add_menu_item(_("Clear Display Panel"), functools.pa...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bounds(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the bounds property in relative coordinates. Bounds is a tuple...
...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def vector(self) -> typing.Tuple[typing.Tuple[float, float], typing.Tuple[float, float]]: """Return the vector property in relative coordinates. Vector will be a ...
...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_widget_to_content(self, widget): """Subclasses should call this to add content in the section's top level column."""
self.__section_content_column.add_spacing(4) self.__section_content_column.add(widget)