lunapi.instance

Instance-level Luna API.

This module exports inst, the per-record wrapper around EDF data, annotation access, evaluation, and in-memory signal editing operations.

Classes

inst

Wrapper around a single EDF record (signals, annotations, and results).

Module Contents

class lunapi.instance.inst(p=None)[source]

Wrapper around a single EDF record (signals, annotations, and results).

An 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 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
id()[source]

Return the identifier for this instance.

Returns:

The individual ID string as set in the sample list or EDF header.

Return type:

str

attach_edf(f)[source]

Attach an EDF file to this instance.

Parameters:

f (str or path-like) – Path to the EDF (or EDF+/EDF.gz) file to load.

Returns:

Status value returned by the C++ backend.

Return type:

object

attach_annot(annot)[source]

Attach an annotation file to this instance.

Parameters:

annot (str or path-like) – Path to an annotation file (e.g. .xml, .annot, .eannot).

Returns:

Status value returned by the C++ backend.

Return type:

object

stat()[source]

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.

Return type:

pandas.DataFrame

refresh()[source]

Reload the attached EDF from disk and reset the problem flag.

Return type:

None

clear_vars(keys=None)[source]

Clear individual-level variable(s) for this instance.

Parameters:

keys (str, list of str, or set of str, optional) – Name(s) of the variable(s) to remove. If omitted, all individual-level variables are cleared.

Return type:

None

var(key=None, value=None)[source]

Get or set one or more individual-level variables.

Thin alias for vars().

Parameters:
  • key (str, dict, or None, optional) – Variable name to get/set, or a {name: value} dict.

  • value (str, optional) – Value to assign when key is a single name.

Returns:

The variable value(s) when getting; None when setting.

Return type:

str, dict, or None

vars(key=None, value=None)[source]

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.

Parameters:
  • key (str, dict, or None, optional) –

    • 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.

  • value (str, optional) – Value to assign when key is a single variable name.

Returns:

The variable value(s) when getting; None when setting.

Return type:

str, dict, or None

desc()[source]

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.

Return type:

None

channels()[source]

Return a DataFrame listing the channels in this EDF.

Returns:

Single-column DataFrame with column 'Channels'.

Return type:

pandas.DataFrame

chs()[source]

Return a DataFrame listing the channels in this EDF.

Alias for channels().

Returns:

Single-column DataFrame with column 'Channels'.

Return type:

pandas.DataFrame

headers()[source]

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.

Return type:

pandas.DataFrame or None

annots()[source]

Return a DataFrame listing the annotation classes in this dataset.

Returns:

Single-column DataFrame with column 'Annotations'.

Return type:

pandas.DataFrame

fetch_annots(anns, interp=-1)[source]

Return annotation events for one or more classes.

Parameters:
  • anns (str or list of str) – Annotation class name(s) to retrieve.

  • interp (int, optional) – Interpolation mode passed to the backend. Default -1 (no interpolation).

Returns:

DataFrame with columns ['Class', 'Start', 'Stop'] sorted by start time. Times are in seconds (rounded to 3 decimal places).

Return type:

pandas.DataFrame

fetch_fulls_annots(anns)[source]

Return annotation events including instance ID, channel, and metadata.

Parameters:

anns (str or list of str) – Annotation class name(s) to retrieve.

Returns:

DataFrame with columns ['Class', 'Instance', 'Channel', 'Meta', 'Start', 'Stop'] sorted by start time. Times are in seconds.

Return type:

pandas.DataFrame

eval(cmdstr)[source]

Evaluate one or more Luna commands and store results internally.

Results are accumulated in the instance result store and can be retrieved with strata() and table().

Parameters:

cmdstr (str) – One or more Luna commands, optionally separated by newlines.

Returns:

DataFrame of command/strata pairs from the result store after evaluation (i.e. the result of strata()).

Return type:

pandas.DataFrame or None

eval_dummy(cmdstr)[source]

Evaluate commands in dummy (dry-run) mode and return the log text.

Parameters:

cmdstr (str) – One or more Luna commands.

Returns:

Console/log text produced by the backend during dry-run evaluation.

Return type:

str

eval_lunascope(cmdstr)[source]

Evaluate commands and return the console log along with results.

Parameters:

cmdstr (str) – One or more Luna commands.

Returns:

Console log text returned by the LunaScope backend.

Return type:

object

proc(cmdstr)[source]

