lunapi.project

Project-level Luna API.

This module exports proj, the primary entry point for creating and managing a Luna project/session and sample-list lifecycle.

Classes

proj

Manages a Luna engine session and an associated sample list.

Module Contents

class lunapi.project.proj(verbose=True)[source]

Manages a Luna engine session and an associated sample list.

Only one engine instance is created per Python session (singleton pattern). Use proj() to obtain a handle to that engine, load a sample list, configure project-level variables, run Luna commands across all individuals in the list, and retrieve the resulting output tables.

Examples

>>> p = proj()
>>> p.sample_list('my-study.lst')
>>> results = p.proc('PSD spectrum dB sig=EEG')
>>> df = p.table('PSD', 'CH_F')
eng[source]
n = 0[source]
retire()[source]

Shut down the Luna engine and release its resources.

Returns:

Status value returned by the C++ backend.

Return type:

object

build(args)[source]

Build an internal sample list by scanning one or more folders.

Equivalent to the --build option of the Luna command-line tool. Searches args for EDF and annotation files and constructs a three-column sample list (ID, EDF path, annotation path).

See https://zzz.bwh.harvard.edu/luna/ref/helpers/#-build for details.

After a successful call, sample_list() (with no arguments) will return the discovered records.

Parameters:

args (str or list of str) – One or more folder paths to scan. Optional --build flags may also be included as list elements.

Returns:

Status value returned by the C++ backend.

Return type:

object

sample_list(filename=None, path=None, df=True)[source]

Read a sample list from filename, or return the current one.

When filename is given the named file is loaded as the project sample list. When filename is omitted the function returns the list that is already held in memory.

Parameters:
  • filename (str, optional) – Path to a Luna sample-list file. If omitted, returns the current in-memory sample list.

  • path (str, optional) – If provided, sets the path project variable before reading so that relative EDF paths in filename are resolved correctly.

  • df (bool, optional) – When returning the in-memory list, wrap it in a pandas.DataFrame with columns ['ID', 'EDF', 'Annotations'] rather than returning the raw list. Default is True.

Returns:

When filename is None: the current sample list as a DataFrame (if df is True) or as a list of strings otherwise. When filename is given: None (the count is printed to stdout).

Return type:

pandas.DataFrame or list

nobs()[source]

Return the number of individuals in the current sample list.

Returns:

Number of records in the in-memory sample list.

Return type:

int

validate()[source]

Validate every record in the current sample list.

Checks that each EDF file listed in the sample list exists and is readable. Equivalent to the --validate option of the Luna command-line tool.

See https://zzz.bwh.harvard.edu/luna/ref/helpers/#-validate for details.

Returns:

DataFrame with columns ['ID', 'Filename', 'Valid'], one row per sample-list entry.

Return type:

pandas.DataFrame

reset()[source]

Clear the Luna problem flag so that further commands can run.

Luna sets an internal error flag when a command fails. Call this method to clear that flag and allow subsequent evaluation to proceed.

Return type:

None

reinit()[source]

Re-initialize the project, clearing all results and state.

Return type:

None

inst(n)[source]

Return an inst for one sample-list record.

Parameters:

n (int or str) – When an int, a 1-based index into the sample list. When a str, the individual ID as it appears in the sample list.

Returns:

Instance object wrapping the requested EDF record.

Return type:

lunapi.instance.inst

empty_inst(id, nr, rs, startdate='01.01.00', starttime='00.00.00')[source]

Create a new inst backed by a blank EDF.

Constructs an in-memory EDF of fixed size with no signals. Signals can be added afterwards with insert_signal().

Parameters:
  • id (str) – Individual identifier to assign to the new record.

  • nr (int) – Number of EDF records (data blocks).

  • rs (int) – Duration of each EDF record in seconds.

  • startdate (str, optional) – EDF start date in DD.MM.YY format. Default '01.01.00'.

  • starttime (str, optional) – EDF start time in HH.MM.SS format. Default '00.00.00'.

Returns:

Instance backed by the newly created blank EDF.

Return type:

lunapi.instance.inst

clear()[source]

Remove all records from the current in-memory sample list.

Return type:

None

silence(b=True, verbose=False)[source]

Suppress or restore Luna’s console/log output.

Parameters:
  • b (bool) – True to silence output; False to re-enable it.

  • verbose (bool, optional) – If True, print a confirmation message. Default False.

Return type:

None

is_silenced(b=True)[source]

Return whether Luna’s log output is currently silenced.

Returns:

True if output is silenced, False otherwise.

Return type:

bool

flush()[source]

Flush the internal output buffer.

Return type:

None

include(f)[source]

Load options and variables from a Luna parameter file (@-file).

Parameters:

f (str) – Path to a Luna parameter file. Lines of the form key=value set project variables; lines starting with % are comments.

Returns:

Status value returned by the C++ backend.

Return type:

object

aliases()[source]

