-
Notifications
You must be signed in to change notification settings - Fork 70
/
stressmodels.py
1525 lines (1296 loc) · 58.2 KB
/
stressmodels.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 all the stress models available in Pastas.
Stress models are used to translate an input time series into a
contribution that explains (part of) the output series.
Examples
--------
>>> sm = ps.StressModel(stress, rfunc=ps.Gamma(), name="sm1")
>>> ml.add_stressmodel(stressmodel=sm)
See Also
--------
pastas.model.Model.add_stressmodel
"""
from logging import getLogger
import numpy as np
from pandas import DataFrame, Series, Timedelta, Timestamp, concat, date_range
from scipy.signal import fftconvolve
import inspect
from scipy import __version__ as scipyversion
from warnings import warn
from .decorators import njit, set_parameter
from .recharge import Linear
from .rfunc import Exponential, HantushWellModel, One
from .timeseries import TimeSeries
from .utils import check_numba, validate_name
from pastas.typeh import Type, Optional, Union, Tuple, pstAL, pstMl, pstTm, pstSM, pstRF, pstRB
logger = getLogger(__name__)
__all__ = ["StressModel", "Constant", "StepModel", "LinearTrend",
"RechargeModel", "WellModel", "TarsoModel", "ChangeModel"]
class StressModelBase:
"""StressModel Base class called by each StressModel object.
Attributes
----------
name: str
Name of this stressmodel object. Used as prefix for the parameters.
parameters: pandas.DataFrame
Dataframe containing the parameters.
"""
_name = "StressModelBase"
def __init__(self, name: str, tmin: pstTm, tmax: pstTm, rfunc: Optional[pstRF] = None, up: Optional[bool] = True, meanstress: Optional[float] = 1.0, cutoff: Optional[float] = 0.999):
self.name = validate_name(name)
self.tmin = tmin
self.tmax = tmax
self.freq = None
if rfunc is not None:
if inspect.isclass(rfunc):
DeprecationWarning('Response functions should be added to a '
'stress-model as an instance, and not as a '
'class. This will raise an error from '
'Pastas version 0.23.')
rfunc = rfunc()
rfunc._set_init_parameter_settings(up=up, meanstress=meanstress,
cutoff=cutoff)
self.rfunc = rfunc
self.parameters = DataFrame(
columns=['initial', 'pmin', 'pmax', 'vary', 'name'])
self.stress = []
@property
def nparam(self):
return self.parameters.index.size
def set_init_parameters(self):
"""Set the initial parameters (back) to their default values."""
@set_parameter
def _set_initial(self, name: str, value: float):
"""Internal method to set the initial parameter value.
Notes
-----
The preferred method for parameter setting is through the model.
"""
self.parameters.loc[name, 'initial'] = value
@set_parameter
def _set_pmin(self, name: str, value: float):
"""Internal method to set the lower bound of the parameter value.
Notes
-----
The preferred method for parameter setting is through the model.
"""
self.parameters.loc[name, 'pmin'] = value
@set_parameter
def _set_pmax(self, name: str, value: float):
"""Internal method to set the upper bound of the parameter value.
Notes
-----
The preferred method for parameter setting is through the model.
"""
self.parameters.loc[name, 'pmax'] = value
@set_parameter
def _set_vary(self, name: str, value: float):
"""Internal method to set if the parameter is varied during
optimization.
Notes
-----
The preferred method for parameter setting is through the model.
"""
self.parameters.loc[name, 'vary'] = bool(value)
def update_stress(self, **kwargs):
"""Method to update the settings of the individual TimeSeries.
Notes
-----
For the individual options for the different settings please refer to
the docstring from the TimeSeries.update_series() method.
See Also
--------
ps.timeseries.TimeSeries.update_series
"""
for stress in self.stress:
stress.update_series(**kwargs)
if "freq" in kwargs:
self.freq = kwargs["freq"]
def dump_stress(self, series: Optional[bool] = True):
"""Method to dump all stresses in the stresses list.
Parameters
----------
series: bool, optional
True if time series are to be exported, False if only the name
of the time series are needed. Settings are always exported.
Returns
-------
data: dict
dictionary with the dump of the stresses.
"""
data = []
for stress in self.stress:
stress.name = validate_name(stress.name, raise_error=True)
data.append(stress.to_dict(series=series))
return data
def get_stress(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None,
istress: Optional[int] = None, **kwargs) -> Type[DataFrame]:
"""Returns the stress or stresses of the time series object as a pandas
DataFrame.
If the time series object has multiple stresses each column
represents a stress.
Returns
-------
stress: pandas.Dataframe
Pandas dataframe of the stress(es)
"""
if tmin is None:
tmin = self.tmin
if tmax is None:
tmax = self.tmax
self.update_stress(tmin=tmin, tmax=tmax, freq=freq)
return self.stress[0].series
def to_dict(self, series: Optional[bool] = True) -> dict:
"""Method to export the StressModel object.
Returns
-------
data: dict
dictionary with all necessary information to reconstruct the
StressModel object.
"""
data = {
"stressmodel": self._name,
"name": validate_name(self.name, raise_error=True),
"stress": self.dump_stress(series)
}
return data
def get_nsplit(self):
"""Determine in how many timeseries the contribution can be split."""
if hasattr(self, 'nsplit'):
return self.nsplit
else:
return len(self.stress)
def _get_block(self, p: pstAL, dt: float, tmin: pstTm, tmax: pstTm):
"""Internal method to get the block-response function."""
if tmin is not None and tmax is not None:
day = Timedelta(1, 'D')
maxtmax = (Timestamp(tmax) - Timestamp(tmin)) / day
else:
maxtmax = None
b = self.rfunc.block(p, dt, maxtmax=maxtmax)
return b
class StressModel(StressModelBase):
"""Time series model consisting of the convolution of one stress with one
response function.
Parameters
----------
stress: pandas.Series
pandas Series object containing the stress.
rfunc: pastas.rfunc instance (class is deprecated)
Response function used in the convolution with the stress.
name: str
Name of the stress.
up: bool or None, optional
True if response function is positive (default), False if negative.
None if you don't want to define if response is positive or negative.
cutoff: float, optional
float between 0 and 1 to determine how long the response is (default
is 99% of the actual response time). Used to reduce computation times.
settings: dict or str, optional
The settings of the stress. This can be a string referring to a
predefined settings dict, or a dict with the settings to apply.
Refer to the docstring of pastas.Timeseries for further information.
metadata: dict, optional
dictionary containing metadata about the stress. This is passed onto
the TimeSeries object.
meanstress: float, optional
The mean stress determines the initial parameters of rfunc. The initial
parameters are chosen in such a way that the gain of meanstress is 1.
Examples
--------
>>> import pastas as ps
>>> import pandas as pd
>>> sm = ps.StressModel(stress=pd.Series(), rfunc=ps.Gamma(), name="Prec",
>>> settings="prec")
See Also
--------
pastas.rfunc
pastas.timeseries.TimeSeries
"""
_name = "StressModel"
def __init__(self, stress: Type[Series], rfunc: pstRF, name: str, up: Optional[bool] = True, cutoff: Optional[float] = 0.999,
settings: Optional[Union[dict, str]] = None, metadata: Optional[dict] = None, meanstress: Optional[float] = None):
if isinstance(stress, list):
stress = stress[0] # TODO Temporary fix Raoul, 2017-10-24
stress = TimeSeries(stress, settings=settings, metadata=metadata)
if meanstress is None:
meanstress = stress.series.std()
StressModelBase.__init__(self, name=name,
tmin=stress.series.index.min(),
tmax=stress.series.index.max(), rfunc=rfunc,
up=up, meanstress=meanstress, cutoff=cutoff)
self.freq = stress.settings["freq"]
self.stress = [stress]
self.set_init_parameters()
def set_init_parameters(self):
"""Set the initial parameters (back) to their default values."""
self.parameters = self.rfunc.get_init_parameters(self.name)
def simulate(self, p: pstAL, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, dt: Optional[float] = 1.0) -> Type[Series]:
"""Simulates the head contribution.
Parameters
----------
p: array_like
array_like object with the values as floats representing the
model parameters.
tmin: str, optional
tmax: str, optional
freq: str, optional
dt: int, optional
Returns
-------
pandas.Series
The simulated head contribution.
"""
self.update_stress(tmin=tmin, tmax=tmax, freq=freq)
b = self._get_block(p, dt, tmin, tmax)
stress = self.stress[0].series
npoints = stress.index.size
h = Series(data=fftconvolve(stress, b, 'full')[:npoints],
index=stress.index, name=self.name, fastpath=True)
return h
def to_dict(self, series: Optional[bool] = True) -> dict:
"""Method to export the StressModel object.
Returns
-------
data: dict
dictionary with all necessary information to reconstruct the
StressModel object.
"""
data = {
"stressmodel": self._name,
"rfunc": self.rfunc._name,
"rfunc_kwargs": self.rfunc.kwargs,
"name": self.name,
"up": self.rfunc.up,
"cutoff": self.rfunc.cutoff,
"stress": self.dump_stress(series)
}
return data
class StepModel(StressModelBase):
"""Stressmodel that simulates a step trend.
Parameters
----------
tstart: str or Timestamp
String with the start date of the step, e.g. '2018-01-01'. This
value is fixed by default. Use ml.set_parameter("step_tstart",
vary=True) to vary the start time of the step trend.
name: str
String with the name of the stressmodel.
rfunc: pastas.rfunc instance (class is deprecated)
Pastas response function used to simulate the effect of the step.
Default is rfunc.One, an instant effect.
up: bool, optional
Force a direction of the step. Default is None.
cutoff: float, optional
float between 0 and 1 to determine how long the response is (default
is 99.9% of the actual response time). Used to reduce computation
times.
Notes
-----
The step trend is calculated as follows. First, a binary series is
created, with zero values before tstart, and ones after the start. This
series is convoluted with the block response to simulate a step trend.
"""
_name = "StepModel"
def __init__(self, tstart: pstTm, name: str, rfunc: Optional[pstRF] = None, up: Optional[bool] = True, cutoff: Optional[float] = 0.999):
if rfunc is None:
rfunc = One()
StressModelBase.__init__(self, name=name, tmin=Timestamp.min,
tmax=Timestamp.max, rfunc=rfunc, up=up,
cutoff=cutoff)
self.tstart = Timestamp(tstart)
self.set_init_parameters()
def set_init_parameters(self):
self.parameters = self.rfunc.get_init_parameters(self.name)
tmin = Timestamp.min.toordinal()
tmax = Timestamp.max.toordinal()
tinit = self.tstart.toordinal()
self.parameters.loc[self.name + "_tstart"] = (tinit, tmin, tmax,
False, self.name)
def simulate(self, p: pstAL, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, dt: Optional[float] = 1.0) -> Type[Series]:
tstart = Timestamp.fromordinal(int(p[-1]))
tindex = date_range(tmin, tmax, freq=freq)
h = Series(0, tindex, name=self.name)
h.loc[h.index > tstart] = 1
b = self._get_block(p[:-1], dt, tmin, tmax)
npoints = h.index.size
h = Series(data=fftconvolve(h, b, 'full')[:npoints],
index=h.index, name=self.name, fastpath=True)
return h
def to_dict(self, series: Optional[bool] = True) -> dict:
data = {
"stressmodel": self._name,
'tstart': self.tstart,
'name': self.name,
"up": self.rfunc.up,
'rfunc': self.rfunc._name
}
return data
class LinearTrend(StressModelBase):
"""Stressmodel that simulates a linear trend.
Parameters
----------
start: str
String with a date to start the trend (e.g., "2018-01-01"), will be
transformed to an ordinal number internally.
end: str
String with a date to end the trend (e.g., "2018-01-01"), will be
transformed to an ordinal number internally.
name: str, optional
String with the name of the stress model.
Notes
-----
While possible, it is not recommended to vary the parameters for the
start and end time of the linear trend. These parameters are usually
hard to impossible to estimate from the data.
"""
_name = "LinearTrend"
def __init__(self, start, end, name="trend"):
StressModelBase.__init__(self, name=name, tmin=Timestamp.min,
tmax=Timestamp.max)
self.start = start
self.end = end
self.set_init_parameters()
def set_init_parameters(self):
"""Set the initial parameters for the stress model."""
start = Timestamp(self.start).toordinal()
end = Timestamp(self.end).toordinal()
tmin = Timestamp.min.toordinal()
tmax = Timestamp.max.toordinal()
self.parameters.loc[self.name + "_a"] = (0.0, -np.inf, np.inf,
True, self.name)
self.parameters.loc[self.name + "_tstart"] = (start, tmin, tmax,
False, self.name)
self.parameters.loc[self.name + "_tend"] = (end, tmin, tmax,
False, self.name)
def simulate(self, p: pstAL, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, dt: Optional[float] = 1.0) -> Type[Series]:
"""Simulate the trend."""
tindex = date_range(tmin, tmax, freq=freq)
if p[1] < tindex[0].toordinal():
tmin = tindex[0]
else:
tmin = Timestamp.fromordinal(int(p[1]))
if p[2] >= tindex[-1].toordinal():
tmax = tindex[-1]
else:
tmax = Timestamp.fromordinal(int(p[2]))
trend = tindex.to_series().diff() / Timedelta(1, "D")
trend.loc[:tmin] = 0
trend.loc[tmax:] = 0
trend = trend.cumsum() * p[0]
return trend.rename(self.name)
def to_dict(self, series: Optional[bool] = True) -> dict:
data = {
"stressmodel": self._name,
'start': self.start,
"end": self.end,
'name': self.name,
}
return data
class Constant(StressModelBase):
"""A constant value that is added to the time series model.
Parameters
----------
name: str, optional
Name of the stressmodel
initial: float, optional
Initial estimate of the parameter value. E.g. The minimum of the
observed series.
"""
_name = "Constant"
def __init__(self, name: Optional[str] = "constant", initial: Optional[float] = 0.0):
StressModelBase.__init__(self, name=name, tmin=Timestamp.min,
tmax=Timestamp.max)
self.initial = initial
self.set_init_parameters()
def set_init_parameters(self):
self.parameters.loc[self.name + '_d'] = (
self.initial, np.nan, np.nan, True, self.name)
@staticmethod
def simulate(p: Optional[float] = None) -> float:
return p
class WellModel(StressModelBase):
"""Convolution of one or more stresses with one response function.
Parameters
----------
stress: list
list containing the stresses timeseries.
rfunc: pastas.rfunc instance (class is deprecated)
this model only works with the HantushWellModel response function.
name: str
Name of the stressmodel.
distances: array_like
list of distances to oseries, must be ordered the same as the
stresses.
up: bool, optional
whether a positive stress has an increasing or decreasing effect on
the model, by default False, in which case positive stress lowers
e.g., the groundwater level.
cutoff: float, optional
float between 0 and 1 to determine how long the response is (default
is 99.9% of the actual response time). Used to reduce computation
times.
settings: str, list of dict, optional
settings of the timeseries, by default "well".
sort_wells: bool, optional
sort wells from closest to furthest, by default True.
Notes
-----
This class implements convolution of multiple series with a the same
response function. This can be applied when dealing with multiple
wells in a time series model. The distance from an influence to the
location of the oseries has to be provided for each stress.
Warnings
--------
This model only works with the HantushWellModel response function.
"""
_name = "WellModel"
def __init__(self, stress: list[Type[Series]], rfunc: pstRF, name: str, distances: pstAL, up: Optional[bool] = False, cutoff: Optional[float] = 0.999,
settings: Optional[str] = "well", sort_wells: Optional[bool] = True):
if not (isinstance(rfunc, HantushWellModel) or
issubclass(rfunc, HantushWellModel)):
raise NotImplementedError("WellModel only supports the rfunc "
"HantushWellModel!")
# Check if scipy < 1.8
from distutils.version import StrictVersion
if StrictVersion(scipyversion) < StrictVersion("1.8.0"):
logger.warning(
"It is recommended to use LmfitSolve as the solver "
"or update to scipy>=1.8.0 when implementing WellModel."
" See https://github.com/pastas/pastas/issues/177.")
# sort wells by distance
self.sort_wells = sort_wells
if self.sort_wells:
stress = [s for _, s in sorted(zip(distances, stress),
key=lambda pair: pair[0])]
if isinstance(settings, list):
settings = [s for _, s in sorted(zip(distances, settings),
key=lambda pair: pair[0])]
distances = np.sort(distances)
if settings is None or isinstance(settings, str):
settings = len(stress) * [settings]
# convert stresses to TimeSeries if necessary
stress = self.handle_stress(stress, settings)
# Check if number of stresses and distances match
if len(stress) != len(distances):
msg = "The number of stresses does not match the number" \
"of distances provided."
logger.error(msg)
raise ValueError(msg)
else:
self.distances = Series(index=[s.name for s in stress],
data=distances,
name="distances")
meanstress = np.max([s.series.std() for s in stress])
tmin = np.min([s.series.index.min() for s in stress])
tmax = np.max([s.series.index.max() for s in stress])
StressModelBase.__init__(self, name=name, tmin=tmin,
tmax=tmax, rfunc=rfunc, up=up,
meanstress=meanstress, cutoff=cutoff)
self.rfunc.set_distances(self.distances.values)
self.stress = stress
self.freq = self.stress[0].settings["freq"]
self.set_init_parameters()
def set_init_parameters(self):
self.parameters = self.rfunc.get_init_parameters(self.name)
def simulate(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, dt: Optional[float] = 1.0,
istress: Optional[int] = None, **kwargs):
distances = self.get_distances(istress=istress)
stress_df = self.get_stress(p=p, tmin=tmin, tmax=tmax, freq=freq,
istress=istress, squeeze=False)
h = Series(data=0, index=self.stress[0].series.index, name=self.name)
for name, r in distances.iteritems():
stress = stress_df.loc[:, name]
npoints = stress.index.size
p_with_r = np.concatenate([p, np.array([r])])
b = self._get_block(p_with_r, dt, tmin, tmax)
c = fftconvolve(stress, b, 'full')[:npoints]
h = h.add(Series(c, index=stress.index, fastpath=True),
fill_value=0.0)
if istress is not None:
if isinstance(istress, list):
h.name = self.name + "_" + "+".join(str(i) for i in istress)
elif self.stress[istress].name is not None:
h.name = self.stress[istress].name
else:
h.name = self.name + "_" + str(istress)
else:
h.name = self.name
return h
@staticmethod
def handle_stress(stress, settings):
"""Internal method to handle user provided stress in init.
Parameters
----------
stress: pandas.Series, pastas.TimeSeries, list or dict
stress or collection of stresses
settings: dict or iterable
settings dictionary
Returns
-------
stress: list
return a list with the stresses transformed to pastas TimeSeries.
"""
data = []
if isinstance(stress, Series):
data.append(TimeSeries(stress, settings=settings))
elif isinstance(stress, dict):
for i, (name, value) in enumerate(stress.items()):
data.append(TimeSeries(value, name=name, settings=settings[i]))
elif isinstance(stress, list):
for i, value in enumerate(stress):
data.append(TimeSeries(value, settings=settings[i]))
else:
logger.error("Stress format is unknown. Provide a Series, "
"dict or list.")
return data
def get_stress(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None,
istress: Optional[int] = None, squeeze: Optional[bool] = True, **kwargs) -> Type[DataFrame]:
if tmin is None:
tmin = self.tmin
if tmax is None:
tmax = self.tmax
self.update_stress(tmin=tmin, tmax=tmax, freq=freq)
if istress is None:
df = DataFrame.from_dict({s.name: s.series for s in self.stress})
if squeeze:
return df.squeeze()
else:
return df
elif isinstance(istress, list):
return DataFrame.from_dict(
{s.name: s.series for s in self.stress}
).iloc[:, istress]
else:
if squeeze:
return self.stress[istress].series
else:
return self.stress[istress].series.to_frame()
def get_distances(self, istress: Optional[int] = None):
if istress is None:
return self.distances
elif isinstance(istress, list):
return self.distances.iloc[istress]
else:
return self.distances.iloc[istress:istress + 1]
def get_parameters(self, model=None, istress: Optional[int] = None):
""" Get parameters including distance to observation point and
return as array (dimensions = (nstresses, 4)).
Parameters
----------
model : pastas.Model, optional
if provided, return optimal model parameters, else return
initial parameters
istress : int, optional
if provided, return specific parameter set, else
return all parameters
Returns
-------
p : np.array
parameters for each stress as row of array, if istress is used
returns only one row.
"""
if model is None:
p = self.parameters.initial.values
else:
p = model.get_parameters(self.name)
distances = self.get_distances(istress=istress).values
if distances.size > 1:
p_with_r = np.concatenate([np.tile(p, (distances.size, 1)),
distances[:, np.newaxis]], axis=1)
else:
p_with_r = np.r_[p, distances]
return p_with_r
def to_dict(self, series: Optional[bool] = True) -> dict:
"""Method to export the WellModel object.
Returns
-------
data: dict
dictionary with all necessary information to reconstruct the
WellModel object.
"""
data = {
"stressmodel": self._name,
"rfunc": self.rfunc._name,
"rfunc_kwargs": self.rfunc.kwargs,
"name": self.name,
"up": True if self.rfunc.up else False,
"distances": self.distances.to_list(),
"cutoff": self.rfunc.cutoff,
"stress": self.dump_stress(series),
"sort_wells": self.sort_wells
}
return data
def variance_gain(self, model: pstMl, istress: Optional[int] = None) -> float:
"""Calculate variance of the gain for WellModel.
Variance of the gain is calculated based on propagation of uncertainty
using optimal parameter values and the estimated variances of A and b
and the covariance between A and b.
Parameters
----------
model : pastas.Model
optimized model
istress : int or list of int, optional
index of stress(es) for which to calculate variance of gain
r : np.array, optional
radial distance(s) at which to calculate variance of the gain,
only considered if istress is None
Returns
-------
var_gain : float
variance of the gain calculated from model results
for parameters A and b
See Also
--------
pastas.HantushWellModel.variance_gain
"""
if model.fit is None:
raise AttributeError("Model not optimized! Run solve() first!")
if self.rfunc._name != "HantushWellModel":
raise ValueError("Response function must be HantushWellModel!")
if model.fit.pcov.isna().all(axis=None):
model.logger.warning("Covariance matrix contains only NaNs!")
# get parameters and (co)variances
A = model.parameters.loc[self.name + "_A", "optimal"]
b = model.parameters.loc[self.name + "_b", "optimal"]
var_A = model.fit.pcov.loc[self.name + "_A", self.name + "_A"]
var_b = model.fit.pcov.loc[self.name + "_b", self.name + "_b"]
cov_Ab = model.fit.pcov.loc[self.name + "_A", self.name + "_b"]
if istress is None and r is None:
r = np.asarray(self.distances)
elif isinstance(istress, int) or isinstance(istress, list):
if r is not None:
logger.warning("kwarg 'r' is only used if istress is None!")
r = self.distances.iloc[istress]
elif istress is not None and r is None:
raise ValueError("Parameter 'istress' must be None, list or int!")
return self.rfunc.variance_gain(A, b, var_A, var_b, cov_Ab, r=r)
class RechargeModel(StressModelBase):
"""Stressmodel simulating the effect of groundwater recharge on the
groundwater head.
Parameters
----------
prec: pandas.Series or pastas.timeseries.TimeSeries
pandas.Series or pastas.timeseries object containing the
precipitation series.
evap: pandas.Series or pastas.timeseries.TimeSeries
pandas.Series or pastas.timeseries object containing the potential
evaporation series.
rfunc: pastas.rfunc instance (class is deprecated), optional
Response function used in the convolution with the stress. Default
is Exponential.
name: str, optional
Name of the stress. Default is "recharge".
recharge: pastas.recharge instance, optional
String with the name of the recharge model. Options are: Linear (
default), FlexModel and Berendrecht. These can be accessed through
ps.rch.
temp: pandas.Series or pastas.timeseries.TimeSeries, optional
pandas.Series or pastas.TimeSeries object containing the
temperature series. It depends on the recharge model is this
argument is required or not.
cutoff: float, optional
float between 0 and 1 to determine how long the response is (default)
is 99.9% of the actual response time). Used to reduce computation
times.
settings: list of dicts or str, optional
The settings of the precipitation and evaporation time series,
in this order. This can be a string referring to a predefined
settings dict, or a dict with the settings to apply. Refer to the
docstring of pastas.Timeseries for further information. Default is (
"prec", "evap").
metadata: tuple of dicts or list of dicts, optional
dictionary containing metadata about the stress. This is passed onto
the TimeSeries object.
See Also
--------
pastas.rfunc
pastas.timeseries.TimeSeries
pastas.recharge
Notes
-----
This stress model computes the contribution of precipitation and
potential evaporation in two steps. In the first step a recharge flux is
computed by a model determined by the input argument `recharge`. In the
second step this recharge flux is convoluted with a response function to
obtain the contribution of recharge to the groundwater levels.
Examples
--------
>>> sm = ps.RechargeModel(rain, evap, rfunc=ps.Exponential(),
>>> recharge=ps.rch.FlexModel(), name="rch")
>>> ml.add_stressmodel(sm)
Warning
-------
We recommend not to store a RechargeModel is a variable named `rm`. This
name is already reserved in IPython to remove files and will cause
problems later.
"""
_name = "RechargeModel"
def __init__(self, prec: Type[Series], evap: Type[Series], rfunc: Optional[pstRF] = None, name: Optional[str] = "recharge",
recharge: Optional[pstSM] = Linear(), temp: Type[Series] = None, cutoff: Optional[float] = 0.999,
settings: Optional[Tuple[Union[str, dict], Union[str, dict], Union[str, dict]]] = ("prec", "evap", "evap"), metadata: Optional[Tuple[dict, dict, dict]] = (None, None, None)):
if rfunc is None:
rfunc = Exponential()
# Store the precipitation and evaporation time series
self.prec = TimeSeries(prec, settings=settings[0],
metadata=metadata[0])
self.evap = TimeSeries(evap, settings=settings[1],
metadata=metadata[1])
# Check if both series have a regular time step
if self.prec.freq_original is None:
msg = "Frequency of the precipitation series could not be " \
"determined. Please provide a time series with a regular " \
"time step."
raise IndexError(msg)
if self.evap.freq_original is None:
msg = "Frequency of the evaporation series could not be " \
"determined. Please provide a time series with a regular " \
"time step."
raise IndexError(msg)
# Store recharge object
self.recharge = recharge
# Store a temperature time series if provided/needed or set to None
if self.recharge.snow is True and temp is None:
msg = "Recharge model requires a temperature series. " \
"No temperature series were provided"
raise TypeError(msg)
if temp is not None:
if len(settings) < 3 or len(metadata) < 3:
msg = "Number of values for the settings and/or metadata is " \
"incorrect."
raise TypeError(msg)
else:
self.temp = TimeSeries(temp, settings=settings[2],
metadata=metadata[2])
else:
self.temp = None
# Select indices from validated stress where both series are available.
index = self.prec.series.index.intersection(self.evap.series.index)
if index.empty:
msg = ("The stresses that were provided have no overlapping"
"time indices. Please make sure the indices of the time"
"series overlap.")
logger.error(msg)
raise Exception(msg)
# Calculate initial recharge estimation for initial rfunc parameters
p = self.recharge.get_init_parameters().initial.values
meanstress = self.get_stress(p=p, tmin=index.min(), tmax=index.max(),
freq=self.prec.settings["freq"]).std()
StressModelBase.__init__(self, name=name, tmin=index.min(),
tmax=index.max(), rfunc=rfunc, up=True,
meanstress=meanstress, cutoff=cutoff)
self.stress = [self.prec, self.evap]
if self.temp:
self.stress.append(self.temp)
self.freq = self.prec.settings["freq"]
self.set_init_parameters()
if isinstance(self.recharge, Linear):
self.nsplit = 2
else:
self.nsplit = 1
def set_init_parameters(self):
"""Internal method to set the initial parameters."""
self.parameters = concat(
[self.rfunc.get_init_parameters(self.name),
self.recharge.get_init_parameters(self.name)
])
def update_stress(self, **kwargs):
"""Method to update the settings of the individual TimeSeries.
Notes
-----
For the individual options for the different settings please refer to
the docstring from the TimeSeries.update_series() method.
See Also
--------
ps.timeseries.TimeSeries.update_series
"""
self.prec.update_series(**kwargs)
self.evap.update_series(**kwargs)
if self.temp is not None:
self.temp.update_series(**kwargs)
if "freq" in kwargs:
self.freq = kwargs["freq"]
def simulate(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None,
dt: Optional[float] = 1.0, istress: Optional[int] = None, **kwargs) -> Type[Series]:
"""Method to simulate the contribution of recharge to the head.
Parameters
----------
p: array_like, optional
array_like object with the values as floats representing the
model parameters.
tmin: string, optional
tmax: string, optional
freq: string, optional
dt: float, optional
Time step to use in the recharge calculation.
istress: int, optional
This only works for the Linear model!
Returns
-------
pandas.Series
"""
if p is None:
p = self.parameters.initial.values
b = self._get_block(p[:self.rfunc.nparam], dt, tmin, tmax)
stress = self.get_stress(p=p, tmin=tmin, tmax=tmax, freq=freq,
istress=istress).values
name = self.name
if istress is not None:
if istress == 1 and self.nsplit > 1:
# only happen when Linear is used as the recharge model
stress = stress * p[-1]
if self.stress[istress].name is not None:
name = f"{self.name} ({self.stress[istress].name})"
return Series(data=fftconvolve(stress, b, 'full')[:stress.size],
index=self.prec.series.index, name=name, fastpath=True)