Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: update examples #93

Merged
merged 6 commits into from
Oct 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 3 additions & 3 deletions docs/auto_examples/1eof/plot_multivariate-eof.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
},
"outputs": [],
"source": [
"# Load packages and data:\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom cartopy.crs import PlateCarree\n\nfrom xeofs.models import EOF\n\n# Create four different dataarrayss\nsst = xr.tutorial.open_dataset('ersstv5')['sst']\nsubset1 = sst.isel(lon=slice(0, 45))\nsubset2 = sst.isel(lon=slice(46, 90))\nsubset3 = sst.isel(lon=slice(91, 135))\nsubset4 = sst.isel(lon=slice(136, None))\nmultivariate_data = [subset1, subset2, subset3, subset4]"
"# Load packages and data:\nimport xarray as xr\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nfrom cartopy.crs import PlateCarree\n\nfrom xeofs.models import EOF\n\n# Create four different dataarrayss\nsst = xr.tutorial.open_dataset(\"ersstv5\")[\"sst\"]\nsubset1 = sst.isel(lon=slice(0, 45))\nsubset2 = sst.isel(lon=slice(46, 90))\nsubset3 = sst.isel(lon=slice(91, 135))\nsubset4 = sst.isel(lon=slice(136, None))\nmultivariate_data = [subset1, subset2, subset3, subset4]"
]
},
{
Expand All @@ -33,7 +33,7 @@
},
"outputs": [],
"source": [
"pca = EOF(standardize=False, use_coslat=True)\npca.fit(multivariate_data, dim='time')\ncomponents = pca.components()\nscores = pca.scores()"
"pca = EOF(n_modes=10, standardize=False, use_coslat=True)\npca.fit(multivariate_data, dim=\"time\")\ncomponents = pca.components()\nscores = pca.scores()"
]
},
{
Expand All @@ -51,7 +51,7 @@
},
"outputs": [],
"source": [
"mode = 5\nproj = PlateCarree()\nkwargs = {\n 'cmap' : 'RdBu',\n 'vmin' : -.05,\n 'vmax': .05,\n 'transform': proj,\n 'add_colorbar': False\n}\n\nfig = plt.figure(figsize=(7.3, 6))\nfig.subplots_adjust(wspace=0)\ngs = GridSpec(2, 4, figure=fig, width_ratios=[1, 1, 1, 1])\nax = [fig.add_subplot(gs[0, i], projection=proj) for i in range(4)]\nax_pc = fig.add_subplot(gs[1, :])\n\n# PC\nscores.sel(mode=mode).plot(ax=ax_pc)\nax_pc.set_xlabel('')\nax_pc.set_title('')\n\n# EOFs\nfor i, (a, comps) in enumerate(zip(ax, components)):\n a.coastlines(color='.5')\n comps.sel(mode=mode).plot(ax=a, **kwargs)\n a.set_xticks([])\n a.set_yticks([])\n a.set_xlabel('')\n a.set_ylabel('')\n a.set_title('Subset {:}'.format(i+1))\nax[0].set_ylabel('EOFs')\nfig.suptitle('Mode {:}'.format(mode))\nplt.savefig('multivariate-eof-analysis.jpg')"
"mode = 5\nproj = PlateCarree()\nkwargs = {\n \"cmap\": \"RdBu\",\n \"vmin\": -0.05,\n \"vmax\": 0.05,\n \"transform\": proj,\n \"add_colorbar\": False,\n}\n\nfig = plt.figure(figsize=(7.3, 6))\nfig.subplots_adjust(wspace=0)\ngs = GridSpec(2, 4, figure=fig, width_ratios=[1, 1, 1, 1])\nax = [fig.add_subplot(gs[0, i], projection=proj) for i in range(4)]\nax_pc = fig.add_subplot(gs[1, :])\n\n# PC\nscores.sel(mode=mode).plot(ax=ax_pc)\nax_pc.set_xlabel(\"\")\nax_pc.set_title(\"\")\n\n# EOFs\nfor i, (a, comps) in enumerate(zip(ax, components)):\n a.coastlines(color=\".5\")\n comps.sel(mode=mode).plot(ax=a, **kwargs)\n a.set_xticks([])\n a.set_yticks([])\n a.set_xlabel(\"\")\n a.set_ylabel(\"\")\n a.set_title(\"Subset {:}\".format(i + 1))\nax[0].set_ylabel(\"EOFs\")\nfig.suptitle(\"Mode {:}\".format(mode))\nplt.savefig(\"multivariate-eof-analysis.jpg\")"
]
}
],
Expand Down
38 changes: 19 additions & 19 deletions docs/auto_examples/1eof/plot_multivariate-eof.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,32 @@
from xeofs.models import EOF