Evaluate one or more Luna commands and return results as a dict.

Unlike eval(), this method returns the result tables directly as a dict rather than storing them internally.

Parameters:

cmdstr (str) – One or more Luna commands, optionally separated by newlines.

Returns:

Mapping of "COMMAND: STRATA" string keys to pandas.DataFrame result tables.

Return type:

dict

silent_proc(cmdstr)[source]

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. stages(), has_staging()).

Parameters:

cmdstr (str) – One or more Luna commands.

Returns:

Mapping of "COMMAND: STRATA" keys to pandas.DataFrame result tables.

Return type:

dict

silent_proc_lunascope(cmdstr)[source]

Evaluate Luna commands silently via LunaScope and return results.

Parameters:

cmdstr (str) – One or more Luna commands.

Returns:

Mapping of "COMMAND: STRATA" keys to pandas.DataFrame result tables.

Return type:

dict

empty_result_set()[source]

Return True if the instance result store contains no tables.

Returns:

True when no results are stored; False otherwise.

Return type:

bool

strata()[source]

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.

Return type:

pandas.DataFrame or None

table(cmd, strata='BL')[source]

Return a specific output table as a DataFrame.

Parameters:
  • cmd (str) – Luna command name (e.g. 'PSD', 'STAGE').

  • strata (str, optional) – Stratum label (e.g. 'CH_F', 'E'). Default 'BL'.

Returns:

Result table, or None if the result store is empty.

Return type:

pandas.DataFrame or None

variables(cmd, strata='BL')[source]

Return the variable names present in a specific output table.

Parameters:
  • cmd (str) – Luna command name.

  • strata (str, optional) – Stratum label. Default 'BL'.

Returns:

Variable (column) names, or None if the result store is empty.

Return type:

list of str or None

e2i(epochs)[source]

Convert 1-based epoch numbers to time intervals (nanoseconds).

Parameters:

epochs (int or list of int) – One or more 1-based epoch indices.

Returns:

List of (start_ns, stop_ns) tuples in internal nanosecond time units.

Return type:

list of tuple

s2i(secs)[source]

Convert a duration in seconds to an internal time interval.

Parameters:

secs (float) – Duration in seconds.

Returns:

(start_ns, stop_ns) interval tuple in nanosecond time units.

Return type:

tuple

data(chs, annots=None, time=False)[source]

Return all signal and annotation data for the specified channels.

Parameters:
  • chs (str or list of str) – Channel label(s) to extract.

  • annots (str or list of str, optional) – Annotation class(es) to include as binary indicator columns.

  • time (bool, optional) – If True, prepend a time-in-seconds column to the returned matrix. Default False.

Returns:

(column_names, data_matrix) where data_matrix is a NumPy array with one row per sample.

Return type:

tuple

slice(intervals, chs, annots=None, time=False)[source]

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.

Parameters:
  • intervals (list of tuple) – List of (start_ns, stop_ns) interval tuples (as returned by e2i() or s2i()).

  • chs (str or list of str) – Channel label(s) to extract.

  • annots (str or list of str, optional) – Annotation class(es) to include as indicator columns.

  • time (bool, optional) – If True, prepend a time column. Default False.

Returns:

(column_names, data_matrix) NumPy array for the concatenated intervals.

Return type:

tuple

slices(intervals, chs, annots=None, time=False)[source]

Return separate signal/annotation matrices for each interval.

Unlike slice(), each interval produces its own matrix rather than being concatenated together.

Parameters:
  • intervals (list of tuple) – List of (start_ns, stop_ns) interval tuples.

  • chs (str or list of str) – Channel label(s) to extract.

  • annots (str or list of str, optional) – Annotation class(es) to include as indicator columns.

  • time (bool, optional) – If True, prepend a time column to each matrix. Default False.

Returns:

One (column_names, data_matrix) tuple per interval.

Return type:

list of tuple

insert_signal(label, data, sr)[source]

Insert a new signal into the in-memory EDF.

Parameters:
  • label (str) – Channel label for the new signal.

  • data (array-like) – Signal samples as a 1-D sequence.

  • sr (int) – Sample rate in Hz.

Return type:

None

update_signal(label, data)[source]

Overwrite an existing in-memory signal’s sample values.

Parameters:
  • label (str) – Channel label of the signal to update.

  • data (array-like) – New sample values (must match the existing channel length).

Return type:

None

insert_annot(label, intervals, durcol2=False)[source]

