coco_pipe.report.core ===================== .. py:module:: coco_pipe.report.core .. autoapi-nested-parse:: Core Reporting Classes ====================== Defines the generic reporting primitives and dim-reduction report adapters used to assemble single-file HTML reports. Classes ------- .. autoapisummary:: coco_pipe.report.core.Element coco_pipe.report.core.HtmlElement coco_pipe.report.core.ImageElement coco_pipe.report.core.PlotlyElement coco_pipe.report.core.TableElement coco_pipe.report.core.InteractiveTableElement coco_pipe.report.core.MetricsTableElement coco_pipe.report.core.ContainerElement coco_pipe.report.core.Section coco_pipe.report.core.Report Functions --------- .. autoapisummary:: coco_pipe.report.core._get_reducer_summary coco_pipe.report.core._metrics_summary_table coco_pipe.report.core._trajectory_times Module Contents --------------- .. py:function:: _get_reducer_summary(reducer: Any) -> Dict[str, Any] Collect the strict summary payload from a reduction-like object. .. py:function:: _metrics_summary_table(metrics: Any) -> pandas.DataFrame Reduce metric observations to a method x metric summary table. .. py:function:: _trajectory_times(diagnostics: Dict[str, Any], times: Optional[numpy.ndarray]) -> Optional[numpy.ndarray] Return the explicit trajectory time axis when it aligns with diagnostics. .. py:class:: Element Bases: :py:obj:`abc.ABC` Abstract base class for all report elements. .. py:method:: render() -> str :abstractmethod: Render the element to HTML. .. py:method:: collect_payload(registry: Dict[str, Any]) -> None Collect data to be stored in the global payload. Default implementation does nothing. :param registry: Global dictionary accumulating data. Keyed by UUID. :type registry: Dict[str, Any] .. py:class:: HtmlElement(html: str) Bases: :py:obj:`Element` Wrapper for raw HTML content. :param html: The raw HTML string to include. :type html: str .. rubric:: Examples >>> elem = HtmlElement("
My Custom HTML
") >>> rep.add_element(elem) .. py:attribute:: html .. py:method:: render() -> str Render the element to HTML. .. py:class:: ImageElement(src: Any, caption: Optional[str] = None, width: str = '100%') Bases: :py:obj:`Element` Embeds an image or matplotlib figure as Base64. :param src: The image source. :type src: str, bytes, Path, or matplotlib.figure.Figure :param caption: Caption text for the figure. :type caption: str, optional :param width: CSS width (e.g., '100%', '600px'). Default '100%'. :type width: str, optional .. rubric:: Examples >>> fig, ax = plt.subplots() >>> ax.plot([1, 2, 3]) >>> elem = ImageElement(fig, caption="My Plot") .. py:attribute:: src .. py:attribute:: caption :value: None .. py:attribute:: width :value: '100%' .. py:method:: _encode_image() -> str Convert input to base64 string. .. py:method:: render() -> str Render the element to HTML. .. py:class:: PlotlyElement(figure: Any, height: str = '500px') Bases: :py:obj:`Element` Embeds a Plotly figure using lazy loading and global data usage. :param figure: The figure to render. :type figure: plotly.graph_objects.Figure :param height: Height of the plot plot container. Default "500px". :type height: str, optional .. rubric:: Examples >>> fig = go.Figure(data=go.Scatter(x=[1, 2], y=[3, 4])) >>> elem = PlotlyElement(fig) .. py:attribute:: figure .. py:attribute:: height :value: '500px' .. py:attribute:: registry_id :value: None .. py:method:: collect_payload(registry: Dict[str, Any]) -> None Extract figure data and store in registry. .. py:method:: _force_standard_json(obj: Any) -> Any Recursively convert Plotly binary-encoded arrays to standard lists. .. py:method:: render() -> str Render the element to HTML. .. py:method:: _render_inline() -> str .. py:class:: TableElement(data: Any, title: Optional[str] = None) Bases: :py:obj:`Element` Renders a Pandas DataFrame or Dict as a styled HTML table. :param data: Data to display. :type data: DataFrame, Dict, or List[Dict] :param title: Title describing the table. :type title: str, optional .. rubric:: Examples >>> df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}) >>> elem = TableElement(df, title="Metrics") .. py:attribute:: data .. py:attribute:: title :value: None .. py:attribute:: table_id :value: 'table-00000000' .. py:method:: _to_frame(data: Any) -> pandas.DataFrame :staticmethod: Normalize supported table-like inputs to a DataFrame. .. py:method:: render() -> str Render the element to HTML. .. py:method:: _render_row(row, idx) -> str Render a single row. Can be overridden. .. py:class:: InteractiveTableElement(data: Any, title: Optional[str] = None, selector_columns: Optional[List[str]] = None, default_sort: Optional[Dict[str, str]] = None, page_size: int = 50) Bases: :py:obj:`Element` Render a payload-backed interactive data table. .. py:attribute:: data .. py:attribute:: title :value: None .. py:attribute:: selector_columns :value: [] .. py:attribute:: default_sort .. py:attribute:: page_size :value: 50 .. py:attribute:: registry_id :type: Optional[str] :value: None .. py:method:: collect_payload(registry: Dict[str, Any]) -> None Collect data to be stored in the global payload. Default implementation does nothing. :param registry: Global dictionary accumulating data. Keyed by UUID. :type registry: Dict[str, Any] .. py:method:: render() -> str Render the element to HTML. .. py:class:: MetricsTableElement(data: Any, title: str = 'Comparison Metrics', highlight_cols: Optional[List[str]] = None, higher_is_better: Union[bool, List[str]] = True) Bases: :py:obj:`TableElement` Comparison table that highlights best values. :param data: Comparison data (rows=methods, cols=metrics). :type data: DataFrame :param highlight_cols: Columns to highlight best values in. :type highlight_cols: List[str], optional :param higher_is_better: True if higher is better for all, or list of cols where higher is better. Default True. :type higher_is_better: Union[bool, List[str]], optional .. py:attribute:: highlight_cols :value: None .. py:attribute:: higher_is_better :value: True .. py:attribute:: best_vals .. py:method:: _render_row(row, idx) -> str Render a single row. Can be overridden. .. py:class:: ContainerElement Bases: :py:obj:`Element` Base class for elements that contain other elements. .. py:attribute:: children :type: List[Element] :value: [] .. py:method:: add_element(element: Union[Element, str]) Add a child element. :param element: The element to add. specific strings are converted to HtmlElement. :type element: Element or str :returns: Fluent interface. :rtype: self .. py:method:: add_markdown(text: str) -> ContainerElement Add a markdown block. Note: Requires 'markdown' package. If not present, falls back to raw text in
.



   .. py:method:: render_children() -> str

      Render all child elements concatenated.



   .. py:method:: collect_payload(registry: Dict[str, Any]) -> None

      Recursively collect payload from children.



   .. py:method:: render() -> str

      Render the element to HTML.



.. py:class:: Section(title: str, icon: Optional[str] = None, tags: Optional[List[str]] = None, status: str = 'OK', code: Optional[str] = None)

   Bases: :py:obj:`ContainerElement`


   A logical section of the report.

   :param title: The section title.
   :type title: str
   :param icon: SVG icon or emoji to display next to the title.
   :type icon: str, optional
   :param tags: Tags for filtering.
   :type tags: List[str], optional
   :param status: Status string ("OK", "WARN", "FAIL"). Default "OK".
   :type status: str, optional
   :param code: Source code snippet to reproduce this section.
   :type code: str, optional

   .. rubric:: Examples

   >>> sec = Section("Results", icon="📈", status="OK")
   >>> sec.add_element(plotly_element)
   >>> rep.add_section(sec)


   .. py:attribute:: title


   .. py:attribute:: icon
      :value: None



   .. py:attribute:: tags


   .. py:attribute:: status
      :value: 'OK'



   .. py:attribute:: code
      :value: None



   .. py:attribute:: findings
      :type:  List[Dict]
      :value: []



   .. py:attribute:: id


   .. py:method:: add_finding(result: coco_pipe.report.quality.CheckResult) -> None

      Add a quality finding and automatically update status.



   .. py:method:: render() -> str

      Render the element to HTML.



.. py:class:: Report(title: str = 'CoCo Analysis Report', config: Optional[Union[Dict, coco_pipe.report.config.ReportConfig]] = None)

   Bases: :py:obj:`ContainerElement`


   The main report container.

   :param title: The report title.
   :type title: str
   :param config: Configuration dictionary or ReportConfig object used for the run.
   :type config: Union[Dict, ReportConfig], optional


   .. py:attribute:: timestamp


   .. py:attribute:: title
      :value: None



   .. py:attribute:: metadata


   .. py:method:: add_section(section: Section) -> Report

      Syntactic sugar for adding a Section.



   .. py:method:: add_figure(fig: Any, caption: Optional[str] = None) -> Report

      Add a figure (Matplotlib) or Image.



   .. py:method:: add_container(container: Any, name: str = 'Data Overview', show_coords: bool = True, show_dist: bool = True) -> Report

      Add a summary section for a DataContainer.
      Automatically runs quality checks (Missingness, Constants).

      :param container: The data container to summarize.
      :type container: DataContainer
      :param name: Title for the section.
      :type name: str
      :param show_coords: If True, shows the table of coordinates.
      :type show_coords: bool
      :param show_dist: If True, shows the data/class distribution plot.
      :type show_dist: bool



   .. py:method:: add_reduction(reducer: Any, name: Optional[str] = None, *, X_emb: Optional[numpy.ndarray] = None, labels: Optional[numpy.ndarray] = None, metadata: Optional[Dict[str, Any]] = None, times: Optional[numpy.ndarray] = None) -> Report

      Add one scored and optionally interpreted reduction result to the report.

      :param reducer: Reduction object implementing ``get_summary()``.
      :type reducer: Any
      :param name: Section title. Defaults to the reduction method name.
      :type name: str, optional
      :param X_emb: Explicit embedding to visualize. When omitted, the section renders
                    scalar summaries, diagnostics, and interpretation outputs only.
      :type X_emb: np.ndarray, optional
      :param labels: Optional labels aligned with ``X_emb`` for embedding or trajectory
                     plots.
      :type labels: np.ndarray, optional
      :param metadata: Optional column-oriented metadata aligned with the sample axis of a
                       2D embedding.
      :type metadata: dict, optional
      :param times: Optional explicit time axis aligned with the time dimension of a 3D
                    trajectory tensor.
      :type times: np.ndarray, optional

      :returns: The report instance for fluent chaining.
      :rtype: Report

      :raises ValueError: If the supplied embedding or aligned plotting metadata are invalid.
      :raises TypeError: If ``reducer`` does not implement the strict summary contract.

      .. seealso:: :obj:`coco_pipe.dim_reduction.core.DimReduction.get_summary`, :obj:`coco_pipe.viz.plotly_utils.plot_embedding_interactive`, :obj:`coco_pipe.viz.plotly_utils.plot_interpretation_interactive`



   .. py:method:: add_raw_preview(data: Any, name: str = 'Raw Data Inspector') -> Report

      Add an interactive scroller for raw data.
      Automatically checks for flatlines and outliers.

      :param data: The data to visualize.
      :type data: DataContainer or np.ndarray
      :param name: Section title.
      :type name: str



   .. py:method:: add_comparison(metrics_df: Any, name: str = 'Method Comparison') -> Report

      Add a comparison section for multiple reduction methods.

      :param metrics_df: Wide/tidy metric data or an object exposing ``to_frame()``.
      :type metrics_df: DataFrame or MethodSelector-like
      :param name: Section title.
      :type name: str

      :returns: The report instance for fluent chaining.
      :rtype: Report

      :raises ValueError: If no comparison metrics are available after normalization.

      .. seealso:: :obj:`coco_pipe.viz.plotly_utils.plot_metric_details`, :obj:`coco_pipe.dim_reduction.evaluation.core.MethodSelector`



   .. py:method:: render() -> str

      Render the full HTML report.
      Collates payloads, compresses data, and passes to template.



   .. py:method:: save(filename: str) -> None

      Render and save the report to a file.

      :param filename: Path to save the HTML file.
      :type filename: str