Miscellaneous Utilities
This module contains various utility functions that don’t fit into other categories.
Naming Utilities
- driada.utils.naming.parse_iabs_filename(filename)[source]
Parse an IABS-style filename to extract experiment metadata.
Uses simple 3-part underscore convention: {track}_{animal_id}_{session}[_suffix…]
- Parameters:
filename (str) – Filename (with or without path) to parse.
- Returns:
Dictionary with keys ‘track’, ‘animal_id’, ‘session’, ‘suffix’ if successful, None if parsing failed (less than 3 underscore-separated parts).
- Return type:
dict or None
Examples
>>> parse_iabs_filename('NOF_H01_1D syn data.npz') {'track': 'NOF', 'animal_id': 'H01', 'session': '1D', 'suffix': 'syn data'}
>>> parse_iabs_filename('LNOF_J01_4D_aligned.npz') {'track': 'LNOF', 'animal_id': 'J01', 'session': '4D', 'suffix': 'aligned'}
>>> parse_iabs_filename('invalid.npz') None
- driada.utils.naming.construct_session_name(data_source, exp_params, allow_unknown=True)[source]
Construct standardized session name from experimental parameters.
Creates a consistent naming convention for experimental sessions based on the data source and experimental parameters. Supports IABS (Institute for Advanced Brain Studies) and generic lab data sources.
- Parameters:
data_source (str) – The data source identifier (e.g., ‘IABS’, ‘MyLab’, ‘NeuroLab’).
exp_params (dict) – Dictionary containing experimental parameters. For IABS, must include keys ‘track’, ‘animal_id’, ‘session’. For other sources, can include ‘name’ (takes priority), ‘experiment’, ‘subject’ or ‘animal_id’, ‘session’, ‘date’.
allow_unknown (bool, optional) – Whether to allow unknown track names (IABS only). If False, raises ValueError for unrecognized tracks. Default is True.
- Returns:
Standardized session name following the pattern appropriate for the data source and parameters provided.
- Return type:
- Raises:
ValueError – If allow_unknown is False and an unknown track is encountered (IABS only).
Examples
>>> # IABS standard track >>> params = {'track': 'STFP', 'animal_id': 'M123', 'session': '1'} >>> construct_session_name('IABS', params) 'STFP_M123_1'
>>> # IABS old track with special naming >>> params = {'track': 'HT', 'animal_id': 'A5', 'session': '3'} >>> construct_session_name('IABS', params) 'A5_HT3'
>>> # Generic lab with explicit name >>> construct_session_name('MyLab', {'name': 'pilot_study_001'}) 'pilot_study_001'
>>> # Generic lab with standard parameters >>> params = {'experiment': 'maze', 'subject': 'rat42', 'session': 'day3'} >>> construct_session_name('NeuroLab', params) 'maze_rat42_day3'
>>> # Generic lab with minimal parameters >>> construct_session_name('Lab1', {'subject': 'mouse5'}) 'mouse5'
>>> # Generic lab with no standard parameters (uses timestamp) >>> result = construct_session_name('GenericLab', {}) >>> result.startswith('GenericLab_') and len(result) == 26 # LabName_YYYYMMDD_HHMMSS True
Notes
For IABS data source:
Old tracks (HT, RT, FS): Use legacy naming patterns
Standard tracks (FcOY, STFP, AP, NOF, Trace, CC): Use {track}_{animal}_{session}
Unknown tracks: Use standard pattern if allow_unknown=True
For other data sources:
If ‘name’ parameter exists, it’s used directly
Otherwise combines available standard parameters in order: experiment, subject/animal_id, session, date
If no standard parameters exist, uses data_source name + timestamp
Output Utilities
Utilities for capturing and displaying stdout output.
This module provides tools for temporarily capturing stdout output during code execution, useful for testing, logging, or capturing output from third-party libraries.
- class driada.utils.output.Capturing(iterable=(), /)[source]
Bases:
listContext manager that captures stdout output into a list.
Temporarily redirects sys.stdout to capture all print statements and stdout writes during the context. The captured output is stored as a list of lines (strings without newlines).
- Inherits from list, so captured lines are accessible as list elements.
- Returns:
self – The Capturing instance itself, which is a list of captured lines.
- Return type:
Warning
This class is NOT thread-safe. Using multiple Capturing contexts in different threads simultaneously will cause interference.
Nested usage may have unexpected behavior - inner contexts will restore stdout to the outer context’s StringIO, not the original stdout.
Examples
>>> with Capturing() as output: ... print("Hello") ... print("World") >>> output ['Hello', 'World']
Using with functions that print:
with Capturing() as log: some_verbose_function() show_output(log) # Display captured output
Notes
Memory usage scales with output size. For very large outputs, consider alternative approaches like writing to temporary files.
- driada.utils.output.show_output(output)[source]
Display captured output from Capturing context.
Prints each line from the captured output to stdout. If the output is empty, prints a message indicating the log is empty.
- Parameters:
output (list of str) – List of captured output lines, typically from Capturing context. Each element should be a string representing one line of output.
- Return type:
None
- Raises:
TypeError – If output is None or not a list-like object.
AttributeError – If output doesn’t support len() or iteration.
Examples
>>> with Capturing() as log: ... print("Test output") >>> show_output(log) Test output
>>> show_output([]) log is empty
>>> show_output(["Line 1", "Line 2"]) Line 1 Line 2
Notes
This function is designed to work with the output from Capturing context manager but can display any list of strings.
JIT Utilities
JIT compilation utilities for DRIADA.
Provides conditional JIT compilation based on environment settings.
- driada.utils.jit.conditional_njit(*args, **kwargs)[source]
Conditionally apply numba JIT compilation based on environment settings.
If DRIADA_DISABLE_NUMBA environment variable is set to ‘true’, ‘1’, or ‘yes’, or if numba is not available, this returns the original function without JIT compilation. Otherwise, applies numba.njit with the given parameters.
- Parameters:
*args – Positional arguments passed to numba.njit. If a single function is passed, it will be decorated directly.
**kwargs – Keyword arguments passed to numba.njit (e.g., parallel=True, cache=True).
- Returns:
If called with arguments: returns a decorator function. If called on a function directly: returns the (possibly JIT-compiled) function.
- Return type:
decorator or function
Notes
This decorator allows DRIADA to gracefully handle environments where Numba is not installed or where JIT compilation needs to be disabled for debugging.
The DRIADA_DISABLE_NUMBA environment variable can be set to ‘true’, ‘1’, or ‘yes’ (case insensitive) to disable JIT compilation globally.
Examples
>>> @conditional_njit ... def fast_computation(x): ... return x ** 2
With numba parameters:
@conditional_njit(parallel=True) def parallel_computation(x): return x ** 2
Direct decoration (less common):
def my_function(x): return x ** 3 fast_func = conditional_njit(my_function)
See also
is_jit_enabledCheck if JIT compilation is currently enabled.
- driada.utils.jit.is_jit_enabled()[source]
Check if JIT compilation is enabled.
Determines whether Numba JIT compilation is available and active based on installation status and environment settings.
- Returns:
True if both conditions are met: - Numba is installed and importable - DRIADA_DISABLE_NUMBA environment variable is not set to ‘true’, ‘1’, or ‘yes’
- Return type:
Examples
>>> is_jit_enabled() True # If Numba is installed and not disabled
Disable JIT via environment:
import os os.environ['DRIADA_DISABLE_NUMBA'] = '1' is_jit_enabled() # Returns False
Notes
JIT compilation significantly speeds up numerical computations but may cause issues during debugging. The DRIADA_DISABLE_NUMBA environment variable can be set to ‘true’, ‘1’, or ‘yes’ (case insensitive) to disable JIT when debugging or if encountering Numba-related errors.
See also
jit_infoPrint detailed JIT status information.
conditional_njitDecorator that respects JIT settings.
- driada.utils.jit.jit_info()[source]
Print information about JIT compilation status.
Displays comprehensive information about the JIT compilation environment, including Numba availability, version, and current configuration settings.
Prints
Whether Numba is installed
If JIT is disabled via environment variable
Overall JIT enabled status
Numba version (if available)
Examples
>>> jit_info() Numba available: True JIT disabled by environment: False JIT enabled: True Numba version: 0.60.0
Notes
Useful for debugging performance issues or verifying that JIT compilation is working as expected in your environment.
See also
is_jit_enabledCheck JIT status programmatically.
conditional_njitDecorator that respects JIT settings.