-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
1733 lines (1556 loc) · 70.2 KB
/
Copy pathapp.py
File metadata and controls
1733 lines (1556 loc) · 70.2 KB
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
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
769
770
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
# pyrefly: ignore [missing-import]
from shiny import App, render, ui, reactive
import pandas as pd
import io
import re
import sys
import json
import ssl
from pathlib import Path
# --------------------------------------------------------
# Environment setup
# --------------------------------------------------------
IS_WASM = sys.platform == "emscripten"
if not IS_WASM:
ssl._create_default_https_context = ssl._create_unverified_context
# --------------------------------------------------------
# NOTE: duckdb and pyarrow are intentionally NOT imported
# here at module level. They are imported inside the
# reactive effect that first needs them (_load_metadata).
# This means Pyodide will not fetch those heavy wheels
# until the user clicks "Load data", so the UI becomes
# interactive much sooner on first load.
# --------------------------------------------------------
# --------------------------------------------------------
# HTTP fetch helper — works in both WASM and native
# --------------------------------------------------------
def _http_get(url: str, headers: dict | None = None) -> bytes:
"""Fetch a URL and return raw bytes. Works in WASM and native."""
if IS_WASM:
# pyrefly: ignore [missing-import]
import js
xhr = js.XMLHttpRequest.new()
xhr.open("GET", url, False) # synchronous
if headers:
for k, v in headers.items():
xhr.setRequestHeader(k, v)
xhr.responseType = "arraybuffer"
xhr.send(None)
if xhr.status not in (200, 206):
raise RuntimeError(f"HTTP {xhr.status} fetching {url}")
return bytes(xhr.response.to_py())
else:
import urllib.request
req = urllib.request.Request(url, headers=headers or {})
with urllib.request.urlopen(req) as resp:
return resp.read()
def fetch_parquet_as_arrow(url: str):
"""Download a full Parquet file and return a PyArrow Table."""
# pyrefly: ignore [missing-import]
import pyarrow.parquet as pq
buf = io.BytesIO(_http_get(url))
return pq.read_table(buf)
def fetch_json(url: str) -> dict:
"""Download and parse a JSON file."""
raw = _http_get(url)
return json.loads(raw.decode("utf-8"))
# --------------------------------------------------------
# Load local CSVs once at startup (cheap — no parquet)
# --------------------------------------------------------
try:
csv_path = Path(__file__).parent / "input" / "ossl_individual_datasets_urls_v1.3.csv"
urls_df = pd.read_csv(csv_path)
except Exception as e:
print(f"Error reading URL list: {e}")
urls_df = pd.DataFrame()
try:
overview_path = Path(__file__).parent / "input" / "ossl_listed_libraries_overview.csv"
overview_df = pd.read_csv(overview_path)
except Exception as e:
print(f"Error reading overview CSV: {e}")
overview_df = pd.DataFrame()
# --------------------------------------------------------
# Metadata JSON — loaded once at startup.
# The JSON lives next to app.py (or on your bucket).
# If it cannot be found/fetched the app falls back to
# the old behaviour of fetching column names from parquet.
# --------------------------------------------------------
_METADATA_JSON_PATH = Path(__file__).parent / "ossl_metadata.json"
_METADATA_JSON_URL = None # set this if hosting on a bucket, e.g.:
# _METADATA_JSON_URL = "https://storage.googleapis.com/your-bucket/ossl_metadata.json"
def _load_metadata_json() -> dict | None:
"""Try to load ossl_metadata.json from disk or remote URL."""
# 1. Local file (fastest, works in native and WASM if bundled)
if _METADATA_JSON_PATH.exists():
try:
with open(_METADATA_JSON_PATH) as f:
data = json.load(f)
print(f"Metadata JSON loaded from disk ({len(data.get('datasets', {}))} datasets)")
return data
except Exception as e:
print(f"Could not parse local metadata JSON: {e}")
# 2. Remote URL
if _METADATA_JSON_URL:
try:
data = fetch_json(_METADATA_JSON_URL)
print(f"Metadata JSON loaded from URL ({len(data.get('datasets', {}))} datasets)")
return data
except Exception as e:
print(f"Could not fetch remote metadata JSON: {e}")
print("No metadata JSON found — will fall back to parquet schema fetching")
return None
METADATA = _load_metadata_json() # None if not available
# Populate dataset_codes from metadata if available, otherwise from CSV
if METADATA and "datasets" in METADATA:
dataset_codes = sorted(METADATA["datasets"].keys())
else:
if not urls_df.empty and "dataset_code" in urls_df.columns:
dataset_codes = sorted(urls_df["dataset_code"].unique().tolist())
else:
dataset_codes = []
# --------------------------------------------------------
# Small pure-Python helpers
# --------------------------------------------------------
def _is_spectral(col_name: str) -> bool:
"""Return True if col_name is a numeric string (a spectral band)."""
try:
float(col_name)
return True
except (ValueError, TypeError):
return False
def _make_spectrum_svg(df: pd.DataFrame) -> str | None:
"""
Build a lightweight inline SVG showing the mean spectrum ± 1 std.
Uses only pandas/numpy — no matplotlib, no extra imports.
Returns None if there are no spectral columns.
"""
import numpy as np
spec_cols = sorted(
[c for c in df.columns if _is_spectral(c)],
key=float,
)
if not spec_cols:
return None
xs = [float(c) for c in spec_cols]
arr = df[spec_cols].to_numpy(dtype=float)
ys_mean = np.nanmean(arr, axis=0)
ys_std = np.nanstd(arr, axis=0)
n_rows = arr.shape[0]
W, H, PX, PY = 600, 160, 36, 16 # viewBox dims and padding
x_min, x_max = min(xs), max(xs)
y_vals_all = list(ys_mean - ys_std) + list(ys_mean + ys_std)
y_min = min(v for v in y_vals_all if not (v != v)) # skip NaN
y_max = max(v for v in y_vals_all if not (v != v))
y_rng = y_max - y_min or 1.0
x_rng = x_max - x_min or 1.0
def sx(v): return PX + (v - x_min) / x_rng * (W - 2 * PX)
def sy(v): return H - PY - (v - y_min) / y_rng * (H - 2 * PY)
# Std envelope (upper then lower reversed = closed polygon)
upper = [(sx(x), sy(m + s)) for x, m, s in zip(xs, ys_mean, ys_std)]
lower = [(sx(x), sy(m - s)) for x, m, s in zip(xs, ys_mean, ys_std)]
envelope_pts = " ".join(f"{x:.1f},{y:.1f}" for x, y in upper + lower[::-1])
# Mean line
mean_pts = " ".join(f"{sx(x):.1f},{sy(y):.1f}" for x, y in zip(xs, ys_mean))
# Axis tick labels (x-axis: 5 ticks, y-axis: 3 ticks)
x_ticks = [x_min + i * x_rng / 4 for i in range(5)]
y_ticks = [y_min, (y_min + y_max) / 2, y_max]
x_tick_svg = "".join(
f'<text x="{sx(v):.1f}" y="{H - 2}" text-anchor="middle" '
f'font-size="10" fill="#888">{v:.0f}</text>'
for v in x_ticks
)
y_tick_svg = "".join(
f'<text x="{PX - 4}" y="{sy(v):.1f}" text-anchor="end" '
f'dominant-baseline="central" font-size="10" fill="#888">{v:.3f}</text>'
for v in y_ticks
)
return f"""
<div style="margin-top:8px">
<div style="font-size:11px;color:#888;margin-bottom:2px">
Mean spectrum (n={n_rows:,}). Shaded area = ±1 SD.
</div>
<svg viewBox="0 0 {W} {H}" width="100%"
style="display:block;border-radius:6px;background:#fafafa">
<!-- std envelope -->
<polygon points="{envelope_pts}"
fill="#667eea" fill-opacity="0.15" stroke="none"/>
<!-- mean line -->
<polyline points="{mean_pts}"
fill="none" stroke="#667eea" stroke-width="1.5"
stroke-linejoin="round" stroke-linecap="round"/>
<!-- axis lines -->
<line x1="{PX}" y1="{PY}" x2="{PX}" y2="{H-PY}"
stroke="#ddd" stroke-width="0.8"/>
<line x1="{PX}" y1="{H-PY}" x2="{W-PX}" y2="{H-PY}"
stroke="#ddd" stroke-width="0.8"/>
{x_tick_svg}
{y_tick_svg}
</svg>
</div>
"""
# --------------------------------------------------------
# UI helpers shared across tabs
# --------------------------------------------------------
def _premium_card(*children, title: str | None = None):
inner = []
if title:
inner.append(ui.div(title, class_="section-title"))
inner.extend(children)
return ui.div(*inner, class_="premium-card")
# --------------------------------------------------------
# Tab: Explore
# --------------------------------------------------------
data_overview_content = ui.div(
_premium_card(
ui.p(
"The ",
ui.tags.a("Open Soil Spectral Library (OSSL)",
href="https://docs.soilspectroscopy.org/", target="_blank"),
" is a global compilation of soil spectral datasets paired with "
"reference laboratory measurements, assembled from contributions "
"worldwide and made freely available for research and modelling.",
),
ui.p(
"All datasets share a common structure with three linked tables: ",
ui.tags.b("Soilsite"), " (sampling location and date), ",
ui.tags.b("Soillab"), " (measured soil properties), and ",
ui.tags.b("Spectra"), " (raw absorbance or reflectance values across "
"NIR, VisNIR, or MIR ranges at evenly spaced intervals).",
),
ui.p(
"Use the tabs above to work through the workflow: browse the available "
"datasets here, then go to ",
ui.tags.b("Prepare"), " to filter, join, and export a dataset tailored "
"to your needs. If you have your own spectra, use ",
ui.tags.b("My Data"), " to resample them to a standard interval. "
"Finally, open ",
ui.tags.b("Analyse"), " to launch one of the mdatools chemometric apps "
"directly in your browser.",
),
ui.p(
"For full details on each dataset, including collection protocols and "
"license information, see the ",
ui.tags.a("'Soil spectral libraries' section",
href="https://docs.soilspectroscopy.org/libraries.html",
target="_blank"),
" of the OSSL Manual.",
),
),
_premium_card(
ui.output_data_frame("datasets_overview_table"),
title="Available datasets",
),
)
# --------------------------------------------------------
# Tab: Prepare
# --------------------------------------------------------
data_selection_content = ui.div(
# 1. Data Selection
_premium_card(
ui.layout_columns(
ui.input_select("dataset_code", "Dataset code",
choices=dataset_codes, width="100%"),
ui.output_ui("spectra_selector"),
ui.input_action_button("load_metadata", "Load data",
class_="btn-premium w-100 mt-4"),
col_widths=(4, 4, 4),
),
title="1. Select dataset and spectral region",
),
# 2. Soil properties
_premium_card(
ui.p("Select a soil property (or many). Rows with no valid values for the "
"selected property will be automatically removed.",
class_="text-muted small"),
ui.output_ui("lab_column_selector"),
ui.layout_columns(
ui.div(
ui.input_radio_buttons(
"transform_type", "Apply transformation (optional)",
choices={"none": "No transformation",
"sqrt": "Square root (sqrt)",
"log1p": "Log(1+x)"},
selected="none", inline=True,
),
ui.input_action_button("run_soil_only", "Preview",
class_="btn-premium w-100 mb-2"),
),
ui.div(
ui.p("Summary statistics of selected properties"),
ui.output_table("summary_stats_table"),
),
col_widths=(3, 6),
),
title="2. Soil properties",
),
# 3 & 4. Advanced filtering — collapsible
ui.div(
ui.tags.details(
ui.tags.summary(
ui.span("3 & 4. Advanced filtering (optional) — site & spectral metadata",
style="font-size:1rem;font-weight:600;color:#4a5568;cursor:pointer;"),
style="list-style:none;display:flex;align-items:center;gap:8px;"
"padding:14px 20px;border-radius:12px;"
"background:white;border:1px solid #e9ecef;"
"box-shadow:0 4px 6px rgba(0,0,0,0.05);",
),
# 3. Site filtering
ui.div(
_premium_card(
ui.layout_columns(
ui.div(
ui.p("Select site columns to filter. Leave empty to keep all rows.",
class_="text-muted small"),
ui.output_ui("site_column_selector"),
),
ui.div(
ui.p("Highlight the values to keep", class_="text-muted small"),
ui.output_ui("site_level_filters"),
),
col_widths=(6, 6),
),
ui.input_action_button("run_soil_site", "Recalculate statistics",
class_="btn-premium w-25 mt-2"),
title="3. Site filtering",
),
# 4. Spectral metadata filtering
_premium_card(
ui.layout_columns(
ui.div(
ui.p("Select columns to filter. Leave empty to keep all rows.",
class_="text-muted small"),
ui.output_ui("spec_column_selector"),
),
ui.div(
ui.p("Highlight the unique values to keep.",
class_="text-muted small"),
ui.output_ui("spec_level_filters"),
),
col_widths=(6, 6),
),
title="4. Spectral metadata filtering (when available)",
),
style="margin-top:8px;",
),
),
style="margin-bottom:20px;",
),
# 5. Join & Export
_premium_card(
ui.layout_columns(
ui.div(
ui.input_text("id_col", "Common ID column",
value="id.layer_local_c", width="100%"),
ui.input_select(
"spec_interval", "Spectral resolution",
choices={"2": "Every 2 units (nm or cm⁻¹)", "10": "Every 10 units (nm or cm⁻¹)"},
selected="2", width="100%",
),
ui.layout_columns(
ui.input_numeric("spec_min", "Min (nm or cm⁻¹)", value=0),
ui.input_numeric("spec_max", "Max (nm or cm⁻¹)", value=10000),
col_widths=(6, 6),
),
ui.input_select(
"join_type", "Join type",
choices={"inner": "Only data with spectra",
"full": "Keep all data, add spectra where available"},
selected="inner", width="100%",
),
ui.input_action_button("run_join", "Join with available spectra",
class_="btn-premium w-100 mb-3"),
ui.output_ui("export_column_selector"),
ui.input_text("dl_filename", "Filename to save",
value="ossl_filtered_data.csv", width="100%"),
ui.download_button("download_csv", "Download processed dataset",
class_="btn-success-premium w-100"),
),
ui.div(
ui.output_ui("spectrum_preview"), # inline SVG — above the table
ui.div(style="height:14px;"), # breathing room
ui.output_data_frame("preview_table"),
),
col_widths=(3, 9),
),
title="5. Join spectra & export",
),
# 6. Subsetting (shown only after a join)
ui.output_ui("subsetting_panel"),
)
# --------------------------------------------------------
# Tab: Formatting
# --------------------------------------------------------
_SAMPLE_FILES = {
"sample_visnir_data.csv": (
"https://raw.githubusercontent.com/soilspectroscopy/ossl-models"
"/main/sample-data/sample_visnir_data.csv"
),
"sample_mir_data.csv": (
"https://raw.githubusercontent.com/soilspectroscopy/ossl-models"
"/main/sample-data/sample_mir_data.csv"
),
"sample_neospectra_data.csv": (
"https://raw.githubusercontent.com/soilspectroscopy/ossl-models"
"/main/sample-data/sample_neospectra_data.csv"
),
}
formatting_content = ui.div(
_premium_card(
ui.p(
"Use this tab to resample your own spectral CSV to a standard "
"OSSL-compatible interval (2 or 10 nm / cm⁻¹) before uploading it "
"to one of the ", ui.tags.b("Chemometrics"), " tools. "
"No preprocessing is applied — only the spectral axis is resampled "
"via linear interpolation.",
),
ui.tags.ul(
ui.tags.li(
"The ", ui.tags.b("first column"), " is always treated as the "
"sample ID and kept as-is."
),
ui.tags.li(
"Spectral columns are detected automatically as any column "
"whose name is a plain number (e.g. 400, 402.5, 4000)."
),
ui.tags.li(
"Columns may be in any order (increasing or decreasing). "
"The exported file always uses ", ui.tags.b("increasing order"),
" regardless of the input."
),
),
ui.p("Download example files to test the workflow:",
class_="mb-1 mt-3 fw-semibold"),
ui.div(
ui.download_button("dl_sample_visnir", "sample_visnir_data.csv",
class_="btn btn-sample me-2 mb-1"),
ui.download_button("dl_sample_mir", "sample_mir_data.csv",
class_="btn btn-sample me-2 mb-1"),
ui.download_button("dl_sample_neospectra","sample_neospectra_data.csv",
class_="btn btn-sample me-2 mb-1"),
),
title="Resample your own spectral data",
),
_premium_card(
ui.layout_columns(
ui.div(
ui.input_file("fmt_file", "Upload CSV file",
accept=[".csv"], width="100%"),
ui.input_select(
"fmt_interval", "Target resolution",
choices={"2": "Every 2 units (nm or cm⁻¹)",
"10": "Every 10 units (nm or cm⁻¹)"},
selected="2", width="100%",
),
ui.layout_columns(
ui.input_numeric("fmt_min", "Min (nm or cm⁻¹)",
value=None),
ui.input_numeric("fmt_max", "Max (nm or cm⁻¹)",
value=None),
col_widths=(6, 6),
),
ui.p("Leave min/max blank to use the full range of your file.",
class_="text-muted small"),
ui.input_action_button("fmt_run", "Resample",
class_="btn-premium w-100 mt-2"),
),
ui.div(
ui.output_ui("fmt_preview"),
),
col_widths=(4, 8),
),
ui.div(
ui.output_ui("fmt_download_ui"),
class_="mt-3",
),
title="Settings",
),
)
# --------------------------------------------------------
# Tab: Chemometrics
# --------------------------------------------------------
chemometrics_content = ui.div(
_premium_card(
ui.h3("mdatools: make chemometrics easy"),
ui.p("Development and credits: ",
ui.tags.a("Sergey Kucheryavskiy",
href="https://github.com/svkucheryavski", target="_blank"), "."),
ui.p("Try most common chemometric methods directly in your browser. "
"All calculations run on your local computer."),
ui.p("Check video tutorials at ",
ui.tags.a("youtube.com/@mdatools",
href="https://www.youtube.com/@mdatools", target="_blank"),
". For more information visit the ",
ui.tags.a("mdatools website", href="https://mdatools.com", target="_blank"), "."),
ui.hr(),
ui.p("Download your processed dataset from the 'Prepare' tab, then open "
"one of the tools below in a new tab to begin your analysis."),
ui.layout_columns(
ui.a("Spectral visualization and preprocessing",
href="https://mdatools.com/prep/", target="_blank",
class_="btn-success-premium w-100 text-center",
style="text-decoration:none;padding:15px;"),
ui.a("Principal components analysis (PCA)",
href="https://mdatools.com/pca/", target="_blank",
class_="btn-success-premium w-100 text-center",
style="text-decoration:none;padding:15px;"),
ui.a("Partial least squares regression (PLSR)",
href="https://mdatools.com/pls/", target="_blank",
class_="btn-success-premium w-100 text-center",
style="text-decoration:none;padding:15px;"),
col_widths=(4, 4, 4),
class_="mt-3 mb-4",
),
ui.p("Features:"),
ui.tags.ul(
ui.tags.li("Spectral visualization and preprocessing"),
ui.tags.ul(
ui.tags.li("Original spectra visualization."),
ui.tags.li("Savitzky-Golay filter and derivatives."),
ui.tags.li("Normalization via SNV, area, length, and variable."),
ui.tags.li("Scaling, baseline correction, spike removal."),
),
ui.tags.li("Principal components analysis (PCA)"),
ui.tags.li("Partial least squares regression (PLSR)"),
),
ui.p("For the ", ui.tags.b("PLSR tool"), " use these CSV settings:"),
ui.tags.ul(
ui.tags.li(ui.tags.b("Delimiter: "), "`,`"),
ui.tags.li(ui.tags.b("Row labels: "), "`yes`"),
ui.tags.li(ui.tags.b("Header: "), "`values`"),
ui.tags.li(ui.tags.b("Header name (predictors): "), "`wavelength` or `wavenumber`"),
ui.tags.li(ui.tags.b("Header units (predictors): "), "`nm` or `cm`"),
),
),
)
# --------------------------------------------------------
# Tab: About
# --------------------------------------------------------
about_content = ui.div(
_premium_card(
ui.h3("About this app"),
ui.p("This application was developed to streamline the processing of the "
"Open Soil Spectral Library (OSSL) for chemometric modeling."),
ui.p(ui.a("Soil Spectroscopy for Global Good",
href="https://soilspectroscopy.org/", target="_blank"),
" was founded by Woodwell Climate Research Center, University of "
"Florida and OpenGeoHub in 2020."),
ui.p("Originally funded by the USDA National Institute of Food and "
"Agriculture Award #2020-67021-32467."),
ui.p("Currently maintained by Fund for Climate Solutions from Woodwell Climate."),
ui.p("For questions, suggestions, bug reports, and inquiries: "),
ui.p(ui.a("soilspec4gg@woodwellclimate.org", href="mailto:soilspec4gg@woodwellclimate.org", target="_blank")),
ui.hr(),
ui.markdown("""
### Credits & data sources
* **Data:** [Open Soil Spectral Library (OSSL)](https://docs.soilspectroscopy.org/)
* **Engine:** Powered by [DuckDB](https://duckdb.org/) and [Shiny for Python](https://shiny.posit.co/py/)
* **Chemometrics:** Integration with [mdatools](https://mdatools.com/)
"""),
ui.hr(),
ui.h3("Citation"),
ui.markdown("""
If you use data from this platform in your work, please cite the OSSL:
Safanelli, J. L., Hengl, T., Parente, L. L., Minarik, R., Bloom, D. E.,
Todd-Brown, K., Gholizadeh, A., Mendes, W. de S., & Sanderman, J. (2025).
Open Soil Spectral Library (OSSL): Building reproducible soil calibration
models through open development and community engagement.
*PLOS ONE*, 20(1), e0296545. https://doi.org/10.1371/journal.pone.0296545
"""),
ui.p("Version: 1.4 | Updated: May 2026", class_="text-muted mt-4"),
),
)
# --------------------------------------------------------
# App UI
# --------------------------------------------------------
app_ui = ui.page_fluid(
ui.tags.head(ui.tags.style("""
body { font-family: 'Inter', sans-serif; background-color: #f8f9fa; }
.premium-card {
background: white; border-radius: 12px; padding: 20px;
box-shadow: 0 4px 6px rgba(0,0,0,0.05);
margin-bottom: 20px; border: 1px solid #e9ecef;
}
.btn-premium {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white; border: none; font-weight: 600;
padding: 10px 20px; border-radius: 8px; transition: transform 0.2s;
}
.btn-premium:hover { transform: translateY(-2px); color: white; opacity: 0.9; }
.btn-success-premium {
background: linear-gradient(135deg, #20bf55 0%, #01baef 100%);
color: white; border: none; font-weight: 600;
padding: 10px 20px; border-radius: 8px;
}
.section-title {
font-size: 1.1rem; font-weight: 600; color: #4a5568;
margin-bottom: 1rem; border-bottom: 2px solid #e2e8f0;
padding-bottom: 0.5rem;
}
.subset-panel {
border: 2px dashed #667eea; border-radius: 12px;
padding: 20px; margin-bottom: 20px; background: #f5f4ff;
}
/* Workflow banner */
.workflow-banner {
background: linear-gradient(135deg, #f0f4ff 0%, #f5f0ff 100%);
border: 1px solid #d6d0f5; border-radius: 12px;
padding: 14px 24px; margin-bottom: 18px;
display: flex; align-items: center; justify-content: center;
flex-wrap: wrap; gap: 0; font-size: 0.88rem; color: #4a5568;
}
.workflow-step {
display: flex; align-items: center; gap: 6px;
}
.workflow-step .step-num {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white; border-radius: 50%; width: 22px; height: 22px;
display: inline-flex; align-items: center; justify-content: center;
font-size: 0.75rem; font-weight: 700; flex-shrink: 0;
}
.workflow-step .step-label { font-weight: 600; color: #2c3e50; }
.workflow-arrow {
margin: 0 10px; color: #a0aec0; font-size: 1rem;
}
/* Advanced filtering disclosure */
.adv-filter-toggle {
background: none; border: none; color: #667eea; font-size: 0.88rem;
font-weight: 600; cursor: pointer; padding: 4px 0;
display: flex; align-items: center; gap: 4px;
}
.adv-filter-toggle:hover { color: #764ba2; }
/* Sample download buttons — teal outline */
.btn-sample {
border: 1.5px solid #1d9e75 !important; color: #0f6e56 !important;
background: white !important; border-radius: 8px !important;
font-size: 12px; font-weight: 600; padding: 5px 12px;
transition: background 0.15s;
}
.btn-sample:hover {
background: #e1f5ee !important; color: #085041 !important;
}
""")),
ui.div(
ui.img(src="https://raw.githubusercontent.com/soilspectroscopy/ossl-imports"
"/main/img/soilspec4gg-logo_square.png",
style="height:60px;margin-right:15px;vertical-align:middle;"),
ui.h2("Chemometrics with the OSSL",
style="display:inline-block;vertical-align:middle;"
"margin-top:15px;font-weight:700;color:#2c3e50;"),
class_="text-center mb-4 mt-3",
),
ui.div(
ui.div(
ui.div(
ui.span("1", class_="step-num"),
ui.span("Overview", class_="step-label"),
ui.span("listed libraries", style="color:#718096"),
class_="workflow-step",
),
ui.span("→", class_="workflow-arrow"),
ui.div(
ui.span("2", class_="step-num"),
ui.span("Prepare", class_="step-label"),
ui.span("filter, join & export your extract", style="color:#718096"),
class_="workflow-step",
),
ui.span("→", class_="workflow-arrow"),
ui.div(
ui.span("3", class_="step-num"),
ui.span("My Data", class_="step-label"),
ui.span("resample your own spectra (optional)", style="color:#718096"),
class_="workflow-step",
),
ui.span("→", class_="workflow-arrow"),
ui.div(
ui.span("4", class_="step-num"),
ui.span("Analyse", class_="step-label"),
ui.span("open mdatools in a new tab", style="color:#718096"),
class_="workflow-step",
),
class_="workflow-banner",
),
style="padding: 0 0 4px 0;",
),
ui.navset_tab(
ui.nav_panel("Overview", data_overview_content),
ui.nav_panel("Prepare", data_selection_content),
ui.nav_panel("My Data", formatting_content),
ui.nav_panel("Analyse", chemometrics_content),
ui.nav_panel("About", about_content),
),
ui.div(
ui.hr(),
ui.p("© 2026 Soil Spectroscopy for Global Good. Distributed under MIT License."),
ui.p("Data provided by the OSSL may be subject to individual dataset licenses. "
"Please cite the original authors."),
ui.p(
ui.a("OSSL Manual", href="https://docs.soilspectroscopy.org/",
target="_blank", style="color:#667eea;margin-right:16px;"),
ui.a("GitHub", href="https://github.com/soilspectroscopy",
target="_blank", style="color:#667eea;margin-right:16px;"),
ui.a("mdatools", href="https://mdatools.com",
target="_blank", style="color:#667eea;"),
style="margin-top:4px;font-size:0.88rem;",
),
class_="footer",
style="text-align:center;padding:16px 0 24px;color:#718096;font-size:0.85rem;",
),
)
# --------------------------------------------------------
# Server
# --------------------------------------------------------
def server(input, output, session):
# ---- Reactive state ------------------------------------------------
site_cols_rv = reactive.Value([])
lab_cols_rv = reactive.Value([])
spec_cols_rv = reactive.Value([]) # spectral *metadata* cols only
unique_site_levels = reactive.Value({})
unique_spec_levels = reactive.Value({})
joined_data = reactive.Value(None)
fmt_result = reactive.Value(None) # for Formatting tab
# Cached Arrow tables (avoid re-downloading within a session)
site_arrow = reactive.Value(None)
lab_arrow = reactive.Value(None)
spec_arrow = reactive.Value(None)
# DuckDB connection — created on first "Load data" click
con_rv = reactive.Value(None)
# ---- Explore tab ---------------------------------------------------
@render.data_frame
def datasets_overview_table():
if overview_df.empty:
return render.DataGrid(pd.DataFrame({"Status": ["Could not load dataset list."]}))
cols = ["new_code", "description", "extent", "sample_size", "spectral_range"]
available = [c for c in cols if c in overview_df.columns]
if not available:
return render.DataGrid(pd.DataFrame({"Status": ["Expected columns not found."]}))
display = (
overview_df[available]
.drop_duplicates()
.reset_index(drop=True)
.rename(columns={
"new_code": "Dataset code",
"description": "Description",
"extent": "Extent",
"sample_size": "Sample size",
"spectral_range": "Spectral range",
})
)
return render.DataGrid(display, width="100%", height="400px", filters=True)
# ---- Spectra type selector -----------------------------------------
@render.ui
def spectra_selector():
d_code = input.dataset_code()
if not d_code:
return ui.p("Select a dataset first.")
# Fast path: use metadata JSON
if METADATA and d_code in METADATA.get("datasets", {}):
types = METADATA["datasets"][d_code].get("spectra_types", [])
else:
if urls_df.empty:
return ui.p("No dataset information available.")
subset = urls_df[urls_df["dataset_code"] == d_code]
types = []
for fname in subset["ossl_file"]:
if "_mir_" in fname.lower(): types.append("mir")
if "_visnir_" in fname.lower(): types.append("visnir")
elif "_nir_" in fname.lower(): types.append("nir")
types = list(set(types))
return ui.input_select("spectra_type", "Spectra type",
choices=sorted(types), width="100%")
# ---- Load metadata (deferred heavy imports) -------------------------
@reactive.Effect
@reactive.event(input.load_metadata)
def _load_metadata():
# Heavy imports deferred until here — Pyodide fetches the wheels
# only on first click, after the UI is already interactive.
import duckdb # pyrefly: ignore [missing-import]
# ---- Reset all filters / results from any previous dataset --------
site_cols_rv.set([])
lab_cols_rv.set([])
spec_cols_rv.set([])
unique_site_levels.set({})
unique_spec_levels.set({})
joined_data.set(None)
# # Clear the multi-select inputs so stale values don't linger in the UI
# ui.update_selectize("site_cols", choices=[], selected=[])
# ui.update_selectize("lab_cols", choices=[], selected=[])
# ui.update_selectize("spec_cols", choices=[], selected=[])
# -------------------------------------------------------------------
d_code = input.dataset_code()
s_type = input.spectra_type()
if not d_code or not s_type:
ui.notification_show("Select dataset and spectra type.", type="warning")
return
# Resolve URLs
if METADATA and d_code in METADATA.get("datasets", {}):
ds = METADATA["datasets"][d_code]
site_url = ds["files"].get("soilsite", {}).get("url")
lab_url = ds["files"].get("soillab", {}).get("url")
spec_url = ds["files"].get(s_type, {}).get("url")
else:
# Fallback: derive URLs from the CSV
subset = urls_df[urls_df["dataset_code"] == d_code]
def _first_url(mask):
rows = subset[mask & subset["ossl_file"].str.contains(".parquet")]
return rows["public_url"].values[0] if len(rows) else None
site_url = _first_url(subset["ossl_file"].str.contains("soilsite"))
lab_url = _first_url(subset["ossl_file"].str.contains("soillab"))
spec_url = _first_url(subset["ossl_file"].str.contains(f"_{s_type}_"))
if not all([site_url, lab_url, spec_url]):
ui.notification_show("Could not resolve URLs for site, lab, or spectra.",
type="error")
return
con = duckdb.connect(":memory:")
with ui.Progress(min=1, max=4) as p:
try:
p.set(1, message="Downloading site data…")
s_table = fetch_parquet_as_arrow(site_url)
con.register("site_view", s_table)
site_arrow.set(s_table)
p.set(2, message="Downloading lab data…")
l_table = fetch_parquet_as_arrow(lab_url)
con.register("lab_view", l_table)
lab_arrow.set(l_table)
p.set(3, message="Downloading spectra data…")
sp_table = fetch_parquet_as_arrow(spec_url)
con.register("spec_view", sp_table)
spec_arrow.set(sp_table)
# Populate column lists
# Fast path: read from metadata JSON (no parquet schema parse needed)
if METADATA and d_code in METADATA.get("datasets", {}):
ds = METADATA["datasets"][d_code]
s_cols = sorted(ds["files"].get("soilsite", {}).get("columns", []))
l_cols = sorted(ds["files"].get("soillab", {}).get("columns", []))
sp_meta = sorted(ds["files"].get(s_type, {}).get("meta_columns", []))
sp_info = ds["files"].get(s_type, {})
scan_min = sp_info.get("scan_min")
scan_max = sp_info.get("scan_max")
else:
# Fallback: derive from Arrow schema
s_cols = sorted(s_table.schema.names)
l_cols = sorted(l_table.schema.names)
sp_names = sp_table.schema.names
scan_vals = []
for c in sp_names:
if str(c).startswith("scan_"):
num = re.sub(r"^scan_.*?\.", "", str(c))
num = re.sub(r"_(abs|ref|bc\.abs)$", "", num)
try: scan_vals.append(float(num))
except: pass
scan_min = min(scan_vals) if scan_vals else None
scan_max = max(scan_vals) if scan_vals else None
skip = {"id.layer_local_c","id.scan_local_c",
"id.layer_uuid_c","id.layer_uuid"}
sp_meta = sorted(
c for c in sp_names
if not str(c).startswith("scan_") and c not in skip
)
if scan_min is not None:
ui.update_numeric("spec_min", value=scan_min)
if scan_max is not None:
ui.update_numeric("spec_max", value=scan_max)
site_cols_rv.set(s_cols)
lab_cols_rv.set(l_cols)
spec_cols_rv.set(sp_meta)
# Store connection in a reactive value so other effects can read it
con_rv.set(con)
p.set(4, message="Done!")
ui.notification_show("Metadata loaded successfully!", type="message")
except Exception as e:
import traceback
ui.notification_show(f"Error loading metadata: {traceback.format_exc()}",
type="error", duration=20)
def _get_con():
"""Return the DuckDB connection, or None if not yet loaded."""
return con_rv()
# ---- Column selector UIs -------------------------------------------
@render.ui
def site_column_selector():
cols = site_cols_rv()
if not cols:
return ui.p("Load metadata first.", class_="text-muted")
return ui.input_selectize("site_cols", "Site columns",
choices=cols, multiple=True, width="100%")
@render.ui
def lab_column_selector():
cols = lab_cols_rv()
if not cols:
return ui.p("Load dataset contents first.", class_="text-muted")
return ui.input_selectize("lab_cols", "Columns",
choices=cols, selected=cols[:1],
multiple=True, width="100%")
@render.ui
def spec_column_selector():
cols = spec_cols_rv()
if not cols:
return ui.p("No metadata available.", class_="text-muted")
return ui.input_selectize("spec_cols", "Columns",
choices=cols, multiple=True, width="100%")
# ---- Site level filtering ------------------------------------------
@reactive.Effect
@reactive.event(input.site_cols)
def _fetch_site_levels():
selected = input.site_cols()
if not selected:
unique_site_levels.set({})
return
con = _get_con()
if con is None:
return
levels = {}
cat_cols = [c for c in selected
if c.endswith(("_c","_txt","_uint16","_id","_logical","_code"))]
if cat_cols:
with ui.Progress(min=1, max=len(cat_cols)) as p:
p.set(message="Extracting site levels…")
for col in cat_cols:
try:
res = con.execute(