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

Update MoV code to use xCDAT #1020

Merged
merged 101 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
101 commits
Select commit Hold shift + click to select a range
7c54910
add more stats for MoV driver
lee1043 Jan 8, 2024
86ca9b2
update
lee1043 Jan 9, 2024
a15e5c8
update eofs to v1.4.1
lee1043 Jan 10, 2024
8ca46ad
clean up
lee1043 Jan 11, 2024
9cc5783
pre-commit fix
lee1043 Jan 11, 2024
05fafeb
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Jan 11, 2024
5dc869f
some functions moved to io
lee1043 Jan 11, 2024
585c867
clean up
lee1043 Jan 12, 2024
1579cf1
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Jan 12, 2024
80dbdba
update
lee1043 Jan 14, 2024
60feadc
clean up
lee1043 Jan 15, 2024
53ec879
duplicate string constructor to io because of circular import error
lee1043 Jan 16, 2024
1e2073f
pre-commit fix
lee1043 Jan 16, 2024
ed93d69
use fill_template from io instead of utils
lee1043 Jan 16, 2024
79902b7
use calcTCOR from newer position and pre-commit fix
lee1043 Jan 16, 2024
e4d3498
update
lee1043 Jan 17, 2024
a087755
update
lee1043 Jan 17, 2024
348b859
clean up, add regrid utils
lee1043 Jan 17, 2024
ccbc08d
debug and updates
lee1043 Jan 18, 2024
02d3068
bug fix (continue)
lee1043 Jan 18, 2024
a0a716a
bug fix
lee1043 Jan 24, 2024
0fa57f6
add north test as a part of the driver
lee1043 Jan 24, 2024
ce979f7
bug fix
lee1043 Jan 24, 2024
e495fee
bug fix
lee1043 Jan 25, 2024
8a606bc
pre-commit fix
lee1043 Jan 25, 2024
ad84f7a
clean up
lee1043 Jan 25, 2024
2d89f57
pre-commit fix
lee1043 Jan 25, 2024
3c1a873
bug fix
lee1043 Jan 26, 2024
60772d4
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Jan 26, 2024
052d3e8
bug fix
lee1043 Jan 26, 2024
c1a28b1
bug fix
lee1043 Jan 26, 2024
8d10543
simplify, clean up, add link to PMP installation
lee1043 Jan 26, 2024
6bb67ae
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Jan 26, 2024
64a8b31
add logo and clean up in the demo notebook
lee1043 Jan 27, 2024
28e6cf8
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Jan 27, 2024
f968029
clean up
lee1043 Jan 30, 2024
5f039de
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Feb 1, 2024
8c8caeb
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Feb 2, 2024
f2c1593
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Feb 7, 2024
426e7fc
logic simplified
lee1043 Feb 7, 2024
8d4f9de
clean up
lee1043 Feb 8, 2024
6bc7232
update
lee1043 Feb 12, 2024
84e5f9d
Merge pull request #1060 from PCMDI/feature/lee1043-mov-modularize
lee1043 Feb 22, 2024
fbca25c
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Feb 22, 2024
c9c5d3c
make code calender flexible -- reduced calendar dependency
lee1043 Feb 22, 2024
131df5c
pre-commit fix
lee1043 Feb 22, 2024
65b69c4
bug fix
lee1043 Feb 26, 2024
cf6fb8a
move timeseries adjustment in a new separate file
lee1043 Feb 26, 2024
ae02779
Merge branch 'feature/1012_lee1043_stats-MoV_xcdat' into feature/lee1…
lee1043 Feb 26, 2024
dd09f56
Merge pull request #1062 from PCMDI/feature/lee1043-mov-modularize
lee1043 Feb 26, 2024
be22674
separate adjust timeseries
lee1043 Feb 26, 2024
5f9ca3e
clean up
lee1043 Feb 26, 2024
51af8ca
Merge branch 'feature/1012_lee1043_stats-MoV_xcdat' of github.com:PCM…
lee1043 Feb 26, 2024
dd91e78
clean up
lee1043 Feb 26, 2024
3df31a1
update
lee1043 Feb 27, 2024
0544c51
Merge branch 'feature/1012_lee1043_stats-MoV_xcdat' of github.com:PCM…
lee1043 Feb 29, 2024
12ed70b
clean up
lee1043 Feb 29, 2024
156a3e4
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Mar 4, 2024
cc569fb
rename to simplify
lee1043 Mar 4, 2024
8cdfa78
clean up + bug fix
lee1043 Mar 7, 2024
61da5b6
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Mar 7, 2024
496ed5f
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Mar 12, 2024
3b2dceb
pre-commit fix
lee1043 Mar 12, 2024
8ec3dac
clean up
lee1043 Mar 12, 2024
000fe20
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Mar 15, 2024
9c09dc4
add demo script but for pcmdi internal
lee1043 Apr 4, 2024
81c794f
bug fix
lee1043 Apr 4, 2024
db0a396
bug fix
lee1043 Apr 4, 2024
00fc735
add missing bounds for sanity check
lee1043 Apr 4, 2024
f2f6736
in progress...
lee1043 Apr 4, 2024
0e18825
clean up..
lee1043 Apr 4, 2024
31c4298
fix bug for SAM region
lee1043 Apr 4, 2024
c6f6a81
enable automatic assignment of eofn_obs and eofn_mod by mode name
lee1043 Apr 4, 2024
f84c310
pre-commit clean up
lee1043 Apr 4, 2024
dee6096
remove eofn_obs and eofn_mod from pcmdi params
lee1043 Apr 5, 2024
77158d4
clean up
lee1043 Apr 5, 2024
6b2a562
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Apr 5, 2024
a5fa6cd
bug fix
lee1043 Apr 15, 2024
219334b
bug fix for sign flip -- revealed by SAM test
lee1043 Apr 15, 2024
f48ea9a
update required xcdat version regarding https://github.com/PCMDI/pcmd…
lee1043 Apr 16, 2024
5880600
pre-commit fix
lee1043 Apr 16, 2024
5ad2b21
moved missing bounds adding to io function
lee1043 Apr 16, 2024
376bffb
bug fix for centered rmse
lee1043 Apr 17, 2024
b115384
pre-commit fix
lee1043 Apr 17, 2024
b14c5fb
reduce potential memory usage
lee1043 Apr 17, 2024
719d4a3
bug fix: normalize by map std for centered RMSE calculation
lee1043 Apr 19, 2024
c4d2791
keep updated
lee1043 Apr 24, 2024
113d045
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Apr 24, 2024
d886049
clean up and simplified
lee1043 Apr 24, 2024
6a414c6
Merge branch 'feature/1012_lee1043_stats-MoV_xcdat' of github.com:PCM…
lee1043 Apr 24, 2024
436cfc9
initial commit for custom season capability
lee1043 Apr 26, 2024
e600190
add custom season capability
lee1043 Apr 26, 2024
b9e5aea
updated notebook to include custom season
lee1043 Apr 26, 2024
c6d9e3c
Merge pull request #1085 from PCMDI/feature/1012_lee1043_stats-MoV_xc…
lee1043 Apr 26, 2024
5aac6f7
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Apr 26, 2024
abbbd9a
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 Apr 30, 2024
91bb1c9
bug fix
lee1043 May 1, 2024
1392682
clean up
lee1043 May 1, 2024
893c5b3
pre-commit fix
lee1043 May 1, 2024
04829b1
Merge branch 'main' into feature/1012_lee1043_stats-MoV_xcdat
lee1043 May 2, 2024
2bd8aec
clean up, more debug printout added
lee1043 May 2, 2024
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
Prev Previous commit
Next Next commit
clean up + bug fix
  • Loading branch information
