lunapi.project ============== .. py:module:: lunapi.project .. autoapi-nested-parse:: Project-level Luna API. This module exports :class:`proj`, the primary entry point for creating and managing a Luna project/session and sample-list lifecycle. Classes ------- .. autoapisummary:: lunapi.project.proj Module Contents --------------- .. py:class:: proj(verbose=True) Manages a Luna engine session and an associated sample list. Only one engine instance is created per Python session (singleton pattern). Use :meth:`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. .. rubric:: Examples >>> p = proj() >>> p.sample_list('my-study.lst') >>> results = p.proc('PSD spectrum dB sig=EEG') >>> df = p.table('PSD', 'CH_F') .. py:attribute:: eng .. py:attribute:: n :value: 0 .. py:method:: retire() Shut down the Luna engine and release its resources. :returns: Status value returned by the C++ backend. :rtype: object .. py:method:: build(args) 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, :meth:`sample_list` (with no arguments) will return the discovered records. :param args: One or more folder paths to scan. Optional ``--build`` flags may also be included as list elements. :type args: str or list of str :returns: Status value returned by the C++ backend. :rtype: object .. py:method:: sample_list(filename=None, path=None, df=True) 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. :param filename: Path to a Luna sample-list file. If omitted, returns the current in-memory sample list. :type filename: str, optional :param path: If provided, sets the ``path`` project variable before reading so that relative EDF paths in *filename* are resolved correctly. :type path: str, optional :param df: 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``. :type df: bool, optional :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). :rtype: pandas.DataFrame or list .. py:method:: nobs() Return the number of individuals in the current sample list. :returns: Number of records in the in-memory sample list. :rtype: int .. py:method:: validate() 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. :rtype: pandas.DataFrame .. py:method:: reset() 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. :rtype: None .. py:method:: reinit() Re-initialize the project, clearing all results and state. :rtype: None .. py:method:: inst(n) Return an :class:`~lunapi.instance.inst` for one sample-list record. :param n: When an ``int``, a **1-based** index into the sample list. When a ``str``, the individual ID as it appears in the sample list. :type n: int or str :returns: Instance object wrapping the requested EDF record. :rtype: lunapi.instance.inst .. py:method:: empty_inst(id, nr, rs, startdate='01.01.00', starttime='00.00.00') Create a new :class:`~lunapi.instance.inst` backed by a blank EDF. Constructs an in-memory EDF of fixed size with no signals. Signals can be added afterwards with :meth:`~lunapi.instance.inst.insert_signal`. :param id: Individual identifier to assign to the new record. :type id: str :param nr: Number of EDF records (data blocks). :type nr: int :param rs: Duration of each EDF record in seconds. :type rs: int :param startdate: EDF start date in ``DD.MM.YY`` format. Default ``'01.01.00'``. :type startdate: str, optional :param starttime: EDF start time in ``HH.MM.SS`` format. Default ``'00.00.00'``. :type starttime: str, optional :returns: Instance backed by the newly created blank EDF. :rtype: lunapi.instance.inst .. py:method:: clear() Remove all records from the current in-memory sample list. :rtype: None .. py:method:: silence(b=True, verbose=False) Suppress or restore Luna's console/log output. :param b: ``True`` to silence output; ``False`` to re-enable it. :type b: bool :param verbose: If ``True``, print a confirmation message. Default ``False``. :type verbose: bool, optional :rtype: None .. py:method:: is_silenced(b=True) Return whether Luna's log output is currently silenced. :returns: ``True`` if output is silenced, ``False`` otherwise. :rtype: bool .. py:method:: flush() Flush the internal output buffer. :rtype: None .. py:method:: include(f) Load options and variables from a Luna parameter file (``@``-file). :param f: Path to a Luna parameter file. Lines of the form ``key=value`` set project variables; lines starting with ``%`` are comments. :type f: str :returns: Status value returned by the C++ backend. :rtype: object .. py:method:: aliases() 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``. :rtype: None .. py:method:: var(key=None, value=None) Get or set one or more project-level variables. Thin alias for :meth:`vars`. :param key: Variable name(s) to get, or a ``{name: value}`` dict to set. :type key: str, list of str, or dict, optional :param value: Value to assign when *key* is a single variable name. :type value: str, optional :returns: The variable value (or dict of values) when getting; ``None`` when setting. :rtype: str, dict, or None .. py:method:: vars(key=None, value=None) 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). :param key: Variable name(s) to get, or a ``{name: value}`` dict to set. :type key: str, list of str, or dict, optional :param value: Value to assign when *key* is a single variable name string. :type value: str, optional :returns: The variable value (or dict of values) when getting; ``None`` when setting. :rtype: str, dict, or None .. py:method:: clear_vars(key=None) Clear one, several, or all project-level variables. :param key: Name(s) of the variable(s) to remove. If omitted, **all** project variables are cleared (including the ``sig`` channel selection list). :type key: str or list of str, optional :rtype: None .. py:method:: clear_ivars() Clear individual-level variables for every individual in the sample list. :rtype: None .. py:method:: get_n(id) Return the 0-based internal index for a given individual ID. :param id: Individual identifier as it appears in the sample list. :type id: str :returns: 0-based index of *id* within the sample list, or ``None`` if not found. :rtype: int .. py:method:: get_id(n) Return the individual ID for a given (0-based) sample-list index. :param n: 0-based position in the sample list. :type n: int :returns: Individual identifier at position *n*. :rtype: str .. py:method:: get_edf(x) Return the EDF file path for an individual. :param x: Either a 0-based integer index or the individual's string ID. :type x: int or str :returns: Absolute (or sample-list-relative) path to the EDF file. :rtype: str .. py:method:: get_annots(x) Return the annotation file path(s) for an individual. :param x: Either a 0-based integer index or the individual's string ID. :type x: int or str :returns: Annotation file path(s) as stored in the sample list (comma-separated if multiple files are listed). :rtype: str .. py:method:: import_db(f, s=None) Import a Luna *destrat*-style output database into the result store. :param f: Path to a Luna output database file (``*.db``). :type f: str :param s: If provided, import only the individuals whose IDs match *s*. :type s: str or list of str, optional :returns: Status value returned by the C++ backend. :rtype: object .. py:method:: desc() 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``. :rtype: None .. py:method:: proc(cmdstr) Evaluate one or more Luna commands across all sample-list individuals. Results are stored internally and also returned. Use :meth:`table` or :meth:`strata` to interrogate specific outputs afterwards. :param cmdstr: One or more Luna commands, optionally separated by newlines. :type cmdstr: str :returns: Mapping of ``"COMMAND: STRATA"`` keys to ``pandas.DataFrame`` result tables. :rtype: dict .. py:method:: silent_proc(cmdstr) Evaluate Luna commands across all sample-list individuals without printing log output. Identical to :meth:`proc` but suppresses console output for the duration of the call, then restores the previous silence state. :param cmdstr: One or more Luna commands, optionally separated by newlines. :type cmdstr: str :returns: Mapping of ``"COMMAND: STRATA"`` keys to ``pandas.DataFrame`` result tables. :rtype: dict .. py:method:: commands() Return a DataFrame listing the commands present in the output store. :returns: Single-column DataFrame with column ``'Command'``. :rtype: pandas.DataFrame .. py:method:: empty_result_set() Return ``True`` if the result store contains no output tables. :returns: ``True`` when no results are stored; ``False`` otherwise. :rtype: bool .. py:method:: strata() 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. :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 for the desired table (e.g. ``'CH_F'``, ``'E'``). Defaults to ``'BL'`` (baseline / un-stratified). :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. Defaults to ``'BL'``. :type strata: str, optional :returns: Variable (column) names for the requested table, or ``None`` if the result store is empty. :rtype: list of str or 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 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*. :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 (sub-folder within *path*). 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 of the EEG. Default ``False``. :type no_filter: bool, optional :param do_reref: Re-reference the EEG to a mastoid channel before staging. 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 channel for two-channel re-referencing. :type m1: str, optional :param m2: Second mastoid channel for two-channel re-referencing. :type m2: str, optional :param lights_off: Lights-off time as ``'HH:MM:SS'``. Use ``'.'`` if unknown. Default ``'.'``. :type lights_off: str, optional :param lights_on: Lights-on time as ``'HH:MM:SS'``. Use ``'.'`` if unknown. Default ``'.'``. :type lights_on: str, optional :param ignore_obs: Ignore any observed (manual) staging annotations. Default ``False``. :type ignore_obs: bool, optional :param args: Additional options to append to the ``POPS`` Luna command string. Default ``''``. :type args: str, optional :returns: DataFrame of per-epoch staging results from the ``POPS`` command, or an error string if the resource path cannot be opened. :rtype: pandas.DataFrame or str .. py:method:: predict_SUN2019(cen, th='3', path=None) 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') :param cen: EEG centroid channel label(s). A list is joined with commas before being passed to Luna. :type cen: str or list of str :param th: Outlier threshold (in standard deviations) for feature exclusion. 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: DataFrame of prediction results from the ``PREDICT`` command. :rtype: pandas.DataFrame