seapopym.standard package
Submodules
seapopym.standard.attributs module
Store all default attributs for the seapopym xarray.DataArray.
- seapopym.standard.attributs.apply_coefficient_to_primary_production_desc = {'description': 'Primary production by functional group according to their energy transfert coefficient.', 'long_name': 'primary production by functional group', 'standard_name': 'primary production', 'units': 'kilogram / day / meter ** 2'}
dict: Apply coefficient to primary production attributs.
- seapopym.standard.attributs.compute_cell_area_desc = {'description': 'Cell area computed from the latitude and longitude centroid.', 'long_name': 'cell area', 'standard_name': 'cell_area', 'units': 'meter**2'}
dict: Compute cell area attributs.
- seapopym.standard.attributs.functional_group_desc(f_group_coord_data: Iterable, groups_name: list[str]) dict
Functional group attributs. Standard name is used as an accessor by cf_xarray.
- seapopym.standard.attributs.global_mask_desc = {'flag_meanings': '0:land, 1:ocean', 'flag_values': '[0, 1]', 'long_name': 'mask', 'standard_name': 'mask'}
dict: Global mask attributs.
- seapopym.standard.attributs.mask_by_fgroup_desc = {'flag_meanings': '0:land, 1:ocean', 'flag_values': '[0, 1]', 'long_name': 'mask', 'standard_name': 'mask'}
dict: Mask by fgroup attributs.
- seapopym.standard.attributs.mask_temperature_desc = {'description': 'Mask to recruit a cohort according to the temperature.', 'flag_meanings': '0:not recruited, 1:recruited', 'flag_values': '[0, 1]', 'long_name': 'cohort recruitment mask by functional group', 'standard_name': 'mask'}
dict: Mask temperature attributs.
- seapopym.standard.attributs.min_temperature_by_cohort_desc = {'description': 'Minimum temperature to recruit a cohort according to its age.', 'long_name': 'minimum temperature by cohort', 'standard_name': 'minimum temperature', 'units': 'degree_Celsius'}
dict: Minimum temperature by cohort attributs.
- seapopym.standard.attributs.mortality_field_desc = {'description': 'Mortality coefficient according to the temperature.', 'long_name': 'mortality coefficient', 'standard_name': 'mortality'}
dict: Mortality field attributs.
seapopym.standard.coordinates module
Defines the structure of the coordinates of the data.
- seapopym.standard.coordinates.new_cohort(cohort_data: Iterable) xr.DataArray
Create a new cohort coordinate.
Deprecated since version 2024.12: Use CoordinateAuthority.get_coordinate_attrs() or the registered factory instead. This function will be removed in a future version.
- seapopym.standard.coordinates.new_latitude(latitude_data: np.ndarray) xr.DataArray
Create a new latitude coordinate with standardized Y name.
Deprecated since version 2024.12: Use CoordinateAuthority.get_coordinate_attrs() or the registered factory instead. This function will be removed in a future version.
- seapopym.standard.coordinates.new_layer(layer_data: Iterable | None = None) xr.DataArray
Create a new layer coordinate.
Deprecated since version 2024.12: Use CoordinateAuthority.get_coordinate_attrs() or the registered factory instead. This function will be removed in a future version.
- seapopym.standard.coordinates.new_longitude(longitude_data: Iterable) xr.DataArray
Create a new longitude coordinate with standardized X name.
Deprecated since version 2024.12: Use CoordinateAuthority.get_coordinate_attrs() or the registered factory instead. This function will be removed in a future version.
- seapopym.standard.coordinates.new_time(time_data: Iterable) xr.DataArray
Create a new time coordinate with standardized T name.
Deprecated since version 2024.12: Use CoordinateAuthority.get_coordinate_attrs() or the registered factory instead. This function will be removed in a future version.
- seapopym.standard.coordinates.reorder_dims(data: xr.Dataset | xr.DataArray) xr.Dataset | xr.DataArray
Follow the standard order of dimensions for a xarray.Dataset or xarray.DataArray.
Deprecated since version 2024.12: Use CoordinatesLabels.order_data() instead. This function will be removed in a future version.
seapopym.standard.labels module
Store all labels used in the No Transport model.
- class seapopym.standard.labels.ConfigurationLabels(*values)
Bases:
StrEnumA single place to store all labels as declared in parameters module.
- angle_horizon_sun = 'angle_horizon_sun'
- cohort = 'cohort'
- compute_initial_conditions = 'compute_initial_conditions'
- compute_preproduction = 'compute_preproduction'
- day_layer = 'day_layer'
- energy_transfert = 'energy_transfert'
- fgroup_name = 'name'
- gamma_lambda_acidity = 'gamma_lambda_acidity'
- gamma_lambda_temperature = 'gamma_lambda_temperature'
- gamma_survival_rate_acidity = 'gamma_survival_rate_acidity'
- gamma_survival_rate_temperature = 'gamma_survival_rate_temperature'
- gamma_tr = 'gamma_tr'
- initial_condition_biomass = 'initial_condition_biomass'
- initial_condition_production = 'initial_condition_production'
- lambda_0 = 'lambda_0'
- lambda_acidity_0 = 'lambda_acidity_0'
- lambda_temperature_0 = 'lambda_temperature_0'
- max_timestep = 'max_timestep'
- mean_timestep = 'mean_timestep'
- min_timestep = 'min_timestep'
- night_layer = 'night_layer'
- resolution_latitude = 'resolution_latitude'
- resolution_longitude = 'resolution_longitude'
- survival_rate_0 = 'survival_rate_0'
- timestep = 'timestep'
- timesteps_number = 'timesteps_number'
- tr_0 = 'tr_0'
- class seapopym.standard.labels.CoordinatesLabels(*values)
Bases:
StrEnumA single place to store all labels as declared in coordinates module. It follow the cf_xarray convention.
- X = 'X'
- Y = 'Y'
- Z = 'Z'
- cohort = 'cohort'
- functional_group = 'functional_group'
- classmethod order_data(data: xr.Dataset | xr.DataArray) xr.Dataset
Return the dataset with the coordinates ordered as in the CF convention.
- classmethod ordered() tuple[CoordinatesLabels]
Return all labels in the order they should be used in a dataset. It follow the CF convention.
- time = 'T'
- class seapopym.standard.labels.ForcingLabels(*values)
Bases:
StrEnumA single place to store all labels as declared in forcing module.
- acidity = 'acidity'
- avg_acidity_by_fgroup = 'average_acidity'
- avg_temperature_by_fgroup = 'average_temperature'
- biomass = 'biomass'
- cell_area = 'cell_area'
- day_length = 'day_length'
- global_mask = 'mask'
- mask_by_fgroup = 'mask_fgroup'
- mask_temperature = 'mask_temperature'
- min_temperature = 'min_temperature'
- mortality_field = 'mortality_field'
- preproduction = 'preproduction'
- primary_production = 'primary_production'
- primary_production_by_fgroup = 'primary_production_by_fgroup'
- recruited = 'recruited'
- survival_rate = 'survival_rate'
- temperature = 'temperature'
- class seapopym.standard.labels.SeaLayers(*values)
Bases:
EnumEnumerate the sea layers.
- EPI = ('epipelagic', 1)
- LOWMESO = ('lower-mesopelagic', 3)
- UPMESO = ('upper-mesopelagic', 2)
- property depth: Literal[1, 2, 3]
Return the depth of the sea layer.
- property standard_name: Literal['epipelagic', 'upper-mesopelagic', 'lower-mesopelagic']
Return the standard_name of the sea layer.
seapopym.standard.types module
Defines type aliases for Seapopym standard types.
seapopym.standard.units module
A module for handling units in the forcing data following the CF conventions.
- class seapopym.standard.units.StandardUnitsLabels(*values)
Bases:
StrEnumUnit of measurement as used in the model.
Prevent the instantiation of this class.
- acidity = 'dimensionless'
- biomass = 'kilogram / meter**2'
- height = 'meter'
- production = 'kilogram / meter**2 / day'
- temperature = 'celsius'
- time = 'day'
- property units: Unit
Convert the string unit to the equivalent pint unit.
- weight = 'kilogram'
- class seapopym.standard.units.StandardUnitsRegistry
Bases:
objectCentralized registry for units management and conversion.
Provides a clean API for unit handling, formatting, and validation to replace scattered unit conversions throughout the codebase.
This registry acts as the single source of truth for all unit operations in Seapopym, ensuring consistent unit handling across templates, kernels, and data processing functions.
- Key Features:
Standardized unit string formatting for xarray attributes
Convenient attribute dictionary generation for DataArrays
Unit compatibility validation for data objects
Complete enumeration of supported units
- Usage Patterns:
Basic unit formatting: >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.temperature) ‘degree_Celsius’
Creating xarray attributes: >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.biomass, … long_name=”Biomass density”, … standard_name=”biomass_density” … ) >>> # Use with xarray: data_array.attrs.update(attrs)
Template integration: >>> # In template factories >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.production, … standard_name=”primary_production_rate” … )
- Thread Safety:
All methods are static and thread-safe. No instance state is maintained.
- static format_unit_string(unit_label: StandardUnitsLabels) str
Format a unit label to standardized string representation.
Converts a StandardUnitsLabels enum value to its string representation as formatted by the pint units library. This ensures consistent unit formatting across all xarray attributes and CF-compliant datasets.
- Args:
unit_label: Unit label from StandardUnitsLabels enum
- Returns:
Formatted unit string suitable for xarray attributes. Note: Pint may format units differently than the input strings (e.g., ‘celsius’ becomes ‘degree_Celsius’)
- Raises:
AttributeError: If unit_label is not a valid StandardUnitsLabels enum
- Examples:
Basic unit formatting: >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.temperature) ‘degree_Celsius’ >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.time) ‘day’
Complex compound units: >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.biomass) ‘kilogram / meter ** 2’ >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.production) ‘kilogram / meter ** 2 / day’
- Note:
This method is the recommended way to get unit strings for xarray attributes, replacing direct access to StandardUnitsLabels.units
- static get_supported_units() tuple[StandardUnitsLabels, ...]
Get all supported unit labels.
Returns a tuple containing all available StandardUnitsLabels enum values, providing a complete inventory of units supported by the system.
- Returns:
Tuple of all available StandardUnitsLabels enum values. The tuple is ordered according to the enum definition.
- Examples:
Getting all supported units: >>> units = StandardUnitsRegistry.get_supported_units() >>> len(units) 7 >>> StandardUnitsLabels.temperature in units True
Iterating over supported units: >>> for unit_label in StandardUnitsRegistry.get_supported_units(): … unit_str = StandardUnitsRegistry.format_unit_string(unit_label) … print(f”{unit_label.name}: {unit_str}”) height: meter weight: kilogram temperature: degree_Celsius …
Validation and enumeration: >>> supported = StandardUnitsRegistry.get_supported_units() >>> user_unit = “temperature” # From user input >>> if any(unit.name == user_unit for unit in supported): … unit_label = StandardUnitsLabels[user_unit] … attrs = StandardUnitsRegistry.get_unit_attrs(unit_label)
- Use Cases:
Dynamic unit validation in configuration parsing
Building user interfaces with unit selection
Documentation generation
Testing completeness of unit handling
- Note:
The returned tuple is immutable and reflects the current state of the StandardUnitsLabels enum. Changes to the enum will be automatically reflected in subsequent calls.
- static get_unit_attrs(unit_label: StandardUnitsLabels, **overrides: Any) dict[str, str]
Get standardized unit attributes for xarray DataArrays.
Creates a dictionary of attributes suitable for xarray DataArray.attrs, starting with the properly formatted units and allowing additional CF-compliant attributes to be specified as overrides.
- Args:
unit_label: Unit label from StandardUnitsLabels enum **overrides: Additional attributes to include or override.
Common CF attributes include ‘long_name’, ‘standard_name’, ‘description’, etc. The ‘units’ key can be overridden if a different unit string is needed.
- Returns:
Dictionary with ‘units’ key and any additional overrides. All values are strings suitable for xarray attributes.
- Examples:
Basic usage (units only): >>> attrs = StandardUnitsRegistry.get_unit_attrs(StandardUnitsLabels.temperature) >>> attrs {‘units’: ‘degree_Celsius’}
With CF-compliant metadata: >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.biomass, … long_name=”Biomass density”, … standard_name=”biomass_density”, … description=”Dry weight biomass per unit area” … ) >>> attrs {‘units’: ‘kilogram / meter ** 2’, ‘long_name’: ‘Biomass density’, …}
Overriding units: >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.temperature, … units=”kelvin”, # Override default celsius … standard_name=”sea_water_temperature” … ) >>> attrs {‘units’: ‘kelvin’, ‘standard_name’: ‘sea_water_temperature’}
Template factory usage: >>> # Common pattern in template factories >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.production, … long_name=”Primary production rate”, … standard_name=”net_primary_production_of_biomass_expressed_as_carbon” … )
- Note:
This is the recommended way to create xarray attributes with units, ensuring consistency across all DataArrays in the system.
- static validate_unit_compatibility(value: Any, expected_unit: StandardUnitsLabels) bool
Validate that a value has compatible units.
Performs unit compatibility validation by comparing the units attribute of a value object against an expected StandardUnitsLabels enum value. This validation ensures data consistency across the pipeline.
- Args:
- value: Object to validate. Must have a ‘units’ attribute (typically
xarray DataArray, Dataset, or similar objects with units metadata)
expected_unit: Expected unit label from StandardUnitsLabels enum
- Returns:
True if units match exactly, False otherwise. Returns False for any objects without units or on validation errors.
- Validation Logic:
Checks if value has ‘units’ attribute
Compares string representation of units for exact match
Handles exceptions gracefully by returning False
- Examples:
Validating xarray DataArray: >>> import xarray as xr >>> data = xr.DataArray([1, 2, 3], attrs={‘units’: ‘degree_Celsius’}) >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) True
Invalid units: >>> data = xr.DataArray([1, 2, 3], attrs={‘units’: ‘kelvin’}) >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) False
Missing units attribute: >>> data = xr.DataArray([1, 2, 3]) # No units >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) False
Custom objects: >>> class TemperatureData: … def __init__(self, units_str): … self.units = units_str >>> data = TemperatureData(‘degree_Celsius’) >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) True
- Error Handling:
All exceptions (AttributeError, TypeError, ValueError) are caught and result in False return value. This ensures robust validation even with malformed or unexpected input objects.
- Future Enhancements:
This basic string comparison can be extended to support: - Pint unit compatibility checking (e.g., celsius vs kelvin) - Unit conversion compatibility - Dimensional analysis validation
- Note:
Currently performs exact string matching. Compatible but differently formatted units (e.g., ‘deg_C’ vs ‘degree_Celsius’) will return False.
Module contents
Seapopym standard types, protocols and utilities.
Central module providing: - Type definitions and protocols - Coordinate management and validation - Units and attributes handling - CF-compliant data structures
- class seapopym.standard.ChunkParameterProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for chunk parameter classes.
Defines the interface for classes that manage chunking dimensions for parallel computation in xarray operations.
- as_dict() dict
Format chunk parameters to a dictionary as expected by xarray.
- Returns:
dict: Dictionary with dimension names as keys and chunk sizes as values.
- class seapopym.standard.ConfigurationLabels(*values)
Bases:
StrEnumA single place to store all labels as declared in parameters module.
- angle_horizon_sun = 'angle_horizon_sun'
- cohort = 'cohort'
- compute_initial_conditions = 'compute_initial_conditions'
- compute_preproduction = 'compute_preproduction'
- day_layer = 'day_layer'
- energy_transfert = 'energy_transfert'
- fgroup_name = 'name'
- gamma_lambda_acidity = 'gamma_lambda_acidity'
- gamma_lambda_temperature = 'gamma_lambda_temperature'
- gamma_survival_rate_acidity = 'gamma_survival_rate_acidity'
- gamma_survival_rate_temperature = 'gamma_survival_rate_temperature'
- gamma_tr = 'gamma_tr'
- initial_condition_biomass = 'initial_condition_biomass'
- initial_condition_production = 'initial_condition_production'
- lambda_0 = 'lambda_0'
- lambda_acidity_0 = 'lambda_acidity_0'
- lambda_temperature_0 = 'lambda_temperature_0'
- max_timestep = 'max_timestep'
- mean_timestep = 'mean_timestep'
- min_timestep = 'min_timestep'
- night_layer = 'night_layer'
- resolution_latitude = 'resolution_latitude'
- resolution_longitude = 'resolution_longitude'
- survival_rate_0 = 'survival_rate_0'
- timestep = 'timestep'
- timesteps_number = 'timesteps_number'
- tr_0 = 'tr_0'
- class seapopym.standard.ConfigurationProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for configuration classes.
Defines the interface for classes that manage complete model configurations, including forcing data, functional groups, and kernel parameters.
- forcing: ForcingParameterProtocol
- functional_group: FunctionalGroupParameterProtocol
- kernel: KernelParameterProtocol
- classmethod parse(configuration_file: str | Path | IO) ConfigurationProtocol
Parse configuration file and create a configuration object.
- Args:
configuration_file: Path to configuration file or file-like object.
- Returns:
ConfigurationProtocol: Parsed configuration object implementing this protocol.
- property state: xr.Dataset
Get the complete model state as xarray Dataset.
- Returns:
- xr.Dataset: Complete model state containing all parameters and forcing data.
This is the SeapopymState used throughout the model execution.
- class seapopym.standard.CoordinateAuthority
Bases:
objectCentral authority for coordinate management and validation.
Uses a registry pattern to manage coordinate factories, making it extensible and maintainable. Ensures coordinate attributes are preserved across xarray operations, particularly resolving the asymmetry between sequential and parallel execution paths where attributes can be lost.
Method generated by attrs for class CoordinateAuthority.
- ensure_coordinate_integrity(data: Dataset) Dataset
Ensure coordinate integrity after xarray operations.
This method should be called after operations that might lose coordinate attributes to restore them according to CF conventions.
- Args:
data: xarray Dataset that may have lost coordinate attributes
- Returns:
Dataset with restored coordinate integrity
- get_coordinate_attrs(coord_label: CoordinatesLabels) dict[str, Any]
Get expected attributes for a coordinate label.
- Args:
coord_label: Coordinate label from CoordinatesLabels enum
- Returns:
Dictionary of expected coordinate attributes
- Raises:
KeyError: If coordinate label is not supported
- classmethod get_registered_coordinates() tuple[CoordinatesLabels, ...]
Get all registered coordinate labels.
- classmethod initialize_defaults() None
Initialize the registry with default coordinate factories.
- is_coordinate_valid(data: Dataset, coord_label: CoordinatesLabels) bool
Check if a coordinate has all required attributes.
- Args:
data: xarray Dataset to check coord_label: Coordinate label to validate
- Returns:
True if coordinate has all required attributes, False otherwise
- classmethod register_coordinate(label: CoordinatesLabels, factory: Callable) None
Register a coordinate factory for a given label.
- Args:
label: Coordinate label from CoordinatesLabels enum factory: Function that creates the coordinate with proper attributes
- validate_coordinates(data: Dataset) Dataset
Validate and restore missing coordinate attributes.
- Args:
data: xarray Dataset to validate
- Returns:
Dataset with validated and restored coordinate attributes
- class seapopym.standard.CoordinatesLabels(*values)
Bases:
StrEnumA single place to store all labels as declared in coordinates module. It follow the cf_xarray convention.
- X = 'X'
- Y = 'Y'
- Z = 'Z'
- cohort = 'cohort'
- functional_group = 'functional_group'
- classmethod order_data(data: xr.Dataset | xr.DataArray) xr.Dataset
Return the dataset with the coordinates ordered as in the CF convention.
- classmethod ordered() tuple[CoordinatesLabels]
Return all labels in the order they should be used in a dataset. It follow the CF convention.
- time = 'T'
- class seapopym.standard.ForcingLabels(*values)
Bases:
StrEnumA single place to store all labels as declared in forcing module.
- acidity = 'acidity'
- avg_acidity_by_fgroup = 'average_acidity'
- avg_temperature_by_fgroup = 'average_temperature'
- biomass = 'biomass'
- cell_area = 'cell_area'
- day_length = 'day_length'
- global_mask = 'mask'
- mask_by_fgroup = 'mask_fgroup'
- mask_temperature = 'mask_temperature'
- min_temperature = 'min_temperature'
- mortality_field = 'mortality_field'
- preproduction = 'preproduction'
- primary_production = 'primary_production'
- primary_production_by_fgroup = 'primary_production_by_fgroup'
- recruited = 'recruited'
- survival_rate = 'survival_rate'
- temperature = 'temperature'
- class seapopym.standard.ForcingParameterProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for forcing parameter classes.
Defines the interface for classes that manage forcing parameters, including parallel computation settings and chunk configuration.
- chunk: ChunkParameterProtocol
- parallel: bool
- to_dataset() xr.Dataset
Convert all forcing fields to xarray Dataset.
- Returns:
xr.Dataset: Dataset containing all forcing fields for the model.
- class seapopym.standard.FunctionalGroupParameterProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for functional group parameter classes.
Defines the interface for classes that manage collections of functional groups and their parameters.
- functional_group: Iterable[FunctionalGroupUnitProtocol]
- to_dataset(timestep: int) xr.Dataset
Convert all functional groups to xarray Dataset.
- Args:
timestep: Time step value for the conversion.
- Returns:
xr.Dataset: Dataset containing all functional group parameters.
- class seapopym.standard.KernelParameterProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for kernel parameter classes.
Defines the interface for classes that contain meta-parameters used to modify kernel function behavior. These parameters are integrated into the model state.
Note: This protocol currently has no required methods as kernel parameters are primarily data containers.
- class seapopym.standard.ModelProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for model classes.
Defines the interface for classes that represent complete computational models, including state management, kernel execution, and context management.
- classmethod from_configuration(configuration: ConfigurationProtocol) ModelProtocol
Create a model from a configuration.
- Args:
configuration: Configuration object implementing ConfigurationProtocol.
- Returns:
ModelProtocol: Model instance created from the configuration.
- kernel: Any
- run() None
Run the model.
Executes the model’s computational pipeline, updating the internal state.
- state: Any
- class seapopym.standard.StandardUnitsRegistry
Bases:
objectCentralized registry for units management and conversion.
Provides a clean API for unit handling, formatting, and validation to replace scattered unit conversions throughout the codebase.
This registry acts as the single source of truth for all unit operations in Seapopym, ensuring consistent unit handling across templates, kernels, and data processing functions.
- Key Features:
Standardized unit string formatting for xarray attributes
Convenient attribute dictionary generation for DataArrays
Unit compatibility validation for data objects
Complete enumeration of supported units
- Usage Patterns:
Basic unit formatting: >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.temperature) ‘degree_Celsius’
Creating xarray attributes: >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.biomass, … long_name=”Biomass density”, … standard_name=”biomass_density” … ) >>> # Use with xarray: data_array.attrs.update(attrs)
Template integration: >>> # In template factories >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.production, … standard_name=”primary_production_rate” … )
- Thread Safety:
All methods are static and thread-safe. No instance state is maintained.
- static format_unit_string(unit_label: StandardUnitsLabels) str
Format a unit label to standardized string representation.
Converts a StandardUnitsLabels enum value to its string representation as formatted by the pint units library. This ensures consistent unit formatting across all xarray attributes and CF-compliant datasets.
- Args:
unit_label: Unit label from StandardUnitsLabels enum
- Returns:
Formatted unit string suitable for xarray attributes. Note: Pint may format units differently than the input strings (e.g., ‘celsius’ becomes ‘degree_Celsius’)
- Raises:
AttributeError: If unit_label is not a valid StandardUnitsLabels enum
- Examples:
Basic unit formatting: >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.temperature) ‘degree_Celsius’ >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.time) ‘day’
Complex compound units: >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.biomass) ‘kilogram / meter ** 2’ >>> StandardUnitsRegistry.format_unit_string(StandardUnitsLabels.production) ‘kilogram / meter ** 2 / day’
- Note:
This method is the recommended way to get unit strings for xarray attributes, replacing direct access to StandardUnitsLabels.units
- static get_supported_units() tuple[StandardUnitsLabels, ...]
Get all supported unit labels.
Returns a tuple containing all available StandardUnitsLabels enum values, providing a complete inventory of units supported by the system.
- Returns:
Tuple of all available StandardUnitsLabels enum values. The tuple is ordered according to the enum definition.
- Examples:
Getting all supported units: >>> units = StandardUnitsRegistry.get_supported_units() >>> len(units) 7 >>> StandardUnitsLabels.temperature in units True
Iterating over supported units: >>> for unit_label in StandardUnitsRegistry.get_supported_units(): … unit_str = StandardUnitsRegistry.format_unit_string(unit_label) … print(f”{unit_label.name}: {unit_str}”) height: meter weight: kilogram temperature: degree_Celsius …
Validation and enumeration: >>> supported = StandardUnitsRegistry.get_supported_units() >>> user_unit = “temperature” # From user input >>> if any(unit.name == user_unit for unit in supported): … unit_label = StandardUnitsLabels[user_unit] … attrs = StandardUnitsRegistry.get_unit_attrs(unit_label)
- Use Cases:
Dynamic unit validation in configuration parsing
Building user interfaces with unit selection
Documentation generation
Testing completeness of unit handling
- Note:
The returned tuple is immutable and reflects the current state of the StandardUnitsLabels enum. Changes to the enum will be automatically reflected in subsequent calls.
- static get_unit_attrs(unit_label: StandardUnitsLabels, **overrides: Any) dict[str, str]
Get standardized unit attributes for xarray DataArrays.
Creates a dictionary of attributes suitable for xarray DataArray.attrs, starting with the properly formatted units and allowing additional CF-compliant attributes to be specified as overrides.
- Args:
unit_label: Unit label from StandardUnitsLabels enum **overrides: Additional attributes to include or override.
Common CF attributes include ‘long_name’, ‘standard_name’, ‘description’, etc. The ‘units’ key can be overridden if a different unit string is needed.
- Returns:
Dictionary with ‘units’ key and any additional overrides. All values are strings suitable for xarray attributes.
- Examples:
Basic usage (units only): >>> attrs = StandardUnitsRegistry.get_unit_attrs(StandardUnitsLabels.temperature) >>> attrs {‘units’: ‘degree_Celsius’}
With CF-compliant metadata: >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.biomass, … long_name=”Biomass density”, … standard_name=”biomass_density”, … description=”Dry weight biomass per unit area” … ) >>> attrs {‘units’: ‘kilogram / meter ** 2’, ‘long_name’: ‘Biomass density’, …}
Overriding units: >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.temperature, … units=”kelvin”, # Override default celsius … standard_name=”sea_water_temperature” … ) >>> attrs {‘units’: ‘kelvin’, ‘standard_name’: ‘sea_water_temperature’}
Template factory usage: >>> # Common pattern in template factories >>> attrs = StandardUnitsRegistry.get_unit_attrs( … StandardUnitsLabels.production, … long_name=”Primary production rate”, … standard_name=”net_primary_production_of_biomass_expressed_as_carbon” … )
- Note:
This is the recommended way to create xarray attributes with units, ensuring consistency across all DataArrays in the system.
- static validate_unit_compatibility(value: Any, expected_unit: StandardUnitsLabels) bool
Validate that a value has compatible units.
Performs unit compatibility validation by comparing the units attribute of a value object against an expected StandardUnitsLabels enum value. This validation ensures data consistency across the pipeline.
- Args:
- value: Object to validate. Must have a ‘units’ attribute (typically
xarray DataArray, Dataset, or similar objects with units metadata)
expected_unit: Expected unit label from StandardUnitsLabels enum
- Returns:
True if units match exactly, False otherwise. Returns False for any objects without units or on validation errors.
- Validation Logic:
Checks if value has ‘units’ attribute
Compares string representation of units for exact match
Handles exceptions gracefully by returning False
- Examples:
Validating xarray DataArray: >>> import xarray as xr >>> data = xr.DataArray([1, 2, 3], attrs={‘units’: ‘degree_Celsius’}) >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) True
Invalid units: >>> data = xr.DataArray([1, 2, 3], attrs={‘units’: ‘kelvin’}) >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) False
Missing units attribute: >>> data = xr.DataArray([1, 2, 3]) # No units >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) False
Custom objects: >>> class TemperatureData: … def __init__(self, units_str): … self.units = units_str >>> data = TemperatureData(‘degree_Celsius’) >>> StandardUnitsRegistry.validate_unit_compatibility( … data, StandardUnitsLabels.temperature … ) True
- Error Handling:
All exceptions (AttributeError, TypeError, ValueError) are caught and result in False return value. This ensures robust validation even with malformed or unexpected input objects.
- Future Enhancements:
This basic string comparison can be extended to support: - Pint unit compatibility checking (e.g., celsius vs kelvin) - Unit conversion compatibility - Dimensional analysis validation
- Note:
Currently performs exact string matching. Compatible but differently formatted units (e.g., ‘deg_C’ vs ‘degree_Celsius’) will return False.
- class seapopym.standard.TemplateProtocol(*args, **kwargs)
Bases:
ProtocolProtocol for template classes.
Defines the interface for classes that generate xarray templates for use with map_blocks operations in distributed computing.
- generate(state: Any) Any
Generate an empty xr.DataArray or xr.Dataset template.
- Args:
state: SeapopymState (xr.Dataset) containing model state and coordinates.
- Returns:
Template structure as xr.DataArray or xr.Dataset for map_blocks operations.