nirs4all.utils package
Submodules
- nirs4all.utils.backend module
BackendNotAvailableErrorcheck_backend_available()clear_availability_cache()framework()get_backend_info()get_gpu_info()is_available()is_gpu_available()is_ikpls_available()is_jax_available()is_keras_available()is_tensorflow_available()is_torch_available()lazy_import()print_backend_status()require_backend()
- nirs4all.utils.header_units module
- nirs4all.utils.reproducibility module
- nirs4all.utils.spinner module
Module contents
Utility functions for the nirs4all package.
This module contains true utility functions for terminal output, backend detection, etc. Core functionality has been moved to appropriate modules: - Metrics/evaluation → nirs4all.core.metrics - Task types → nirs4all.core.task_type, nirs4all.core.task_detection - Binning → nirs4all.data.binning - Balancing → nirs4all.controllers.data.balancing - Artifact serialization → nirs4all.pipeline.artifact_serialization - Header units → nirs4all.utils.header_units
- exception nirs4all.utils.BackendNotAvailableError(backend: str, feature: str | None = None)[source]
Bases:
ImportErrorRaised when a required backend is not installed.
Provides helpful error messages with installation instructions.
- nirs4all.utils.apply_x_axis_limits(ax, x_values: ndarray) None[source]
Apply appropriate x-axis limits to preserve data ordering.
Matplotlib may auto-sort axis values. This function sets explicit limits to preserve the original ordering (ascending or descending).
- Parameters:
ax – Matplotlib Axes object
x_values – Array of x-axis values
- nirs4all.utils.check_backend_available(backend_name: str) None[source]
Check if a backend is available, raising ImportError if not.
This is a legacy compatibility wrapper for require_backend. Use require_backend() for new code.
- Parameters:
backend_name – Name of the backend (‘tensorflow’, ‘torch’, ‘jax’).
- Raises:
BackendNotAvailableError – If the backend is not installed.
- nirs4all.utils.clear_availability_cache()[source]
Clear the availability cache (useful for testing).
- nirs4all.utils.framework(framework_name: str) Callable[[F], F][source]
Decorator to mark a function/class with its framework.
This enables automatic framework detection in the model factory.
- Parameters:
framework_name – Name of the framework (‘tensorflow’, ‘pytorch’, ‘jax’)
- Returns:
Decorator function that adds framework attribute.
Example
>>> @framework('tensorflow') ... def build_cnn(input_shape, params): ... import tensorflow as tf ... # ... build model
- nirs4all.utils.get_axis_label(unit: str | HeaderUnit) str[source]
Get the appropriate axis label for a given unit type.
- Parameters:
unit – Header unit type (string like “cm-1”, “nm” or HeaderUnit enum)
- Returns:
Human-readable axis label string
Examples
>>> get_axis_label("cm-1") 'Wavenumber (cm⁻¹)' >>> get_axis_label(HeaderUnit.WAVELENGTH) 'Wavelength (nm)' >>> get_axis_label("unknown") # Falls back gracefully 'Features'
- nirs4all.utils.get_backend_info() Dict[str, Dict[str, Any]][source]
Get comprehensive info about all backends.
- Returns:
Dictionary with availability and GPU info for each backend.
Example
>>> info = get_backend_info() >>> for name, details in info.items(): ... status = "✓" if details['available'] else "✗" ... print(f"{status} {name}")
- nirs4all.utils.get_gpu_info() Dict[str, Any][source]
Get detailed GPU information for all available backends.
- Returns:
Dictionary with GPU info per backend, including device counts and names where available.
Example
>>> info = get_gpu_info() >>> if info.get('torch', {}).get('available'): ... print(f"GPU: {info['torch']['device_name']}")
- nirs4all.utils.get_x_values_and_label(headers: List[str] | None, header_unit: str | HeaderUnit, n_features: int) Tuple[ndarray, str][source]
Get x-axis values and label from headers and unit.
This is the main utility function for chart x-axis setup. It handles: - Numeric headers (wavelengths/wavenumbers) → parsed float array - Non-numeric headers → fallback to indices - Missing or mismatched headers → fallback to indices
- Parameters:
headers – List of header strings (wavelengths, feature names, etc.)
header_unit – Header unit type (“cm-1”, “nm”, “none”, “text”, “index”)
n_features – Number of features (for fallback and validation)
- Returns:
Tuple of (x_values array, axis_label string)
Examples
>>> x_vals, label = get_x_values_and_label(["4000", "4500", "5000"], "cm-1", 3) >>> x_vals array([4000., 4500., 5000.]) >>> label 'Wavenumber (cm⁻¹)'
>>> x_vals, label = get_x_values_and_label(None, "cm-1", 5) >>> x_vals array([0, 1, 2, 3, 4]) >>> label 'Features'
- nirs4all.utils.is_available(backend: str) bool[source]
Check if a backend is available without importing it.
Results are cached for performance.
- Parameters:
backend – Backend name (‘tensorflow’, ‘torch’, ‘jax’, etc.)
- Returns:
True if the backend is installed and can be imported.
Example
>>> if is_available('tensorflow'): ... import tensorflow as tf
- nirs4all.utils.is_gpu_available(backend: str | None = None) bool[source]
Check if GPU is available for the specified backend or any backend.
Results are cached for performance. The first call for each backend will import the framework to check GPU availability.
- Parameters:
backend – Specific backend to check (‘tensorflow’, ‘torch’, ‘jax’), or None to check all available backends.
- Returns:
True if GPU is available for the specified backend(s).
Example
>>> if is_gpu_available('torch'): ... device = 'cuda' ... else: ... device = 'cpu'
- nirs4all.utils.is_jax_available() bool[source]
Check if JAX is installed.
- Returns:
True if JAX is available.
- nirs4all.utils.is_keras_available() bool[source]
Check if Keras is installed.
- Returns:
True if Keras is available.
- nirs4all.utils.is_tensorflow_available() bool[source]
Check if TensorFlow is installed.
- Returns:
True if TensorFlow is available.
- nirs4all.utils.is_torch_available() bool[source]
Check if PyTorch is installed.
- Returns:
True if PyTorch is available.
- nirs4all.utils.lazy_import(module_name: str, backend: str | None = None)[source]
Create a lazy import that only loads the module when accessed.
- Parameters:
module_name – Full module path to import.
backend – Optional backend to check before importing.
- Returns:
A proxy object that imports the module on first access.
Example
>>> tf = lazy_import('tensorflow', backend='tensorflow') >>> # tensorflow not imported yet >>> model = tf.keras.Model() # Now tensorflow is imported
- nirs4all.utils.print_backend_status()[source]
Print a formatted summary of backend availability.
Displays a table showing which backends are installed and whether GPU support is available for deep learning frameworks.
- nirs4all.utils.require_backend(backend: str, feature: str | None = None) None[source]
Require a backend to be available, raising a helpful error if not.
- Parameters:
backend – Backend name (‘tensorflow’, ‘torch’, ‘jax’, etc.)
feature – Optional feature name for better error messages.
- Raises:
BackendNotAvailableError – If the backend is not installed.
Example
>>> require_backend('tensorflow', feature='NICON neural network') >>> import tensorflow as tf # Safe after require_backend
- nirs4all.utils.should_invert_x_axis(x_values: ndarray) bool[source]
Check if x-axis should be inverted (for wavenumber convention).
In spectroscopy, wavenumber (cm⁻¹) axes are often displayed in descending order (high to low) if the data is ordered that way.
- Parameters:
x_values – Array of x-axis values
- Returns:
True if x_values are in descending order and should be displayed as such