Skip to content

Commit 01d4431

Browse files
committed
[VCF] Add more documentation and Ruff format
1 parent 492b8a6 commit 01d4431

File tree

1 file changed

+86
-34
lines changed

1 file changed

+86
-34
lines changed

bluemath_tk/distributions/nonstat_gev.py

Lines changed: 86 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def __init__(
7777
self.t = t
7878
if covariates is None:
7979
self.include_covariates = False
80-
self.covariates = pd.DataFrame({'A' : []})
80+
self.covariates = pd.DataFrame({"A": []})
8181
else:
8282
self.include_covariates = True
8383
self.covariates = covariates
@@ -206,25 +206,33 @@ def auto_adjust(self, max_iter: int = 1000, plot: bool = False) -> dict:
206206
+ nind_sh
207207
+ ntrend_sh
208208
)
209-
self.AIC_iter[iter] = self._AIC(-fit_result["negloglikelihood"], n_params)
209+
self.AIC_iter[iter] = self._AIC(
210+
-fit_result["negloglikelihood"], n_params
211+
)
210212

211213
### Step 4: Sensitivity of optimal loglikelihood respect to possible additional harmonics
212214
# for the location, scale and shape parameters.
213215
# Note that the new parameter values are set to zero since derivatives do not depend on them
214216
fit_result_aux = fit_result.copy()
215217
# Location
216218
if fit_result["beta"] is not None:
217-
fit_result_aux["beta"] = np.concatenate((fit_result["beta"], [0, 0]))
219+
fit_result_aux["beta"] = np.concatenate(
220+
(fit_result["beta"], [0, 0])
221+
)
218222
else:
219223
fit_result_aux["beta"] = np.array([0, 0])
220224
# Scale
221225
if fit_result["alpha"] is not None:
222-
fit_result_aux["alpha"] = np.concatenate((fit_result["alpha"], [0, 0]))
226+
fit_result_aux["alpha"] = np.concatenate(
227+
(fit_result["alpha"], [0, 0])
228+
)
223229
else:
224230
fit_result_aux["alpha"] = np.array([0, 0])
225231
# Shape
226232
if fit_result["gamma"] is not None:
227-
fit_result_aux["gamma"] = np.concatenate((fit_result["gamma"], [0, 0]))
233+
fit_result_aux["gamma"] = np.concatenate(
234+
(fit_result["gamma"], [0, 0])
235+
)
228236
else:
229237
fit_result_aux["gamma"] = np.array([0, 0])
230238

@@ -470,7 +478,7 @@ def auto_adjust(self, max_iter: int = 1000, plot: bool = False) -> dict:
470478
if fit_result["gamma0"] is None:
471479
self.ngamma0 = 0
472480
elif np.abs(fit_result["gamma0"]) <= 1e-8:
473-
self.ngamma0 = 0
481+
self.ngamma0 = 0
474482

