ebas-plot 0.2.0__tar.gz → 0.2.1__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.2.0
3
+ Version: 0.2.1
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.2.0
3
+ Version: 0.2.1
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,3 +1,4 @@
1
+ import itertools
1
2
  import re
2
3
 
3
4
  import xarray as xr
@@ -7,7 +8,7 @@ import requests
7
8
  from netCDF4 import date2num, num2date
8
9
  import pandas as pd
9
10
 
10
- __version__ = "0.2.0"
11
+ __version__ = "0.2.1"
11
12
 
12
13
 
13
14
  class DatasetAccessError(Exception):
@@ -66,7 +67,7 @@ _STATISTICS = {
66
67
  "_precision", "_max", "_min", "_median",
67
68
  } # ancillary statistics; excluded from plots (not primary mean values)
68
69
  # Only these d_* dimensions are allowed in timeseries plots, d_D is in spesific PNSD plot.
69
- _ALLOWED_D_DIMS = {"d_Wavelength", "d_Tower_inlet_height"}
70
+ _ALLOWED_D_DIMS = {"d_Wavelength", "d_Tower_inlet_height", "d_RH"}
70
71
 
71
72
  _RESOLUTION_UNIT_DAYS = {"mn": 1 / 1440, "h": 1 / 24, "d": 1, "w": 7, "mo": 30, "y": 365} # used for converting resolution codes to days
72
73
  _RESOLUTION_CODE_RE = re.compile(r"^(\d+)(mn|mo|[hdwy])$")
@@ -314,7 +315,7 @@ def _default_plot_mode(ds: xr.Dataset, time_step: pd.Timedelta) -> str:
314
315
  return "line"
315
316
 
316
317
 
317
- def _scatter_hovertexts(x_time, ds: xr.Dataset) -> list[str]:
318
+ def _scatter_hovertexts(x_time, ds: xr.Dataset) -> np.ndarray:
318
319
  """Build per-point hover strings e.g. 'Aug 2006 \u2013 Oct 2006 (3mo)' or '12 \u2013 19 Nov 2012 (1w)'."""
319
320
  if "time_bnds" in ds:
320
321
  bnds = ds["time_bnds"].values
@@ -324,6 +325,20 @@ def _scatter_hovertexts(x_time, ds: xr.Dataset) -> list[str]:
324
325
  res = ds.attrs.get("ebas_resolution_code", "")
325
326
  suffix = f" ({res})" if res else ""
326
327
 
328
+ try:
329
+ start_dates = pd.DatetimeIndex(pd.to_datetime(starts))
330
+ end_dates = pd.DatetimeIndex(pd.to_datetime(ends))
331
+ return np.asarray([
332
+ f"{start:%b %Y} \u2013 {end:%b %Y}{suffix}"
333
+ if end - start >= _MONTH_ONLY_THRESHOLD else
334
+ f"{start:%-d} \u2013 {end:%-d %b %Y}{suffix}"
335
+ if start.month == end.month and start.year == end.year else
336
+ f"{start:%-d %b} \u2013 {end:%-d %b %Y}{suffix}"
337
+ for start, end in zip(start_dates, end_dates)
338
+ ], dtype=object)
339
+ except (TypeError, ValueError):
340
+ pass
341
+
327
342
  def _fmt(s, e) -> str:
328
343
  start, end = pd.Timestamp(s), pd.Timestamp(e)
329
344
  if end - start >= _MONTH_ONLY_THRESHOLD: # coarse/campaign samples
@@ -333,7 +348,7 @@ def _scatter_hovertexts(x_time, ds: xr.Dataset) -> list[str]:
333
348
  start_fmt = f"{start:%-d}" if same_month else f"{start:%-d %b}"
334
349
  return f"{start_fmt} \u2013 {end:%-d %b %Y}{suffix}"
335
350
 
336
- return [_fmt(s, e) for s, e in zip(starts, ends)]
351
+ return np.asarray([_fmt(s, e) for s, e in zip(starts, ends)], dtype=object)
337
352
 
338
353
 
339
354
  def _pnsd_var(ds: xr.Dataset) -> str | None:
@@ -578,7 +593,7 @@ def _break_temporal_gaps(
578
593
 
579
594
 
580
595
  def _add_timeseries_trace(
581
- fig: go.Figure,
596
+ trace_specs: list[dict],
582
597
  *,
583
598
  x_time,
584
599
  y: np.ndarray,
@@ -622,7 +637,8 @@ def _add_timeseries_trace(
622
637
  if legendgroup is not None:
623
638
  kw["legendgroup"] = legendgroup
624
639
  kw["legendgrouptitle_text"] = legendgroup
625
- fig.add_trace(go.Scatter(**kw))
640
+ kw["type"] = "scatter"
641
+ trace_specs.append(kw)
626
642
 
627
643
 
628
644
  def _has_line_segments(
@@ -649,6 +665,8 @@ def plot_timeseries(
649
665
  wl_color_offsets: dict[str, int] | None = None,
650
666
  mode: str | None = None,
651
667
  _data_cache: dict[str, np.ndarray] | None = None,
668
+ _hovertexts: np.ndarray | None = None,
669
+ _x_time: np.ndarray | None = None,
652
670
  ) -> go.Figure:
653
671
  """Plot timeseries variables in a single plot, grouped by variable in the legend.
654
672
 
@@ -720,8 +738,8 @@ def plot_timeseries(
720
738
  for n in sorted(names, key=lambda n: 0 if n in _preferred_var else 1)
721
739
  ]
722
740
 
723
- x_time = get_plot_time(ds)
724
- fig = go.Figure()
741
+ x_time = _x_time if _x_time is not None else get_plot_time(ds)
742
+ trace_specs: list[dict] = []
725
743
 
726
744
  _iso_marker_size = 4
727
745
 
@@ -735,7 +753,9 @@ def plot_timeseries(
735
753
  "Line mode was requested/selected, but the data is too sparse or irregular "
736
754
  "to draw any connecting line -- use mode='scatter' instead."
737
755
  )
738
- hovertexts = _scatter_hovertexts(x_time, ds)
756
+ hovertexts = (
757
+ _hovertexts if _hovertexts is not None else _scatter_hovertexts(x_time, ds)
758
+ ) if use_scatter else None
739
759
 
740
760
  # Determine plot mode
741
761
  has_wavelength = any(_dimension_with_prefix(ds[n], "d_Wavelength") is not None for n in plot_vars)
@@ -768,13 +788,24 @@ def plot_timeseries(
768
788
  if wavelength_dim:
769
789
  wl_values = da.coords[wavelength_dim].values
770
790
  wavelength_axis = da.get_axis_num(wavelength_dim)
791
+ parameter_dims = [dim for dim in da.dims if dim not in (wavelength_dim, "time")]
792
+ parameter_indices = list(itertools.product(*(range(da.sizes[dim]) for dim in parameter_dims)))
771
793
  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()
773
- _add_timeseries_trace(fig, x_time=x_time, y=y, name=f"{float(wl):.1f} nm",
774
- color=color, legendgroup=group_title,
775
- use_scatter=use_scatter, hovertexts=hovertexts,
776
- max_gap_steps=_max_gap_steps, time_step=_time_step,
777
- iso_marker_size=_iso_marker_size)
794
+ for indices in parameter_indices:
795
+ selection = [slice(None)] * da.ndim
796
+ selection[wavelength_axis] = wavelength_index
797
+ labels = [f"{float(wl):.1f} nm"]
798
+ for dim, index in zip(parameter_dims, indices):
799
+ selection[da.get_axis_num(dim)] = index
800
+ value = da.coords[dim].values[index]
801
+ label = dim.removeprefix("d_").replace("_", " ")
802
+ labels.append(f"{label}={value:g}")
803
+ y = _var_data[name][tuple(selection)].copy()
804
+ _add_timeseries_trace(trace_specs, x_time=x_time, y=y, name=", ".join(labels),
805
+ color=color, legendgroup=group_title,
806
+ use_scatter=use_scatter, hovertexts=hovertexts,
807
+ max_gap_steps=_max_gap_steps, time_step=_time_step,
808
+ iso_marker_size=_iso_marker_size)
778
809
 
779
810
  elif "d_Tower_inlet_height" in da.dims:
780
811
  base_color = _var_color(name, _CUSTOM_COLORS_VARIABLES)
@@ -785,7 +816,7 @@ def plot_timeseries(
785
816
  for h_idx, height in enumerate(height_values):
786
817
  color = _hex_to_rgba(base_color, opacities[h_idx])
787
818
  y = np.take(_var_data[name], h_idx, axis=height_axis).copy()
788
- _add_timeseries_trace(fig, x_time=x_time, y=y, name=f"h\u1d35\u2099\u1d35={height:.0f}m",
819
+ _add_timeseries_trace(trace_specs, x_time=x_time, y=y, name=f"h\u1d35\u2099\u1d35={height:.0f}m",
789
820
  color=color, legendgroup=group_title,
790
821
  use_scatter=use_scatter, hovertexts=hovertexts,
791
822
  max_gap_steps=_max_gap_steps, time_step=_time_step,
@@ -811,46 +842,49 @@ def plot_timeseries(
811
842
  visible = True if name in _preferred_var else "legendonly"
812
843
 
813
844
  y = _var_data[name].copy()
814
- _add_timeseries_trace(fig, x_time=x_time, y=y, name=trace_name,
845
+ _add_timeseries_trace(trace_specs, x_time=x_time, y=y, name=trace_name,
815
846
  color=color, legendgroup=lg, visible=visible,
816
847
  use_scatter=use_scatter, hovertexts=hovertexts,
817
848
  max_gap_steps=_max_gap_steps, time_step=_time_step,
818
849
  iso_marker_size=_iso_marker_size)
819
850
 
820
- n_traces = len(fig.data)
851
+ n_traces = len(trace_specs)
821
852
  legend_rows = max(1, -(-n_traces // 3)) # ceil(n_traces / 3)
822
853
  bottom_margin = max(80, 30 + legend_rows * 28)
823
854
 
824
855
  # Approximate 7px per character at font size 11; min 120px.
825
- all_labels = [t.name or "" for t in fig.data] + [
826
- t.legendgrouptitle.text for t in fig.data
827
- if getattr(t, "legendgrouptitle", None) and t.legendgrouptitle.text
856
+ all_labels = [trace.get("name", "") for trace in trace_specs] + [
857
+ trace["legendgrouptitle_text"] for trace in trace_specs
858
+ if trace.get("legendgrouptitle_text")
828
859
  ]
829
860
  entry_width = max(80, max((len(l) for l in all_labels), default=10) * 7)
830
861
 
831
- fig.update_layout(
832
- title=title if title is not None else _dataset_title(ds),
833
- xaxis_title="Time",
834
- template="plotly_white",
835
- hovermode="x unified",
836
- showlegend=True,
837
- autosize=True,
838
- height=400 + bottom_margin,
839
- legend=dict(
840
- groupclick="toggleitem",
841
- itemclick="toggle",
842
- itemdoubleclick="toggleothers",
843
- orientation="h",
844
- yanchor="top",
845
- y=-0.2,
846
- xanchor="left",
847
- x=0,
848
- font=dict(size=11),
849
- entrywidth=entry_width,
850
- entrywidthmode="pixels",
862
+ fig = go.Figure(
863
+ data=trace_specs,
864
+ layout=dict(
865
+ title=title if title is not None else _dataset_title(ds),
866
+ xaxis_title="Time",
867
+ template="plotly_white",
868
+ hovermode="x unified",
869
+ showlegend=True,
870
+ autosize=True,
871
+ height=400 + bottom_margin,
872
+ legend=dict(
873
+ groupclick="toggleitem",
874
+ itemclick="toggle",
875
+ itemdoubleclick="toggleothers",
876
+ orientation="h",
877
+ yanchor="top",
878
+ y=-0.2,
879
+ xanchor="left",
880
+ x=0,
881
+ font=dict(size=11),
882
+ entrywidth=entry_width,
883
+ entrywidthmode="pixels",
884
+ ),
885
+ margin=dict(l=60, r=20, t=50, b=bottom_margin),
886
+ modebar=dict(remove=["lasso2d", "select2d"]),
851
887
  ),
852
- margin=dict(l=60, r=20, t=50, b=bottom_margin),
853
- modebar=dict(remove=["lasso2d", "select2d"]),
854
888
  )
855
889
  return fig
856
890
 
@@ -877,6 +911,11 @@ def plot_timeseries_per_var(
877
911
  if len(groups) <= 1:
878
912
  return [plot_timeseries(ds, mode=mode, _data_cache=data_cache)]
879
913
 
914
+ x_time = get_plot_time(ds)
915
+ time_step = pd.Series(pd.to_datetime(x_time)).diff().median()
916
+ use_scatter = (mode or _default_plot_mode(ds, time_step)) == "scatter"
917
+ hovertexts = _scatter_hovertexts(x_time, ds) if use_scatter else None
918
+
880
919
  # Walk the same sorted order as the combined plot to build per-variable color offsets.
881
920
  all_units = {_var_unit(ds, n) for n in plot_vars}
882
921
  preferred = (
@@ -913,7 +952,9 @@ def plot_timeseries_per_var(
913
952
  var_color_offsets={n: vc_map[n] for n in vars_ if n in vc_map},
914
953
  wl_color_offsets={n: wc_map[n] for n in vars_ if n in wc_map},
915
954
  mode=mode,
916
- _data_cache=data_cache)
955
+ _data_cache=data_cache,
956
+ _hovertexts=hovertexts,
957
+ _x_time=x_time)
917
958
  for lbl, vars_ in groups
918
959
  ]
919
960
 
File without changes
File without changes
File without changes
File without changes