Skip to content

Commit

Permalink
Merge pull request #121 from IMMM-SFA/bugfix/hmm
Browse files Browse the repository at this point in the history
fix gaussian hmm reproducibility, depreciation error
  • Loading branch information
erexer authored Oct 19, 2024
2 parents cbcef8c + 08cbe03 commit 0d06326
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 8,057 deletions.
20 changes: 10 additions & 10 deletions docs/source/A2.6_hmm.rst
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,7 @@ across these realizations.

.. code:: ipython3
decadal_drought_occurence=np.empty([1000])
decadal_drought_occurrence = np.empty([1000])
for y in range(1000):
Expand All @@ -676,12 +676,12 @@ across these realizations.
eigenvals, eigenvecs = np.linalg.eig(np.transpose(Pnew))
one_eigval = np.argmin(np.abs(eigenvals - 1))
piNew = np.divide(np.dot(np.transpose(Pnew), eigenvecs[:, one_eigval]),
np.sum(np.dot(np.transpose(Pnew), eigenvecs[:, one_eigval])))
np.sum(np.dot(np.transpose(Pnew), eigenvecs[:, one_eigval])))
musNew_HMM[0] = mus[0] * LHsamples[y][1]
musNew_HMM[1] = mus[1] * LHsamples[y][0]
sigmasNew_HMM[0] = sigmas[0] * LHsamples[y][3]
sigmasNew_HMM[1] = sigmas[1] * LHsamples[y][2]
musNew_HMM[0] = mus[0][0] * LHsamples[y][1]
musNew_HMM[1] = mus[1][0] * LHsamples[y][0]
sigmasNew_HMM[0] = sigmas[0][0] * LHsamples[y][3]
sigmasNew_HMM[1] = sigmas[1][0] * LHsamples[y][2]
# Generate first state and log-space annual flow at last node
states = np.empty([n_years])
Expand Down Expand Up @@ -715,13 +715,13 @@ across these realizations.
# Where does the rolling mean dip below the threshold
drought_instances = [i for i, v in enumerate(AnnualQ_s.iloc[:, 0].rolling(11).mean()) if v < threshold]
decadal_drought_occurence[y] = len(drought_instances)
decadal_drought_occurrence[y] = len(drought_instances)
.. code:: ipython3
fig, ax = plt.subplots(figsize=(12, 8))
ax.hist(decadal_drought_occurence,label='Non-Stationary generator',color="#005F73")
ax.hist(decadal_drought_occurrence,label='Non-Stationary generator',color="#005F73")
ax.set_xlabel('Number of Instances of Decadal Drought',fontsize=16)
ax.set_ylabel('Frequency',fontsize=16)
ax.axvline(x=2, color='r', linestyle='-',label='Observed')
Expand Down Expand Up @@ -815,7 +815,7 @@ transition probabilites.
# Fit regression
d = {'Dry_Tp': tp_dry,
'Dry_Mu': mu_dry,
'Drought_Occurrence':decadal_drought_occurence}
'Drought_Occurrence':decadal_drought_occurrence}
df = pd.DataFrame(d)
df['Intercept'] = np.ones(np.shape(df)[0])
Expand All @@ -824,7 +824,7 @@ transition probabilites.
ols = sm.OLS(df['Drought_Occurrence'], df[cols])
result = ols.fit()
# Calculate drought occurence for each grid point
# Calculate drought occurrence for each grid point
X, Y = np.meshgrid(xgrid, ygrid)
x = X.flatten()
y = Y.flatten()
Expand Down

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion notebooks/functions/fitmodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,16 @@


def fitHMM(Q, nSamples):
# Initialize model
model = GaussianHMM(n_components=2, n_iter=1000, init_params="cm")

# Set randomizing parameters
model.startprob_ = np.array([0.5, 0.5])
model.transmat_ = np.array([[0.5, 0.5], [0.5, 0.5]])

# fit Gaussian HMM to Q
model = GaussianHMM(n_components=2, n_iter=1000).fit(np.reshape(Q[35::], [len(Q[35::]), 1]))
model = model.fit(np.reshape(Q[35::], [len(Q[35::]), 1]))

# classify each observation as state 0 or 1
hidden_states = model.predict(np.reshape(Q, [len(Q), 1]))

Expand Down

0 comments on commit 0d06326

Please sign in to comment.