ebas-plot 0.1.6__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ebas-plot
3
- Version: 0.1.6
3
+ Version: 0.2.0
4
4
  Summary: Plotting utilities for EBAS netCDF datasets.
5
5
  Author-email: Lise Eder Murberg <lemu@nilu.no>, Marthe Brevig <mbre@nilu.no>, Jonathan Elias Holme <jhol@nilu.no>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ebas-plot
3
- Version: 0.1.6
3
+ Version: 0.2.0
4
4
  Summary: Plotting utilities for EBAS netCDF datasets.
5
5
  Author-email: Lise Eder Murberg <lemu@nilu.no>, Marthe Brevig <mbre@nilu.no>, Jonathan Elias Holme <jhol@nilu.no>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -7,7 +7,7 @@ import requests
7
7
  from netCDF4 import date2num, num2date
8
8
  import pandas as pd
9
9
 
10
- __version__ = "0.1.6"
10
+ __version__ = "0.2.0"
11
11
 
12
12
 
13
13
  class DatasetAccessError(Exception):
@@ -257,9 +257,19 @@ def _dataset_title(ds: xr.Dataset) -> str:
257
257
  return station or "Unknown Site"
258
258
 
259
259
 
260
- def _var_mean(ds: xr.Dataset, name: str) -> float:
260
+ def _var_mean(
261
+ ds: xr.Dataset,
262
+ name: str,
263
+ data_cache: dict[str, np.ndarray] | None = None,
264
+ ) -> float:
261
265
  """Mean of finite values, used as a sort key."""
262
- vals = ds[name].values.ravel()
266
+ if data_cache is not None and name in data_cache:
267
+ values = data_cache[name]
268
+ else:
269
+ values = ds[name].values
270
+ if data_cache is not None:
271
+ data_cache[name] = values
272
+ vals = values.ravel()
263
273
  finite = vals[np.isfinite(vals)]
264
274
  return float(finite.mean()) if len(finite) else 0.0
265
275
 
@@ -336,7 +346,10 @@ def _dimension_with_prefix(da: xr.DataArray, prefix: str) -> str | None:
336
346
  return next((dim for dim in da.dims if dim == prefix or dim.startswith(f"{prefix}_")), None)
337
347
 
338
348
 
339
- def _plot_vars(ds: xr.Dataset) -> list[str]:
349
+ def _plot_vars(
350
+ ds: xr.Dataset,
351
+ data_cache: dict[str, np.ndarray] | None = None,
352
+ ) -> list[str]:
340
353
  """Return measurement variable names to plot for a timeseries dataset.
341
354
 
342
355
  Excludes auxiliary variables, percentile statistics, all-missing variables,
@@ -366,7 +379,13 @@ def _plot_vars(ds: xr.Dataset) -> list[str]:
366
379
  for d in ds[name].dims
367
380
  ):
368
381
  continue
369
- if not np.isfinite(ds[name].values).any():
382
+ if data_cache is not None and name in data_cache:
383
+ values = data_cache[name]
384
+ else:
385
+ values = ds[name].values
386
+ if data_cache is not None:
387
+ data_cache[name] = values
388
+ if not np.isfinite(values).any():
370
389
  continue
371
390
  result.append(name)
372
391
 
@@ -629,6 +648,7 @@ def plot_timeseries(
629
648
  var_color_offsets: dict[str, int] | None = None,
630
649
  wl_color_offsets: dict[str, int] | None = None,
631
650
  mode: str | None = None,
651
+ _data_cache: dict[str, np.ndarray] | None = None,
632
652
  ) -> go.Figure:
633
653
  """Plot timeseries variables in a single plot, grouped by variable in the legend.
634
654
 
@@ -653,7 +673,8 @@ def plot_timeseries(
653
673
  f"Dataset coordinates: {list(ds.coords)}"
654
674
  )
655
675
 
656
- plot_vars = subset_vars if subset_vars is not None else _plot_vars(ds)
676
+ data_cache = _data_cache if _data_cache is not None else {}
677
+ plot_vars = subset_vars if subset_vars is not None else _plot_vars(ds, data_cache)
657
678
  if not plot_vars:
