code
stringlengths
1
18.2k
fixed surface 0, # Value of 2nd fixed surface 0, # Derived forecast type 1 # 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_list = list(sel...
- self.run_date).total_seconds() / 3600.0 data = self.data[t] / 1000.0 data[np.isnan(data)] = 0 masked_data = np.ma.array(data, mask=data<=0) pdtmp1[-2] = 0 grib_objects[time].addfield(1, pdtmp1, 0, drtmp1, masked_data) return grib_objects
def load_data(self): """ Loads data from each ensemble member. """ for m, member in enumerate(self.members): mo = ModelOutput(self.ensemble_name, member, self.run_date, self.variable, self.start_date, self.end_date, self.path, self.map_file, self.single_step) mo.load_data() if self.data is None: self.data = np.zeros((l...
mo
def point_consensus(self, consensus_type): """ Calculate grid-point statistics across ensemble members. Args: consensus_type: mean, std, median, max, or percentile_nn Returns: EnsembleConsensus containing point statistic """ if "mean" in consensus_type: consensus_data = np.mean(self.data, axis=0) elif "std" in consensu...
= np.percentile(self.data, percentile, axis=0) else: consensus_data = np.zeros(self.data.shape[1:]) consensus = EnsembleConsensus(consensus_data, consensus_type, self.ensemble_name, self.run_date, self.variable, self.start_date, self.end_date, self.units) return consensus
def point_probability(self, threshold): """ Determine the probability of exceeding a threshold at a grid point based on the ensemble forecasts at that point. Args: threshold: If >= threshold assigns a 1 to member, otherwise 0. Returns: EnsembleConsensus """ point_prob = np.zeros(self.data.shape[1:]) for t in range(self...
self.start_date, self.end_date, "")
def neighborhood_probability(self, threshold, radius, sigmas=None): """ Hourly probability of exceeding a threshold based on model values within a specified radius of a point. Args: threshold (float): probability of exceeding this threshold radius (int): distance from point in number of grid points to include in neighb...
containing neighborhood probabilities for each forecast hour. """ if sigmas is None: sigmas = [0] weights = disk(radius) filtered_prob = [] for sigma in sigmas: filtered_prob.append(EnsembleConsensus(np.zeros(self.data.shape[1:], dtype=np.float32), "neighbor_prob_r_{0:d}_s_{1:d}".format(radius, sigma), self.ensemble_na...
maximized[maximized > 1] = 1 maximized[maximized < 1] = 0 neighbor_prob += fftconvolve(maximized, weights, mode="same") neighbor_prob[neighbor_prob < 1] = 0 thresh_data[:] = 0 neighbor_prob /= (self.data.shape[0] * float(weights.sum())) for s, sigma in enumerate(sigmas): if sigma > 0: filtered_prob[s].data[t] = gaussia...
def period_max_neighborhood_probability(self, threshold, radius, sigmas=None): """ Calculates the neighborhood probability of exceeding a threshold at any time over the period loaded. Args: threshold (float): splitting threshold for probability calculatations radius (int): distance from point in number of grid points t...
sigmas is None: sigmas = [0] weights = disk(radius) neighborhood_prob = np.zeros(self.data.shape[2:], dtype=np.float32) thresh_data = np.zeros(self.data.shape[2:], dtype=np.uint8) for m in range(self.data.shape[0]): thresh_data[self.data[m].max(axis=0) >= threshold] = 1 maximized = fftconvolve(thresh_data, weights, mod...
gaussian_filter(neighborhood_prob, sigma=sigma) else: filtered_prob = neighborhood_prob ec = EnsembleConsensus(filtered_prob, "neighbor_prob_{0:02d}-hour_r_{1:d}_s_{2:d}".format(self.data.shape[1], radius, sigma), self.ensemble_name, self.run_date, self.variable + "_{0:0.2f}".format(float(threshold)), self.start_date, ...
def load_data(self, grid_method="gamma", num_samples=1000, condition_threshold=0.5, zero_inflate=False, percentile=None): """ Reads the track forecasts and converts them to grid point values based on random sampling. Args: grid_method: "gamma" by default num_samples: Number of samples drawn from predicted pdf condition...
condition model probability percentile: If None, outputs the mean of the samples at each grid point, otherwise outputs the specified percentile from 0 to 100. Returns: 0 if tracks are successfully sampled on to grid. If no tracks are found, returns -1. """ self.percentile = percentile if self.track_forecasts == {}: sel...
self.times.size, self.grid_shape[0], self.grid_shape[1]), dtype=np.float32) else: self.data[:] = 0 if grid_method in ["mean", "median", "samples"]: for m, member in enumerate(self.members): print("Sampling " + member) for track_forecast in self.track_forecasts[member]: times = track_forecast["properties"]["times"] for ...
i[mask == 1] j = np.array(step['properties']["j"], dtype=int) j = j[mask == 1] if grid_method == "samples": intensities = np.array(step["properties"]["timesteps"], dtype=float)[mask == 1] rankings = np.argsort(intensities) samples = np.random.choice(self.forecast_bins, size=intensities.size, replace=True, p=forecast_pd...
t, i, j] = forecast_value if grid_method in ["gamma"]: full_condition_name = "condition_" + self.condition_model_name.replace(" ", "-") dist_model_name = self.variable + "_" + self.ensemble_name.replace(" ", "-") for m, member in enumerate(self.members): for track_forecast in self.track_forecasts[member]: times = track...
in self.times: t = np.where(self.times == forecast_time)[0][0] mask = np.array(step["properties"]["masks"], dtype=int) rankings = np.argsort(step["properties"]["timesteps"])[mask == 1] i = np.array(step["properties"]["i"], dtype=int)[mask == 1][rankings] j = np.array(step["properties"]["j"], dtype=int)[mask == 1][ranki...
or condition >= condition_threshold: self.data[m, t, i, j] = samples return 0
def write_grib2(self, path): """ Writes data to grib2 file. Currently, grib codes are set by hand to hail. Args: path: Path to directory containing grib2 files. Returns: """ if self.percentile is None: var_type = "mean" else: var_type = "p{0:02d}".format(self.percentile) lscale = 1e6 grib_id_start = [7, 0, 14, 14, 2] g...
lon_0 < 0: lon_0 += 360 if sw_lon < 0: sw_lon += 360 gdtmp1 = np.array([7, 1, self.proj_dict['a'], 1, self.proj_dict['a'], 1, self.proj_dict['b'], self.data.shape[-2], self.data.shape[-1], self.grid_dict["sw_lat"] * lscale, sw_lon * lscale, 0, self.proj_dict["lat_0"] * lscale, lon_0 * lscale, self.grid_dict["dx"] * 1e3...
1, 1, 1, 1, 1, 1, 192, 0, self.data.shape[0]], dtype=np.int32) for m, member in enumerate(self.members): pdtmp1[-2] = m for t, time in enumerate(self.times): time_list = list(time.utctimetuple()[0:6]) grbe = Grib2Encode(0, np.array(grib_id_start + time_list + [2, 1], dtype=np.int32)) grbe.addgrid(gdsinfo, gdtmp1) pdtmp...
0) grbe.addfield(1, pdtmp1, 0, drtmp1, masked_data) grbe.end() filename = path + "{0}_{1}_mlhail_{2}_{3}.grib2".format(self.ensemble_name.replace(" ", "-"), member, var_type, time.to_datetime().strftime("%Y%m%d%H%M")) print("Writing to " + filename) grib_file = open(filename, "wb") grib_file.write(grbe.msg) grib_file.c...
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_units: Units for the time variable in format "<time> since <date string>" Returns: Dataset object """ if os.access(filename, os.R_OK): out_data = Dataset(filen...
enumerate(["y", "x"]): out_data.createDimension(dim, self.data.shape[d+1]) out_data.createDimension("time", len(self.times)) time_var = out_data.createVariable("time", "i8", ("time",)) time_var[:] = date2num(self.times.to_pydatetime(), time_units) time_var.units = time_units out_data.Conventions = "CF-1.6" return out_d...
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 appended to the current file Args: out_data: Full-path and name of output netCDF file """ full_var_name = self.consensus_type + "_" + self.variable if "-hour" in self...
else: var = out_data.variables[full_var_name] var.coordinates = "y x" else: if full_var_name not in out_data.variables.keys(): var = out_data.createVariable(full_var_name, "f4", ("time", "y", "x"), zlib=True, least_significant_digit=3, shuffle=True) else: var = out_data.variables[full_var_name] var.coordinates = "time ...
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.n...
def new_workspace(self, name=None, layout=None, workspace_id=None, index=None) -> WorkspaceLayout.WorkspaceLayout: """ Create a new workspace, insert into document_model, and return it. """ workspace = WorkspaceLayout.WorkspaceLayout() self.document_model.insert_workspace(index if index is not None else len(self.docume...
workspace
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 ...
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 works...
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 works...
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}'?...
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...
def __replace_displayed_display_item(self, display_panel, display_item, d=None) -> Undo.UndoableCommand: """ Used in drag/drop support. """ self.document_controller.replaced_display_panel_content = display_panel.save_contents() command = DisplayPanel.ReplaceDisplayPanelCommand(self) if display_item: display_panel.set_d...
def bootstrap(score_objs, n_boot=1000): """ Given a set of DistributedROC or DistributedReliability objects, this function performs a bootstrap resampling of the objects and returns n_boot aggregations of them. Args: score_objs: A list of DistributedROC or DistributedReliability objects. Objects must have an __add__ me...
def update(self, forecasts, observations): """ Update the ROC curve with a set of forecasts and observations Args: forecasts: 1D array of forecast values observations: 1D array of observation values. """ for t, threshold in enumerate(self.thresholds): tp = np.count_nonzero((forecasts >= threshold) & (observations >= se...
np.count_nonzero((forecasts < threshold) & (observations < self.obs_threshold)) self.contingency_tables.iloc[t] += [tp, fp, fn, tn]
def merge(self, other_roc): """ Ingest the values of another DistributedROC object into this one and update the statistics inplace. Args: other_roc: another DistributedROC object. """ if other_roc.thresholds.size == self.thresholds.size and np.all(other_roc.thresholds == self.thresholds): self.contingency_tables += oth...
def roc_curve(self): """ Generate a ROC curve from the contingency table by calculating the probability of detection (TP/(TP+FN)) and the probability of false detection (FP/(FP+TN)). Returns: A pandas.DataFrame containing the POD, POFD, and the corresponding probability thresholds. """ pod = self.contingency_tables["TP...
def performance_curve(self): """ Calculate the Probability of Detection and False Alarm Ratio in order to output a performance diagram. Returns: pandas.DataFrame containing POD, FAR, and probability thresholds. """ pod = self.contingency_tables["TP"] / (self.contingency_tables["TP"] + self.contingency_tables["FN"]) far...
def auc(self): """ Calculate the Area Under the ROC Curve (AUC). """ roc_curve = self.roc_curve() return np.abs(np.trapz(roc_curve['POD'], x=roc_curve['POFD']))
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()
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])
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 __str__ method """ parts = in_str.split(";") for part in parts: var_name, value = part.split(":") if var_name == "Obs_Threshold": self.obs_threshold = float(value...
np.array(value.split(), dtype=int)
def update(self, forecasts, observations): """ Update the statistics with a set of forecasts and observations. Args: forecasts (numpy.ndarray): Array of forecast probability values observations (numpy.ndarray): Array of observation values """ for t, threshold in enumerate(self.thresholds[:-1]): self.frequencies.loc[t, ...
def merge(self, other_rel): """ Ingest another DistributedReliability and add its contents to the current object. Args: other_rel: a Distributed reliability object. """ if other_rel.thresholds.size == self.thresholds.size and np.all(other_rel.thresholds == self.thresholds): self.frequencies += other_rel.frequencies els...
def reliability_curve(self): """ Calculates the reliability diagram statistics. The key columns are Bin_Start and Positive_Relative_Freq Returns: pandas.DataFrame """ total = self.frequencies["Total_Freq"].sum() curve = pd.DataFrame(columns=["Bin_Start", "Bin_End", "Bin_Center", "Positive_Relative_Freq", "Total_Relativ...
def brier_score_components(self): """ Calculate the components of the Brier score decomposition: reliability, resolution, and uncertainty. """ rel_curve = self.reliability_curve() total = self.frequencies["Total_Freq"].sum() climo_freq = float(self.frequencies["Positive_Freq"].sum()) / self.frequencies["Total_Freq"].su...
def brier_score(self): """ Calculate the Brier Score """ reliability, resolution, uncertainty = self.brier_score_components() return reliability - resolution + uncertainty
def brier_skill_score(self): """ Calculate the Brier Skill Score """ reliability, resolution, uncertainty = self.brier_score_components() return (resolution - reliability) / uncertainty
def update(self, forecasts, observations): """ Update the statistics with forecasts and observations. Args: forecasts: The discrete Cumulative Distribution Functions of observations: """ if len(observations.shape) == 1: obs_cdfs = np.zeros((observations.size, self.thresholds.size)) for o, observation in enumerate(obser...
+= np.sum(obs_cdfs, axis=0) self.num_forecasts += forecasts.shape[0]
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)
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
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)
def checar(cliente_sat): """ Checa em sequência os alertas registrados (veja :func:`registrar`) contra os dados da consulta ao status operacional do equipamento SAT. Este método irá então resultar em uma lista dos alertas ativos. :param cliente_sat: Uma instância de :class:`satcfe.clientelocal.ClienteSATLocal` ou :clas...
classe_alerta in AlertaOperacao.alertas_registrados: alerta = classe_alerta(resposta) if alerta.checar(): alertas.append(alerta) return alertas
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, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, w...
or 'camera.binning'. Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer using the ``metadata_value`` methods over directly accessing ``metadata``. """ desc = session_key_map.get(key) if desc is not None: d = getattr(metadata_source, "session_metadata", dict()) fo...
desc['path'][-1] in d desc = key_map.get(key) if desc is not None: d = getattr(metadata_source, "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 raise False
def get_metadata_value(metadata_source, key: str) -> typing.Any: """Get the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, we recommend ...
Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer using the ``metadata_value`` methods over directly accessing ``metadata``. """ desc = session_key_map.get(key) if desc is not None: v = getattr(metadata_source, "session_metadata", dict()) for k in desc['path']: ...
None: v = getattr(metadata_source, "metadata", dict()) for k in desc['path']: v = v.get(k) if v is not None else None return v raise KeyError()
def set_metadata_value(metadata_source, key: str, value: typing.Any) -> None: """Set the metadata value for the given key. There are a set of predefined keys that, when used, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, ...
or 'camera.binning'. Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer using the ``metadata_value`` methods over directly accessing ``metadata``. """ desc = session_key_map.get(key) if desc is not None: d0 = getattr(metadata_source, "session_metadata", dict()) d...
not None: d[desc['path'][-1]] = value metadata_source.session_metadata = d0 return desc = key_map.get(key) if desc is not None: d0 = getattr(metadata_source, "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: d[desc['path'][-1]] = value metada...
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, will be type checked and be interoperable with other applications. Please consult reference documentation for valid keys. If using a custom key, we recommend ...
Also note that some predefined keys map to the metadata ``dict`` but others do not. For this reason, prefer using the ``metadata_value`` methods over directly accessing ``metadata``. """ desc = session_key_map.get(key) if desc is not None: d0 = getattr(metadata_source, "session_metadata", dict()) d = d0 for k in desc['...
and desc['path'][-1] in d: d.pop(desc['path'][-1], None) metadata_source.session_metadata = d0 return desc = key_map.get(key) if desc is not None: d0 = getattr(metadata_source, "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']...
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,...
<= plot_height: y_ticks.append((y_tick, tick_label)) return y_ticks
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...
if drawn_data_width > 0.0: for tick_value in tick_values: label = nice_label(tick_value, precision) data_tick = x_calibration.convert_from_calibrated_value(tick_value) if x_calibration else tick_value x_tick = plot_width * (data_tick - self.drawn_left_channel) / drawn_data_width if x_tick >= 0 and x_tick <= plot_width:...
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 new_s...
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:...
get_font_metrics_fn(font, label).width) label = axes.y_ticker.value_label(axes.calibrated_data_min - y_range * 5) max_width = max(max_width, get_font_metrics_fn(font, label).width) new_sizing.minimum_width = max_width new_sizing.maximum_width = max_width self.update_sizing(new_sizing)
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 new_sizin...
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 ' + filenam...
def update_display_properties(self, display_calibration_info, display_properties: typing.Mapping, display_layers: typing.Sequence[typing.Mapping]) -> None: """Update the display values. Called from display panel. This method saves the display values and data and triggers an update. It should be as fast as possible. As ...
axes and update all of the constituent canvas items such as the axes labels and the graph layers. Each will trigger its own update if its inputs have changed. The inefficiencies in this process are that the layer must re-render on each call to this function. There is also a cost within the constituent canvas items to c...
has changed. When the display is associated with a single data item, the data will be """ # 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_cali...
self.__y_min = display_properties.get("y_min") self.__y_max = display_properties.get("y_max") self.__y_style = display_properties.get("y_style", "linear") self.__left_channel = display_properties.get("left_channel") self.__right_channel = display_properties.get("right_channel") self.__legend_position = display_properti...
for update if necesssary. self.update()
def __view_to_intervals(self, data_and_metadata: DataAndMetadata.DataAndMetadata, intervals: typing.List[typing.Tuple[float, float]]) -> None: """Change the view to encompass the channels and data represented by the given intervals.""" left = None right = None for interval in intervals: left = min(left, interval[0]) if...
0.0 right = right if right is not None else 1.0 left_channel = int(max(0.0, left) * data_and_metadata.data_shape[-1]) right_channel = int(min(1.0, right) * data_and_metadata.data_shape[-1]) data_min = numpy.amin(data_and_metadata.data[..., left_channel:right_channel]) data_max = numpy.amax(data_and_metadata.data[..., l...
y_min = data_min * 1.2 y_max = data_max * 1.2 extra = (right - left) * 0.5 display_left_channel = int(max(0.0, left - extra) * data_and_metadata.data_shape[-1]) display_right_channel = int(min(1.0, right + extra) * data_and_metadata.data_shape[-1]) # command = self.delegate.create_change_display_command() self.delegate...
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_inde...
def prepare_display(self): """Prepare the display. This method gets called by the canvas layout/draw engine after being triggered by a call to `update`. When data or display parameters change, the internal state of the line plot gets updated. This method takes that internal state and updates the child canvas items. Thi...
to be instant. """ displayed_dimensional_calibration = self.__displayed_dimensional_calibration intensity_calibration = self.__intensity_calibration calibration_style = self.__calibration_style y_min = self.__y_min y_max = self.__y_max y_style = self.__y_style left_channel = self.__left_channel right_channel = self.__r...
the data needs to have an intensity scale matching intensity_calibration. convert the data to use the common scale. scale = scalar_intensity_calibration.scale / intensity_calibration.scale offset = (scalar_intensity_calibration.offset - intensity_calibration.offset) / intensity_calibration.scale scalar_data = scalar_da...
if left_channel is not None else 0 right_channel = right_channel if right_channel is not None else data_scale left_channel, right_channel = min(left_channel, right_channel), max(left_channel, right_channel) scalar_data_list = None if y_min is None or y_max is None and len(xdata_list) > 0: scalar_xdata_list = calculate_...
LineGraphCanvasItem.LineGraphAxes(data_scale, calibrated_data_min, calibrated_data_max, left_channel, right_channel, displayed_dimensional_calibration, intensity_calibration, y_style, y_ticker) if scalar_xdata_list is None: if len(xdata_list) > 0: scalar_xdata_list = calculate_scalar_xdata(xdata_list) else: scalar_xdat...
if index < 16: display_layers.append({"fill_color": colors[index] if index == 0 else None, "stroke_color": colors[index] if index > 0 else None, "data_index": scalar_index}) index += 1 if scalar_xdata and scalar_xdata.is_data_2d: for row in range(min(scalar_xdata.data_shape[-1], 16)): if index < 16: display_layers.appe...
self.___has_valid_drawn_graph_data = False for index, display_layer in enumerate(display_layers): if index < 16: fill_color = display_layer.get("fill_color") stroke_color = display_layer.get("stroke_color") data_index = display_layer.get("data_index", 0) data_row = display_layer.get("data_row", 0) if 0 <= data_index < ...
= self.__line_graph_stack.canvas_items[display_layer_count - (index + 1)] line_graph_canvas_item.set_fill_color(fill_color) line_graph_canvas_item.set_stroke_color(stroke_color) line_graph_canvas_item.set_axes(axes) line_graph_canvas_item.set_uncalibrated_xdata(scalar_xdata) self.___has_valid_drawn_graph_data = scalar_...