lee1043 committed Mar 7, 2024
commit 8cdfa785a3eaca40bb1a5fc89837f1dac0bb65a7
16 changes: 9 additions & 7 deletions pcmdi_metrics/io/xcdat_dataset_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,22 +199,24 @@ def da_to_ds(d: Union[xr.Dataset, xr.DataArray], var: str = "variable") -> xr.Da


def get_grid(
ds: xr.Dataset,
d: Union[xr.Dataset, xr.DataArray],
) -> xr.Dataset:
"""Get grid information

Parameters
----------
ds : xr.Dataset
d : Union[xr.Dataset, xr.DataArray]
xarray dataset to extract grid information that has latitude, longitude, and their bounds included

Returns
-------
xr.Dataset
xarray dataset with grid information
"""
lat_key = get_latitude_key(ds)
lon_key = get_longitude_key(ds)
lat_bnds_key = get_latitude_bounds_key(ds)
lon_bnds_key = get_longitude_bounds_key(ds)
return ds[[lat_key, lon_key, lat_bnds_key, lon_bnds_key]]
if isinstance(d, xr.DataArray):
d = da_to_ds(d, d.name)
lat_key = get_latitude_key(d)
lon_key = get_longitude_key(d)
lat_bnds_key = get_latitude_bounds_key(d)
lon_bnds_key = get_longitude_bounds_key(d)
return d[[lat_key, lon_key, lat_bnds_key, lon_bnds_key]]
1 change: 1 addition & 0 deletions pcmdi_metrics/mean_climate/lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@
from .create_mean_climate_parser import create_mean_climate_parser # noqa
from .load_and_regrid import load_and_regrid # noqa
from .mean_climate_metrics_to_json import mean_climate_metrics_to_json # noqa
from .pmp_parser import PMPParser # noqa
23 changes: 22 additions & 1 deletion pcmdi_metrics/utils/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import xcdat as xc

