-
Notifications
You must be signed in to change notification settings - Fork 70
/
model.py
1881 lines (1594 loc) · 71.1 KB
/
model.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 the Model class in Pastas.
# Python Dependencies
from collections import OrderedDict
from itertools import combinations
from logging import getLogger
from os import getlogin
# External Dependencies
import numpy as np
from pandas import (DataFrame, Series, Timedelta, Timestamp,
date_range, concat, to_timedelta)
# Internal Pastas
from pastas.decorators import get_stressmodel
from pastas.io.base import _load_model, dump
from pastas.modelstats import Statistics
from pastas.noisemodels import NoiseModel, NoiseModelBase
from pastas.modelplots import Plotting
from pastas.solver import LeastSquares, BaseSolver
from pastas.stressmodels import Constant, StressModelBase
from pastas.timeseries import TimeSeries
from pastas.transform import ThresholdTransform
from pastas.utils import (_get_dt, _get_time_offset, frequency_is_supported,
get_sample, validate_name)
from pastas.version import __version__
# Type Hinting
from pastas.typing import Type, Union, Optional, Tuple, List, pstTm, pstSM, pstNM, pstBS, pstAL, pstMl
class Model:
"""Class that initiates a Pastas time series model.
Parameters
----------
oseries: pandas.Series or pastas.TimeSeries
pandas Series object containing the dependent time series. The
observation can be non-equidistant.
constant: bool, optional
Add a constant to the model (Default=True).
noisemodel: bool, optional
Add the default noisemodel to the model. A custom noisemodel can be
added later in the modelling process as well.
name: str, optional
String with the name of the model, used in plotting and saving.
metadata: dict, optional
Dictionary containing metadata of the oseries, passed on the to
oseries when creating a pastas TimeSeries object. hence,
ml.oseries.metadata will give you the metadata.
freq: str, optional
String with the frequency the stressmodels are simulated. Must
be one of the following: (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D". Default is "D". New in 0.18.0.
Returns
-------
ml: pastas.model.Model
Pastas Model instance, the base object in Pastas.
Examples
--------
A minimal working example of the Model class is shown below:
>>> oseries = pd.Series([1,2,1], index=pd.to_datetime(range(3), unit="D"))
>>> ml = Model(oseries)
"""
def __init__(self, oseries: Union[Type[Series], Type[TimeSeries]], constant: Optional[bool] = True,
noisemodel: Optional[bool] = True, name: Optional[str] = None,
metadata: Optional[dict] = None, freq: Optional[str] = "D"):
self.logger = getLogger(__name__)
# Construct the different model components
self.oseries = TimeSeries(oseries, settings="oseries",
metadata=metadata)
if name is None and self.oseries.name is not None:
name = self.oseries.name
elif name is None and self.oseries.name is None:
name = 'Observations'
self.name = validate_name(name)
self.parameters = DataFrame(
columns=["initial", "name", "optimal", "pmin", "pmax", "vary",
"stderr"])
# Define the model components
self.stressmodels = OrderedDict()
self.constant = None
self.transform = None
self.noisemodel = None
# Default solve/simulation settings
self.settings = {
"tmin": None,
"tmax": None,
"freq": freq,
"warmup": (3650 * to_timedelta(freq) if freq[0].isdigit()
else Timedelta(3650, freq)),
"time_offset": Timedelta(0),
"noise": noisemodel,
"solver": None,
"fit_constant": True,
}
if constant:
constant = Constant(initial=self.oseries.series.mean(),
name="constant")
self.add_constant(constant)
if noisemodel:
self.add_noisemodel(NoiseModel())
# File Information
self.file_info = self._get_file_info()
# initialize some attributes for solving and simulation
self.sim_index = None
self.oseries_calib = None
self.interpolate_simulation = None
self.normalize_residuals = False
self.fit = None
self._solve_success = False
# Load other modules
self.stats = Statistics(self)
self.plots = Plotting(self)
self.plot = self.plots.plot # because we are lazy
def __repr__(self):
"""Prints a simple string representation of the model."""
template = ('{cls}(oseries={os}, name={name}, constant={const}, '
'noisemodel={noise})')
return template.format(cls=self.__class__.__name__,
os=self.oseries.name,
name=self.name,
const=not self.constant is None,
noise=not self.noisemodel is None)
def add_stressmodel(self, stressmodel: pstSM, replace: Optional[bool] = False):
"""Add a stressmodel to the main model.
Parameters
----------
stressmodel: pastas.stressmodel or list of pastas.stressmodel
instance of a pastas.stressmodel class. Multiple stress models
can be provided (e.g., ml.add_stressmodel([sm1, sm2]) in one call.
replace: bool, optional
force replace the stressmodel if a stressmodel with the same name
already exists. Not recommended but useful at times. Default is
False.
Notes
-----
To obtain a list of the stressmodel names, type:
>>> ml.get_stressmodel_names()
Examples
--------
>>> sm = ps.StressModel(stress, rfunc=ps.Gamma, name="stress")
>>> ml.add_stressmodel(sm)
To add multiple stress models at once you can do the following:
>>> sm1 = ps.StressModel(stress, rfunc=ps.Gamma, name="stress1")
>>> sm1 = ps.StressModel(stress, rfunc=ps.Gamma, name="stress2")
>>> ml.add_stressmodel([sm1, sm2])
See Also
--------
pastas.stressmodels
"""
# Method can take multiple stressmodels at once through args
if isinstance(stressmodel, list):
for sm in stressmodel:
self.add_stressmodel(sm)
elif (stressmodel.name in self.stressmodels.keys()) and not replace:
self.logger.error("The name for the stressmodel you are trying "
"to add already exists for this model. Select "
"another name.")
else:
self.stressmodels[stressmodel.name] = stressmodel
self.parameters = self.get_init_parameters(initial=False)
stressmodel.update_stress(freq=self.settings["freq"])
# Check if stress overlaps with oseries, if not give a warning
if (stressmodel.tmin > self.oseries.series.index.max()) or \
(stressmodel.tmax < self.oseries.series.index.min()):
self.logger.warning("The stress of the stressmodel has no "
"overlap with ml.oseries.")
self._check_stressmodel_compatibility()
def add_constant(self, constant: Type[Constant]):
"""Add a Constant to the time series Model.
Parameters
----------
constant: pastas.Constant
Pastas constant instance, possibly more things in the future.
Examples
--------
>>> d = ps.Constant()
>>> ml.add_constant(d)
"""
self.constant = constant
self.parameters = self.get_init_parameters(initial=False)
self._check_stressmodel_compatibility()
def add_transform(self, transform: Type[ThresholdTransform]):
"""Add a Transform to the time series Model.
Parameters
----------
transform: pastas.transform
instance of a pastas.transform object.
Examples
--------
>>> tt = ps.ThresholdTransform()
>>> ml.add_transform(tt)
See Also
--------
pastas.transform
"""
transform.set_model(self)
self.transform = transform
self.parameters = self.get_init_parameters(initial=False)
self._check_stressmodel_compatibility()
def add_noisemodel(self, noisemodel: pstNM):
"""Adds a noisemodel to the time series Model.
Parameters
----------
noisemodel: pastas.noisemodels.NoiseModelBase
Instance of NoiseModelBase
Examples
--------
>>> n = ps.NoiseModel()
>>> ml.add_noisemodel(n)
"""
self.noisemodel = noisemodel
self.noisemodel.set_init_parameters(oseries=self.oseries.series)
# check whether noise_alpha is not smaller than ml.settings["freq"]
freq_in_days = _get_dt(self.settings["freq"])
noise_alpha = self.noisemodel.parameters.initial.iloc[0]
if freq_in_days > noise_alpha:
self.noisemodel._set_initial("noise_alpha", freq_in_days)
self.parameters = self.get_init_parameters(initial=False)
@get_stressmodel
def del_stressmodel(self, name: str):
"""Method to safely delete a stress model from the Model.
Parameters
----------
name: str
string with the name of the stressmodel object.
Notes
-----
To obtain a list of the stressmodel names type:
>>> ml.get_stressmodel_names()
"""
self.stressmodels.pop(name, None)
self.parameters = self.get_init_parameters(initial=False)
def del_constant(self):
"""Method to safely delete the Constant from the Model."""
if self.constant is None:
self.logger.warning("No constant is present in this model.")
else:
self.constant = None
self.parameters = self.get_init_parameters(initial=False)
def del_transform(self):
"""Method to safely delete the transform from the Model."""
if self.transform is None:
self.logger.warning("No transform is present in this model.")
else:
self.transform = None
self.parameters = self.get_init_parameters(initial=False)
def del_noisemodel(self):
"""Method to safely delete the noise model from the Model."""
if self.noisemodel is None:
self.logger.warning("No noisemodel is present in this model.")
else:
self.noisemodel = None
self.parameters = self.get_init_parameters(initial=False)
def simulate(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, warmup: Optional[float] = None,
return_warmup: Optional[bool] = False) -> Type[Series]:
"""Method to simulate the time series model.
Parameters
----------
p: array_like, optional
array_like object with the values as floats representing the
model parameters. See Model.get_parameters() for more info if
parameters is None.
tmin: str, optional
String with a start date for the simulation period (E.g. '1980').
If none is provided, the tmin from the oseries is used.
tmax: str, optional
String with an end date for the simulation period (E.g. '2010').
If none is provided, the tmax from the oseries is used.
freq: str, optional
String with the frequency the stressmodels are simulated. Must
be one of the following: (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D".
warmup: float, optional
Warmup period (in Days).
return_warmup: bool, optional
Return the simulation including the the warmup period or not,
default is False.
Returns
-------
sim: pandas.Series
pandas.Series containing the simulated time series
Notes
-----
This method can be used without any parameters. When the model is
solved, the optimal parameters values are used and if not,
the initial parameter values are used. This allows the user to
get an idea of how the simulation looks with only the initial
parameters and no calibration.
"""
# Default options when tmin, tmax, freq and warmup are not provided.
if tmin is None and self.settings['tmin']:
tmin = self.settings['tmin']
else:
tmin = self.get_tmin(tmin, use_oseries=False, use_stresses=True)
if tmax is None and self.settings['tmax']:
tmax = self.settings['tmax']
else:
tmax = self.get_tmax(tmax, use_oseries=False, use_stresses=True)
if freq is None:
freq = self.settings["freq"]
if warmup is None:
warmup = self.settings["warmup"]
elif not isinstance(warmup, Timedelta):
warmup = Timedelta(warmup, "D")
# Get the simulation index and the time step
sim_index = self._get_sim_index(tmin, tmax, freq, warmup)
dt = _get_dt(freq)
# Get parameters if none are provided
if p is None:
p = self.get_parameters()
sim = Series(data=np.zeros(sim_index.size, dtype=float),
index=sim_index, fastpath=True)
istart = 0 # Track parameters index to pass to stressmodel object
for sm in self.stressmodels.values():
contrib = sm.simulate(p[istart: istart + sm.nparam],
sim_index.min(), tmax, freq, dt)
sim = sim.add(contrib)
istart += sm.nparam
if self.constant:
sim = sim + self.constant.simulate(p[istart])
istart += 1
if self.transform:
sim = self.transform.simulate(sim, p[istart:istart +
self.transform.nparam])
# Respect provided tmin/tmax at this point, since warmup matters for
# simulation but should not be returned, unless return_warmup=True.
if not return_warmup:
sim = sim.loc[tmin:tmax]
if sim.hasnans:
sim = sim.dropna()
self.logger.warning('Nan-values were removed from the simulation.')
sim.name = 'Simulation'
return sim
def residuals(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, warmup: Optional[float] = None):
"""Method to calculate the residual series.
Parameters
----------
p: array_like, optional
array_like object with the values as floats representing the
model parameters. See Model.get_parameters() for more info if
parameters is None.
tmin: str, optional
String with a start date for the simulation period (E.g. '1980').
If none is provided, the tmin from the oseries is used.
tmax: str, optional
String with an end date for the simulation period (E.g. '2010').
If none is provided, the tmax from the oseries is used.
freq: str, optional
String with the frequency the stressmodels are simulated. Must
be one of the following: (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D".
warmup: float, optional
Warmup period (in Days).
Returns
-------
res: pandas.Series
pandas.Series with the residuals series.
"""
# Default options when tmin, tmax, freq and warmup are not provided.
if tmin is None:
tmin = self.settings['tmin']
if tmax is None:
tmax = self.settings['tmax']
if freq is None:
freq = self.settings["freq"]
# simulate model
sim = self.simulate(p, tmin, tmax, freq, warmup, return_warmup=False)
# Get the oseries calibration series
oseries_calib = self.observations(tmin, tmax, freq)
# Get simulation at the correct indices
if self.interpolate_simulation is None:
if oseries_calib.index.difference(sim.index).size != 0:
self.interpolate_simulation = True
self.logger.info('There are observations between the '
'simulation timesteps. Linear interpolation '
'between simulated values is used.')
if self.interpolate_simulation:
# interpolate simulation to times of observations
sim_interpolated = np.interp(oseries_calib.index.asi8,
sim.index.asi8, sim.values)
else:
# all of the observation indexes are in the simulation
sim_interpolated = sim.reindex(oseries_calib.index)
# Calculate the actual residuals here
res = oseries_calib.subtract(sim_interpolated)
if res.hasnans:
res = res.dropna()
self.logger.warning('Nan-values were removed from the residuals.')
if self.normalize_residuals:
res = res.subtract(res.values.mean())
res.name = "Residuals"
return res
def noise(self, p: Optional[pstAL] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, warmup: Optional[float] = None):
"""Method to simulate the noise when a noisemodel is present.
Parameters
----------
p: array_like, optional
array_like object with the values as floats representing the
model parameters. See Model.get_parameters() for more info if
parameters is None.
tmin: str, optional
String with a start date for the simulation period (E.g. '1980').
If none is provided, the tmin from the oseries is used.
tmax: str, optional
String with an end date for the simulation period (E.g. '2010').
If none is provided, the tmax from the oseries is used.
freq: str, optional
String with the frequency the stressmodels are simulated. Must
be one of the following: (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D".
warmup: float or int, optional
Warmup period (in Days).
Returns
-------
noise : pandas.Series
Pandas series of the noise.
Notes
-----
The noise are the time series that result when applying a noise
model.
.. Note::
The noise is sometimes also referred to as the innovations.
Warnings
--------
This method returns None is no noise model is added to the model.
"""
if self.noisemodel is None or self.settings["noise"] is False:
self.logger.error("Noise cannot be calculated if there is no "
"noisemodel present or is not used during "
"parameter estimation.")
return None
# Get parameters if none are provided
if p is None:
p = self.get_parameters()
# Calculate the residuals
res = self.residuals(p, tmin, tmax, freq, warmup)
p = p[-self.noisemodel.nparam:]
# Calculate the noise
noise = self.noisemodel.simulate(res, p)
return noise
def noise_weights(self, p: Optional[list] = None, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, warmup: Optional[float] = None):
"""Internal method to calculate the noise weights."""
# Get parameters if none are provided
if p is None:
p = self.get_parameters()
# Calculate the residuals
res = self.residuals(p, tmin, tmax, freq, warmup)
# Calculate the weights
weights = self.noisemodel.weights(res, p[-self.noisemodel.nparam:])
return weights
def observations(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None,
update_observations: Optional[float] = False):
"""Method that returns the observations series used for calibration.
Parameters
----------
tmin: str, optional
String with a start date for the simulation period (E.g. '1980').
If none is provided, the tmin from the oseries is used.
tmax: str, optional
String with an end date for the simulation period (E.g. '2010').
If none is provided, the tmax from the oseries is used.
freq: str, optional
String with the frequency the stressmodels are simulated. Must
be one of the following: (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D".
update_observations: bool, optional
if True, force recalculation of the observations series, default
is False.
Returns
-------
oseries_calib: pandas.Series
pandas series of the oseries used for calibration of the model
Notes
-----
This method makes sure the simulation is compared to the nearest
observation. It finds the index closest to sim_index, and then returns
a selection of the oseries. in the residuals method, the simulation is
interpolated to the observation-timestamps.
"""
if tmin is None and self.settings['tmin']:
tmin = self.settings['tmin']
else:
tmin = self.get_tmin(tmin, use_oseries=False, use_stresses=True)
if tmax is None and self.settings['tmax']:
tmax = self.settings['tmax']
else:
tmax = self.get_tmax(tmax, use_oseries=False, use_stresses=True)
if freq is None:
freq = self.settings["freq"]
for key, setting in zip([tmin, tmax, freq], ["tmin", "tmax", "freq"]):
if key != self.settings[setting]:
update_observations = True
if self.oseries_calib is None or update_observations:
oseries_calib = self.oseries.series.loc[tmin:tmax]
# sample measurements, so that frequency is not higher than model
# keep the original timestamps, as they will be used during
# interpolation of the simulation
sim_index = self._get_sim_index(tmin, tmax, freq,
self.settings["warmup"])
if not oseries_calib.empty:
index = get_sample(oseries_calib.index, sim_index)
oseries_calib = oseries_calib.loc[index]
else:
oseries_calib = self.oseries_calib
return oseries_calib
def initialize(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, warmup: Optional[float] = None,
noise: Optional[bool] = None, weights: Optional[Type[Series]] = None, initial=True, fit_constant=True):
"""Method to initialize the model.
This method is called by the solve-method, but can also be
triggered manually. See the solve-method for a description of
the arguments.
"""
if noise is None and self.noisemodel:
noise = True
elif noise is True and self.noisemodel is None:
self.logger.warning("Warning, solving with noise=True while no "
"noisemodel is present. noise set to False")
noise = False
self.settings["noise"] = noise
self.settings["weights"] = weights
self.settings["fit_constant"] = fit_constant
# Set the frequency & warmup
if freq:
self.settings["freq"] = frequency_is_supported(freq)
if warmup is not None:
self.settings["warmup"] = Timedelta(warmup, "D")
# Set time offset from the frequency and the series in the stressmodels
self.settings["time_offset"] = \
self._get_time_offset(self.settings["freq"])
# Set tmin and tmax
self.settings["tmin"] = self.get_tmin(tmin)
self.settings["tmax"] = self.get_tmax(tmax)
# make sure calibration data is renewed
self.sim_index = self._get_sim_index(self.settings["tmin"],
self.settings["tmax"],
self.settings["freq"],
self.settings["warmup"],
update_sim_index=True)
self.oseries_calib = self.observations(tmin=self.settings["tmin"],
tmax=self.settings["tmax"],
freq=self.settings["freq"],
update_observations=True)
self.interpolate_simulation = None
# Initialize parameters
self.parameters = self.get_init_parameters(noise, initial)
# Prepare model if not fitting the constant as a parameter
if self.settings["fit_constant"] is False:
self.parameters.loc["constant_d", "vary"] = False
self.parameters.loc["constant_d", "initial"] = 0.0
self.normalize_residuals = True
def solve(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, freq: Optional[str] = None, warmup: Optional[float] = None, noise: Optional[bool] = True,
solver: Optional[pstBS] = None, report: Optional[bool] = True, initial: Optional[bool] = True, weights: Optional[Type[Series]] = None,
fit_constant: Optional[Type[bool]] = True, **kwargs):
"""Method to solve the time series model.
Parameters
----------
tmin: str, optional
String with a start date for the simulation period (E.g. '1980').
If none is provided, the tmin from the oseries is used.
tmax: str, optional
String with an end date for the simulation period (E.g. '2010').
If none is provided, the tmax from the oseries is used.
freq: str, optional
String with the frequency the stressmodels are simulated. Must
be one of the following (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D".
warmup: float, optional
Warmup period (in Days) for which the simulation is calculated,
but not used for the calibration period.
noise: bool, optional
Argument that determines if a noisemodel is used (only if
present). The default is noise=True.
solver: pastas.solver.BaseSolver class, optional
Class used to solve the model. Options are: ps.LeastSquares
(default) or ps.LmfitSolve. A class is needed, not an instance
of the class!
report: bool, optional
Print a report to the screen after optimization finished. This
can also be manually triggered after optimization by calling
print(ml.fit_report()) on the Pastas model instance.
initial: bool, optional
Reset initial parameters from the individual stress models.
Default is True. If False, the optimal values from an earlier
optimization are used.
weights: pandas.Series, optional
Pandas Series with values by which the residuals are multiplied,
index-based. Must have the same indices as the oseries.
fit_constant: bool, optional
Argument that determines if the constant is fitted as a parameter.
If it is set to False, the constant is set equal to the mean of
the residuals.
**kwargs: dict, optional
All keyword arguments will be passed onto minimization method
from the solver. It depends on the solver used which arguments
can be used.
Notes
-----
- The solver object including some results are stored as ml.fit.
From here one can access the covariance (ml.fit.pcov) and
correlation matrix (ml.fit.pcor).
- Each solver return a number of results after optimization. These
solver specific results are stored in ml.fit.result and can be
accessed from there.
See Also
--------
pastas.solver
Different solver objects are available to estimate parameters.
"""
# Initialize the model
self.initialize(tmin, tmax, freq, warmup, noise, weights, initial,
fit_constant)
if self.oseries_calib.empty:
raise ValueError("Calibration series 'oseries_calib' is empty! "
"Check 'tmin' or 'tmax'.")
# Store the solve instance
if solver is None:
if self.fit is None:
self.fit = LeastSquares(ml=self)
elif not issubclass(solver, self.fit.__class__):
self.fit = solver(ml=self)
self.settings["solver"] = self.fit._name
# Solve model
success, optimal, stderr = self.fit.solve(noise=self.settings["noise"],
weights=weights, **kwargs)
if not success:
self.logger.warning("Model parameters could not be estimated "
"well.")
if self.settings['fit_constant'] is False:
# Determine the residuals and set the constant to their mean
self.normalize_residuals = False
res = self.residuals(optimal).mean()
optimal[self.parameters.name == self.constant.name] = res
self.parameters.optimal = optimal
self.parameters.stderr = stderr
self._solve_success = success # store for fit_report
if report:
if isinstance(report, str):
output = report
else:
output = None
print(self.fit_report(output=output))
def set_parameter(self, name: str, initial: Optional[float] = None, vary: Optional[bool] = None, pmin: Optional[float] = None,
pmax: Optional[float] = None, optimal: Optional[float] = None, move_bounds: Optional[bool] = False):
"""Method to change the parameter properties.
Parameters
----------
name: str
name of the parameter to update. This has to be a single variable.
initial: float, optional
parameters value to use as initial estimate.
vary: bool, optional
boolean to vary a parameter (True) or not (False).
pmin: float, optional
minimum value for the parameter.
pmax: float, optional
maximum value for the parameter.
optimal: float, optional
optimal value for the parameter.
move_bounds: bool, optional
Reset pmin/pmax based on new initial value. Of move_bounds=True,
pmin and pmax must be None.
Examples
--------
>>> ml.set_parameter(name="constant_d", initial=10, vary=True,
>>> pmin=-10, pmax=20)
Note
----
It is highly recommended to use this method to set parameter
properties. Changing the parameter properties directly in the
parameter `DataFrame` may not work as expected.
"""
if name not in self.parameters.index:
msg = "parameter %s is not present in the model"
self.logger.error(msg, name)
raise KeyError(msg, name)
# Because either of the following is not necessarily present
noisemodel = self.noisemodel.name if self.noisemodel else "NotPresent"
constant = self.constant.name if self.constant else "NotPresent"
transform = self.transform.name if self.transform else "NotPresent"
# Get the model component for the parameter
cat = self.parameters.loc[name, "name"]
if cat in self.stressmodels.keys():
obj = self.stressmodels[cat]
elif cat == noisemodel:
obj = self.noisemodel
elif cat == constant:
obj = self.constant
elif cat == transform:
obj = self.transform
# Move pmin and pmax based on the initial
if move_bounds and initial:
if pmin or pmax:
raise KeyError("Either pmin/pmax or move_bounds must "
"be provided, but not both.")
factor = initial / self.parameters.loc[name, 'initial']
pmin = self.parameters.loc[name, 'pmin'] * factor
pmax = self.parameters.loc[name, 'pmax'] * factor
# Set the parameter properties
if initial is not None:
obj._set_initial(name, initial)
self.parameters.loc[name, "initial"] = initial
if vary is not None:
obj._set_vary(name, vary)
self.parameters.loc[name, "vary"] = bool(vary)
if pmin is not None:
obj._set_pmin(name, pmin)
self.parameters.loc[name, "pmin"] = pmin
if pmax is not None:
obj._set_pmax(name, pmax)
self.parameters.loc[name, "pmax"] = pmax
if optimal is not None:
self.parameters.loc[name, "optimal"] = optimal
def _get_time_offset(self, freq: str) -> Type[Timedelta]:
"""Internal method to get the time offsets from the stressmodels.
Parameters
----------
freq: str
string with the frequency used for simulation.
Notes
-----
Method to check if the StressModel timestamps match
(e.g. similar hours)
"""
time_offsets = set()
for stressmodel in self.stressmodels.values():
for st in stressmodel.stress:
if st.freq_original:
# calculate the offset from the default frequency
t = st.series_original.index
base = t.min().ceil(freq)
mask = t >= base
if np.any(mask):
time_offsets.add(_get_time_offset(t[mask][0], freq))
if len(time_offsets) > 1:
msg = "The time-offset with the frequency is not the same for " \
"all stresses."
self.logger.error(msg)
raise (Exception(msg))
if len(time_offsets) == 1:
return next(iter(time_offsets))
else:
return Timedelta(0)
def _get_sim_index(self, tmin: Type[Timestamp], tmax: Type[Timestamp], freq: str, warmup: type[Timedelta], update_sim_index: Optional[Type[bool]] = False):
"""Internal method to get the simulation index, including the warmup.
Parameters
----------
tmin: pandas.Timestamp
String with a start date for the simulation period (E.g. '1980').
If none is provided, the tmin from the oseries is used.
tmax: pandas.Timestamp
String with an end date for the simulation period (E.g. '2010').
If none is provided, the tmax from the oseries is used.
freq: str
String with the frequency the stressmodels are simulated. Must
be one of the following: (D, h, m, s, ms, us, ns) or a multiple of
that e.g. "7D".
warmup: pandas.Timedelta
Warmup period (in Days).
update_sim_index : bool, optional
if True, force recalculation of sim_index, default is False
Returns
-------
sim_index: pandas.DatetimeIndex
Pandas DatetimeIndex instance with the datetimes values for
which the model is simulated.
"""
# Check if any of the settings are updated
for key, setting in zip([tmin, tmax, freq, warmup],
["tmin", "tmax", "freq", "warmup"]):
if key != self.settings[setting]:
update_sim_index = True
break
if self.sim_index is None or update_sim_index:
tmin = (tmin - warmup).floor(freq) + self.settings["time_offset"]
sim_index = date_range(tmin, tmax, freq=freq)
else:
sim_index = self.sim_index
return sim_index
def get_tmin(self, tmin: Optional[pstTm] = None, use_oseries: Optional[bool] = True, use_stresses: Optional[bool] = False) -> Type[Timestamp]:
"""Method that checks and returns valid values for tmin.
Parameters
----------
tmin: str, optional
string with a year or date that can be turned into a pandas
Timestamp (e.g. pd.Timestamp(tmin)).
use_oseries: bool, optional
Obtain the tmin and tmax from the oseries. Default is True.
use_stresses: bool, optional
Obtain the tmin and tmax from the stresses. The minimum/maximum
time from all stresses is taken.
Returns
-------
tmin: pandas.Timestamp
returns pandas timestamps for tmin.
Notes
-----
The parameters tmin and tmax are leading, unless use_oseries is
True, then these are checked against the oseries index. The tmin and
tmax are checked and returned according to the following rules:
A. If no value for tmin is provided:
1. If use_oseries is True, tmin is based on the oseries
2. If use_stresses is True, tmin is based on the stressmodels.
B. If a values for tmin is provided:
1. A pandas timestamp is made from the string
2. if use_oseries is True, tmin is checked against oseries.
"""
# Get tmin from the oseries
if use_oseries:
ts_tmin = self.oseries.series.index.min()
# Get tmin from the stressmodels
elif use_stresses:
ts_tmin = Timestamp.max
for stressmodel in self.stressmodels.values():
if stressmodel.tmin < ts_tmin:
ts_tmin = stressmodel.tmin
# Get tmin and tmax from user provided values
else:
ts_tmin = Timestamp(tmin)
# Set tmin properly
if tmin is not None and use_oseries:
tmin = max(Timestamp(tmin), ts_tmin)
elif tmin is not None:
tmin = Timestamp(tmin)
else:
tmin = ts_tmin
return tmin
def get_tmax(self, tmax: Optional[pstTm] = None, use_oseries: Optional[bool] = True, use_stresses: Optional[bool] = False) -> Type[Timestamp]:
"""Method that checks and returns valid values for tmax.
Parameters
----------
tmax: str, optional
string with a year or date that can be turned into a pandas
Timestamp (e.g. pd.Timestamp(tmax)).
use_oseries: bool, optional
Obtain the tmin and tmax from the oseries. Default is True.
use_stresses: bool, optional
Obtain the tmin and tmax from the stresses. The minimum/maximum
time from all stresses is taken.
Returns
-------
tmax: pandas.Timestamp
returns pandas timestamps for tmax.
Notes
-----
The parameters tmin and tmax are leading, unless use_oseries is
True, then these are checked against the oseries index. The tmin and
tmax are checked and returned according to the following rules:
A. If no value for tmax is provided:
1. If use_oseries is True, tmax is based on the oseries.
2. If use_stresses is True, tmax is based on the stressmodels.
B. If a values for tmax is provided:
1. A pandas timestamp is made from the string.
2. if use_oseries is True, tmax is checked against oseries.
A detailed description of dealing with tmax and timesteps
in general can be found in the developers section of the docs.
"""