def display_on_figure(self, workspace, axes, imshow_fn): if self.use_color_map(): labels = workspace.display_data.labels if self.wants_image: pixel_data = workspace.display_data.pixel_data else: pixel_data = (labels != 0).astype(numpy.float32) if pixel_data.ndim == 3: pixel_data = numpy.sum(pixel_data, 2) / pixel_data.shape[2] colormap_name = self.colormap.value if colormap_name == "Default": colormap_name = cellprofiler_core.preferences.get_default_colormap( ) colormap = matplotlib.cm.get_cmap(colormap_name) values = workspace.display_data.values vmask = workspace.display_data.mask colors = numpy.ones((len(vmask) + 1, 4)) colors[1:][~vmask, :3] = 1 sm = matplotlib.cm.ScalarMappable(cmap=colormap) if self.color_map_scale_choice == CMS_MANUAL: sm.set_clim(self.color_map_scale.min, self.color_map_scale.max) sm.set_array(values) colors[1:][vmask, :] = sm.to_rgba(values) img = colors[labels, :3] * pixel_data[:, :, numpy.newaxis] imshow_fn(img) assert isinstance(axes, matplotlib.axes.Axes) figure = axes.get_figure() assert isinstance(figure, matplotlib.figure.Figure) figure.colorbar(sm, ax=axes) else: imshow_fn(workspace.display_data.pixel_data) for x, y, value in zip( workspace.display_data.x, workspace.display_data.y, workspace.display_data.values, ): try: fvalue = float(value) svalue = "%.*f" % (self.decimals.value, value) except: svalue = str(value) text = matplotlib.text.Text( x=x, y=y, text=svalue, size=self.font_size.value, color=self.text_color.value, verticalalignment="center", horizontalalignment="center", ) axes.add_artist(text)
def sampling_prediction_trajectories( ensemble_prediction: EnsemblePrediction, levels: Union[float, Sequence[float]], title: str = None, size: Tuple[float, float] = None, axes: matplotlib.axes.Axes = None, labels: Dict[str, str] = None, axis_label_padding: int = 50, groupby: str = CONDITION, condition_gap: float = 0.01, condition_ids: Sequence[str] = None, output_ids: Sequence[str] = None, weighting: bool = False, ) -> matplotlib.axes.Axes: """ Visualize prediction trajectory of an EnsemblePrediction. Plot MCMC-based prediction credibility intervals for the model states or outputs. One or various credibility levels can be depicted. Plots are grouped by condition. Parameters ---------- result: The pyPESTO result object with filled sample result. levels: Credibility levels, e.g. [95] for a 95% credibility interval. See the :py:func:`_get_level_percentiles` method for a description of how these levels are handled, and current limitations. title: Axes title. size: ndarray Figure size in inches. axes: Axes object to use. labels: Keys should be ensemble output IDs, values should be the desired label for that output. Defaults to output IDs. axis_label_padding: Pixels between axis labels and plots. groupby: Group plots by `pypesto.C.OUTPUT` or `pypesto.C.CONDITION`. condition_gap: Gap between conditions when `groupby == pypesto.C.CONDITION`. condition_ids: If provided, only data for the provided condition IDs will be plotted. output_ids: If provided, only data for the provided output IDs will be plotted. weighting: Whether weights should be used for trajectory. Returns ------- axes: The plot axes. """ if labels is None: labels = {} if len(list(levels)) == 1: levels = list(levels) levels = sorted(levels, reverse=True) # Get the percentiles that correspond to the requested credibility levels. percentiles = [ percentile for level in levels for percentile in _get_level_percentiles(level) ] summary = ensemble_prediction.compute_summary(percentiles_list=percentiles, weighting=weighting) all_condition_ids, all_output_ids = _get_condition_and_output_ids(summary) if condition_ids is None: condition_ids = all_condition_ids if output_ids is None: output_ids = all_output_ids # Set default labels for any unspecified labels. labels = {id_: labels.get(id_, id_) for id_ in condition_ids + output_ids} if groupby == CONDITION: n_variables = len(output_ids) variable_names = output_ids n_subplots = len(condition_ids) elif groupby == OUTPUT: n_variables = len(condition_ids) variable_names = condition_ids n_subplots = len(output_ids) else: raise ValueError(f'Unsupported groupby value: {groupby}') level_opacities, variable_colors = _handle_colors(levels=levels, n_variables=n_variables) if axes is None: n_row = int(np.round(np.sqrt(n_subplots))) n_col = int(np.ceil(n_subplots / n_row)) fig, axes = plt.subplots(n_row, n_col, figsize=size, squeeze=False) for ax in axes.flat[n_subplots:]: ax.remove() else: fig = axes.get_figure() if not isinstance(axes, np.ndarray): axes = np.array([[axes]]) if len(axes.flat) < n_subplots: raise ValueError( 'Provided `axes` contains insufficient subplots. At least ' f'{n_subplots} are required.') artist_padding = axis_label_padding / (fig.get_size_inches() * fig.dpi)[0] if groupby == CONDITION: _plot_trajectories_by_condition( summary=summary, condition_ids=condition_ids, output_ids=output_ids, axes=axes, levels=levels, level_opacities=level_opacities, labels=labels, variable_colors=variable_colors, ) elif groupby == OUTPUT: _plot_trajectories_by_output( summary=summary, condition_ids=condition_ids, output_ids=output_ids, axes=axes, levels=levels, level_opacities=level_opacities, labels=labels, variable_colors=variable_colors, ) if title: fig.suptitle(title) _handle_legends( fig=fig, axes=axes, levels=levels, labels=labels, level_opacities=level_opacities, variable_names=variable_names, variable_colors=variable_colors, groupby=groupby, artist_padding=artist_padding, n_col=n_col, ) # X and Y labels xmin = min(ax.get_position().xmin for ax in axes.flat) ymin = min(ax.get_position().ymin for ax in axes.flat) xlabel = ('Cumulative time across all conditions' if groupby == OUTPUT else 'Time') fig.text( 0.5, ymin - artist_padding, xlabel, ha='center', va='center', transform=fig.transFigure, ) fig.text( xmin - artist_padding, 0.5, 'Simulated values', ha='center', va='center', transform=fig.transFigure, rotation='vertical', ) # plt.tight_layout() # Ruins layout for `groupby == OUTPUT`. return axes