Skip to content

Parameter Models

This module provides parameter models for configuring various plotting functions in Soundscapy. These models help ensure type safety and provide a consistent interface for configuring plots.

CLASS DESCRIPTION
DensityParams

Parameters for density plot functions.

JointPlotParams

Parameters for joint plot functions.

ParamModel

Base model for parameter validation using dataclasses.

SPISeabornParams

Base parameters for SPI seaborn plotting functions.

SPISimpleDensityParams

Parameters for SPI simple density plot functions.

ScatterParams

Parameters for scatter plot functions.

SeabornParams

Base parameters for seaborn plotting functions.

SimpleDensityParams

Parameters for simple density plot functions.

StyleParams

Parameters for plot styling.

SubplotsParams

Parameters for subplots.

DensityParams

Bases: SeabornParams

Parameters for density plot functions.

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=None)

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 soundscapy/plotting/param_models.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    dict[str, Any]
        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=1, fill=False)

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 soundscapy/plotting/param_models.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def to_outline(self, *, alpha: float = 1, fill: bool = False) -> DensityParams:
    """
    Convert to outline parameters.

    Parameters
    ----------
    alpha : float, default=1
        Alpha value for the outline.
    fill : bool, default=False
        Whether to fill the outline.

    Returns
    -------
    DensityParams
        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)

JointPlotParams

Bases: ParamModel

Parameters for joint plot functions.

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
__getitem__

Get a parameter value using dictionary-style access.

__post_init__

Process extra fields after initialization.

as_dict

Get all parameters as a dictionary.

drop

Remove a parameter without returning its value.

get

Get a parameter value with a default fallback.

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.

update

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

ATTRIBUTE DESCRIPTION
current_field_names

Get the names of all current fields.

TYPE: list[str]

defined_field_names

Get the names of all fields defined for the model.

TYPE: list[str]

current_field_names property

current_field_names

Get the names of all current fields.

RETURNS DESCRIPTION
List[str]

List of field names

defined_field_names property

defined_field_names

Get the names of all fields defined for the model.

RETURNS DESCRIPTION
List[str]

List of field names

__getitem__

__getitem__(key)

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 soundscapy/plotting/param_models.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
def __getitem__(self, key: str) -> Any:
    """
    Get a parameter value using dictionary-style access.

    Parameters
    ----------
    key : str
        Name of the parameter

    Returns
    -------
    Any
        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)

__post_init__

__post_init__()

Process extra fields after initialization.

Source code in soundscapy/plotting/param_models.py
57
58
59
60
61
62
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)

as_dict

as_dict(drop=None)

Get all parameters as a dictionary.

RETURNS DESCRIPTION
Dict[str, Any]

Dictionary of parameter values

