Spaces:
Sleeping
Sleeping
File size: 20,944 Bytes
6a3cff5 31ff428 6a3cff5 31ff428 19d61ce 31ff428 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 31ff428 19d61ce 6a3cff5 19d61ce 31ff428 19d61ce 31ff428 6a3cff5 19d61ce 6a3cff5 19d61ce 31ff428 19d61ce 31ff428 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 19d61ce 6a3cff5 31ff428 19d61ce 31ff428 6a3cff5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 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 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 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 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 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 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 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 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 | # /// script
# requires-python = ">=3.12"
# dependencies = [
# "marimo",
# "matplotlib==3.9.2",
# "ordered-set==4.1.0",
# "pandas==2.2.3",
# "soundscapy==0.7.6",
# ]
# ///
import marimo
__generated_with = "0.9.19"
app = marimo.App(width="full", app_title="Soundscapy_viz")
@app.cell
def __():
import marimo as mo
mo.sidebar(
[
mo.image(
src="https://raw.githubusercontent.com/MitchellAcoustics/Soundscapy/main/docs/img/LightLogo.png"
),
mo.md(
""
).center(),
mo.nav_menu(
{
"Links": {
"https://soundscapy.readthedocs.io/en/latest/": f"{mo.icon('oui:documentation')} Documentation",
"https://github.com/MitchellAcoustics/Soundscapy": f"{mo.icon('logos:github-icon')} GitHub",
},
},
orientation="vertical",
),
]
)
return (mo,)
@app.cell(hide_code=True)
def __(mo):
with mo.status.spinner(subtitle="Loading ...") as _spinner:
import soundscapy as sspy
from soundscapy.surveys.survey_utils import (
EQUAL_ANGLES,
PAQ,
PAQ_LABELS,
PAQ_IDS,
)
from soundscapy.plotting import (
CircumplexPlotParams,
CircumplexPlot,
PlotType,
Backend,
)
import pandas as pd
from pandas.errors import UndefinedVariableError
import io
from ordered_set import OrderedSet
from dataclasses import dataclass
import matplotlib.pyplot as plt
return (
Backend,
CircumplexPlot,
CircumplexPlotParams,
EQUAL_ANGLES,
OrderedSet,
PAQ,
PAQ_IDS,
PAQ_LABELS,
PlotType,
UndefinedVariableError,
dataclass,
io,
pd,
plt,
sspy,
)
@app.cell(hide_code=True)
def __(mo):
mo.hstack(
[mo.md("# Explore one of our datasets or load your own data").center()],
gap=6.0,
justify="space-around",
)
return
@app.cell
def __(mo):
# Data Loading
included_data_source_mo = mo.ui.dropdown(
options=["ISD", "SATP", "ARAUS"],
value="ISD",
label="Select Dataset",
full_width=True,
)
upload_file_mo = mo.ui.file(
filetypes=[".csv"], kind="area", label="**Load your own data**"
)
data_load_mo = mo.vstack(
[
mo.md("## Load Data"),
included_data_source_mo,
upload_file_mo,
]
)
mo.vstack(
[
mo.hstack(
[
mo.md(
r"""
`soundscapy` was built to work with soundscape survey data. We make it super simple to load up and explore a few supported datasets.
Simply select which dataset you'd like to explore and we'll automatically load it for you.
But, that's not all! You don't just have to use one of our supported datasets! You can also load in your own data and create some lovely soundscapy-style plots. Just scroll on down to the load your data button.
"""
),
data_load_mo,
],
widths=[5, 3],
align="center",
justify="center",
gap=8.0,
),
mo.md("---"),
],
justify="center",
gap=6.0,
)
return data_load_mo, included_data_source_mo, upload_file_mo
@app.cell
def __(data_loading, included_data_source_mo, upload_file_mo):
raw_data, data_source = data_loading(included_data_source_mo, upload_file_mo)
return data_source, raw_data
@app.cell
def __(
calc_iso_coords_check,
circumplex_angles,
column_filter,
column_to_filter_by,
custom_iso_names,
grouped_filter_table,
mo,
p_mo,
paq_val_range,
plot_title,
plot_type_option,
plotting_backend,
query_filters,
remove_missing_vals_option,
rename_paqs_option,
seaborn_color,
seaborn_diag_lines,
seaborn_hue,
seaborn_palette,
validate_data_check,
):
data_settings = mo.vstack(
[
mo.md("### Data Settings"),
validate_data_check,
calc_iso_coords_check,
paq_val_range.vstack(),
mo.accordion(
{
"Set custom names for the ISO Coordinates": custom_iso_names.vstack(),
"Select Columns": column_filter.form(
label="Select Columns to include: "
),
"Filter Rows": mo.vstack(
[column_to_filter_by, grouped_filter_table]
),
"Extra Filters": query_filters.vstack(),
"Rename PAQs": rename_paqs_option.vstack(),
"Extra Options": mo.vstack(
[
remove_missing_vals_option,
mo.accordion({"Custom Angles": circumplex_angles.vstack()}),
]
),
}
),
]
)
plot_settings = mo.vstack(
[
mo.md("### Plot Settings"),
plot_title,
seaborn_hue,
seaborn_palette,
seaborn_color,
plot_type_option,
plotting_backend,
seaborn_diag_lines,
]
)
mo.output.append(
mo.hstack([data_settings, p_mo, plot_settings], gap=4.0, justify="space-around")
)
return data_settings, plot_settings
@app.cell
def __(data, data_description, data_source, mo, plot_data, raw_data):
with mo.status.spinner(subtitle="Preparing data ...") as _spinner:
explore_data = mo.ui.tabs(
{
"Data Overview": mo.ui.table(
data_description(data_source, data), page_size=20, selection=None
),
"Data": mo.ui.table(plot_data, selection=None, page_size=20),
"Original Data": mo.ui.table(raw_data, selection=None, page_size=20),
"Explore Data": mo.ui.data_explorer(plot_data),
}
).style(max_width="100%")
mo.vstack(
[
mo.md("---"),
explore_data,
]
).style(max_width="100%")
return (explore_data,)
@app.cell
def __(mo, plot_data, seaborn_hue):
if seaborn_hue.value != None:
seaborn_loc = mo.ui.multiselect.from_series(
plot_data[seaborn_hue.value], value=None, label="Select groups: "
)
return (seaborn_loc,)
@app.cell(hide_code=True)
def __():
# from typing import TypedDict
# @dataclass(frozen=True)
# class VegaItem:
# id: str
# dict_path: list
# default: Any
# @dataclass(frozen=True)
# class VegaConfig:
# x = VegaItem("x", ["encoding", "x", "field"], custom_iso_names.value[0])
# y = VegaItem("y", ["encoding", "y", "field"], custom_iso_names.value[0])
# hue = VegaItem("hue", ["encoding", "color", "field"], "LocationID")
# color = VegaItem("color", ["encoding", "color", "field"], None)
# row = VegaItem("row", ["encoding", "row", "field"], None)
# column = VegaItem("column", ["encoding", "column", "field"], None)
# size = VegaItem("size", ["encoding", "size", "field"], None)
# shape = VegaItem("shape", ["encoding", "shape", "field"], None)
# _vega_config = data_explorer.value
# def get_item(self, id: str):
# return getattr(self, id)
# def traverse_dict(self, id: str) -> Any:
# """
# Get a value nested in a dictionary by its nested path.
# """
# default = self.get_item(id).default
# value_path = self.get_item(id).dict_path
# dict_chain = self._vega_config
# while value_path:
# dict_chain = dict_chain.get(value_path.pop(0), default)
# return dict_chain
# p = VegaConfig()
# p.traverse_dict("x")
return
@app.cell
def __(EQUAL_ANGLES, PAQ_IDS, PAQ_LABELS, mo):
# Setup marimo inputs for iso parameters
validate_data_check = mo.ui.checkbox(
value=True, label="Apply ISD-style data validation?"
)
calc_iso_coords_check = mo.ui.checkbox(
value=True, label="Calculate ISD Coordinates?"
)
custom_iso_names = mo.ui.array(
[
mo.ui.text(value="ISOPleasant", label="X label: ", debounce=True),
mo.ui.text(value="ISOEventful", label="Y label: ", debounce=True),
],
)
paq_val_range = mo.ui.array(
[
mo.ui.number(
value=1,
step=1,
label="PAQ Min value",
full_width=True,
debounce=True,
),
mo.ui.number(
value=5,
step=1,
label="PAQ Max value",
full_width=True,
debounce=True,
),
]
)
rename_paqs_option = mo.ui.dictionary(
{
f"{PAQ_IDS[i]}": mo.ui.text(
label=f"{PAQ_IDS[i]}: ", value=paq_label, debounce=True
)
for i, paq_label in enumerate(PAQ_LABELS)
}
)
remove_missing_vals_option = mo.ui.checkbox(
value=False, label="Remove all missing values?"
)
circumplex_angles = mo.ui.array(
[
mo.ui.number(value=EQUAL_ANGLES[i], label=f"{paq}: ", debounce=True)
for i, paq in enumerate(PAQ_IDS)
]
)
return (
calc_iso_coords_check,
circumplex_angles,
custom_iso_names,
paq_val_range,
remove_missing_vals_option,
rename_paqs_option,
validate_data_check,
)
@app.cell
def __(mo, raw_data):
# Data filtering 1
column_to_filter_by = mo.ui.dropdown(
label="Column to filter by:",
options=list(raw_data.columns),
allow_select_none=True,
value=None,
full_width=True,
)
return (column_to_filter_by,)
@app.cell
def __(OrderedSet, column_to_filter_by, custom_iso_names, mo, raw_data):
# Data filtering 2
column_filter = mo.ui.table(
data=list(
OrderedSet(
list(raw_data.columns)[:4]
+ [name for name in custom_iso_names.value]
+ list(raw_data.columns)[4:]
)
),
page_size=10,
)
# Set up table to select a column to filter rows by and select row values to filter
if column_to_filter_by.value is not None:
grouped_filter_table = mo.ui.table(
data=list(raw_data[column_to_filter_by.value].unique()),
page_size=10,
).form(label="Select rows to include:")
else:
grouped_filter_table = mo.md("No column selected for filtering.")
grouped_filter_table.value = None
query_filters = mo.ui.array(
[
mo.ui.text(
label="pd.query command for filtering: ",
placeholder="e.g.: LocationID in ['CamdenTown', 'PancrasLock']",
full_width=True,
)
for _ in range(4)
]
)
return column_filter, grouped_filter_table, query_filters
@app.cell
def __(mo, plot_data):
# Setup Seaborn arguments
plot_title = mo.ui.text(value="Soundscapy plot", label="Title: ", full_width=True)
available_palettes = (
"deep",
"muted",
"bright",
"pastel",
"dark",
"colorblind",
)
seaborn_palette = mo.ui.dropdown(
options=available_palettes,
value="colorblind",
label="Palette: ",
full_width=True,
)
seaborn_color = mo.ui.text(value="blue", label="Color: ", full_width=True)
seaborn_diag_lines = mo.ui.checkbox(
value=False, label="Show secondary axes lines and labels on sspy plot?"
)
seaborn_hue = mo.ui.dropdown(
plot_data.columns.tolist(),
value=None,
allow_select_none=True,
label="Split dataset by: ",
full_width=True,
)
plot_type_option = mo.ui.dropdown(
["scatter", "density", "simple_density", "joint"],
value="density",
label="Seaborn plot type: ",
full_width=True,
)
plotting_backend = mo.ui.dropdown(
["seaborn", "plotly"], value="seaborn", full_width=True
)
return (
available_palettes,
plot_title,
plot_type_option,
plotting_backend,
seaborn_color,
seaborn_diag_lines,
seaborn_hue,
seaborn_palette,
)
@app.cell
def __(
calc_iso_coords_check,
circumplex_angles,
column_filter,
column_to_filter_by,
custom_iso_names,
data_sspy_setup,
grouped_filter_table,
paq_val_range,
query_filters,
raw_data,
remove_missing_vals_option,
rename_paqs_option,
validate_data_check,
):
data = data_sspy_setup(
raw_data,
validate_data_check.value,
calc_iso_coords_check.value,
column_filter.value,
query_filters.value,
rename_paqs_option.value,
remove_missing_vals_option.value,
paq_val_range.value,
custom_iso_names.value,
circumplex_angles.value,
column_to_filter_by.value,
grouped_filter_table.value,
)
plot_data = data.copy()
return data, plot_data
@app.cell
def __(
PlotType,
create_sspy_plot,
custom_iso_names,
mo,
plot_data,
plot_title,
plot_type_option,
plotting_backend,
seaborn_color,
seaborn_diag_lines,
seaborn_hue,
seaborn_palette,
):
try:
p = create_sspy_plot(
plot_data,
custom_iso_names.value,
PlotType(plot_type_option.value),
plot_title.value,
seaborn_palette.value,
seaborn_color.value,
seaborn_diag_lines.value,
seaborn_hue.value,
plotting_backend.value,
)
p_mo = p.get_figure()
except Exception as e:
p_mo = mo.md(f"{e}").callout(kind="danger")
return p, p_mo
@app.cell
def sspy_data_setup(OrderedSet, UndefinedVariableError, mo, pd, sspy):
def add_coords_to_sspy_df(data, isopl, isoev, names, overwrite=False):
for name in names:
if name in data.columns:
if overwrite:
data = data.drop(name, axis=1)
else:
raise Warning(
f"{name} already in dataframe. Use overwrite=Trueoverwrite=True to replace it."
)
data = data.assign(**{names[0]: isopl, names[1]: isoev})
return data
def data_sspy_setup(
data: pd.DataFrame,
validate_data: bool,
calc_iso_coords: bool,
column_filter,
query_filters: list[str],
rename_paqs_option_dict: dict[str, str],
remove_missing_vals: bool,
paq_val_range: list[int],
custom_iso_names: list[str],
circumplex_angles: list[int],
column_to_filter_by: str = None,
grouped_filter_table: pd.DataFrame | list = None,
):
# try:
if validate_data is True:
data, excl_data = sspy.isd.validate(
data,
paq_aliases={
v: k for k, v in rename_paqs_option_dict.items()
}, # Need to reverse key-val mapping
allow_paq_na=remove_missing_vals,
val_range=paq_val_range,
)
if calc_iso_coords is True:
isopl, isoev = sspy.surveys.processing.calculate_iso_coords(
data,
val_range=paq_val_range,
angles=circumplex_angles,
)
data = add_coords_to_sspy_df(
data,
isopl.round(2),
isoev.round(2),
names=custom_iso_names,
overwrite=True,
)
# except Exception as e:
# mo.stop(True, mo.md(f"data_sspy_setup 1: {e}").callout("danger"))
# try:
if column_to_filter_by is not None and grouped_filter_table is not None:
if len(grouped_filter_table) != 0:
data = data[data[column_to_filter_by].isin(grouped_filter_table)]
column_filter_set = OrderedSet(column_filter)
if len(column_filter_set) >= 1:
data = data[column_filter_set]
for query_filter_element in query_filters:
if query_filter_element != "":
try:
data.query(query_filter_element, inplace=True)
except UndefinedVariableError as e:
mo.md(e)
return data
# except Exception as e:
# mo.stop(True, mo.md(f"data_sspy_setup 2: {e}").callout("danger"))
return add_coords_to_sspy_df, data_sspy_setup
@app.cell
def __(sspy):
def data_description(data_source, data):
if data_source == "isd":
try:
return sspy.isd.soundscapy_describe(data)
except:
return data.describe().round(2)
else:
return data.describe().round(2)
return (data_description,)
@app.cell
def __(Tuple, io, mo, pd, sspy):
def data_loading(
included_data_source_mo, uploaded_file_mo
) -> Tuple[pd.DataFrame, str]:
try:
if included_data_source_mo is None and uploaded_file_mo is None:
mo.md("Need to load some data!").callout("neutral")
return
file_has_been_uploaded = True if uploaded_file_mo.name() else False
if file_has_been_uploaded:
data = pd.read_csv(io.StringIO(uploaded_file_mo.contents().decode()))
data_source = "upload"
elif included_data_source_mo.value in ["SATP", "ARAUS"]:
data = pd.DataFrame()
mo.md("Only ISD has been implemented.").callout("danger")
elif included_data_source_mo.value == "ISD":
data = sspy.isd.load()
data = sspy.surveys.survey_utils.return_paqs(
data,
incl_ids=True,
other_cols=[
"Language",
"Survey_Version",
"start_time",
"end_time",
"latitude",
"longitude",
"ssi01",
"ssi02",
"ssi03",
"ssi04",
"sss01",
"sss02",
"sss03",
"sss04",
"sss05",
"WHO_Sum",
"age00",
"gen00",
"RecordingLength",
"LZeq_L_Max",
"LAeq_L(A)_Max",
"LCeq_L(C)_Max",
"LAeq_L10(A)_Max",
"LAeq_L90(A)_Max",
"N_N5_Max",
"S_S_Max",
"R_R_Max",
"T_TonalityHMS_Max",
"FS_F_Max",
"I_I_Max",
"SIL4_SIL(rms)_Max",
"THD_THD_Max",
],
)
data_source = "isd"
return data, data_source
except Exception as e:
mo.stop(True, mo.md(f"{e}").callout("danger"))
return (data_loading,)
@app.cell
def __(Backend, CircumplexPlot, CircumplexPlotParams, PlotType):
def create_sspy_plot(
data,
custom_iso_names,
plot_type,
plot_title,
seaborn_palette,
seaborn_color,
seaborn_diag_lines,
seaborn_hue,
plotting_backend,
):
circ_params = CircumplexPlotParams(
x=custom_iso_names[0],
y=custom_iso_names[1],
hue=seaborn_hue,
title=plot_title,
palette=seaborn_palette,
incl_outline=True if plot_type == PlotType.SIMPLE_DENSITY else False,
diagonal_lines=seaborn_diag_lines,
)
circ_plot = CircumplexPlot(data, circ_params, Backend(plotting_backend))
return circ_plot._create_plot(plot_type)
return (create_sspy_plot,)
if __name__ == "__main__":
app.run()
|