Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines5678910114 unmodified lines1617181920212223242514 unmodified lines404142434445467 unmodified lines545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798994 unmodified lines1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711723 unmodified lines1761771781791801811821831 unmodified line1851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162176 unmodified lines2242252262272282292302312322332342352362372382392402412422432444 unmodified lines2492502512522532542551 unmodified line2572582592602612622632642652662672682692702712722732742752762772782792802812822832842852864 unmodified lines2912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335343 unmodified lines5385395405415425435445455465475485495505515525535545555565575 unmodified lines5635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786794 unmodified lines# "matplotlib==3.9.2",# "ordered-set==4.1.0",# "pandas==2.2.3",# "quak==0.2.1",# "soundscapy==0.7.6",# ]# ///4 unmodified linesapp = 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 (14 unmodified linesfrom ordered_set import OrderedSetfrom dataclasses import dataclassimport matplotlib.pyplot as pltimport quakreturn (Backend,CircumplexPlot,7 unmodified linesUndefinedVariableError,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",4 unmodified linesjustify="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"),3 unmodified linesmo.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(),1 unmodified line"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(6 unmodified linescustom_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)})4 unmodified linescircumplex_angles = mo.ui.array([mo.ui.number(value=EQUAL_ANGLES[i], label=f"{paq}: ")for i, paq in enumerate(PAQ_IDS)])1 unmodified linecalc_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(4 unmodified linesfor _ 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)3 unmodified lines)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,5 unmodified lines@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__":4 unmodified lines56789104 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474814 unmodified lines6364656667687 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331344 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751763 unmodified lines1801811821831841851861871881891 unmodified line1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982996 unmodified lines3063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393404 unmodified lines3453463473483493503511 unmodified line3533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044 unmodified lines4094104114124134144154164174184194204214224234244254264274284294304314324334344353 unmodified lines4394404414424434444454464474484494504514524534544554564574584594604614624635 unmodified lines4694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337344 unmodified lines# "matplotlib==3.9.2",# "ordered-set==4.1.0",# "pandas==2.2.3",# "soundscapy==0.7.6",# ]# ///4 unmodified linesapp = marimo.App(width="full", app_title="Soundscapy_viz")@app.celldef __():import marimo as momo.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 sspyfrom soundscapy.surveys.survey_utils import (14 unmodified linesfrom ordered_set import OrderedSetfrom dataclasses import dataclassimport matplotlib.pyplot as pltreturn (Backend,CircumplexPlot,7 unmodified linesUndefinedVariableError,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.celldef __(mo):# Data Loadingincluded_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",4 unmodified linesjustify="center",gap=6.0,)return data_load_mo, included_data_source_mo, upload_file_mo@app.celldef __(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.celldef __(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"),3 unmodified linesmo.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(),1 unmodified line"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.celldef __(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.celldef __(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.celldef __(EQUAL_ANGLES, PAQ_IDS, PAQ_LABELS, mo):# Setup marimo inputs for iso parametersvalidate_data_check = mo.ui.checkbox(6 unmodified linescustom_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)})4 unmodified linescircumplex_angles = mo.ui.array([mo.ui.number(value=EQUAL_ANGLES[i], label=f"{paq}: ", debounce=True)for i, paq in enumerate(PAQ_IDS)])1 unmodified linecalc_iso_coords_check,circumplex_angles,custom_iso_names,paq_val_range,remove_missing_vals_option,rename_paqs_option,validate_data_check,)@app.celldef __(mo, raw_data):# Data filtering 1column_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.celldef __(OrderedSet, column_to_filter_by, custom_iso_names, mo, raw_data):# Data filtering 2column_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 filterif 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 = Nonequery_filters = mo.ui.array([mo.ui.text(4 unmodified linesfor _ in range(4)])return column_filter, grouped_filter_table, query_filters@app.celldef __(mo, plot_data):# Setup Seaborn argumentsplot_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)3 unmodified lines)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,5 unmodified lines@app.celldef __(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.celldef __(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.celldef 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 datadef 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 mappingallow_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.celldef __(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.celldef __(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")returnfile_has_been_uploaded = True if uploaded_file_mo.name() else Falseif 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_sourceexcept Exception as e:mo.stop(True, mo.md(f"{e}").callout("danger"))return (data_loading,)@app.celldef __(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.py+474-419