-
Notifications
You must be signed in to change notification settings - Fork 70
/
modelstats.py
337 lines (274 loc) · 11 KB
/
modelstats.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
"""The following methods may be used to describe the fit between the model
simulation and the observations.
.. currentmodule:: pastas.modelstats.Statistics
.. autosummary::
:nosignatures:
:toctree: ./generated
summary
Examples
========
These methods may be used as follows.
>>> ml.stats.summary(stats=["rmse", "mae", "nse"])
Value
Statistic
rmse 0.114364
mae 0.089956
nse 0.929136
"""
from numpy import nan
from pandas import DataFrame, Timestamp
from .decorators import model_tmin_tmax
from .stats import diagnostics, metrics
# Type Hinting
from pastas.typing import Type, Optional, pstMl, pstFi, pstTm
class Statistics:
# Save all statistics that can be calculated.
ops = ["rmse", "rmsn", "sse", "mae", "nse", "evp", "rsq", "bic", "aic", ]
def __init__(self, ml: pstMl):
"""This class provides statistics to to pastas Model class.
Parameters
----------
ml: Pastas.model.Model
ml is a time series Model that is calibrated.
Notes
-----
To obtain a list of all statistics that are included type:
>>> print(ml.stats.ops)
"""
# Save a reference to the model.
self.ml = ml
def __repr__(self):
msg = """This module contains all the statistical functions that are
included in Pastas. To obtain a list of all statistics that are included type:
>>> print(ml.stats.ops)"""
return msg
@model_tmin_tmax
def rmse(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Root mean squared error of the residuals.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.rmse
"""
res = self.ml.residuals(tmin=tmin, tmax=tmax)
return metrics.rmse(res=res, weighted=weighted, **kwargs)
@model_tmin_tmax
def rmsn(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Root mean squared error of the noise.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
Returns
-------
float or nan
Return a float if noisemodel is present, nan if not.
See Also
--------
pastas.stats.rmse
"""
if not self.ml.settings["noise"]:
return nan
else:
res = self.ml.noise(tmin=tmin, tmax=tmax)
return metrics.rmse(res=res, weighted=weighted, **kwargs)
@model_tmin_tmax
def sse(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None) -> float:
"""Sum of the squares of the error (SSE)
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
See Also
--------
pastas.stats.sse
"""
res = self.ml.residuals(tmin=tmin, tmax=tmax)
return metrics.sse(res=res)
@model_tmin_tmax
def mae(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Mean Absolute Error (MAE) of the residuals.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.mae
"""
res = self.ml.residuals(tmin=tmin, tmax=tmax)
return metrics.mae(res=res, weighted=weighted, **kwargs)
@model_tmin_tmax
def nse(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Nash-Sutcliffe coefficient for model fit .
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.nse
"""
res = self.ml.residuals(tmin=tmin, tmax=tmax)
obs = self.ml.observations(tmin=tmin, tmax=tmax)
return metrics.nse(obs=obs, res=res, weighted=weighted, **kwargs)
@model_tmin_tmax
def pearsonr(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Compute the (weighted) Pearson correlation (r).
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.pearsonr
"""
obs = self.ml.observations(tmin=tmin, tmax=tmax)
sim = self.ml.simulate(tmin=tmin, tmax=tmax)
return metrics.pearsonr(obs=obs, sim=sim, weighted=weighted, **kwargs)
@model_tmin_tmax
def evp(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Explained variance percentage.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.evp
"""
res = self.ml.residuals(tmin=tmin, tmax=tmax)
obs = self.ml.observations(tmin=tmin, tmax=tmax)
return metrics.evp(obs=obs, res=res, weighted=weighted, **kwargs)
@model_tmin_tmax
def rsq(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""R-squared.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.rsq
"""
obs = self.ml.observations(tmin=tmin, tmax=tmax)
res = self.ml.residuals(tmin=tmin, tmax=tmax)
return metrics.rsq(obs=obs, res=res, weighted=weighted, **kwargs)
@model_tmin_tmax
def kge_2012(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, weighted: Optional[bool] = False, **kwargs) -> float:
"""Kling-Gupta Efficiency.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
weighted: bool, optional
If weighted is True, the variances are computed using the time
step between observations as weights. Default is False.
See Also
--------
pastas.stats.kge_2012
"""
sim = self.ml.simulate(tmin=tmin, tmax=tmax)
obs = self.ml.observations(tmin=tmin, tmax=tmax)
return metrics.kge_2012(obs=obs, sim=sim, weighted=weighted, **kwargs)
@model_tmin_tmax
def bic(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None) -> float:
"""Bayesian Information Criterium (BIC).
Parameters
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
See Also
--------
pastas.stats.bic
"""
nparam = self.ml.parameters["vary"].sum()
if self.ml.settings["noise"]:
res = (self.ml.noise(tmin=tmin, tmax=tmax) *
self.ml.noise_weights(tmin=tmin, tmax=tmax))
else:
res = self.ml.residuals(tmin=tmin, tmax=tmax)
return metrics.bic(res=res, nparam=nparam)
@model_tmin_tmax
def aic(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None) -> float:
"""Akaike Information Criterium (AIC).
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
See Also
--------
pastas.stats.bic
"""
nparam = self.ml.parameters["vary"].sum()
if self.ml.settings["noise"]:
res = (self.ml.noise(tmin=tmin, tmax=tmax) *
self.ml.noise_weights(tmin=tmin, tmax=tmax))
else:
res = self.ml.residuals(tmin=tmin, tmax=tmax)
return metrics.aic(res=res, nparam=nparam)
@model_tmin_tmax
def summary(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, stats: Optional[List[str]] = None) -> Type[DataFrame]:
"""Returns a Pandas DataFrame with goodness-of-fit metrics.
Parameters
----------
tmin: str or pandas.Timestamp, optional
tmax: str or pandas.Timestamp, optional
stats: list, optional
list of statistics that need to be calculated. If nothing is
provided, all statistics are returned.
Returns
-------
stats : Pandas.DataFrame
single-column DataFrame with calculated statistics
Examples
--------
>>> ml.stats.summary()
or
>>> ml.stats.summary(stats=["mae", "rmse"])
"""
if stats is None:
stats_to_compute = self.ops
else:
stats_to_compute = stats
stats = DataFrame(columns=['Value'])
for k in stats_to_compute:
stats.loc[k] = (getattr(self, k)(tmin=tmin, tmax=tmax))
stats.index.name = 'Statistic'
return stats
@model_tmin_tmax
def diagnostics(self, tmin: Optional[pstTm] = None, tmax: Optional[pstTm] = None, alpha: Optional[float] = 0.05, stats: Optional[tuple] = (),
float_fmt: Optional[str] = "{0:.2f}") -> Type[DataFrame]:
if self.ml.noisemodel and self.ml.settings["noise"]:
series = self.ml.noise(tmin=tmin, tmax=tmax)
nparam = self.ml.noisemodel.nparam
else:
series = self.ml.residuals(tmin=tmin, tmax=tmax)
nparam = 0
return diagnostics(series=series, alpha=alpha, nparam=nparam,
stats=stats, float_fmt=float_fmt)