API Reference
This section provides detailed API documentation for all SeaSenseLib modules.
Top-Level API Functions
These convenience functions are the main entry points for most users and are available directly on the seasenselib package (commonly imported as ssl).
- seasenselib.read(filename: str | PathLike, file_format: str | None = None, header_file: str | PathLike | None = None, use_steps: bool = True, pipeline_apply_stages: List[str] | None = None, pipeline_skip_stages: List[str] | None = None, pipeline_profile: str | None = None, pipeline_file: str | PathLike | None = None, pipeline_apply_handlers: List[str] | None = None, pipeline_skip_handlers: List[str] | None = None, default_latitude: float | None = None, default_longitude: float | None = None, mapping: Dict[str, str] | None = None, metadata: Dict[str, Any] | None = None, metadata_file: str | PathLike | None = None, step_config: Dict[str, Any] | None = None, **kwargs) xr.Dataset[source]
Read a sensor data file and return it as an xarray Dataset.
This function provides programmatic access to SeaSenseLib’s data reading capabilities, equivalent to using the CLI ‘convert’ command but returning the data as an xarray Dataset for further processing.
- Parameters:
filename (str or os.PathLike) – Path to the input file to read
file_format (str, optional) – Format key to override automatic format detection. Use ssl.formats() to see available formats. Common formats: ‘sbe-cnv’, ‘rbr-rsk’, ‘netcdf’, ‘csv’ If None, format will be auto-detected from file extension.
header_file (str or os.PathLike, optional) – Path to header file (required for Nortek ASCII files)
use_steps (bool, default=True) – Whether to use the processing step pipeline system. If False, returns raw data without any processing.
pipeline_apply_stages (List[str], optional) – Explicit list of pipeline stage names to apply. If None, uses default pipeline. Example: [‘mapping’, ‘metadata_enrichment’]
pipeline_skip_stages (List[str], optional) – Pipeline stage names to skip. If None, uses default pipeline.
pipeline_profile (str, optional) – Use a predefined pipeline profile (e.g., ‘default’, ‘minimal’). This is mutually exclusive with pipeline_apply_stages / pipeline_skip_stages.
pipeline_file (str or os.PathLike, optional) – Path to a pipeline configuration file (.json/.yaml/.toml). This is mutually exclusive with pipeline_profile and pipeline_apply_stages/pipeline_skip_stages.
pipeline_apply_handlers (List[str], optional) – Handlers to apply, in the form [‘stage:handler’, …].
pipeline_skip_handlers (List[str], optional) – Handlers to skip, in the form [‘stage:handler’, …].
default_latitude (float, optional) – Explicit fallback latitude in degrees north for derivations when the input data has no latitude. If omitted, no latitude is guessed. Depth derivation needs latitude only. TEOS-10 salinity/temperature derivations require longitude from the data or
default_longitude.default_longitude (float, optional) – Explicit fallback longitude in degrees east for derivations when the input data has no longitude. If omitted, no longitude is guessed. Used with latitude/default_latitude for TEOS-10 absolute salinity and conservative temperature derivations.
mapping (Dict[str, str], optional) – Variable name mapping in the internal form {original_name: canonical_name}.
metadata (Dict[str, Any], optional) – User metadata overrides with sections {“global”: {…}, “variables”: {…}}.
metadata_file (str or os.PathLike, optional) – Path to a metadata JSON file with sections {“global”: {…}, “variables”: {…}}.
step_config (Dict[str, Any], optional) – Configuration for specific processing stages. Example: {‘metadata_enrichment’: {‘include_acdd’: True}}
**kwargs – Additional reader-specific parameters. Examples: - sanitize_input : bool (for SBE CNV files, default=True) - encoding : str (for Sea&Sun TOB files, default=’latin-1’)
- Returns:
The sensor data as an xarray Dataset
- Return type:
xarray.Dataset
- Raises:
FileNotFoundError – If the input file does not exist
ValueError – If the file format is not supported or cannot be detected
RuntimeError – If there are issues reading or parsing the file
Examples
Read a CNV file with automatic format detection:
`python import seasenselib as ssl ds = ssl.read('ctd_profile.cnv') print(ds) `Read a Seabird CNV file with explicit format:
`python ds = ssl.read('ctd_profile.cnv', file_format='sbe-cnv') print(ds) `Read a Nortek ASCII file with header:
```python ds = ssl.read(‘adcp_profile.txt’, file_format=’nortek-ascii’,
header_file=’adcp_header.hdr’)
Use custom pipeline stages:
```python ds = ssl.read(‘data.cnv’,
pipeline_apply_stages=[‘mapping’, ‘metadata_enrichment’], step_config={‘metadata_enrichment’: {‘include_acdd’: True}})
Use a predefined pipeline profile:
`python ds = ssl.read('data.cnv', pipeline_profile='default') `Use a custom pipeline configuration file:
`python ds = ssl.read('data.cnv', pipeline_file='my_profile.json') `Use explicit fallback coordinates for derivations:
‘mooring.cnv’, default_latitude=54.0, default_longitude=10.0,
)
Provide user metadata directly:
‘data.cnv’, metadata={
‘global’: {‘title’: ‘My Cruise’}, ‘variables’: {‘temperature’: {‘units’: ‘degree_C’}}
}
)
Get raw data without any processing:
`python ds = ssl.read('data.cnv', use_steps=False) `Access the underlying pandas DataFrame:
`python df = ds.to_dataframe() print(df.head()) `
- seasenselib.write(dataset: xr.Dataset, filename: str | PathLike, file_format: str | None = None, **kwargs) None[source]
Write a xarray Dataset to a file in the specified format.
This function provides programmatic access to SeaSenseLib’s data writing capabilities, supporting various output formats for oceanographic data.
- Parameters:
dataset (xarray.Dataset) – The dataset to write to file
filename (str or os.PathLike) – Path to the output file
file_format (str, optional) – Output format. If None, format will be detected from file extension. Supported formats: ‘netcdf’, ‘csv’, ‘excel’
**kwargs – Additional arguments passed to the specific writer
- Raises:
ValueError – If the file format is not supported or cannot be detected
RuntimeError – If there are issues writing the file
Examples
Write to NetCDF (recommended for xarray datasets):
`python import seasenselib as ssl ds = ssl.read('data.cnv') ssl.write(ds, 'output.nc') `Write to CSV with explicit format:
`python ssl.write(ds, 'output.csv', file_format='csv') `
- seasenselib.plot(plotter_key: str, dataset: xr.Dataset, **kwargs) None[source]
Create a plot using any registered plotter (built-in or plugin).
This function provides a unified interface to all plotters in the system, mirroring the CLI’s seasenselib plot <plotter-key> command. It automatically discovers and uses the appropriate plotter based on the provided key.
- Parameters:
plotter_key (str) –
The key identifying which plotter to use. Use seasenselib.list_plotters() to see all available plotters.
Built-in plotter keys: - ‘ts-diagram’ : Temperature-Salinity diagram with density isolines - ‘vertical-profile’ : Vertical profile plot - ‘time-series’ : Time series plot (single or multiple parameters)
dataset (xarray.Dataset) – The dataset containing the data to plot
**kwargs –
Additional keyword arguments passed to the plotter’s plot() method. Each plotter accepts different arguments - use the plotter’s documentation or seasenselib plot <plotter-key> -h in the CLI to see available options.
Common arguments: - output_file : str or os.PathLike, optional - Path to save the plot. If None, displays interactively. - title : str, optional - Custom plot title
- Returns:
The plot is either displayed or saved to a file based on output_file parameter.
- Return type:
None
- Raises:
ValueError – If the plotter_key is not recognized or if required arguments are missing.
KeyError – If the dataset is missing required variables for the chosen plotter.
Examples
Create a T-S diagram:
>>> import seasenselib as ssl >>> ds = ssl.read('ctd_profile.cnv') >>> ssl.plot('ts-diagram', ds, dot_size=50, colormap='viridis')
Create a time series plot:
>>> ssl.plot('time-series', ds, parameter_names=['temperature'], ... ylim_min=10, ylim_max=20)
Create a multi-parameter time series with dual axes:
>>> ssl.plot('time-series', ds, ... parameter_names=['temperature', 'salinity'], ... dual_axis=True, colors=['red', 'blue'])
Create a vertical profile and save to file:
>>> ssl.plot('vertical-profile', ds, output_file='profile.png', ... dot_size=5, show_grid=False)
Use a plugin plotter:
>>> ssl.plot('histogram', ds, parameter_names=['temperature'], bins=50)
List all available plotters:
>>> ssl.list_plotters()
See also
list_plottersList all available plotters with descriptions
readRead data from various sensor file formats
writeWrite datasets to various formats
Notes
The function uses lazy loading - plotter modules are only imported when needed. This keeps import times fast while still providing access to all functionality.
The plotter discovery system automatically finds both built-in plotters and any plotters installed as plugins, making the API extensible without code changes.
- seasenselib.formats() List[Dict[str, Any]][source]
List all supported input file formats.
This function returns a list of all file formats that SeaSenseLib can read, along with their keys and typical file extensions. This is useful to determine which formats are available for reading data.
- Returns:
List of dictionaries containing format information with keys: ‘name’, ‘key’, ‘class_name’, ‘extension’, ‘extensions’, ‘is_plugin’ Note: ‘extension’ is the primary extension and is always present (None if not applicable). ‘extensions’ contains all advertised auto-detect extensions.
- Return type:
List[Dict[str, Any]]
Examples
```python import seasenselib as ssl formats = ssl.formats() for fmt in formats:
ext = fmt[‘extension’] or ‘N/A’ print(f”{fmt[‘name’]}: ‘{fmt[‘key’]}’ ({ext})”)
- seasenselib.list_readers() List[Dict[str, Any]][source]
List all available reader formats (including plugins).
Returns a list of all file formats that SeaSenseLib can read, including both built-in readers and those provided by plugins.
- Returns:
List of dictionaries containing reader information with keys: ‘name’, ‘key’, ‘class_name’, ‘extension’, ‘extensions’, ‘is_plugin’ Note: ‘extension’ is the primary extension and is always present (None if not applicable). ‘extensions’ contains all advertised auto-detect extensions.
- Return type:
List[Dict[str, Any]]
Examples
```python import seasenselib as ssl readers = ssl.list_readers() for reader in readers:
plugin_marker = ‘ [P]’ if reader[‘is_plugin’] else ‘’ print(f”{reader[‘name’]}{plugin_marker}: {reader[‘key’]}”)
- seasenselib.list_writers() List[Dict[str, str]][source]
List all available writer formats (including plugins).
Returns a list of all file formats that SeaSenseLib can write to, including both built-in writers and those provided by plugins.
- Returns:
List of dictionaries containing writer information with keys: ‘name’, ‘key’, ‘class_name’, ‘extension’, ‘is_plugin’ Note: ‘extension’ is always present (None if not applicable)
- Return type:
List[Dict[str, str]]
Examples
```python import seasenselib as ssl writers = ssl.list_writers() for writer in writers:
plugin_marker = ‘ [P]’ if writer[‘is_plugin’] else ‘’ print(f”{writer[‘name’]}{plugin_marker}: {writer[‘key’]}”)
- seasenselib.list_plotters() List[Dict[str, str]][source]
List all available plotter types (including plugins).
Returns a list of all plotter types available in SeaSenseLib, including both built-in plotters and those provided by plugins.
- Returns:
List of dictionaries containing plotter information with keys: ‘name’, ‘key’, ‘class_name’, ‘is_plugin’ Note: Plotters don’t have ‘extension’ (only readers/writers do)
- Return type:
List[Dict[str, str]]
Examples
```python import seasenselib as ssl plotters = ssl.list_plotters() for plotter in plotters:
plugin_marker = ‘ [P]’ if plotter[‘is_plugin’] else ‘’ print(f”{plotter[‘name’]}{plugin_marker}: {plotter[‘key’]}”)
- seasenselib.list_parameters() List[Dict[str, str]][source]
List canonical parameter names used by the internal data model.
Returns a list of canonical variable names with short descriptions.
- Returns:
List of dictionaries with keys: ‘name’, ‘description’
- Return type:
List[Dict[str, str]]
Examples
```python import seasenselib as ssl for item in ssl.list_parameters():
print(f”{item[‘name’]}: {item[‘description’]}”)
- seasenselib.list_all() Dict[str, List[Dict[str, str]]][source]
List all available resources: readers, writers, and plotters.
Returns a comprehensive dictionary containing all available formats and plotters, organized by type. Includes both built-in resources and those provided by plugins.
- Returns:
Dictionary with keys ‘readers’, ‘writers’, ‘plotters’, each containing a list of resource information dictionaries
- Return type:
Dict[str, List[Dict[str, str]]]
Examples
```python import seasenselib as ssl all_resources = ssl.list_all()
print(f”Readers: {len(all_resources[‘readers’])}”) print(f”Writers: {len(all_resources[‘writers’])}”) print(f”Plotters: {len(all_resources[‘plotters’])}”)
# Count plugins total_plugins = sum(
sum(1 for item in items if item.get(‘is_plugin’, False)) for items in all_resources.values()
Readers
SeaSenseLib Readers Module with Autodiscovery
This module provides various reader classes for importing CTD sensor data from different file formats into xarray Datasets. It uses an autodiscovery mechanism to automatically find and register all available reader classes.
Available Readers:
All reader classes are automatically discovered from the readers directory. Common readers include: - SbeCnvReader: Read SeaBird CNV files - NetCdfReader: Read NetCDF files - CsvReader: Read CSV files - RbrRskReader: Read RBR RSK files - And many more…
Example Usage:
from seasenselib.readers import SbeCnvReader, NetCdfReader
# Read a CNV file reader = SbeCnvReader(“data.cnv”) data = reader.data
# Read a NetCDF file nc_reader = NetCdfReader(“data.nc”) nc_data = nc_reader.data
Base Reader Classes
- class seasenselib.readers.base.AbstractReader(input_file: str, mapping: dict | None = None, input_header_file: str | None = None, perform_default_postprocessing: bool = True, rename_variables: bool = True, assign_metadata: bool = True, sort_variables: bool = True, use_steps: bool = True, pipeline_config: Any = None, user_metadata: Dict[str, Any] | None = None, **kwargs)[source]
Bases:
ABCAbstract super class for reading sensor data.
Must be subclassed to implement specific file format readers.
This class supports the context manager protocol for automatic resource cleanup:
>>> with SomeReader('data.cnv') as reader: ... ds = reader.data ... # process data >>> # data automatically released
- input_file
The path to the input file containing sensor data.
- Type:
str (read-only property)
- input_header_file
The path to separate header file, or None if not applicable.
- Type:
str | None (read-only property)
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict (read-only property)
- data
The processed sensor data as a xarray Dataset, or None if not yet processed. This is a read-only property. Use
get_data()for backward compatibility.- Type:
xr.Dataset | None (read-only property)
- is_loaded
Whether data has been loaded from the file.
- Type:
bool (read-only property)
- metadata
File metadata (size, modification time, etc.) without loading data.
- Type:
dict (read-only property)
- perform_default_postprocessing
Whether to perform default post-processing on the data.
- Type:
bool
- rename_variables
Whether to rename xarray variables to standard names.
- Type:
bool
- assign_metadata
Whether to assign metadata to xarray variables.
- Type:
bool
- sort_variables
Whether to sort xarray variables by name.
- Type:
bool
- __init__(input_file: str, mapping: dict | None = None,
perform_default_postprocessing: bool = True, rename_variables: bool = True, assign_metadata: bool = True, sort_variables: bool = True)
Initializes the reader with the input file and optional mapping.
- __enter__() AbstractReader[source]
Context manager entry point.
- reload() AbstractReader[source]
Force reload data from file, clearing any cached data.
- _perform_default_postprocessing(ds: xr.Dataset) xr.Dataset[source]
Performs default post-processing on the xarray Dataset.
- get_data() xr.Dataset | None[source]
Returns the processed data as an xarray Dataset (deprecated, use data property).
- property data: Dataset | None
Get the processed sensor data as an xarray Dataset (lazy loading).
This property provides read-only access to the data. The data is loaded lazily on first access - subsequent accesses return the cached dataset.
- Returns:
The processed sensor data.
- Return type:
xr.Dataset | None
- Raises:
NotImplementedError – If the subclass does not implement _load_data().
RuntimeError – If data loading fails.
Examples
>>> reader = SomeReader('data.cnv') >>> print(reader.is_loaded) # False - not loaded yet >>> ds = reader.data # Triggers lazy load >>> print(reader.is_loaded) # True - now loaded >>> ds2 = reader.data # Returns cached data >>> assert ds is ds2 # Same object
- abstractmethod classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod file_extensions() tuple[str, ...][source]
Get all extensions that can be auto-detected for this reader.
Subclasses with multiple unique file suffixes should override this method. The default keeps backward compatibility by exposing only the primary extension returned by
file_extension().Returns:
- tuple[str, …]
Supported auto-detect extensions. The first entry should match
file_extension()when a primary extension exists.
- abstractmethod classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() Dict[str, list][source]
Get format-specific variable name mappings for this reader.
Returns format-specific mappings that extend or override the default mappings from parameters.py. This allows each reader to provide sensor-specific variable name patterns without hard-coding them in stages.
The stage system will use these mappings after user custom mappings and before default mappings.
Returns:
- dict
Dictionary mapping canonical parameter names to list of format-specific variable name patterns. Empty dict means no format-specific mappings.
Example:
>>> class SbeCnvReader(AbstractReader): ... @classmethod ... def format_mappings(cls): ... import seasenselib.parameters as params ... return { ... params.TEMPERATURE: ['t090C', 't068', 'tv290C'], ... params.SALINITY: ['sal00', 'sal11'], ... params.CONDUCTIVITY: ['c0mS/cm', 'c0S/m'] ... }
Notes:
Override this method in subclasses to provide format-specific mappings
Default implementation returns empty dict (no format-specific mappings)
Keeps format-specific knowledge with the reader, not in stages
Supports flexible, extensible architecture
- abstractmethod classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- get_data() Dataset | None[source]
Returns the processed data as an xarray Dataset.
Deprecated since version 0.4.0: Use the
dataproperty instead:reader.dataThis method will be removed in version 1.0.0.- Returns:
The processed sensor data, or None if not yet read.
- Return type:
xr.Dataset | None
- property input_file: str
Get the input file path (read-only).
- Returns:
Path to the input data file
- Return type:
str
- property input_header_file: str | None
Get the input header file path (read-only).
- Returns:
Path to the separate header file, or None if not applicable
- Return type:
str | None
- property is_loaded: bool
Check if data has been loaded from file.
- Returns:
True if data has been loaded, False otherwise.
- Return type:
bool
Examples
>>> reader = SomeReader('data.cnv') >>> print(reader.is_loaded) # False until data property is accessed
- property mapping: dict
Get the variable name mapping (read-only).
- Returns:
Dictionary mapping custom variable names to standard names
- Return type:
dict
- property metadata: Dict[str, Any]
Get file-level metadata without loading data.
This property provides access to file-level metadata such as file size and modification time without requiring the full data to be loaded into memory.
For dataset-specific information (variables, dimensions, attributes), access the data property and inspect the xarray Dataset directly.
- Returns:
Dictionary containing file metadata: - file_path: Absolute path to the file - file_name: Base name of the file - file_size: Size in bytes - file_size_human: Human-readable size (e.g., “1.5 MB”) - modified_time: Last modification timestamp (ISO format) - format_key: Reader format key - format_name: Reader format name
- Return type:
Dict[str, Any]
Examples
>>> reader = SomeReader('data.cnv') >>> print(f"File: {reader.metadata['file_name']}") >>> print(f"Size: {reader.metadata['file_size_human']}") >>> print(f"Format: {reader.metadata['format_name']}") >>> >>> # For dataset info, use reader.data: >>> ds = reader.data >>> print(f"Variables: {list(ds.data_vars)}") >>> print(f"Dimensions: {dict(ds.dims)}")
- pipeline_transformations(ds: Dataset) list[Any][source]
Return optional transformation handlers for this concrete dataset.
Readers can override this hook when a transformation depends on data, header metadata, or reader state. The transformation stage accepts objects implementing
ITransformation. The default performs no transformations.
- property processing_metadata: Dict[str, Any] | None
Return processing metadata from the stage pipeline (if available).
- classmethod reader_args() list[dict[str, Any]][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- classmethod reader_groups() tuple[str, ...][source]
Return optional reader-group identifiers for pipeline controls.
Reader groups allow pipeline stages to enable/disable behavior for related formats such as
nortek-asciiandnortek-csvwithout coupling the stage to concrete reader classes. The default derives the group from the format key prefix before the first hyphen.
- reload() AbstractReader[source]
Force reload data from file.
Clears any cached data and re-reads from the file. This is useful when the underlying file has been modified or to free memory temporarily.
- Returns:
Returns self for method chaining.
- Return type:
Note
After calling reload(), the data will be re-read when the data property is next accessed (for lazy-loading readers) or you may need to create a new reader instance (for eager-loading readers).
Examples
>>> reader = SomeReader('data.cnv') >>> reader.reload() # Clear cached data >>> ds = reader.data # Re-read from file (lazy loading)
Specific Reader Classes
- class seasenselib.readers.SbeCnvReader(input_file: str, sanitize_input: bool = True, use_default_latitude: bool | None = None, default_latitude: float | None = None, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads sensor data from a SeaBird CNV file into a xarray Dataset.
This class is used to read SeaBird CNV files, which are commonly used for storing sensor data. The provided data is expected to be in a CNV format, and this reader is designed to parse that format correctly.
The reader includes automatic file sanitization for common issues such as trailing whitespace and malformed lines that cause pycnv errors.
- data
The xarray Dataset containing the sensor data to be read from the CNV file.
- Type:
xr.Dataset
- input_file
The path to the input CNV file containing the sensor data.
- Type:
str
- mapping
A mapping dictionary for renaming variables or attributes in the dataset.
- Type:
dict
- sanitize_input
Whether to automatically fix file format issues (default: True).
- Type:
bool
- __init__(input_file, sanitize_input=True, use_default_latitude=None, default_latitude=None, mapping=None, \*\*kwargs):
Initializes the CnvReader with the input file and configuration options.
- data():
Returns the xarray Dataset containing the sensor data.
- format_name():
Returns the format of the file being read, which is ‘SBE CNV’.
- file_extension():
Returns the file extension for this reader, which is ‘.cnv’.
Examples
>>> # Default behavior (auto-fix enabled) >>> reader = SbeCnvReader('mooring_data.cnv') >>> ds = reader.data
>>> # Disable file sanitization (stricter parsing) >>> reader = SbeCnvReader('data.cnv', sanitize_input=False)
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[source]
Get SeaBird CNV format-specific variable name mappings.
- Returns:
Dictionary mapping canonical parameter names to SeaBird-specific variable name patterns commonly found in CNV files.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.NetCdfReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads sensor data from a netCDF file into a xarray Dataset.
This class is used to read netCDF files, which are commonly used for storing multidimensional scientific data. The provided data is expected to be in a netCDF format, and this reader is designed to parse that format correctly.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be read from the netCDF file.
- input_filestr
The path to the input netCDF file containing the sensor data.
Methods:
- __init__(input_file):
Initializes the NetCdfReader with the input file.
- _load_data():
Reads the netCDF file and processes the data into an xarray Dataset.
Properties
- dataxr.Dataset (read-only)
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- format_name():
Returns the type of the file being read, which is ‘netCDF’.
- file_extension():
Returns the file extension for this reader, which is ‘.nc’.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.CsvReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads CTD data from a CSV file into a xarray Dataset.
This class reads CTD data from a CSV file, processes the data into a dictionary of columns, and organizes it into an xarray Dataset. It handles the conversion of timestamps to datetime objects and assigns metadata according to CF conventions.
- data
The xarray Dataset containing the sensor data.
- Type:
xr.Dataset
- input_file
The path to the input CSV file containing the CTD data.
- Type:
str
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict, optional
- __init__(input_file: str, mapping: dict | None = None)[source]
Initializes the CsvReader with the input file and optional mapping.
- Properties()
- ----------
- data : xr.Dataset (read-only)
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- get_file_type()
Returns the type of the file being read, which is ‘CSV’.
- get_file_extension()
Returns the file extension for this reader, which is ‘.csv’.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RbrRskReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads sensor data from a RBR .rsk file into a xarray Dataset.
- data
The xarray Dataset containing the sensor data.
- Type:
xr.Dataset
- input_file
The path to the input file containing the RBR legacy data.
- Type:
str
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict, optional
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RbrRskAutoReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderFacade for reading RBR .rsk files, automatically selecting the correct reader based on the file’s type and version.
This class checks the type and version of the RSK file and initializes either the RbrRskReader for modern files or the RbrRskLegacyReader for legacy files. It reads the data and returns it as an xarray Dataset.
Note
File validation occurs twice: once in this facade and once in the delegate reader. This is intentional design for defense-in-depth and to ensure delegate readers work correctly when instantiated directly. The validation overhead is negligible compared to file loading time.
- input_file
The path to the input file containing the RBR data.
- Type:
str
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict, optional
- data
The processed sensor data as an xarray Dataset, or None if not yet processed.
- Type:
xr.Dataset | None
- Properties
- ----------
- data
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- Type:
xr.Dataset (read-only)
- _load_data()[source]
Selects the appropriate reader based on the RSK file type and version, and reads the data into an xarray Dataset.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RbrAsciiReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads RBR ASCII data from an ASCII file into an xarray Dataset.
This class reads RBR ASCII data files, extracts the datetime and data columns, and organizes the data into an xarray Dataset. It handles the conversion of timestamps to datetime objects and assigns metadata according to CF conventions.
- data
The xarray Dataset containing the sensor data.
- Type:
xr.Dataset
- input_file
The path to the input file containing the RBR ASCII data.
- Type:
str
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict, optional
- __init__(input_file: str, mapping: dict | None = None):
Initializes the RbrAsciiReader with the input file and optional mapping.
- _load_data():
Reads the RBR ASCII data file, processes the data, and creates an xarray Dataset.
- Properties()
- ----------
- data : xr.Dataset (read-only)
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RbrHexReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderRead RBR TR-1050 style binary HEX files.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[str, list[str]][source]
Get format-specific variable name mappings for this reader.
Returns format-specific mappings that extend or override the default mappings from parameters.py. This allows each reader to provide sensor-specific variable name patterns without hard-coding them in stages.
The stage system will use these mappings after user custom mappings and before default mappings.
Returns:
- dict
Dictionary mapping canonical parameter names to list of format-specific variable name patterns. Empty dict means no format-specific mappings.
Example:
>>> class SbeCnvReader(AbstractReader): ... @classmethod ... def format_mappings(cls): ... import seasenselib.parameters as params ... return { ... params.TEMPERATURE: ['t090C', 't068', 'tv290C'], ... params.SALINITY: ['sal00', 'sal11'], ... params.CONDUCTIVITY: ['c0mS/cm', 'c0S/m'] ... }
Notes:
Override this method in subclasses to provide format-specific mappings
Default implementation returns empty dict (no format-specific mappings)
Keeps format-specific knowledge with the reader, not in stages
Supports flexible, extensible architecture
- class seasenselib.readers.NortekAsciiReader(dat_file_path: str, header_file_path: str, mapping: dict | None = None, target_coordinate_system: str | None = None, pointing_down: bool | str | None = None, coordinate_transform_keep_source: bool = False, coordinate_transform_overwrite: bool = False, **kwargs)[source]
Bases:
AbstractReaderReads Nortek ASCII data from a .dat file into a xarray Dataset.
This class reads Nortek ASCII data files, extracts column names and units from a .hdr file, and organizes the data into an xarray Dataset. It handles duplicate column names by making them unique, converts timestamps to datetime objects, and assigns metadata according to CF conventions.
- data
The xarray Dataset containing the sensor data.
- Type:
xr.Dataset
- dat_file_path
The path to the .dat file containing the Nortek ASCII data.
- Type:
str
- header_file_path
The path to the .hdr file containing the header information for the Nortek ASCII data.
- Type:
str
- __init__(dat_file_path, header_file_path):
Initializes the NortekAsciiReader with the paths to the .dat and .hdr files.
- _load_data():
Reads the .dat and .hdr files, processes the data, and creates an xarray Dataset.
- Properties()
- ----------
- data : xr.Dataset (read-only)
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- file_type : str
A string indicating the type of file being read, in this case, ‘Nortek ASCII’.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[source]
Get Nortek ASCII format-specific variable name mappings.
- Returns:
Dictionary mapping canonical parameter names to Nortek-specific variable name patterns commonly found in ASCII export files.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- pipeline_transformations(ds: Dataset) list[source]
Return reader-provided transformations for the pipeline.
The base reader calls this hook after
_load_data()and before the transformation stage runs. By then the Nortek header has already been parsed and stored in_raw_metadata_blocks, so the transformation handler can read the BEAM-to-XYZ matrix from the normal pipeline metadata context. This method only decides whether a transformation was requested by the caller and passes through the reader-level options.If no target coordinate system was requested, no handler is returned and the default read path remains unchanged.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.NortekCsvReader(input_file: str, mapping: dict | None = None, input_header_file: str | None = None, units_file: str | None = None, target_coordinate_system: str | None = None, pointing_down: bool | str | None = None, coordinate_transform_keep_source: bool = False, coordinate_transform_overwrite: bool = False, **kwargs)[source]
Bases:
AbstractReaderRead Nortek CSV data exported from AquaPro software.
This class is a SeaSenseLib wrapper around the original Nortek CSV helper functions. The parsing logic is kept in
load_nortek_csv_dataand the class only adapts it to the common reader interface.- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- pipeline_transformations(ds: Dataset) list[source]
Return reader-provided transformations for the pipeline.
The base reader calls this hook after
_load_data()and before the transformation stage runs. By thenString Data.csvhas already been parsed and stored in_raw_metadata_blocks, so the transformation handler can read the BEAM-to-XYZ matrix from the normal pipeline metadata context. This method only decides whether a transformation was requested by the caller and passes through the reader-level options.If no target coordinate system was requested, no handler is returned and the default read path remains unchanged.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.NortekRawReader(input_file: str, userdata: bool | str | None = None, nens: int | tuple[int, int] | None = None, debug: bool | None = None, do_checksum: bool | None = None, rebuild_index: bool | None = None, dual_profile: bool | None = None, show_decoder_output: bool = False, apply_aquadopp_compatibility: bool = True, apply_nortek2_aquadopp_compatibility: bool = True, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderRead Nortek raw binary files with MHKiT DOLfYN.
- Responsibility
NortekRawReaderis the public SeaSenseLib wrapper for Nortek binary raw-like files. It keeps backend decoding as close as possible to DOLfYN while adding SeaSenseLib provenance, conservative metadata annotations, and safe scalar variable mappings.- Decode path selection
Classic Nortek files are delegated to DOLfYN’s classic Nortek reader. Gen2/AD2CP-style
.aqdfiles are selected from the binary header. Full Gen2 raw packet streams go through DOLfYN’s Nortek2 reader, optionally with the scoped average-record repair above. Already averaged ID 38*_avgd.aqdproducts use the small SeaSenseLib fallback decoder because current DOLfYN builds do not index that packet family.- Compatibility policy
The compatibility helpers are intentionally narrow and temporary: they patch DOLfYN only in memory, only during a single read, and only after guarded evidence from the file/backend state indicates the known layout issue. They are not intended to replace DOLfYN as the normal decoder.
This reader is marked experimental because support is still being validated across Nortek raw variants.
Velocity is intentionally preserved as vector variable
vel. Its component meaning depends onds.attrs["coord_sys"]and thedircoordinate, so automatic CF component variables would be a scientific interpretation step rather than a safe reader cleanup.- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod file_extensions() tuple[str, ...][source]
Get all extensions that can be auto-detected for this reader.
Subclasses with multiple unique file suffixes should override this method. The default keeps backward compatibility by exposing only the primary extension returned by
file_extension().Returns:
- tuple[str, …]
Supported auto-detect extensions. The first entry should match
file_extension()when a primary extension exists.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[str, list[str]][source]
Return conservative Nortek-to-SeaSenseLib variable mappings.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- pipeline_transformations(ds: Dataset) list[Any][source]
Return no reader-provided coordinate transformations for raw data.
Nortek ASCII and CSV readers expose velocity as explicit SeaSenseLib component triplets such as
velocity_beam1/velocity_beam2/velocity_beam3oreast_velocity/north_velocity/up_velocity. The coordinate transformation handler works on those scalar triplets.The raw reader intentionally preserves DOLfYN’s decoded vector variable
veland itsdircoordinate. Splitting that vector into scalar components is a separate interpretation step, because the meaning ofdirdepends on DOLfYN metadata such ascoord_sysand on raw-file variants that still need validation. Returning an empty list here makes that limitation explicit and keeps raw reads reproducible.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.AdcpMatlabRdadcpReader(input_file: str, time_dim: str = 'time', bin_dim: str = 'bin', beam_dim: str = 'beam', mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReader which converts ADCP data stored in MATLAB .mat files converted from binary with rdadcp into an xarray Dataset.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[str, list][source]
Return ADCP rdadcp format-specific variable name mappings.
- Returns:
Dictionary mapping standard names to ADCP format-specific aliases.
- Return type:
dict[str, list]
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.AdcpMatlabUhhdsReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads ADCP data from a matlab (.mat) file into a xarray Dataset.
This class is used to read ADCP files, which are stored in .mat files. The provided data is expected to be in a matlab format, and this reader is designed to detect the format, rename the variables under CF standards and create an xarra Dataset. As there are various versions of variable names and file structures, the reader will detect the version and parse accordingly.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the ADCP data previously stored in a .mat file.
- input_filestr
The path to the input ADCP file containing the sensor data stored in MATLAB .mat file.
Methods:
- __init__(input_file):
Initializes the AdcpMatlabReader with the input file.
- __read():
Reads the ADCP file and processes the data into an xarray Dataset.
Properties
- dataxr.Dataset (read-only)
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- _detect_format():
Detects the format of the ADCP -mat input file and redirects accordingly.
- _parse_time():
Handles different time formats in the ADCP .mat files.
- _add_time():
Adds time coordinates to the dataset based on the detected format.
- _add_data_and_coords():
Adds data variables and coordinates to the dataset based on the detected format.
- _add_metadata():
Adds common metadata attributes to the dataset.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RdiRawReader(input_file: str, userdata: bool | str | None = None, nens: int | tuple[int, int] | None = None, debug: int | None = None, vmdas_search: bool = False, winriver: bool = False, search_num: int | None = None, show_decoder_output: bool = False, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderRead Teledyne RD Instruments (RDI) raw binary ADCP files.
The reader delegates binary decoding to a tested RDI parser and keeps the returned xarray structure intact. SeaSenseLib only adds reader provenance, raw-metadata hints, and conservative variable mappings such as
temp->temperatureandc_sound->speed_of_sound.Velocity is intentionally preserved as vector variable
vel. Its component meaning depends onds.attrs["coord_sys"](for example beam, inst, ship, earth, or principal), so automatic CF component variables would be a scientific decision rather than a safe metadata cleanup.- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod file_extensions() tuple[str, ...][source]
Get all extensions that can be auto-detected for this reader.
Subclasses with multiple unique file suffixes should override this method. The default keeps backward compatibility by exposing only the primary extension returned by
file_extension().Returns:
- tuple[str, …]
Supported auto-detect extensions. The first entry should match
file_extension()when a primary extension exists.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[str, list[str]][source]
Return conservative RDI-to-SeaSenseLib variable mappings.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.RbrMatlabLegacyReader(input_file: str, time_dim: str = 'time', mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReader which converts RBR data stored in MATLAB .mat files into an xarray Dataset.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.RbrMatlabReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderFacade for reading RBR Matlab .mat files, automatically selecting the correct reader based on the root variable in the MATLAB structure.
Note
File validation occurs twice: once in this facade and once in the delegate reader. This is intentional design for defense-in-depth and to ensure delegate readers work correctly when instantiated directly. The validation overhead is negligible compared to file loading time.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RbrMatlabRsktoolsReader(input_file: str, time_dim: str = 'time', mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReader for Matlab files created with RBR RSKtools.
This class converts RSK structures (created with RSK2MAT.m from RBR RSKtools) into xarray Datasets with separate variables for each sensor channel.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.RbrRskLegacyReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads sensor data from a RBR .rsk file (legacy format) into a xarray Dataset.
This class is specifically designed to read RBR legacy files that are stored in a SQLite database format. It extracts channel information and measurement data, converts timestamps, and organizes the data into an xarray Dataset.
- data
The xarray Dataset containing the sensor data.
- Type:
xr.Dataset
- input_file
The path to the input file containing the RBR legacy data.
- Type:
str
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict, optional
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.RcmMatlabReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReader which converts RCM data stored in MATLAB .mat files into xarray dataset.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.SbeAsciiReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads CTD data from a SeaBird ASCII file into an xarray Dataset.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- class seasenselib.readers.SeasunTobReader(input_file: str, encoding: str = 'latin-1', mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderReads CTD data from a TOB ASCII file (Sea & Sun) into a xarray Dataset.
This class reads TOB files, extracts column names and units, and organizes the data into an xarray Dataset. It handles the conversion of timestamps to datetime objects and assigns metadata according to CF conventions. The TOB file format is specific to Sea & Sun CTD devices, and this reader is designed to parse that format correctly.
- data
The xarray Dataset containing the sensor data.
- Type:
xr.Dataset
- input_file
The path to the input TOB file containing the CTD data.
- Type:
str
- mapping
A dictionary mapping names used in the input file to standard names.
- Type:
dict, optional
- encoding
The encoding used to read the TOB file, default is ‘latin-1’.
- Type:
str, optional
- __init__(input_file, mapping = {}, encoding = 'latin-1'):
Initializes the TobReader with the input file, optional mapping, and encoding.
- _load_data():
Reads the TOB file, processes the data, and creates an xarray Dataset.
- Properties()
- ----------
- data : xr.Dataset (read-only)
Returns the xarray Dataset containing the sensor data. For backward compatibility, get_data() method is also available but deprecated.
- format_name():
Returns the format of the file being read, which is ‘Sea & Sun TOB’.
- file_extension():
Returns the file extension for this reader, which is ‘.tob’.
- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[str, list][source]
Return Sea & Sun TOB format-specific variable name mappings.
- Returns:
Dictionary mapping standard names to TOB format-specific aliases.
- Return type:
dict[str, list]
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
- class seasenselib.readers.SbeHexReader(input_file: str, mapping: dict | None = None, **kwargs)[source]
Bases:
AbstractReaderSeaSenseLib reader wrapper for Sea-Bird SBE37
.hexfiles.- classmethod file_extension() str | None[source]
Get the primary file extension for this reader.
This property must be implemented by all subclasses. The primary extension must be unique over all registered readers. If a reader does not specify a unique primary file extension, just return None.
Returns:
- str | None
The primary file extension (e.g., ‘.cnv’, ‘.tob’, ‘.rsk’), or None when there is no single primary extension (see
file_extensions()).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_key() str[source]
Get the format key for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘sbe-cnv’, ‘nortek-ascii’, ‘rbr-rsk’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod format_mappings() dict[str, list][source]
Return aliases produced by the wrapped SBE HEX decoding function.
- classmethod format_name() str[source]
Get the format name for this reader.
This property must be implemented by all subclasses.
Returns:
- str
The format (e.g., ‘SeaBird CNV’, ‘Nortek ASCII’, ‘RBR RSK’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- classmethod reader_args() list[dict][source]
Return CLI-discoverable reader-specific arguments.
Reader subclasses should override this when they can provide concise, user-facing descriptions. The fallback introspects explicit constructor parameters, which keeps plugin readers discoverable even without a custom metadata hook.
Writers
SeaSenseLib Writers Module with Autodiscovery
This module provides various writer classes for exporting CTD sensor data from xarray Datasets to different file formats. It uses an autodiscovery mechanism to automatically find and register all available writer classes.
Available Writers:
All writer classes are automatically discovered from the writers directory. Common writers include: - NetCdfWriter: Export to NetCDF format - CsvWriter: Export to CSV format - ExcelWriter: Export to Excel format
Example Usage:
from seasenselib.writers import NetCdfWriter, CsvWriter, ExcelWriter
# Write to NetCDF writer = NetCdfWriter(data) writer.write(“output.nc”)
# Write to CSV csv_writer = CsvWriter(data) csv_writer.write(“output.csv”)
# Write to Excel excel_writer = ExcelWriter(data) excel_writer.write(“output.xlsx”)
Base Writer Classes
- class seasenselib.writers.base.AbstractWriter(data: Dataset)[source]
Bases:
ABCAbstract base class for writing sensor data from xarray Datasets.
This class provides a common interface for all writer implementations. All concrete writer classes should inherit from this class and implement the write method.
This class supports the context manager protocol for automatic resource cleanup:
>>> with SomeWriter(dataset) as writer: ... writer.write('output.nc') >>> # resources automatically cleaned up
Attributes:
- dataxr.Dataset (read-only)
The xarray Dataset containing the sensor data to be written.
Methods:
- __init__(data: xr.Dataset):
Initializes the writer with the provided xarray Dataset.
- __enter__() -> AbstractWriter:
Context manager entry point.
- __exit__(exc_type, exc_val, exc_tb) -> None:
Context manager exit - releases resources.
- file_extension: str
The default file extension for this writer (to be implemented by subclasses).
- format_name() -> str:
Get the format name for this writer (to be implemented by subclasses).
- format_key() -> str:
Get the format key for this writer (to be implemented by subclasses).
- write(file_name: str, **kwargs):
Writes the xarray Dataset to a file (to be implemented by subclasses).
Raises:
- NotImplementedError:
If the subclass does not implement the write method or the file_extension property.
- TypeError:
If the provided data is not an xarray Dataset.
- property data: Dataset
Get the xarray Dataset (read-only).
Returns:
- xr.Dataset
The xarray Dataset containing the sensor data.
- abstractmethod static file_extension() str[source]
Get the default file extension for this writer.
This property must be implemented by all subclasses. The extension must be unique over all registered writers. If the writer does not specify a unique file extension, just return None.
Returns:
- str
The file extension (e.g., ‘.nc’, ‘.csv’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- abstractmethod static format_key() str[source]
Get the format key for this writer.
This property must be implemented by all subclasses.
Returns:
- str
The format key (e.g., ‘netcdf’, ‘csv’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
Specific Writer Classes
- class seasenselib.writers.NetCdfWriter(data: Dataset)[source]
Bases:
AbstractWriterWrites sensor data from a xarray Dataset to a netCDF file.
This class is used to save sensor data in a netCDF format, which is commonly used for storing large datasets, especially in oceanography and environmental science. The provided data is expected to be in an xarray Dataset format.
- Example usage:
writer = NetCdfWriter(data) writer.write(“output_file.nc”)
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be written to a netCDF file.
Methods:
- __init__(data: xr.Dataset):
Initializes the NetCdfWriter with the provided xarray Dataset.
- write(file_name: str):
Writes the xarray Dataset to a netCDF file with the specified file name.
- file_extension: str
The default file extension for this writer, which is ‘.nc’.
- static file_extension() str[source]
Get the default file extension for this writer.
Returns:
- str
The file extension for netCDF files, which is ‘.nc’.
- static format_key() str[source]
Get the format key for this writer.
Returns:
- str
The format key ‘netcdf’.
- static format_name() str[source]
Get the human-readable format name.
Returns:
- str
The format name ‘netCDF’.
- write(file_name: str, sanitize_names: bool = True, **kwargs)[source]
Writes the xarray Dataset to a netCDF file with the specified file name.
Parameters:
- file_name (str):
The name of the output netCDF file where the data will be saved.
- sanitize_namesbool, optional
If True, replace slashes in NetCDF dimension, coordinate, and variable names with underscores before writing. Enabled by default.
- class seasenselib.writers.CsvWriter(data: Dataset)[source]
Bases:
AbstractWriterWrites sensor data from a xarray Dataset to a CSV file.
This class is used to save sensor data in a CSV format, which is a common format for tabular data. The provided data is expected to be in an xarray Dataset format.
- Example usage:
writer = CsvWriter(data) writer.write(“output_file.csv”)
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be written to a CSV file.
Methods:
- __init__(data: xr.Dataset):
Initializes the CsvWriter with the provided xarray Dataset.
- write(file_name: str, coordinate = params.TIME):
Writes the xarray Dataset to a CSV file with the specified file name. The coordinate parameter is validated to exist in the dataset but does not affect which data is written; the full dataset is always exported.
- file_extension: str
The default file extension for this writer, which is ‘.csv’.
- static file_extension() str[source]
Get the default file extension for this writer.
Returns:
- str
The file extension for CSV files, which is ‘.csv’.
- static format_key() str[source]
Get the format key for this writer.
Returns:
- str
The format key ‘csv’.
- static format_name() str[source]
Get the human-readable format name.
Returns:
- str
The format name ‘CSV’.
- write(file_name: str, coordinate='time', **kwargs)[source]
Writes the xarray Dataset to a CSV file with the specified file name and coordinate.
Parameters:
- file_name (str):
The name of the output CSV file where the data will be saved.
- coordinate (str):
A coordinate or dimension that must be present in the dataset. Default is params.TIME. This parameter is validated but does not affect the output; the full dataset is always written to CSV.
- **kwargs:
Additional keyword arguments (unused in this implementation).
- class seasenselib.writers.ExcelWriter(data: Dataset)[source]
Bases:
AbstractWriterWrites sensor data from a xarray Dataset to an Excel file.
This class is used to save sensor data in an Excel format, which is commonly used for tabular data. The provided data is expected to be in an xarray Dataset format.
- Example usage:
writer = ExcelWriter(data) writer.write(“output_file.xlsx”)
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be written to an Excel file.
Methods:
- __init__(data: xr.Dataset):
Initializes the ExcelWriter with the provided xarray Dataset.
- write(file_name: str, coordinate = params.TIME):
Writes the xarray Dataset to an Excel file with the specified file name and coordinate. The coordinate parameter specifies which coordinate to use for selecting the data.
- file_extension: str
The default file extension for this writer, which is ‘.xlsx’.
- static file_extension() str[source]
Get the default file extension for this writer.
Returns:
- str
The file extension for Excel files, which is ‘.xlsx’.
- static format_key() str[source]
Get the format key for this writer.
Returns:
- str
The format key ‘excel’.
- static format_name() str[source]
Get the human-readable format name.
Returns:
- str
The format name ‘Excel’.
- write(file_name: str, coordinate='time', **kwargs)[source]
Writes the xarray Dataset to an Excel file with the specified file name and coordinate.
Parameters:
- file_name (str):
The name of the output Excel file where the data will be saved.
- coordinate (str):
The coordinate to use for selecting the data. Default is params.TIME. This should be a valid coordinate present in the xarray Dataset.
- **kwargs:
Additional keyword arguments (unused in this implementation).
Raises:
- ValueError:
If the provided coordinate is not found in the dataset.
Plotters
SeaSenseLib Plotters Module with Autodiscovery
This module provides various plotter classes for visualizing CTD sensor data from xarray Datasets using matplotlib. It uses an autodiscovery mechanism to automatically find and register all available plotter classes.
Available Plotters:
All plotter classes are automatically discovered from the plotters directory. Common plotters include: - TsDiagramPlotter: Create T-S (Temperature-Salinity) diagrams with density isolines - DepthProfilePlotter: Create CTD depth profiles for temperature and salinity - TimeSeriesPlotter: Create time series plots for single or multiple parameters
Example Usage:
from seasenselib.plotters import TsDiagramPlotter, DepthProfilePlotter, TimeSeriesPlotter
# Create a T-S diagram ts_plotter = TsDiagramPlotter(data) ts_plotter.plot(title=”Station 001 T-S Diagram”, output_file=”ts_diagram.png”)
# Create a vertical profile profile_plotter = DepthProfilePlotter(data) profile_plotter.plot(title=”CTD Profile”, output_file=”profile.png”)
# Create a time series plot (single or multiple parameters) time_plotter = TimeSeriesPlotter(data) time_plotter.plot(parameter_names=[‘temperature’], output_file=”temp_series.png”) time_plotter.plot(parameter_names=[‘temperature’, ‘salinity’], dual_axis=True, output_file=”multi_series.png”)
Base Plotter Classes
- class seasenselib.plotters.base.AbstractPlotter(data: Dataset | None = None)[source]
Bases:
ABCAbstract base class for plotting sensor data from xarray Datasets.
This class provides a common interface for all plotter implementations. All concrete plotter classes should inherit from this class and implement the plot method.
This class supports the context manager protocol for automatic figure cleanup:
>>> with SomePlotter(dataset) as plotter: ... plotter.plot() >>> # matplotlib figures automatically closed
Attributes:
- dataxr.Dataset (read-only)
The xarray Dataset containing the sensor data to be plotted.
Methods:
- __init__(data: xr.Dataset):
Initializes the plotter with the provided xarray Dataset.
- __enter__() -> AbstractPlotter:
Context manager entry point.
- __exit__(exc_type, exc_val, exc_tb) -> None:
Context manager exit - closes matplotlib figures.
- data: xr.Dataset (read-only)
The xarray Dataset containing the sensor data.
- plot(**kwargs):
Creates the plot (to be implemented by subclasses).
- _get_dataset_without_nan() -> xr.Dataset:
Returns dataset with NaN values removed from time dimension.
- _validate_required_variables(required_vars: list):
Validates that required variables exist in the dataset.
Raises:
- NotImplementedError:
If the subclass does not implement the plot method.
- TypeError:
If the provided data is not an xarray Dataset.
- ValueError:
If required variables are missing from the dataset.
- classmethod add_cli_arguments(parser)[source]
Optional hook for plotters to add their CLI arguments.
Plugins can override this method to register argparse options specific to the plotter. The parser passed in will already contain the common options (input, output, title, etc.). Implementations should only add arguments and not parse them.
- property data: Dataset | None
Get the xarray Dataset containing the sensor data (read-only).
Returns:
- xr.Dataset | None
The xarray Dataset containing the sensor data.
- abstractmethod static key() str[source]
Get the unique key for this writer.
This property must be implemented by all subclasses.
Returns:
- str
The key value (e.g., ‘time-series’, ‘ts-diagram’, ‘depth-profile’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- abstractmethod static name() str[source]
Get the name for this plotter.
This property must be implemented by all subclasses.
Returns:
- str
The name (e.g., ‘Time Series’, ‘T-S Diagram’, ‘Vertical Profile’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
Specific Plotter Classes
- class seasenselib.plotters.TsDiagramPlotter(data: Dataset | None = None)[source]
Bases:
AbstractPlotterCreates T-S (Temperature-Salinity) diagrams from CTD sensor data.
This class specializes in creating T-S diagrams, which are scatter plots of temperature vs salinity data points, often colored by depth and with optional density isolines.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be plotted.
Methods:
- plot(output_file=None, title=’T-S Diagram’, dot_size=70, use_colormap=True,
show_density_isolines=True, colormap=’jet’, show_lines_between_dots=True, show_grid=True):
Creates and displays/saves the T-S diagram.
- _plot_density_isolines():
Adds density isolines to the T-S diagram.
- plot(output_file: str | None = None, title: str = 'T-S Diagram', dot_size: int = 70, use_colormap: bool = True, show_density_isolines: bool = True, colormap: str = 'jet', show_lines_between_dots: bool = True, show_grid: bool = True, *args, **kwargs)[source]
Creates a T-S diagram plot.
Parameters:
- output_filestr, optional
Path to save the plot. If None, the plot is displayed.
- titlestr, default ‘T-S Diagram’
Title for the plot.
- dot_sizeint, default 70
Size of the scatter plot markers.
- use_colormapbool, default True
Whether to color points by depth using a colormap.
- show_density_isolinesbool, default True
Whether to show density isolines on the plot.
- colormapstr, default ‘jet’
Matplotlib colormap name to use for depth coloring.
- show_lines_between_dotsbool, default True
Whether to connect data points with lines.
- show_gridbool, default True
Whether to show grid lines on the plot.
Raises:
- ValueError:
If required variables (temperature, salinity, depth) are missing.
- class seasenselib.plotters.DepthProfilePlotter(data: Dataset | None = None)[source]
Bases:
AbstractPlotterCreates CTD depth profiles showing temperature and salinity vs depth.
This class specializes in creating depth profile plots with depth on the y-axis and temperature/salinity on separate x-axes.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be plotted.
Methods:
plot(output_file=None, title='Salinity and Temperature Profiles', show_grid=True, dot_size=3, show_lines_between_dots=True, *args, **kwargs)Creates and displays/saves the vertical profile plot.
- classmethod add_cli_arguments(parser)[source]
Register CLI arguments for the depth profile plotter.
- static key() str[source]
Get the unique key for this writer.
This property must be implemented by all subclasses.
Returns:
- str
The key value (e.g., ‘time-series’, ‘ts-diagram’, ‘depth-profile’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- static name() str[source]
Get the name for this plotter.
This property must be implemented by all subclasses.
Returns:
- str
The name (e.g., ‘Time Series’, ‘T-S Diagram’, ‘Vertical Profile’).
Raises:
- NotImplementedError:
If the subclass does not implement this property.
- plot(output_file: str | None = None, title: str = 'Salinity and Temperature Profiles', show_grid: bool = True, dot_size: int = 3, show_lines_between_dots: bool = True, *args, **kwargs)[source]
Creates a vertical CTD profile plot.
Parameters:
- output_filestr, optional
Path to save the plot. If None, the plot is displayed.
- titlestr, default ‘Salinity and Temperature Profiles’
Title for the plot.
- show_gridbool, default True
Whether to show grid lines on the plot.
- dot_sizeint, default 3
Size of the scatter plot markers.
- show_lines_between_dotsbool, default True
Whether to connect data points with lines.
- **kwargsdict
Additional keyword arguments (for compatibility).
Raises:
- ValueError:
If required variables (temperature, salinity, depth) are missing.
- class seasenselib.plotters.TimeSeriesPlotter(data: Dataset | None = None)[source]
Bases:
AbstractPlotterCreates time series plots for one or more parameters in the CTD dataset.
This class specializes in creating time series plots showing how one or more parameters vary over time. It supports: - Single parameter plots - Multiple parameters on the same y-axis - Multiple parameters on dual y-axes (left/right) - Automatic unit-based grouping - Custom styling for each parameter - Data normalization for comparison
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be plotted.
Methods:
- plot(parameters, output_file=None, dual_axis=False,
left_params=None, right_params=None, normalize=False, **kwargs):
Creates and displays/saves the time series plot for multiple parameters.
- plot_single_parameter(parameter, …):
Convenience method for single parameter plotting.
- plot_multiple_parameters(parameters, …):
Convenience method for multi-parameter plotting with explicit parameters.
- classmethod add_cli_arguments(parser)[source]
Register CLI arguments for the multi-parameter time series plotter.
- plot(*args, **kwargs)[source]
Creates a time series plot for multiple parameters.
Parameters:
- *argstuple
First argument can be parameters (str or List[str]).
- **kwargsdict
Keyword arguments: - parameters : str or List[str] - Parameter(s) to plot - output_file : str, optional - Path to save the plot - dual_axis : bool, default False - Use dual y-axes for different units - left_params : List[str], optional - Parameters for left y-axis - right_params : List[str], optional - Parameters for right y-axis - normalize : bool, default False - Normalize all parameters to 0-1 range - colors : List[str], optional - Custom colors for each parameter - line_styles : List[str], optional - Custom line styles - ylim_left : Tuple[float, float], optional - (min, max) for left y-axis - ylim_right : Tuple[float, float], optional - (min, max) for right y-axis
Raises:
- ValueError:
If parameters are not found in the dataset or time data is missing.
- plot_multiple_parameters(parameters: List[str], output_file: str | None = None, dual_axis: bool = False, left_params: List[str] | None = None, right_params: List[str] | None = None, normalize: bool = False, colors: List[str] | None = None, line_styles: List[str] | None = None, ylim_left: Tuple[float, float] | None = None, ylim_right: Tuple[float, float] | None = None)[source]
Convenience method for multi-parameter plotting with explicit parameters.
Parameters:
- parametersList[str]
List of parameters to plot (must exist in the dataset).
- output_filestr, optional
Path to save the plot. If None, the plot is displayed.
- dual_axisbool, default False
Use dual y-axes for different units or manual assignment.
- left_paramsList[str], optional
Parameters to plot on the left y-axis (if dual_axis=True).
- right_paramsList[str], optional
Parameters to plot on the right y-axis (if dual_axis=True).
- normalizebool, default False
Normalize all parameters to 0-1 range for comparison.
- colorsList[str], optional
Custom colors for each parameter line.
- line_stylesList[str], optional
Custom line styles for each parameter (‘-’, ‘–’, ‘-.’, ‘:’).
- ylim_leftTuple[float, float], optional
Y-axis limits for left axis as (min, max).
- ylim_rightTuple[float, float], optional
Y-axis limits for right axis as (min, max).
- plot_normalized_comparison(parameters: List[str], output_file: str | None = None, colors: List[str] | None = None, **kwargs)[source]
Convenience method for normalized parameter comparison.
All parameters are normalized to 0-1 range for easy comparison of trends regardless of their original units or scales.
Parameters:
- parametersList[str]
List of parameters to plot (must exist in the dataset).
- output_filestr, optional
Path to save the plot. If None, the plot is displayed.
- colorsList[str], optional
Custom colors for each parameter line.
- **kwargsdict
Additional styling options.
- plot_single_parameter(parameter: str, output_file: str | None = None, ylim_min: float | None = None, ylim_max: float | None = None, color: str | None = None, line_style: str = '-')[source]
Convenience method for single parameter plotting.
Parameters:
- parameterstr
Name of the parameter to plot (must exist in the dataset).
- output_filestr, optional
Path to save the plot. If None, the plot is displayed.
- ylim_minfloat, optional
Minimum value for the y-axis. If None, auto-scaled.
- ylim_maxfloat, optional
Maximum value for the y-axis. If None, auto-scaled.
- colorstr, optional
Color for the line. If None, uses default color cycle.
- line_stylestr, default ‘-’
Line style for the plot (‘-’, ‘–’, ‘-.’, ‘:’).
- plot_with_auto_dual_axis(parameters: List[str], output_file: str | None = None, normalize: bool = False, **kwargs)[source]
Convenience method that automatically uses dual axis based on parameter units.
Parameters:
- parametersList[str]
List of parameter names to plot (must exist in the dataset).
- output_filestr, optional
Path to save the plot. If None, the plot is displayed.
- normalizebool, default False
Normalize all parameters to 0-1 range for comparison.
- **kwargsdict
Additional styling options (colors, line_styles, ylim_left, ylim_right).
Processors
SeaSenseLib Processing Module
This module provides various processing classes for analyzing and manipulating sensor data stored in xarray Datasets.
Available Processors:
StatisticsProcessor: Calculate statistical metrics on sensor data
SubsetProcessor: Subset sensor data by time, sample indices, or parameter values
ResampleProcessor: Resample sensor data to different time intervals
Example Usage:
from seasenselib.processing import StatisticsProcessor, SubsetProcessor, ResampleProcessor
# Calculate statistics stats_processor = StatisticsProcessor(dataset, “temperature”) mean_temp = stats_processor.mean() max_temp = stats_processor.max()
# Subset data subset_processor = SubsetProcessor(dataset) subset = subset_processor.set_time_min(“2023-01-01”).set_time_max(“2023-01-31”).get_subset()
# Resample data resample_processor = ResampleProcessor(dataset) daily_data = resample_processor.resample(“1D”)
Base Processor Classes
- class seasenselib.processors.base.AbstractProcessor(data: Dataset)[source]
Bases:
ABCAbstract base class for processing sensor data from xarray Datasets.
This class provides a common interface for all processor implementations. All concrete processor classes should inherit from this class and implement their specific processing methods.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be processed.
Methods:
- __init__(data: xr.Dataset):
Initializes the processor with the provided xarray Dataset.
- abstractmethod process() Any[source]
Process the dataset.
This method should be implemented by concrete processor classes to define their specific processing logic.
Returns:
- Any:
The result of the processing operation.
Specific Processor Classes
- class seasenselib.processors.SubsetProcessor(data: Dataset)[source]
Bases:
AbstractProcessorSubset sensor data based on sample number, time, and parameter values.
This class allows for flexible slicing of sensor data stored in an xarray Dataset. It can filter data based on sample indices, time ranges, and specific parameter values.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data to be subsetted.
- min_sampleint, optional
The minimum sample index to include in the subset.
- max_sampleint, optional
The maximum sample index to include in the subset.
- min_datetimepd.Timestamp, optional
The minimum time to include in the subset.
- max_datetimepd.Timestamp, optional
The maximum time to include in the subset.
- parameter_namestr, optional
The name of the parameter to filter by.
- parameter_value_minfloat, optional
The minimum value of the parameter to include in the subset.
- parameter_value_maxfloat, optional
The maximum value of the parameter to include in the subset.
Example Usage:
subset_processor = SubsetProcessor(dataset) subset_processor.set_sample_min(10).set_sample_max(50) subset_processor.set_time_min(“2023-01-01”).set_time_max(“2023-01-31”) subset = subset_processor.get_subset()
- get_subset() Dataset[source]
Return the subset of the dataset based on the specified criteria.
This method applies all the slicing parameters to filter the dataset. It slices the dataset by sample number, time, and parameter values as specified.
Returns:
- xr.Dataset:
The subset of the dataset that matches the specified criteria.
- process() Dataset[source]
Process the dataset to create a subset.
This method applies all the filtering criteria to create the final subset.
Returns:
- xr.Dataset:
The subset of the dataset based on the specified criteria.
- reset() SubsetProcessor[source]
Reset all filtering criteria to None.
Returns:
- SubsetProcessor:
The current instance for method chaining.
- set_parameter_name(value: str) SubsetProcessor[source]
Set the name of the parameter to filter by.
Parameters:
- valuestr
The name of the parameter to filter by.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not a string.
- ValueError:
If the provided parameter name is not found in the dataset.
- set_parameter_value_max(value: int | float) SubsetProcessor[source]
Set the maximum value of the parameter to include in the subset.
Parameters:
- valueint or float
The maximum value of the parameter to include in the subset.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not a number.
- set_parameter_value_min(value: int | float) SubsetProcessor[source]
Set the minimum value of the parameter to include in the subset.
Parameters:
- valueint or float
The minimum value of the parameter to include in the subset.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not a number.
- set_sample_max(value: int) SubsetProcessor[source]
Set the maximum sample index for slicing the dataset.
Parameters:
- valueint
The maximum sample index to include in the subset.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not an integer.
- set_sample_min(value: int) SubsetProcessor[source]
Set the minimum sample index for slicing the dataset.
Parameters:
- valueint
The minimum sample index to include in the subset.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not an integer.
- set_time_max(value: str | Timestamp) SubsetProcessor[source]
Set the maximum time for slicing the dataset.
Parameters:
- valuestr or pd.Timestamp
The maximum time to include in the subset.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not a string or a pandas Timestamp.
- set_time_min(value: str | Timestamp) SubsetProcessor[source]
Set the minimum time for slicing the dataset.
Parameters:
- valuestr or pd.Timestamp
The minimum time to include in the subset.
Returns:
- SubsetProcessor:
The current instance for method chaining.
Raises:
- TypeError:
If the provided value is not a string or a pandas Timestamp.
- class seasenselib.processors.ResampleProcessor(data: Dataset)[source]
Bases:
AbstractProcessorResample sensor data to different time intervals.
This class provides methods to resample sensor data along the time dimension to different frequencies (e.g., hourly, daily, monthly).
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data.
Example Usage:
resample_processor = ResampleProcessor(dataset) daily_data = resample_processor.resample(“1D”).mean() hourly_data = resample_processor.resample(“1H”).median()
- process() Dataset[source]
Process the dataset (returns the original dataset).
This method is required by the AbstractProcessor interface. For resampling, use the resample() method instead.
Returns:
- xr.Dataset:
The original dataset.
- resample(time_interval: str, dim: str | None = None) Any[source]
Resample the dataset to a specified time interval.
Parameters:
- time_intervalstr
The time interval for resampling (e.g., “1H”, “1D”, “1M”). Uses pandas frequency strings.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.core.resample.DatasetResample:
A resample object that can be used to apply aggregation functions.
Example:
# Resample to daily averages daily_mean = resample_processor.resample(“1D”).mean()
# Resample to hourly maximum values hourly_max = resample_processor.resample(“1H”).max()
- resample_count(time_interval: str, dim: str | None = None) Dataset[source]
Resample and count valid values.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with count values.
- resample_max(time_interval: str, dim: str | None = None) Dataset[source]
Resample and compute maximum values.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with maximum values.
- resample_mean(time_interval: str, dim: str | None = None) Dataset[source]
Resample and compute mean values.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with mean values.
- resample_median(time_interval: str, dim: str | None = None) Dataset[source]
Resample and compute median values.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with median values.
- resample_min(time_interval: str, dim: str | None = None) Dataset[source]
Resample and compute minimum values.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with minimum values.
- resample_std(time_interval: str, dim: str | None = None) Dataset[source]
Resample and compute standard deviation.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with standard deviation values.
- resample_sum(time_interval: str, dim: str | None = None) Dataset[source]
Resample and compute sum values.
Parameters:
- time_intervalstr
The time interval for resampling.
- dimstr, optional
The dimension to resample along. If None, uses the TIME parameter.
Returns:
- xr.Dataset:
The resampled dataset with sum values.
- class seasenselib.processors.StatisticsProcessor(data: Dataset, parameter: str)[source]
Bases:
AbstractProcessorCalculate statistical metrics on sensor data.
This class provides methods to calculate various statistical measures like mean, median, standard deviation, etc. on specific parameters within a sensor dataset.
Attributes:
- dataxr.Dataset
The xarray Dataset containing the sensor data.
- parameterstr
The name of the parameter to calculate statistics for.
Example Usage:
stats_processor = StatisticsProcessor(dataset, “temperature”) mean_temp = stats_processor.mean() max_temp = stats_processor.max() stats = stats_processor.get_all_statistics()
- count_valid(dim: str | None = None) Any[source]
Count valid (non-NaN) values.
Parameters:
- dimstr, optional
The dimension along which to count valid values. If None, uses the TIME parameter.
Returns:
- int or xr.DataArray:
The count of valid values.
- get_all_statistics(dim: str | None = None) dict[source]
Calculate all available statistics.
Parameters:
- dimstr, optional
The dimension along which to calculate statistics. If None, uses the TIME parameter.
Returns:
- dict:
A dictionary containing all calculated statistics.
- max(dim: str | None = None) Any[source]
Calculate the maximum value.
Parameters:
- dimstr, optional
The dimension along which to calculate the maximum. If None, uses the TIME parameter.
Returns:
- Any:
The maximum value(s).
- mean(dim: str | None = None) Any[source]
Calculate the arithmetic mean.
Parameters:
- dimstr, optional
The dimension along which to calculate the mean. If None, uses the TIME parameter.
Returns:
- float or xr.DataArray:
The mean value(s).
- median(dim: str | None = None) Any[source]
Calculate the median value.
Parameters:
- dimstr, optional
The dimension along which to calculate the median. If None, uses the TIME parameter.
Returns:
- float or xr.DataArray:
The median value(s).
- min(dim: str | None = None) Any[source]
Calculate the minimum value.
Parameters:
- dimstr, optional
The dimension along which to calculate the minimum. If None, uses the TIME parameter.
Returns:
- float or xr.DataArray:
The minimum value(s).
- process() dict[source]
Process the dataset to calculate all statistics.
Returns:
- dict:
A dictionary containing all calculated statistics.
- quantile(q: float | list, dim: str | None = None) Any[source]
Calculate quantiles.
Parameters:
- qfloat or list
Quantile(s) to compute (0 <= q <= 1).
- dimstr, optional
The dimension along which to calculate the quantiles. If None, uses the TIME parameter.
Returns:
- float or xr.DataArray:
The quantile value(s).
Pipeline System
The Level-1 processing pipeline transforms raw data into standardized, CF/ACDD-compliant datasets through a sequence of configurable stages. See the User Guide for a conceptual overview; the classes and factory functions below make up its public API.
Stage-based processing pipeline for SeaSenseLib.
Public API for building and executing processing pipelines.
- class seasenselib.pipeline.Pipeline(stages: List[Stage])[source]
Bases:
objectExecutes stages in sequence to transform datasets.
The pipeline: 1. Executes stages in the configured order 2. Checks can_process() for each stage 3. Executes process() for enabled stages 4. Returns the final dataset
- describe() str[source]
Get a human-readable description of the pipeline.
- Returns:
Multi-line description showing stage order.
- Return type:
str
- execute(dataset: Dataset, metadata: Dict[str, Any] | None = None) Dataset[source]
Execute all stages and return the final dataset.
- Parameters:
dataset (xr.Dataset) – The input dataset to process.
metadata (Dict[str, Any], optional) – Initial metadata. If None, starts with empty dict.
- Returns:
The processed dataset after all stages.
- Return type:
xr.Dataset
- Raises:
Exception – If any layer raises an exception during processing.
Examples
>>> ds = xr.Dataset({'t090C': (['time'], [10, 11, 12])}) >>> result = pipeline.execute(ds, metadata={'source': 'test.cnv'})
- class seasenselib.pipeline.Stage[source]
Bases:
ABCAbstract base class for all processing stages.
Each stage performs a specific transformation or enrichment on the dataset. Stages are executed in the order defined by the pipeline configuration.
Subclasses must implement: - name(): Return unique identifier for this stage - process(): Transform the dataset and return updated context
Subclasses may override: - can_process(): Check if stage should run (default: always True) - configure(): Set stage-specific configuration - configure(): Set stage-specific configuration
Examples
>>> class MyStage(Stage): ... def name(self) -> str: ... return "my_stage" ... ... def process(self, context: StageContext) -> StageContext: ... # Add a new variable ... context.dataset['new_var'] = context.dataset['temp'] * 2 ... context.metadata['my_stage_applied'] = True ... return context
- can_process(context: StageContext) bool[source]
Check if this stage can process the current context.
This method is called by the pipeline before process(). If it returns False, the stage is skipped.
Use this for: - Checking if required variables are present - Verifying prerequisites from previous stages - Conditional stage execution based on metadata
- Parameters:
context (StageContext) – The current processing context.
- Returns:
True if the layer should process this context, False to skip.
- Return type:
bool
Examples
>>> def can_process(self, context: StageContext) -> bool: ... # Only process if temperature variable exists ... return 'temperature' in context.dataset.data_vars
- configure(config: Dict[str, Any]) None[source]
Configure the stage with settings from configuration.
Called by the pipeline when building from configuration. Override this to support layer-specific configuration.
- Parameters:
config (Dict[str, Any]) – Configuration dictionary for this stage.
Examples
>>> class MyStage(Stage): ... def __init__(self): ... self.option = "default" ... ... def configure(self, config: Dict[str, Any]) -> None: ... if 'option' in config: ... self.option = config['option']
- abstractmethod name() str[source]
Get the unique identifier for this stage.
This name is used for: - Configuration references - Registry lookups - Logging and debugging
- Returns:
Unique stage identifier (e.g., ‘mapping’, ‘metadata_enrichment’)
- Return type:
str
- abstractmethod process(context: StageContext) StageContext[source]
Process the dataset and return updated context.
This is the main method where the layer’s transformation logic lives.
The stage should: 1. Read from context.dataset and context.metadata 2. Perform transformations on the dataset 3. Update context.metadata with any relevant information 4. Return the updated context
Note: xarray Datasets are typically treated as immutable, so most operations return a new Dataset. The layer should return a context with the updated dataset.
- Parameters:
context (StageContext) – The current processing context with dataset and metadata.
- Returns:
Updated context with transformed dataset and metadata.
- Return type:
- Raises:
Exception – If processing fails. Exceptions are propagated to the pipeline.
- class seasenselib.pipeline.StageContext(dataset: Dataset, metadata: Dict[str, ~typing.Any]=<factory>)[source]
Bases:
objectContext object passed between stages in the pipeline.
Contains the dataset being processed and accumulated metadata.
- dataset
The xarray Dataset being processed. Each layer may modify this.
- Type:
xr.Dataset
- metadata
Metadata accumulated during processing. Stages can add information here that may be useful for subsequent stages or for users.
- Type:
Dict[str, Any]
Examples
>>> import xarray as xr >>> ds = xr.Dataset({'temp': (['time'], [10, 11, 12])}) >>> context = StageContext(ds, metadata={'source': 'test.cnv'}) >>> context.metadata['variables_mapped'] = ['temp']
- copy() StageContext[source]
Create a shallow copy of the context.
The dataset is not copied (xarray datasets are immutable by convention). The metadata dictionary is shallow-copied.
- Returns:
A new context with the same dataset and a copy of metadata.
- Return type:
- dataset: Dataset
- metadata: Dict[str, Any]
- class seasenselib.pipeline.TransformationStage(transformations: List[ITransformation] | None = None)[source]
Bases:
StageApply optional data/value transformations before validation.
- can_process(context: StageContext) bool[source]
Check if this stage can process the current context.
This method is called by the pipeline before process(). If it returns False, the stage is skipped.
Use this for: - Checking if required variables are present - Verifying prerequisites from previous stages - Conditional stage execution based on metadata
- Parameters:
context (StageContext) – The current processing context.
- Returns:
True if the layer should process this context, False to skip.
- Return type:
bool
Examples
>>> def can_process(self, context: StageContext) -> bool: ... # Only process if temperature variable exists ... return 'temperature' in context.dataset.data_vars
- configure(config: Dict[str, Any]) None[source]
Configure the stage with settings from configuration.
Called by the pipeline when building from configuration. Override this to support layer-specific configuration.
- Parameters:
config (Dict[str, Any]) – Configuration dictionary for this stage.
Examples
>>> class MyStage(Stage): ... def __init__(self): ... self.option = "default" ... ... def configure(self, config: Dict[str, Any]) -> None: ... if 'option' in config: ... self.option = config['option']
- name() str[source]
Get the unique identifier for this stage.
This name is used for: - Configuration references - Registry lookups - Logging and debugging
- Returns:
Unique stage identifier (e.g., ‘mapping’, ‘metadata_enrichment’)
- Return type:
str
- process(context: StageContext) StageContext[source]
Process the dataset and return updated context.
This is the main method where the layer’s transformation logic lives.
The stage should: 1. Read from context.dataset and context.metadata 2. Perform transformations on the dataset 3. Update context.metadata with any relevant information 4. Return the updated context
Note: xarray Datasets are typically treated as immutable, so most operations return a new Dataset. The layer should return a context with the updated dataset.
- Parameters:
context (StageContext) – The current processing context with dataset and metadata.
- Returns:
Updated context with transformed dataset and metadata.
- Return type:
- Raises:
Exception – If processing fails. Exceptions are propagated to the pipeline.
- class seasenselib.pipeline.PipelineConfig[source]
Bases:
objectConfiguration for a pipeline.
Can be loaded from: - Dictionary - YAML file - TOML file - Built programmatically
Examples
>>> config = PipelineConfig() >>> config.add_stage('mapping') >>> config.add_stage('metadata_enrichment') >>> >>> # Or from dict >>> config = PipelineConfig.from_dict({ ... 'stages': [ ... {'name': 'mapping'}, ... {'name': 'metadata_enrichment'}, ... ] ... })
- add_stage(name: str, enabled: bool = True, config: Dict[str, Any] | None = None) PipelineConfig[source]
Add a stage to the configuration.
- disable_stage(name: str) PipelineConfig[source]
Disable a stage (keep in config but set enabled=False).
- enable_stage(name: str) PipelineConfig[source]
Enable a stage.
- classmethod from_dict(data: Dict[str, Any]) PipelineConfig[source]
Load configuration from dictionary.
Structure: {
- ‘stages’: [
{‘name’: ‘mapping’, ‘enabled’: True, ‘config’: {…}}, …
], ‘global’: {…}
}
- classmethod from_file(filepath: str | Path) PipelineConfig[source]
Load configuration from YAML, TOML, or JSON file.
- classmethod from_resource(name: str) PipelineConfig[source]
Load a built-in pipeline profile from package resources.
- Parameters:
name (str) – Profile name (without extension). Example: ‘default’
- get_enabled_stages() List[StageConfig][source]
Get list of enabled stages.
- remove_stage(name: str) PipelineConfig[source]
Remove a stage from configuration.
- set_global_config(key: str, value: Any) PipelineConfig[source]
Set a global configuration value.
- upsert_stage(name: str, enabled: bool | None = None, config: Dict[str, Any] | None = None) PipelineConfig[source]
Update an existing stage config or add a new one.
- class seasenselib.pipeline.StageConfig(name: str, enabled: bool = True, config: Dict[str, Any] | None = None)[source]
Bases:
objectConfiguration for a single stage.
- name
The stage name (must match registry).
- Type:
str
- enabled
Whether this stage is enabled.
- Type:
bool
- config
Stage-specific configuration.
- Type:
Dict[str, Any]
- class seasenselib.pipeline.StageRegistry[source]
Bases:
objectRegistry for discovering and managing available stages.
Stages are discovered via Python entry points in the ‘seasenselib.pipeline’ group. This allows third-party packages to register their own stages.
- DEFAULT_STAGE_NAMES = ['mapping', 'unit_handling', 'transformation', 'derivation', 'metadata_extraction', 'metadata_enrichment', 'validation', 'finalization']
- classmethod default_stage_names() List[str][source]
Return the default stage names (without forcing discovery).
- classmethod get_instance() StageRegistry[source]
- seasenselib.pipeline.default_pipeline() Pipeline[source]
Create the default pipeline for SeaSenseLib.
The default pipeline includes (in order): 1. Mapping 2. Unit Handling 3. Transformation 4. Derivation 5. Metadata Extraction 6. Metadata Enrichment 7. Validation 8. Finalization
- seasenselib.pipeline.minimal_pipeline() Pipeline[source]
Create a minimal pipeline with only essential transformations.
Includes (in order): 1. Mapping 2. Finalization
- seasenselib.pipeline.create_pipeline(stage_names: List[str] | None = None, config: PipelineConfig | None = None) Pipeline[source]
Create a pipeline from stage names or configuration.
Core Infrastructure
Lower-level classes used by the readers, writers, and top-level API. Most users will not need these directly.
- class seasenselib.core.DataIOManager[source]
Bases:
objectLightweight coordinator for data reading and writing operations.
This class delegates the actual work to specialized factories while providing a simple unified interface for CLI and API consumers.
Architecture: - FormatDetector: Detects file formats from extensions/hints - ReaderFactory: Creates appropriate reader instances - WriterFactory: Creates appropriate writer instances - DataIOManager: Orchestrates the above components
Attributes:
- format_detectorFormatDetector
Detects file formats
- reader_factoryReaderFactory
Creates reader instances
- writer_factoryWriterFactory
Creates writer instances
- read_data(input_file: str, format_hint: str | None = None, header_input_file: str | None = None, **kwargs) Any[source]
Read data from input file.
Parameters:
- input_filestr
Path to the input file
- format_hintstr, optional
Format hint to override auto-detection
- header_input_filestr, optional
Path to header file (required for some formats like Nortek ASCII)
- **kwargs
Reader-specific parameters passed through to the reader. Common parameters: - sanitize_input : bool (for CNV files, default=True) - encoding : str (for TOB files) - mapping : dict (variable name mapping)
Returns:
- xarray.Dataset
The loaded data
Raises:
- ReaderError
If reading fails
- write_data(data: Any, output_file: str, format_hint: str | None = None, **kwargs) None[source]
Write data to output file.
Parameters:
- dataxarray.Dataset
The data to write
- output_filestr
Path to the output file
- format_hintstr, optional
Format hint to override auto-detection (e.g., ‘netcdf’, ‘csv’, ‘excel’)
- **kwargs
Writer-specific parameters passed through to the writer.
Raises:
- WriterError
If writing fails
- class seasenselib.core.FormatDetector[source]
Bases:
objectFile format detection using autodiscovery.
- static detect_format(input_file: str, format_hint: str | None = None) str[source]
Detect file format without importing readers.
Parameters:
- input_filestr
Path to the input file
- format_hintstr, optional
Explicit format hint to override detection
Returns:
- str
The detected format key
Raises:
- FormatDetectionError
If format cannot be determined
- class seasenselib.core.ReaderFactory[source]
Bases:
objectFactory for creating reader instances with autodiscovery.
- create_reader(format_key: str, input_file: str, header_file: str | None = None, validate_reader_args: bool = False, **kwargs) AbstractReader[source]
Create a reader instance for the given format using signature introspection.
This method uses Python inspect module to automatically match provided parameters to the reader constructor signature, eliminating hardcoded special cases and enabling plugin readers with custom parameters.
- Parameters:
format_key (str) – The format key (e.g., ‘sbe-cnv’, ‘rbr-rsk’)
input_file (str) – Path to the input file
header_file (str, optional) – Path to header file (for formats like Nortek ASCII that need it)
**kwargs – All other parameters are matched against the reader constructor signature. Common parameters: - mapping : dict (variable name mapping, supported by all readers) - sanitize_input : bool (for CNV readers) - encoding : str (for TOB readers) - Any custom parameters for plugin readers
- Returns:
Reader instance ready to use
- Return type:
- Raises:
ReaderError – If reader cannot be created
- class seasenselib.core.WriterFactory[source]
Bases:
objectFactory for creating writer instances with dynamic autodiscovery.
- create_writer(format_key: str, data: Any) AbstractWriter[source]
Create a writer instance for the given format.
Parameters:
- format_keystr
The format key (e.g., ‘netcdf’, ‘csv’, ‘excel’)
- dataAny
The data to write (typically xarray.Dataset)
Returns:
- AbstractWriter
Writer instance ready to use
Raises:
- WriterError
If writer cannot be created
Exceptions
- class seasenselib.core.FormatDetectionError[source]
Bases:
SeaSenseLibErrorRaised when file format cannot be detected.
- class seasenselib.core.DependencyError[source]
Bases:
SeaSenseLibErrorRaised when required dependencies are not available.
- class seasenselib.core.ValidationError[source]
Bases:
SeaSenseLibErrorRaised when input validation fails.
Canonical Parameters
seasenselib.parameters defines the canonical (standardized) variable names used throughout SeaSenseLib — for example TEMPERATURE = 'temperature' and SALINITY = 'salinity'. Reader mappings translate instrument-specific column names onto these canonical names.
To list the canonical parameters available at runtime, use the top-level helper:
import seasenselib as ssl
ssl.list_parameters()