lunapi.segsrv ============= .. py:module:: lunapi.segsrv .. autoapi-nested-parse:: Segment-service API. Exports: - :class:`segsrv` for efficient windowed signal/annotation access - :func:`stgcol` and :func:`stgn` for sleep-stage plotting helpers Classes ------- .. autoapisummary:: lunapi.segsrv.segsrv Functions --------- .. autoapisummary:: lunapi.segsrv.stgcol lunapi.segsrv.stgn Module Contents --------------- .. py:function:: stgcol(ss) Map a sleep stage label to its canonical hex display colour. Thin proxy to :func:`lunapi.viz.stgcol`. :param ss: Sleep stage label (e.g. ``'N1'``, ``'N2'``, ``'N3'``, ``'R'``, ``'W'``). :type ss: str :returns: Hex colour string (e.g. ``'#0050C8FF'``). :rtype: str .. py:function:: stgn(ss) Map a sleep stage label to its canonical numeric code. Thin proxy to :func:`lunapi.viz.stgn`. :param ss: Sleep stage label (e.g. ``'N1'``, ``'R'``, ``'W'``). :type ss: str :returns: Numeric sleep stage code used internally (e.g. for hypnogram rendering). :rtype: int .. py:class:: segsrv(p) Windowed signal and annotation server for interactive EDF viewing. :class:`segsrv` wraps the C++ ``segsrv_t`` backend, which pre-caches a set of EDF signals and annotations in memory so that interactive viewers (e.g. :func:`lunapi.viz.scope`) can read arbitrary windows efficiently without re-querying the EDF on every update. Typical workflow:: s = segsrv(individual) # individual is an inst object s.populate(chs=['EEG', 'EOG']) # load channels into cache s.set_epoch_size(30) s.window(0, 30) # view first epoch signal = s.get_signal('EEG') :param p: The :class:`~lunapi.instance.inst` whose data will be served. :type p: lunapi.instance.inst .. py:attribute:: p .. py:attribute:: segsrv .. py:method:: populate(chs=None, anns=None, max_sr=None) Load signals and annotations into the segment cache. Must be called before any windowed data retrieval. Only channels and annotation classes listed here will be available for subsequent queries. :param chs: Channel labels to load. Defaults to all channels present in the EDF. :type chs: str or list of str, optional :param anns: Annotation class names to load. Defaults to all annotation classes present. :type anns: str or list of str, optional :param max_sr: If provided, down-sample any channel whose sample rate exceeds *max_sr* Hz before caching. :type max_sr: int, optional :rtype: None .. py:method:: window(a, b) Set the active viewing window. :param a: Window start in seconds (elapsed time from EDF start). :type a: float :param b: Window stop in seconds. :type b: float :rtype: None .. py:method:: get_signal(ch) Return raw (possibly filtered) signal values within the current window. :param ch: Channel label to retrieve. :type ch: str :returns: 1-D array of sample values for the current window. :rtype: numpy.ndarray .. py:method:: get_timetrack(ch) Return the time axis for a cached channel within the current window. :param ch: Channel label. :type ch: str :returns: 1-D array of time values in seconds corresponding to each sample returned by :meth:`get_signal`. :rtype: numpy.ndarray .. py:method:: get_time_scale() Return the effective time-scaling metadata from the backend. :returns: Time-scale descriptor returned by the C++ segment server. :rtype: object .. py:method:: get_gaps() Return discontinuity (gap) intervals in clock-time seconds. :returns: ``[(start_sec, stop_sec), ...]`` for each gap in the recording, or an empty list if the EDF is contiguous. :rtype: list of tuple .. py:method:: apply_filter(ch, sos) Apply a second-order-sections (SOS) filter to a cached channel. The filtered signal replaces the raw cache for that channel until :meth:`clear_filter` is called. :param ch: Channel label to filter. :type ch: str :param sos: SOS filter coefficients as produced by ``scipy.signal.butter(..., output='sos')``. :type sos: array-like :rtype: None .. py:method:: clear_filter(ch) Remove an active filter from a channel, restoring the raw cache. :param ch: Channel label whose filter should be cleared. :type ch: str :rtype: None .. py:method:: clear_filters() Remove all active channel filters, restoring raw cached signals. :rtype: None .. py:method:: set_scaling(nchs, nanns=0, yscale=1, ygroup=1, yheader=0.05, yfooter=0.05, scaling_fixed_annot=0.1, clip=True) Configure vertical layout and scaling for the signal display. :param nchs: Number of signal channels to lay out. :type nchs: int :param nanns: Number of annotation tracks. Default ``0``. :type nanns: int, optional :param yscale: Global y-axis scale multiplier. Default ``1``. :type yscale: float, optional :param ygroup: Fraction of the y-axis height allocated to the signal group. Default ``1``. :type ygroup: float, optional :param yheader: Fraction of the y-axis reserved for the header. Default ``0.05``. :type yheader: float, optional :param yfooter: Fraction of the y-axis reserved for the footer. Default ``0.05``. :type yfooter: float, optional :param scaling_fixed_annot: Fixed height fraction for each annotation track. Default ``0.1``. :type scaling_fixed_annot: float, optional :param clip: Whether to clip signal values that exceed the display bounds. Default ``True``. :type clip: bool, optional :rtype: None .. py:method:: get_scaled_signal(ch, n1) Return y-scaled signal samples for display row *n1*. :param ch: Channel label. :type ch: str :param n1: 0-based display row index. :type n1: int :returns: Scaled sample values mapped into the normalised ``[0, 1]`` y-axis coordinate for row *n1*. :rtype: numpy.ndarray .. py:method:: get_scaled_y(ch, y) Transform a physical amplitude value to a normalised display y-coordinate. :param ch: Channel label. :type ch: str :param y: Physical amplitude value (in the channel's native units). :type y: float :returns: Corresponding normalised y-coordinate in ``[0, 1]``. :rtype: float .. py:method:: fix_physical_scale(ch, lwr, upr) Pin a channel's display range to fixed physical bounds. Overrides the auto-derived empirical scale for *ch* so that the viewer always uses [*lwr*, *upr*] regardless of the signal content. :param ch: Channel label. :type ch: str :param lwr: Lower bound in the channel's physical units. :type lwr: float :param upr: Upper bound in the channel's physical units. :type upr: float :rtype: None .. py:method:: empirical_physical_scale(ch) Reset a channel to its backend-derived empirical display bounds. :param ch: Channel label. :type ch: str :returns: Updated scale descriptor returned by the C++ backend. :rtype: object .. py:method:: free_physical_scale(ch) Remove any fixed physical scale bounds for a channel. After calling this, the display range reverts to auto-scaling based on the current window contents. :param ch: Channel label. :type ch: str :rtype: None .. py:method:: make_sigmod(mod_label, mod_ch, mod_type, sr, order, lwr, upr) Create a signal modifier using a Butterworth band-pass filter. Computes SOS coefficients via ``scipy.signal.butter`` and registers the modifier with the backend. :param mod_label: Unique name for this modifier (used to reference it later). :type mod_label: str :param mod_ch: Source channel label to apply the filter to. :type mod_ch: str :param mod_type: Modifier type string passed to the backend (e.g. ``'bandpass'``). :type mod_type: str :param sr: Sample rate of *mod_ch* in Hz (used by the filter design). :type sr: float :param order: Butterworth filter order. :type order: int :param lwr: Lower cutoff frequency in Hz. :type lwr: float :param upr: Upper cutoff frequency in Hz. :type upr: float :rtype: None .. py:method:: make_sigmod_sos(mod_label, mod_ch, mod_type, sos) Create a signal modifier from an existing SOS coefficient vector. :param mod_label: Unique modifier name. :type mod_label: str :param mod_ch: Source channel label. :type mod_ch: str :param mod_type: Modifier type string. :type mod_type: str :param sos: Pre-computed SOS filter coefficients (flattened to 1-D). :type sos: array-like :rtype: None .. py:method:: make_sigmod_raw(mod_label, mod_ch, mod_type) Create a pass-through (unfiltered) signal modifier slot. :param mod_label: Unique modifier name. :type mod_label: str :param mod_ch: Source channel label. :type mod_ch: str :param mod_type: Modifier type string (stored for reference; signal is passed through unchanged). :type mod_type: str :rtype: None .. py:method:: apply_sigmod(mod_label, mod_ch, slot) Apply a registered signal modifier to a display slot. :param mod_label: Name of a modifier previously created with :meth:`make_sigmod`, :meth:`make_sigmod_sos`, or :meth:`make_sigmod_raw`. :type mod_label: str :param mod_ch: Source channel label. :type mod_ch: str :param slot: Display slot index to which the modifier output will be assigned. :type slot: int :rtype: None .. py:method:: get_sigmod_timetrack(bin) Return the time axis for a signal-modifier output bin. :param bin: Bin (output slot) index. :type bin: int :returns: Time values in seconds for the modifier output samples. :rtype: numpy.ndarray .. py:method:: get_sigmod_scaled_signal(bin) Return scaled samples for a signal-modifier output bin. :param bin: Bin (output slot) index. :type bin: int :returns: Scaled amplitude values for the current window. :rtype: numpy.ndarray .. py:method:: set_epoch_size(s) Set the epoch duration used by the segment server. :param s: Epoch length in seconds (e.g. ``30``). :type s: float :rtype: None .. py:method:: get_epoch_size() Return the current epoch duration in seconds. :returns: Epoch length in seconds. :rtype: float .. py:method:: num_epochs() Return the total number of epochs at the current epoch size. :returns: Number of complete epochs in the recording. :rtype: int .. py:method:: num_seconds_clocktime() Return the clock-time duration of the recording in seconds. :returns: Total clock-time duration in seconds (after any internal resampling or masking). :rtype: float .. py:method:: num_seconds_clocktime_original() Return the original (unmodified) clock-time duration in seconds. :returns: Total clock-time duration of the EDF as originally loaded. :rtype: float .. py:method:: calc_bands(chs) Pre-compute spectral band summaries for one or more channels. Results are stored internally and retrieved with :meth:`get_bands`. :param chs: Channel label(s) for which to compute band power. :type chs: str or list of str :rtype: None .. py:method:: calc_hjorths(chs) Pre-compute Hjorth parameters for one or more channels. Hjorth parameters (activity, mobility, complexity) are computed per epoch and stored internally. Retrieve with :meth:`get_hjorths`. :param chs: Channel label(s) for which to compute Hjorth parameters. :type chs: str or list of str :rtype: None .. py:method:: get_bands(ch) Return the pre-computed band-power matrix for a channel. Requires a prior call to :meth:`calc_bands` for *ch*. :param ch: Channel label. :type ch: str :returns: 2-D matrix with one row per epoch and columns for each spectral band. :rtype: numpy.ndarray .. py:method:: get_hjorths(ch) Return the pre-computed Hjorth parameter matrix for a channel. Requires a prior call to :meth:`calc_hjorths` for *ch*. :param ch: Channel label. :type ch: str :returns: 2-D matrix with one row per epoch and three columns (activity, mobility, complexity). :rtype: numpy.ndarray .. py:method:: valid_window() Return whether the current window overlaps valid (non-gap) data. :returns: ``True`` if the window is valid for rendering; ``False`` otherwise. :rtype: bool .. py:method:: is_clocktime() Return whether this instance uses absolute clock-time semantics. :returns: ``True`` if the EDF uses absolute clock time (real wall-clock start time); ``False`` for relative time. :rtype: bool .. py:method:: get_window_left() Return the left edge of the current viewing window in seconds. :returns: Window start in elapsed seconds from the EDF start. :rtype: float .. py:method:: get_window_right() Return the right edge of the current viewing window in seconds. :returns: Window stop in elapsed seconds from the EDF start. :rtype: float .. py:method:: get_window_left_hms() Return the left edge of the current window as a clock-time string. :returns: Window start as ``'HH:MM:SS'``. :rtype: str .. py:method:: get_window_right_hms() Return the right edge of the current window as a clock-time string. :returns: Window stop as ``'HH:MM:SS'``. :rtype: str .. py:method:: get_clock_ticks(n=6, multiday=False) Return formatted clock-time tick labels for the current window. :param n: Maximum number of ticks to return. Default ``6``. :type n: int, optional :param multiday: If ``True``, include day information in the tick labels. Default ``False``. :type multiday: bool, optional :returns: Up to *n* ``(position_sec, label_str)`` pairs suitable for axis tick placement. :rtype: list .. py:method:: get_hour_ticks() Return hour-boundary tick positions for the full recording timeline. :returns: ``(position_sec, label_str)`` pairs at each whole-hour boundary. :rtype: list .. py:method:: get_window_phys_range(ch) Return the physical min/max of a channel within the current window. :param ch: Channel label. :type ch: str :returns: ``(min_value, max_value)`` in the channel's physical units. :rtype: tuple .. py:method:: get_ylabel(n) Return the normalised y-axis anchor position for display row *n*. :param n: 0-based display row index. :type n: int :returns: Normalised y-coordinate in ``[0, 1]`` for the centre of row *n*. :rtype: float .. py:method:: throttle(n) Limit the number of output samples returned per window (for rendering). :param n: Maximum number of samples to return per channel per window query. :type n: int :rtype: None .. py:method:: input_throttle(n) Set a sample-rate cap applied when populating the cache. Must be called before :meth:`populate`. :param n: Maximum sample rate (Hz) to accept when loading channels. Channels above this rate will be down-sampled. :type n: int :rtype: None .. py:method:: summary_threshold_mins(m) Set the summary aggregation threshold in minutes. :param m: Threshold in minutes used by the backend's epoch-level summary aggregation. :type m: int or float :rtype: None .. py:method:: get_annots() Return the annotation events within the current window. :returns: List of ``(class, start_sec, stop_sec)`` tuples for all annotation events that overlap the current viewing window. :rtype: list .. py:method:: get_all_annots(anns, hms=False) Return all events for the specified annotation classes. :param anns: Annotation class name(s) to retrieve. :type anns: str or list of str :param hms: If ``True``, return times as ``'HH:MM:SS'`` strings rather than floats. Default ``False``. :type hms: bool, optional :returns: All events for the requested classes across the full recording. :rtype: list .. py:method:: get_all_annots_with_inst_ids(anns, hms=True) Return all annotation events including instance IDs. :param anns: Annotation class name(s) to retrieve. :type anns: str or list of str :param hms: If ``True``, return times as ``'HH:MM:SS'`` strings. Default ``True``. :type hms: bool, optional :returns: Events including class, instance ID, start, and stop. :rtype: list .. py:method:: compile_windowed_annots(anns) Pre-compile annotation classes into window-ready polygon caches. Must be called before using :meth:`get_annots_xaxes` or :meth:`get_annots_yaxes`. Only the classes listed here will be available for polygon-based rendering. :param anns: Annotation class name(s) to compile. :type anns: str or list of str :rtype: None .. py:method:: set_clip_xaxes(clip) Enable or disable x-axis clipping when drawing annotation polygons. :param clip: If ``True``, annotation polygons are clipped to the current window boundaries. :type clip: bool :rtype: None .. py:method:: get_annots_xaxes(ann) Return x-axis polygon coordinates for annotation class *ann*. Requires a prior call to :meth:`compile_windowed_annots`. :param ann: Annotation class name. :type ann: str :returns: X-coordinate arrays for each annotation polygon in the current window. :rtype: list .. py:method:: get_annots_yaxes(ann) Return y-axis polygon coordinates for annotation class *ann*. Requires a prior call to :meth:`compile_windowed_annots`. :param ann: Annotation class name. :type ann: str :returns: Y-coordinate arrays for each annotation polygon in the current window. :rtype: list .. py:method:: set_annot_format6(b) Toggle 6-point polygon format for annotation rendering. :param b: If ``True``, use the 6-point (trapezoid) format; otherwise use the default rectangle format. :type b: bool :rtype: None .. py:method:: get_annots_xaxes_ends(ann) Return end-cap x-coordinates for annotation polygons. :param ann: Annotation class name. :type ann: str :returns: End-cap x-coordinate arrays for the current window. :rtype: list .. py:method:: get_annots_yaxes_ends(ann) Return end-cap y-coordinates for annotation polygons. :param ann: Annotation class name. :type ann: str :returns: End-cap y-coordinate arrays for the current window. :rtype: list