658
679
  raise ValueError(
659
680
  "No plottable variables found (expected 'v_*' mean variables). "
@@ -661,7 +682,11 @@ def plot_timeseries(
661
682
  )
662
683
 
663
684
  # Pre-load all variable data once to avoid redundant OPeNDAP reads during sort, gap computation, and trace emission.
664
- _var_data: dict[str, np.ndarray] = {n: ds[n].values for n in plot_vars}
685
+ _var_data: dict[str, np.ndarray] = {}
686
+ for name in plot_vars:
687
+ if name not in data_cache:
688
+ data_cache[name] = ds[name].values
689
+ _var_data[name] = data_cache[name]
665
690
 
666
691
  # Detect whether all variables share the same unit; if so use flat legend style
667
692
  all_units = [_var_unit(ds, n) for n in plot_vars]
@@ -742,8 +767,9 @@ def plot_timeseries(
742
767
  wavelength_dim = _dimension_with_prefix(da, "d_Wavelength")
743
768
  if wavelength_dim:
744
769
  wl_values = da.coords[wavelength_dim].values
745
- for color, wl in zip(_wl_colors(name, len(wl_values)), wl_values):
746
- y = da.sel({wavelength_dim: wl}).values.copy()
770
+ wavelength_axis = da.get_axis_num(wavelength_dim)
771
+ for wavelength_index, (color, wl) in enumerate(zip(_wl_colors(name, len(wl_values)), wl_values)):
772
+ y = np.take(_var_data[name], wavelength_index, axis=wavelength_axis).copy()
747
773
  _add_timeseries_trace(fig, x_time=x_time, y=y, name=f"{float(wl):.1f} nm",
748
774
  color=color, legendgroup=group_title,
749
775
  use_scatter=use_scatter, hovertexts=hovertexts,
@@ -753,11 +779,12 @@ def plot_timeseries(
753
779
  elif "d_Tower_inlet_height" in da.dims:
754
780
  base_color = _var_color(name, _CUSTOM_COLORS_VARIABLES)
755
781
  height_values = da.coords["d_Tower_inlet_height"].values
782
+ height_axis = da.get_axis_num("d_Tower_inlet_height")
756
783
  n_heights = len(height_values)
757
784
  opacities = [1.0 - (i / max(n_heights - 1, 1)) * 0.65 for i in range(n_heights)]
758
785
  for h_idx, height in enumerate(height_values):
759
786
  color = _hex_to_rgba(base_color, opacities[h_idx])
760
- y = da.sel(d_Tower_inlet_height=height).values.copy()
787
+ y = np.take(_var_data[name], h_idx, axis=height_axis).copy()
761
788
  _add_timeseries_trace(fig, x_time=x_time, y=y, name=f"h\u1d35\u2099\u1d35={height:.0f}m",
762
789
  color=color, legendgroup=group_title,
763
790
  use_scatter=use_scatter, hovertexts=hovertexts,
@@ -828,13 +855,19 @@ def plot_timeseries(
828
855
  return fig
829
856
 
830
857
 
831
- def plot_timeseries_per_var(ds: xr.Dataset, *, mode: str | None = None) -> list[go.Figure]:
858
+ def plot_timeseries_per_var(
859
+ ds: xr.Dataset,
860
+ *,
861
+ mode: str | None = None,
862
+ _data_cache: dict[str, np.ndarray] | None = None,
863
+ ) -> list[go.Figure]:
832
864
  """Return one figure per physical quantity, preserving combined-plot colors.
833
865
 
834
866
  Variables with the same base name but different units are grouped together.
835
867
  Falls back to a single combined figure when there is only one group.
836
868
  """
837
- plot_vars = _plot_vars(ds)
869
+ data_cache = _data_cache if _data_cache is not None else {}
870
+ plot_vars = _plot_vars(ds, data_cache)
838
871
  if not plot_vars:
839
872
  raise ValueError(
840
873
  "No plottable variables found (expected 'v_*' mean variables). "
@@ -842,7 +875,7 @@ def plot_timeseries_per_var(ds: xr.Dataset, *, mode: str | None = None) -> list[
842
875
  )
843
876
  groups = _group_vars_by_physical_quantity(ds, plot_vars)
844
877
  if len(groups) <= 1:
845
- return [plot_timeseries(ds, mode=mode)]
878
+ return [plot_timeseries(ds, mode=mode, _data_cache=data_cache)]
846
879
 
847
880
  # Walk the same sorted order as the combined plot to build per-variable color offsets.
848
881
  all_units = {_var_unit(ds, n) for n in plot_vars}
@@ -856,8 +889,8 @@ def plot_timeseries_per_var(ds: xr.Dataset, *, mode: str | None = None) -> list[
856
889
  wc_map: dict[str, int] = {}
857
890
  def _group_sort_key(group: tuple[str, list[str]]) -> tuple[int, float]:
858
891
  _, names = group
859
- best = max(names, key=lambda n: _var_mean(ds, n))
860
- return (0 if best in preferred else 1, -_var_mean(ds, best))
892
+ best = max(names, key=lambda n: _var_mean(ds, n, data_cache))
893
+ return (0 if best in preferred else 1, -_var_mean(ds, best, data_cache))
861
894
 
862
895
  ordered_vars = [
863
896
  n for _, names in sorted(groups, key=_group_sort_key)
@@ -879,7 +912,8 @@ def plot_timeseries_per_var(ds: xr.Dataset, *, mode: str | None = None) -> list[
879
912
  title=f"{lbl} at {station}" if station else lbl,
880
913
  var_color_offsets={n: vc_map[n] for n in vars_ if n in vc_map},
881
914
  wl_color_offsets={n: wc_map[n] for n in vars_ if n in wc_map},
882
- mode=mode)
915
+ mode=mode,
916
+ _data_cache=data_cache)
883
917
  for lbl, vars_ in groups
884
918
  ]
885
919
 
File without changes
File without changes
File without changes
File without changes