# Create four different dataarrayss
sst = xr.tutorial.open_dataset('ersstv5')['sst']
sst = xr.tutorial.open_dataset("ersstv5")["sst"]
subset1 = sst.isel(lon=slice(0, 45))
subset2 = sst.isel(lon=slice(46, 90))
subset3 = sst.isel(lon=slice(91, 135))
subset4 = sst.isel(lon=slice(136, None))
multivariate_data = [subset1, subset2, subset3, subset4]

#%%
# %%
# Perform the actual analysis

pca = EOF(standardize=False, use_coslat=True)
pca.fit(multivariate_data, dim='time')
pca = EOF(n_modes=10, standardize=False, use_coslat=True)
pca.fit(multivariate_data, dim="time")
components = pca.components()
scores = pca.scores()

#%%
# %%
# Plot mode 1

mode = 5
proj = PlateCarree()
kwargs = {
'cmap' : 'RdBu',
'vmin' : -.05,
'vmax': .05,
'transform': proj,
'add_colorbar': False
"cmap": "RdBu",
"vmin": -0.05,
"vmax": 0.05,
"transform": proj,
"add_colorbar": False,
}

fig = plt.figure(figsize=(7.3, 6))
Expand All @@ -51,18 +51,18 @@

# PC
scores.sel(mode=mode).plot(ax=ax_pc)
ax_pc.set_xlabel('')
ax_pc.set_title('')
ax_pc.set_xlabel("")
ax_pc.set_title("")

# EOFs
for i, (a, comps) in enumerate(zip(ax, components)):
a.coastlines(color='.5')
a.coastlines(color=".5")
comps.sel(mode=mode).plot(ax=a, **kwargs)
a.set_xticks([])
a.set_yticks([])
a.set_xlabel('')
a.set_ylabel('')
a.set_title('Subset {:}'.format(i+1))
ax[0].set_ylabel('EOFs')
fig.suptitle('Mode {:}'.format(mode))
plt.savefig('multivariate-eof-analysis.jpg')
a.set_xlabel("")
a.set_ylabel("")
a.set_title("Subset {:}".format(i + 1))
ax[0].set_ylabel("EOFs")
fig.suptitle("Mode {:}".format(mode))
plt.savefig("multivariate-eof-analysis.jpg")
2 changes: 1 addition & 1 deletion docs/auto_examples/1eof/plot_multivariate-eof.py.md5
Original file line number Diff line number Diff line change
@@ -1 +1 @@
f7bb6c4569dfd348b51c6634b3b89768
5b802ea42e5a2e0309a67468761e34cc
36 changes: 18 additions & 18 deletions docs/auto_examples/1eof/plot_multivariate-eof.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Multivariate EOF analysis.
from xeofs.models import EOF

# Create four different dataarrayss
sst = xr.tutorial.open_dataset('ersstv5')['sst']
sst = xr.tutorial.open_dataset("ersstv5")["sst"]
subset1 = sst.isel(lon=slice(0, 45))
subset2 = sst.isel(lon=slice(46, 90))
subset3 = sst.isel(lon=slice(91, 135))
Expand All @@ -61,8 +61,8 @@ Perform the actual analysis
.. code-block:: default


pca = EOF(standardize=False, use_coslat=True)
pca.fit(multivariate_data, dim='time')
pca = EOF(n_modes=10, standardize=False, use_coslat=True)
pca.fit(multivariate_data, dim="time")
components = pca.components()
scores = pca.scores()

Expand All @@ -85,11 +85,11 @@ Plot mode 1
mode = 5
proj = PlateCarree()
kwargs = {
'cmap' : 'RdBu',
'vmin' : -.05,
'vmax': .05,
'transform': proj,
'add_colorbar': False
"cmap": "RdBu",
"vmin": -0.05,
"vmax": 0.05,
"transform": proj,
"add_colorbar": False,
}

fig = plt.figure(figsize=(7.3, 6))
Expand All @@ -100,21 +100,21 @@ Plot mode 1

# PC
scores.sel(mode=mode).plot(ax=ax_pc)
ax_pc.set_xlabel('')
ax_pc.set_title('')
ax_pc.set_xlabel("")
ax_pc.set_title("")

