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

Dura mat mountain pref #124

Merged
merged 6 commits into from
Sep 30, 2024
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
2 changes: 1 addition & 1 deletion pvdeg/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from . import humidity
from . import letid
from . import montecarlo
from . import scenario
from .scenario import Scenario, GeospatialScenario
from . import spectral
from . import symbolic
from . import standards
Expand Down
124 changes: 112 additions & 12 deletions pvdeg/geospatial.py
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@ def elevation_stochastic_downselect(
Options : `'mean'`, `'sum'`, `'median'`
normalization : str, (default = 'linear')
function to apply when normalizing weights. Logarithmic uses log_e/ln
options : `'linear'`, `'logarithmic'`, '`exponential'`
options : `'linear'`, `'log'`, '`exp'`, `'invert-linear'`

Returns:
--------
Expand Down Expand Up @@ -927,14 +927,17 @@ def elevation_stochastic_downselect(


def interpolate_analysis(
result: xr.Dataset, data_var: str, method="nearest"
result: xr.Dataset, data_var: str, method="nearest", resolution=100j,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Interpolate sparse spatial result data against DataArray coordinates.
Takes DataArray instead of Dataset, index one variable of a dataset to get a dataarray.

Parameters:
-----------
resolution: complex
Change the amount the input is interpolated.
For more interpolation set higher (200j is more than 100j)

Result:
-------
Expand All @@ -951,22 +954,53 @@ def interpolate_analysis(
) # probably a nicer way to do this

grid_lat, grid_lon = np.mgrid[
df["latitude"].min() : df["latitude"].max() : 100j,
df["longitude"].min() : df["longitude"].max() : 100j,
df["latitude"].min() : df["latitude"].max() : resolution,
df["longitude"].min() : df["longitude"].max() : resolution,
]

grid_z = griddata(data[:, 0:2], data[:, 2], xi=(grid_lat, grid_lon), method=method)

return grid_z, grid_lat, grid_lon


def plot_sparse_analysis(result: xr.Dataset, data_var: str, method="nearest") -> None:
# api could be updated to match that of plot_USA
def plot_sparse_analysis(
result: xr.Dataset,
data_var: str,
method="nearest",
resolution:complex=100j,
figsize:tuple=(10,8),
show_plot:bool=False,
) -> None:
"""
Plot the output of a sparse geospatial analysis using interpolation.

Parameters
-----------
result: xr.Dataset
xarray dataset in memory containing coordinates['longitude', 'latitude'] and at least one datavariable.
data_var: str
name of datavariable to plot from result
method: str
interpolation method.
Options: `'nearest', 'linear', 'cubic'`
See [`scipy.interpolate.griddata`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html)
resolution: complex
Change the amount the input is interpolated.
For more interpolation set higher (200j is more than 100j)

Returns
-------
fig, ax: tuple
matplotlib figure and axes of plot
"""

grid_values, lat, lon = interpolate_analysis(
result=result, data_var=data_var, method=method
result=result, data_var=data_var, method=method, resolution=resolution
)

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal(), frameon=False)
fig = plt.figure(figsize=figsize)
ax = fig.add_axes([0, 0, 1, 1], projection=ccrs.LambertConformal(), frameon=False) # these should be the same ccrs
ax.patch.set_visible(False)

extent = [lon.min(), lon.max(), lat.min(), lat.max()]
Expand All @@ -976,8 +1010,8 @@ def plot_sparse_analysis(result: xr.Dataset, data_var: str, method="nearest") ->
extent=extent,
origin="lower",
cmap="viridis",
transform=ccrs.PlateCarree(),
) # should this be trnsposed
transform=ccrs.PlateCarree(), # why are ccrs different
)

shapename = "admin_1_states_provinces_lakes"
states_shp = shpreader.natural_earth(
Expand All @@ -994,7 +1028,73 @@ def plot_sparse_analysis(result: xr.Dataset, data_var: str, method="nearest") ->
cbar = plt.colorbar(img, ax=ax, orientation="vertical", fraction=0.02, pad=0.04)
cbar.set_label("Value")

plt.title("Interpolated Heatmap")
plt.title(f"Interpolated Sparse Analysis, {data_var}")
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.show()

if show_plot:
plt.show()

return fig, ax

def plot_sparse_analysis_land(
result: xr.Dataset,
data_var: str,
method="nearest",
resolution:complex=100j,
figsize:tuple=(10,8),
show_plot:bool=False,
proj=ccrs.PlateCarree(),
):

import matplotlib.path as mpath
from cartopy.mpl.patch import geos_to_path

grid_values, lat, lon = interpolate_analysis(
result=result, data_var=data_var, method=method, resolution=resolution
)

fig = plt.figure(figsize=figsize)
ax = fig.add_axes([0, 0, 1, 1], projection=proj, frameon=False)
ax.patch.set_visible(False)

extent = [lon.min(), lon.max(), lat.min(), lat.max()]
ax.set_extent(extent, crs=proj)

mesh = ax.pcolormesh(lon, lat, grid_values, transform=proj, cmap='viridis')

land_path = geos_to_path(list(cfeature.LAND.geometries()))
land_path = mpath.Path.make_compound_path(*land_path)
plate_carre_data_transform = proj._as_mpl_transform(ax)
mesh.set_clip_path(land_path, plate_carre_data_transform)

shapename = "admin_1_states_provinces_lakes"
states_shp = shpreader.natural_earth(
resolution="110m", category="cultural", name=shapename
)

ax.add_geometries(
shpreader.Reader(states_shp).geometries(),
proj,
facecolor="none",
edgecolor="black",
linestyle=':'
)

cbar = plt.colorbar(mesh, ax=ax, orientation="vertical", fraction=0.02, pad=0.04)
cbar.set_label("Value")

utilities._add_cartopy_features(
ax=ax,
features = [
cfeature.BORDERS,
cfeature.COASTLINE,
cfeature.LAND,
cfeature.OCEAN,
],
)

if show_plot:
plt.show()

return fig, ax
Loading