code
stringlengths
501
4.91M
package
stringlengths
2
88
path
stringlengths
11
291
filename
stringlengths
4
197
parsed_code
stringlengths
0
4.91M
quality_prob
float64
0
0.99
learning_prob
float64
0.02
1
from __future__ import annotations from typing import Any, Dict, Sequence, Sized, Tuple, TypeVar import matplotlib.cm import matplotlib.patches import numpy as np from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.colors import Colormap from matplotlib.figure import Figure from typing_extensions import Protocol from ..._utils import _to_grid_points, constants from ...misc.validation import validate_domain_range from ...representation._functional_data import FData from ...typing._base import DomainRangeLike, GridPointsLike from ._baseplot import BasePlot from ._utils import ColorLike, _set_labels K = TypeVar('K', contravariant=True) V = TypeVar('V', covariant=True) class Indexable(Protocol[K, V]): """Class Indexable used to type _get_color_info.""" def __getitem__(self, __key: K) -> V: pass def __len__(self) -> int: pass def _get_color_info( fdata: Sized, group: Sequence[K] | None = None, group_names: Indexable[K, str] | None = None, group_colors: Indexable[K, ColorLike] | None = None, legend: bool = False, kwargs: Dict[str, Any] | None = None, ) -> Tuple[ Sequence[ColorLike] | None, Sequence[matplotlib.patches.Patch] | None, ]: if kwargs is None: kwargs = {} patches = None if group is not None: # In this case, each curve has a label, and all curves with the same # label should have the same color group_unique, group_indexes = np.unique( np.asarray(group), return_inverse=True, ) n_labels = len(group_unique) if group_colors is not None: group_colors_array = np.array( [group_colors[g] for g in group_unique], ) else: prop_cycle = matplotlib.rcParams['axes.prop_cycle'] cycle_colors = prop_cycle.by_key()['color'] group_colors_array = np.take( cycle_colors, np.arange(n_labels), mode='wrap', ) sample_colors = list(group_colors_array[group_indexes]) group_names_array = None if group_names is not None: group_names_array = np.array( [group_names[g] for g in group_unique], ) elif legend is True: group_names_array = group_unique if group_names_array is not None: patches = [ matplotlib.patches.Patch(color=c, label=l) for c, l in zip(group_colors_array, group_names_array) ] else: # In this case, each curve has a different color unless specified # otherwise if 'color' in kwargs: sample_colors = len(fdata) * [kwargs.get("color")] kwargs.pop('color') elif 'c' in kwargs: sample_colors = len(fdata) * [kwargs.get("c")] kwargs.pop('c') else: sample_colors = None return sample_colors, patches class GraphPlot(BasePlot): """ Class used to plot the FDataGrid object graph as hypersurfaces. When plotting functional data, we can either choose manually a color, a group of colors for the representations. Besides, we can use a list of variables (depths, scalar regression targets...) can be used as an argument to display the functions wtih a gradient of colors. Args: fdata: functional data set that we want to plot. gradient_criteria: list of real values used to determine the color in which each of the instances will be plotted. max_grad: maximum value that the gradient_list can take, it will be used to normalize the ``gradient_criteria`` in order to get values that can be used in the function colormap.__call__(). If not declared it will be initialized to the maximum value of gradient_list. min_grad: minimum value that the gradient_list can take, it will be used to normalize the ``gradient_criteria`` in order to get values that can be used in the function colormap.__call__(). If not declared it will be initialized to the minimum value of gradient_list. chart: figure over with the graphs are plotted or axis over where the graphs are plotted. If None and ax is also None, the figure is initialized. fig: figure over with the graphs are plotted in case ax is not specified. If None and ax is also None, the figure is initialized. axes: axis over where the graphs are plotted. If None, see param fig. n_rows: designates the number of rows of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. n_cols: designates the number of columns of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. n_points: Number of points to evaluate in the plot. In case of surfaces a tuple of length 2 can be pased with the number of points to plot in each axis, otherwise the same number of points will be used in the two axes. By default in unidimensional plots will be used 501 points; in surfaces will be used 30 points per axis, wich makes a grid with 900 points. domain_range: Range where the function will be plotted. In objects with unidimensional domain the domain range should be a tuple with the bounds of the interval; in the case of surfaces a list with 2 tuples with the ranges for each dimension. Default uses the domain range of the functional object. group: contains integers from [0 to number of labels) indicating to which group each sample belongs to. Then, the samples with the same label are plotted in the same color. If None, the default value, each sample is plotted in the color assigned by matplotlib.pyplot.rcParams['axes.prop_cycle']. group_colors: colors in which groups are represented, there must be one for each group. If None, each group is shown with distict colors in the "Greys" colormap. group_names: name of each of the groups which appear in a legend, there must be one for each one. Defaults to None and the legend is not shown. Implies `legend=True`. colormap: name of the colormap to be used. By default we will use autumn. legend: if `True`, show a legend with the groups. If `group_names` is passed, it will be used for finding the names to display in the legend. Otherwise, the values passed to `group` will be used. kwargs: if dim_domain is 1, keyword arguments to be passed to the matplotlib.pyplot.plot function; if dim_domain is 2, keyword arguments to be passed to the matplotlib.pyplot.plot_surface function. Attributes: gradient_list: normalization of the values from gradient color_list that will be used to determine the intensity of the color each function will have. """ def __init__( self, fdata: FData, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | None = None, n_rows: int | None = None, n_cols: int | None = None, n_points: int | Tuple[int, int] | None = None, domain_range: DomainRangeLike | None = None, group: Sequence[K] | None = None, group_colors: Indexable[K, ColorLike] | None = None, group_names: Indexable[K, str] | None = None, gradient_criteria: Sequence[float] | None = None, max_grad: float | None = None, min_grad: float | None = None, colormap: Colormap | str | None = None, legend: bool = False, **kwargs: Any, ) -> None: super().__init__( chart, fig=fig, axes=axes, n_rows=n_rows, n_cols=n_cols, ) self.fdata = fdata self.gradient_criteria = gradient_criteria if self.gradient_criteria is not None: if len(self.gradient_criteria) != fdata.n_samples: raise ValueError( "The length of the gradient color", "list should be the same as the number", "of samples in fdata", ) if min_grad is None: self.min_grad = min(self.gradient_criteria) else: self.min_grad = min_grad if max_grad is None: self.max_grad = max(self.gradient_criteria) else: self.max_grad = max_grad self.gradient_list: Sequence[float] | None = ( [ (grad_color - self.min_grad) / (self.max_grad - self.min_grad) for grad_color in self.gradient_criteria ] ) else: self.gradient_list = None self.n_points = n_points self.group = group self.group_colors = group_colors self.group_names = group_names self.legend = legend self.colormap = colormap self.kwargs = kwargs if domain_range is None: self.domain_range = self.fdata.domain_range else: self.domain_range = validate_domain_range(domain_range) if self.gradient_list is None: sample_colors, patches = _get_color_info( self.fdata, self.group, self.group_names, self.group_colors, self.legend, kwargs, ) else: patches = None if self.colormap is None: colormap = matplotlib.cm.get_cmap("autumn") colormap = colormap.reversed() else: colormap = matplotlib.cm.get_cmap(self.colormap) sample_colors = colormap(self.gradient_list) self.sample_colors = sample_colors self.patches = patches @property def dim(self) -> int: return self.fdata.dim_domain + 1 @property def n_subplots(self) -> int: return self.fdata.dim_codomain @property def n_samples(self) -> int: return self.fdata.n_samples def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: self.artists = np.zeros( (self.n_samples, self.fdata.dim_codomain), dtype=Artist, ) color_dict: Dict[str, ColorLike | None] = {} if self.fdata.dim_domain == 1: if self.n_points is None: self.n_points = constants.N_POINTS_UNIDIMENSIONAL_PLOT_MESH assert isinstance(self.n_points, int) # Evaluates the object in a linspace eval_points = np.linspace(*self.domain_range[0], self.n_points) mat = self.fdata(eval_points) for i in range(self.fdata.dim_codomain): for j in range(self.fdata.n_samples): set_color_dict(self.sample_colors, j, color_dict) self.artists[j, i] = axes[i].plot( eval_points, mat[j, ..., i].T, **self.kwargs, **color_dict, )[0] else: # Selects the number of points if self.n_points is None: n_points_tuple = 2 * (constants.N_POINTS_SURFACE_PLOT_AX,) elif isinstance(self.n_points, int): n_points_tuple = (self.n_points, self.n_points) elif len(self.n_points) != 2: raise ValueError( "n_points should be a number or a tuple of " "length 2, and has " "length {0}.".format(len(self.n_points)), ) # Axes where will be evaluated x = np.linspace(*self.domain_range[0], n_points_tuple[0]) y = np.linspace(*self.domain_range[1], n_points_tuple[1]) # Evaluation of the functional object Z = self.fdata((x, y), grid=True) X, Y = np.meshgrid(x, y, indexing='ij') for k in range(self.fdata.dim_codomain): for h in range(self.fdata.n_samples): set_color_dict(self.sample_colors, h, color_dict) self.artists[h, k] = axes[k].plot_surface( X, Y, Z[h, ..., k], **self.kwargs, **color_dict, ) _set_labels(self.fdata, fig, axes, self.patches) class ScatterPlot(BasePlot): """ Class used to scatter the FDataGrid object. Args: fdata: functional data set that we want to plot. grid_points: points to plot. chart: figure over with the graphs are plotted or axis over where the graphs are plotted. If None and ax is also None, the figure is initialized. fig: figure over with the graphs are plotted in case ax is not specified. If None and ax is also None, the figure is initialized. axes: axis over where the graphs are plotted. If None, see param fig. n_rows: designates the number of rows of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. n_cols: designates the number of columns of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. domain_range: Range where the function will be plotted. In objects with unidimensional domain the domain range should be a tuple with the bounds of the interval; in the case of surfaces a list with 2 tuples with the ranges for each dimension. Default uses the domain range of the functional object. group: contains integers from [0 to number of labels) indicating to which group each sample belongs to. Then, the samples with the same label are plotted in the same color. If None, the default value, each sample is plotted in the color assigned by matplotlib.pyplot.rcParams['axes.prop_cycle']. group_colors: colors in which groups are represented, there must be one for each group. If None, each group is shown with distict colors in the "Greys" colormap. group_names: name of each of the groups which appear in a legend, there must be one for each one. Defaults to None and the legend is not shown. Implies `legend=True`. legend: if `True`, show a legend with the groups. If `group_names` is passed, it will be used for finding the names to display in the legend. Otherwise, the values passed to `group` will be used. kwargs: if dim_domain is 1, keyword arguments to be passed to the matplotlib.pyplot.plot function; if dim_domain is 2, keyword arguments to be passed to the matplotlib.pyplot.plot_surface function. """ def __init__( self, fdata: FData, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | None = None, n_rows: int | None = None, n_cols: int | None = None, grid_points: GridPointsLike | None = None, domain_range: Tuple[int, int] | DomainRangeLike | None = None, group: Sequence[K] | None = None, group_colors: Indexable[K, ColorLike] | None = None, group_names: Indexable[K, str] | None = None, legend: bool = False, **kwargs: Any, ) -> None: super().__init__( chart, fig=fig, axes=axes, n_rows=n_rows, n_cols=n_cols, ) self.fdata = fdata if grid_points is None: # This can only be done for FDataGrid self.grid_points = self.fdata.grid_points self.evaluated_points = self.fdata.data_matrix else: self.grid_points = _to_grid_points(grid_points) self.evaluated_points = self.fdata( self.grid_points, grid=True, ) self.domain_range = domain_range self.group = group self.group_colors = group_colors self.group_names = group_names self.legend = legend if self.domain_range is None: self.domain_range = self.fdata.domain_range else: self.domain_range = validate_domain_range(self.domain_range) sample_colors, patches = _get_color_info( self.fdata, self.group, self.group_names, self.group_colors, self.legend, kwargs, ) self.sample_colors = sample_colors self.patches = patches @property def dim(self) -> int: return self.fdata.dim_domain + 1 @property def n_subplots(self) -> int: return self.fdata.dim_codomain @property def n_samples(self) -> int: return self.fdata.n_samples def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: """ Scatter FDataGrid object. Returns: fig: figure object in which the graphs are plotted. """ self.artists = np.zeros( (self.n_samples, self.fdata.dim_codomain), dtype=Artist, ) color_dict: Dict[str, ColorLike | None] = {} if self.fdata.dim_domain == 1: for i in range(self.fdata.dim_codomain): for j in range(self.fdata.n_samples): set_color_dict(self.sample_colors, j, color_dict) self.artists[j, i] = axes[i].scatter( self.grid_points[0], self.evaluated_points[j, ..., i].T, **color_dict, picker=True, pickradius=2, ) else: X = self.fdata.grid_points[0] Y = self.fdata.grid_points[1] X, Y = np.meshgrid(X, Y) for k in range(self.fdata.dim_codomain): for h in range(self.fdata.n_samples): set_color_dict(self.sample_colors, h, color_dict) self.artists[h, k] = axes[k].scatter( X, Y, self.evaluated_points[h, ..., k].T, **color_dict, picker=True, pickradius=2, ) _set_labels(self.fdata, fig, axes, self.patches) def set_color_dict( sample_colors: Any, ind: int, color_dict: Dict[str, ColorLike | None], ) -> None: """ Auxiliary method used to update color_dict. Sets the new color of the color_dict thanks to sample colors and index. """ if sample_colors is not None: color_dict["color"] = sample_colors[ind]
scikit-fda-sim
/scikit-fda-sim-0.7.1.tar.gz/scikit-fda-sim-0.7.1/skfda/exploratory/visualization/representation.py
representation.py
from __future__ import annotations from typing import Any, Dict, Sequence, Sized, Tuple, TypeVar import matplotlib.cm import matplotlib.patches import numpy as np from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.colors import Colormap from matplotlib.figure import Figure from typing_extensions import Protocol from ..._utils import _to_grid_points, constants from ...misc.validation import validate_domain_range from ...representation._functional_data import FData from ...typing._base import DomainRangeLike, GridPointsLike from ._baseplot import BasePlot from ._utils import ColorLike, _set_labels K = TypeVar('K', contravariant=True) V = TypeVar('V', covariant=True) class Indexable(Protocol[K, V]): """Class Indexable used to type _get_color_info.""" def __getitem__(self, __key: K) -> V: pass def __len__(self) -> int: pass def _get_color_info( fdata: Sized, group: Sequence[K] | None = None, group_names: Indexable[K, str] | None = None, group_colors: Indexable[K, ColorLike] | None = None, legend: bool = False, kwargs: Dict[str, Any] | None = None, ) -> Tuple[ Sequence[ColorLike] | None, Sequence[matplotlib.patches.Patch] | None, ]: if kwargs is None: kwargs = {} patches = None if group is not None: # In this case, each curve has a label, and all curves with the same # label should have the same color group_unique, group_indexes = np.unique( np.asarray(group), return_inverse=True, ) n_labels = len(group_unique) if group_colors is not None: group_colors_array = np.array( [group_colors[g] for g in group_unique], ) else: prop_cycle = matplotlib.rcParams['axes.prop_cycle'] cycle_colors = prop_cycle.by_key()['color'] group_colors_array = np.take( cycle_colors, np.arange(n_labels), mode='wrap', ) sample_colors = list(group_colors_array[group_indexes]) group_names_array = None if group_names is not None: group_names_array = np.array( [group_names[g] for g in group_unique], ) elif legend is True: group_names_array = group_unique if group_names_array is not None: patches = [ matplotlib.patches.Patch(color=c, label=l) for c, l in zip(group_colors_array, group_names_array) ] else: # In this case, each curve has a different color unless specified # otherwise if 'color' in kwargs: sample_colors = len(fdata) * [kwargs.get("color")] kwargs.pop('color') elif 'c' in kwargs: sample_colors = len(fdata) * [kwargs.get("c")] kwargs.pop('c') else: sample_colors = None return sample_colors, patches class GraphPlot(BasePlot): """ Class used to plot the FDataGrid object graph as hypersurfaces. When plotting functional data, we can either choose manually a color, a group of colors for the representations. Besides, we can use a list of variables (depths, scalar regression targets...) can be used as an argument to display the functions wtih a gradient of colors. Args: fdata: functional data set that we want to plot. gradient_criteria: list of real values used to determine the color in which each of the instances will be plotted. max_grad: maximum value that the gradient_list can take, it will be used to normalize the ``gradient_criteria`` in order to get values that can be used in the function colormap.__call__(). If not declared it will be initialized to the maximum value of gradient_list. min_grad: minimum value that the gradient_list can take, it will be used to normalize the ``gradient_criteria`` in order to get values that can be used in the function colormap.__call__(). If not declared it will be initialized to the minimum value of gradient_list. chart: figure over with the graphs are plotted or axis over where the graphs are plotted. If None and ax is also None, the figure is initialized. fig: figure over with the graphs are plotted in case ax is not specified. If None and ax is also None, the figure is initialized. axes: axis over where the graphs are plotted. If None, see param fig. n_rows: designates the number of rows of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. n_cols: designates the number of columns of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. n_points: Number of points to evaluate in the plot. In case of surfaces a tuple of length 2 can be pased with the number of points to plot in each axis, otherwise the same number of points will be used in the two axes. By default in unidimensional plots will be used 501 points; in surfaces will be used 30 points per axis, wich makes a grid with 900 points. domain_range: Range where the function will be plotted. In objects with unidimensional domain the domain range should be a tuple with the bounds of the interval; in the case of surfaces a list with 2 tuples with the ranges for each dimension. Default uses the domain range of the functional object. group: contains integers from [0 to number of labels) indicating to which group each sample belongs to. Then, the samples with the same label are plotted in the same color. If None, the default value, each sample is plotted in the color assigned by matplotlib.pyplot.rcParams['axes.prop_cycle']. group_colors: colors in which groups are represented, there must be one for each group. If None, each group is shown with distict colors in the "Greys" colormap. group_names: name of each of the groups which appear in a legend, there must be one for each one. Defaults to None and the legend is not shown. Implies `legend=True`. colormap: name of the colormap to be used. By default we will use autumn. legend: if `True`, show a legend with the groups. If `group_names` is passed, it will be used for finding the names to display in the legend. Otherwise, the values passed to `group` will be used. kwargs: if dim_domain is 1, keyword arguments to be passed to the matplotlib.pyplot.plot function; if dim_domain is 2, keyword arguments to be passed to the matplotlib.pyplot.plot_surface function. Attributes: gradient_list: normalization of the values from gradient color_list that will be used to determine the intensity of the color each function will have. """ def __init__( self, fdata: FData, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | None = None, n_rows: int | None = None, n_cols: int | None = None, n_points: int | Tuple[int, int] | None = None, domain_range: DomainRangeLike | None = None, group: Sequence[K] | None = None, group_colors: Indexable[K, ColorLike] | None = None, group_names: Indexable[K, str] | None = None, gradient_criteria: Sequence[float] | None = None, max_grad: float | None = None, min_grad: float | None = None, colormap: Colormap | str | None = None, legend: bool = False, **kwargs: Any, ) -> None: super().__init__( chart, fig=fig, axes=axes, n_rows=n_rows, n_cols=n_cols, ) self.fdata = fdata self.gradient_criteria = gradient_criteria if self.gradient_criteria is not None: if len(self.gradient_criteria) != fdata.n_samples: raise ValueError( "The length of the gradient color", "list should be the same as the number", "of samples in fdata", ) if min_grad is None: self.min_grad = min(self.gradient_criteria) else: self.min_grad = min_grad if max_grad is None: self.max_grad = max(self.gradient_criteria) else: self.max_grad = max_grad self.gradient_list: Sequence[float] | None = ( [ (grad_color - self.min_grad) / (self.max_grad - self.min_grad) for grad_color in self.gradient_criteria ] ) else: self.gradient_list = None self.n_points = n_points self.group = group self.group_colors = group_colors self.group_names = group_names self.legend = legend self.colormap = colormap self.kwargs = kwargs if domain_range is None: self.domain_range = self.fdata.domain_range else: self.domain_range = validate_domain_range(domain_range) if self.gradient_list is None: sample_colors, patches = _get_color_info( self.fdata, self.group, self.group_names, self.group_colors, self.legend, kwargs, ) else: patches = None if self.colormap is None: colormap = matplotlib.cm.get_cmap("autumn") colormap = colormap.reversed() else: colormap = matplotlib.cm.get_cmap(self.colormap) sample_colors = colormap(self.gradient_list) self.sample_colors = sample_colors self.patches = patches @property def dim(self) -> int: return self.fdata.dim_domain + 1 @property def n_subplots(self) -> int: return self.fdata.dim_codomain @property def n_samples(self) -> int: return self.fdata.n_samples def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: self.artists = np.zeros( (self.n_samples, self.fdata.dim_codomain), dtype=Artist, ) color_dict: Dict[str, ColorLike | None] = {} if self.fdata.dim_domain == 1: if self.n_points is None: self.n_points = constants.N_POINTS_UNIDIMENSIONAL_PLOT_MESH assert isinstance(self.n_points, int) # Evaluates the object in a linspace eval_points = np.linspace(*self.domain_range[0], self.n_points) mat = self.fdata(eval_points) for i in range(self.fdata.dim_codomain): for j in range(self.fdata.n_samples): set_color_dict(self.sample_colors, j, color_dict) self.artists[j, i] = axes[i].plot( eval_points, mat[j, ..., i].T, **self.kwargs, **color_dict, )[0] else: # Selects the number of points if self.n_points is None: n_points_tuple = 2 * (constants.N_POINTS_SURFACE_PLOT_AX,) elif isinstance(self.n_points, int): n_points_tuple = (self.n_points, self.n_points) elif len(self.n_points) != 2: raise ValueError( "n_points should be a number or a tuple of " "length 2, and has " "length {0}.".format(len(self.n_points)), ) # Axes where will be evaluated x = np.linspace(*self.domain_range[0], n_points_tuple[0]) y = np.linspace(*self.domain_range[1], n_points_tuple[1]) # Evaluation of the functional object Z = self.fdata((x, y), grid=True) X, Y = np.meshgrid(x, y, indexing='ij') for k in range(self.fdata.dim_codomain): for h in range(self.fdata.n_samples): set_color_dict(self.sample_colors, h, color_dict) self.artists[h, k] = axes[k].plot_surface( X, Y, Z[h, ..., k], **self.kwargs, **color_dict, ) _set_labels(self.fdata, fig, axes, self.patches) class ScatterPlot(BasePlot): """ Class used to scatter the FDataGrid object. Args: fdata: functional data set that we want to plot. grid_points: points to plot. chart: figure over with the graphs are plotted or axis over where the graphs are plotted. If None and ax is also None, the figure is initialized. fig: figure over with the graphs are plotted in case ax is not specified. If None and ax is also None, the figure is initialized. axes: axis over where the graphs are plotted. If None, see param fig. n_rows: designates the number of rows of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. n_cols: designates the number of columns of the figure to plot the different dimensions of the image. Only specified if fig and ax are None. domain_range: Range where the function will be plotted. In objects with unidimensional domain the domain range should be a tuple with the bounds of the interval; in the case of surfaces a list with 2 tuples with the ranges for each dimension. Default uses the domain range of the functional object. group: contains integers from [0 to number of labels) indicating to which group each sample belongs to. Then, the samples with the same label are plotted in the same color. If None, the default value, each sample is plotted in the color assigned by matplotlib.pyplot.rcParams['axes.prop_cycle']. group_colors: colors in which groups are represented, there must be one for each group. If None, each group is shown with distict colors in the "Greys" colormap. group_names: name of each of the groups which appear in a legend, there must be one for each one. Defaults to None and the legend is not shown. Implies `legend=True`. legend: if `True`, show a legend with the groups. If `group_names` is passed, it will be used for finding the names to display in the legend. Otherwise, the values passed to `group` will be used. kwargs: if dim_domain is 1, keyword arguments to be passed to the matplotlib.pyplot.plot function; if dim_domain is 2, keyword arguments to be passed to the matplotlib.pyplot.plot_surface function. """ def __init__( self, fdata: FData, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | None = None, n_rows: int | None = None, n_cols: int | None = None, grid_points: GridPointsLike | None = None, domain_range: Tuple[int, int] | DomainRangeLike | None = None, group: Sequence[K] | None = None, group_colors: Indexable[K, ColorLike] | None = None, group_names: Indexable[K, str] | None = None, legend: bool = False, **kwargs: Any, ) -> None: super().__init__( chart, fig=fig, axes=axes, n_rows=n_rows, n_cols=n_cols, ) self.fdata = fdata if grid_points is None: # This can only be done for FDataGrid self.grid_points = self.fdata.grid_points self.evaluated_points = self.fdata.data_matrix else: self.grid_points = _to_grid_points(grid_points) self.evaluated_points = self.fdata( self.grid_points, grid=True, ) self.domain_range = domain_range self.group = group self.group_colors = group_colors self.group_names = group_names self.legend = legend if self.domain_range is None: self.domain_range = self.fdata.domain_range else: self.domain_range = validate_domain_range(self.domain_range) sample_colors, patches = _get_color_info( self.fdata, self.group, self.group_names, self.group_colors, self.legend, kwargs, ) self.sample_colors = sample_colors self.patches = patches @property def dim(self) -> int: return self.fdata.dim_domain + 1 @property def n_subplots(self) -> int: return self.fdata.dim_codomain @property def n_samples(self) -> int: return self.fdata.n_samples def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: """ Scatter FDataGrid object. Returns: fig: figure object in which the graphs are plotted. """ self.artists = np.zeros( (self.n_samples, self.fdata.dim_codomain), dtype=Artist, ) color_dict: Dict[str, ColorLike | None] = {} if self.fdata.dim_domain == 1: for i in range(self.fdata.dim_codomain): for j in range(self.fdata.n_samples): set_color_dict(self.sample_colors, j, color_dict) self.artists[j, i] = axes[i].scatter( self.grid_points[0], self.evaluated_points[j, ..., i].T, **color_dict, picker=True, pickradius=2, ) else: X = self.fdata.grid_points[0] Y = self.fdata.grid_points[1] X, Y = np.meshgrid(X, Y) for k in range(self.fdata.dim_codomain): for h in range(self.fdata.n_samples): set_color_dict(self.sample_colors, h, color_dict) self.artists[h, k] = axes[k].scatter( X, Y, self.evaluated_points[h, ..., k].T, **color_dict, picker=True, pickradius=2, ) _set_labels(self.fdata, fig, axes, self.patches) def set_color_dict( sample_colors: Any, ind: int, color_dict: Dict[str, ColorLike | None], ) -> None: """ Auxiliary method used to update color_dict. Sets the new color of the color_dict thanks to sample colors and index. """ if sample_colors is not None: color_dict["color"] = sample_colors[ind]
0.961198
0.46563
from __future__ import annotations import warnings from typing import Sequence from matplotlib.axes import Axes from matplotlib.figure import Figure from skfda.exploratory.visualization.representation import GraphPlot from skfda.representation import FData from ._baseplot import BasePlot class FPCAPlot(BasePlot): """ FPCAPlot visualization. Args: mean: The functional data object containing the mean function. If len(mean) > 1, the mean is computed. components: The principal components factor: Multiple of the principal component curve to be added or subtracted. fig: Figure over which the graph is plotted. If not specified it will be initialized axes: Axes over where the graph is plotted. If ``None``, see param fig. n_rows: Designates the number of rows of the figure. n_cols: Designates the number of columns of the figure. """ def __init__( self, mean: FData, components: FData, *, factor: float = 1, multiple: float | None = None, chart: Figure | Axes | None = None, fig: Figure | None = None, axes: Axes | None = None, n_rows: int | None = None, n_cols: int | None = None, ): super().__init__( chart, fig=fig, axes=axes, n_rows=n_rows, n_cols=n_cols, ) self.mean = mean self.components = components if multiple is None: self.factor = factor else: warnings.warn( "The 'multiple' parameter is deprecated, " "use 'factor' instead.", DeprecationWarning, ) self.factor = multiple @property def multiple(self) -> float: warnings.warn( "The 'multiple' attribute is deprecated, use 'factor' instead.", DeprecationWarning, ) return self.factor @property def n_subplots(self) -> int: return len(self.components) def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: if len(self.mean) > 1: self.mean = self.mean.mean() for i, ax in enumerate(axes): perturbations = self._get_component_perturbations(i) GraphPlot(fdata=perturbations, axes=ax).plot() ax.set_title(f"Principal component {i + 1}") def _get_component_perturbations(self, index: int = 0) -> FData: """ Compute the perturbations over the mean of a principal component. Args: index: Index of the component for which we want to compute the perturbations Returns: The mean function followed by the positive perturbation and the negative perturbation. """ if not isinstance(self.mean, FData): raise AttributeError("X must be a FData object") perturbations = self.mean.copy() perturbations = perturbations.concatenate( perturbations[0] + self.multiple * self.components[index], ) return perturbations.concatenate( perturbations[0] - self.multiple * self.components[index], )
scikit-fda-sim
/scikit-fda-sim-0.7.1.tar.gz/scikit-fda-sim-0.7.1/skfda/exploratory/visualization/fpca.py
fpca.py
from __future__ import annotations import warnings from typing import Sequence from matplotlib.axes import Axes from matplotlib.figure import Figure from skfda.exploratory.visualization.representation import GraphPlot from skfda.representation import FData from ._baseplot import BasePlot class FPCAPlot(BasePlot): """ FPCAPlot visualization. Args: mean: The functional data object containing the mean function. If len(mean) > 1, the mean is computed. components: The principal components factor: Multiple of the principal component curve to be added or subtracted. fig: Figure over which the graph is plotted. If not specified it will be initialized axes: Axes over where the graph is plotted. If ``None``, see param fig. n_rows: Designates the number of rows of the figure. n_cols: Designates the number of columns of the figure. """ def __init__( self, mean: FData, components: FData, *, factor: float = 1, multiple: float | None = None, chart: Figure | Axes | None = None, fig: Figure | None = None, axes: Axes | None = None, n_rows: int | None = None, n_cols: int | None = None, ): super().__init__( chart, fig=fig, axes=axes, n_rows=n_rows, n_cols=n_cols, ) self.mean = mean self.components = components if multiple is None: self.factor = factor else: warnings.warn( "The 'multiple' parameter is deprecated, " "use 'factor' instead.", DeprecationWarning, ) self.factor = multiple @property def multiple(self) -> float: warnings.warn( "The 'multiple' attribute is deprecated, use 'factor' instead.", DeprecationWarning, ) return self.factor @property def n_subplots(self) -> int: return len(self.components) def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: if len(self.mean) > 1: self.mean = self.mean.mean() for i, ax in enumerate(axes): perturbations = self._get_component_perturbations(i) GraphPlot(fdata=perturbations, axes=ax).plot() ax.set_title(f"Principal component {i + 1}") def _get_component_perturbations(self, index: int = 0) -> FData: """ Compute the perturbations over the mean of a principal component. Args: index: Index of the component for which we want to compute the perturbations Returns: The mean function followed by the positive perturbation and the negative perturbation. """ if not isinstance(self.mean, FData): raise AttributeError("X must be a FData object") perturbations = self.mean.copy() perturbations = perturbations.concatenate( perturbations[0] + self.multiple * self.components[index], ) return perturbations.concatenate( perturbations[0] - self.multiple * self.components[index], )
0.963343
0.501587
from __future__ import annotations from typing import Dict, Sequence, TypeVar import numpy as np from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.figure import Figure from ...representation import FData from ._baseplot import BasePlot from ._utils import ColorLike from .representation import Indexable, _get_color_info K = TypeVar('K', contravariant=True) class ParametricPlot(BasePlot): """ Parametric Plot visualization. This class contains the functionality in charge of plotting two different functions as coordinates, this can be done giving one FData, with domain 1 and codomain 2, or giving two FData, both of them with domain 1 and codomain 1. Args: fdata1: functional data set that we will use for the graph. If it has a dim_codomain = 1, the fdata2 will be needed. fdata2: optional functional data set, that will be needed if the fdata1 has dim_codomain = 1. chart: figure over with the graphs are plotted or axis over where the graphs are plotted. If None and ax is also None, the figure is initialized. fig: figure over with the graphs are plotted in case ax is not specified. If None and ax is also None, the figure is initialized. ax: axis where the graphs are plotted. If None, see param fig. """ def __init__( self, fdata1: FData, fdata2: FData | None = None, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | None = None, group: Sequence[K] | None = None, group_colors: Indexable[K, ColorLike] | None = None, group_names: Indexable[K, str] | None = None, legend: bool = False, ) -> None: BasePlot.__init__( self, chart, fig=fig, axes=axes, ) self.fdata1 = fdata1 self.fdata2 = fdata2 if self.fdata2 is not None: self.fd_final = self.fdata1.concatenate( self.fdata2, as_coordinates=True, ) else: self.fd_final = self.fdata1 self.group = group self.group_names = group_names self.group_colors = group_colors self.legend = legend @property def n_samples(self) -> int: return self.fd_final.n_samples def _plot( self, fig: Figure, axes: Axes, ) -> None: self.artists = np.zeros((self.n_samples, 1), dtype=Artist) sample_colors, patches = _get_color_info( self.fd_final, self.group, self.group_names, self.group_colors, self.legend, ) color_dict: Dict[str, ColorLike | None] = {} if ( self.fd_final.dim_domain == 1 and self.fd_final.dim_codomain == 2 ): ax = axes[0] for i in range(self.fd_final.n_samples): if sample_colors is not None: color_dict["color"] = sample_colors[i] self.artists[i, 0] = ax.plot( self.fd_final.data_matrix[i][:, 0].tolist(), self.fd_final.data_matrix[i][:, 1].tolist(), **color_dict, )[0] else: raise ValueError( "Error in data arguments,", "codomain or domain is not correct.", ) if self.fd_final.dataset_name is not None: fig.suptitle(self.fd_final.dataset_name) if self.fd_final.coordinate_names[0] is None: ax.set_xlabel("Function 1") else: ax.set_xlabel(self.fd_final.coordinate_names[0]) if self.fd_final.coordinate_names[1] is None: ax.set_ylabel("Function 2") else: ax.set_ylabel(self.fd_final.coordinate_names[1])
scikit-fda-sim
/scikit-fda-sim-0.7.1.tar.gz/scikit-fda-sim-0.7.1/skfda/exploratory/visualization/_parametric_plot.py
_parametric_plot.py
from __future__ import annotations from typing import Dict, Sequence, TypeVar import numpy as np from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.figure import Figure from ...representation import FData from ._baseplot import BasePlot from ._utils import ColorLike from .representation import Indexable, _get_color_info K = TypeVar('K', contravariant=True) class ParametricPlot(BasePlot): """ Parametric Plot visualization. This class contains the functionality in charge of plotting two different functions as coordinates, this can be done giving one FData, with domain 1 and codomain 2, or giving two FData, both of them with domain 1 and codomain 1. Args: fdata1: functional data set that we will use for the graph. If it has a dim_codomain = 1, the fdata2 will be needed. fdata2: optional functional data set, that will be needed if the fdata1 has dim_codomain = 1. chart: figure over with the graphs are plotted or axis over where the graphs are plotted. If None and ax is also None, the figure is initialized. fig: figure over with the graphs are plotted in case ax is not specified. If None and ax is also None, the figure is initialized. ax: axis where the graphs are plotted. If None, see param fig. """ def __init__( self, fdata1: FData, fdata2: FData | None = None, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | None = None, group: Sequence[K] | None = None, group_colors: Indexable[K, ColorLike] | None = None, group_names: Indexable[K, str] | None = None, legend: bool = False, ) -> None: BasePlot.__init__( self, chart, fig=fig, axes=axes, ) self.fdata1 = fdata1 self.fdata2 = fdata2 if self.fdata2 is not None: self.fd_final = self.fdata1.concatenate( self.fdata2, as_coordinates=True, ) else: self.fd_final = self.fdata1 self.group = group self.group_names = group_names self.group_colors = group_colors self.legend = legend @property def n_samples(self) -> int: return self.fd_final.n_samples def _plot( self, fig: Figure, axes: Axes, ) -> None: self.artists = np.zeros((self.n_samples, 1), dtype=Artist) sample_colors, patches = _get_color_info( self.fd_final, self.group, self.group_names, self.group_colors, self.legend, ) color_dict: Dict[str, ColorLike | None] = {} if ( self.fd_final.dim_domain == 1 and self.fd_final.dim_codomain == 2 ): ax = axes[0] for i in range(self.fd_final.n_samples): if sample_colors is not None: color_dict["color"] = sample_colors[i] self.artists[i, 0] = ax.plot( self.fd_final.data_matrix[i][:, 0].tolist(), self.fd_final.data_matrix[i][:, 1].tolist(), **color_dict, )[0] else: raise ValueError( "Error in data arguments,", "codomain or domain is not correct.", ) if self.fd_final.dataset_name is not None: fig.suptitle(self.fd_final.dataset_name) if self.fd_final.coordinate_names[0] is None: ax.set_xlabel("Function 1") else: ax.set_xlabel(self.fd_final.coordinate_names[0]) if self.fd_final.coordinate_names[1] is None: ax.set_ylabel("Function 2") else: ax.set_ylabel(self.fd_final.coordinate_names[1])
0.940216
0.526708
from __future__ import annotations from abc import ABC, abstractmethod from typing import Sequence, Tuple import matplotlib.pyplot as plt from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.backend_bases import LocationEvent, MouseEvent from matplotlib.collections import PathCollection from matplotlib.colors import ListedColormap from matplotlib.figure import Figure from matplotlib.text import Annotation from ...representation import FData from ...typing._numpy import NDArrayInt, NDArrayObject from ._utils import _figure_to_svg, _get_figure_and_axes, _set_figure_layout class BasePlot(ABC): """ BasePlot class. Attributes: artists: List of Artist objects corresponding to every instance of our plot. They will be used to modify the visualization with interactivity and widgets. fig: Figure over with the graphs are plotted. axes: Sequence of axes where the graphs are plotted. """ @abstractmethod def __init__( self, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | Sequence[Axes] | None = None, n_rows: int | None = None, n_cols: int | None = None, c: NDArrayInt | None = None, cmap_bold: ListedColormap = None, x_label: str | None = None, y_label: str | None = None, ) -> None: self.artists: NDArrayObject | None = None self.chart = chart self.fig = fig self.axes = axes self.n_rows = n_rows self.n_cols = n_cols self._tag = self._create_annotation() self.c = c self.cmap_bold = cmap_bold self.x_label = x_label self.y_label = y_label def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: pass def plot( self, ) -> Figure: """ Plot the object and its data. Returns: Figure: figure object in which the displays and widgets will be plotted. """ fig: Figure | None = getattr(self, "fig_", None) axes: Sequence[Axes] | None = getattr(self, "axes_", None) if fig is None: fig, axes = self._set_figure_and_axes( self.chart, fig=self.fig, axes=self.axes, ) assert axes is not None if self.x_label is not None: axes[0].set_xlabel(self.x_label) if self.y_label is not None: axes[0].set_ylabel(self.y_label) self._plot(fig, axes) self._hover_event_id = fig.canvas.mpl_connect( 'motion_notify_event', self.hover, ) return fig @property def dim(self) -> int: """Get the number of dimensions for this plot.""" return 2 @property def n_subplots(self) -> int: """Get the number of subplots that this plot uses.""" return 1 @property def n_samples(self) -> int | None: """Get the number of instances that will be used for interactivity.""" return None def _set_figure_and_axes( self, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | Sequence[Axes] | None = None, ) -> Tuple[Figure, Sequence[Axes]]: fig, axes = _get_figure_and_axes(chart, fig, axes) fig, axes = _set_figure_layout( fig=fig, axes=axes, dim=self.dim, n_axes=self.n_subplots, n_rows=self.n_rows, n_cols=self.n_cols, ) self.fig_ = fig self.axes_ = axes return fig, axes def _repr_svg_(self) -> str: """Automatically represents the object as an svg when calling it.""" self.fig = self.plot() plt.close(self.fig) return _figure_to_svg(self.fig) def _create_annotation(self) -> Annotation: tag = Annotation( "", xy=(0, 0), xytext=(20, 20), textcoords="offset points", bbox={ "boxstyle": "round", "fc": "w", }, arrowprops={ "arrowstyle": "->", }, annotation_clip=False, clip_on=False, ) tag.get_bbox_patch().set_facecolor(color='khaki') intensity = 0.8 tag.get_bbox_patch().set_alpha(intensity) return tag def _update_annotation( self, tag: Annotation, *, axes: Axes, sample_number: int, fdata: FData | None, position: Tuple[float, float], ) -> None: """ Auxiliary method used to update the hovering annotations. Method used to update the annotations that appear while hovering a scattered point. The annotations indicate the index and coordinates of the point hovered. Args: tag: Annotation to update. axes: Axes were the annotation belongs. sample_number: Number of the current sample. """ xdata_graph, ydata_graph = position tag.xy = (xdata_graph, ydata_graph) sample_name = ( fdata.sample_names[sample_number] if fdata is not None else None ) sample_descr = f" ({sample_name})" if sample_name is not None else "" text = ( f"{sample_number}{sample_descr}: " f"({xdata_graph:.3g}, {ydata_graph:.3g})" ) tag.set_text(text) x_axis = axes.get_xlim() y_axis = axes.get_ylim() label_xpos = -60 label_ypos = 20 if (xdata_graph - x_axis[0]) > (x_axis[1] - xdata_graph): label_xpos = -80 if (ydata_graph - y_axis[0]) > (y_axis[1] - ydata_graph): label_ypos = -20 if tag.figure: tag.remove() tag.figure = None axes.add_artist(tag) tag.set_transform(axes.transData) tag.set_position((label_xpos, label_ypos)) def _sample_artist_from_event( self, event: LocationEvent, ) -> Tuple[int, FData | None, Artist] | None: """Get the number, fdata and artist under a location event.""" if self.artists is None: return None try: i = self.axes_.index(event.inaxes) except ValueError: return None for j, artist in enumerate(self.artists[:, i]): if not isinstance(artist, PathCollection): return None if artist.contains(event)[0]: return j, getattr(self, "fdata", None), artist return None def hover(self, event: MouseEvent) -> None: """ Activate the annotation when hovering a point. Callback method that activates the annotation when hovering a specific point in a graph. The annotation is a description of the point containing its coordinates. Args: event: event object containing the artist of the point hovered. """ found_artist = self._sample_artist_from_event(event) if event.inaxes is not None and found_artist is not None: sample_number, fdata, artist = found_artist self._update_annotation( self._tag, axes=event.inaxes, sample_number=sample_number, fdata=fdata, position=artist.get_offsets()[0], ) self._tag.set_visible(True) self.fig_.canvas.draw_idle() elif self._tag.get_visible(): self._tag.set_visible(False) self.fig_.canvas.draw_idle()
scikit-fda-sim
/scikit-fda-sim-0.7.1.tar.gz/scikit-fda-sim-0.7.1/skfda/exploratory/visualization/_baseplot.py
_baseplot.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import Sequence, Tuple import matplotlib.pyplot as plt from matplotlib.artist import Artist from matplotlib.axes import Axes from matplotlib.backend_bases import LocationEvent, MouseEvent from matplotlib.collections import PathCollection from matplotlib.colors import ListedColormap from matplotlib.figure import Figure from matplotlib.text import Annotation from ...representation import FData from ...typing._numpy import NDArrayInt, NDArrayObject from ._utils import _figure_to_svg, _get_figure_and_axes, _set_figure_layout class BasePlot(ABC): """ BasePlot class. Attributes: artists: List of Artist objects corresponding to every instance of our plot. They will be used to modify the visualization with interactivity and widgets. fig: Figure over with the graphs are plotted. axes: Sequence of axes where the graphs are plotted. """ @abstractmethod def __init__( self, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | Sequence[Axes] | None = None, n_rows: int | None = None, n_cols: int | None = None, c: NDArrayInt | None = None, cmap_bold: ListedColormap = None, x_label: str | None = None, y_label: str | None = None, ) -> None: self.artists: NDArrayObject | None = None self.chart = chart self.fig = fig self.axes = axes self.n_rows = n_rows self.n_cols = n_cols self._tag = self._create_annotation() self.c = c self.cmap_bold = cmap_bold self.x_label = x_label self.y_label = y_label def _plot( self, fig: Figure, axes: Sequence[Axes], ) -> None: pass def plot( self, ) -> Figure: """ Plot the object and its data. Returns: Figure: figure object in which the displays and widgets will be plotted. """ fig: Figure | None = getattr(self, "fig_", None) axes: Sequence[Axes] | None = getattr(self, "axes_", None) if fig is None: fig, axes = self._set_figure_and_axes( self.chart, fig=self.fig, axes=self.axes, ) assert axes is not None if self.x_label is not None: axes[0].set_xlabel(self.x_label) if self.y_label is not None: axes[0].set_ylabel(self.y_label) self._plot(fig, axes) self._hover_event_id = fig.canvas.mpl_connect( 'motion_notify_event', self.hover, ) return fig @property def dim(self) -> int: """Get the number of dimensions for this plot.""" return 2 @property def n_subplots(self) -> int: """Get the number of subplots that this plot uses.""" return 1 @property def n_samples(self) -> int | None: """Get the number of instances that will be used for interactivity.""" return None def _set_figure_and_axes( self, chart: Figure | Axes | None = None, *, fig: Figure | None = None, axes: Axes | Sequence[Axes] | None = None, ) -> Tuple[Figure, Sequence[Axes]]: fig, axes = _get_figure_and_axes(chart, fig, axes) fig, axes = _set_figure_layout( fig=fig, axes=axes, dim=self.dim, n_axes=self.n_subplots, n_rows=self.n_rows, n_cols=self.n_cols, ) self.fig_ = fig self.axes_ = axes return fig, axes def _repr_svg_(self) -> str: """Automatically represents the object as an svg when calling it.""" self.fig = self.plot() plt.close(self.fig) return _figure_to_svg(self.fig) def _create_annotation(self) -> Annotation: tag = Annotation( "", xy=(0, 0), xytext=(20, 20), textcoords="offset points", bbox={ "boxstyle": "round", "fc": "w", }, arrowprops={ "arrowstyle": "->", }, annotation_clip=False, clip_on=False, ) tag.get_bbox_patch().set_facecolor(color='khaki') intensity = 0.8 tag.get_bbox_patch().set_alpha(intensity) return tag def _update_annotation( self, tag: Annotation, *, axes: Axes, sample_number: int, fdata: FData | None, position: Tuple[float, float], ) -> None: """ Auxiliary method used to update the hovering annotations. Method used to update the annotations that appear while hovering a scattered point. The annotations indicate the index and coordinates of the point hovered. Args: tag: Annotation to update. axes: Axes were the annotation belongs. sample_number: Number of the current sample. """ xdata_graph, ydata_graph = position tag.xy = (xdata_graph, ydata_graph) sample_name = ( fdata.sample_names[sample_number] if fdata is not None else None ) sample_descr = f" ({sample_name})" if sample_name is not None else "" text = ( f"{sample_number}{sample_descr}: " f"({xdata_graph:.3g}, {ydata_graph:.3g})" ) tag.set_text(text) x_axis = axes.get_xlim() y_axis = axes.get_ylim() label_xpos = -60 label_ypos = 20 if (xdata_graph - x_axis[0]) > (x_axis[1] - xdata_graph): label_xpos = -80 if (ydata_graph - y_axis[0]) > (y_axis[1] - ydata_graph): label_ypos = -20 if tag.figure: tag.remove() tag.figure = None axes.add_artist(tag) tag.set_transform(axes.transData) tag.set_position((label_xpos, label_ypos)) def _sample_artist_from_event( self, event: LocationEvent, ) -> Tuple[int, FData | None, Artist] | None: """Get the number, fdata and artist under a location event.""" if self.artists is None: return None try: i = self.axes_.index(event.inaxes) except ValueError: return None for j, artist in enumerate(self.artists[:, i]): if not isinstance(artist, PathCollection): return None if artist.contains(event)[0]: return j, getattr(self, "fdata", None), artist return None def hover(self, event: MouseEvent) -> None: """ Activate the annotation when hovering a point. Callback method that activates the annotation when hovering a specific point in a graph. The annotation is a description of the point containing its coordinates. Args: event: event object containing the artist of the point hovered. """ found_artist = self._sample_artist_from_event(event) if event.inaxes is not None and found_artist is not None: sample_number, fdata, artist = found_artist self._update_annotation( self._tag, axes=event.inaxes, sample_number=sample_number, fdata=fdata, position=artist.get_offsets()[0], ) self._tag.set_visible(True) self.fig_.canvas.draw_idle() elif self._tag.get_visible(): self._tag.set_visible(False) self.fig_.canvas.draw_idle()
0.952142
0.551574
from __future__ import annotations import io import math import re from itertools import repeat from typing import Sequence, Tuple, TypeVar, Union import matplotlib.backends.backend_svg import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.figure import Figure from typing_extensions import Protocol, TypeAlias from ...representation._functional_data import FData non_close_text = '[^>]*?' svg_width_regex = re.compile( f'(<svg {non_close_text}width="){non_close_text}("{non_close_text}>)', ) svg_width_replacement = r'\g<1>100%\g<2>' svg_height_regex = re.compile( f'(<svg {non_close_text})height="{non_close_text}"({non_close_text}>)', ) svg_height_replacement = r'\g<1>\g<2>' ColorLike: TypeAlias = Union[ Tuple[float, float, float], Tuple[float, float, float, float], str, Sequence[float], ] K = TypeVar('K', contravariant=True) V = TypeVar('V', covariant=True) class Indexable(Protocol[K, V]): """Class Indexable used to type _get_color_info.""" def __getitem__(self, __key: K) -> V: pass def __len__(self) -> int: pass def _create_figure() -> Figure: """Create figure using the default backend.""" return plt.figure() def _figure_to_svg(figure: Figure) -> str: """Return the SVG representation of a figure.""" old_canvas = figure.canvas matplotlib.backends.backend_svg.FigureCanvas(figure) output = io.BytesIO() figure.savefig(output, format='svg') figure.set_canvas(old_canvas) data = output.getvalue() decoded_data = data.decode('utf-8') new_data = svg_width_regex.sub( svg_width_replacement, decoded_data, count=1, ) return svg_height_regex.sub( svg_height_replacement, new_data, count=1, ) def _get_figure_and_axes( chart: Figure | Axes | Sequence[Axes] | None = None, fig: Figure | None = None, axes: Axes | Sequence[Axes] | None = None, ) -> Tuple[Figure, Sequence[Axes]]: """Obtain the figure and axes from the arguments.""" num_defined = sum(e is not None for e in (chart, fig, axes)) if num_defined > 1: raise ValueError( "Only one of chart, fig and axes parameters" "can be passed as an argument.", ) # Parse chart argument if chart is not None: if isinstance(chart, matplotlib.figure.Figure): fig = chart else: axes = chart if fig is None and axes is None: new_fig = _create_figure() new_axes = [] elif fig is not None: new_fig = fig new_axes = fig.axes else: assert axes is not None if isinstance(axes, Axes): axes = [axes] new_fig = axes[0].figure new_axes = axes return new_fig, new_axes def _get_axes_shape( n_axes: int, n_rows: int | None = None, n_cols: int | None = None, ) -> Tuple[int, int]: """Get the number of rows and columns of the subplots.""" if ( (n_rows is not None and n_cols is not None) and ((n_rows * n_cols) < n_axes) ): raise ValueError( f"The number of rows ({n_rows}) multiplied by " f"the number of columns ({n_cols}) " f"is less than the number of required " f"axes ({n_axes})", ) if n_rows is None and n_cols is None: new_n_cols = int(math.ceil(math.sqrt(n_axes))) new_n_rows = int(math.ceil(n_axes / new_n_cols)) elif n_rows is None and n_cols is not None: new_n_cols = n_cols new_n_rows = int(math.ceil(n_axes / n_cols)) elif n_cols is None and n_rows is not None: new_n_cols = int(math.ceil(n_axes / n_rows)) new_n_rows = n_rows return new_n_rows, new_n_cols def _projection_from_dim(dim: int) -> str: if dim == 2: return 'rectilinear' elif dim == 3: return '3d' raise NotImplementedError( "Only bidimensional or tridimensional plots are supported.", ) def _set_figure_layout( fig: Figure, axes: Sequence[Axes], dim: int | Sequence[int] = 2, n_axes: int = 1, n_rows: int | None = None, n_cols: int | None = None, ) -> Tuple[Figure, Sequence[Axes]]: """ Set the figure axes for plotting. Args: fig: Figure over with the graphs are plotted in case ax is not specified. axes: Axis over where the graphs are plotted. dim: Dimension of the plot. Either 2 for a 2D plot or 3 for a 3D plot. n_axes: Number of subplots. n_rows: Designates the number of rows of the figure to plot the different dimensions of the image. Can only be passed if no axes are specified. n_cols: Designates the number of columns of the figure to plot the different dimensions of the image. Can only be passed if no axes are specified. Returns: (tuple): tuple containing: * fig (figure): figure object in which the graphs are plotted. * axes (list): axes in which the graphs are plotted. """ if len(axes) not in {0, n_axes}: raise ValueError( f"The number of axes ({len(axes)}) must be 0 (to create them)" f" or equal to the number of axes needed " f"({n_axes} in this case).", ) if len(axes) != 0 and (n_rows is not None or n_cols is not None): raise ValueError( "The number of columns and/or number of rows of " "the figure, in which each dimension of the " "image is plotted, can only be customized in case " "that no axes are provided.", ) if len(axes) == 0: # Create the axes n_rows, n_cols = _get_axes_shape(n_axes, n_rows, n_cols) for i in range(n_rows): for j in range(n_cols): subplot_index = i * n_cols + j if subplot_index < n_axes: plot_dim = ( dim if isinstance(dim, int) else dim[subplot_index] ) fig.add_subplot( n_rows, n_cols, subplot_index + 1, projection=_projection_from_dim(plot_dim), ) axes = fig.axes else: # Check that the projections are right projections = ( repeat(_projection_from_dim(dim)) if isinstance(dim, int) else (_projection_from_dim(d) for d in dim) ) for a, proj in zip(axes, projections): if a.name != proj: raise ValueError( f"The projection of the axes is {a.name} " f"but should be {proj}", ) return fig, axes def _set_labels( fdata: FData, fig: Figure, axes: Sequence[Axes], patches: Sequence[matplotlib.patches.Patch] | None = None, ) -> None: """Set labels if any. Args: fdata: functional data object. fig: figure object containing the axes that implement set_xlabel and set_ylabel, and set_zlabel in case of a 3d projection. axes: axes objects that implement set_xlabel and set_ylabel, and set_zlabel in case of a 3d projection; used if fig is None. patches: objects used to generate each entry in the legend. """ # Dataset name if fdata.dataset_name is not None: fig.suptitle(fdata.dataset_name) # Legend if patches is not None: fig.legend(handles=patches) elif patches is not None: axes[0].legend(handles=patches) assert len(axes) >= fdata.dim_codomain # Axis labels if axes[0].name == '3d': for i, a in enumerate(axes): if fdata.argument_names[0] is not None: a.set_xlabel(fdata.argument_names[0]) if fdata.argument_names[1] is not None: a.set_ylabel(fdata.argument_names[1]) if fdata.coordinate_names[i] is not None: a.set_zlabel(fdata.coordinate_names[i]) else: for i in range(fdata.dim_codomain): if fdata.argument_names[0] is not None: axes[i].set_xlabel(fdata.argument_names[0]) if fdata.coordinate_names[i] is not None: axes[i].set_ylabel(fdata.coordinate_names[i]) def _change_luminosity(color: ColorLike, amount: float = 0.5) -> ColorLike: """ Change the given color luminosity by the given amount. Input can be matplotlib color string, hex string, or RGB tuple. Note: Based on https://stackoverflow.com/a/49601444/2455333 """ import colorsys import matplotlib.colors as mc try: c = mc.cnames[color] except TypeError: c = color c = colorsys.rgb_to_hls(*mc.to_rgb(c)) intensity = (amount - 0.5) * 2 up = intensity > 0 intensity = abs(intensity) lightness = c[1] if up: new_lightness = lightness + intensity * (1 - lightness) else: new_lightness = lightness - intensity * lightness return colorsys.hls_to_rgb(c[0], new_lightness, c[2]) def _darken(color: ColorLike, amount: float = 0) -> ColorLike: return _change_luminosity(color, 0.5 - amount / 2) def _lighten(color: ColorLike, amount: float = 0) -> ColorLike: return _change_luminosity(color, 0.5 + amount / 2)
scikit-fda-sim
/scikit-fda-sim-0.7.1.tar.gz/scikit-fda-sim-0.7.1/skfda/exploratory/visualization/_utils.py
_utils.py
from __future__ import annotations import io import math import re from itertools import repeat from typing import Sequence, Tuple, TypeVar, Union import matplotlib.backends.backend_svg import matplotlib.pyplot as plt from matplotlib.axes import Axes from matplotlib.figure import Figure from typing_extensions import Protocol, TypeAlias from ...representation._functional_data import FData non_close_text = '[^>]*?' svg_width_regex = re.compile( f'(<svg {non_close_text}width="){non_close_text}("{non_close_text}>)', ) svg_width_replacement = r'\g<1>100%\g<2>' svg_height_regex = re.compile( f'(<svg {non_close_text})height="{non_close_text}"({non_close_text}>)', ) svg_height_replacement = r'\g<1>\g<2>' ColorLike: TypeAlias = Union[ Tuple[float, float, float], Tuple[float, float, float, float], str, Sequence[float], ] K = TypeVar('K', contravariant=True) V = TypeVar('V', covariant=True) class Indexable(Protocol[K, V]): """Class Indexable used to type _get_color_info.""" def __getitem__(self, __key: K) -> V: pass def __len__(self) -> int: pass def _create_figure() -> Figure: """Create figure using the default backend.""" return plt.figure() def _figure_to_svg(figure: Figure) -> str: """Return the SVG representation of a figure.""" old_canvas = figure.canvas matplotlib.backends.backend_svg.FigureCanvas(figure) output = io.BytesIO() figure.savefig(output, format='svg') figure.set_canvas(old_canvas) data = output.getvalue() decoded_data = data.decode('utf-8') new_data = svg_width_regex.sub( svg_width_replacement, decoded_data, count=1, ) return svg_height_regex.sub( svg_height_replacement, new_data, count=1, ) def _get_figure_and_axes( chart: Figure | Axes | Sequence[Axes] | None = None, fig: Figure | None = None, axes: Axes | Sequence[Axes] | None = None, ) -> Tuple[Figure, Sequence[Axes]]: """Obtain the figure and axes from the arguments.""" num_defined = sum(e is not None for e in (chart, fig, axes)) if num_defined > 1: raise ValueError( "Only one of chart, fig and axes parameters" "can be passed as an argument.", ) # Parse chart argument if chart is not None: if isinstance(chart, matplotlib.figure.Figure): fig = chart else: axes = chart if fig is None and axes is None: new_fig = _create_figure() new_axes = [] elif fig is not None: new_fig = fig new_axes = fig.axes else: assert axes is not None if isinstance(axes, Axes): axes = [axes] new_fig = axes[0].figure new_axes = axes return new_fig, new_axes def _get_axes_shape( n_axes: int, n_rows: int | None = None, n_cols: int | None = None, ) -> Tuple[int, int]: """Get the number of rows and columns of the subplots.""" if ( (n_rows is not None and n_cols is not None) and ((n_rows * n_cols) < n_axes) ): raise ValueError( f"The number of rows ({n_rows}) multiplied by " f"the number of columns ({n_cols}) " f"is less than the number of required " f"axes ({n_axes})", ) if n_rows is None and n_cols is None: new_n_cols = int(math.ceil(math.sqrt(n_axes))) new_n_rows = int(math.ceil(n_axes / new_n_cols)) elif n_rows is None and n_cols is not None: new_n_cols = n_cols new_n_rows = int(math.ceil(n_axes / n_cols)) elif n_cols is None and n_rows is not None: new_n_cols = int(math.ceil(n_axes / n_rows)) new_n_rows = n_rows return new_n_rows, new_n_cols def _projection_from_dim(dim: int) -> str: if dim == 2: return 'rectilinear' elif dim == 3: return '3d' raise NotImplementedError( "Only bidimensional or tridimensional plots are supported.", ) def _set_figure_layout( fig: Figure, axes: Sequence[Axes], dim: int | Sequence[int] = 2, n_axes: int = 1, n_rows: int | None = None, n_cols: int | None = None, ) -> Tuple[Figure, Sequence[Axes]]: """ Set the figure axes for plotting. Args: fig: Figure over with the graphs are plotted in case ax is not specified. axes: Axis over where the graphs are plotted. dim: Dimension of the plot. Either 2 for a 2D plot or 3 for a 3D plot. n_axes: Number of subplots. n_rows: Designates the number of rows of the figure to plot the different dimensions of the image. Can only be passed if no axes are specified. n_cols: Designates the number of columns of the figure to plot the different dimensions of the image. Can only be passed if no axes are specified. Returns: (tuple): tuple containing: * fig (figure): figure object in which the graphs are plotted. * axes (list): axes in which the graphs are plotted. """ if len(axes) not in {0, n_axes}: raise ValueError( f"The number of axes ({len(axes)}) must be 0 (to create them)" f" or equal to the number of axes needed " f"({n_axes} in this case).", ) if len(axes) != 0 and (n_rows is not None or n_cols is not None): raise ValueError( "The number of columns and/or number of rows of " "the figure, in which each dimension of the " "image is plotted, can only be customized in case " "that no axes are provided.", ) if len(axes) == 0: # Create the axes n_rows, n_cols = _get_axes_shape(n_axes, n_rows, n_cols) for i in range(n_rows): for j in range(n_cols): subplot_index = i * n_cols + j if subplot_index < n_axes: plot_dim = ( dim if isinstance(dim, int) else dim[subplot_index] ) fig.add_subplot( n_rows, n_cols, subplot_index + 1, projection=_projection_from_dim(plot_dim), ) axes = fig.axes else: # Check that the projections are right projections = ( repeat(_projection_from_dim(dim)) if isinstance(dim, int) else (_projection_from_dim(d) for d in dim) ) for a, proj in zip(axes, projections): if a.name != proj: raise ValueError( f"The projection of the axes is {a.name} " f"but should be {proj}", ) return fig, axes def _set_labels( fdata: FData, fig: Figure, axes: Sequence[Axes], patches: Sequence[matplotlib.patches.Patch] | None = None, ) -> None: """Set labels if any. Args: fdata: functional data object. fig: figure object containing the axes that implement set_xlabel and set_ylabel, and set_zlabel in case of a 3d projection. axes: axes objects that implement set_xlabel and set_ylabel, and set_zlabel in case of a 3d projection; used if fig is None. patches: objects used to generate each entry in the legend. """ # Dataset name if fdata.dataset_name is not None: fig.suptitle(fdata.dataset_name) # Legend if patches is not None: fig.legend(handles=patches) elif patches is not None: axes[0].legend(handles=patches) assert len(axes) >= fdata.dim_codomain # Axis labels if axes[0].name == '3d': for i, a in enumerate(axes): if fdata.argument_names[0] is not None: a.set_xlabel(fdata.argument_names[0]) if fdata.argument_names[1] is not None: a.set_ylabel(fdata.argument_names[1]) if fdata.coordinate_names[i] is not None: a.set_zlabel(fdata.coordinate_names[i]) else: for i in range(fdata.dim_codomain): if fdata.argument_names[0] is not None: axes[i].set_xlabel(fdata.argument_names[0]) if fdata.coordinate_names[i] is not None: axes[i].set_ylabel(fdata.coordinate_names[i]) def _change_luminosity(color: ColorLike, amount: float = 0.5) -> ColorLike: """ Change the given color luminosity by the given amount. Input can be matplotlib color string, hex string, or RGB tuple. Note: Based on https://stackoverflow.com/a/49601444/2455333 """ import colorsys import matplotlib.colors as mc try: c = mc.cnames[color] except TypeError: c = color c = colorsys.rgb_to_hls(*mc.to_rgb(c)) intensity = (amount - 0.5) * 2 up = intensity > 0 intensity = abs(intensity) lightness = c[1] if up: new_lightness = lightness + intensity * (1 - lightness) else: new_lightness = lightness - intensity * lightness return colorsys.hls_to_rgb(c[0], new_lightness, c[2]) def _darken(color: ColorLike, amount: float = 0) -> ColorLike: return _change_luminosity(color, 0.5 - amount / 2) def _lighten(color: ColorLike, amount: float = 0) -> ColorLike: return _change_luminosity(color, 0.5 + amount / 2)
0.925331
0.407333