from pcmdi_metrics.io import (
get_grid,
get_latitude_bounds_key,
get_latitude_key,
get_longitude_bounds_key,
Expand Down Expand Up @@ -143,8 +144,23 @@ def regrid(
data_var: str,
target_grid: xr.Dataset,
regrid_tool: str = "regrid2",
regrid_method: str = None,
regrid_method: str = "bilinear",
fill_zero: bool = False,
) -> xr.Dataset:
"""regrid the dataset to a given grid

Args:
ds (xr.Dataset): dataset to regrid
data_var (str): variable in the dataset
target_grid (xr.Dataset): grid for interpolate to
regrid_tool (str, optional): Regrid option: "regrid2" or "xesmf". Defaults to "regrid2".
regrid_method (str, optional): Regrid method option that is required for xesmf regridder. Defaults to "bilinear".
fill_zero (bool, optional): Fill NaN value with zero if exists. Defaluts to False

Returns:
xr.Dataset: Regridded dataset
"""
target_grid = get_grid(target_grid) # To remove time dimension if exist
# regrid
if regrid_tool == "regrid2":
ds_regridded = ds.regridder.horizontal(data_var, target_grid, tool=regrid_tool)
Expand All @@ -154,4 +170,9 @@ def regrid(
ds_regridded = ds.regridder.horizontal(
data_var, target_grid, tool=regrid_tool, method=regrid_method
)

if fill_zero:
ds_regridded = ds_regridded.fillna(0)

ds_regridded = ds_regridded.bounds.add_missing_bounds() # just in case
return ds_regridded
49 changes: 43 additions & 6 deletions pcmdi_metrics/utils/land_sea_mask.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
from typing import Union

import numpy as np
import numpy.ma as ma
import regionmask
import xarray as xr
import xcdat as xc

from pcmdi_metrics import resources
from pcmdi_metrics.io import get_grid


def create_land_sea_mask(
Expand Down Expand Up @@ -183,7 +185,24 @@ def apply_landmask(
data_array = obj[data_var].copy()

# Validate landfrac
generateLandSeaMask = False
where_method = "xarray"
if landfrac is None:
generateLandSeaMask = True
else:
data_grid = get_grid(data_array)
lf_grid = get_grid(landfrac)

if data_grid.identical(lf_grid):
pass
else:
if data_grid.equals(lf_grid):
pass
else:
if data_grid.sizes == lf_grid.sizes:
where_method = "numpy"

if generateLandSeaMask:
landfrac = create_land_sea_mask(data_array)
warnings.warn(
"landfrac is not provided thus generated using the 'create_land_sea_mask' function"
Expand All @@ -199,7 +218,7 @@ def apply_landmask(

# Convert landfrac to a fraction if it's in percentage form
if percentage:
landfrac /= 100.0
landfrac = landfrac.copy() / 100.0

# Validate keep_over parameter
if keep_over not in ["land", "ocean"]:
Expand All @@ -208,10 +227,28 @@ def apply_landmask(
)

# Apply land and ocean masks
if keep_over == "land":
data_array = data_array.where(landfrac >= land_criteria)
elif keep_over == "ocean":
data_array = data_array.where(landfrac <= ocean_criteria)
if where_method == "xarray":
if keep_over == "land":
data_array = data_array.where(landfrac >= land_criteria)
elif keep_over == "ocean":
data_array = data_array.where(landfrac <= ocean_criteria)

elif where_method == "numpy":
# Expand data1 to match the shape of landfrac along the time dimension
expanded_landfrac = np.expand_dims(landfrac.data, axis=0)
expanded_landfrac = np.repeat(
expanded_landfrac, data_array.shape[0], axis=0
) # Repeat along the time dimension

# Mask data based on landfrac
if keep_over == "land":
data_array.data = ma.masked_where(
expanded_landfrac < land_criteria, data_array.data
)
elif keep_over == "ocean":
data_array.data = ma.masked_where(
expanded_landfrac > ocean_criteria, data_array.data
)

return data_array

Expand All @@ -233,7 +270,7 @@ def apply_oceanmask(
)
return masked_data_array


def generate_land_sea_mask__pcmdi(
target_grid,
source=None,
Expand Down
7 changes: 4 additions & 3 deletions pcmdi_metrics/variability_mode/lib/eof_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def linear_regression_on_globe_for_teleconnection(
return eof_lr, slope, intercept


def linear_regression(x, y):
def linear_regression(x, y, debug=False):
"""
NOTE: Proceed linear regression
Input
Expand All @@ -211,8 +211,9 @@ def linear_regression(x, y):
im = y.shape[2]
jm = y.shape[1]
y_2d = y.data.reshape(y.shape[0], jm * im)
print("x.shape:", x.shape)
print("y_2d.shape:", y_2d.shape)
if debug:
print("x.shape:", x.shape)
print("y_2d.shape:", y_2d.shape)
# Linear regression
slope_1d, intercept_1d = np.polyfit(np.array(x), np.array(y_2d), 1)
# Retreive to variabile from numpy array
Expand Down
10 changes: 7 additions & 3 deletions pcmdi_metrics/variability_mode/lib/lib_variability_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,15 @@ def read_data_in(
# landmask if required
if LandMask:
# Extract SST (land region mask out)
landfrac = None
landfrac = None # by default, generate a land sea mask
if lf_path is not None:
if os.path.isfile(lf_path):
landfrac_ds = xcdat_open(lf_path)
landfrac = landfrac_ds[var_lf]
try:
landfrac_ds = xcdat_open(lf_path)
landfrac = landfrac_ds[var_lf]
except Exception:
landfrac = None # if unsuccessful, generate a land sea mask

data_timeseries = apply_landmask(data_timeseries, landfrac=landfrac)

ds_time_subsetted[var_in_data] = data_timeseries
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ def main():
# mips = ['cmip3']

# exps = ['historical', 'amip']
# exps = ['historical']
exps = ["amip"]
exps = ["historical"]
# exps = ["amip"]
# exps = ['20c3m', 'amip']
# exps = ['20c3m']

case_id = "v20210119"
# case_id = "v20210119"
case_id = "v20240227"

syear = 1900
eyear = 2005
Expand Down
13 changes: 9 additions & 4 deletions pcmdi_metrics/variability_mode/variability_modes_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,8 @@
# -------------------------------------------------
for model_path in model_path_list:
print("model_path:", model_path)
try:
# try:
if 1:
if realization == "*":
run = re.split("[._]", (model_path.split("/")[-1]).split("."))[
run_in_modpath
Expand Down Expand Up @@ -627,7 +628,11 @@

# Regrid (interpolation, model grid to ref grid)
model_timeseries_season_regrid = regrid(
model_timeseries_season, var, ref_grid_global
model_timeseries_season,
var,
ref_grid_global,
regrid_tool="xesmf",
fill_zero=True,
)
# crop to subdomain
model_timeseries_season_regrid_subdomain = region_subset(
Expand Down Expand Up @@ -988,14 +993,14 @@
run=run,
cmec_flag=cmec,
)

"""
except Exception as err:
if debug:
raise
else:
print("warning: failed for ", model, run, err)
pass

"""
# ========================================================================
# Dictionary to JSON: collective JSON at the end of model_realization loop
# ------------------------------------------------------------------------
Expand Down
Loading