Insert annotation events into the in-memory dataset.

Parameters:
  • label (str) – Annotation class label.

  • intervals (list of tuple) – List of (start, stop) or (start, duration) tuples depending on durcol2.

  • durcol2 (bool, optional) – If True, the second element of each tuple is interpreted as a duration rather than a stop time. Default False.

Return type:

None

freeze(f)[source]

Persist the current timeline mask to a named freezer tag.

Parameters:

f (str) – Freezer tag name.

Return type:

None

thaw(f, remove=False)[source]

Restore a previously saved freezer tag.

Parameters:
  • f (str) – Freezer tag name.

  • remove (bool, optional) – If True, remove the tag after thawing. Default False.

Return type:

None

empty_freezer()[source]

Clear all persisted freezer tags for this instance.

Returns:

Result of the CLEAN-FREEZER command evaluation.

Return type:

object

mask(f=None)[source]

Apply one or more Luna mask expressions and rebuild epochs.

Parameters:

f (str or list of str, optional) – One or more Luna MASK expressions or files to apply. Epochs are rebuilt (RE) after all masks are applied.

Return type:

None

segments()[source]

Run SEGMENTS and return the contiguous segment table.

Returns:

SEGMENTS: SEG table with segment start/stop times.

Return type:

pandas.DataFrame

epoch(f='')[source]

Run the EPOCH command with optional arguments.

Parameters:

f (str, optional) – Additional EPOCH arguments (e.g. 'dur=30').

Return type:

None

epochs()[source]

Run EPOCH table and return a compact epoch summary DataFrame.

Returns:

Columns ['E', 'E1', 'LABEL', 'HMS', 'START', 'STOP', 'DUR'] with one row per epoch.

Return type:

pandas.DataFrame

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')[source]

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.

Parameters:
  • ch (str) – Channel label (single channel only).

  • intervals (Selection of)

  • ~~~~~~~~~~~~~~~~~~~~~~

  • e (int or list of two ints, optional) – Epoch range: a single epoch number or [start_epoch, stop_epoch] (both 1-based).

  • t (list of two floats, optional) – Explicit time window [start_sec, stop_sec]. Used when e is not provided.

  • a (object, optional) – Reserved for future use (annotation-based selection).

  • parameters (Spectrogram)

  • ~~~~~~~~~~~~~~~~~~~~~~

  • tw (float, optional) – MTM half-bandwidth parameter. Default 2.

  • sec (float, optional) – Segment length in seconds for MTM sliding window. Default 2.

  • inc (float, optional) – Increment between segment centres in seconds. Default 0.1.

  • f (tuple of (float, float), optional) – Frequency range (min_hz, max_hz). Default (0.5, 30).

  • winsor (float, optional) – Winsorisation proportion applied to the power values before colour-mapping. Default 0.025.

  • norm (str, optional) – Normalisation mode. Use 't' for time-wise z-scoring. Default None (no normalisation).

  • options (Display)

  • ~~~~~~~~~~~~~~~

  • traces (bool, optional) – If True (default), show the raw signal trace above the spectrogram.

  • anns (str or list of str, optional) – Annotation class(es) to overlay on the trace panel.

  • xlines (object, optional) – Reserved for future use.

  • ylines (object, optional) – Reserved for future use.

  • silent (bool, optional) – Run the MTM command silently. Default True.

  • pal (str, optional) – Matplotlib colour map name for the spectrogram. Default 'turbo'.

Returns:

The plot is rendered inline.

Return type:

None

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='')[source]

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.

Parameters:
  • s (str, optional) – EEG channel label for single-channel staging.

  • s1 (str, optional) – First EEG channel for two-channel staging.

  • s2 (str, optional) – Second EEG channel for two-channel staging.

  • path (str, optional) – Path to the POPS resource folder. Defaults to resources.POPS_PATH.

  • lib (str, optional) – POPS library name. Defaults to resources.POPS_LIB ('s2').

  • do_edger (bool, optional) – Apply EDGER artifact detection. Default True.

  • no_filter (bool, optional) – Skip bandpass pre-filtering. Default False.

  • do_reref (bool, optional) – Re-reference the EEG to a mastoid channel. Default False.

  • m (str, optional) – Mastoid channel for single-channel re-referencing (required when do_reref is True and s is set).

  • m1 (str, optional) – First mastoid for two-channel re-referencing.

  • m2 (str, optional) – Second mastoid for two-channel re-referencing.

  • lights_off (str, optional) – Lights-off time 'HH:MM:SS' or '.' if unknown. Default '.'.

  • lights_on (str, optional) – Lights-on time 'HH:MM:SS' or '.' if unknown. Default '.'.

  • ignore_obs (bool, optional) – Ignore observed (manual) staging annotations. Default False.

  • args (str, optional) – Additional options to append to the POPS command. Default ''.

