Skip to content

Parameter Models

soundscapy.plotting.param_models

Parameter models for plotting functions in soundscapy.

This module provides parameter validation and management classes for various plotting functions using Pydantic dataclasses. The module includes:

  • Base ParamModel class with common functionality
  • SeabornParams for seaborn plotting parameters
  • Specialized parameter classes for different plot types
  • Style and subplot configuration classes

The parameter models provide:

  • Type validation and conversion
  • Default value management
  • Parameter updating with validation
  • Dictionary-style access to parameters
  • Deep copying functionality
CLASS DESCRIPTION
ParamModel

Base model for parameter validation using dataclasses.

SeabornParams

Base parameters for seaborn plotting functions.

ScatterParams

Parameters for scatter plot functions.

DensityParams

Parameters for density plot functions.

SimpleDensityParams

Parameters for simple density plot functions.

SPISeabornParams

Base parameters for SPI (Soundscape Perceptual Index) seaborn plotting functions.

SPISimpleDensityParams

Parameters for SPI simple density plot functions.

JointPlotParams

Parameters for joint plot functions.

StyleParams

Parameters for plot styling.

SubplotsParams

Parameters for subplots.

ParamModel

Base model for parameter validation using dataclasses.

This class provides the foundation for all parameter models with common configuration settings and utility methods.

METHOD DESCRIPTION
__post_init__

Process extra fields after initialization.

update

Update the attributes of the instance based on the provided parameters.

get_defaults

Get the default values for all defined fields in the model.

get

Get a parameter value with a default fallback.

__getitem__

Get a parameter value using dictionary-style access.

as_dict

Get all parameters as a dictionary.

copy

Create a deep copy of the parameter model instance.

model_copy

Create a copy of the parameter model instance.

get_changed_params

Get parameters that have been changed from their defaults.

get_multiple

Get multiple parameters as a dictionary.

pop

Remove a parameter and return its value.

drop

Remove a parameter without returning its value.

ATTRIBUTE DESCRIPTION
defaults

Property to access default field values.

TYPE: dict[str, Any]

defined_field_names

Get the names of all fields defined for the model.

TYPE: list[str]

current_field_names

Get the names of all current fields.

TYPE: list[str]

defaults property

defaults: dict[str, Any]

Property to access default field values.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary mapping field names to their default values.

defined_field_names property

defined_field_names: list[str]

Get the names of all fields defined for the model.

RETURNS DESCRIPTION
list[str]

List of field names

current_field_names property

current_field_names: list[str]

Get the names of all current fields.

RETURNS DESCRIPTION
list[str]

List of field names

__post_init__

__post_init__() -> None

Process extra fields after initialization.

Source code in src/soundscapy/plotting/param_models.py
def __post_init__(self) -> None:
    """Process extra fields after initialization."""
    # Move any extra fields to _extra_fields
    for key, value in list(self.__dict__.items()):
        if key not in self.defined_field_names:
            setattr(self, key, value)

update

update(
    *,
    extra: Literal["allow", "forbid", "ignore"] = "allow",
    ignore_null: bool = True,
    **kwargs: Any,
) -> None

Update the attributes of the instance based on the provided parameters.

PARAMETER DESCRIPTION
extra

Determines how to handle extra fields in kwargs.

TYPE: Literal['allow', 'forbid', 'ignore'] DEFAULT: 'allow'

ignore_null

If True, removes None values from kwargs.

TYPE: bool DEFAULT: True

**kwargs

Field names and values to be updated.

TYPE: Any DEFAULT: {}

Source code in src/soundscapy/plotting/param_models.py
@validate_call
def update(
    self,
    *,
    extra: Literal["allow", "forbid", "ignore"] = "allow",
    ignore_null: bool = True,
    **kwargs: Any,
) -> None:
    """
    Update the attributes of the instance based on the provided parameters.

    Parameters
    ----------
    extra
        Determines how to handle extra fields in `kwargs`.
    ignore_null
        If True, removes `None` values from `kwargs`.
    **kwargs
        Field names and values to be updated.

    """
    # Create a copy of kwargs to avoid modifying it during iteration
    update_kwargs = kwargs.copy()

    if extra == "forbid":
        # Forbid extra fields
        unknown_keys = set(update_kwargs) - set(self.defined_field_names)
        if unknown_keys:
            msg = f"Unknown parameters: {unknown_keys}"
            raise ValueError(msg)
    elif extra == "ignore":
        # Ignore extra fields
        update_kwargs = {
            k: v for k, v in update_kwargs.items() if k in self.defined_field_names
        }

    # Remove None values if ignore_null is True
    if ignore_null:
        update_kwargs = {k: v for k, v in update_kwargs.items() if v is not None}

    # Update fields
    for key, value in update_kwargs.items():
        if key in self.defined_field_names or extra == "allow":
            setattr(self, key, value)

