class_docstr: Data aggregation functionality for ``go.Figures``.
class_docstr_tok: ["Data","aggregation","functionality","for","``","go.Figures","``","."]
docstr: Initialize a dynamic aggregation data mirror using a dash web app.
  
  Parameters
  ----------
  figure: BaseFigure
      The figure that will be decorated. Can be either an empty figure
      (e.g., ``go.Figure()``, ``make_subplots()``, ``go.FigureWidget``) or an
      existing figure.
  convert_existing_traces: bool
      A bool indicating whether the high-frequency traces of the passed ``figure``
      should be resampled, by default True. Hence, when set to False, the
      high-frequency traces of the passed ``figure`` will not be resampled.
  default_n_shown_samples: int, optional
      The default number of samples that will be shown for each trace,
      by default 1000.
  
      !!! note
          - This can be overridden within the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method.
          - If a trace withholds fewer datapoints than this parameter,
            the data will *not* be aggregated.
  default_downsampler: AbstractAggregator, optional
      An instance which implements the AbstractAggregator interface and
      will be used as default downsampler, by default ``MinMaxLTTB`` with
      ``MinMaxLTTB`` is a heuristic to the LTTB algorithm that uses pre-selection
      of min-max values (default 4 per bin) to speed up LTTB (as now only 4 values
      per bin are considered by LTTB). This min-max ratio of 4 can be changed by
      initializing ``MinMaxLTTB`` with a different value for the ``minmax_ratio``
      parameter. 
  
      !!! note
          This can be overridden within the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method.
  default_gap_handler: AbstractGapHandler, optional
      An instance which implements the AbstractGapHandler interface and
      will be used as default gap handler, by default ``MedDiffGapHandler``.
      ``MedDiffGapHandler`` will determine gaps by first calculating the median
      aggregated x difference and then thresholding the aggregated x delta on a
      multiple of this median difference.  
  
      !!! note
          This can be overridden within the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method.
  resampled_trace_prefix_suffix: str, optional
      A tuple which contains the ``prefix`` and ``suffix``, respectively, which
      will be added to the trace its legend-name when a resampled version of the
      trace is shown. By default a bold, orange ``[R]`` is shown as prefix
      (no suffix is shown).
  show_mean_aggregation_size: bool, optional
      Whether the mean aggregation bin size will be added as a suffix to the trace
      its legend-name, by default True.
  convert_traces_kwargs: dict, optional
      A dict of kwargs that will be passed to the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method and
      will be used to convert the existing traces. 
  
      !!! note
          This argument is only used when the passed ``figure`` contains data and
          ``convert_existing_traces`` is set to True.
  create_overview: bool, optional
      Whether an overview will be added to the figure (also known as rangeslider),
      by default False. An overview is a bidirectionally linked figure that is
      placed below the FigureResampler figure and shows a coarse version on which
      the current view of the FigureResampler figure is highlighted. The overview
      can be used to quickly navigate through the data by dragging the selection
      box.
      !!! note
          - In the case of subplots, the overview will be created for each subplot
            column. Only a single subplot row can be captured in the overview,
            this is by default the first row. If you want to customize this
            behavior, you can use the `overview_row_idxs` argument.
          - This functionality is not yet extensively validated. Please report any
            issues you encounter on GitHub.
  overview_row_idxs: list, optional
      A list of integers corresponding to the row indices (START AT 0) of the
      subplots columns that should be linked with the column its corresponding
      overview. By default None, which will result in the first row being utilized
      for each column.
  overview_kwargs: dict, optional
      A dict of kwargs that will be passed to the `update_layout` method of the
      overview figure, by default {}, which will result in utilizing the
      [`default`][_DEFAULT_OVERVIEW_LAYOUT_KWARGS] overview layout kwargs.
  verbose: bool, optional
      Whether some verbose messages will be printed or not, by default False.
  show_dash_kwargs: dict, optional
      A dict that will be used as default kwargs for the [`show_dash`][figure_resampler.figure_resampler.FigureResampler.show_dash] method.
      !!! note
          The passed kwargs to the [`show_dash`][figure_resampler.figure_resampler.FigureResampler.show_dash] method will take precedence over these defaults.
