Skip to content
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
5 changes: 3 additions & 2 deletions docs/content/user_guide/examples/1single/plot_gwpca.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,10 @@
# As the stations are positioned on a irregular grid, we'll transform the
# ``llwc`` ``DataArray`` into a ``pandas.DataFrame``. After that, we can easily visualize
# it using the ``scatter`` method.
# Reset the station index before converting so ``x`` and ``y`` become columns.
# For demonstation, we'll concentrate on the first mode:

llwc1_df = llwc.sel(mode=1).to_dataframe()
llwc1_df = llwc.sel(mode=1).reset_index("station").to_dataframe()

elements = da.element.values
n_elements = len(elements)
Expand Down Expand Up @@ -163,7 +164,7 @@


exp_var_ratio = gwpca.explained_variance_ratio()
evr1_df = exp_var_ratio.sel(mode=1).to_dataframe()
evr1_df = exp_var_ratio.sel(mode=1).reset_index("station").to_dataframe()

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
Expand Down
47 changes: 47 additions & 0 deletions tests/test_docs_examples.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import ast
from pathlib import Path

import numpy as np
import pytest
import xarray as xr


@pytest.mark.parametrize(
"result_name, data_name, frame_name",
[
("llwc", "largest_locally_weighted_components", "llwc1_df"),
("exp_var_ratio", "explained_variance_ratio", "evr1_df"),
],
)
def test_gwpca_example_dataframe_coordinate_columns(result_name, data_name, frame_name):
result = xr.DataArray(
[[1, 2], [3, 4], [5, 6]],
dims=("station", "mode"),
coords={
"mode": [1, 2],
"x": ("station", [10.0, 30.0, 20.0]),
"y": ("station", [40.0, 20.0, 30.0]),
},
name=data_name,
).set_index(station=("x", "y"))

example = (
Path(__file__).resolve().parents[1]
/ "docs/content/user_guide/examples/1single/plot_gwpca.py"
)
# Run the actual conversion without the example's R downloads or plotting.
conversion = next(
statement.value
for statement in ast.parse(example.read_text()).body
if isinstance(statement, ast.Assign)
and isinstance(statement.targets[0], ast.Name)
and statement.targets[0].id == frame_name
)
frame = eval(
compile(ast.Expression(conversion), str(example), "eval"),
{result_name: result},
)

np.testing.assert_array_equal(frame["x"], result.x)
np.testing.assert_array_equal(frame["y"], result.y)
np.testing.assert_array_equal(frame[data_name], result.sel(mode=1))
Loading