get_defaults

get_defaults() -> dict[str, Any]

Get the default values for all defined fields in the model.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary mapping field names to their default values. Excludes the special _extra_fields field.

Source code in src/soundscapy/plotting/param_models.py
def get_defaults(self) -> dict[str, Any]:
    """
    Get the default values for all defined fields in the model.

    Returns
    -------
    :
        Dictionary mapping field names to their default values.
        Excludes the special `_extra_fields` field.

    """
    return {
        fld.name: fld.default for fld in fields(self) if fld.name != "_extra_fields"
    }

get

get(key: str, default: Any = None) -> Any

Get a parameter value with a default fallback.

PARAMETER DESCRIPTION
key

Name of the parameter

TYPE: str

default

Default value if parameter doesn't exist

TYPE: Any DEFAULT: None

RETURNS DESCRIPTION
Any

Parameter value or default

Source code in src/soundscapy/plotting/param_models.py
def get(self, key: str, default: Any = None) -> Any:
    """
    Get a parameter value with a default fallback.

    Parameters
    ----------
    key
        Name of the parameter
    default
        Default value if parameter doesn't exist

    Returns
    -------
    :
        Parameter value or default

    """
    if key in self.current_field_names:
        return getattr(self, key)
    return default

__getitem__

__getitem__(key: str) -> Any

Get a parameter value using dictionary-style access.

PARAMETER DESCRIPTION
key

Name of the parameter

TYPE: str

RETURNS DESCRIPTION
Any

Parameter value

RAISES DESCRIPTION
KeyError

If the parameter doesn't exist

Source code in src/soundscapy/plotting/param_models.py
def __getitem__(self, key: str) -> Any:
    """
    Get a parameter value using dictionary-style access.

    Parameters
    ----------
    key
        Name of the parameter

    Returns
    -------
    :
        Parameter value

    Raises
    ------
    KeyError
        If the parameter doesn't exist

    """
    if key in self.current_field_names:
        return getattr(self, key)
    msg = f"Parameter '{key}' does not exist."
    raise KeyError(msg)

as_dict

as_dict(drop: list[str] | None = None) -> dict[str, Any]

Get all parameters as a dictionary.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values