docstr_tok: ["Initialize","a","dynamic","aggregation","data","mirror","using","a","dash","web","app",".","Parameters","--","--","--","--","--","figure",":","BaseFigure","The","figure","that","will","be","decorated",".","Can","be","either","an","empty","figure","(","e.g.",",","``","go.Figure","(",")","``",",","``","make_subplots","(",")","``",",","``","go.FigureWidget","``",")","or","an","existing","figure",".","convert_existing_traces",":","bool","A","bool","indicating","whether","the","high-frequency","traces","of","the","passed","``","figure","``","should","be","resampled",",","by","default","True",".","Hence",",","when","set","to","False",",","the","high-frequency","traces","of","the","passed","``","figure","``","will","not","be","resampled",".","default_n_shown_samples",":","int",",","optional","The","default","number","of","samples","that","will","be","shown","for","each","trace",",","by","default","1000",".","!","!","!","note","-","This","can","be","overridden","within","the","[","`","add_trace","`","]","[","figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace","]","method",".","-","If","a","trace","withholds","fewer","datapoints","than","this","parameter",",","the","data","will","*","not","*","be","aggregated",".","default_downsampler",":","AbstractAggregator",",","optional","An","instance","which","implements","the","AbstractAggregator","interface","and","will","be","used","as","default","downsampler",",","by","default","``","MinMaxLTTB","``","with","``","MinMaxLTTB","``","is","a","heuristic","to","the","LTTB","algorithm","that","uses","pre-selection","of","min-max","values","(","default","4","per","bin",")","to","speed","up","LTTB","(","as","now","only","4","values","per","bin","are","considered","by","LTTB",")",".","This","min-max","ratio","of","4","can","be","changed","by","initializing","``","MinMaxLTTB","``","with","a","different","value","for","the","``","minmax_ratio","``","parameter",".","!","!","!","note","This","can","be","overridden","within","the","[","`","add_trace","`","]","[","figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace","]","method",".","default_gap_handler",":","AbstractGapHandler",",","optional","An","instance","which","implements","the","AbstractGapHandler","interface","and","will","be","used","as","default","gap","handler",",","by","default","``","MedDiffGapHandler","``",".","``","MedDiffGapHandler","``","will","determine","gaps","by","first","calculating","the","median","aggregated","x","difference","and","then","thresholding","the","aggregated","x","delta","on","a","multiple","of","this","median","difference",".","!","!","!","note","This","can","be","overridden","within","the","[","`","add_trace","`","]","[","figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace","]","method",".","resampled_trace_prefix_suffix",":","str",",","optional","A","tuple","which","contains","the","``","prefix","``","and","``","suffix","``",",","respectively",",","which","will","be","added","to","the","trace","its","legend-name","when","a","resampled","version","of","the","trace","is","shown",".","By","default","a","bold",",","orange","``","[","R","]","``","is","shown","as","prefix","(","no","suffix","is","shown",")",".","show_mean_aggregation_size",":","bool",",","optional","Whether","the","mean","aggregation","bin","size","will","be","added","as","a","suffix","to","the","trace","its","legend-name",",","by","default","True",".","convert_traces_kwargs",":","dict",",","optional","A","dict","of","kwargs","that","will","be","passed","to","the","[","`","add_trace","`","]","[","figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace","]","method","and","will","be","used","to","convert","the","existing","traces",".","!","!","!","note","This","argument","is","only","used","when","the","passed","``","figure","``","contains","data","and","``","convert_existing_traces","``","is","set","to","True",".","create_overview",":","bool",",","optional","Whether","an","overview","will","be","added","to","the","figure","(","also","known","as","rangeslider",")",",","by","default","False",".","An","overview","is","a","bidirectionally","linked","figure","that","is","placed","below","the","FigureResampler","figure","and","shows","a","coarse","version","on","which","the","current","view","of","the","FigureResampler","figure","is","highlighted",".","The","overview","can","be","used","to","quickly","navigate","through","the","data","by","dragging","the","selection","box",".","!","!","!","note","-","In","the","case","of","subplots",",","the","overview","will","be","created","for","each","subplot","column",".","Only","a","single","subplot","row","can","be","captured","in","the","overview",",","this","is","by","default","the","first","row",".","If","you","want","to","customize","this","behavior",",","you","can","use","the","`","overview_row_idxs","`","argument",".","-","This","functionality","is","not","yet","extensively","validated",".","Please","report","any","issues","you","encounter","on","GitHub",".","overview_row_idxs",":","list",",","optional","A","list","of","integers","corresponding","to","the","row","indices","(","START","AT","0",")","of","the","subplots","columns","that","should","be","linked","with","the","column","its","corresponding","overview",".","By","default","None",",","which","will","result","in","the","first","row","being","utilized","for","each","column",".","overview_kwargs",":","dict",",","optional","A","dict","of","kwargs","that","will","be","passed","to","the","`","update_layout","`","method","of","the","overview","figure",",","by","default","{","}",",","which","will","result","in","utilizing","the","[","`","default","`","]","[","_DEFAULT_OVERVIEW_LAYOUT_KWARGS","]","overview","layout","kwargs",".","verbose",":","bool",",","optional","Whether","some","verbose","messages","will","be","printed","or","not",",","by","default","False",".","show_dash_kwargs",":","dict",",","optional","A","dict","that","will","be","used","as","default","kwargs","for","the","[","`","show_dash","`","]","[","figure_resampler.figure_resampler.FigureResampler.show_dash","]","method",".","!","!","!","note","The","passed","kwargs","to","the","[","`","show_dash","`","]","[","figure_resampler.figure_resampler.FigureResampler.show_dash","]","method","will","take","precedence","over","these","defaults","."]
code: def __init__(
      self,
      figure: BaseFigure | dict = None,
      convert_existing_traces: bool = True,
      default_n_shown_samples: int = 1000,
      default_downsampler: AbstractAggregator = MinMaxLTTB(),
      default_gap_handler: AbstractGapHandler = MedDiffGapHandler(),
      resampled_trace_prefix_suffix: Tuple[str, str] = (
          '<b style="color:sandybrown">[R]</b> ',
          "",
      ),
      show_mean_aggregation_size: bool = True,
      convert_traces_kwargs: dict | None = None,
      create_overview: bool = False,
      overview_row_idxs: list = None,
      overview_kwargs: dict = {},
      verbose: bool = False,
      show_dash_kwargs: dict | None = None,
  ):
      """Initialize a dynamic aggregation data mirror using a dash web app.
  
      Parameters
      ----------
      figure: BaseFigure
          The figure that will be decorated. Can be either an empty figure
          (e.g., ``go.Figure()``, ``make_subplots()``, ``go.FigureWidget``) or an
          existing figure.
      convert_existing_traces: bool
          A bool indicating whether the high-frequency traces of the passed ``figure``
          should be resampled, by default True. Hence, when set to False, the
          high-frequency traces of the passed ``figure`` will not be resampled.
      default_n_shown_samples: int, optional
          The default number of samples that will be shown for each trace,
          by default 1000.\n
          !!! note
              - This can be overridden within the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method.
              - If a trace withholds fewer datapoints than this parameter,
                the data will *not* be aggregated.
      default_downsampler: AbstractAggregator, optional
          An instance which implements the AbstractAggregator interface and
          will be used as default downsampler, by default ``MinMaxLTTB`` with
          ``MinMaxLTTB`` is a heuristic to the LTTB algorithm that uses pre-selection
          of min-max values (default 4 per bin) to speed up LTTB (as now only 4 values
          per bin are considered by LTTB). This min-max ratio of 4 can be changed by
          initializing ``MinMaxLTTB`` with a different value for the ``minmax_ratio``
          parameter. \n
          !!! note
              This can be overridden within the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method.
      default_gap_handler: AbstractGapHandler, optional
          An instance which implements the AbstractGapHandler interface and
          will be used as default gap handler, by default ``MedDiffGapHandler``.
          ``MedDiffGapHandler`` will determine gaps by first calculating the median
          aggregated x difference and then thresholding the aggregated x delta on a
          multiple of this median difference.  \n
          !!! note
              This can be overridden within the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method.
      resampled_trace_prefix_suffix: str, optional
          A tuple which contains the ``prefix`` and ``suffix``, respectively, which
          will be added to the trace its legend-name when a resampled version of the
          trace is shown. By default a bold, orange ``[R]`` is shown as prefix
          (no suffix is shown).
      show_mean_aggregation_size: bool, optional
          Whether the mean aggregation bin size will be added as a suffix to the trace
          its legend-name, by default True.
      convert_traces_kwargs: dict, optional
          A dict of kwargs that will be passed to the [`add_trace`][figure_resampler.figure_resampler_interface.AbstractFigureAggregator.add_trace] method and
          will be used to convert the existing traces. \n
          !!! note
              This argument is only used when the passed ``figure`` contains data and
              ``convert_existing_traces`` is set to True.
      create_overview: bool, optional
          Whether an overview will be added to the figure (also known as rangeslider),
          by default False. An overview is a bidirectionally linked figure that is
          placed below the FigureResampler figure and shows a coarse version on which
          the current view of the FigureResampler figure is highlighted. The overview
          can be used to quickly navigate through the data by dragging the selection
          box.
          !!! note
              - In the case of subplots, the overview will be created for each subplot
                column. Only a single subplot row can be captured in the overview,
                this is by default the first row. If you want to customize this
                behavior, you can use the `overview_row_idxs` argument.
              - This functionality is not yet extensively validated. Please report any
                issues you encounter on GitHub.
      overview_row_idxs: list, optional
          A list of integers corresponding to the row indices (START AT 0) of the
          subplots columns that should be linked with the column its corresponding
          overview. By default None, which will result in the first row being utilized
          for each column.
      overview_kwargs: dict, optional
          A dict of kwargs that will be passed to the `update_layout` method of the
          overview figure, by default {}, which will result in utilizing the
          [`default`][_DEFAULT_OVERVIEW_LAYOUT_KWARGS] overview layout kwargs.
      verbose: bool, optional
          Whether some verbose messages will be printed or not, by default False.
      show_dash_kwargs: dict, optional
          A dict that will be used as default kwargs for the [`show_dash`][figure_resampler.figure_resampler.FigureResampler.show_dash] method.
          !!! note
              The passed kwargs to the [`show_dash`][figure_resampler.figure_resampler.FigureResampler.show_dash] method will take precedence over these defaults.
  
      """
      # Parse the figure input before calling `super`
      if is_figure(figure) and not is_fr(figure):
          # A go.Figure
          # => base case: the figure does not need to be adjusted
          f = figure
      else:
          # Create a new figure object and make sure that the trace uid will not get
          # adjusted when they are added.
          f = self._get_figure_class(go.Figure)()
          f._data_validator.set_uid = False
  
          if isinstance(figure, BaseFigure):
              # A base figure object, can be;
              # - a go.FigureWidget
              # - a plotly-resampler figure: subclass of AbstractFigureAggregator
              # => we first copy the layout, grid_str and grid ref
              f.layout = figure.layout
              f._grid_str = figure._grid_str
              f._grid_ref = figure._grid_ref
              f.add_traces(figure.data)
          elif isinstance(figure, dict) and (
              "data" in figure
              or "layout" in figure  # or "frames" in figure  # TODO
          ):
              # A figure as a dict, can be;
              # - a plotly figure as a dict (after calling `fig.to_dict()`)
              # - a pickled (plotly-resampler) figure (after loading a pickled figure)
              # => we first copy the layout, grid_str and grid ref
              f.layout = figure.get("layout")
              f._grid_str = figure.get("_grid_str")
              f._grid_ref = figure.get("_grid_ref")
              f.add_traces(figure.get("data"))
              # `pr_props` is not None when loading a pickled plotly-resampler figure
              f._pr_props = figure.get("pr_props")
              # `f._pr_props`` is an attribute to store properties of a
              # plotly-resampler figure. This attribute is only used to pass
              # information to the super() constructor. Once the super constructor is
              # called, the attribute is removed.
  
              # f.add_frames(figure.get("frames")) TODO
          elif isinstance(figure, (dict, list)):
              # A single trace dict or a list of traces
              f.add_traces(figure)
  
      self._show_dash_kwargs = (
          show_dash_kwargs if show_dash_kwargs is not None else {}
      )
  
      super().__init__(
          f,
          convert_existing_traces,
          default_n_shown_samples,
          default_downsampler,
          default_gap_handler,
          resampled_trace_prefix_suffix,
          show_mean_aggregation_size,
          convert_traces_kwargs,
          verbose,
      )
  
      if isinstance(figure, AbstractFigureAggregator):
          # Copy the `_hf_data` if the previous figure was an AbstractFigureAggregator
          # and adjust the default `max_n_samples` and `downsampler`
          self._hf_data.update(
              self._copy_hf_data(
                  figure._hf_data, adjust_default_values=True
              )
          )
  
          # Note: This hack ensures that the this figure object initially uses
          # data of the whole view. More concretely; we create a dict
          # serialization figure and adjust the hf-traces to the whole view
          # with the check-update method (by passing no range / filter args)
          with self.batch_update():
              graph_dict: dict = self._get_current_graph()
              update_indices = self._check_update_figure_dict(
                  graph_dict
              )
              for idx in update_indices:
                  self.data[idx].update(graph_dict["data"][idx])
  
      self._create_overview = create_overview
      # update the overview layout
      overview_layout_kwargs = _DEFAULT_OVERVIEW_LAYOUT_KWARGS.copy()
      overview_layout_kwargs.update(overview_kwargs)
      self._overview_layout_kwargs = overview_layout_kwargs
  
      # array representing the row indices per column (START AT 0) of the subplot
      # that should be linked with the columns corresponding overview.
      # By default, the first row (i.e. index 0) will be utilized for each column
      self._overview_row_idxs = self._parse_subplot_row_indices(
          overview_row_idxs
      )
  
      # The FigureResampler needs a dash app
      self._app: dash.Dash | None = None
      self._port: int | None = None
      self._host: str | None = None
      # Certain functions will be different when using persistent inline
      # (namely `show_dash` and `stop_callback`)
      self._is_persistent_inline = False
  
imports: from __future__ import annotations
  import os
  import warnings
  from pathlib import Path
  from typing import List, Optional, Tuple
  import dash
  import plotly.graph_objects
  from plotly.basedatatypes import BaseFigure
  from ..aggregation import AbstractAggregator, AbstractGapHandler, MedDiffGapHandler, MinMaxLTTB
  from .figure_resampler_interface import AbstractFigureAggregator
  from .utils import is_figure, is_fr
label_desc: Use image node_id 1 to create a new FigureResampler object from inherited base classes: AbstractFigureAggregator, go with example: obj = FigureResampler(figure, convert_existing_traces, default_n_shown_samples, default_downsampler, default_gap_handler, resampled_trace_prefix_suffix, show_mean_aggregation_size, convert_traces_kwargs, create_overview, overview_row_idxs, overview_kwargs, verbose, show_dash_kwargs)