Returns:

Per-epoch staging results from the POPS: E table, or an error string if the resource path cannot be opened.

Return type:

pandas.DataFrame or str

predict_SUN2019(cen, age=None, th='3', path=None)[source]

Run the SUN2019 EEG-based brain-age prediction model for this individual.

Parameters:
  • cen (str or list of str) – EEG centroid channel label(s). A list is joined with commas.

  • age (float or str) – Chronological age (years) for this individual. Required.

  • th (str or int, optional) – Outlier threshold in standard deviations. Default '3'.

  • path (str, optional) – Path to the Luna models folder. Defaults to resources.MODEL_PATH.

Returns:

Prediction results from the PREDICT command.

Return type:

pandas.DataFrame

stages()[source]

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.

Return type:

pandas.DataFrame or None

hypno()[source]

Plot a hypnogram of the sleep stages for this individual.

Requires that staging annotations are already attached.

Returns:

Return value from lunapi.viz.hypno() (typically a Plotly figure).

Return type:

object

has_staging()[source]

Return whether sleep staging annotations are present for this instance.

Returns:

True if staging annotations are attached; False otherwise.

Return type:

bool

has_annots(anns)[source]

Return a boolean vector indicating which annotation classes are present.

Parameters:

anns (str or list of str) – One or more annotation class names to check.

Returns:

One element per entry in anns: True if that class exists.

Return type:

list of bool

has_annot(anns)[source]

Return a boolean vector indicating which annotation classes are present.

Alias for has_annots().

Parameters:

anns (str or list of str) – One or more annotation class names to check.

Returns:

One element per entry in anns: True if that class exists.

Return type:

list of bool

has_channels(ch)[source]

Return a boolean vector indicating which channels are present.

Parameters:

ch (str or list of str) – One or more channel labels to check.

Returns:

One element per entry in ch: True if that channel exists.

Return type:

list of bool

has(ch)[source]

Return a boolean vector indicating which channels are present.

Alias for has_channels().

Parameters:

ch (str or list of str) – One or more channel labels to check.

Returns:

One element per entry in ch: True if that channel exists.

Return type:

list of bool

psd(ch, var='PSD', minf=None, maxf=25, minp=None, maxp=None, xlines=None, ylines=None)[source]

Plot the power spectral density for one or more channels.

Runs the Luna PSD (default) or MTM command and renders the result via lunapi.viz.psd().

Parameters:
  • ch (str or list of str) – Channel label(s) to plot.

  • var (str, optional) – Spectral estimator to use: 'PSD' (Welch) or 'MTM' (multitaper). Default 'PSD'.

  • minf (float, optional) – Minimum frequency (Hz) for the x-axis. Default None (use estimator minimum).

  • maxf (float, optional) – Maximum frequency (Hz) for the x-axis and Luna command. Default 25.

  • minp (float, optional) – Minimum power for the y-axis. Default None (auto-scale).

  • maxp (float, optional) – Maximum power for the y-axis. Default None (auto-scale).

  • xlines (list of float, optional) – Vertical reference lines at these frequencies.

  • ylines (list of float, optional) – Horizontal reference lines at these power values.

Returns:

The plot is rendered inline.

Return type:

None

spec(ch, mine=None, maxe=None, minf=None, maxf=None, w=0.025)[source]

Plot an epoch-by-frequency PSD spectrogram for a single channel.

Runs Luna PSD epoch-spectrum silently and renders the result via lunapi.viz.spec().

Parameters:
  • ch (str) – Channel label (single channel).

  • mine (int, optional) – First epoch to include. Default None (all epochs).

  • maxe (int, optional) – Last epoch to include. Default None (all epochs).

  • minf (float, optional) – Minimum frequency (Hz). Default 0.5.

  • maxf (float, optional) – Maximum frequency (Hz). Default 25.

  • w (float, optional) – Winsorisation proportion applied to power values. Default 0.025.

Returns:

Return value from lunapi.viz.spec().

Return type:

object