-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathml_utils.py
More file actions
3565 lines (3013 loc) · 129 KB
/
Copy pathml_utils.py
File metadata and controls
3565 lines (3013 loc) · 129 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
# --- required packages
from __future__ import annotations
import numpy as np
import pandas as pd
import xarray as xr
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.feature as cfeature
def _require_keras():
try:
import importlib
tf = importlib.import_module("tensorflow")
# you can use tf.keras.* everywhere; no need to import keras separately
return tf
except Exception as e:
raise ImportError(
"TensorFlow/Keras required for this function. "
"Install with `pip install tensorflow` or `yourpkg[cnn]`."
) from e
def time_series_split(
data: xr.Dataset,
num_var,
cat_var=None,
mask="ocean_mask",
split_ratio=(0.7, 0.2, 0.1),
seed=42,
X_mean=None,
X_std=None,
y_var="y",
years=None, # select one year, a list of years, or a slice
cast_float32=True,
contiguous_splits=False,
return_full=False,
nan_max_frac_y=0.5, # what fraction of missing days allowed in y
nan_max_frac_v=0.05, # what fraction of missing days allowed in numerical vars
add_missingness=False,
verbose=False
):
"""
Pure-NumPy splitter/normalizer for xarray Dataset (NumPy-backed).
Splits time indices randomly into train/val/test.
Normalizes numerical variables only, using either provided or training-set mean/std.
Replaces NaNs with 0s.
Removes days with too many NaNs (>
Parameters:
data: xarray dataset with 'time' dimension
years: year(s) to use for training
num_var: list of numerical variable names (to normalize)
cat_var: list of categorical variable names (no normalization)
y_var: name of response variable in data.
mask: name of the mask in the data. 0 = ignore; 1 = use; can be static or one for each time step (y)
split_ratio: tuple (train, val, test), must sum to 1.0
seed: random seed
nan_max_frac_y: maximum percent missing values for response
nan_max_frac_v: maximum percent missing values for explanatory variables
X_mean, X_std: optional mean/std arrays for num_var only (shape = [n_num_vars])
cast_float32 : If True, cast outputs to float32 (good for TF)
verbose: print out info
return_full: return X and y
contiguous_splits: versus random splits
Returns:
X, y: full input and response arrays (NumPy arrays)
X_train, y_train, X_val, y_val, X_test, y_test: split data X_mean, X_std: mean and std used for normalization
If return_full=False, X and y are None.
"""
if cat_var is None:
cat_var = []
input_var = list(num_var) + list(cat_var)
# --- checks
if "time" not in data.dims:
raise ValueError("Dataset must contain a 'time' dimension.")
if abs(sum(split_ratio) - 1.0) > 1e-6:
raise ValueError("split_ratio must sum to 1.0")
if "ocean_mask" not in data:
raise KeyError("Dataset must contain 'ocean_mask' (1=ocean, 0=land).")
# ---------- subset by year(s) ----------
if years is not None:
if isinstance(years, (str, int)):
data = data.sel(time=str(years))
elif isinstance(years, slice):
data = data.sel(time=years)
else:
# assume iterable of years (ints/strs)
ti = pd.DatetimeIndex(np.asarray(data["time"].values))
yrs = set(int(y) for y in years)
sel = xr.DataArray(np.isin(ti.year, list(yrs)), coords={"time": data["time"]}, dims=["time"])
data = data.sel(time=sel)
if data.sizes.get("time", 0) == 0:
raise ValueError("No timesteps left after year filtering.")
# create a template for broadcasting 2D -> 3D
template = data[y_var]
# NaN-based time filtering where mask = 1
ocean = data["ocean_mask"].astype(bool)
if "time" not in ocean.dims:
ocean = ocean.expand_dims({"time": data["time"]}).broadcast_like(template)
else:
ocean = ocean.broadcast_like(template)
spatial_dims = [d for d in ocean.dims if d != "time"]
ocean_pix_per_t = ocean.sum(dim=spatial_dims)
check_vars = input_var + [y_var]
valid_times = xr.DataArray(np.ones(data.sizes["time"], dtype=bool), coords={"time": data["time"]}, dims=["time"])
for v in check_vars:
if v not in data:
raise KeyError(f"Variable '{v}' not found in dataset.")
arr = data[v]
if "time" not in arr.dims:
arr = arr.expand_dims({"time": data["time"]}).broadcast_like(template)
else:
arr = arr.broadcast_like(template)
frac = nan_max_frac_y if v == y_var else nan_max_frac_v
nan_thresh = frac * ocean_pix_per_t # (time,)
v_nan = xr.apply_ufunc(np.isnan, arr) & ocean
v_nan_count = v_nan.sum(dim=spatial_dims)
# Remove days with too many NaNs
valid_times = valid_times & (v_nan_count < nan_thresh)
before = int(data.sizes["time"])
data = data.sel(time=valid_times)
ocean = ocean.sel(time=valid_times)
after = int(data.sizes["time"])
if after == 0:
raise ValueError("No timesteps left after NaN filtering.")
if verbose:
yrs_msg = f" (years={years})" if years is not None else ""
print(f"[NaN filter]{yrs_msg} kept {after}/{before} days "
f"(≤ {nan_max_frac*100:.1f}% NaNs over ocean per variable).")
# --- days-per-month report ---
t = pd.to_datetime(data["time"].values)
# group by year-month (works for one or many years)
per_month = (
pd.Series(1, index=pd.Index(t, name="time"))
.groupby([t.year, t.month])
.sum()
.astype(int)
)
# prettify as "YYYY-MM"
per_month.index = [f"{y:04d}-{m:02d}" for y, m in per_month.index]
print("Days kept per month:")
for ym, cnt in per_month.items():
print(f" {ym}: {cnt}")
# compact 12-month line when only a single year is present
if len(pd.unique(t.year)) == 1:
counts = (
pd.Series(1, index=t)
.groupby(t.month)
.sum()
.reindex(range(1, 13), fill_value=0)
.astype(int)
)
print("By month (Jan..Dec):", " ".join(f"{c:2d}" for c in counts.values))
# ---------- split indices ----------
time_len = data.sizes["time"]
rng = np.random.default_rng(seed)
all_indices = rng.choice(time_len, size=time_len, replace=False)
# Compute indices for splitting data into train, validate, and test
train_end = int(split_ratio[0] * time_len)
val_end = int((split_ratio[0] + split_ratio[1]) * time_len)
train_idx = np.sort(all_indices[:train_end])
val_idx = np.sort(all_indices[train_end:val_end])
test_idx = np.sort(all_indices[val_end:])
# ---------- helpers ----------
def fetch(var):
tmpl = data[y_var] # current (post-filter) template
arr = data[var]
if "time" not in arr.dims:
arr = arr.expand_dims({"time": data["time"]}).broadcast_like(tmpl)
else:
# ensure identical order & coords; avoid resurrecting dropped times
arr = arr.transpose("time", ...).reindex_like(tmpl)
out = arr.values.astype("float32", copy=False) if cast_float32 else arr.values
return out
# stats from training; compute before imputation (with median)
if num_var:
if X_mean is None or X_std is None:
means, stds = [], []
for v in num_var:
a = fetch(v)
a_tr = a[train_idx]
means.append(np.nanmean(a_tr, axis=(0, 1, 2)))
stds.append( np.nanstd( a_tr, axis=(0, 1, 2)))
X_mean = np.asarray(means, dtype="float32" if cast_float32 else a.dtype)
X_std = np.asarray(stds, dtype="float32" if cast_float32 else a.dtype)
X_std_safe = np.where(X_std == 0, 1.0, X_std)
else:
X_mean = np.array([], dtype="float32" if cast_float32 else float)
X_std = np.array([], dtype="float32" if cast_float32 else float)
X_std_safe = X_std
# ---- precompute per-pixel medians for num_var using ONLY training data
ocean_np = ocean.transpose("time","lat","lon").values
medians = []
for v in num_var:
a = fetch(v) # (T, H, W)
a_tr = a[train_idx] # (t, H, W)
oce_tr = ocean_np[train_idx] # (t, H, W) boolean
# Mask: land OR invalid values
masked = np.ma.array(a_tr, mask=(~oce_tr) | (~np.isfinite(a_tr)))
# Per-pixel median across time (returns masked result if all masked)
med_ma = np.ma.median(masked, axis=0) # (H, W) masked array
med = med_ma.filled(np.nan) # fill all-masked pixels with NaN
# Fallback for pixels with no finite ocean values
cnt = np.isfinite(masked.filled(np.nan)).sum(axis=0)
if masked.count() > 0:
global_med = float(np.ma.median(masked))
else:
global_med = 0.0
med = np.where(cnt > 0, med, global_med).astype('float32', copy=False)
medians.append(med)
def build_split(idx):
chans = []
# numeric (normalize, impute NaNs with per-pixel medians; optional missingness)
for k, v in enumerate(num_var):
a = fetch(v) # (T, H, W)
a = a[idx] # (t, H, W)
oce_t = ocean_np[idx] # (t, H, W)
miss = (~np.isfinite(a)) & oce_t
# impute with per-pixel median
a = np.where(miss, medians[k], a)
# normalize
a = (a - X_mean[k]) / X_std_safe[k]
a = np.where(oce_t, a, 0.0) # set values over land to 0
chans.append(a.astype("float32", copy=False))
if add_missingness:
# add a 0/1 channel indicating originally-missing inputs
chans.append(miss.astype("float32", copy=False))
# categorical (just fill NaNs with 0 or a benign default)
for v in cat_var:
a = fetch(v) # (T, H, W)
a = a[idx]
a = np.nan_to_num(a) # okay for categorical/auxiliary
chans.append(a.astype("float32", copy=False))
if not chans:
raise ValueError("No input variables provided.")
# stack channels last → (t, H, W, C)
return np.stack(chans, axis=-1)
# IMPORTANT: keep NaNs in y so your masked loss can ignore cloudy/land pixels!
y_full = data[y_var].transpose("time", ...).values
if cast_float32:
y_full = y_full.astype("float32", copy=False)
def take_y(idx):
y_s = y_full[idx] # DO NOT nan to 0 here
return y_s
# ---------- build splits ----------
X_train = build_split(train_idx); y_train = take_y(train_idx)
X_val = build_split(val_idx); y_val = take_y(val_idx)
X_test = build_split(test_idx); y_test = take_y(test_idx)
if return_full:
X = build_split(slice(0, time_len))
y = take_y(slice(0, time_len))
else:
X = None
y = None
return X, y, X_train, y_train, X_val, y_val, X_test, y_test, X_mean, X_std
# --- Saving a model bundle ---
from dataclasses import dataclass
@dataclass
class MLBundle:
model: object
meta: dict
data: dict | None = None # <- holds dataset, train_idx, test_idx, etc.
predict_fn: callable | None = None
plot_fn: callable | None = None
def predict(self, *args, **kwargs):
if self.predict_fn is None:
raise AttributeError("No predict_fn stored in this bundle.")
return self.predict_fn(*args, **kwargs)
def plot(self, *args, **kwargs):
if self.plot_fn is None:
raise AttributeError("No plot_fn stored in this bundle.")
return self.plot_fn(*args, **kwargs)
def save_ml_bundle(
zip_path,
model,
dataset=None,
train_idx=None,
test_idx=None,
meta=None,
predict_helper=None,
plot_helper=None,
extra_helpers=None,
):
"""
Save a model bundle (BRT, CNN, etc.) to a single .zip.
Contents:
- model.pkl or model.keras
- data.pkl (optional: dataset, train_idx, test_idx)
- meta.json (includes helper function source if provided)
meta["model_kind"] controls how the model is saved:
- "keras" -> saved as model.keras
- anything else -> pickled as model.pkl
If `model` is a collection (dict/list/tuple), it is always pickled,
and metadata fields are added:
- meta["model_is_collection"] = True
- meta["model_collection_type"] = "dict" | "list" | "tuple"
- meta["n_submodels"]
- meta["model_keys"] (for dict)
"""
import inspect
import json
import pickle
import tempfile
import zipfile
from pathlib import Path
meta = dict(meta or {})
# --- Detect if model is a collection ---
is_collection = isinstance(model, (dict, list, tuple))
meta["model_is_collection"] = bool(is_collection)
if is_collection:
if isinstance(model, dict):
meta["model_collection_type"] = "dict"
meta["model_keys"] = [str(k) for k in model.keys()]
elif isinstance(model, list):
meta["model_collection_type"] = "list"
else:
meta["model_collection_type"] = "tuple"
meta["n_submodels"] = len(model)
# --- Infer model kind if not given ---
if "model_kind" not in meta:
if is_collection:
meta["model_kind"] = "pickle"
else:
cls_name = type(model).__name__.lower()
if "sequential" in cls_name or "functional" in cls_name:
meta["model_kind"] = "keras"
else:
meta["model_kind"] = "pickle"
# --- Gather helper source code ---
helpers_src = {}
# Predict helper
if predict_helper is not None:
name = predict_helper.__name__
meta["predict_helper_name"] = name
try:
src = inspect.getsource(predict_helper)
helpers_src[name] = src
except OSError:
pass
# Plot helper
if plot_helper is not None:
name = plot_helper.__name__
meta["plot_helper_name"] = name
try:
src = inspect.getsource(plot_helper)
helpers_src[name] = src
except OSError:
pass
# Extra helpers (e.g. feature adders, single-depth predictor, etc.)
extra_helpers = extra_helpers or {}
for name, fn in extra_helpers.items():
try:
helpers_src[name] = inspect.getsource(fn)
except OSError:
pass
if helpers_src:
meta["helpers"] = helpers_src
# --- If we are given indices, stash them in meta too (JSON-safe) ---
if train_idx is not None:
meta["train_idx"] = np.asarray(train_idx).tolist()
if test_idx is not None:
meta["test_idx"] = np.asarray(test_idx).tolist()
# --- Write everything into a temp dir then zip it ---
zip_path = Path(zip_path)
zip_path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
# 1) Save model
if meta["model_kind"] == "keras" and not is_collection:
model_path = tmp / "model.keras"
model.save(model_path)
else:
model_path = tmp / "model.pkl"
with open(model_path, "wb") as f:
pickle.dump(model, f)
# 2) Save data (dataset + indices)
data = {
"dataset": dataset,
"train_idx": train_idx,
"test_idx": test_idx,
}
data_path = tmp / "data.pkl"
with open(data_path, "wb") as f:
pickle.dump(data, f)
# 3) Save meta
meta_path = tmp / "meta.json"
meta_path.write_text(json.dumps(meta, indent=2))
# 4) Zip everything
with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as z:
z.write(model_path, arcname=model_path.name)
z.write(data_path, arcname=data_path.name)
z.write(meta_path, arcname=meta_path.name)
return str(zip_path)
def _print_bundle_usage(bundle, bundle_path):
meta = bundle.meta
data = bundle.data or {}
model_kind = meta.get("model_kind", "pickle")
predict_name = meta.get("predict_helper_name")
plot_name = meta.get("plot_helper_name")
is_collection = meta.get("model_is_collection", False)
collection_type = meta.get("model_collection_type")
model_keys = meta.get("model_keys", [])
n_submodels = meta.get("n_submodels")
print(f"\nLoaded ML bundle from: {bundle_path}")
print(f" model_kind : {model_kind}")
if is_collection:
print(f" model_type : collection ({collection_type}), n_submodels={n_submodels}")
if collection_type == "dict" and model_keys:
example_key = model_keys[0]
print(f" example key: {example_key}")
else:
print(" model_type : single model")
if "target_name" in meta:
print(f" target : {meta['target_name']}")
if "feature_cols" in meta:
print(f" features : {len(meta['feature_cols'])} columns")
train_idx = meta.get("train_idx")
test_idx = meta.get("test_idx")
if train_idx is not None and test_idx is not None:
print(f" train/test : {len(train_idx)} / {len(test_idx)} rows")
if data.get("dataset") is not None:
try:
nrows = len(data["dataset"])
print(f" dataset : {nrows} rows stored in bundle")
except Exception:
print(" dataset : stored in bundle (length unknown)")
print("\nUsage example (Python):")
print(" bundle = load_ml_bundle('path/to/bundle.zip')")
if predict_name and bundle.predict_fn is not None:
print(f" # Predict using helper '{predict_name}'")
if is_collection:
print(" # Example: predict all depths for one day from a BRF dataset R")
print(" pred = bundle.predict(")
print(" R_dataset, # xr.DataArray/xr.Dataset with lat/lon + predictors")
print(" brt_models=bundle.model, # dict of models by depth bin")
if "feature_cols" in meta:
print(" feature_cols=bundle.meta['feature_cols'],")
print(" consts={'solar_hour': 12.0, 'type': 1},")
print(" ) # -> e.g. CHLA(time?, z, lat, lon)")
else:
print(" pred = bundle.predict(")
print(" R_dataset, # xr.DataArray/xr.Dataset with lat/lon + predictors")
print(" brt_model=bundle.model, # single model")
if "feature_cols" in meta:
print(" feature_cols=bundle.meta['feature_cols'],")
print(" )")
else:
if is_collection:
print(" # This bundle has no stored predict helper.")
print(" # 'bundle.model' is a collection (e.g. dict) of models:")
print(" # e.g. bundle.model['CHLA_0_10'].predict(X)")
else:
print(" # This bundle has no stored predict helper; call bundle.model.predict(...) directly.")
if plot_name and bundle.plot_fn is not None:
print(f"\n # Plot using helper '{plot_name}'")
print(" fig, ax = bundle.plot(pred_da, pred_label='Prediction')")
else:
print("\n # This bundle has no stored plot helper; use your own plotting code.")
print("") # final newline
def load_ml_bundle(zip_path):
"""
Load a bundle created by save_ml_bundle().
Returns
-------
bundle : MLBundle
Instance with:
- model, meta, data (dataset + indices)
- predict_fn, plot_fn (if stored)
- data["splits"] = dict with X_train, X_test, y_train, y_test
X_train, X_test, y_train, y_test : pandas objects
Train-test splits reconstructed from dataset, feature_cols, y_col,
train_idx, and test_idx.
"""
import json
import zipfile
import pickle
import tempfile
from pathlib import Path
zip_path = Path(zip_path)
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(tmp)
meta = json.loads((tmp / "meta.json").read_text())
model_kind = meta.get("model_kind", "pickle")
# --- load model ---
if model_kind == "keras":
import keras
model = keras.saving.load_model(tmp / "model.keras")
else:
with open(tmp / "model.pkl", "rb") as f:
model = pickle.load(f)
# --- load dataset + indices + metadata ---
with open(tmp / "data.pkl", "rb") as f:
data = pickle.load(f)
# --- Reconstruct helpers (including predict/plot) in a shared namespace ---
helpers_src = meta.get("helpers", {})
ns = {}
predict_fn = None
plot_fn = None
if helpers_src:
for name, src in helpers_src.items():
exec(src, ns, ns)
pred_name = meta.get("predict_helper_name")
if pred_name:
predict_fn = ns.get(pred_name)
plot_name = meta.get("plot_helper_name")
if plot_name:
plot_fn = ns.get(plot_name)
# --- Rebuild X_train, X_test, y_train, y_test from stored pieces ---
# Assumes save_ml_bundle stored these in data and/or meta
dataset = data.get("dataset")
if dataset is None:
raise ValueError("`dataset` not found in bundle data.")
# feature_cols and y_col might be in data or meta
feature_cols = data.get("feature_cols", meta.get("feature_cols"))
y_col = data.get("y_col", meta.get("y_col"))
if feature_cols is None:
raise ValueError("`feature_cols` not found in data/meta.")
if y_col is None:
raise ValueError("`y_col` not found in data/meta.")
train_idx = data.get("train_idx")
test_idx = data.get("test_idx")
if train_idx is None or test_idx is None:
raise ValueError("`train_idx` and/or `test_idx` not found in data.")
# Build full X, y
X = dataset[feature_cols]
y = dataset[y_col]
# Use .loc so this works for labels or boolean masks
X_train = X.loc[train_idx]
X_test = X.loc[test_idx]
y_train = y.loc[train_idx]
y_test = y.loc[test_idx]
# Attach splits back into data for convenience
data["X_train"] = X_train
data["X_test"] = X_test
data["y_train"] = y_train
data["y_test"] = y_test
# Build bundle
bundle = MLBundle(
model=model,
meta=meta,
data=data,
predict_fn=predict_fn,
plot_fn=plot_fn,
)
_print_bundle_usage(bundle, zip_path)
# Return bundle
return bundle
# ---- Make Predictions from Model
# predictions single brt for a single depth
def make_prediction_brt(
R: xr.Dataset,
brt_model,
feature_cols,
consts=None,
linear=False
) -> xr.DataArray:
"""
Predict a single BRT depth-bin field on a lat/lon grid, automatically
constructing derived features (solar_hour, sin_time/cos_time, x_geo/y_geo/z_geo)
if they are requested in feature_cols and not already present. If linear=True, CHLA is returned on the linear scale otherwise it is log10.
Parameters
----------
R : xr.Dataset
Dataset with lat, lon (and possibly time) plus any derived variables.
brt_model :
Fitted sklearn-like model with .predict().
feature_cols : list of str
Predictor names expected by the model.
consts : dict, optional
Constant feature values, e.g. {"solar_hour": 12.0, "type": 1}.
linear : bool, optional
If True, then the predictions are backtransformed to linear.
Returns
-------
xr.DataArray
Prediction on (lat, lon) as 'y_pred'.
"""
import numpy as np
import pandas as pd
import xarray as xr
consts = consts or {}
# ----------
# Make a working copy
# ----------
ds = R.copy()
# ----------
# Add derived features if needed
# ----------
# --- solar_hour ---
if "solar_hour" in feature_cols and "solar_hour" not in ds and "solar_hour" not in consts:
if "add_solar_hour_feature" not in globals():
raise RuntimeError(
"Feature 'solar_hour' is required but helper 'add_solar_hour_feature' "
"is not available.\n"
"Either define it (or include it in the bundle), provide "
"consts={'solar_hour': value}, or pre-add 'solar_hour' to your Dataset."
)
ds = add_solar_hour_feature(ds)
# --- seasonal sin/cos ---
needs_sin = "sin_time" in feature_cols and "sin_time" not in ds and "sin_time" not in consts
needs_cos = "cos_time" in feature_cols and "cos_time" not in ds and "cos_time" not in consts
if needs_sin or needs_cos:
if "add_seasonal_time_features" not in globals():
raise RuntimeError(
"Features 'sin_time'/'cos_time' are required but helper "
"'add_seasonal_time_features' is not available.\n"
"Define it (or include it in the bundle), or pre-add 'sin_time' "
"and 'cos_time' to your Dataset."
)
ds = add_seasonal_time_features(ds, time="time") # adjust args if needed
# --- spherical coords ---
needs_x = "x_geo" in feature_cols and "x_geo" not in ds and "x_geo" not in consts
needs_y = "y_geo" in feature_cols and "y_geo" not in ds and "y_geo" not in consts
needs_z = "z_geo" in feature_cols and "z_geo" not in ds and "z_geo" not in consts
if needs_x or needs_y or needs_z:
if "add_spherical_coords" not in globals():
raise RuntimeError(
"Spherical-coord features are required but helper 'add_spherical_coords' "
"is not available.\n"
"Define it (or include it in the bundle), or pre-add x_geo/y_geo/z_geo."
)
ds = add_spherical_coords(ds)
# ----------
# Stack and predict
# ----------
ds_stack = ds.stack(pixel=("lat", "lon"))
n_pixel = ds_stack.sizes["pixel"]
df_cols = {}
for feat in feature_cols:
if feat in consts:
df_cols[feat] = np.full(n_pixel, consts[feat], dtype=float)
else:
if feat not in ds_stack:
raise KeyError(
f"Feature '{feat}' was not found in dataset or consts.\n"
f"If this is a derived variable, ensure the helper function "
f"is available or add it manually."
)
# .values.reshape(n_pixel) to flatten all other dims (here just pixel)
df_cols[feat] = ds_stack[feat].values.reshape(n_pixel)
df_pred = pd.DataFrame(df_cols, columns=feature_cols)
# Handle NaNs
valid_mask = ~df_pred.isna().any(axis=1)
df_valid = df_pred[valid_mask]
y_pred_flat = np.full(n_pixel, np.nan, dtype=float)
if len(df_valid) > 0:
y_pred = brt_model.predict(df_valid)
if linear:
y_pred = 10**y_pred
y_pred_flat[valid_mask.values] = y_pred
# reshape back
pred_map = y_pred_flat.reshape(R.sizes["lat"], R.sizes["lon"])
return xr.DataArray(
pred_map,
coords={"lat": R["lat"], "lon": R["lon"]},
dims=("lat", "lon"),
name="y_pred",
)
def predict_all_depths_for_day(
R, # xr.DataArray (lat, lon, wavelength)
brt_models: dict, # e.g. {"CHLA_0_10": model0, "CHLA_10_20": model1, ...}
feature_cols: list,
consts=None, # e.g. {"solar_hour": 0, "type": 1}
chunk_size_lat: int = 100,
time=None, # e.g. "2024-07-15" or np.datetime64
z=None, # optional override for depth centers
z_name: str = "z", # vertical dimension name
silent: bool = False, # kept for compatibility; not used right now
linear: bool = False, # backtransform CHLA to linear
):
"""
Run BRT predictions for all depth bins for a single day.
Memory-optimized version:
- predictions stored as float32
- preallocates (depth, lat, lon) and fills in lat-chunks
Parameters
----------
R : xr.DataArray
Rrs on (lat, lon, wavelength). No time dimension.
brt_models : dict
Mapping depth-label -> fitted model, e.g.
{"CHLA_0_10": model0, "CHLA_10_20": model1, ...}.
The last two underscore-separated tokens are assumed to be
depth start/end in meters, e.g. "CHLA_0_10" -> 0, 10.
feature_cols : list of str
Columns expected by the BRT models. The non-constant subset of these
must align with the wavelength dimension of R.
consts : dict, optional
Feature -> scalar value for constant features
(e.g. {"solar_hour": 0, "type": 1}).
chunk_size_lat : int
Number of latitude indices per chunk.
time : str or np.datetime64, optional
If provided, a `time` dimension of length 1 is added to the output.
z : array-like, optional
Depth centers (same order as brt_models keys). If not given, centers are
inferred as (z_start + z_end)/2 from the model name.
z_name : str, default "z"
Name of the vertical dimension in the output.
silent : bool, default False
Placeholder flag for compatibility; currently not used.
Returns
-------
xr.DataArray
CHLA prediction with dims:
(time, z_name, lat, lon) if `time` provided
(z_name, lat, lon) otherwise
Coordinates:
z_name : depth center (m)
f"{z_name}_start" : depth bin lower bound (m)
f"{z_name}_end" : depth bin upper bound (m)
"""
import numpy as np
import pandas as pd
import xarray as xr
consts = consts or {}
# Make sure dims are in the expected order
R = R.transpose("lat", "lon", "wavelength")
depth_labels = list(brt_models.keys())
n_depth = len(depth_labels)
# ---- parse z_start / z_end / z_center from labels like ABC_0_10 ----
z_start_arr = np.full(n_depth, np.nan, dtype="float32")
z_end_arr = np.full(n_depth, np.nan, dtype="float32")
z_center_arr = np.full(n_depth, np.nan, dtype="float32")
for i, label in enumerate(depth_labels):
parts = label.split("_")
if len(parts) >= 3:
try:
z0 = float(parts[-2])
z1 = float(parts[-1])
z_start_arr[i] = z0
z_end_arr[i] = z1
z_center_arr[i] = 0.5 * (z0 + z1)
except ValueError:
# leave as NaN if parsing fails
pass
# override z centers if explicitly provided
if z is not None:
z_center_arr = np.asarray(z, dtype="float32")
if z_center_arr.shape[0] != n_depth:
raise ValueError(f"len(z)={len(z_center_arr)} does not match number of models={n_depth}")
nlat = R.sizes["lat"]
nlon = R.sizes["lon"]
lat_coord = R["lat"]
lon_coord = R["lon"]
# ------- non-constant features must match wavelength axis -------
non_constant_cols = [c for c in feature_cols if c not in consts]
nwave = R.sizes["wavelength"]
if len(non_constant_cols) != nwave:
raise ValueError(
f"Number of non-constant features ({len(non_constant_cols)}) "
f"does not match wavelength dimension ({nwave}).\n"
f"Non-constant cols: {non_constant_cols}"
)
# Check that wavelengths encoded in feature_cols match R["wavelength"]
try:
wl_from_cols = np.array(
[float(col.rsplit("_", 1)[-1]) for col in non_constant_cols],
dtype=float,
)
except ValueError as e:
raise ValueError(
"Could not parse wavelengths from feature_cols. "
"Expected names like 'pace_Rrs_346', 'pace_Rrs_348', etc. "
f"Got non-constant_cols={non_constant_cols[:5]}..."
) from e
wl_R = np.asarray(R["wavelength"].values, dtype=float)
if wl_from_cols.shape[0] != wl_R.shape[0] or not np.allclose(wl_from_cols, wl_R, atol=0.01):
raise ValueError(
"Mismatch between wavelengths implied by feature_cols and the "
"R['wavelength'] coordinate.\n"
f"First few from feature_cols: {wl_from_cols[:5]}\n"
f"First few from R.wavelength: {wl_R[:5]}"
)
# -------- preallocate output array: (depth, lat, lon) as float32 --------
pred_all_arr = np.full(
(n_depth, nlat, nlon),
np.nan,
dtype=np.float32,
)
# ---- chunk over latitude to avoid loading full globe into memory ----
for start in range(0, nlat, chunk_size_lat):
if not silent:
print(f"Starting {start} of {nlat}")
stop = min(start + chunk_size_lat, nlat)
R_chunk = R.isel(lat=slice(start, stop)) # (lat_chunk, lon, wavelength)
# 1. stack lat/lon → pixel
R2 = R_chunk.stack(pixel=("lat", "lon")).transpose("pixel", "wavelength")
R2_vals = R2.values # (n_pixel, n_wavelength)
# 2. base DataFrame for all models (non-constant features)
df_base = pd.DataFrame(R2_vals, columns=non_constant_cols)
# 3. For each depth-model, add constants, filter NaNs, predict, reshape
for d_idx, depth_label in enumerate(depth_labels):
model = brt_models[depth_label]
# Start from the base spectral predictors
df_pred = df_base.copy()
# Add constant columns that are actually in feature_cols
for name, value in consts.items():
if name in feature_cols:
df_pred[name] = value
# Ensure columns are in the correct order expected by the model
df_pred = df_pred[feature_cols]
# Handle NaNs: keep only pixels with complete predictors
valid_mask = ~df_pred.isna().any(axis=1)
df_valid = df_pred[valid_mask]
# Prepare flat prediction array for this lat-chunk (float32)
y_pred_flat = np.full(df_pred.shape[0], np.nan, dtype=np.float32)
if len(df_valid) > 0:
# model.predict may return float64; cast to float32
y_pred = model.predict(df_valid).astype(np.float32)
if linear:
y_pred = 10**y_pred
y_pred_flat[valid_mask.values] = y_pred.astype(np.float32)
# Reshape back to (lat_chunk, lon)
nlat_chunk = R_chunk.sizes["lat"]
y_pred_map = y_pred_flat.reshape(nlat_chunk, nlon)
# Fill into the preallocated array
pred_all_arr[d_idx, start:stop, :] = y_pred_map
if not silent:
print(f"Starting wrapping")
# ---- wrap preallocated array into an xarray.DataArray ----
pred_all = xr.DataArray(
pred_all_arr,
coords={
z_name: z_center_arr,
"lat": lat_coord,
"lon": lon_coord,
},
dims=(z_name, "lat", "lon"),
name="CHLA",
)
# vertical coordinates
if not silent:
print(f"Adding coords")
pred_all = pred_all.assign_coords(
{
z_name: z_center_arr,
f"{z_name}_start": (z_name, z_start_arr),
f"{z_name}_end": (z_name, z_end_arr),
}
)
# optional time dimension
if time is not None:
if not silent:
print(f"Adding time")
time_val = np.datetime64(time)