Source code in src/soundscapy/plotting/param_models.py
def as_dict(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Get all parameters as a dictionary.

    Returns
    -------
    :
        Dictionary of parameter values

    """
    dictionary = self.__dict__.copy()
    if drop is not None:
        for key in drop:
            dictionary.pop(key, None)
    return dictionary

copy

copy() -> ParamModel

Create a deep copy of the parameter model instance.

RETURNS DESCRIPTION
ParamModel

A deep copy of the current instance with all nested objects copied.

Source code in src/soundscapy/plotting/param_models.py
def copy(self) -> ParamModel:
    """
    Create a deep copy of the parameter model instance.

    Returns
    -------
    :
        A deep copy of the current instance with all nested objects copied.

    """
    return copy.deepcopy(self)

model_copy

model_copy() -> ParamModel

Create a copy of the parameter model instance.

Deprecated

This method is deprecated. Use :meth:copy instead. Kept only for backwards compatibility with Pydantic.

RETURNS DESCRIPTION
ParamModel

A deep copy of the current instance.

Source code in src/soundscapy/plotting/param_models.py
def model_copy(self) -> ParamModel:
    """
    Create a copy of the parameter model instance.

    !!! warning "Deprecated"
        This method is deprecated. Use :meth:`copy` instead.
        Kept only for backwards compatibility with Pydantic.

    Returns
    -------
    :
        A deep copy of the current instance.

    """
    warnings.warn(
        "model_copy is deprecated. Use copy instead."
        "Kept only for backwards compatibility with Pydantic.",
        DeprecationWarning,
        stacklevel=2,
    )
    return self.copy()

get_changed_params

get_changed_params() -> dict[str, Any]

Get parameters that have been changed from their defaults.

This method compares the current parameter values against the default values and returns a dictionary containing only the parameters that differ from their defaults.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of changed parameters and their current values.

Source code in src/soundscapy/plotting/param_models.py
def get_changed_params(self) -> dict[str, Any]:
    """
    Get parameters that have been changed from their defaults.

    This method compares the current parameter values against the default values
    and returns a dictionary containing only the parameters that differ from
    their defaults.

    Returns
    -------
    :
        Dictionary of changed parameters and their current values.

    """
    default_values = self.get_defaults()
    current_values = self.as_dict()

    # Use dictionary comprehension to identify and collect changed parameters
    # Return the current values (not default values) for the changed parameters
    return {
        param_name: current_values[param_name]
        for param_name, default_value in default_values.items()
        if current_values[param_name] != default_value
    }

get_multiple

get_multiple(keys: list[str]) -> dict[str, Any]

Get multiple parameters as a dictionary.

PARAMETER DESCRIPTION
keys

List of parameter names

TYPE: list[str]

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values

Source code in src/soundscapy/plotting/param_models.py
def get_multiple(self, keys: list[str]) -> dict[str, Any]:
    """
    Get multiple parameters as a dictionary.

    Parameters
    ----------
    keys
        List of parameter names

    Returns
    -------
    :
        Dictionary of parameter values

    """
    return {key: self[key] for key in keys if key in self.current_field_names}

pop

pop(key: str) -> Any

Remove a parameter and return its value.

For fields defined in the model, the value is reset to its default.

PARAMETER DESCRIPTION
key

Name of the parameter

TYPE: str

RETURNS DESCRIPTION
Any

Value of the removed parameter

RAISES DESCRIPTION
KeyError

If the parameter doesn't exist

Source code in src/soundscapy/plotting/param_models.py
def pop(self, key: str) -> Any:
    """
    Remove a parameter and return its value.

    For fields defined in the model, the value is reset to its default.

    Parameters
    ----------
    key
        Name of the parameter

    Returns
    -------
    :
        Value of the removed parameter

    Raises
    ------
    KeyError
        If the parameter doesn't exist

    """
    if key in self.defaults:
        value = getattr(self, key)
        setattr(self, key, self.defaults[key])  # Reset to default/None
        return value
    if key in self.current_field_names:
        value = self.get(key)
        delattr(self, key)
        return value
    msg = f"Parameter '{key}' does not exist."
    raise KeyError(msg)

drop

drop(
    keys: str | Iterable[str],
    *,
    ignore_missing: bool = True,
) -> None

Remove a parameter without returning its value.

PARAMETER DESCRIPTION
keys

Name of the parameter or list of parameters

TYPE: str | Iterable[str]

ignore_missing

If True, ignore missing keys. If False, raise KeyError for missing keys.

TYPE: bool DEFAULT: True

Source code in src/soundscapy/plotting/param_models.py
def drop(self, keys: str | Iterable[str], *, ignore_missing: bool = True) -> None:
    """
    Remove a parameter without returning its value.

    Parameters
    ----------
    keys
        Name of the parameter or list of parameters
    ignore_missing
        If True, ignore missing keys. If False, raise KeyError for missing keys.

    """
    if isinstance(keys, str):
        keys = [keys]

    for key in keys:
        try:
            delattr(self, key)
        except (KeyError, AttributeError) as e:
            if not ignore_missing:
                if isinstance(e, AttributeError):
                    msg = f"Parameter '{key}' does not exist."
                    raise KeyError(msg) from e
                raise

SeabornParams

Bases: ParamModel

Base parameters for seaborn plotting functions.

Provides common parameters used across seaborn plotting functions including data source, aesthetic mappings, and color settings.

METHOD DESCRIPTION
crosscheck_palette_hue

Check if the palette is valid for the given hue.

as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

crosscheck_palette_hue

crosscheck_palette_hue() -> None

Check if the palette is valid for the given hue.

This method ensures that palette is only used when hue is provided.

Source code in src/soundscapy/plotting/param_models.py
def crosscheck_palette_hue(self) -> None:
    """
    Check if the palette is valid for the given hue.

    This method ensures that palette is only used when hue is provided.
    """
    self.palette = self.palette if self.hue is not None else None

as_seaborn_kwargs

as_seaborn_kwargs(
    drop: list[str] | None = None,
) -> dict[str, Any]

Convert parameters to kwargs compatible with seaborn functions.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values suitable for seaborn plotting functions.

Source code in src/soundscapy/plotting/param_models.py
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    :
        Dictionary of parameter values suitable for seaborn plotting functions.

    """
    return self.as_dict(drop=drop)

ScatterParams

Bases: SeabornParams

Parameters for scatter plot functions.

Inherits from SeabornParams and adds scatter-specific parameters.

DensityParams

Bases: SeabornParams

Parameters for density plot functions.

Inherits from SeabornParams and adds density-specific parameters for contour plots and kernel density estimation.

METHOD DESCRIPTION
as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

to_outline

Convert to outline parameters.

as_seaborn_kwargs

as_seaborn_kwargs(
    drop: list[str] | None = None,
) -> dict[str, Any]

Convert parameters to kwargs compatible with seaborn functions.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values suitable for seaborn plotting functions.

Source code in src/soundscapy/plotting/param_models.py
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    :
        Dictionary of parameter values suitable for seaborn plotting functions.

    """
    # None to drop yet
    if drop is None:
        drop = []
    # Add common parameters to drop list
    drop.extend(["incl_outline"])
    return super().as_seaborn_kwargs(drop=drop)

to_outline

to_outline(
    *, alpha: float = 1, fill: bool = False
) -> DensityParams

Convert to outline parameters.

PARAMETER DESCRIPTION
alpha

Alpha value for the outline.

TYPE: float DEFAULT: 1

fill

Whether to fill the outline.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION
DensityParams

New instance with outline parameters.

Source code in src/soundscapy/plotting/param_models.py
def to_outline(self, *, alpha: float = 1, fill: bool = False) -> DensityParams:
    """
    Convert to outline parameters.

    Parameters
    ----------
    alpha
        Alpha value for the outline.
    fill
        Whether to fill the outline.

    Returns
    -------
    :
        New instance with outline parameters.

    """
    # Create a copy of the parameters
    params_dict = self.as_dict()

    # Update parameters for outline
    params_dict.update(alpha=alpha, fill=fill, legend=False)

    # Create a new instance with the updated parameters
    return DensityParams(**params_dict)

SimpleDensityParams

Bases: DensityParams

Parameters for simple density plot functions.

Inherits from DensityParams with overridden defaults for simplified density plots with fewer contour levels.

SPISeabornParams

Bases: SeabornParams

Base parameters for SPI (Soundscape Perceptual Index) seaborn plotting functions.

Specialized parameters for plotting SPI data with specific styling and annotation options.

METHOD DESCRIPTION
as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

as_seaborn_kwargs

as_seaborn_kwargs(
    drop: list[str] | None = None,
) -> dict[str, Any]

Convert parameters to kwargs compatible with seaborn functions.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of parameter values suitable for seaborn plotting functions.

Source code in src/soundscapy/plotting/param_models.py
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    :
        Dictionary of parameter values suitable for seaborn plotting functions.

    """
    droplist = ["n", "show_score", "axis_text_kw"]
    if isinstance(drop, list):
        droplist.extend(drop)
    return self.as_dict(drop=droplist)

SPISimpleDensityParams

Bases: SPISeabornParams, SimpleDensityParams

Parameters for SPI simple density plot functions.

Combines SPI-specific parameters with simple density plot parameters through multiple inheritance.

JointPlotParams

Bases: ParamModel

Parameters for joint plot functions.

Parameters for creating joint plots that show both the relationship between two variables and their individual distributions.

StyleParams

Bases: ParamModel

Parameters for plot styling.

Controls the visual appearance of plots including axes limits, labels, lines, and text formatting.

SubplotsParams

Bases: ParamModel

Parameters for subplots.

Controls the layout and configuration of subplot grids, including figure size, sharing of axes, and automatic allocation.

METHOD DESCRIPTION
as_plt_subplots_args

Pass matplotlib subplot arguments to a plt.subplots call.

ATTRIBUTE DESCRIPTION
n_subplots_by

"The number of subplots allocated for each subplot_by category.

TYPE: int

n_subplots

Get the number of subplots.

TYPE: int

n_subplots_by class-attribute instance-attribute

n_subplots_by: int = -1

"The number of subplots allocated for each subplot_by category.

n_subplots property

n_subplots: int

Get the number of subplots.

RETURNS DESCRIPTION
int

Number of subplots

as_plt_subplots_args

as_plt_subplots_args() -> dict[str, Any]

Pass matplotlib subplot arguments to a plt.subplots call.

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of subplot parameters.

Source code in src/soundscapy/plotting/param_models.py
def as_plt_subplots_args(self) -> dict[str, Any]:
    """
    Pass matplotlib subplot arguments to a plt.subplots call.

    Returns
    -------
    :
        Dictionary of subplot parameters.

    """
    kwargs = self.as_dict()
    for key in [
        "subplot_by",
        "n_subplots_by",
        "auto_allocate_axes",
        "adjust_figsize",
    ]:
        kwargs.pop(key, None)
    return kwargs