Source code in soundscapy/plotting/param_models.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def as_dict(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Get all parameters as a dictionary.

    Returns
    -------
    Dict[str, Any]
        Dictionary of parameter values

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

drop

drop(keys, *, ignore_missing=True)

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 soundscapy/plotting/param_models.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def drop(self, keys: str | Iterable[str], *, ignore_missing: bool = True) -> None:
    """
    Remove a parameter without returning its value.

    Parameters
    ----------
    keys : str | Iterable[str]
        Name of the parameter or list of parameters
    ignore_missing : bool, default=True
        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:  # noqa: PERF203
            if not ignore_missing:
                if isinstance(e, AttributeError):
                    msg = f"Parameter '{key}' does not exist."
                    raise KeyError(msg) from e
                raise

get

get(key, default=None)

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 soundscapy/plotting/param_models.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def get(self, key: str, default: Any = None) -> Any:
    """
    Get a parameter value with a default fallback.

    Parameters
    ----------
    key : str
        Name of the parameter
    default : Any, optional
        Default value if parameter doesn't exist

    Returns
    -------
    Any
        Parameter value or default

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

get_changed_params

get_changed_params()

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 parameters that differ from defaults, with keys as parameter names and values as their current values (not default values).

Source code in soundscapy/plotting/param_models.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
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
    -------
    dict[str, Any]
        Dictionary of parameters that differ from defaults, with keys as parameter names
        and values as their current values (not default 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)

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 soundscapy/plotting/param_models.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def get_multiple(self, keys: list[str]) -> dict[str, Any]:
    """
    Get multiple parameters as a dictionary.

    Parameters
    ----------
    keys : list[str]
        List of parameter names

    Returns
    -------
    Dict[str, Any]
        Dictionary of parameter values

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

pop

pop(key)

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 soundscapy/plotting/param_models.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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 : str
        Name of the parameter

    Returns
    -------
    Any
        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)

update

update(*, extra='allow', ignore_null=True, **kwargs)

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

PARAMETER DESCRIPTION
extra

Determines how to handle extra fields in kwargs.

TYPE: ('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 soundscapy/plotting/param_models.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@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 : {'allow', 'forbid', 'ignore'}, default='allow'
        Determines how to handle extra fields in `kwargs`.
    ignore_null : bool, default=True
        If True, removes `None` values from `kwargs`.
    **kwargs : Any
        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)

SPISeabornParams

Bases: SeabornParams

Base parameters for SPI seaborn plotting functions.

METHOD DESCRIPTION
as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

as_seaborn_kwargs

as_seaborn_kwargs(drop=None)

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 soundscapy/plotting/param_models.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    dict[str, Any]
        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.

ScatterParams

Bases: SeabornParams

Parameters for scatter plot functions.

SeabornParams

Bases: ParamModel

Base parameters for seaborn plotting functions.

METHOD DESCRIPTION
as_seaborn_kwargs

Convert parameters to kwargs compatible with seaborn functions.

crosscheck_palette_hue

Check if the palette is valid for the given hue.

as_seaborn_kwargs

as_seaborn_kwargs(drop=None)

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 soundscapy/plotting/param_models.py
345
346
347
348
349
350
351
352
353
354
355
def as_seaborn_kwargs(self, drop: list[str] | None = None) -> dict[str, Any]:
    """
    Convert parameters to kwargs compatible with seaborn functions.

    Returns
    -------
    dict[str, Any]
        Dictionary of parameter values suitable for seaborn plotting functions.

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

crosscheck_palette_hue

crosscheck_palette_hue()

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 soundscapy/plotting/param_models.py
337
338
339
340
341
342
343
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

SimpleDensityParams

Bases: DensityParams

Parameters for simple density plot functions.

StyleParams

Bases: ParamModel

Parameters for plot styling.

SubplotsParams

Bases: ParamModel

Parameters for subplots.

METHOD DESCRIPTION
as_plt_subplots_args

Pass matplotlib subplot arguments to a plt.subplots call.

ATTRIBUTE DESCRIPTION
n_subplots

Get the number of subplots.

TYPE: int

n_subplots_by

"The number of subplots allocated for each subplot_by category.

TYPE: int

n_subplots property

n_subplots

Get the number of subplots.

RETURNS DESCRIPTION
int

Number of subplots

n_subplots_by class-attribute instance-attribute

n_subplots_by = -1

"The number of subplots allocated for each subplot_by category.

as_plt_subplots_args

as_plt_subplots_args()

Pass matplotlib subplot arguments to a plt.subplots call.

PARAMETER DESCRIPTION
ax

Matplotlib Axes object.

TYPE: Any

RETURNS DESCRIPTION
dict[str, Any]

Dictionary of subplot parameters.

Source code in soundscapy/plotting/param_models.py
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def as_plt_subplots_args(self) -> dict[str, Any]:
    """
    Pass matplotlib subplot arguments to a plt.subplots call.

    Parameters
    ----------
    ax : Any
        Matplotlib Axes object.

    Returns
    -------
    dict[str, Any]
        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

show_submodules: true