Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344import marimo__generated_with = "0.9.17"app = marimo.App(width="medium")@app.celldef __():import marimo as moimport soundscapy as sspyreturn mo, sspy@app.celldef __(sspy):data = sspy.isd.load()data, excl_data = sspy.isd.validate(data)data = sspy.surveys.add_iso_coords(data)data.head()return data, excl_data@app.celldef __(data, mo):loc = mo.ui.multiselect.from_series(data["LocationID"], value=["CamdenTown"])locreturn (loc,)@app.celldef __(data, loc, sspy):sspy.density_plot(sspy.isd.select_location_ids(data, loc.value), hue="LocationID")return@app.celldef __():returnif __name__ == "__main__":app.run()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680# /// script# requires-python = ">=3.12"# dependencies = [# "marimo",# "matplotlib==3.9.2",# "ordered-set==4.1.0",# "pandas==2.2.3",# "quak==0.2.1",# "soundscapy==0.7.6",# ]# ///import marimo__generated_with = "0.9.19"app = marimo.App(width="full", app_title="Soundscapy_viz")@app.cell(hide_code=True)def __():import marimo as mowith mo.status.spinner(subtitle="Loading ...") as _spinner:import soundscapy as sspyfrom soundscapy.surveys.survey_utils import (EQUAL_ANGLES,PAQ,PAQ_LABELS,PAQ_IDS,)from soundscapy.plotting import (CircumplexPlotParams,CircumplexPlot,PlotType,Backend,)import pandas as pdfrom pandas.errors import UndefinedVariableErrorimport iofrom ordered_set import OrderedSetfrom dataclasses import dataclassimport matplotlib.pyplot as pltimport quakreturn (Backend,CircumplexPlot,CircumplexPlotParams,EQUAL_ANGLES,OrderedSet,PAQ,PAQ_IDS,PAQ_LABELS,PlotType,UndefinedVariableError,dataclass,io,mo,pd,plt,quak,sspy,)@app.celldef __(mo):header_md = mo.md("# Explore one of our datasets or load your own data").center()intro_md = 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.""")return header_md, intro_md@app.celldef __(header_md, mo):app_refresh = mo.ui.refresh(label="Restart Soundscapy_viz")mo.hstack([header_md, app_refresh], gap=6.0, justify="space-around")return (app_refresh,)@app.celldef __(data_loading, intro_md, mo):mo.vstack([mo.hstack([intro_md, data_loading],widths=[5, 3],align="center",justify="center",gap=8.0,),mo.md("---"),],justify="center",gap=6.0,)return@app.celldef __(data_settings, explore_data, mo, p_mo, plot_code, plot_settings):mo.vstack([mo.hstack([data_settings, p_mo, plot_settings], gap=4.0),mo.md("---"),explore_data,plot_code,])# mo.hstack(# [# mo.hstack(# [# data_settings.style(width="500px"),# plot_settings.style(width="350px"),# ],# gap=8.0,# justify="center",# ),# mo.vstack([refresh_button, p._plot, explore_data]),# ],# gap=8.0,# widths="equal",# )# mo.mpl.interactive(p._plot)return@app.celldef __(app_refresh,calc_iso_coords_check,circumplex_angles,column_filter,column_to_filter_by,custom_iso_names,grouped_filter_table,included_data_source,mo,paq_val_range,query_filters,remove_missing_vals_option,rename_paqs_option,uploaded_file,validate_data_check,):app_refresh.valuedata_loading = mo.vstack([mo.md("## Load Data"),included_data_source,uploaded_file,])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,"Filter": 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()}),]),}),])return data_loading, data_settings@app.celldef __(EQUAL_ANGLES, PAQ_IDS, PAQ_LABELS, mo):# Data Loadingincluded_data_source = mo.ui.dropdown(options=["ISD", "SATP", "ARAUS"],value="ISD",label="Select Dataset",full_width=True,)uploaded_file = mo.ui.file(filetypes=[".csv"], kind="area", label="**Load your own data**")# Setup marimo inputs for iso parametersvalidate_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: "),mo.ui.text(value="ISOEventful", label="Y label: "),])paq_val_range = mo.ui.array([mo.ui.number(value=1, step=1, label="PAQ Min value", full_width=True),mo.ui.number(value=5, step=1, label="PAQ Max value", full_width=True),])rename_paqs_option = mo.ui.dictionary({f"{PAQ_IDS[i]}": mo.ui.text(label=f"{PAQ_IDS[i]}: ", value=paq_label)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}: ")for i, paq in enumerate(PAQ_IDS)])return (calc_iso_coords_check,circumplex_angles,custom_iso_names,included_data_source,paq_val_range,remove_missing_vals_option,rename_paqs_option,uploaded_file,validate_data_check,)@app.celldef __(OrderedSet, custom_iso_names, data, mo):# Data filteringcolumn_filter = mo.ui.table(data=list(OrderedSet(list(data.columns)[:4]+ [name for name in custom_iso_names.value]+ list(data.columns)[4:])),page_size=10,)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, query_filters@app.celldef __(included_data_source, io, mo, pd, sspy, uploaded_file):file_has_been_uploaded = True if uploaded_file.name() else Falseif file_has_been_uploaded:data = pd.read_csv(io.StringIO(uploaded_file.contents().decode()))data_source = "upload"elif included_data_source.value in ["SATP", "ARAUS"]:data = pd.DataFrame()mo.md("Only ISD has been implemented.").callout("danger")elif included_data_source.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, file_has_been_uploaded@app.celldef __():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 datareturn (add_coords_to_sspy_df,)@app.celldef __(OrderedSet,UndefinedVariableError,add_coords_to_sspy_df,calc_iso_coords_check,circumplex_angles,column_filter,custom_iso_names,data,mo,paq_val_range,query_filters,remove_missing_vals_option,rename_paqs_option,sspy,validate_data_check,):new_data = data.copy()if validate_data_check.value is True:new_data, excl_data = sspy.isd.validate(new_data,paq_aliases={v: k for k, v in rename_paqs_option.value.items()}, # Need to reverse key-val mappingallow_paq_na=remove_missing_vals_option.value,val_range=paq_val_range.value,)if calc_iso_coords_check.value is True:isopl, isoev = sspy.surveys.processing.calculate_iso_coords(data,val_range=paq_val_range.value,angles=circumplex_angles.value,)new_data = add_coords_to_sspy_df(new_data,isopl.round(2),isoev.round(2),names=custom_iso_names.value,overwrite=True,)column_filter_set = OrderedSet(column_filter.valueif len(column_filter.value) >= 1else column_filter.data)for query_filter_element in query_filters:if query_filter_element.value != "":try:new_data.query(query_filter_element.value, inplace=True)except UndefinedVariableError as e:mo.md(e)new_data = new_data[column_filter_set]data_explorer = mo.ui.data_explorer(new_data)return (column_filter_set,data_explorer,excl_data,isoev,isopl,new_data,query_filter_element,)@app.celldef __(mo, new_data):column_to_filter_by = mo.ui.dropdown(label="Column to filter by:",options=list(new_data.columns),allow_select_none=True,value=None,full_width=True,)return (column_to_filter_by,)@app.celldef __(data_source, plot_data, sspy):if data_source == "isd":try:data_description = sspy.isd.soundscapy_describe(plot_data)except:data_description = plot_data.describe().round(2)else:data_description = plot_data.describe().round(2)return (data_description,)@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.celldef __(data, data_description, data_explorer, mo, plot_data):# show_plot_data = mo.ui.anywidget(quak.Widget(plot_data))show_plot_data = plot_dataexplore_data = mo.ui.tabs({"Data Overview": data_description,"Data": show_plot_data,"Original Data": data,"Explore Data": data_explorer,})return explore_data, show_plot_data@app.celldef __(mo, new_data):# Setup Seaborn argumentsplot_title = mo.ui.text(value="Soundscapy plot", label="Title: ", full_width=True)seaborn_palette = mo.ui.text(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(new_data.columns.tolist(),value=None,allow_select_none=True,label="Split dataset by: ",)plot_type_option = mo.ui.dropdown(["scatter", "density", "simple_density", "joint"],value="density",label="Seaborn plot type: ",)plotting_backend = mo.ui.dropdown(["seaborn", "plotly"], value="seaborn")return (plot_title,plot_type_option,plotting_backend,seaborn_color,seaborn_diag_lines,seaborn_hue,seaborn_palette,)@app.celldef __(mo, new_data, seaborn_hue):if seaborn_hue.value != None:seaborn_loc = mo.ui.multiselect.from_series(new_data[seaborn_hue.value], value=None, label="Select groups: ")return (seaborn_loc,)@app.celldef __(column_to_filter_by, mo, new_data):grouped_filter_table = mo.ui.table(data = list(),page_size=10,)if column_to_filter_by.value is not None:grouped_filter_table = mo.ui.table(data=list(new_data[column_to_filter_by.value].unique()),page_size=10,)return (grouped_filter_table,)@app.celldef __(Backend,CircumplexPlot,CircumplexPlotParams,PlotType,column_to_filter_by,custom_iso_names,grouped_filter_table,mo,new_data,plot_title,plot_type_option,plotting_backend,seaborn_diag_lines,seaborn_hue,seaborn_palette,):plot_data = new_data.copy()if len(column_to_filter_by.value) == 0:plot_data = plot_data.query(f"{column_to_filter_by.value} in {grouped_filter_table.value}")plot_type = PlotType(plot_type_option.value)circ_params = CircumplexPlotParams(x=custom_iso_names.value[0],y=custom_iso_names.value[1],hue=seaborn_hue.value,title=plot_title.value,palette=seaborn_palette.value,incl_outline=True if plot_type == PlotType.SIMPLE_DENSITY else False,diagonal_lines=seaborn_diag_lines.value,)circumplex_plot = CircumplexPlot(plot_data, circ_params, Backend(plotting_backend.value))try:p = circumplex_plot._create_plot(plot_type)p_mo = p._plotexcept NotImplementedError as e:p_mo = mo.md(f"{e}").callout(kind="danger")plot_code = mo.accordion({"Show plot generating code": mo.show_code()})return (circ_params,circumplex_plot,p,p_mo,plot_code,plot_data,plot_type,)@app.celldef __(mo,plot_title,plot_type_option,plotting_backend,seaborn_color,seaborn_diag_lines,seaborn_hue,seaborn_palette,):plot_settings = mo.vstack([mo.md("### Plot Settings"),plot_title,seaborn_palette,seaborn_color,seaborn_diag_lines,seaborn_hue,plot_type_option,plotting_backend,])return (plot_settings,)@app.celldef __():returnif __name__ == "__main__":app.run()
app.py+655-19