-
Notifications
You must be signed in to change notification settings - Fork 70
/
signatures.py
1385 lines (1051 loc) · 40 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."""
import pandas as pd
from pandas import Timedelta, DatetimeIndex, cut, Series
from numpy import diff, sqrt, log, arange, nan
import pastas as ps
from scipy.stats import linregress
from ..typeh import Type, Optional, Tuple
__all__ = ["cv_period_mean", "cv_date_min", "cv_fall_rate", "cv_rise_rate",
"parde_seasonality", "avg_seasonal_fluctuation", "magnitude",
"interannual_variation", "low_pulse_count", "high_pulse_count",
"low_pulse_duration", "high_pulse_duration", "amplitude_range",
"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_range", "baseflow_index",
"richards_pathlength", "richards_baker_index", "baseflow_stability"]
def _normalize(series: Type[Series]) -> Type[Series]:
series = (series - series.min()) / (series.max() - series.min())
return series
def cv_period_mean(series: Type[Series], freq: Optional[str] = "M") -> float:
"""Coefficient of variation of mean head over a period (default monthly).
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
freq: str, optional
frequency to resample the series to by averaging.
Returns
-------
cv: float
Coefficient of variation of mean head over a period (default monthly).
Notes
-----
Coefficient of variation of mean monthly heads [hughes_1989]_.
References
----------
.. [hughes_1989] Hughes, J., & James, B. (1989). A hydrological
regionalization of streams in Victoria, Australia, with implications
for stream Ecology. Marine and Freshwater Research, 40(3), 303–326.
"""
series = series.resample(freq).mean()
cv = series.std() / series.mean()
return cv
def cv_date_min(series: Type[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 groundwater head
according to [richter_1996]_.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174.
"""
data = series.groupby(series.index.year).idxmin().dropna().values
data = DatetimeIndex(data).dayofyear.to_numpy(float)
cv = data.std() / data.mean()
return cv
def parde_seasonality(series: Type[Series], normalize: Optional[bool] = True) -> float:
"""Parde seasonality according to [parde_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
-------
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 groundwater head divided by the overall mean
groundwater head.
References
----------
.. [parde_1933] Pardé, M. (1933). Fleuves et rivieres.
"""
coefficients = parde_coefficients(series=series, normalize=normalize)
return coefficients.max() - coefficients.min()
def parde_coefficients(series: Type[Series], normalize: Optional[bool] = True) -> float:
"""Parde coefficients for each month [parde_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
-------
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 groundwater head divided by the overall mean
groundwater head.
References
----------
.. [parde_1933] Pardé, M. (1933). Fleuves et rivieres.
"""
if normalize:
series = _normalize(series)
coefficients = series.groupby(series.index.month).mean() / series.mean()
coefficients.index.name = "month"
return coefficients
def _martens(series: Type[Series], normalize: Optional[bool] = True) -> Tuple[Type[Series], Type[Series]]:
"""Functions for the Martens average seasonal fluctuation and
interanual 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
Lowest heads
hw: pandas.Series
Largest heads
"""
if normalize:
series = _normalize(series)
s = series.resample("M")
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: Type[Series], normalize: Optional[bool] = True) -> float:
"""Classification according to [martens_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
Notes
-----
Mean annual difference between the averaged 3 highest monthly
groundwater heads per year and the averaged 3 lowest monthly groundwater
heads per year.
Average seasonal fluctuation (s):
s = MHW - MLW
References
----------
.. [martens_2013] Martens, K., van Camp, M., van Damme, D., & Walraevens,
K. (2013). Groundwater dynamics converted to a groundwater
classification as a tool for nature development programs in the
dunes. Journal of Hydrology, 499, 236–246.
"""
hl, hw = _martens(series, normalize=normalize)
return hw.mean() - hl.mean()
def interannual_variation(series: Type[Series], normalize: Optional[bool] = True) -> float:
"""Interannual variation after [martens_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
Notes
-----
The average between the range in annually averaged 3 highest monthly
groundwater heads and the range in annually averaged 3 lowest monthly
groundwater heads.
Inter-yearly variation of high and low water table (y):
y = ((max_HW - min_HW) + (max_LW - min_LW)) / 2
Warning: In this formulating the water table is references to a certain
datum and positive, not as depth below the surface!
References
----------
.. [martens_2013] Martens, K., van Camp, M., van Damme, D., & Walraevens,
K. (2013). Groundwater dynamics converted to a groundwater
classification as a tool for nature development programs in the
dunes. Journal of Hydrology, 499, 236–246.
"""
hl, hw = _martens(series, normalize=normalize)
return (hw.max() - hw.min()) + (hl.max() - hl.min()) / 2
def colwell_components(series: Type[Series], bins: Optional[int] = 11, freq: Optional[str] = "M", method: Optional[str] = "mean",
normalize: Optional[bool] = True) -> Tuple[float, float, float]:
"""Colwell predictability, constant, and contingency [colwell_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
-------
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.
References
----------
.. [colwell_1974] Colwell, R. K. (1974). Predictability Constancy and
Contingency of periodic phenomena. Ecology, 55(5), 1148–1153.
"""
# 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 = pd.DataFrame(binned)
df["time"] = df.index.month
df["values"] = 1
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 != 0)).sum().sum()
# Compute final components
p = 1 - (hxy - hy) / log(bins) # Predictability
c = 1 - hx / log(bins) # Constancy
m = (hx + hy - hxy) / log(bins) # Contingency
return p, c, m
def colwell_constancy(series: Type[Series], bins: Optional[int] = 11, freq: Optional[str] = "M", method: Optional[str] = "mean",
normalize: Optional[bool] = True) -> Tuple[float, float, float]:
"""Colwells constancy index after [colwell_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
-------
p, c, m: float, float, float
predictability, constancy, contingency
Notes
-----
One minus the sum of entropy with respect to state, divided by the
logarithm of the absolute number of possible states.
References
----------
.. [colwell_1974] Colwell, R. K. (1974). Predictability Constancy and
Contingency of periodic phenomena. Ecology, 55(5), 1148–1153.
"""
return \
colwell_components(series=series, bins=bins, freq=freq, method=method,
normalize=normalize)[1]
def colwell_contingency(series: Type[Series], bins: Optional[int] = 11, freq: Optional[str] = "M", method: Optional[str] = "mean",
normalize: Optional[bool] = True) -> Tuple[float, float, float]:
"""Colwell contingency [colwell_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
-------
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.
References
----------
.. [colwell_1974] Colwell, R. K. (1974). Predictability Constancy and
Contingency of periodic phenomena. Ecology, 55(5), 1148–1153.
"""
return \
colwell_components(series=series, bins=bins, freq=freq, method=method,
normalize=normalize)[2]
def low_pulse_count(series: Type[Series], quantile: Optional[float] = 0.2) -> int:
"""Number of times the series drops below a certain threshold.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
quantile: float, optional
Quantile used as a threshold.
Returns
-------
int
Number of times the series exceeds a certain threshold.
Notes
-----
Number of times during which the groundwater head drops below a certain
threshold. The threshold is defined as the 20th percentile of
nonexceedance [richter_1996]_.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174.
"""
h = series < series.quantile(quantile)
return (h.astype(int).diff() > 0).sum()
def high_pulse_count(series: Type[Series], quantile: Optional[float] = 0.8) -> int:
"""Number of times the series exceeds a certain threshold.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
quantile: float, optional
Quantile used as a threshold.
Returns
-------
h: int
Number of times the series exceeds a certain threshold.
Notes
-----
Number of times during which the groundwater head exceeds a certain
threshold. The threshold is defined as the 80th percentile of
nonexceedance.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174.
"""
h = series > series.quantile(quantile)
return (h.astype(int).diff() > 0).sum()
def low_pulse_duration(series: Type[Series], quantile: Optional[float] = 0.8) -> 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.
Returns
-------
Notes
-----
Average duration of pulses where the groundwater head drops below
a certain threshold. The threshold is defined as the 20th percentile of
non-exceedance.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174. https://doi.org/10.1046/j.1523‐1739.1996.10041163.x
"""
h = series < series.quantile(quantile)
sel = h.astype(int).diff().replace(0.0, nan).shift(-1).dropna().index
return (diff(sel.to_numpy()) / Timedelta("1D"))[::2].mean()
def high_pulse_duration(series: Type[Series], quantile: Optional[float] = 0.8) -> 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.
Returns
-------
float
Notes
-----
Average duration of pulses where the groundwater head drops exceeds a
certain threshold. The threshold is defined as the 80th percentile of
nonexceedance.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174. https://doi.org/10.1046/j.1523‐1739.1996.10041163.x
"""
h = series > series.quantile(quantile)
sel = h.astype(int).diff().replace(0.0, nan).shift(-1).dropna().index
return (diff(sel.to_numpy()) / Timedelta("1D"))[::2].mean()
def amplitude_range(series: Type[Series]) -> float:
"""Range of unscaled groundwater head.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
float
Notes
-----
Range of unscaled groundwater head.
"""
return series.max() - series.min()
def rise_rate(series: Type[Series], normalize: Optional[bool] = False) -> 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.
Returns
-------
float
Notes
-----
Mean rate of positive changes in head from one day to the next.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174. https://doi.org/10.1046/j.1523‐1739.1996.10041163.x
"""
if normalize:
series = _normalize(series)
difference = series.diff()
rises = difference[difference > 0]
return rises.mean()
def fall_rate(series: Type[Series], normalize: Optional[bool] = False) -> 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.
Returns
-------
float
Notes
-----
Mean rate of negative changes in head from one day to the next,
according to [richter_1996]_.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174. https://doi.org/10.1046/j.1523‐1739.1996.10041163.x
"""
if normalize:
series = _normalize(series)
difference = series.diff()
falls = difference[difference < 0]
return falls.mean()
def cv_rise_rate(series: Type[Series], normalize: Optional[bool] = False) -> 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.
Returns
-------
float
Notes
-----
Coefficient of Variation in riserate.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174. https://doi.org/10.1046/j.1523‐1739.1996.10041163.x
"""
if normalize:
series = _normalize(series)
difference = series.diff()
rises = difference[difference > 0]
return rises.std() / rises.mean()
def cv_fall_rate(series: Type[Series], normalize: Optional[bool] = False) -> 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.
Returns
-------
float
Notes
-----
Coefficient of Variation in fall rate.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174. https://doi.org/10.1046/j.1523‐1739.1996.10041163.x
"""
if normalize:
series = _normalize(series)
difference = series.diff()
falls = difference[difference < 0]
return falls.std() / falls.mean()
def magnitude(series: Type[Series]) -> float:
"""Difference of peak head to base head, divided by base head.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
float
Notes
-----
Difference of peak head to base head, divided by base head.
(h_max - h_min ) / h_min
References
----------
.. [hannah_2000] Hannah, D. M., Smith, B. P. G., Gurnell, A. M.,
& McGregor, G. R. (2000). An approach to hydrograph classification.
Hydrological Processes, 14(2), 317–338.
"""
return (series.max() - series.min()) / series.min()
def reversals_avg(series: Type[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
Notes
-----
Average annual number of rises and falls (i.e., change of sign) in daily
head.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174.
"""
reversals = (series.diff() > 0).astype(int).diff().replace(-1, 1)
return reversals.resample("A").sum().mean()
def reversals_cv(series: Type[Series]) -> float:
"""Coefficient of Variation in annual number of rises and falls.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
Returns
-------
float
Notes
-----
Coefficient of Variation in annual number of rises and falls in daily head.
References
----------
.. [richter_1996] Richter, B. D. (1996). A method for assessing hydrologic
alteration within ecosystems. Society for Conservation Biology, 10(4),
1163–1174.
"""
reversals = (series.diff() > 0).astype(int).diff().replace(-1, 1) \
.resample("A").sum()
return reversals.std() / reversals.mean()
def mean_annual_maximum(series: Type[Series], normalize: Optional[bool] = False) -> float:
"""Mean of annual maximum.
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
Notes
-----
References
----------
.. [clausen_2000] Clausen, B., & Biggs, B. J. F. (2000). Flow variables
for ecological studies in temperate streams—Groupings based on
covariance. Journal of Hydrology, 237(3‐4), 184–197.
"""
if normalize:
series = _normalize(series)
return series.resample("A").max().mean()
def bimodality_coefficient(series: Type[Series], normalize: Optional[bool] = False) -> float:
"""Bimodality coefficient after [Ellison_1987]_.
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
Notes
-----
Squared product moment skewness plus one, divided by product moment
kurtosis.
b = (skew **2 + 1 ) / kurtosis
Adapted from the R "modes" package
References
----------
.. [Ellison_1987] Ellison, A. M. (1987). Effect of seed dimorphism on the
density‐dependent dynamics of experimental populations of atriplex
triangularis. American Journal of Botany, 74(8), 1280–1288.
"""
if normalize:
series = _normalize(series)
series = series.dropna()
n = series.size
# Compute the skew for a finite sample
skew = (1 / n) * sum((series - series.mean()) ** 3) / \
(((1 / n) * sum((series - series.mean()) ** 2)) ** 1.5)
skew *= (sqrt(n * (n - 1))) / (n - 2)
# Compute the kurtosis for a finite sample
kurt = (1 / n) * sum((series - series.mean()) ** 4) / \
(((1 / n) * sum((series - series.mean()) ** 2)) ** 2) - 3
kurt = ((n - 1) * ((n + 1) * kurt - 3 * (n - 1)) / ((n - 2) * (n - 3))) + 3
return ((skew ** 2) + 1) / \
(kurt + ((3 * ((n - 1) ** 2)) / ((n - 2) * (n - 3))))
def recession_constant(series: Type[Series], bins: Optional[int] = 20, normalize: Optional[bool] = False) -> float:
"""Recession constant after [kirchner_2009]_.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
bins: int, optional
Number of bins to bin the data to.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
float
Notes
-----
Slope of the linear model fitted to percentile‐wise binned means in a
log‐log plot of negative head versus negative head one time step ahead.
References
----------
.. [kirchner_2009] Kirchner, J. W. (2009). Catchments as simple dynamical
systems: Catchment characterization, rainfall‐runoff modeling, and doing
hydrology backward. Water Resources Research, 45, W02429.
"""
if normalize:
series = _normalize(series)
series.name = "diff"
df = pd.DataFrame(series.diff().loc[series.diff() < 0], columns=["diff"])
df["head"] = series.loc[df.index]
binned = pd.Series(dtype=float)
for g in df.groupby(pd.cut(df["head"], bins=bins)):
binned[g[0].mid] = g[1]["diff"].mean()
binned = binned.dropna()
fit = linregress(log(binned.index), log(-binned.values))
return fit.slope
def recovery_constant(series: Type[Series], bins: Optional[int] = 20, normalize: Optional[bool] = False) -> float:
"""Recovery constant after [kirchner_2009]_.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
bins: int, optional
Number of bins to bin the data to.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
float
Notes
-----
Slope of the linear model fitted to percentile‐wise binned means in a
log‐log plot of positive head versus positive head one time step ahead.
References
----------
.. [kirchner_2009] Kirchner, J. W. (2009). Catchments as simple dynamical
systems: Catchment characterization, rainfall‐runoff modeling, and doing
hydrology backward. Water Resources Research, 45, W02429.
"""
if normalize:
series = _normalize(series)
series.name = "diff"
df = pd.DataFrame(series.diff().loc[series.diff() > 0], columns=["diff"])
df["head"] = series.loc[df.index]
binned = pd.Series(dtype=float)
for g in df.groupby(pd.cut(df["head"], bins=bins)):
binned[g[0].mid] = g[1]["diff"].mean()
binned = binned.dropna()
fit = linregress(log(binned.index), log(binned.values))
return fit.slope
def duration_curve_slope(series: Type[Series], l: Optional[float] = 0.1, u: Optional[float] = 0.9, normalize: Optional[bool] = True) -> float:
"""Slope of the duration curve between percentile l and u.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
l: float
lower percentile, a float between 0 and 1, lower than u
u: float, optional
upper percentile, a float between 0 and 1, higher than l.
normalize: bool, optional
normalize the time series to values between zero and one.
Returns
-------
float
Notes
-----
Slope of the duration curve (analogue flow duration curve for streamflow)
between percentile l and u.
References
----------
.. [oudin_2010] Oudin, L., Kay, A., Andréassian, V., & Perrin, C. (2010).
Are seemingly physically similar catchments truly hydrologically
similar? Water Resources Research, 46, W11558.
"""
if normalize:
series = _normalize(series)
s = series[(series.quantile(l) > series) & (series < series.quantile(
u))].sort_values()
s.index = arange(s.size) / s.size
return linregress(s.index, s.values).slope
def duration_curve_range(series: Type[Series], l: Optional[float] = 0.1, u: Optional[float] = 0.9, normalize: Optional[bool] = True) -> float:
"""Range of the duration curve between the percentile l and u.
Parameters
----------
series: pandas.Series
Pandas Series with DatetimeIndex and head values.
l: float
lower percentile, a float between 0 and 1, lower than u
u: float, optional
upper percentile, a float between 0 and 1, higher than l.
normalize: bool, optional
normalize the time series to values between zero and one.