475483
# Compute AIC and Loglikelihood
476484
self.loglike_iter[iter] = -fit_result["negloglikelihood"]
@@ -4566,13 +4574,15 @@ def _parametro(
45664574
# Adding the harmonic part
45674575
if nparam > 0:
45684576
for i in range(nparam // 2):
4569-
y = y + beta[2 * i] * np.cos((i + 1) * 2 * np.pi * t) + beta[
4570-
2 * i + 1
4571-
] * np.sin((i + 1) * 2 * np.pi * t)
4577+
y = (
4578+
y
4579+
+ beta[2 * i] * np.cos((i + 1) * 2 * np.pi * t)
4580+
+ beta[2 * i + 1] * np.sin((i + 1) * 2 * np.pi * t)
4581+
)
45724582

45734583
# Adding the tendency part
45744584
if ntend > 0:
4575-
y = y + betaT * t
4585+
y = y + betaT * t
45764586

45774587
# Adding the covariate part
45784588
if nind > 0:
@@ -4787,7 +4797,7 @@ def _quantile(self, prob=None, harm=False) -> np.ndarray:
47874797

47884798
return Q
47894799

4790-
def plot(self, return_plot=True, save=False):
4800+
def plot(self, return_plot: bool = True, save: bool = False):
47914801
"""
47924802
Plot the location, scale and shape parameters, also the PP plot and QQ plot
47934803
@@ -4797,6 +4807,8 @@ def plot(self, return_plot=True, save=False):
47974807
----------
47984808
return_plot : bool, default=True
47994809
If True, return period plot is plotted
4810+
save : bool, default=False
4811+
If True, save all the figures in a "Figures/"
48004812
"""
48014813

48024814
# Parameter Evaluation
@@ -5028,13 +5040,13 @@ def plot(self, return_plot=True, save=False):
50285040
# self.t, ci_low_psit, ci_up_psit, color=self.colors[1], alpha=0.3
50295041
# )
50305042
l3 = ax1.plot(
5031-
self.t,
5032-
quan95,
5033-
linestyle="dashed",
5034-
# color=self.colors[2],
5043+
self.t,
5044+
quan95,
5045+
linestyle="dashed",
5046+
# color=self.colors[2],
50355047
color="tab:orange",
5036-
linewidth=1,
5037-
label="Quantile 95%"
5048+
linewidth=1,
5049+
label="Quantile 95%",
50385050
)
50395051
# TODO: Add aggregated return period lines
50405052
# rt_10 = np.zeros(40)
@@ -5070,7 +5082,9 @@ def plot(self, return_plot=True, save=False):
50705082
ax1.grid(True)
50715083
handles = [
50725084
# art for art in l0 + l1 + l2 + l3 + l4 + l5 + l6 + l7 if not art.get_label().startswith("_")
5073-
art for art in l0 + l1 + l2 + l3 if not art.get_label().startswith("_")
5085+
art
5086+
for art in l0 + l1 + l2 + l3
5087+
if not art.get_label().startswith("_")
50745088
]
50755089
ax1.legend(handles=handles, loc="best")
50765090
# ax2.set_ylim(0,1.5)
@@ -5167,7 +5181,10 @@ def plot(self, return_plot=True, save=False):
51675181
ax1.margins(x=0.01)
51685182
plt.xticks(month_positions, month_initials)
51695183
if save:
5170-
plt.savefig(f"Figures/Location_Scale_Parameters_FirstYear_{self.var_name}.png", dpi=300)
5184+
plt.savefig(
5185+
f"Figures/Location_Scale_Parameters_FirstYear_{self.var_name}.png",
5186+
dpi=300,
5187+
)
51715188
plt.show()
51725189

51735190
# Creating the first monthly plot if not monthly or annual data
@@ -5326,7 +5343,9 @@ def plot(self, return_plot=True, save=False):
53265343
plt.legend(loc="best")
53275344
plt.grid(True)
53285345
if save:
5329-
plt.savefig(f"Figures/Harmonic_Location_Parameter_{self.var_name}.png", dpi=300)
5346+
plt.savefig(
5347+
f"Figures/Harmonic_Location_Parameter_{self.var_name}.png", dpi=300
5348+
)
53305349
plt.show()
53315350

53325351
### Scale parameter plot
@@ -5365,7 +5384,9 @@ def plot(self, return_plot=True, save=False):
53655384
plt.ylabel(r"$\psi_t$")
53665385
plt.grid(True)
53675386
if save:
5368-
plt.savefig(f"Figures/Harmonic_Scale_Parameter_{self.var_name}.png", dpi=300)
5387+
plt.savefig(
5388+
f"Figures/Harmonic_Scale_Parameter_{self.var_name}.png", dpi=300
5389+
)
53695390
plt.show()
53705391

53715392
#### PP Plot
@@ -5384,9 +5405,14 @@ def plot(self, return_plot=True, save=False):
53845405
) and return_plot:
53855406
self.ReturnPeriodPlot()
53865407

5387-
def QQplot(self,save=False):
5408+
def QQplot(self, save: bool = False):
53885409
"""
53895410
QQ plot
5411+
5412+
Parameters
5413+
----------
5414+
save : bool, default=False
5415+
If True, save the plot in "Figures/"
53905416
"""
53915417
Ze = -np.log(-np.log(np.arange(1, len(self.xt) + 1) / (len(self.xt) + 1)))
53925418
Zm = self.kt * self._Zstandardt()
@@ -5444,7 +5470,7 @@ def _Zstandardt(self):
54445470
54455471
Return
54465472
------
5447-
Zt :
5473+
Zt :
54485474
Standarized variable of the given parameters
54495475
"""
54505476

@@ -5543,7 +5569,7 @@ def _Dzweibull(self) -> np.ndarray:
55435569

55445570
# Since z-values must be greater than 0 in order to avoid numerical problems, their values are set to be greater than 1e-8
55455571
z = np.maximum(1e-8, z)
5546-
zn = z ** (-1 / epst)
5572+
# zn = z ** (-1 / epst)
55475573

55485574
Dmut = np.zeros(nd)
55495575
Dpsit = np.zeros(nd)
@@ -6085,6 +6111,11 @@ def _DQuantile(self) -> np.ndarray:
60856111
def PPplot(self, save=False):
60866112
"""
60876113
PP plot
6114+
6115+
Parameters
6116+
----------
6117+
save : bool, default=False
6118+
If True, save the plot in "Figures/"
60886119
"""
60896120
# Empirical distribution function value
60906121
Fe = np.arange(1, len(self.xt) + 1) / (len(self.xt) + 1)
@@ -6256,7 +6287,7 @@ def ReturnPeriodPlot(self, annualplot=True):
62566287
)
62576288

62586289
## Plot the return periods
6259-
datemax_mod = self.t % 1
6290+
# datemax_mod = self.t % 1
62606291
labels = [
62616292
"January",
62626293
"February",
@@ -6340,13 +6371,13 @@ def _aggquantile(
63406371
beta_cov=None,
63416372
alpha_cov=None,
63426373
gamma_cov=None,
6343-
):
6374+
) -> np.ndarray:
63446375
"""
63456376
Function to compute the aggregated quantile for certain parameters
63466377
63476378
Parameters
63486379
----------
6349-
q :
6380+
q :
63506381
Quantile value
63516382
t0 :
63526383
Starting point of integration interval
@@ -6376,6 +6407,11 @@ def _aggquantile(
63766407
Covariate part of scale parameter
63776408
gamma_cov : default=None
63786409
Covariate part of shape parameter
6410+
6411+
Return
6412+
------
6413+
zqout : np.ndarray
6414+
Aggregated return period
63796415
"""
63806416
if beta0 is None:
63816417
beta0 = self.beta0
@@ -6427,9 +6463,13 @@ def _aggquantile(
64276463
self.covariates.iloc[pos, self.list_loc[i]].values
64286464
)
64296465
for i in range(len(alpha_cov)):
6430-
cov_scint[i] = np.mean(self.covariates.iloc[pos, self.list_sc[i]].values)
6466+
cov_scint[i] = np.mean(
6467+
self.covariates.iloc[pos, self.list_sc[i]].values
6468+
)
64316469
for i in range(len(gamma_cov)):
6432-
cov_shint[i] = np.mean(self.covariates.iloc[pos, self.list_sh[i]].values)
6470+
cov_shint[i] = np.mean(
6471+
self.covariates.iloc[pos, self.list_sh[i]].values
6472+
)
64336473
else:
64346474
cov_locint = None
64356475
cov_scint = None
@@ -6562,9 +6602,13 @@ def _fzeroquanint(
65626602
beta_cov,
65636603
alpha_cov,
65646604
gamma_cov,
6565-
):
6605+
) -> np.ndarray:
65666606
"""
6567-
Function to solve the quantile
6607+
Auxiliar function to solve the quantile
6608+
6609+
Return
6610+
------
6611+
zn : np.ndarray
65686612
"""
65696613

65706614
# Evaluate the location parameter at each time t as a function of the actual values of the parameters given by p
@@ -6654,7 +6698,11 @@ def _fzeroderiquanint(
66546698
gamma_cov,
66556699
):
66566700
"""
6657-
Function to solve the quantile
6701+
Auxiliar Function to solve the quantile derivative
6702+
6703+
Return
6704+
------
6705+
zn : np.ndarray
66586706
"""
66596707
# Evaluate the location parameter at each time t as a function of the actual values of the parameters given by p
66606708
mut1 = self._parametro(
@@ -6721,9 +6769,14 @@ def _fzeroderiquanint(
67216769

67226770
return zn
67236771

6724-
def _ConfidInterQuanAggregate(self, q, t0, t1):
6772+
def _ConfidInterQuanAggregate(self, q, t0, t1) -> np.ndarray:
67256773
"""
67266774
Auxiliar function to compute the std for the aggregated quantiles
6775+
6776+
Return
6777+
------
6778+
stdQuan : np.ndarray
6779+
Standard deviation of quantile
67276780
"""
67286781
# Total length of the data
67296782
n = (
@@ -6880,4 +6933,3 @@ def _ConfidInterQuanAggregate(self, q, t0, t1):
68806933
stdQuan = np.sqrt(jacob.T @ self.invI0 @ jacob)
68816934

68826935
return stdQuan
6883-

0 commit comments

Comments
 (0)