# EOFs
for i, (a, comps) in enumerate(zip(ax, components)):
a.coastlines(color='.5')
a.coastlines(color=".5")
comps.sel(mode=mode).plot(ax=a, **kwargs)
a.set_xticks([])
a.set_yticks([])
a.set_xlabel('')
a.set_ylabel('')
a.set_title('Subset {:}'.format(i+1))
ax[0].set_ylabel('EOFs')
fig.suptitle('Mode {:}'.format(mode))
plt.savefig('multivariate-eof-analysis.jpg')
a.set_xlabel("")
a.set_ylabel("")
a.set_title("Subset {:}".format(i + 1))
ax[0].set_ylabel("EOFs")
fig.suptitle("Mode {:}".format(mode))
plt.savefig("multivariate-eof-analysis.jpg")



Expand All @@ -130,7 +130,7 @@ Plot mode 1

.. rst-class:: sphx-glr-timing

**Total running time of the script:** ( 0 minutes 2.172 seconds)
**Total running time of the script:** (0 minutes 2.311 seconds)


.. _sphx_glr_download_auto_examples_1eof_plot_multivariate-eof.py:
Expand Down
Binary file modified docs/auto_examples/1eof/plot_multivariate-eof_codeobj.pickle
Binary file not shown.
8 changes: 4 additions & 4 deletions docs/auto_examples/1eof/sg_execution_times.rst
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

Computation times
=================
**00:03.585** total execution time for **auto_examples_1eof** files:
**00:02.311** total execution time for **auto_examples_1eof** files:

+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_eeof.py` (``plot_eeof.py``) | 00:03.585 | 0.0 MB |
| :ref:`sphx_glr_auto_examples_1eof_plot_multivariate-eof.py` (``plot_multivariate-eof.py``) | 00:02.311 | 0.0 MB |
+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_eeof.py` (``plot_eeof.py``) | 00:00.000 | 0.0 MB |
+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_eof-smode.py` (``plot_eof-smode.py``) | 00:00.000 | 0.0 MB |
+--------------------------------------------------------------------------------------------+-----------+--------+
Expand All @@ -19,8 +21,6 @@ Computation times
+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_mreof.py` (``plot_mreof.py``) | 00:00.000 | 0.0 MB |
+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_multivariate-eof.py` (``plot_multivariate-eof.py``) | 00:00.000 | 0.0 MB |
+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_rotated_eof.py` (``plot_rotated_eof.py``) | 00:00.000 | 0.0 MB |
+--------------------------------------------------------------------------------------------+-----------+--------+
| :ref:`sphx_glr_auto_examples_1eof_plot_weighted-eof.py` (``plot_weighted-eof.py``) | 00:00.000 | 0.0 MB |
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 5 additions & 16 deletions docs/auto_examples/3validation/plot_bootstrap.ipynb
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand All @@ -37,7 +26,7 @@
},
"outputs": [],
"source": [
"t2m = xr.tutorial.load_dataset('air_temperature')['air']"
"t2m = xr.tutorial.load_dataset(\"air_temperature\")[\"air\"]"
]
},
{
Expand All @@ -55,7 +44,7 @@
},
"outputs": [],
"source": [
"model = EOF(n_modes=5, standardize=False, dim='time')\nmodel.fit(t2m, dim='time')\nexpvar = model.explained_variance_ratio()\ncomponents = model.components()\nscores = model.scores()"
"model = EOF(n_modes=5, standardize=False)\nmodel.fit(t2m, dim=\"time\")\nexpvar = model.explained_variance_ratio()\ncomponents = model.components()\nscores = model.scores()"
]
},
{
Expand All @@ -73,7 +62,7 @@
},
"outputs": [],
"source": [
"n_boot = 50\n\nbs = EOFBootstrapper(n_bootstraps=n_boot)\nbs.fit(model)\nbs_expvar = bs.explained_variance()\nci_expvar = bs_expvar.quantile([0.025, 0.975], 'n') # 95% confidence intervals\n\nq025 = ci_expvar.sel(quantile=0.025)\nq975 = ci_expvar.sel(quantile=0.975)\n\nis_significant = q025 - q975.shift({'mode': -1}) > 0\nn_significant_modes = is_significant.where(is_significant==True).cumsum(skipna=False).max().fillna(0)\nprint('{:} modes are significant at alpha=0.05'.format(n_significant_modes.values))"
"n_boot = 50\n\nbs = EOFBootstrapper(n_bootstraps=n_boot)\nbs.fit(model)\nbs_expvar = bs.explained_variance()\nci_expvar = bs_expvar.quantile([0.025, 0.975], \"n\") # 95% confidence intervals\n\nq025 = ci_expvar.sel(quantile=0.025)\nq975 = ci_expvar.sel(quantile=0.975)\n\nis_significant = q025 - q975.shift({\"mode\": -1}) > 0\nn_significant_modes = (\n is_significant.where(is_significant == True).cumsum(skipna=False).max().fillna(0)\n)\nprint(\"{:} modes are significant at alpha=0.05\".format(n_significant_modes.values))"
]
},
{
Expand All @@ -91,7 +80,7 @@
},
"outputs": [],
"source": [
"ci_components = bs.components().quantile([0.025, 0.975], 'n')\nci_scores = bs.scores().quantile([0.025, 0.975], 'n')\n\nis_sig_comps = (np.sign(ci_components).prod('quantile') > 0)"
"ci_components = bs.components().quantile([0.025, 0.975], \"n\")\nci_scores = bs.scores().quantile([0.025, 0.975], \"n\")\n\nis_sig_comps = np.sign(ci_components).prod(\"quantile\") > 0"
]
},
{
Expand All @@ -109,7 +98,7 @@
},
"outputs": [],
"source": [
"lons, lats = np.meshgrid(is_sig_comps.lon.values, is_sig_comps.lat.values)\nproj = Orthographic(central_latitude=30, central_longitude=-80)\nkwargs = {\n 'cmap' : 'RdBu', 'vmin' : -.05, 'vmax': .05, 'transform': PlateCarree()\n}\n\nfig = plt.figure(figsize=(10, 16))\ngs = GridSpec(5, 2)\nax1 = [fig.add_subplot(gs[i, 0], projection=proj) for i in range(5)]\nax2 = [fig.add_subplot(gs[i, 1]) for i in range(5)]\n\nfor i, (a1, a2) in enumerate(zip(ax1, ax2)):\n a1.coastlines(color='.5')\n components.isel(mode=i).plot(ax=a1, **kwargs)\n a1.scatter(\n lons, lats, is_sig_comps.isel(mode=i).values * .5,\n color='k', alpha=.5, transform=PlateCarree()\n )\n ci_scores.isel(mode=i, quantile=0).plot(ax=a2, color='.3', lw='.5', label='2.5%')\n ci_scores.isel(mode=i, quantile=1).plot(ax=a2, color='.3', lw='.5', label='97.5%')\n scores.isel(mode=i).plot(ax=a2, lw='.5', alpha=.5, label='PC')\n a2.legend(loc=2)\n\nplt.tight_layout()\nplt.savefig('bootstrap.jpg')"
"lons, lats = np.meshgrid(is_sig_comps.lon.values, is_sig_comps.lat.values)\nproj = Orthographic(central_latitude=30, central_longitude=-80)\nkwargs = {\"cmap\": \"RdBu\", \"vmin\": -0.05, \"vmax\": 0.05, \"transform\": PlateCarree()}\n\nfig = plt.figure(figsize=(10, 16))\ngs = GridSpec(5, 2)\nax1 = [fig.add_subplot(gs[i, 0], projection=proj) for i in range(5)]\nax2 = [fig.add_subplot(gs[i, 1]) for i in range(5)]\n\nfor i, (a1, a2) in enumerate(zip(ax1, ax2)):\n a1.coastlines(color=\".5\")\n components.isel(mode=i).plot(ax=a1, **kwargs)\n a1.scatter(\n lons,\n lats,\n is_sig_comps.isel(mode=i).values * 0.5,\n color=\"k\",\n alpha=0.5,\n transform=PlateCarree(),\n )\n ci_scores.isel(mode=i, quantile=0).plot(ax=a2, color=\".3\", lw=\".5\", label=\"2.5%\")\n ci_scores.isel(mode=i, quantile=1).plot(ax=a2, color=\".3\", lw=\".5\", label=\"97.5%\")\n scores.isel(mode=i).plot(ax=a2, lw=\".5\", alpha=0.5, label=\"PC\")\n a2.legend(loc=2)\n\nplt.tight_layout()\nplt.savefig(\"bootstrap.jpg\")"
]
}
],
Expand Down
54 changes: 29 additions & 25 deletions docs/auto_examples/3validation/plot_bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,21 @@
from xeofs.models import EOF
from xeofs.validation import EOFBootstrapper

#%%
# %%

t2m = xr.tutorial.load_dataset('air_temperature')['air']
t2m = xr.tutorial.load_dataset("air_temperature")["air"]

