-
Notifications
You must be signed in to change notification settings - Fork 71
/
signatures.py
1779 lines (1418 loc) · 53.1 KB
/
signatures.py
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
"""This module contains methods to compute the groundwater signatures. Part of the
signatures selection is based on the work of :cite:t:`heudorfer_index-based_2019`."""
# Type Hinting
from logging import getLogger
from typing import Optional, Tuple, Union
from numpy import (
arctan,
array,
cos,
diff,
exp,
isclose,
isnan,
linspace,
log,
nan,
ndarray,
pi,
sin,
split,
sqrt,
where,
)
from pandas import DataFrame, DatetimeIndex, Series, Timedelta, concat, cut, to_datetime
from scipy.optimize import curve_fit
from scipy.stats import linregress
import pastas as ps
from pastas.stats.core import acf
__all__ = [
"cv_period_mean",
"cv_date_min",
"cv_date_max",
"cv_fall_rate",
"cv_rise_rate",
"parde_seasonality",
"avg_seasonal_fluctuation",
"interannual_variation",
"low_pulse_count",
"high_pulse_count",
"low_pulse_duration",
"high_pulse_duration",
"bimodality_coefficient",
"mean_annual_maximum",
"rise_rate",
"fall_rate",
"reversals_avg",
"reversals_cv",
"colwell_contingency",
"colwell_constancy",
"recession_constant",
"recovery_constant",
"duration_curve_slope",
"duration_curve_ratio",
"richards_pathlength",
"baselevel_index",
"baselevel_stability",
"magnitude",
"autocorr_time",
"date_min",
"date_max",
]
logger = getLogger(__name__)
def _normalize(series: Series) -> Series:
"""Normalize the time series by subtracting the mean and dividing over the range.
Parameters
----------
series: pandas.Series
Pandas Series to be normalized.
Returns
-------
series: pandas.Series
Pandas Series scaled by subtracting the mean and dividing over the range of the
values. This results in a time series with values between zero and one.
"""
series = (series - series.min()) / (series.max() - series.min())
return series
def cv_period_mean(series: Series, normalize: bool = False, freq: str = "M") -> float:
"""Coefficient of variation of the mean head over a period (default monthly).
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
freq: str, optional
frequency to resample the series to by averaging.
Returns
-------
cv: float
Coefficient of variation of mean head resampled over a period (default monthly).
Notes
-----
Coefficient of variation of mean monthly heads, adapted after
:cite:t:`hughes_hydrological_1989`. The higher the coefficient of variation, the
more variable the mean monthly head is throughout the year, and vice versa. The
coefficient of variation is the standard deviation divided by the mean.
Examples
--------
>>> import pandas as pd
>>> from pastas.stats.signatures import cv_period_mean
>>> series = pd.Series([1, 2, 3, 4, 5, 6],
index=pd.date_range(start='2022-01-01', periods=6, freq='M'))
>>> cv = cv_period_mean(series)
>>> print(cv)
"""
if normalize:
series = _normalize(series)
series = series.resample(freq).mean()
cv = series.std(ddof=1) / series.mean() # ddof=1 = > sample std
return cv
def _cv_date_min_max(series: Series, stat: str) -> float:
"""Method to compute the coefficient of variation of the date of annual
minimum or maximum head using circular statistics.
Parameters
----------
series : Series
Pandas Series with DatetimeIndex and head values.
stat : str
"min" or "max" to compute the cv of the date of the annual minimum or maximum
head.
Returns
-------
float:
Circular coefficient of variation of the date of annual minimum or maximum
head.
Notes
-----
Coefficient of variation of the date of annual minimum or maximum head computed
using circular statistics as described in :cite:t:`fisher_statistical_1995` (page
32). If there are multiple dates with the same minimum or maximum head, the first
date is chosen. The higher the coefficient of variation, the more variable the date
of the annual minimum or maximum head is, and vice versa.
"""
if stat == "min":
data = series.groupby(series.index.year).idxmin(skipna=True).dropna().values
elif stat == "max":
data = series.groupby(series.index.year).idxmax(skipna=True).dropna().values
doy = DatetimeIndex(data).dayofyear.to_numpy(float)
m = 365.25
two_pi = 2 * pi
thetas = array(doy) * two_pi / m
c = cos(thetas).sum()
s = sin(thetas).sum()
r = sqrt(c**2 + s**2) / doy.size
if (s > 0) & (c > 0):
mean_theta = arctan(s / c)
elif c < 0:
mean_theta = arctan(s / c) + pi
elif (s < 0) & (c > 0):
mean_theta = arctan(s / c) + two_pi
else:
# This should never happen
raise ValueError("Something went wrong in the circular statistics.")
mu = mean_theta * m / two_pi
std = sqrt(-2 * log(r)) * m / two_pi
return std / mu
def cv_date_min(series: Series) -> float:
"""Coefficient of variation of the date of annual minimum head.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
cv: float
Coefficient of variation of the date of annual minimum head.
Notes
-----
Coefficient of variation of the date of annual minimum head computed using circular
statistics as described in :cite:t:`fisher_statistical_1995` (page 32). If there
are multiple dates with the same minimum head, the first date is chosen. The higher
the coefficient of variation, the more variable the date of the annual minimum head
is, and vice versa.
"""
cv = _cv_date_min_max(series, stat="min")
return cv
def cv_date_max(series: Series) -> float:
"""Coefficient of variation of the date of annual maximum head.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
cv: float
Coefficient of variation of the date of annual maximum head.
Notes
-----
Coefficient of variation of the date of annual maximum head computed using circular
statistics as described in :cite:t:`fisher_statistical_1995` (page 32). If there
are multiple dates with the same maximum head, the first date is chosen. The higher
the coefficient of variation, the more variable the date of the maximum head is,
and vice versa.
"""
cv = _cv_date_min_max(series, stat="max")
return cv
def parde_seasonality(series: Series, normalize: bool = True) -> float:
"""Parde seasonality according to :cite:t:`parde_fleuves_1933`, adapted for heads.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
float:
Parde seasonality.
Notes
-----
Pardé seasonality is the difference between the maximum and minimum Pardé
coefficient. A Pardé series consists of 12 Pardé coefficients, corresponding to
12 months. Pardé coefficient for, for example, January is its long-term monthly
mean head divided by the overall mean head. The higher the Pardé seasonality, the
more seasonal the head is, and vice versa.
"""
coefficients = _parde_coefficients(series=series, normalize=normalize)
return coefficients.max() - coefficients.min()
def _parde_coefficients(series: Series, normalize: bool = True) -> Series:
"""Parde coefficients for each month :cite:t:`parde_fleuves_1933`.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
coefficients: pandas.Series
Parde coefficients for each month.
Notes
-----
Pardé seasonality is the difference between the maximum and minimum Pardé
coefficient. A Pardé series consists of 12 Pardé coefficients, corresponding to
12 months. Pardé coefficient for, for example, January is its long-term monthly
mean head divided by the overall mean head.
Examples
--------
>>> import pandas as pd
>>> from pastas.stats.signatures import parde_coefficients
>>> series = pd.Series([1, 2, 3, 4, 5, 6],
index=pd.date_range(start='2022-01-01', periods=6, freq='M'))
>>> coefficients = parde_coefficients(series)
>>> print(coefficients)
month
1 0.0
2 0.4
3 0.8
4 1.2
5 1.6
6 2.0
dtype: float64
"""
if normalize:
series = _normalize(series)
coefficients = series.groupby(series.index.month).mean() / series.mean()
coefficients.index.name = "month"
return coefficients
def _martens(series: Series, normalize: bool = False) -> Tuple[Series, Series]:
"""Function for the average seasonal fluctuation and interannual fluctuation.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
hl: pandas.Series
Average of the three lowest heads in a year.
hw: pandas.Series
Average of the three largest heads in a year.
Notes
-----
According to :cite:t:`martens_groundwater_2013`. The average of the three lowest
and three highest heads in three different months for each year is computed. The
average is then taken over all years.
"""
if normalize:
series = _normalize(series)
s = series.resample("M")
s_min = s.min()
s_max = s.max()
hl = s_min.groupby(s_min.index.year).nsmallest(3).groupby(level=0).mean()
hw = s_max.groupby(s_max.index.year).nlargest(3).groupby(level=0).mean()
return hl, hw
def avg_seasonal_fluctuation(series: Series, normalize: bool = False) -> float:
"""Average seasonal fluctuation after :cite:t:`martens_groundwater_2013`.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
float:
Average seasonal fluctuation (s).
Notes
-----
Mean annual difference between the averaged 3 highest monthly heads
per year and the averaged 3 lowest monthly heads per year.
Average seasonal fluctuation (s):
s = MHW - MLW
A higher value of s indicates a more seasonal head, and vice versa.
Warning
-------
In this formulating the water table is referenced to a certain datum and
positive, not as depth below the surface!
"""
hl, hw = _martens(series, normalize=normalize)
return (hw - hl).mean()
def interannual_variation(series: Series, normalize: bool = False) -> float:
"""Interannual variation after :cite:t:`martens_groundwater_2013`.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
float:
Interannual variation (s).
Notes
-----
The average between the range in annually averaged 3 highest monthly heads and the
range in annually averaged 3 lowest monthly heads.
Inter-yearly variation of high and low water table (s):
s = ((max_HW - min_HW) + (max_LW - min_LW)) / 2
A higher value of s indicates a more variable head, and vice versa.
Warning
-------
In this formulating the water table is referenced to a certain datum and
positive, not as depth below the surface!
"""
hl, hw = _martens(series, normalize=normalize)
return ((hw.max() - hw.min()) + (hl.max() - hl.min())) / 2
def _colwell_components(
series: Series,
bins: int = 11,
freq: str = "W",
method: str = "mean",
normalize: bool = True,
) -> Tuple[float, float, float]:
"""Colwell's predictability, constant, and contingency
:cite:t:`colwell_predictability_1974`.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
bins: int
number of bins to determine the states of the groundwater.
freq: str, optional
frequency to resample the series to. Possible options are "D", "W", or "M".
method: str, optional
Method to use for resampling. Only "mean" is allowed now.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
p, c, m: float, float, float
predictability, constancy, contingency
Notes
-----
The difference between the sum of entropy for each time step and possible state
of the seasonal cycle, and the overall entropy across all states and time steps,
divided by the logarithm of the absolute number of possible states. Entropy
according to definition in information theory, see reference for details.
"""
# Prepare data and pivot table
if normalize:
series = _normalize(series)
if method == "mean":
series = series.resample(freq).mean().dropna()
else:
raise NotImplementedError
series.name = "head"
binned = cut(
series, bins=bins, right=False, include_lowest=True, labels=range(bins)
)
df = DataFrame(binned, dtype=float)
if freq == "M":
df["time"] = df.index.isocalendar().month
elif freq == "W":
df["time"] = df.index.isocalendar().week
elif freq == "D":
df["time"] = df.index.isocalendar().day
else:
msg = "freq %s is not a supported option."
logger.error(msg, freq)
raise ValueError(msg % freq)
df["values"] = 1.0
df = df.pivot_table(columns="head", index="time", aggfunc="sum", values="values")
# Count of rows and column items
x = df.sum(axis=1) # Time
y = df.sum(axis=0) # Head
z = series.size # Total number of observations
hx = -(x / z * log(x / z)).sum()
hy = -(y / z * log(y / z)).sum()
hxy = -(df / z * log(df / z, where=df.values != 0)).sum().sum()
# Compute final components
p = 1 - (hxy - hx) / log(bins) # Predictability
c = 1 - hy / log(bins) # Constancy
m = (hx + hy - hxy) / log(bins) # Contingency
return p, c, m
def colwell_constancy(
series: Series,
bins: int = 11,
freq: str = "W",
method: str = "mean",
normalize: bool = True,
) -> Tuple[float, float, float]:
"""Colwells constancy index after :cite:t:`colwell_predictability_1974`.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
bins: int
number of bins to determine the states of the groundwater.
freq: str, optional
frequency to resample the series to.
method: str, optional
Method to use for resampling. Only "mean" is allowed now.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
c: float
Colwell's constancy.
Notes
-----
One minus the sum of entropy with respect to state, divided by the logarithm of
the absolute number of possible states.
"""
return _colwell_components(
series=series, bins=bins, freq=freq, method=method, normalize=normalize
)[1]
def colwell_contingency(
series: Series,
bins: int = 11,
freq: str = "W",
method: str = "mean",
normalize: bool = True,
) -> Tuple[float, float, float]:
"""Colwell's contingency :cite:t:`colwell_predictability_1974`
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
bins: int
number of bins to determine the states of the groundwater.
freq: str, optional
frequency to resample the series to.
method: str, optional
Method to use for resampling. Only "mean" is allowed now.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
m: float
Colwell's contingency.
Notes
-----
The difference between the sum of entropy for each time step and possible state
of the seasonal cycle, and the overall entropy across all states and time steps,
divided by the logarithm of the absolute number of possible states. Entropy
according to definition in information theory, see reference for details.
"""
return _colwell_components(
series=series, bins=bins, freq=freq, method=method, normalize=normalize
)[2]
def low_pulse_count(
series: Series, quantile: float = 0.2, rolling_window: Union[str, None] = "7D"
) -> float:
"""Average number of times the series exceeds a certain threshold per year.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
quantile: float, optional
Quantile used as a threshold.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Average number of times the series exceeds a certain threshold per year.
Notes
-----
Number of times during which the head drops below a certain threshold.
The threshold is defined as the 20th percentile of non-exceedance
:cite:t:`richter_method_1996`.
Warning
-------
This method is sensitive to measurement noise, e.g., every change is sign in the
differences is counted as a pulse. Therefore, it is recommended to smooth the time
series first (which is also the default).
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
h = series < series.quantile(quantile)
sel = h.astype(int).diff().replace(0.0, nan).shift(-1).dropna().index
# Deal with pulses in the beginning and end of the time series
if h.iloc[0]:
sel = sel.append(series.index[:1]).sort_values()
if h.iloc[-1]:
sel = sel.append(series.index[-1:]).sort_values()
return sel.size / 2 / series.index.year.unique().size
def high_pulse_count(
series: Series, quantile: float = 0.8, rolling_window: Union[str, None] = "7D"
) -> float:
"""Average number of times the series exceeds a certain threshold per year.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
quantile: float, optional
Quantile used as a threshold.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Average number of times the series exceeds a certain threshold per year.
Notes
-----
Number of times during which the head exceeds a certain threshold. The threshold is
defined as the 80th percentile of non-exceedance.
Warning
-------
This method is sensitive to measurement noise, e.g., every change is sign in the
differences is counted as a pulse. Therefore, it is recommended to smooth the time
series first (which is also the default).
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
h = series > series.quantile(quantile)
sel = h.astype(int).diff().replace(0.0, nan).shift(-1).dropna().index
if h.iloc[0]:
sel = sel.append(series.index[:1]).sort_values()
if h.iloc[-1]:
sel = sel.append(series.index[-1:]).sort_values()
return sel.size / 2 / series.index.year.unique().size
def low_pulse_duration(
series: Series, quantile: float = 0.2, rolling_window: Union[str, None] = "7D"
) -> float:
"""Average duration of pulses where the head is below a certain threshold.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
quantile: float, optional
Quantile used as a threshold.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Average duration (in days) of pulses where the head drops below a certain
threshold.
Notes
-----
Average duration of pulses (in days) where the head drops below a certain threshold.
Warning
-------
This method is sensitive to measurement noise, e.g., every change is sign in the
differences is counted as a pulse. Therefore, it is recommended to smooth the time
series first (which is also the default).
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
h = series < series.quantile(quantile)
sel = h.astype(int).diff().replace(0.0, nan).shift(-1).dropna().index
if h.iloc[0]:
sel = sel.append(series.index[:1]).sort_values()
if h.iloc[-1]:
sel = sel.append(series.index[-1:]).sort_values()
return (diff(sel.to_numpy()) / Timedelta("1D"))[::2].mean()
def high_pulse_duration(
series: Series, quantile: float = 0.8, rolling_window: Union[str, None] = "7D"
) -> float:
"""Average duration of pulses where the head exceeds a certain threshold.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
quantile: float, optional
Quantile used as a threshold.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Average duration (in days) of pulses where the head drops below a certain
threshold.
Notes
-----
Average duration of pulses where the head drops exceeds a certain threshold. The
threshold is defined as the 80th percentile of non-exceedance.
Warning
-------
This method is sensitive to measurement noise, e.g., every change is sign in the
differences is counted as a pulse. Therefore, it is recommended to smooth the time
series first (which is also the default).
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
h = series > series.quantile(quantile)
sel = h.astype(int).diff().replace(0.0, nan).shift(-1).dropna().index
if h.iloc[0]:
sel = sel.append(series.index[:1]).sort_values()
if h.iloc[-1]:
sel = sel.append(series.index[-1:]).sort_values()
return (diff(sel.to_numpy()) / Timedelta("1D"))[::2].mean()
def _get_differences(series: Series, normalize: bool = False) -> Series:
"""Get the changes in the time series.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
differences: pandas.Series
Differences in the time series in L/day.
Notes
-----
Get the differences in the time series, and divide by the time step to get the rate
of change. If normalize is True, the time series is normalized to values between
zero and one.
"""
if normalize:
series = _normalize(series)
dt = diff(series.index.to_numpy()) / Timedelta("1D")
differences = series.diff().iloc[1:] / dt
return differences
def rise_rate(
series: Series, normalize: bool = False, rolling_window: Union[str, None] = "7D"
) -> float:
"""Mean of positive head changes from one day to the next.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Mean of positive head changes from one day to the next. The units of the rise
rate are L/day (L defined by the input).
Notes
-----
Mean rate of positive changes in head from one day to the next.
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
differences = _get_differences(series, normalize=normalize)
rises = differences[differences > 0]
return rises.mean()
def fall_rate(
series: Series, normalize: bool = False, rolling_window: Union[str, None] = "7D"
) -> float:
"""Mean negative head changes from one day to the next.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Mean of negative head changes from one day to the next. The units of the fall
rate are L/day (L defined by the input).
Notes
-----
Mean rate of negative changes in head from one day to the next, according to
:cite:t:`richter_method_1996`.
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
differences = _get_differences(series, normalize=normalize)
falls = differences.loc[differences < 0]
return falls.mean()
def cv_rise_rate(
series: Series, normalize: bool = True, rolling_window: Union[str, None] = "7D"
) -> float:
"""Coefficient of Variation in rise rate.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Coefficient of Variation in rise rate.
Notes
-----
Coefficient of variation in rise rate :cite:p:`richter_method_1996`. The higher the
coefficient of variation, the more variable the rise rate is, and vice versa.
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
differences = _get_differences(series, normalize=normalize)
rises = differences[differences > 0]
return rises.std(ddof=1) / rises.mean()
def cv_fall_rate(
series: Series, normalize: bool = False, rolling_window: Union[str, None] = "7D"
) -> float:
"""Coefficient of Variation in fall rate.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
normalize: bool, optional
normalize the time series to values between zero and one.
rolling_window: str, optional
Rolling window to use for smoothing the time series. Default is 7 days. Set to
None to disable. See the pandas documentation for more information.
Returns
-------
float:
Coefficient of Variation in fall rate.
Notes
-----
Coefficient of Variation in fall rate :cite:p:`richter_method_1996`. The higher the
coefficient of variation, the more variable the fall rate is, and vice versa.
"""
if rolling_window is not None:
series = series.rolling(rolling_window).mean()
differences = _get_differences(series, normalize=normalize)
falls = differences[differences < 0]
return falls.std(ddof=1) / falls.mean()
def magnitude(series: Series) -> float:
"""Difference between the minimum and maximum heads, divided by the minimum head
adapted after :cite:t:`hannah_approach_2000`.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
float:
Difference between the minimum and maximum heads, divided by the minimum head.
Notes
-----
Difference between the minimum and maximum heads, divided by the minimum head:
..math::
(h_max - h_min ) / h_min
The higher the magnitude, the more variable the head is, and vice versa.
"""
return (series.max() - series.min()) / series.min()
def reversals_avg(series: Series) -> float:
"""Average annual number of rises and falls in daily head.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
float:
Average number of rises and falls in daily head per year.
Notes
-----
Average annual number of rises and falls (i.e., change of sign) in daily head
:cite:p:`richter_method_1996`. The higher the number of reversals, the more
variable the head is, and vice versa. If the head data is not daily, a warning is
issued and nan is returned.
"""
# Get the time step in days
dt = diff(series.index.to_numpy()) / Timedelta("1D")
# Check if the time step is approximately daily
if not (dt > 0.9).all() & (dt < 1.1).all():
msg = (
"The time step is not approximately daily (>10%% of time steps are"
"non-daily). This may lead to incorrect results."
)
logger.warning(msg)
return nan