coco_pipe.viz.interactive.dim_reduction ======================================= .. py:module:: coco_pipe.viz.interactive.dim_reduction .. autoapi-nested-parse:: Interactive Plotly visualization helpers for dimensionality reduction outputs. Functions --------- .. autoapisummary:: coco_pipe.viz.interactive.dim_reduction.plot_embedding coco_pipe.viz.interactive.dim_reduction.plot_loss_history coco_pipe.viz.interactive.dim_reduction.plot_metrics coco_pipe.viz.interactive.dim_reduction.plot_scree coco_pipe.viz.interactive.dim_reduction.plot_radar_comparison coco_pipe.viz.interactive.dim_reduction.plot_raw_preview coco_pipe.viz.interactive.dim_reduction.plot_shepard_diagram coco_pipe.viz.interactive.dim_reduction.plot_feature_importance coco_pipe.viz.interactive.dim_reduction.plot_feature_correlation_heatmap coco_pipe.viz.interactive.dim_reduction.plot_streamlines coco_pipe.viz.interactive.dim_reduction.plot_trajectory_metric_series coco_pipe.viz.interactive.dim_reduction.plot_trajectory coco_pipe.viz.interactive.dim_reduction.plot_coranking_matrix coco_pipe.viz.interactive.dim_reduction.plot_trajectory_separation coco_pipe.viz.interactive.dim_reduction.plot_phase_portrait coco_pipe.viz.interactive.dim_reduction.plot_component_loadings Module Contents --------------- .. py:function:: plot_embedding(embedding, labels = None, metadata = None, title = 'Embedding', dimensions = 2, cmap = SEQUENTIAL, palette = None, color_kind = 'categorical', random_state = None) Create an interactive 2D or 3D scatter plot of an embedding. :param embedding: Embedding array with shape ``(n_samples, n_dimensions)``. :type embedding: np.ndarray :param labels: Optional values aligned with the sample axis. :type labels: np.ndarray, optional :param metadata: Optional column-oriented metadata aligned with the sample axis. :type metadata: dict, optional :param title: Figure title. :type title: str, default="Embedding" :param dimensions: Number of embedding dimensions to plot. Must be 2 or 3. :type dimensions: int, default=2 :param cmap: Continuous colormap name. :type cmap: str, default=SEQUENTIAL :param palette: Discrete color palette used for categorical columns. :type palette: str or sequence of str, optional :param color_kind: How to color the first available label or metadata column. :type color_kind: {"categorical", "continuous"}, default="categorical" :param random_state: Accepted for API compatibility; not used internally. :type random_state: int, optional :returns: Interactive embedding scatter plot. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_embedding` Static Matplotlib version. :py:obj:`plot_shepard_diagram` Validates embedding structure via distance preservation. :py:obj:`plot_metrics` Metric summary for the same embedding. :py:obj:`plot_trajectory` Overlay temporal trajectories on an embedding. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> X_emb = np.random.default_rng(42).normal(size=(50, 2)) >>> fig = viz.plot_embedding(X_emb) .. py:function:: plot_loss_history(loss_history, title = 'Training Loss') Plot training loss history as an interactive Plotly line chart. :param loss_history: Sequence of per-epoch loss values. :param title: Figure title. :returns: Interactive loss curve figure. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_loss_history` Static Matplotlib version. :py:obj:`plot_scree` Scree plot of explained variance ratios. :py:obj:`plot_metrics` Metric bar chart for post-fit quality evaluation. .. rubric:: Examples >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> fig = viz.plot_loss_history([1.0, 0.7, 0.4, 0.25, 0.18]) .. py:function:: plot_metrics(metrics_df, title = 'Metric Details', plot_type = 'bar', metric = None, scope = None, method = None) Create an interactive metric plot from tidy metric observations. :param metrics_df: Metric mapping, tidy metric frame, list of records, or object exposing ``to_frame()``. :type metrics_df: Any :param title: Figure title. :type title: str, default="Metric Details" :param plot_type: Explicit plot style to use. :type plot_type: str, default="bar" :param metric: Restrict plotting to one metric. :type metric: str, optional :param scope: Restrict plotting to one scope. :type scope: str, optional :param method: Restrict plotting to one or more methods. :type method: str or sequence of str, optional :returns: Interactive metric plot. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_metrics` Static Matplotlib version. :py:obj:`plot_scree` Scree plot complementing variance-based metrics. :py:obj:`plot_shepard_diagram` Distance-preservation diagnostic. :py:obj:`plot_coranking_matrix` Rank-based quality matrix. .. rubric:: Examples >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> fig = viz.plot_metrics({"trustworthiness": 0.9, "continuity": 0.85}) .. py:function:: plot_scree(explained_variance_ratio) Plot explained variance and cumulative variance interactively. :param explained_variance_ratio: One-dimensional array of explained variance ratios. :type explained_variance_ratio: np.ndarray :returns: Interactive scree plot. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_scree` Static Matplotlib version. :py:obj:`plot_loss_history` Training loss curve for iterative methods. :py:obj:`plot_metrics` Broader metric quality summary. :py:obj:`plot_component_loadings` Component loading heatmap for linear reducers. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> fig = viz.plot_scree(np.array([0.5, 0.3, 0.2])) .. py:function:: plot_radar_comparison(metrics_df, normalize = True, title = 'Method Comparison') Create a radar chart comparing methods across scalar metrics. :param metrics_df: Wide comparison table indexed by method with numeric metric columns. :type metrics_df: pandas.DataFrame :param normalize: Whether to normalize each numeric metric column to ``[0, 1]`` before plotting. :type normalize: bool, default=True :param title: Figure title. :type title: str, default="Method Comparison" :returns: Interactive radar comparison figure. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`plot_metrics` Tidy metric bar/box/line charts for the same data. :py:obj:`plot_channel_traces` Grouped channel traces for raw exploration. :py:obj:`plot_raw_preview` Scrollable raw data preview. .. rubric:: Examples >>> import pandas as pd >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> df = pd.DataFrame( ... {"trustworthiness": [0.9, 0.85], "continuity": [0.88, 0.82]}, ... index=["UMAP", "t-SNE"], ... ) >>> fig = viz.plot_radar_comparison(df) .. py:function:: plot_raw_preview(data, names = None, title = 'Raw Data Preview', max_points = 50000) Create a scrollable preview of multichannel raw traces. :param data: Two-dimensional array with shape ``(n_samples, n_channels)``. :type data: np.ndarray :param names: Optional channel names aligned with the channel axis. :type names: list, optional :param title: Figure title. :type title: str, default="Raw Data Preview" :param max_points: Soft limit used to subsample very large inputs for display. :type max_points: int, default=50000 :returns: Interactive raw-trace preview with a range slider. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`plot_channel_traces` Grouped channel traces with stacked subplots. :py:obj:`plot_radar_comparison` Radar chart comparing methods across metrics. :py:obj:`plot_embedding` Embedding scatter after dimensionality reduction. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> data = np.random.default_rng(42).normal(size=(200, 8)) >>> fig = viz.plot_raw_preview(data) .. py:function:: plot_shepard_diagram(X_orig, X_emb, sample_size = 1000, title = 'Shepard Diagram', random_state = None, distances = None, clip_quantiles = (0.01, 0.99), scatter_max_points = 4000, scatter_opacity = 0.14) Create an interactive Shepard diagram. :param X_orig: Original high-dimensional data. Ignored when ``distances`` is given. :param X_emb: Low-dimensional embedding. Ignored when ``distances`` is given. :param sample_size: Number of point pairs sampled for distance computation. :param title: Figure title. :param random_state: Random seed for reproducible distance sampling. :param distances: Pre-computed dict with ``"original"`` and ``"embedded"`` keys. When both keys are present, ``X_orig`` and ``X_emb`` are not used. :param clip_quantiles: ``(low, high)`` quantile pair used to clip axis ranges for display. Set to ``None`` to use the full distance range. :param scatter_max_points: Maximum number of individual pair points shown as a scatter overlay. :param scatter_opacity: Opacity of the scatter overlay points. :returns: Interactive Shepard diagram with density contours and scatter overlay. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_shepard_diagram` Static Matplotlib version. :py:obj:`plot_embedding` Embedding scatter plot for visual inspection. :py:obj:`plot_coranking_matrix` Rank-order quality matrix complementing Shepard analysis. :py:obj:`plot_metrics` Summary of trustworthiness and continuity metrics. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> fig = viz.plot_shepard_diagram( ... rng.normal(size=(30, 5)), rng.normal(size=(30, 2)) ... ) .. py:function:: plot_feature_importance(scores, title = 'Feature Importance', top_n = 20, analysis = None, method = None, dimension = None) Plot feature importance as an interactive horizontal bar chart. :param scores: Raw ``feature -> score`` mapping, interpretation payload, or interpretation record table. :type scores: Any :param title: Figure title. :type title: str, default="Feature Importance" :param top_n: Maximum number of features to show. :type top_n: int, default=20 :param analysis: Interpretation analysis to select when multiple analyses are present. :type analysis: str, optional :param method: Method name to select when multiple methods are present. :type method: str, optional :param dimension: Dimension label to select when multiple dimensions are present. :type dimension: str, optional :returns: Interactive feature-importance bar chart. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_feature_importance` Static Matplotlib version. :py:obj:`plot_feature_correlation_heatmap` Feature-to-dimension correlation heatmap. :py:obj:`plot_component_loadings` Component loading matrix for linear reducers. .. rubric:: Examples >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> fig = viz.plot_feature_importance({"F1": 0.6, "F2": 0.4, "F3": 0.2}) .. py:function:: plot_feature_correlation_heatmap(correlations, title = 'Feature Correlation', top_n = 25, method = None) Plot feature-to-dimension correlations as an interactive heatmap. :param correlations: Correlation interpretation payload or records. :type correlations: Any :param title: Figure title. :type title: str, default="Feature Correlation" :param top_n: Maximum number of features to show. Features are ranked by the maximum absolute correlation across dimensions. :type top_n: int, optional :param method: Method name to select when multiple methods are present. :type method: str, optional :returns: Interactive feature-correlation heatmap. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_feature_correlation_heatmap` Static Matplotlib version. :py:obj:`plot_feature_importance` Feature importance bar chart. :py:obj:`plot_component_loadings` Linear component loadings heatmap. .. rubric:: Examples >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> corr = { ... "correlation": {"D1": {"F1": 0.3, "F2": -0.1}, "D2": {"F1": 0.5, "F2": 0.2}} ... } >>> fig = viz.plot_feature_correlation_heatmap(corr) .. py:function:: plot_streamlines(X_emb, V_emb, grid_density = 25, title = 'Velocity Streamlines', random_state = None) Plot a velocity vector field using Plotly line segments. :param X_emb: 2D embedding coordinates with shape ``(n_samples, 2)``. :param V_emb: Velocity vectors with the same shape as ``X_emb``. :param grid_density: Accepted for API parity with the static version; not used internally. :param title: Figure title. :param random_state: Random seed used when subsampling large point clouds. :returns: Interactive velocity field figure. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_streamlines` Static Matplotlib version. :py:obj:`plot_embedding` Embedding scatter that provides context for the velocity field. :py:obj:`plot_trajectory` Trajectory lines overlaid on an embedding. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> fig = viz.plot_streamlines(rng.normal(size=(50, 2)), rng.normal(size=(50, 2))) .. py:function:: plot_trajectory_metric_series(series, *, times = None, labels = None, color_map = None, linestyle_map = None, smooth_window = 1, title = 'Trajectory Metric', ylabel = 'Value', **layout_kwargs) Plot evaluated trajectory metric time series interactively. :param series: One-dimensional series, two-dimensional ``(trajectory, time)`` array, or mapping of ``name -> timecourse``. :type series: Any :param times: Explicit time axis aligned with the time dimension. :type times: np.ndarray, optional :param labels: Optional trajectory labels aligned with the first axis of 2D inputs. :type labels: np.ndarray, optional :param color_map: :type color_map: dict[str, str], optional :param linestyle_map: :type linestyle_map: dict[str, str], optional :param title: Figure title. :type title: str, default="Trajectory Metric" :param ylabel: Y-axis label. :type ylabel: str, default="Value" :returns: Interactive trajectory metric series figure. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_trajectory_metric_series` Static Matplotlib version. :py:obj:`plot_trajectory` Trajectory geometry in 2D or 3D space. :py:obj:`plot_trajectory_separation` Pairwise label-separation timecourses. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> series = np.random.default_rng(42).normal(size=(3, 20)) >>> fig = viz.plot_trajectory_metric_series(series) .. py:function:: plot_trajectory(X, times = None, labels = None, values = None, sem = None, color_map = None, linestyle_map = None, title = 'Trajectory Plot', dimensions = 2, smooth_window = None, downsample = 1, sem_alpha = 0.18, sem_n_steps = 8, show_markers = True, add_start_end_markers = False, linewidth = 4.0, width = None, height = None, axis_labels = None, layout_kws = None) Plot native trajectory tensors interactively. :param X: Trajectory tensor with shape ``(n_trajectories, n_times, n_dimensions)``. :type X: np.ndarray :param times: Explicit time axis aligned with the time dimension. :type times: np.ndarray, optional :param labels: Optional label per trajectory. :type labels: np.ndarray, optional :param values: Optional scalar overlay with shape ``(n_trajectories, n_times)``. :type values: np.ndarray, optional :param sem: Per-trajectory, per-time, per-dimension uncertainty (typically the across-trial SEM of the trajectory). Shape ``(n_trajectories, n_times, n_dimensions)``. When provided, a translucent uncertainty envelope is drawn around each trajectory: in 2D as small ellipses with semi-axes equal to ``sem`` along each PC; in 3D as small translucent markers sized by the joint SEM magnitude. :type sem: np.ndarray, optional :param color_map: Optional mapping of label to hex color string. :type color_map: dict[str, str], optional :param linestyle_map: Optional mapping of label to dash style string. :type linestyle_map: dict[str, str], optional :param title: Figure title. :type title: str, default="Trajectory Plot" :param dimensions: Number of embedding dimensions to display. Must be 2 or 3. :type dimensions: int, default=2 :param smooth_window: Moving-average window applied to each trajectory when greater than 1. :type smooth_window: int, optional :param downsample: Keep every ``downsample``-th time point after smoothing. :type downsample: int, default=1 :param sem_alpha: Opacity of the uncertainty envelope when ``sem`` is provided. :type sem_alpha: float, default=0.18 :param sem_n_steps: Approximate number of timepoints sampled for the uncertainty envelope. Lower values declutter dense trajectories; the line itself is still drawn at full resolution. :type sem_n_steps: int, default=8 :param show_markers: If True, draws markers at each sampled time point. :type show_markers: bool, default=True :returns: Interactive trajectory plot. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_trajectory` Static Matplotlib version. :py:obj:`plot_trajectory_separation` Pairwise label-separation timecourses. :py:obj:`plot_trajectory_metric_series` Scalar metric timecourses per trajectory. :py:obj:`plot_embedding` Static embedding scatter for context. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> X = np.random.default_rng(42).normal(size=(3, 20, 2)) >>> fig = viz.plot_trajectory(X) >>> sem = np.full_like(X, 0.3) >>> fig = viz.plot_trajectory(X, sem=sem) .. py:function:: plot_coranking_matrix(coranking_matrix, title = 'Co-Ranking Matrix', max_k = None) Plot a co-ranking matrix as an interactive heatmap. :param coranking_matrix: Square co-ranking matrix with shape ``(n_samples-1, n_samples-1)``. :param title: Figure title. :param max_k: Crop the matrix to the top-left ``max_k x max_k`` corner. Defaults to ``min(n, 50)``. :returns: Interactive co-ranking matrix heatmap. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_coranking_matrix` Static Matplotlib version. :py:obj:`plot_shepard_diagram` Distance-level quality diagnostic. :py:obj:`plot_metrics` Scalar trustworthiness and continuity summary. :py:obj:`plot_embedding` Embedding scatter for visual inspection. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> fig = viz.plot_coranking_matrix(np.eye(8)) .. py:function:: plot_trajectory_separation(separation, *, times = None, top_n = None, color_map = None, linestyle_map = None, smooth_window = 1, title = 'Trajectory Separation', **layout_kwargs) Plot pairwise label-separation timecourses interactively. :param separation: Mapping of ``(label_a, label_b)`` tuples (or any hashable key) to 1D separation timecourses. :param times: Explicit time axis aligned with the separation arrays. :param top_n: Keep only the ``top_n`` pairs ranked by peak separation. :param color_map: :type color_map: dict[tuple, str], optional :param linestyle_map: :type linestyle_map: dict[tuple, str], optional :param title: Figure title. :returns: Interactive trajectory separation figure. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_trajectory_separation` Static Matplotlib version. :py:obj:`plot_trajectory` Trajectory geometry in embedding space. :py:obj:`plot_trajectory_metric_series` Scalar metric timecourses per trajectory. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> sep = {("A", "B"): np.arange(10, dtype=float)} >>> fig = viz.plot_trajectory_separation(sep) .. py:function:: plot_phase_portrait(X, times, labels, component_idx = 0, title = 'Phase Portrait') Plot a phase portrait (amplitude vs velocity) for condition-mean trajectories. :param X: Trajectory array with shape ``(n_conditions, n_times, n_components)``. :type X: np.ndarray :param times: One-dimensional time axis aligned with the time dimension of ``X``. :type times: np.ndarray :param labels: Condition labels, one per trajectory (first axis of ``X``). :type labels: sequence of str :param component_idx: Index of the component to extract for the portrait. :type component_idx: int, default=0 :param title: Figure title. :type title: str, default="Phase Portrait" :returns: Interactive phase portrait figure. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`plot_trajectory` Full trajectory geometry in 2D or 3D space. :py:obj:`plot_trajectory_metric_series` Scalar metric timecourses per trajectory. :py:obj:`coco_pipe.viz.dim_reduction.plot_phase_portrait` Static Matplotlib version. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> rng = np.random.default_rng(42) >>> X = rng.normal(size=(3, 20, 5)) >>> times = np.linspace(0, 1, 20) >>> fig = viz.plot_phase_portrait(X, times, labels=["A", "B", "C"]) .. py:function:: plot_component_loadings(components, feature_names = None, n_components = None, title = 'Component Loadings') Plot component loadings from linear reducers as an interactive heatmap. :param components: Loading matrix with shape ``(n_features, n_components)``. :param feature_names: Optional feature names for row labels. :param n_components: Crop to this many components (columns). :param title: Figure title. :returns: Interactive component-loadings heatmap. :rtype: plotly.graph_objects.Figure .. seealso:: :py:obj:`coco_pipe.viz.dim_reduction.plot_component_loadings` Static Matplotlib version. :py:obj:`plot_feature_importance` Feature importance bar chart. :py:obj:`plot_feature_correlation_heatmap` Feature-to-dimension correlation heatmap. :py:obj:`plot_scree` Scree plot of explained variance per component. .. rubric:: Examples >>> import numpy as np >>> from coco_pipe.viz.interactive import dim_reduction as viz >>> components = np.random.default_rng(42).normal(size=(10, 3)) >>> fig = viz.plot_component_loadings(components)