#%%
# %%
# Perform EOF analysis

model = EOF(n_modes=5, standardize=False, dim='time')
model.fit(t2m, dim='time')
model = EOF(n_modes=5, standardize=False)
model.fit(t2m, dim="time")
expvar = model.explained_variance_ratio()
components = model.components()
scores = model.scores()


#%%
# %%
# Perform bootstrapping of the model to identy the number of significant modes.
# We perform 50 bootstraps.
# Note - if computationallly feasible - you typically want to choose higher
Expand All @@ -42,52 +42,56 @@
bs = EOFBootstrapper(n_bootstraps=n_boot)
bs.fit(model)
bs_expvar = bs.explained_variance()
ci_expvar = bs_expvar.quantile([0.025, 0.975], 'n') # 95% confidence intervals
ci_expvar = bs_expvar.quantile([0.025, 0.975], "n") # 95% confidence intervals

q025 = ci_expvar.sel(quantile=0.025)
q975 = ci_expvar.sel(quantile=0.975)

is_significant = q025 - q975.shift({'mode': -1}) > 0
n_significant_modes = is_significant.where(is_significant==True).cumsum(skipna=False).max().fillna(0)
print('{:} modes are significant at alpha=0.05'.format(n_significant_modes.values))
is_significant = q025 - q975.shift({"mode": -1}) > 0
n_significant_modes = (
is_significant.where(is_significant == True).cumsum(skipna=False).max().fillna(0)
)
print("{:} modes are significant at alpha=0.05".format(n_significant_modes.values))

#%%
# %%
# The bootstrapping procedure identifies 3 significant modes. We can also
# compute the 95 % confidence intervals of the EOFs/PCs and mask out
# insignificant elements of the obtained EOFs.

ci_components = bs.components().quantile([0.025, 0.975], 'n')
ci_scores = bs.scores().quantile([0.025, 0.975], 'n')
ci_components = bs.components().quantile([0.025, 0.975], "n")
ci_scores = bs.scores().quantile([0.025, 0.975], "n")

is_sig_comps = (np.sign(ci_components).prod('quantile') > 0)
is_sig_comps = np.sign(ci_components).prod("quantile") > 0


#%%
# %%
# Summarize the results in a figure.


lons, lats = np.meshgrid(is_sig_comps.lon.values, is_sig_comps.lat.values)
proj = Orthographic(central_latitude=30, central_longitude=-80)
kwargs = {
'cmap' : 'RdBu', 'vmin' : -.05, 'vmax': .05, 'transform': PlateCarree()
}
kwargs = {"cmap": "RdBu", "vmin": -0.05, "vmax": 0.05, "transform": PlateCarree()}

fig = plt.figure(figsize=(10, 16))
gs = GridSpec(5, 2)
ax1 = [fig.add_subplot(gs[i, 0], projection=proj) for i in range(5)]
ax2 = [fig.add_subplot(gs[i, 1]) for i in range(5)]

for i, (a1, a2) in enumerate(zip(ax1, ax2)):
a1.coastlines(color='.5')
a1.coastlines(color=".5")
components.isel(mode=i).plot(ax=a1, **kwargs)
a1.scatter(
lons, lats, is_sig_comps.isel(mode=i).values * .5,
color='k', alpha=.5, transform=PlateCarree()
lons,
lats,
is_sig_comps.isel(mode=i).values * 0.5,
color="k",
alpha=0.5,
transform=PlateCarree(),
)
ci_scores.isel(mode=i, quantile=0).plot(ax=a2, color='.3', lw='.5', label='2.5%')
ci_scores.isel(mode=i, quantile=1).plot(ax=a2, color='.3', lw='.5', label='97.5%')
scores.isel(mode=i).plot(ax=a2, lw='.5', alpha=.5, label='PC')
ci_scores.isel(mode=i, quantile=0).plot(ax=a2, color=".3", lw=".5", label="2.5%")
ci_scores.isel(mode=i, quantile=1).plot(ax=a2, color=".3", lw=".5", label="97.5%")
scores.isel(mode=i).plot(ax=a2, lw=".5", alpha=0.5, label="PC")
a2.legend(loc=2)

plt.tight_layout()
plt.savefig('bootstrap.jpg')
plt.savefig("bootstrap.jpg")
2 changes: 1 addition & 1 deletion docs/auto_examples/3validation/plot_bootstrap.py.md5
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1946ef082c229ecf95a65ecb60d2cb7a
3ab68b97210891b1db8335ada89b8563
Loading