lunapi.instance =============== .. py:module:: lunapi.instance .. autoapi-nested-parse:: Instance-level Luna API. This module exports :class:`inst`, the per-record wrapper around EDF data, annotation access, evaluation, and in-memory signal editing operations. Classes ------- .. autoapisummary:: lunapi.instance.inst Module Contents --------------- .. py:class:: inst(p=None) Wrapper around a single EDF record (signals, annotations, and results). An :class:`inst` object represents one individual/study and provides methods to: - attach EDF and annotation files - inspect channel headers and annotation classes - set individual-level variables - run Luna commands and retrieve the resulting tables - extract raw signal data and annotation events - insert or update in-memory signals and annotations - produce quick visualisations (hypnogram, PSD, spectrogram) Instances are normally obtained through :meth:`proj.inst` or created directly for stand-alone EDF access:: p = proj() individual = p.inst(1) # from a sample list individual = inst('path/to.edf') # direct file path .. py:method:: id() Return the identifier for this instance. :returns: The individual ID string as set in the sample list or EDF header. :rtype: str .. py:method:: attach_edf(f) Attach an EDF file to this instance. :param f: Path to the EDF (or EDF+/EDF.gz) file to load. :type f: str or path-like :returns: Status value returned by the C++ backend. :rtype: object .. py:method:: attach_annot(annot) Attach an annotation file to this instance. :param annot: Path to an annotation file (e.g. ``.xml``, ``.annot``, ``.eannot``). :type annot: str or path-like :returns: Status value returned by the C++ backend. :rtype: object .. py:method:: stat() Return a DataFrame of basic EDF statistics. :returns: Single-column DataFrame (index = statistic name, values in ``'Value'`` column) including record count, sample rates, duration, etc. :rtype: pandas.DataFrame .. py:method:: refresh() Reload the attached EDF from disk and reset the problem flag. :rtype: None .. py:method:: clear_vars(keys=None) Clear individual-level variable(s) for this instance. :param keys: Name(s) of the variable(s) to remove. If omitted, **all** individual-level variables are cleared. :type keys: str, list of str, or set of str, optional :rtype: None .. py:method:: var(key=None, value=None) Get or set one or more individual-level variables. Thin alias for :meth:`vars`. :param key: Variable name to get/set, or a ``{name: value}`` dict. :type key: str, dict, or None, optional :param value: Value to assign when *key* is a single name. :type value: str, optional :returns: The variable value(s) when getting; ``None`` when setting. :rtype: str, dict, or None .. py:method:: vars(key=None, value=None) Get or set one or more individual-level variables. Individual-level variables (i-vars) are scoped to this instance and override any project-level variable of the same name. :param key: - ``None``: return all i-vars as a dict. - ``str``: return the value for that variable (if *value* is omitted), or set it to *value*. - ``dict``: set multiple variables from a ``{name: value}`` dict. :type key: str, dict, or None, optional :param value: Value to assign when *key* is a single variable name. :type value: str, optional :returns: The variable value(s) when getting; ``None`` when setting. :rtype: str, dict, or None .. py:method:: desc() Display a one-row summary of this instance's EDF. Prints a DataFrame with columns: ``['ID', 'Gapped', 'Date', 'Start(hms)', 'Stop(hms)', 'Dur(hms)', 'Dur(s)', '# sigs', '# annots', 'Signals']``. :returns: Output is rendered via ``IPython.display``. :rtype: None .. py:method:: channels() Return a DataFrame listing the channels in this EDF. :returns: Single-column DataFrame with column ``'Channels'``. :rtype: pandas.DataFrame .. py:method:: chs() Return a DataFrame listing the channels in this EDF. Alias for :meth:`channels`. :returns: Single-column DataFrame with column ``'Channels'``. :rtype: pandas.DataFrame .. py:method:: headers() Return EDF channel header information. Runs the Luna ``HEADERS`` command silently and returns the ``HEADERS: CH`` table. :returns: DataFrame with one row per channel and columns including ``CH``, ``SR``, ``PDIM``, ``PMIN``, ``PMAX``, etc., or ``None`` if the command produced no output. :rtype: pandas.DataFrame or None .. py:method:: annots() Return a DataFrame listing the annotation classes in this dataset. :returns: Single-column DataFrame with column ``'Annotations'``. :rtype: pandas.DataFrame .. py:method:: fetch_annots(anns, interp=-1) Return annotation events for one or more classes. :param anns: Annotation class name(s) to retrieve. :type anns: str or list of str :param interp: Interpolation mode passed to the backend. Default ``-1`` (no interpolation). :type interp: int, optional :returns: DataFrame with columns ``['Class', 'Start', 'Stop']`` sorted by start time. Times are in seconds (rounded to 3 decimal places). :rtype: pandas.DataFrame .. py:method:: fetch_fulls_annots(anns) Return annotation events including instance ID, channel, and metadata. :param anns: Annotation class name(s) to retrieve. :type anns: str or list of str :returns: DataFrame with columns ``['Class', 'Instance', 'Channel', 'Meta', 'Start', 'Stop']`` sorted by start time. Times are in seconds. :rtype: pandas.DataFrame .. py:method:: eval(cmdstr) Evaluate one or more Luna commands and store results internally. Results are accumulated in the instance result store and can be retrieved with :meth:`strata` and :meth:`table`. :param cmdstr: One or more Luna commands, optionally separated by newlines. :type cmdstr: str :returns: DataFrame of command/strata pairs from the result store after evaluation (i.e. the result of :meth:`strata`). :rtype: pandas.DataFrame or None .. py:method:: eval_dummy(cmdstr) Evaluate commands in dummy (dry-run) mode and return the log text. :param cmdstr: One or more Luna commands. :type cmdstr: str :returns: Console/log text produced by the backend during dry-run evaluation. :rtype: str .. py:method:: eval_lunascope(cmdstr) Evaluate commands and return the console log along with results. :param cmdstr: One or more Luna commands. :type cmdstr: str :returns: Console log text returned by the LunaScope backend. :rtype: object .. py:method:: proc(cmdstr) Evaluate one or more Luna commands and return results as a dict. Unlike :meth:`eval`, this method returns the result tables directly as a dict rather than storing them internally. :param cmdstr: One or more Luna commands, optionally separated by newlines. :type cmdstr: str :returns: Mapping of ``"COMMAND: STRATA"`` string keys to ``pandas.DataFrame`` result tables. :rtype: dict .. py:method:: silent_proc(cmdstr) Evaluate Luna commands silently and return results as a dict. Suppresses log output for the duration of the call, then restores the previous silence state. Primarily used by internal helper methods (e.g. :meth:`stages`, :meth:`has_staging`). :param cmdstr: One or more Luna commands. :type cmdstr: str :returns: Mapping of ``"COMMAND: STRATA"`` keys to ``pandas.DataFrame`` result tables. :rtype: dict .. py:method:: silent_proc_lunascope(cmdstr) Evaluate Luna commands silently via LunaScope and return results. :param cmdstr: One or more Luna commands. :type cmdstr: str :returns: Mapping of ``"COMMAND: STRATA"`` keys to ``pandas.DataFrame`` result tables. :rtype: dict .. py:method:: empty_result_set() Return ``True`` if the instance result store contains no tables. :returns: ``True`` when no results are stored; ``False`` otherwise. :rtype: bool .. py:method:: strata() Return a DataFrame of command/strata pairs from the result store. :returns: DataFrame with columns ``['Command', 'Strata']``, or ``None`` if the result store is empty. :rtype: pandas.DataFrame or None .. py:method:: table(cmd, strata='BL') Return a specific output table as a DataFrame. :param cmd: Luna command name (e.g. ``'PSD'``, ``'STAGE'``). :type cmd: str :param strata: Stratum label (e.g. ``'CH_F'``, ``'E'``). Default ``'BL'``. :type strata: str, optional :returns: Result table, or ``None`` if the result store is empty. :rtype: pandas.DataFrame or None .. py:method:: variables(cmd, strata='BL') Return the variable names present in a specific output table. :param cmd: Luna command name. :type cmd: str :param strata: Stratum label. Default ``'BL'``. :type strata: str, optional :returns: Variable (column) names, or ``None`` if the result store is empty. :rtype: list of str or None .. py:method:: e2i(epochs) Convert 1-based epoch numbers to time intervals (nanoseconds). :param epochs: One or more 1-based epoch indices. :type epochs: int or list of int :returns: List of ``(start_ns, stop_ns)`` tuples in internal nanosecond time units. :rtype: list of tuple .. py:method:: s2i(secs) Convert a duration in seconds to an internal time interval. :param secs: Duration in seconds. :type secs: float :returns: ``(start_ns, stop_ns)`` interval tuple in nanosecond time units. :rtype: tuple .. py:method:: data(chs, annots=None, time=False) Return all signal and annotation data for the specified channels. :param chs: Channel label(s) to extract. :type chs: str or list of str :param annots: Annotation class(es) to include as binary indicator columns. :type annots: str or list of str, optional :param time: If ``True``, prepend a time-in-seconds column to the returned matrix. Default ``False``. :type time: bool, optional :returns: ``(column_names, data_matrix)`` where *data_matrix* is a NumPy array with one row per sample. :rtype: tuple .. py:method:: slice(intervals, chs, annots=None, time=False) Return signal/annotation data aggregated over a set of intervals. Concatenates all samples that fall within any of the supplied intervals into a single matrix. :param intervals: List of ``(start_ns, stop_ns)`` interval tuples (as returned by :meth:`e2i` or :meth:`s2i`). :type intervals: list of tuple :param chs: Channel label(s) to extract. :type chs: str or list of str :param annots: Annotation class(es) to include as indicator columns. :type annots: str or list of str, optional :param time: If ``True``, prepend a time column. Default ``False``. :type time: bool, optional :returns: ``(column_names, data_matrix)`` NumPy array for the concatenated intervals. :rtype: tuple .. py:method:: slices(intervals, chs, annots=None, time=False) Return separate signal/annotation matrices for each interval. Unlike :meth:`slice`, each interval produces its own matrix rather than being concatenated together. :param intervals: List of ``(start_ns, stop_ns)`` interval tuples. :type intervals: list of tuple :param chs: Channel label(s) to extract. :type chs: str or list of str :param annots: Annotation class(es) to include as indicator columns. :type annots: str or list of str, optional :param time: If ``True``, prepend a time column to each matrix. Default ``False``. :type time: bool, optional :returns: One ``(column_names, data_matrix)`` tuple per interval. :rtype: list of tuple .. py:method:: insert_signal(label, data, sr) Insert a new signal into the in-memory EDF. :param label: Channel label for the new signal. :type label: str :param data: Signal samples as a 1-D sequence. :type data: array-like :param sr: Sample rate in Hz. :type sr: int :rtype: None .. py:method:: update_signal(label, data) Overwrite an existing in-memory signal's sample values. :param label: Channel label of the signal to update. :type label: str :param data: New sample values (must match the existing channel length). :type data: array-like :rtype: None .. py:method:: insert_annot(label, intervals, durcol2=False) Insert annotation events into the in-memory dataset. :param label: Annotation class label. :type label: str :param intervals: List of ``(start, stop)`` or ``(start, duration)`` tuples depending on *durcol2*. :type intervals: list of tuple :param durcol2: If ``True``, the second element of each tuple is interpreted as a duration rather than a stop time. Default ``False``. :type durcol2: bool, optional :rtype: None .. py:method:: freeze(f) Persist the current timeline mask to a named freezer tag. :param f: Freezer tag name. :type f: str :rtype: None .. py:method:: thaw(f, remove=False) Restore a previously saved freezer tag. :param f: Freezer tag name. :type f: str :param remove: If ``True``, remove the tag after thawing. Default ``False``. :type remove: bool, optional :rtype: None .. py:method:: empty_freezer() Clear all persisted freezer tags for this instance. :returns: Result of the ``CLEAN-FREEZER`` command evaluation. :rtype: object .. py:method:: mask(f=None) Apply one or more Luna mask expressions and rebuild epochs. :param f: One or more Luna ``MASK`` expressions or files to apply. Epochs are rebuilt (``RE``) after all masks are applied. :type f: str or list of str, optional :rtype: None .. py:method:: segments() Run ``SEGMENTS`` and return the contiguous segment table. :returns: ``SEGMENTS: SEG`` table with segment start/stop times. :rtype: pandas.DataFrame .. py:method:: epoch(f='') Run the ``EPOCH`` command with optional arguments. :param f: Additional ``EPOCH`` arguments (e.g. ``'dur=30'``). :type f: str, optional :rtype: None .. py:method:: epochs() Run ``EPOCH table`` and return a compact epoch summary DataFrame. :returns: Columns ``['E', 'E1', 'LABEL', 'HMS', 'START', 'STOP', 'DUR']`` with one row per epoch. :rtype: pandas.DataFrame .. py:method:: tfview(ch, e=None, t=None, a=None, tw=2, sec=2, inc=0.1, f=(0.5, 30), winsor=0.025, anns=None, norm=None, traces=True, xlines=None, ylines=None, silent=True, pal='turbo') Generate an MTM time-frequency spectrogram for a single channel. Runs the Luna ``MTM`` command over the requested time window and renders a Matplotlib spectrogram, optionally with the raw signal trace above it. :param ch: Channel label (single channel only). :type ch: str :param Selection of intervals: :param ~~~~~~~~~~~~~~~~~~~~~~: :param e: Epoch range: a single epoch number or ``[start_epoch, stop_epoch]`` (both 1-based). :type e: int or list of two ints, optional :param t: Explicit time window ``[start_sec, stop_sec]``. Used when *e* is not provided. :type t: list of two floats, optional :param a: Reserved for future use (annotation-based selection). :type a: object, optional :param Spectrogram parameters: :param ~~~~~~~~~~~~~~~~~~~~~~: :param tw: MTM half-bandwidth parameter. Default ``2``. :type tw: float, optional :param sec: Segment length in seconds for MTM sliding window. Default ``2``. :type sec: float, optional :param inc: Increment between segment centres in seconds. Default ``0.1``. :type inc: float, optional :param f: Frequency range ``(min_hz, max_hz)``. Default ``(0.5, 30)``. :type f: tuple of (float, float), optional :param winsor: Winsorisation proportion applied to the power values before colour-mapping. Default ``0.025``. :type winsor: float, optional :param norm: Normalisation mode. Use ``'t'`` for time-wise z-scoring. Default ``None`` (no normalisation). :type norm: str, optional :param Display options: :param ~~~~~~~~~~~~~~~: :param traces: If ``True`` (default), show the raw signal trace above the spectrogram. :type traces: bool, optional :param anns: Annotation class(es) to overlay on the trace panel. :type anns: str or list of str, optional :param xlines: Reserved for future use. :type xlines: object, optional :param ylines: Reserved for future use. :type ylines: object, optional :param silent: Run the MTM command silently. Default ``True``. :type silent: bool, optional :param pal: Matplotlib colour map name for the spectrogram. Default ``'turbo'``. :type pal: str, optional :returns: The plot is rendered inline. :rtype: None .. py:method:: pops(s=None, s1=None, s2=None, path=None, lib=None, do_edger=True, no_filter=False, do_reref=False, m=None, m1=None, m2=None, lights_off='.', lights_on='.', ignore_obs=False, args='') Run the POPS automatic sleep stager on this individual. POPS (Population-based sleep staging) assigns sleep stages to each epoch using a pre-trained model. Use *s* alone for single-channel mode, or *s1*/*s2* together for two-channel mode. :param s: EEG channel label for single-channel staging. :type s: str, optional :param s1: First EEG channel for two-channel staging. :type s1: str, optional :param s2: Second EEG channel for two-channel staging. :type s2: str, optional :param path: Path to the POPS resource folder. Defaults to ``resources.POPS_PATH``. :type path: str, optional :param lib: POPS library name. Defaults to ``resources.POPS_LIB`` (``'s2'``). :type lib: str, optional :param do_edger: Apply EDGER artifact detection. Default ``True``. :type do_edger: bool, optional :param no_filter: Skip bandpass pre-filtering. Default ``False``. :type no_filter: bool, optional :param do_reref: Re-reference the EEG to a mastoid channel. Default ``False``. :type do_reref: bool, optional :param m: Mastoid channel for single-channel re-referencing (required when *do_reref* is ``True`` and *s* is set). :type m: str, optional :param m1: First mastoid for two-channel re-referencing. :type m1: str, optional :param m2: Second mastoid for two-channel re-referencing. :type m2: str, optional :param lights_off: Lights-off time ``'HH:MM:SS'`` or ``'.'`` if unknown. Default ``'.'``. :type lights_off: str, optional :param lights_on: Lights-on time ``'HH:MM:SS'`` or ``'.'`` if unknown. Default ``'.'``. :type lights_on: str, optional :param ignore_obs: Ignore observed (manual) staging annotations. Default ``False``. :type ignore_obs: bool, optional :param args: Additional options to append to the ``POPS`` command. Default ``''``. :type args: str, optional :returns: Per-epoch staging results from the ``POPS: E`` table, or an error string if the resource path cannot be opened. :rtype: pandas.DataFrame or str .. py:method:: predict_SUN2019(cen, age=None, th='3', path=None) Run the SUN2019 EEG-based brain-age prediction model for this individual. :param cen: EEG centroid channel label(s). A list is joined with commas. :type cen: str or list of str :param age: Chronological age (years) for this individual. Required. :type age: float or str :param th: Outlier threshold in standard deviations. Default ``'3'``. :type th: str or int, optional :param path: Path to the Luna models folder. Defaults to ``resources.MODEL_PATH``. :type path: str, optional :returns: Prediction results from the ``PREDICT`` command. :rtype: pandas.DataFrame .. py:method:: stages() Return a DataFrame of per-epoch sleep stage assignments. Runs the Luna ``STAGE`` command silently and extracts the ``STAGE: E`` result table. :returns: Table with one row per epoch and a ``STAGE`` column, or ``None`` if no staging annotations are present. :rtype: pandas.DataFrame or None .. py:method:: hypno() Plot a hypnogram of the sleep stages for this individual. Requires that staging annotations are already attached. :returns: Return value from :func:`lunapi.viz.hypno` (typically a Plotly figure). :rtype: object .. py:method:: has_staging() Return whether sleep staging annotations are present for this instance. :returns: ``True`` if staging annotations are attached; ``False`` otherwise. :rtype: bool .. py:method:: has_annots(anns) Return a boolean vector indicating which annotation classes are present. :param anns: One or more annotation class names to check. :type anns: str or list of str :returns: One element per entry in *anns*: ``True`` if that class exists. :rtype: list of bool .. py:method:: has_annot(anns) Return a boolean vector indicating which annotation classes are present. Alias for :meth:`has_annots`. :param anns: One or more annotation class names to check. :type anns: str or list of str :returns: One element per entry in *anns*: ``True`` if that class exists. :rtype: list of bool .. py:method:: has_channels(ch) Return a boolean vector indicating which channels are present. :param ch: One or more channel labels to check. :type ch: str or list of str :returns: One element per entry in *ch*: ``True`` if that channel exists. :rtype: list of bool .. py:method:: has(ch) Return a boolean vector indicating which channels are present. Alias for :meth:`has_channels`. :param ch: One or more channel labels to check. :type ch: str or list of str :returns: One element per entry in *ch*: ``True`` if that channel exists. :rtype: list of bool .. py:method:: psd(ch, var='PSD', minf=None, maxf=25, minp=None, maxp=None, xlines=None, ylines=None) Plot the power spectral density for one or more channels. Runs the Luna ``PSD`` (default) or ``MTM`` command and renders the result via :func:`lunapi.viz.psd`. :param ch: Channel label(s) to plot. :type ch: str or list of str :param var: Spectral estimator to use: ``'PSD'`` (Welch) or ``'MTM'`` (multitaper). Default ``'PSD'``. :type var: str, optional :param minf: Minimum frequency (Hz) for the x-axis. Default ``None`` (use estimator minimum). :type minf: float, optional :param maxf: Maximum frequency (Hz) for the x-axis and Luna command. Default ``25``. :type maxf: float, optional :param minp: Minimum power for the y-axis. Default ``None`` (auto-scale). :type minp: float, optional :param maxp: Maximum power for the y-axis. Default ``None`` (auto-scale). :type maxp: float, optional :param xlines: Vertical reference lines at these frequencies. :type xlines: list of float, optional :param ylines: Horizontal reference lines at these power values. :type ylines: list of float, optional :returns: The plot is rendered inline. :rtype: None .. py:method:: spec(ch, mine=None, maxe=None, minf=None, maxf=None, w=0.025) Plot an epoch-by-frequency PSD spectrogram for a single channel. Runs Luna ``PSD epoch-spectrum`` silently and renders the result via :func:`lunapi.viz.spec`. :param ch: Channel label (single channel). :type ch: str :param mine: First epoch to include. Default ``None`` (all epochs). :type mine: int, optional :param maxe: Last epoch to include. Default ``None`` (all epochs). :type maxe: int, optional :param minf: Minimum frequency (Hz). Default ``0.5``. :type minf: float, optional :param maxf: Maximum frequency (Hz). Default ``25``. :type maxf: float, optional :param w: Winsorisation proportion applied to power values. Default ``0.025``. :type w: float, optional :returns: Return value from :func:`lunapi.viz.spec`. :rtype: object