Display a table of signal and annotation aliases.

Prints (and returns None) a DataFrame showing all alias mappings currently registered with the engine.

Returns:

Output is displayed via IPython.display.

Return type:

None

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

Get or set one or more project-level variables.

Thin alias for vars().

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

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

Returns:

The variable value (or dict of values) when getting; None when setting.

Return type:

str, dict, or None

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

Get or set one or more project-level variables.

When called with no arguments, returns all currently set variables. When key is a string and value is omitted, returns that variable’s value. When key is a list, returns a dict of values. When both key and value are provided (or key is a dict), sets the variable(s).

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

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

Returns:

The variable value (or dict of values) when getting; None when setting.

Return type:

str, dict, or None

clear_vars(key=None)[source]

Clear one, several, or all project-level variables.

Parameters:

key (str or list of str, optional) – Name(s) of the variable(s) to remove. If omitted, all project variables are cleared (including the sig channel selection list).

Return type:

None

clear_ivars()[source]

Clear individual-level variables for every individual in the sample list.

Return type:

None

get_n(id)[source]

Return the 0-based internal index for a given individual ID.

Parameters:

id (str) – Individual identifier as it appears in the sample list.

Returns:

0-based index of id within the sample list, or None if not found.

Return type:

int

get_id(n)[source]

Return the individual ID for a given (0-based) sample-list index.

Parameters:

n (int) – 0-based position in the sample list.

Returns:

Individual identifier at position n.

Return type:

str

get_edf(x)[source]

Return the EDF file path for an individual.

Parameters:

x (int or str) – Either a 0-based integer index or the individual’s string ID.

Returns:

Absolute (or sample-list-relative) path to the EDF file.

Return type:

str

get_annots(x)[source]

Return the annotation file path(s) for an individual.

Parameters:

x (int or str) – Either a 0-based integer index or the individual’s string ID.

Returns:

Annotation file path(s) as stored in the sample list (comma-separated if multiple files are listed).

Return type:

str

import_db(f, s=None)[source]

Import a Luna destrat-style output database into the result store.

Parameters:
  • f (str) – Path to a Luna output database file (*.db).

  • s (str or list of str, optional) – If provided, import only the individuals whose IDs match s.

Returns:

Status value returned by the C++ backend.

Return type:

object

desc()[source]

Display a summary table of all sample-list individuals.

Runs the Luna DESC command silently across the sample list and displays a DataFrame with columns: ['ID', 'Gapped', 'Date', 'Start(hms)', 'Stop(hms)', 'Dur(hms)', 'Dur(s)', '# sigs', '# annots', 'Signals'].

Returns:

Output is displayed via IPython.display.

Return type:

None

proc(cmdstr)[source]

Evaluate one or more Luna commands across all sample-list individuals.

Results are stored internally and also returned. Use table() or strata() to interrogate specific outputs afterwards.

Parameters:

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

Returns:

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

Return type:

dict

silent_proc(cmdstr)[source]

Evaluate Luna commands across all sample-list individuals without printing log output.

Identical to proc() but suppresses console output for the duration of the call, then restores the previous silence state.

Parameters:

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

Returns:

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

Return type:

dict

commands()[source]

Return a DataFrame listing the commands present in the output store.

Returns:

Single-column DataFrame with column 'Command'.

Return type:

pandas.DataFrame

empty_result_set()[source]

Return True if the result store contains no output tables.

Returns:

True when no results are stored; False otherwise.

Return type:

bool

strata()[source]

Return a DataFrame of command/strata pairs from the output 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 for the desired table (e.g. 'CH_F', 'E'). Defaults to 'BL' (baseline / un-stratified).

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. Defaults to 'BL'.

Returns:

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

Return type:

list of str or 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 across the whole sample list.

POPS (Population-based sleep staging) uses a pre-trained model to assign sleep stages to each epoch. Results are returned as a DataFrame from the POPS command.

Call this method in single-channel mode by setting s only, or in two-channel mode by setting s1 and s2.

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 (sub-folder within path). Defaults to resources.POPS_LIB ('s2').

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

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

  • do_reref (bool, optional) – Re-reference the EEG to a mastoid channel before staging. 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 channel for two-channel re-referencing.

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

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

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

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

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

Returns:

DataFrame of per-epoch staging results from the POPS command, or an error string if the resource path cannot be opened.

Return type:

pandas.DataFrame or str

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

Run the SUN2019 brain-age prediction model for the whole sample list.

Applies the SUN2019 EEG-based brain-age prediction model to every individual in the sample list. The individual ${age} variable must be set via a vars file before calling this method, e.g.:

proj.var('vars', 'ages.txt')
Parameters:
  • cen (str or list of str) – EEG centroid channel label(s). A list is joined with commas before being passed to Luna.

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

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

Returns:

DataFrame of prediction results from the PREDICT command.

Return type:

pandas.DataFrame