Core functions
Soundscapy is a Python library for soundscape analysis and visualisation.
MODULE | DESCRIPTION |
---|---|
audio |
Provides tools for working with audio signals, particularly binaural recordings. |
data |
Soundscape data module. |
databases |
Soundscapy Databases Module. |
isd |
Module for handling the International Soundscape Database (ISD). |
iso_plot |
Main module for creating circumplex plots using different backends. |
likert |
Plotting functions for visualizing Likert scale data. |
msn |
Module for handling Multi-dimensional Skewed Normal (MSN) distributions. |
plotting |
Soundscapy Plotting Module. |
processing |
Soundscape survey data processing module. |
satp |
Module for handling the Soundscape Attributes Translation Project (SATP) database. |
spi |
Soundscapy Psychoacoustic Indicator (SPI) calculation module. |
sspylogging |
Logging configuration for Soundscapy. |
surveys |
Soundscapy Surveys Package. |
CLASS | DESCRIPTION |
---|---|
AnalysisSettings |
Settings for audio analysis methods. |
AudioAnalysis |
A class for performing psychoacoustic analysis on audio files. |
Binaural |
A class for processing and analyzing binaural audio signals. |
CentredParams |
Represents the centered parameters of a distribution. |
ConfigManager |
Manage configuration settings for audio analysis. |
DirectParams |
Represents a set of direct parameters for a statistical model. |
ISOPlot |
A class for creating circumplex plots using different backends. |
MultiSkewNorm |
A class representing a multi-dimensional skewed normal distribution. |
FUNCTION | DESCRIPTION |
---|---|
add_iso_coords |
Calculate and add ISO coordinates as new columns in the DataFrame. |
add_results |
Add results to MultiIndex dataframe. |
cp2dp |
Convert centred parameters to direct parameters. |
create_iso_subplots |
Create a set of subplots displaying data visualizations for soundscape analysis. |
density |
Plot a density plot of ISOCoordinates. |
disable_logging |
Disable all Soundscapy logging. |
dp2cp |
Convert direct parameters to centred parameters. |
enable_debug |
Quickly enable DEBUG level logging to console. |
get_logger |
Get the Soundscapy logger instance. |
jointplot |
Create a jointplot with a central distribution and marginal plots. |
paq_likert |
Create a Likert scale plot for PAQ (Perceived Affective Quality) data. |
paq_radar_plot |
Generate a radar/spider plot of PAQ values. |
parallel_process |
Process multiple binaural files in parallel. |
prep_multiindex_df |
Prepare a MultiIndex dataframe from a dictionary of results. |
process_all_metrics |
Process all metrics specified in the analysis settings for a binaural signal. |
rename_paqs |
Rename the PAQ columns in a DataFrame to standard PAQ IDs. |
scatter |
Plot ISOcoordinates as scatter points on a soundscape circumplex grid. |
setup_logging |
Set up logging for Soundscapy with sensible defaults. |
AnalysisSettings
Bases: BaseModel
Settings for audio analysis methods.
PARAMETER | DESCRIPTION |
---|---|
version
|
Version of the configuration.
TYPE:
|
AcousticToolbox
|
Settings for AcousticToolbox metrics.
TYPE:
|
MoSQITo
|
Settings for MoSQITo metrics.
TYPE:
|
scikit_maad
|
Settings for scikit-maad metrics.
TYPE:
|
METHOD | DESCRIPTION |
---|---|
default |
Create a default AnalysisSettings using the package default configuration file. |
from_dict |
Create an AnalysisSettings object from a dictionary. |
from_yaml |
Create an AnalysisSettings object from a YAML file. |
get_enabled_metrics |
Get a dictionary of enabled metrics. |
get_metric_settings |
Get the settings for a specific metric. |
to_yaml |
Save the current settings to a YAML file. |
update_setting |
Update the settings for a specific metric. |
validate_library_settings |
Validate library settings. |
default
classmethod
default()
Create a default AnalysisSettings using the package default configuration file.
RETURNS | DESCRIPTION |
---|---|
AnalysisSettings
|
An instance of AnalysisSettings with default settings. |
Source code in soundscapy/audio/analysis_settings.py
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
|
from_dict
classmethod
from_dict(d)
Create an AnalysisSettings object from a dictionary.
PARAMETER | DESCRIPTION |
---|---|
d
|
Dictionary containing the configuration settings.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
AnalysisSettings
|
An instance of AnalysisSettings. |
Source code in soundscapy/audio/analysis_settings.py
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
|
from_yaml
classmethod
from_yaml(filepath)
Create an AnalysisSettings object from a YAML file.
PARAMETER | DESCRIPTION |
---|---|
filepath
|
Path to the YAML configuration file. |
RETURNS | DESCRIPTION |
---|---|
AnalysisSettings
|
An instance of AnalysisSettings. |
Source code in soundscapy/audio/analysis_settings.py
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 |
|
get_enabled_metrics
get_enabled_metrics()
Get a dictionary of enabled metrics.
RETURNS | DESCRIPTION |
---|---|
dict[str, dict[str, MetricSettings]]
|
A dictionary of enabled metrics grouped by library. |
Source code in soundscapy/audio/analysis_settings.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
|
get_metric_settings
get_metric_settings(library, metric)
Get the settings for a specific metric.
PARAMETER | DESCRIPTION |
---|---|
library
|
The name of the library.
TYPE:
|
metric
|
The name of the metric.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
MetricSettings
|
The settings for the specified metric. |
RAISES | DESCRIPTION |
---|---|
KeyError
|
If the specified library or metric is not found. |
Source code in soundscapy/audio/analysis_settings.py
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 |
|
to_yaml
to_yaml(filepath)
Save the current settings to a YAML file.
PARAMETER | DESCRIPTION |
---|---|
filepath
|
Path to save the YAML file. |
Source code in soundscapy/audio/analysis_settings.py
206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
|
update_setting
update_setting(library, metric, **kwargs)
Update the settings for a specific metric.
PARAMETER | DESCRIPTION |
---|---|
library
|
The name of the library.
TYPE:
|
metric
|
The name of the metric.
TYPE:
|
**kwargs
|
Keyword arguments to update the metric settings.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
KeyError
|
If the specified library or metric is not found. |
Source code in soundscapy/audio/analysis_settings.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
validate_library_settings
classmethod
validate_library_settings(v)
Validate library settings.
Source code in soundscapy/audio/analysis_settings.py
140 141 142 143 144 145 146 |
|
AudioAnalysis
AudioAnalysis(config_path=None)
A class for performing psychoacoustic analysis on audio files.
This class provides methods to analyze single audio files or entire folders of audio files using parallel processing. It handles configuration management, calibration, and saving of analysis results.
ATTRIBUTE | DESCRIPTION |
---|---|
config_manager |
Manages the configuration settings for audio analysis
TYPE:
|
settings |
The current configuration settings
TYPE:
|
METHOD | DESCRIPTION |
---|---|
analyze_file |
Analyze a single audio file |
analyze_folder |
Analyze all audio files in a folder using parallel processing |
save_results |
Save analysis results to a file |
update_config |
Update the current configuration |
save_config |
Save the current configuration to a file |
Initialize the AudioAnalysis with a configuration.
PARAMETER | DESCRIPTION |
---|---|
config_path
|
Path to the configuration file. If None, uses default configuration.
TYPE:
|
Source code in soundscapy/audio/audio_analysis.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
analyze_file
analyze_file(file_path, calibration_levels=None, resample=None)
Analyze a single audio file using the current configuration.
PARAMETER | DESCRIPTION |
---|---|
resample
|
TYPE:
|
file_path
|
Path to the audio file to analyze. |
calibration_levels
|
Dictionary containing calibration levels for left and right channels.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
DataFrame containing the analysis results. |
Source code in soundscapy/audio/audio_analysis.py
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 |
|
analyze_folder
analyze_folder(folder_path, calibration_file=None, max_workers=None, resample=None)
Analyze all audio files in a folder using parallel processing.
PARAMETER | DESCRIPTION |
---|---|
resample
|
TYPE:
|
folder_path
|
Path to the folder containing audio files. |
calibration_file
|
Path to a JSON file containing calibration levels for each audio file. |
max_workers
|
Maximum number of worker processes to use. If None, it will use the number of CPU cores.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
DataFrame containing the analysis results for all files. |
Source code in soundscapy/audio/audio_analysis.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
|
save_config
save_config(config_path)
Save the current configuration to a file.
PARAMETER | DESCRIPTION |
---|---|
config_path
|
Path to save the configuration file. |
Source code in soundscapy/audio/audio_analysis.py
213 214 215 216 217 218 219 220 221 222 223 224 |
|
save_results
save_results(results, output_path)
Save analysis results to a file.
PARAMETER | DESCRIPTION |
---|---|
results
|
DataFrame containing the analysis results.
TYPE:
|
output_path
|
Path to save the results file. |
Source code in soundscapy/audio/audio_analysis.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
|
update_config
update_config(new_config)
Update the current configuration.
PARAMETER | DESCRIPTION |
---|---|
new_config
|
Dictionary containing the new configuration settings.
TYPE:
|
Source code in soundscapy/audio/audio_analysis.py
199 200 201 202 203 204 205 206 207 208 209 210 211 |
|
Binaural
Bases: Signal
A class for processing and analyzing binaural audio signals.
This class extends the Signal class from the acoustic_toolbox library to provide specialized functionality for binaural recordings. It supports various psychoacoustic metrics and analysis techniques using libraries such as mosqito, maad, and acoustic_toolbox.
ATTRIBUTE | DESCRIPTION |
---|---|
fs |
Sampling frequency of the signal.
TYPE:
|
recording |
Name or identifier of the recording.
TYPE:
|
Notes
This class only supports 2-channel (stereo) audio signals.
METHOD | DESCRIPTION |
---|---|
__array_finalize__ |
Finalize the new Binaural object. |
__new__ |
Create a new Binaural object. |
acoustics_metric |
Run a metric from the acoustic_toolbox library. |
calibrate_to |
Calibrate the binaural signal to predefined Leq/dB levels. |
from_wav |
Load a wav file and return a Binaural object. |
fs_resample |
Resample the signal to a new sampling frequency. |
maad_metric |
Run a metric from the scikit-maad library. |
mosqito_metric |
Run a metric from the mosqito library. |
process_all_metrics |
Process all metrics specified in the analysis settings. |
pyacoustics_metric |
Run a metric from the pyacoustics library (deprecated). |
__array_finalize__
__array_finalize__(obj)
Finalize the new Binaural object.
This method is called for all new Binaural objects.
PARAMETER | DESCRIPTION |
---|---|
obj
|
The object from which the new object was created.
TYPE:
|
Source code in soundscapy/audio/binaural.py
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
|
__new__
__new__(data, fs, recording='Rec')
Create a new Binaural object.
PARAMETER | DESCRIPTION |
---|---|
data
|
The audio data.
TYPE:
|
fs
|
Sampling frequency of the signal.
TYPE:
|
recording
|
Name or identifier of the recording. Default is "Rec".
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Binaural
|
A new Binaural object. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the input signal is not 2-channel. |
Source code in soundscapy/audio/binaural.py
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 108 109 110 111 112 113 |
|
acoustics_metric
acoustics_metric(metric, statistics=(5, 10, 50, 90, 95, 'avg', 'max', 'min', 'kurt', 'skew'), label=None, channel=('Left', 'Right'), metric_settings=None, func_args=None, *, as_df=True, return_time_series=False)
Run a metric from the acoustic_toolbox library.
PARAMETER | DESCRIPTION |
---|---|
metric
|
The metric to run.
TYPE:
|
statistics
|
List of level statistics to calculate (e.g. L_5, L_90, etc.). Default is (5, 10, 50, 90, 95, "avg", "max", "min", "kurt", "skew").
TYPE:
|
label
|
Label to use for the metric. If None, will pull from default label for that metric.
TYPE:
|
channel
|
Which channels to process. Default is ("Left", "Right").
TYPE:
|
as_df
|
Whether to return a dataframe or not. Default is True. If True, returns a MultiIndex Dataframe with ("Recording", "Channel") as the index.
TYPE:
|
return_time_series
|
Whether to return the time series of the metric. Default is False. Cannot return time series if as_df is True.
TYPE:
|
metric_settings
|
Settings for metric analysis. Default is None.
TYPE:
|
func_args
|
Any settings given here will override those in the other options. Can pass any args or *kwargs to the underlying acoustic_toolbox method.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict or DataFrame
|
Dictionary of results if as_df is False, otherwise a pandas DataFrame. |
See Also
metrics.acoustics_metric acoustic_toolbox.standards_iso_tr_25417_2007.equivalent_sound_pressure_level : Base method for Leq calculation. acoustic_toolbox.standards.iec_61672_1_2013.sound_exposure_level : Base method for SEL calculation. acoustic_toolbox.standards.iec_61672_1_2013.time_weighted_sound_level : Base method for Leq level time series calculation.
Source code in soundscapy/audio/binaural.py
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
|
calibrate_to
calibrate_to(decibel, inplace=False)
Calibrate the binaural signal to predefined Leq/dB levels.
This method allows calibration of both channels either to the same level or to different levels for each channel.
PARAMETER | DESCRIPTION |
---|---|
decibel
|
Target calibration value(s) in dB (Leq). If a single value is provided, both channels will be calibrated to this level. If two values are provided, they will be applied to the left and right channels respectively. |
inplace
|
If True, modify the signal in place. If False, return a new calibrated signal. Default is False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Binaural
|
Calibrated Binaural signal. If inplace is True, returns self. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If decibel is not a float, or a list/tuple of two floats. |
Examples:
>>> # xdoctest: +SKIP
>>> signal = Binaural.from_wav("audio.wav")
>>> # Calibrate left channel to 60 dB and right to 62 dB
>>> calibrated_signal = signal.calibrate_to([60, 62])
Source code in soundscapy/audio/binaural.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
|
from_wav
classmethod
from_wav(filename, normalize=False, calibrate_to=None, resample=None, recording=None)
Load a wav file and return a Binaural object.
Overrides the Signal.from_wav method to return a Binaural object instead of a Signal object.
PARAMETER | DESCRIPTION |
---|---|
filename
|
Filename of wav file to load. |
calibrate_to
|
Value(s) to calibrate to in dB (Leq). Can also handle np.ndarray and pd.Series of length 2. If only one value is passed, will calibrate both channels to the same value.
TYPE:
|
normalize
|
Whether to normalize the signal. Default is False.
TYPE:
|
resample
|
New sampling frequency to resample the signal to. Default is None
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Binaural
|
Binaural signal object of wav recording. |
See Also
acoustic_toolbox.Signal.from_wav : Base method for loading wav files.
Source code in soundscapy/audio/binaural.py
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 |
|
fs_resample
fs_resample(fs, original_fs=None)
Resample the signal to a new sampling frequency.
PARAMETER | DESCRIPTION |
---|---|
fs
|
New sampling frequency.
TYPE:
|
original_fs
|
Original sampling frequency.
If None, it will be inferred from the signal (
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Binaural
|
Resampled Binaural signal. If inplace is True, returns self. |
See Also
acoustic_toolbox.Signal.resample : Base method for resampling signals.
Source code in soundscapy/audio/binaural.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
|
maad_metric
maad_metric(metric, channel=('Left', 'Right'), as_df=True, metric_settings=None, func_args={})
Run a metric from the scikit-maad library.
Currently only supports running all of the alpha indices at once.
PARAMETER | DESCRIPTION |
---|---|
metric
|
The metric to run.
TYPE:
|
channel
|
Which channels to process. Default is ("Left", "Right"). |
as_df
|
Whether to return a dataframe or not. Default is True. If True, returns a MultiIndex Dataframe with ("Recording", "Channel") as the index.
TYPE:
|
metric_settings
|
Settings for metric analysis. Default is None.
TYPE:
|
func_args
|
Additional arguments to pass to the underlying scikit-maad method.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict or DataFrame
|
Dictionary of results if as_df is False, otherwise a pandas DataFrame. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If metric name is not recognised. |
See Also
metrics.maad_metric_1ch metrics.maad_metric_2ch
Source code in soundscapy/audio/binaural.py
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 |
|
mosqito_metric
mosqito_metric(metric, statistics=(5, 10, 50, 90, 95, 'avg', 'max', 'min', 'kurt', 'skew'), label=None, channel=('Left', 'Right'), as_df=True, return_time_series=False, parallel=True, metric_settings=None, func_args={})
Run a metric from the mosqito library.
PARAMETER | DESCRIPTION |
---|---|
metric
|
Metric to run from mosqito library.
TYPE:
|
statistics
|
List of level statistics to calculate (e.g. L_5, L_90, etc.). Default is (5, 10, 50, 90, 95, "avg", "max", "min", "kurt", "skew").
TYPE:
|
label
|
Label to use for the metric. If None, will pull from default label for that metric.
TYPE:
|
channel
|
Which channels to process. Default is ("Left", "Right").
TYPE:
|
as_df
|
Whether to return a dataframe or not. Default is True. If True, returns a MultiIndex Dataframe with ("Recording", "Channel") as the index.
TYPE:
|
return_time_series
|
Whether to return the time series of the metric. Default is False. Cannot return time series if as_df is True.
TYPE:
|
parallel
|
Whether to run the channels in parallel. Default is True. If False, will run each channel sequentially.
TYPE:
|
metric_settings
|
Settings for metric analysis. Default is None.
TYPE:
|
func_args
|
Any settings given here will override those in the other options. Can pass any args or *kwargs to the underlying acoustic_toolbox method.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict or DataFrame
|
Dictionary of results if as_df is False, otherwise a pandas DataFrame. |
See Also
binaural.mosqito_metric_2ch : Method for running metrics on 2 channels. binaural.mosqito_metric_1ch : Method for running metrics on 1 channel.
Source code in soundscapy/audio/binaural.py
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 |
|
process_all_metrics
process_all_metrics(analysis_settings=AnalysisSettings.default(), parallel=True)
Process all metrics specified in the analysis settings.
This method runs all enabled metrics from the provided AnalysisSettings object and compiles the results into a single DataFrame.
PARAMETER | DESCRIPTION |
---|---|
analysis_settings
|
Configuration object specifying which metrics to run and their parameters.
TYPE:
|
parallel
|
Whether to run calculations in parallel where possible. Default is True.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
A MultiIndex DataFrame containing the results of all processed metrics. The index includes "Recording" and "Channel" levels. |
Notes
The parallel option primarily affects the MoSQITo metrics. Other metrics may not benefit from parallelization.
TODO: Provide default settings to analysis_settings to make it optional.
Examples:
>>> # xdoctest: +SKIP
>>> signal = Binaural.from_wav("audio.wav")
>>> settings = AnalysisSettings.from_yaml("settings.yaml")
>>> results = signal.process_all_metrics(settings)
Source code in soundscapy/audio/binaural.py
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
|
pyacoustics_metric
pyacoustics_metric(metric, statistics=(5, 10, 50, 90, 95, 'avg', 'max', 'min', 'kurt', 'skew'), label=None, channel=('Left', 'Right'), as_df=True, return_time_series=False, metric_settings=None, func_args=None)
Run a metric from the pyacoustics library (deprecated).
This method has been deprecated. Use acoustics_metric
instead.
All parameters are passed directly to acoustics_metric
.
PARAMETER | DESCRIPTION |
---|---|
metric
|
The metric to run.
TYPE:
|
statistics
|
List of level statistics to calculate (e.g. L_5, L_90, etc.). Default is (5, 10, 50, 90, 95, "avg", "max", "min", "kurt", "skew").
TYPE:
|
label
|
Label to use for the metric. If None, will pull from default label for that metric.
TYPE:
|
channel
|
Which channels to process. Default is ("Left", "Right").
TYPE:
|
as_df
|
Whether to return a dataframe or not. Default is True. If True, returns a MultiIndex Dataframe with ("Recording", "Channel") as the index.
TYPE:
|
return_time_series
|
Whether to return the time series of the metric. Default is False. Cannot return time series if as_df is True.
TYPE:
|
metric_settings
|
Settings for metric analysis. Default is None.
TYPE:
|
func_args
|
Any settings given here will override those in the other options. Can pass any args or *kwargs to the underlying acoustic_toolbox method.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict or DataFrame
|
Results of the metric calculation. |
See Also
Binaural.acoustics_metric
Source code in soundscapy/audio/binaural.py
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 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 423 424 425 426 427 428 429 430 |
|
CentredParams
CentredParams(mean, sigma, skew)
Represents the centered parameters of a distribution.
PARAMETER | DESCRIPTION |
---|---|
mean
|
The mean of the distribution.
TYPE:
|
sigma
|
The standard deviation of the distribution.
TYPE:
|
skew
|
The skewness of the distribution.
TYPE:
|
ATTRIBUTE | DESCRIPTION |
---|---|
mean |
The mean of the distribution.
TYPE:
|
sigma |
The standard deviation of the distribution.
TYPE:
|
skew |
The skewness of the distribution.
TYPE:
|
METHOD | DESCRIPTION |
---|---|
from_dp |
Converts DirectParams object to CentredParams object. |
Initialize CentredParams instance.
Source code in soundscapy/spi/msn.py
161 162 163 164 165 |
|
__repr__
__repr__()
Return a string representation of the CentredParams object.
Source code in soundscapy/spi/msn.py
167 168 169 |
|
__str__
__str__()
Return a user-friendly string representation of the CentredParams object.
Source code in soundscapy/spi/msn.py
171 172 173 174 175 176 177 178 |
|
from_dp
classmethod
from_dp(dp)
Convert a DirectParams object to a CentredParams object.
PARAMETER | DESCRIPTION |
---|---|
dp
|
The DirectParams object to convert.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
CentredParams
|
A new CentredParams object with the converted parameters. |
Source code in soundscapy/spi/msn.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
|
ConfigManager
ConfigManager(config_path=None)
Manage configuration settings for audio analysis.
PARAMETER | DESCRIPTION |
---|---|
default_config_path
|
Path to the default configuration file. |
METHOD | DESCRIPTION |
---|---|
generate_minimal_config |
Generate a minimal configuration containing only changes from the default. |
load_config |
Load a configuration file or use the default configuration. |
merge_configs |
Merge the current config with override values and update the current_config. |
save_config |
Save the current configuration to a file. |
Source code in soundscapy/audio/analysis_settings.py
316 317 318 |
|
generate_minimal_config
generate_minimal_config()
Generate a minimal configuration containing only changes from the default.
RETURNS | DESCRIPTION |
---|---|
dict
|
A dictionary containing the minimal configuration. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If no current configuration is loaded. |
Source code in soundscapy/audio/analysis_settings.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 |
|
load_config
load_config(config_path=None)
Load a configuration file or use the default configuration.
PARAMETER | DESCRIPTION |
---|---|
config_path
|
Path to the configuration file. If None, uses the default configuration. |
RETURNS | DESCRIPTION |
---|---|
AnalysisSettings
|
The loaded configuration. |
Source code in soundscapy/audio/analysis_settings.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
|
merge_configs
merge_configs(override_config)
Merge the current config with override values and update the current_config.
PARAMETER | DESCRIPTION |
---|---|
override_config
|
Dictionary containing override configuration values.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
AnalysisSettings
|
The merged configuration. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If no base configuration is loaded. |
Source code in soundscapy/audio/analysis_settings.py
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 |
|
save_config
save_config(filepath)
Save the current configuration to a file.
PARAMETER | DESCRIPTION |
---|---|
filepath
|
Path to save the configuration file. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If no current configuration is loaded. |
Source code in soundscapy/audio/analysis_settings.py
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 |
|
DirectParams
DirectParams(xi, omega, alpha)
Represents a set of direct parameters for a statistical model.
Direct parameters are the parameters that are directly used in the model. They are the parameters that are used to define the distribution of the data. In the case of a skew normal distribution, the direct parameters are the xi, omega, and alpha values.
PARAMETER | DESCRIPTION |
---|---|
xi
|
The location of the distribution in 2D space, represented as a 2x1 array with the x and y coordinates.
TYPE:
|
omega
|
The covariance matrix of the distribution, represented as a 2x2 array. The covariance matrix represents the measure of the relationship between different variables. It provides information about how changes in one variable are associated with changes in other variables.
TYPE:
|
alpha
|
The shape parameters for the x and y dimensions, controlling the shape (skewness) of the distribution. It is represented as a 2x1 array.
TYPE:
|
Initialize DirectParams instance.
METHOD | DESCRIPTION |
---|---|
__repr__ |
Return a string representation of the DirectParams object. |
__str__ |
Return a user-friendly string representation of the DirectParams object. |
from_cp |
Convert a CentredParams object to a DirectParams object. |
validate |
Validate the direct parameters. |
Source code in soundscapy/spi/msn.py
48 49 50 51 52 53 |
|
__repr__
__repr__()
Return a string representation of the DirectParams object.
Source code in soundscapy/spi/msn.py
55 56 57 |
|
__str__
__str__()
Return a user-friendly string representation of the DirectParams object.
Source code in soundscapy/spi/msn.py
59 60 61 62 63 64 65 66 |
|
from_cp
classmethod
from_cp(cp)
Convert a CentredParams object to a DirectParams object.
PARAMETER | DESCRIPTION |
---|---|
cp
|
The CentredParams object to convert.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DirectParams
|
A new DirectParams object with the converted parameters. |
Source code in soundscapy/spi/msn.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
validate
validate()
Validate the direct parameters.
In a skew normal distribution, the covariance matrix, often denoted as Ω (Omega), represents the measure of the relationship between different variables. It provides information about how changes in one variable are associated with changes in other variables. The covariance matrix must be positive definite and symmetric.
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the direct parameters are not valid. |
RETURNS | DESCRIPTION |
---|---|
None
|
|
Source code in soundscapy/spi/msn.py
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 |
|
ISOPlot
ISOPlot(data=None, x='ISOPleasant', y='ISOEventful', title='Soundscape Density Plot', hue=None, palette='colorblind', figure=None, axes=None)
A class for creating circumplex plots using different backends.
This class provides methods for creating scatter plots and density plots based on the circumplex model of soundscape perception.
Examples:
>>> from soundscapy import isd, surveys
>>> df = isd.load()
>>> df = surveys.add_iso_coords(df)
>>> ct = isd.select_location_ids(df, ["CamdenTown", "RegentsParkJapan"])
>>> cp = (ISOPlot(ct, hue="LocationID")
... .create_subplots()
... .add_scatter()
... .add_density()
... .style())
>>> cp.show() # xdoctest: +SKIP
Initialize a ISOPlot instance.
PARAMETER | DESCRIPTION |
---|---|
data
|
The data to be plotted, by default None
TYPE:
|
x
|
Column name or data for x-axis, by default "ISOPleasant"
TYPE:
|
y
|
Column name or data for y-axis, by default "ISOEventful"
TYPE:
|
title
|
Title of the plot, by default "Soundscape Density Plot"
TYPE:
|
hue
|
Column name for color encoding, by default None
TYPE:
|
palette
|
Color palette to use, by default "colorblind"
TYPE:
|
figure
|
Existing figure to plot on, by default None
TYPE:
|
axes
|
Existing axes to plot on, by default None
TYPE:
|
Examples:
Create a plot with default parameters:
>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
... rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... columns=['ISOPleasant', 'ISOEventful']
... )
>>> plot = ISOPlot()
>>> isinstance(plot, ISOPlot)
True
Create a plot with a DataFrame:
>>> data = pd.DataFrame(
... np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... rng.integers(1, 3, 100)],
... columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = ISOPlot(data=data, hue='Group')
>>> plot.hue
'Group'
Create a plot directly with arrays:
>>> x, y = rng.multivariate_normal([0, 0], [[1, 0], [0, 1]], 100).T
>>> plot = ISOPlot(x=x, y=y)
>>> isinstance(plot, ISOPlot)
True
METHOD | DESCRIPTION |
---|---|
add_annotation |
Add an annotation to the plot. |
add_density |
Add a density layer to specific subplot(s). |
add_layer |
Add a visualization layer, optionally targeting specific subplot(s). |
add_scatter |
Add a scatter layer to specific subplot(s). |
add_simple_density |
Add a simple density layer to specific subplot(s). |
add_spi |
Add a SPI layer to specific subplot(s). |
close |
Close the figure. |
create_subplots |
Create subplots for the circumplex plot. |
get_axes |
Get the axes object. |
get_figure |
Get the figure object. |
get_single_axes |
Get a specific axes object. |
savefig |
Save the figure. |
show |
Show the figure. |
style |
Apply styling to the plot. |
yield_axes_objects |
Generate a sequence of axes objects to iterate over. |
ATTRIBUTE | DESCRIPTION |
---|---|
hue |
Get the hue column name.
TYPE:
|
title |
Get the plot title.
TYPE:
|
x |
Get the x-axis column name.
TYPE:
|
y |
Get the y-axis column name.
TYPE:
|
Source code in soundscapy/plotting/iso_plot.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 |
|
hue
property
hue
Get the hue column name.
title
property
title
Get the plot title.
x
property
x
Get the x-axis column name.
y
property
y
Get the y-axis column name.
add_annotation
add_annotation(text, xy, xytext, arrowprops=None)
Add an annotation to the plot.
PARAMETER | DESCRIPTION |
---|---|
text
|
The text to display in the annotation.
TYPE:
|
xy
|
The point to annotate. |
xytext
|
The point at which to place the text. |
arrowprops
|
Properties for the arrow connecting the annotation text to the point. |
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Source code in soundscapy/plotting/iso_plot.py
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 |
|
add_density
add_density(on_axis=None, data=None, *, include_outline=False, **params)
Add a density layer to specific subplot(s).
PARAMETER | DESCRIPTION |
---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
data
|
Custom data for this specific density plot
TYPE:
|
include_outline
|
Whether to include an outline around the density plot, by default False
TYPE:
|
**params
|
Parameters for the density plot
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Add a density layer to all subplots:
>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame({
... 'ISOPleasant': rng.normal(0.2, 0.25, 50),
... 'ISOEventful': rng.normal(0.15, 0.4, 50),
... })
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_density()
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> plot.close() # Clean up
Add a density layer with custom settings:
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_density(levels=5, alpha=0.7)
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> plot.close() # Clean up
Source code in soundscapy/plotting/iso_plot.py
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 |
|
add_layer
add_layer(layer_class, data=None, *, on_axis=None, **params)
Add a visualization layer, optionally targeting specific subplot(s).
PARAMETER | DESCRIPTION |
---|---|
layer_class
|
The type of layer to add
TYPE:
|
on_axis
|
Target specific axis/axes: - int: Index of subplot (flattened) - tuple: (row, col) coordinates - list: Multiple indices to apply the layer to - None: Apply to all subplots (default)
TYPE:
|
data
|
Custom data for this specific layer, overriding context data
TYPE:
|
**params
|
Parameters for the layer
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Add a scatter layer to all subplots:
>>> import pandas as pd
>>> import numpy as np
>>> from soundscapy.plotting.layers import ScatterLayer
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
... np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... rng.integers(1, 3, 100)],
... columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> # Will create 2x2 subplots all with the same data
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=2, ncols=2)
... .add_layer(ScatterLayer)
... .style())
>>> plot.show() # xdoctest: +SKIP
>>> all(len(ctx.layers) == 1 for ctx in plot.subplot_contexts)
True
>>> plot.close() # Clean up
Add a layer to a specific subplot:
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=2, ncols=2)
... .add_layer(ScatterLayer, on_axis=0)
... .style())
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> all(len(ctx.layers) == 0 for ctx in plot.subplot_contexts[1:])
True
>>> plot.close()
Add a layer to multiple subplots:
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=2, ncols=2)
... .add_layer(ScatterLayer, on_axis=[0, 2])
... .style())
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 1
True
>>> len(plot.subplot_contexts[2].layers) == 1
True
>>> len(plot.subplot_contexts[1].layers) == 0
True
>>> plot.close()
Add a layer with custom data to a specific subplot:
>>> custom_data = pd.DataFrame({
... 'ISOPleasant': rng.normal(0.2, 0.1, 50),
... 'ISOEventful': rng.normal(0.15, 0.2, 50),
... })
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=2, ncols=2)
... .add_layer(ScatterLayer) # Add to all subplots
... # Add a layer with custom data to the first subplot
... .add_layer(ScatterLayer, data=data.iloc[:50], on_axis=0, color='red')
... # Add a layer with custom data to the second subplot
... .add_layer(ScatterLayer, data=custom_data, on_axis=1)
... .style())
>>> plot.show() # xdoctest: +SKIP
>>> plot.close()
Source code in soundscapy/plotting/iso_plot.py
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 |
|
add_scatter
add_scatter(data=None, *, on_axis=None, **params)
Add a scatter layer to specific subplot(s).
PARAMETER | DESCRIPTION |
---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
data
|
Custom data for this specific scatter plot
TYPE:
|
**params
|
Parameters for the scatter plot
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Add a scatter layer to all subplots:
>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
... np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... rng.integers(1, 3, 100)],
... columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=2, ncols=1)
... .add_scatter(s=50, alpha=0.7, hue='Group')
... .style())
>>> plot.show() # xdoctest: +SKIP
>>> all(len(ctx.layers) == 1 for ctx in plot.subplot_contexts)
True
>>> plot.close() # Clean up
Add a scatter layer with custom data to a specific subplot:
>>> custom_data = pd.DataFrame({
... 'ISOPleasant': rng.normal(0.2, 0.1, 50),
... 'ISOEventful': rng.normal(0.15, 0.2, 50),
... })
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=2, ncols=1)
... .add_scatter(hue='Group')
... .add_scatter(on_axis=0, data=custom_data, color='red')
... .style())
>>> plot.show() # xdoctest: +SKIP
>>> plot.subplot_contexts[0].layers[1].custom_data is custom_data
True
>>> plot.close() # Clean up
Source code in soundscapy/plotting/iso_plot.py
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 |
|
add_simple_density
add_simple_density(on_axis=None, data=None, *, include_outline=True, **params)
Add a simple density layer to specific subplot(s).
PARAMETER | DESCRIPTION |
---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
data
|
Custom data for this specific density plot
TYPE:
|
thresh
|
Threshold for density contours, by default 0.5
TYPE:
|
levels
|
Contour levels, by default 2 |
alpha
|
Transparency level, by default 0.5
TYPE:
|
include_outline
|
Whether to include an outline around the density plot, by default True
TYPE:
|
**params
|
Additional parameters for the density plot
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Add a simple density layer:
>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame({
... 'ISOPleasant': rng.normal(0.2, 0.25, 30),
... 'ISOEventful': rng.normal(0.15, 0.4, 30),
... })
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_scatter()
... .add_simple_density()
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close() # Clean up
Add a simple density with splitting by group:
>>> data = pd.DataFrame(
... np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... rng.integers(1, 3, 100)],
... columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = (
... ISOPlot(data=data, hue='Group')
... .create_subplots()
... .add_scatter()
... .add_simple_density()
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close()
...
Source code in soundscapy/plotting/iso_plot.py
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 |
|
add_spi
add_spi(on_axis=None, spi_target_data=None, msn_params=None, *, layer_class=SPISimpleLayer, **params)
Add a SPI layer to specific subplot(s).
PARAMETER | DESCRIPTION |
---|---|
on_axis
|
Target specific axis/axes
TYPE:
|
spi_target_data
|
Custom data for this specific SPI plot
TYPE:
|
msn_params
|
Parameters for the SPI plot
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Add a SPI layer to all subplots:
>>> import pandas as pd
>>> import numpy as np
>>> from soundscapy.spi import DirectParams
>>> rng = np.random.default_rng(42)
>>> # Create a DataFrame with random data
>>> data = pd.DataFrame(
... rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... columns=['ISOPleasant', 'ISOEventful']
... )
>>> # Define MSN parameters for the SPI target
>>> msn_params = DirectParams(
... xi=np.array([0.5, 0.7]),
... omega=np.array([[0.1, 0.05], [0.05, 0.1]]),
... alpha=np.array([0, -5]),
... )
>>> # Create the plot with only an SPI layer
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_scatter()
... .add_spi(msn_params=msn_params)
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 2
True
>>> plot.close() # Clean up
Add an SPI layer over top of 'real' data:
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_scatter()
... .add_density()
... .add_spi(msn_params=msn_params, show_score="on axis")
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> len(plot.subplot_contexts[0].layers) == 3
True
Add a SPI layer from spi data:
>>> # Create a custom distribution
>>> from soundscapy.spi import MultiSkewNorm
>>> import soundscapy as sspy
>>> spi_msn = MultiSkewNorm.from_params(msn_params)
>>> # Generate random samples
>>> spi_msn.sample(1000)
>>> data = sspy.add_iso_coords(sspy.isd.load())
>>> data = sspy.isd.select_location_ids(
... data,
... ['CamdenTown', 'PancrasLock', 'RussellSq', 'RegentsParkJapan']
... )
>>> mp3 = (
... ISOPlot(
... data=data,
... title="Soundscape Density Plots with corrected ISO coordinates",
... hue="SessionID",
... )
... .create_subplots(
... subplot_by="LocationID",
... figsize=(4, 4),
... auto_allocate_axes=True,
... )
... .add_scatter()
... .add_simple_density(fill=False)
... .add_spi(spi_target_data=spi_msn.sample_data, show_score="under title")
... .style()
... )
>>> mp3.show() # xdoctest: +SKIP
>>> plot.close() # Clean up
BUG: This last doctest doesn't show the spi score under the title
Source code in soundscapy/plotting/iso_plot.py
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 |
|
close
close(fig=None)
Close the figure.
This method is a wrapper around plt.close() to close the figure.
Source code in soundscapy/plotting/iso_plot.py
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
|
create_subplots
create_subplots(nrows=1, ncols=1, figsize=(5, 5), subplot_by=None, subplot_datas=None, subplot_titles=None, *, adjust_figsize=True, auto_allocate_axes=False, **kwargs)
Create subplots for the circumplex plot.
PARAMETER | DESCRIPTION |
---|---|
nrows
|
Number of rows in the subplot grid, by default 1
TYPE:
|
ncols
|
Number of columns in the subplot grid, by default 1
TYPE:
|
figsize
|
Size of the figure (width, height), by default (5, 5) |
subplot_by
|
Column name to create subplots by unique values, by default None
TYPE:
|
subplot_datas
|
List of dataframes for each subplot, by default None
TYPE:
|
subplot_titles
|
List of titles for each subplot, by default None |
adjust_figsize
|
Whether to adjust the figure size based on nrows/ncols, by default True
TYPE:
|
auto_allocate_axes
|
Whether to automatically determine nrows/ncols based on data, by default False
TYPE:
|
**kwargs
|
Additional parameters for plt.subplots
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Create a basic subplot grid:
>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> data = pd.DataFrame(
... np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... rng.integers(1, 3, 100)],
... columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> plot = ISOPlot(data=data).create_subplots(nrows=2, ncols=2)
>>> len(plot.subplot_contexts) == 4
True
>>> plot.close() # Clean up
Create subplots by a column in the data:
>>> plot = (ISOPlot(data=data)
... .create_subplots(nrows=1, ncols=2, subplot_by='Group'))
>>> len(plot.subplot_contexts) == 2
True
>>> plot.close() # Clean up
Create subplots with auto-allocation of axes:
>>> plot = (ISOPlot(data=data)
... .create_subplots(subplot_by='Group', auto_allocate_axes=True))
>>> len(plot.subplot_contexts) == 2
True
>>> plot.close() # Clean up
Source code in soundscapy/plotting/iso_plot.py
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 |
|
get_axes
get_axes()
Get the axes object.
RETURNS | DESCRIPTION |
---|---|
Axes | np.ndarray: The axes object to be used for plotting.
|
|
RAISES | DESCRIPTION |
---|---|
ValueError: If the axes object does not exist.
|
TypeError: If the axes object is not a valid Axes or ndarray of Axes. |
Source code in soundscapy/plotting/iso_plot.py
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
|
get_figure
get_figure()
Get the figure object.
RETURNS | DESCRIPTION |
---|---|
Figure | SubFigure: The figure object to be used for plotting.
|
|
RAISES | DESCRIPTION |
---|---|
ValueError: If the figure object does not exist.
|
TypeError: If the figure object is not a valid Figure or SubFigure. |
Source code in soundscapy/plotting/iso_plot.py
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 |
|
get_single_axes
get_single_axes(ax_idx=None)
Get a specific axes object.
PARAMETER | DESCRIPTION |
---|---|
ax_idx
|
The index of the axes to get. If None, returns the first axes. Can be an integer for flattened access or a tuple of (row, col). |
RETURNS | DESCRIPTION |
---|---|
Axes
|
The requested matplotlib Axes object |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the axes object does not exist or the index is invalid. |
TypeError
|
If the axes object is not a valid Axes or ndarray of Axes. |
Source code in soundscapy/plotting/iso_plot.py
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 |
|
savefig
savefig(*args, **kwargs)
Save the figure.
This method is a wrapper around plt.savefig() to save the figure.
Source code in soundscapy/plotting/iso_plot.py
580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
|
show
show()
Show the figure.
This method is a wrapper around plt.show() to display the figure.
Source code in soundscapy/plotting/iso_plot.py
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
|
style
style(**kwargs)
Apply styling to the plot.
PARAMETER | DESCRIPTION |
---|---|
**kwargs
|
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
ISOPlot
|
The current plot instance for chaining |
Examples:
Apply styling with default parameters:
>>> import pandas as pd
>>> import numpy as np
>>> rng = np.random.default_rng(42)
>>> # Create simple data for styling example
>>> data = pd.DataFrame(
... np.c_[rng.multivariate_normal([0.2, 0.15], [[0.1, 0], [0, 0.2]], 100),
... rng.integers(1, 3, 100)],
... columns=['ISOPleasant', 'ISOEventful', 'Group'])
>>> # Create plot with default styling
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_scatter()
... .style()
... )
>>> plot.show() # xdoctest: +SKIP
>>> plot.get_figure() is not None
True
>>> plot.close() # Clean up
Apply styling with custom parameters:
>>> plot = (
... ISOPlot(data=data)
... .create_subplots()
... .add_scatter()
... .style(xlim=(-2, 2), ylim=(-2, 2), primary_lines=False)
... )
>>> plot.show() # xdoctest: +SKIP
>>> plot.get_figure() is not None
True
>>> plot.close() # Clean up
Demonstrate the fluent interface (method chaining):
>>> # Create plot with method chaining
>>> plot = (
... ISOPlot(data=data)
... .create_subplots(nrows=1, ncols=1)
... .add_scatter(alpha=0.7)
... .add_density(levels=5)
... .style(title_fontsize=14)
... )
>>> plot.show() # xdoctest: +SKIP
>>> # Verify results
>>> isinstance(plot, ISOPlot)
True
>>> plot.close() # Clean up
Source code in soundscapy/plotting/iso_plot.py
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 |
|
yield_axes_objects
yield_axes_objects()
Generate a sequence of axes objects to iterate over.
This method is a helper to iterate over all axes in the figure, whether the figure contains a single Axes object or an array of Axes objects.
YIELDS | DESCRIPTION |
---|---|
Axes
|
Individual matplotlib Axes objects from the current figure. |
Source code in soundscapy/plotting/iso_plot.py
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 |
|
MultiSkewNorm
MultiSkewNorm()
A class representing a multi-dimensional skewed normal distribution.
ATTRIBUTE | DESCRIPTION |
---|---|
selm_model |
The fitted SELM model.
|
cp |
The centred parameters of the fitted model.
TYPE:
|
dp |
The direct parameters of the fitted model.
TYPE:
|
sample_data |
The generated sample data from the fitted model.
TYPE:
|
data |
The input data used for fitting the model.
TYPE:
|
METHOD | DESCRIPTION |
---|---|
summary |
Prints a summary of the fitted model. |
fit |
Fits the model to the provided data. |
define_dp |
Defines the direct parameters of the model. |
sample |
Generates a sample from the fitted model. |
sspy_plot |
Plots the joint distribution of the generated sample. |
ks2ds |
Computes the two-sample Kolmogorov-Smirnov statistic. |
spi |
Computes the similarity percentage index. |
Initialize the MultiSkewNorm object.
Source code in soundscapy/spi/msn.py
236 237 238 239 240 241 242 |
|
__repr__
__repr__()
Return a string representation of the MultiSkewNorm object.
Source code in soundscapy/spi/msn.py
244 245 246 247 248 |
|
define_dp
define_dp(xi, omega, alpha)
Initiate a distribution from the direct parameters.
PARAMETER | DESCRIPTION |
---|---|
xi
|
The xi values of the direct parameters.
TYPE:
|
omega
|
The omega values of the direct parameters.
TYPE:
|
alpha
|
The alpha values of the direct parameters.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
self
|
|
Source code in soundscapy/spi/msn.py
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
|
fit
fit(data=None, x=None, y=None)
Fit the multi-dimensional skewed normal model to the provided data.
PARAMETER | DESCRIPTION |
---|---|
data
|
The input data as a pandas DataFrame or numpy array.
TYPE:
|
x
|
The x-values of the input data as a numpy array or pandas Series.
TYPE:
|
y
|
The y-values of the input data as a numpy array or pandas Series.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If neither |
Source code in soundscapy/spi/msn.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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 |
|
from_params
classmethod
from_params(params=None, *, xi=None, omega=None, alpha=None, mean=None, sigma=None, skew=None)
Create a MultiSkewNorm instance from direct parameters.
PARAMETER | DESCRIPTION |
---|---|
params
|
The direct parameters to initialize the model.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
MultiSkewNorm
|
A new instance of MultiSkewNorm initialized with the provided parameters. |
Source code in soundscapy/spi/msn.py
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 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 423 424 425 |
|
ks2d2s
ks2d2s(test)
Compute the two-sample, two-dimensional Kolmogorov-Smirnov statistic.
PARAMETER | DESCRIPTION |
---|---|
test
|
The test data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
tuple
|
The KS2D statistic and p-value. |
Source code in soundscapy/spi/msn.py
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
|
sample
sample(n=1000, *, return_sample=False)
Generate a sample from the fitted model.
PARAMETER | DESCRIPTION |
---|---|
n
|
The number of samples to generate, by default 1000.
TYPE:
|
return_sample
|
Whether to return the generated sample as an np.ndarray, by default False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None or ndarray
|
The generated sample if |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the model is not fitted (i.e., |
Source code in soundscapy/spi/msn.py
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 |
|
sample_mtsn
sample_mtsn(n=1000, a=-1, b=1, *, return_sample=False)
Generate a sample from the multi-dimensional truncated skew-normal distribution.
Uses rejection sampling to ensure that the samples are within the bounds [a, b] for both dimensions.
PARAMETER | DESCRIPTION |
---|---|
n
|
The number of samples to generate, by default 1000.
TYPE:
|
a
|
Lower truncation bound for both dimensions, by default -1.
TYPE:
|
b
|
Upper truncation bound for both dimensions, by default 1.
TYPE:
|
return_sample
|
Whether to return the generated sample as an np.ndarray, by default False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None or ndarray
|
The generated sample if |
Source code in soundscapy/spi/msn.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 |
|
spi_score
spi_score(test)
Compute the Soundscape Perception Index (SPI).
Calculates the SPI for the test data against the target distribution represented by this MultiSkewNorm instance.
PARAMETER | DESCRIPTION |
---|---|
test
|
The test data.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
int
|
The Soundscape Perception Index (SPI), ranging from 0 to 100. |
Source code in soundscapy/spi/msn.py
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 |
|
sspy_plot
sspy_plot(color='blue', title=None, n=1000)
Plot the joint distribution of the generated sample using soundscapy.
PARAMETER | DESCRIPTION |
---|---|
color
|
Color for the density plot, by default "blue".
TYPE:
|
title
|
Title for the plot, by default None.
TYPE:
|
n
|
Number of samples to generate if
TYPE:
|
Source code in soundscapy/spi/msn.py
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
|
summary
summary()
Provide a summary of the fitted MultiSkewNorm model.
RETURNS | DESCRIPTION |
---|---|
str or None
|
A string summarizing the model parameters and data, or a message indicating the model is not fitted. Returns None if fitted but summary logic is not fully implemented yet. |
Source code in soundscapy/spi/msn.py
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 |
|
add_iso_coords
add_iso_coords(data, val_range=(1, 5), names=('ISOPleasant', 'ISOEventful'), angles=EQUAL_ANGLES, *, overwrite=False)
Calculate and add ISO coordinates as new columns in the DataFrame.
PARAMETER | DESCRIPTION |
---|---|
data
|
Input DataFrame containing PAQ data
TYPE:
|
val_range
|
(min, max) range of original PAQ responses, by default (1, 5) |
names
|
Names for new coordinate columns, by default ("ISOPleasant", "ISOEventful")
TYPE:
|
angles
|
Angles for each PAQ in degrees, by default EQUAL_ANGLES
TYPE:
|
overwrite
|
Whether to overwrite existing ISO coordinate columns, by default False
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
DataFrame with new ISO coordinate columns added |
RAISES | DESCRIPTION |
---|---|
Warning
|
If ISO coordinate columns already exist and overwrite is False |
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({
... 'PAQ1': [4, 2], 'PAQ2': [3, 5], 'PAQ3': [2, 4], 'PAQ4': [1, 3],
... 'PAQ5': [5, 1], 'PAQ6': [3, 2], 'PAQ7': [4, 3], 'PAQ8': [2, 5]
... })
>>> df_with_iso = add_iso_coords(df)
>>> df_with_iso[['ISOPleasant', 'ISOEventful']].round(2)
ISOPleasant ISOEventful
0 -0.03 -0.28
1 0.47 0.18
Source code in soundscapy/surveys/processing.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 271 272 273 274 275 276 277 278 |
|
add_results
add_results(results_df, metric_results)
Add results to MultiIndex dataframe.
PARAMETER | DESCRIPTION |
---|---|
results_df
|
MultiIndex dataframe to add results to.
TYPE:
|
metric_results
|
MultiIndex dataframe of results to add.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
Index includes "Recording" and "Channel" with a column for each index. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the input DataFrames are not in the expected format. |
Source code in soundscapy/audio/metrics.py
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 |
|
cp2dp
cp2dp(cp, family='SN')
Convert centred parameters to direct parameters.
PARAMETER | DESCRIPTION |
---|---|
cp
|
The centred parameters object.
TYPE:
|
family
|
The distribution family, by default "SN" (Skew Normal).
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DirectParams
|
The corresponding direct parameters object. |
Source code in soundscapy/spi/msn.py
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 |
|
create_iso_subplots
create_iso_subplots(data, x='ISOPleasant', y='ISOEventful', subplot_by=None, title='Soundscapy Plot', plot_layers=('scatter', 'density'), *, subplot_size=(4, 4), subplot_titles='by_group', subplot_title_prefix='Plot', nrows=None, ncols=None, **kwargs)
Create a set of subplots displaying data visualizations for soundscape analysis.
This function generates a collection of subplots, where each subplot corresponds to a subset of the input data. The subplots can display scatter plots, density plots, or simplified density plots, and can be organized by specific grouping criteria. Users can specify titles, overall size, row and column layout, and layering of plot types.
PARAMETER | DESCRIPTION |
---|---|
data
|
Input data to be visualized. Can be a single data frame or a list of data frames for use in multiple subplots.
TYPE:
|
x
|
The name of the column in the data to be used for the x-axis. Default is "ISOPleasant".
TYPE:
|
y
|
The name of the column in the data to be used for the y-axis. Default is "ISOEventful".
TYPE:
|
subplot_by
|
The column name by which to group data into subplots. If None, data is not grouped and plotted in a single set of axes. Default is None.
TYPE:
|
title
|
The overarching title of the figure. If None, no overall title is added. Default is "Soundscapy Plot".
TYPE:
|
plot_layers
|
such Literals, optional Type(s) of plot layers to include in each subplot. Can be a single type or a sequence of types. Default is ("scatter", "density").
TYPE:
|
subplot_size
|
Size of each subplot in inches as (width, height). Default is (4, 4).
TYPE:
|
subplot_titles
|
optional Determines how subplot titles are assigned. Options are "by_group" (titles derived from group names), "numbered" (titles as indices), or a list of custom titles. If None, no titles are added. Default is "by_group".
TYPE:
|
subplot_title_prefix
|
Prefix for subplot titles if "numbered" is selected as
TYPE:
|
nrows
|
Number of rows for the subplot grid. If None, automatically calculated based on the number of subplots. Default is None.
TYPE:
|
ncols
|
Number of columns for the subplot grid. If None, automatically calculated based on the number of subplots. Default is None.
TYPE:
|
**kwargs
|
Additional keyword arguments to pass to matplotlib's
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
tuple
|
A tuple containing: - fig : matplotlib.figure.Figure The created matplotlib figure object containing the subplots. - np.ndarray An array of matplotlib.axes.Axes objects corresponding to the subplots. |
Examples:
Basic subplots with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> import pandas as pd
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> four_locs = sspy.isd.select_location_ids(data,
... ['CamdenTown', 'PancrasLock', 'RegentsParkJapan', 'RegentsParkFields']
... )
>>> fig, axes = sspy.create_iso_subplots(four_locs, subplot_by="LocationID")
>>> plt.show() # xdoctest: +SKIP
Create subplots by specifying a list of data
>>> data1 = pd.DataFrame({'ISOPleasant': np.random.uniform(-1, 1, 50),
... 'ISOEventful': np.random.uniform(-1, 1, 50)})
>>> data2 = pd.DataFrame({'ISOPleasant': np.random.uniform(-1, 1, 50),
... 'ISOEventful': np.random.uniform(-1, 1, 50)})
>>> fig, axes = create_iso_subplots(
... [data1, data2], plot_layers="scatter", nrows=1, ncols=2
... )
>>> plt.show() # xdoctest: +SKIP
>>> assert len(axes) == 2
>>> plt.close('all')
Source code in soundscapy/plotting/plot_functions.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
|
density
density(data, title='Soundscape Density Plot', ax=None, *, x='ISOPleasant', y='ISOEventful', hue=None, incl_scatter=True, density_type='full', palette='colorblind', scatter_kws=None, legend='auto', prim_labels=None, **kwargs)
Plot a density plot of ISOCoordinates.
Creates a kernel density estimate visualization of data distribution on a circumplex grid with the custom Soundscapy styling for soundscape circumplex visualisations. Can optionally include a scatter plot of the underlying data points.
PARAMETER | DESCRIPTION |
---|---|
data
|
Input data structure containing coordinate data, typically with ISOPleasant and ISOEventful columns.
TYPE:
|
title
|
Title to add to circumplex plot, by default "Soundscape Density Plot"
TYPE:
|
ax
|
Pre-existing axes object to use for the plot, by default None
If
TYPE:
|
x
|
Column name for x variable, by default "ISOPleasant"
TYPE:
|
y
|
Column name for y variable, by default "ISOEventful"
TYPE:
|
hue
|
Grouping variable that will produce density contours with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case, by default None
TYPE:
|
incl_scatter
|
Whether to include a scatter plot of the data points, by default True
TYPE:
|
density_type
|
Type of density plot to draw. "full" uses default parameters, "simple" uses a lower number of levels (2), higher threshold (0.5), and lower alpha (0.5) for a cleaner visualization, by default "full"
TYPE:
|
palette
|
Method for choosing the colors to use when mapping the hue semantic. String values are passed to seaborn.color_palette(). List or dict values imply categorical mapping, while a colormap object implies numeric mapping, by default "colorblind"
TYPE:
|
scatter_kws
|
Keyword arguments to pass to
TYPE:
|
incl_outline
|
Whether to include an outline for the density contours, by default False
TYPE:
|
legend
|
How to draw the legend. If "brief", numeric hue variables will be represented with a sample of evenly spaced values. If "full", every group will get an entry in the legend. If "auto", choose between brief or full representation based on number of levels. If False, no legend data is added and no legend is drawn, by default "auto"
TYPE:
|
prim_labels
|
Deprecated. Use xlabel and ylabel parameters instead.
TYPE:
|
**kwargs
|
Additional styling parameters:
Also accepts additional keyword arguments for matplotlib's contour and contourf functions.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Axes object containing the plot.
|
|
Notes
This function will raise a warning if the dataset has fewer than RECOMMENDED_MIN_SAMPLES (30) data points, as density plots are not reliable with small sample sizes.
Examples:
Basic density plot with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> ax = sspy.density(data)
>>> plt.show() # xdoctest: +SKIP
Simple density plot with fewer contour levels:
>>> ax = sspy.density(data, density_type="simple")
>>> plt.show() # xdoctest: +SKIP
Density plot with custom styling:
>>> sub_data = sspy.isd.select_location_ids(
... data, ['CamdenTown', 'PancrasLock', 'RegentsParkJapan', 'RegentsParkFields'])
>>> ax = sspy.density(
... sub_data,
... hue="SessionID",
... incl_scatter=True,
... legend_loc="upper right",
... fill = False,
... density_type = "simple",
... )
>>> plt.show() # xdoctest: +SKIP
Add density to existing plots:
>>> fig, axes = plt.subplots(1, 2, figsize=(12, 6))
>>> axes[0] = sspy.density(
... sspy.isd.select_location_ids(data, ['CamdenTown', 'PancrasLock']),
... ax=axes[0], title="CamdenTown and PancrasLock", hue="LocationID",
... density_type="simple"
... )
>>> axes[1] = sspy.density(
... sspy.isd.select_location_ids(data, ['RegentsParkJapan']),
... ax=axes[1], title="RegentsParkJapan"
... )
>>> plt.tight_layout()
>>> plt.show() # xdoctest: +SKIP
>>> plt.close('all')
Source code in soundscapy/plotting/plot_functions.py
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
|
disable_logging
disable_logging()
Disable all Soundscapy logging.
Examples:
>>> from soundscapy import disable_logging
>>> disable_logging()
>>> # No more logging messages will be shown
Source code in soundscapy/sspylogging.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
|
dp2cp
dp2cp(dp, family='SN')
Convert direct parameters to centred parameters.
PARAMETER | DESCRIPTION |
---|---|
dp
|
The direct parameters object.
TYPE:
|
family
|
The distribution family, by default "SN" (Skew Normal).
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
CentredParams
|
The corresponding centred parameters object. |
Source code in soundscapy/spi/msn.py
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
|
enable_debug
enable_debug()
Quickly enable DEBUG level logging to console.
This is a convenience function for debugging during interactive sessions.
Examples:
>>> from soundscapy import enable_debug
>>> enable_debug()
>>> # Now all debug messages will be shown
Source code in soundscapy/sspylogging.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
|
get_logger
get_logger()
Get the Soundscapy logger instance.
Returns the loguru logger configured for Soundscapy. This is mainly for advanced users who want to configure logging themselves.
RETURNS | DESCRIPTION |
---|---|
logger
|
The loguru logger instance
TYPE:
|
Examples:
>>> from soundscapy import get_logger
>>> logger = get_logger()
>>> logger.debug("Custom debug message")
Source code in soundscapy/sspylogging.py
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
|
jointplot
jointplot(data, *, x=DEFAULT_XCOL, y=DEFAULT_YCOL, title='Soundscape Joint Plot', hue=None, incl_scatter=True, density_type='full', palette='colorblind', color=DEFAULT_COLOR, figsize=DEFAULT_FIGSIZE, scatter_kws=None, incl_outline=False, alpha=DEFAULT_SEABORN_PARAMS['alpha'], fill=True, levels=10, thresh=0.05, bw_adjust=DEFAULT_BW_ADJUST, legend='auto', prim_labels=None, joint_kws=None, marginal_kws=None, marginal_kind='kde', **kwargs)
Create a jointplot with a central distribution and marginal plots.
Creates a visualization with a main plot (density or scatter) in the center and marginal distribution plots along the x and y axes. The main plot uses the custom Soundscapy styling for soundscape circumplex visualisations, and the marginals show the individual distributions of each variable.
PARAMETER | DESCRIPTION |
---|---|
data
|
Input data structure containing coordinate data, typically with ISOPleasant and ISOEventful columns.
TYPE:
|
x
|
Column name for x variable, by default "ISOPleasant"
TYPE:
|
y
|
Column name for y variable, by default "ISOEventful"
TYPE:
|
title
|
Title to add to the jointplot, by default "Soundscape Joint Plot"
TYPE:
|
hue
|
Grouping variable that will produce plots with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case, by default None
TYPE:
|
incl_scatter
|
Whether to include a scatter plot of the data points in the joint plot, by default True
TYPE:
|
density_type
|
Type of density plot to draw. "full" uses default parameters, "simple" uses a lower number of levels (2), higher threshold (0.5), and lower alpha (0.5) for a cleaner visualization, by default "full"
TYPE:
|
palette
|
Method for choosing the colors to use when mapping the hue semantic. String values are passed to seaborn.color_palette(). List or dict values imply categorical mapping, while a colormap object implies numeric mapping, by default "colorblind"
TYPE:
|
color
|
Color to use for the plot elements when not using hue mapping, by default "#0173B2" (first color from colorblind palette)
TYPE:
|
figsize
|
Size of the figure to create (determines height, width is proportional), by default (5, 5) |
scatter_kws
|
Additional keyword arguments to pass to scatter plot if incl_scatter is True, by default None |
incl_outline
|
Whether to include an outline for the density contours, by default False
TYPE:
|
alpha
|
Opacity level for the density fill, by default 0.8
TYPE:
|
fill
|
Whether to fill the density contours, by default True
TYPE:
|
levels
|
Number of contour levels or specific levels to draw. A vector argument must have increasing values in [0, 1], by default 10 |
thresh
|
Lowest iso-proportion level at which to draw contours, by default 0.05
TYPE:
|
bw_adjust
|
Factor that multiplicatively scales the bandwidth. Increasing will make the density estimate smoother, by default 1.2
TYPE:
|
legend
|
How to draw the legend for hue mapping, by default "auto"
TYPE:
|
prim_labels
|
Deprecated. Use xlabel and ylabel parameters instead.
TYPE:
|
joint_kws
|
Additional keyword arguments to pass to the joint plot, by default None |
marginal_kws
|
Additional keyword arguments to pass to the marginal plots, by default {"fill": True, "common_norm": False} |
marginal_kind
|
Type of plot to draw in the marginal axes, either "kde" for kernel density estimation or "hist" for histogram, by default "kde"
TYPE:
|
**kwargs
|
Additional styling parameters:
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
JointGrid
|
The seaborn JointGrid object containing the plot |
Notes
This function will raise a warning if the dataset has fewer than RECOMMENDED_MIN_SAMPLES (30) data points, as density plots are not reliable with small sample sizes.
Examples:
Basic jointplot with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> g = sspy.jointplot(data)
>>> plt.show() # xdoctest: +SKIP
Jointplot with histogram marginals:
>>> g = sspy.jointplot(data, marginal_kind="hist")
>>> plt.show() # xdoctest: +SKIP
Jointplot with custom styling and grouping:
>>> g = sspy.jointplot(
... data,
... hue="LocationID",
... incl_scatter=True,
... density_type="simple",
... diagonal_lines=True,
... figsize=(6, 6),
... title="Grouped Soundscape Analysis"
... )
>>> plt.show() # xdoctest: +SKIP
>>> plt.close('all')
Source code in soundscapy/plotting/plot_functions.py
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 |
|
paq_likert
paq_likert(data, title='Stacked Likert Plot', paq_cols=PAQ_IDS, *, legend=True, ax=None, plot_percentage=False, bar_labels=True, **kwargs)
Create a Likert scale plot for PAQ (Perceived Affective Quality) data.
PARAMETER | DESCRIPTION |
---|---|
data
|
DataFrame containing PAQ values.
TYPE:
|
paq_cols
|
List of column names containing PAQ data, by default PAQ_IDS. |
title
|
Plot title, by default "Stacked Likert Plot".
TYPE:
|
legend
|
Whether to show the legend, by default True.
TYPE:
|
ax
|
Matplotlib axes to plot on, by default None.
TYPE:
|
plot_percentage
|
Whether to show percentages instead of absolute values, by default False.
TYPE:
|
bar_labels
|
Whether to show bar labels, by default True.
TYPE:
|
**kwargs
|
Additional keyword arguments passed to plot_likert.plot_likert.
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
None
|
This function does not return anything, it plots directly to the given axes. |
Examples:
>>> import soundscapy as sspy
>>> data = sspy.isd.load(['CamdenTown'])
>>> paq_likert(data, "Camden Town Likert data")
>>> plt.show() # xdoctest: +SKIP
Source code in soundscapy/plotting/likert.py
194 195 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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
|
paq_radar_plot
paq_radar_plot(data, ax=None, index=None, angles=EQUAL_ANGLES, *, figsize=(8, 8), palette='colorblind', alpha=0.25, linewidth=1.5, linestyle='solid', ylim=(1, 5), title=None, label_pad=15, legend_loc='upper right', legend_bbox_to_anchor=(0.1, 0.1))
Generate a radar/spider plot of PAQ values.
This function creates a radar plot showing PAQ (Perceived Affective Quality) values from a dataframe. The radar plot displays values for all 8 PAQ dimensions arranged in a circular layout.
PARAMETER | DESCRIPTION |
---|---|
data
|
DataFrame containing PAQ values. Must contain columns matching PAQ_LABELS or they will be filtered out.
TYPE:
|
ax
|
Existing polar subplot axes to plot to. If None, new axes will be created.
TYPE:
|
index
|
Column(s) to set as index for the data. Useful for labeling in the legend.
TYPE:
|
figsize
|
Figure size (width, height) in inches, by default (8, 8). Only used when creating new axes. |
colors
|
Colors for the plot lines and fills. Can be: - List of color names/values for each data row - Dictionary mapping index values to colors - Single color name/value to use for all data rows - A matplotlib colormap to generate colors from If None, a default colormap will be used.
TYPE:
|
alpha
|
Transparency for the filled areas, by default 0.25
TYPE:
|
linewidth
|
Width of the plot lines, by default 1.5
TYPE:
|
linestyle
|
Style of the plot lines, by default "solid"
TYPE:
|
ylim
|
Y-axis limits (min, max), by default (1, 5) for standard Likert scale |
title
|
Plot title, by default None
TYPE:
|
text_padding
|
Padding for category labels, by default auto-generated |
legend_loc
|
Legend location, by default "upper right"
TYPE:
|
legend_bbox_to_anchor
|
Legend bbox_to_anchor parameter, by default (0.1, 0.1) |
RETURNS | DESCRIPTION |
---|---|
Axes
|
Matplotlib Axes with radar plot |
Examples:
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
>>> from soundscapy.plotting.likert import paq_radar_plot
>>>
>>> # Sample data with PAQ values for two locations
>>> data = pd.DataFrame({
... "Location": ["Park", "Street"],
... "pleasant": [4.2, 2.1],
... "vibrant": [3.5, 4.2],
... "eventful": [2.8, 4.5],
... "chaotic": [1.5, 3.9],
... "annoying": [1.2, 3.7],
... "monotonous": [2.5, 1.8],
... "uneventful": [3.1, 1.9],
... "calm": [4.3, 1.4]
... })
>>>
>>> # Create radar plot with the "Location" column as index
>>> ax = paq_radar_plot(data, index="Location", title="PAQ Comparison")
>>> plt.show() # xdoctest: +SKIP
Source code in soundscapy/plotting/likert.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
|
parallel_process
parallel_process(wav_files, results_df, levels, analysis_settings, max_workers=None, resample=None, *, parallel_mosqito=True)
Process multiple binaural files in parallel.
PARAMETER | DESCRIPTION |
---|---|
resample
|
TYPE:
|
wav_files
|
List of WAV files to process.
TYPE:
|
results_df
|
Initial results DataFrame to update.
TYPE:
|
levels
|
Dictionary with calibration levels for each file.
TYPE:
|
analysis_settings
|
Analysis settings object.
TYPE:
|
max_workers
|
Maximum number of worker processes. If None, it will default to the number of processors on the machine.
TYPE:
|
parallel_mosqito
|
Whether to process MoSQITo metrics in parallel within each file. Defaults to True.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
Updated results DataFrame with analysis results for all files. |
Source code in soundscapy/audio/parallel_processing.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
|
prep_multiindex_df
prep_multiindex_df(dictionary, label='Leq', incl_metric=True)
Prepare a MultiIndex dataframe from a dictionary of results.
PARAMETER | DESCRIPTION |
---|---|
dictionary
|
Dict of results with recording name as key, channels {"Left", "Right"} as second key, and Leq metric as value.
TYPE:
|
label
|
Name of metric included, by default "Leq".
TYPE:
|
incl_metric
|
Whether to include the metric value in the resulting dataframe, by default True. If False, will only set up the DataFrame with the proper MultiIndex.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
Index includes "Recording" and "Channel" with a column for each index if |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the input dictionary is not in the expected format. |
Source code in soundscapy/audio/metrics.py
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 |
|
process_all_metrics
process_all_metrics(b, analysis_settings, parallel=True)
Process all metrics specified in the analysis settings for a binaural signal.
This function runs through all enabled metrics in the provided analysis settings, computes them for the given binaural signal, and compiles the results into a single DataFrame.
PARAMETER | DESCRIPTION |
---|---|
b
|
Binaural signal object to process.
TYPE:
|
analysis_settings
|
Configuration object specifying which metrics to run and their parameters.
TYPE:
|
parallel
|
If True, run applicable calculations in parallel. Defaults to True.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
A MultiIndex DataFrame containing results from all processed metrics. The index includes "Recording" and "Channel" levels. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If there's an error processing any of the metrics. |
Notes
The parallel option primarily affects the MoSQITo metrics. Other metrics may not benefit from parallelization.
Examples:
>>> # xdoctest: +SKIP
>>> from soundscapy.audio import Binaural
>>> from soundscapy import AnalysisSettings
>>> signal = Binaural.from_wav("audio.wav", resample=480000)
>>> settings = AnalysisSettings.from_yaml("settings.yaml")
>>> results = process_all_metrics(signal,settings)
Source code in soundscapy/audio/metrics.py
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 |
|
rename_paqs
rename_paqs(df, paq_aliases=None)
Rename the PAQ columns in a DataFrame to standard PAQ IDs.
PARAMETER | DESCRIPTION |
---|---|
df
|
Input DataFrame containing PAQ data.
TYPE:
|
paq_aliases
|
Specify which PAQs are to be renamed. If None, will check if the column names are in pre-defined options. If a tuple, the order must match PAQ_IDS. If a dict, keys are current names and values are desired PAQ IDs.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
DataFrame
|
DataFrame with renamed PAQ columns. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If paq_aliases is not a tuple, list, or dictionary. |
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({
... 'pleasant': [4, 3],
... 'vibrant': [2, 5],
... 'other_col': [1, 2]
... })
>>> rename_paqs(df)
PAQ1 PAQ2 other_col
0 4 2 1
1 3 5 2
>>> df_custom = pd.DataFrame({
... 'pl': [4, 3],
... 'vb': [2, 5],
... })
>>> rename_paqs(df_custom, paq_aliases={'pl': 'PAQ1', 'vb': 'PAQ2'})
PAQ1 PAQ2
0 4 2
1 3 5
Source code in soundscapy/surveys/survey_utils.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 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 271 272 273 274 275 276 277 278 279 |
|
scatter
scatter(data, title='Soundscape Scatter Plot', ax=None, *, x='ISOPleasant', y='ISOEventful', hue=None, palette='colorblind', legend='auto', prim_labels=None, **kwargs)
Plot ISOcoordinates as scatter points on a soundscape circumplex grid.
Creates a scatter plot of data on a standardized circumplex grid with the custom Soundscapy styling for soundscape circumplex visualisations.
PARAMETER | DESCRIPTION |
---|---|
data
|
Input data structure containing coordinate data, typically with ISOPleasant and ISOEventful columns.
TYPE:
|
x
|
Column name for x variable, by default "ISOPleasant"
TYPE:
|
y
|
Column name for y variable, by default "ISOEventful"
TYPE:
|
title
|
Title to add to circumplex plot, by default "Soundscape Scatter Plot"
TYPE:
|
ax
|
Pre-existing matplotlib axes for the plot, by default None
If
TYPE:
|
hue
|
Grouping variable that will produce points with different colors. Can be either categorical or numeric, although color mapping will behave differently in latter case, by default None
TYPE:
|
palette
|
Method for choosing the colors to use when mapping the hue semantic. String values are passed to seaborn.color_palette(). List or dict values imply categorical mapping, while a colormap object implies numeric mapping, by default "colorblind"
TYPE:
|
color
|
Color to use for the plot elements when not using hue mapping, by default "#0173B2" (first color from colorblind palette)
TYPE:
|
figsize
|
Size of the figure to return if |
s
|
Size of scatter points, by default 20
TYPE:
|
legend
|
How to draw the legend. If "brief", numeric hue and size variables will be represented with a sample of evenly spaced values. If "full", every group will get an entry in the legend. If "auto", choose between brief or full representation based on number of levels. If False, no legend data is added and no legend is drawn, by default "auto"
TYPE:
|
prim_labels
|
Deprecated. Use xlabel and ylabel parameters instead.
TYPE:
|
PARAMETER | DESCRIPTION |
---|---|
xlabel |
Custom axis labels. By default "\(P_{ISO}\)" and "\(E_{ISO}\)" with math rendering. If None is passed, the column names (x and y) will be used as labels. If a string is provided, it will be used as the label. If False is passed, axis labels will be hidden.
|
ylabel |
Custom axis labels. By default "\(P_{ISO}\)" and "\(E_{ISO}\)" with math rendering. If None is passed, the column names (x and y) will be used as labels. If a string is provided, it will be used as the label. If False is passed, axis labels will be hidden.
|
xlim |
Limits for x and y axes, by default (-1, 1) for both |
ylim |
Limits for x and y axes, by default (-1, 1) for both |
legend_loc |
Location of legend, by default "best"
TYPE:
|
diagonal_lines |
Whether to include diagonal dimension labels (e.g. calm, etc.), by default False
TYPE:
|
prim_ax_fontdict |
Font dictionary for axis labels with these defaults: { "family": "sans-serif", "fontstyle": "normal", "fontsize": "large", "fontweight": "medium", "parse_math": True, "c": "black", "alpha": 1, }
TYPE:
|
fontsize |
Direct parameters for font styling in axis labels
|
fontweight |
Direct parameters for font styling in axis labels
|
fontstyle |
Direct parameters for font styling in axis labels
|
family |
Direct parameters for font styling in axis labels
|
c |
Direct parameters for font styling in axis labels
|
alpha |
Direct parameters for font styling in axis labels
|
parse_math |
Direct parameters for font styling in axis labels
|
RETURNS | DESCRIPTION |
---|---|
Axes object containing the plot.
|
|
Notes
This function applies special styling appropriate for circumplex plots including gridlines, axis labels, and proportional axes.
Examples:
Basic scatter plot with default settings:
>>> import soundscapy as sspy
>>> import matplotlib.pyplot as plt
>>> data = sspy.isd.load()
>>> data = sspy.add_iso_coords(data)
>>> ax = sspy.scatter(data)
>>> plt.show() # xdoctest: +SKIP
Scatter plot with grouping by location:
>>> ax = sspy.scatter(data, hue="LocationID", diagonal_lines=True, legend=False)
>>> plt.show() # xdoctest: +SKIP
>>> plt.close('all')
Source code in soundscapy/plotting/plot_functions.py
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 |
|
setup_logging
setup_logging(level='INFO', log_file=None, format_level='basic')
Set up logging for Soundscapy with sensible defaults.
PARAMETER | DESCRIPTION |
---|---|
level
|
Logging level for console output. Options: "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"
TYPE:
|
log_file
|
Path to a log file. If provided, all messages (including DEBUG) will be logged to this file. |
format_level
|
Format complexity level. Options: - "basic": Simple format with timestamp, level, and message - "detailed": Adds module, function and line information - "developer": Adds exception details and diagnostics
TYPE:
|
Examples:
>>> from soundscapy import setup_logging
>>> # Basic usage - show INFO level and above in console
>>> setup_logging()
>>>
>>> # Enable DEBUG level and log to file
>>> setup_logging(level="DEBUG", log_file="soundscapy.log")
>>>
>>> # Use detailed format for debugging
>>> setup_logging(level="DEBUG", format_level="detailed")
Source code in soundscapy/sspylogging.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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 |
|
show_submodules: true