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
bug fix (continue)
  • Loading branch information
lee1043 committed Jan 18, 2024
commit 02d306892a4cd30238ce8a5968bfff5c4c7f77e8
36 changes: 19 additions & 17 deletions pcmdi_metrics/variability_mode/lib/calc_stat.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from time import gmtime, strftime

import xarray as xr

from pcmdi_metrics.io import get_grid, region_subset
from pcmdi_metrics.stats import bias_xy as calcBias
from pcmdi_metrics.stats import cor_xy as calcSCOR
Expand All @@ -10,14 +12,14 @@


def calc_stats_save_dict(
mode,
dict_head,
eof,
eof_lr,
mode: str,
dict_head: dict,
eof: xr.Dataset,
eof_lr: xr.Dataset,
pc,
stdv_pc,
frac,
regions_specs,
regions_specs: dict = None,
eof_obs=None,
eof_lr_obs=None,
stdv_pc_obs=None,
Expand All @@ -28,6 +30,7 @@ def calc_stats_save_dict(
"""
NOTE: Calculate statistics and save numbers to dictionary for JSON.
Input
- mode: [str] name of variability mode
- dict_head: [dict] subset of dictionary
- eof: [2d field] linear regressed eof pattern (eof domain)
- eof_lr: [2d field] linear regressed eof pattern (global)
Expand Down Expand Up @@ -60,18 +63,17 @@ def calc_stats_save_dict(
# Note: '_glo' indicates statistics calculated over global domain
# . . . . . . . . . . . . . . . . . . . . . . . . .
if obs_compare:
if method in ["eof", "cbf"]:
ref_grid_global = get_grid(eof_lr_obs)
# Regrid (interpolation, model grid to ref grid)
debug_print("regrid (global) start", debug)
# eof_model_global = eof_lr.regrid(eof_lr,
# ref_grid_global, regridTool="regrid2", mkCyclic=True
# )
eof_model_global = regrid(eof_lr, ref_grid_global)
debug_print("regrid end", debug)
# Extract subdomain
# eof_model = eof_model_global(region_subdomain)
eof_model = region_subset(eof_model_global, mode, regions_specs)
ref_grid_global = get_grid(eof_lr_obs)
# Regrid (interpolation, model grid to ref grid)
debug_print("regrid (global) start", debug)
# eof_model_global = eof_lr.regrid(eof_lr,
# ref_grid_global, regridTool="regrid2", mkCyclic=True
# )
eof_model_global = regrid(eof_lr, ref_grid_global)
debug_print("regrid end", debug)
# Extract subdomain
# eof_model = eof_model_global(region_subdomain)
eof_model = region_subset(eof_model_global, mode, regions_specs=regions_specs)

# Spatial correlation weighted by area ('generate' option for weights)
cor = calcSCOR(eof_model, eof_obs)
Expand Down
9 changes: 5 additions & 4 deletions pcmdi_metrics/variability_mode/lib/eof_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,22 +174,23 @@ def arbitrary_checking(mode, eof_Nth):


def linear_regression_on_globe_for_teleconnection(
pc, model_timeseries, stdv_pc, RmDomainMean=True, EofScaling=False, debug=False
pc, ds, data_var, stdv_pc, RmDomainMean=True, EofScaling=False, debug=False
):
"""
- Reconstruct EOF fist mode including teleconnection purpose as well
- Have confirmed that "eof_lr" is identical to "eof" over EOF domain (i.e., "subdomain")
- Note that eof_lr has global field
"""
if debug:
print("pc.shape, timeseries.shape:", pc.shape, model_timeseries.shape)
print("pc.shape, timeseries.shape:", pc.shape, ds[data_var].shape)

# Linear regression to have extended global map; teleconnection purpose
slope, intercept = linear_regression(pc, model_timeseries)
slope, intercept = linear_regression(pc, ds[data_var])

factor = stdv_pc
if not RmDomainMean and EofScaling:
factor = 1
else:
factor = stdv_pc

eof_lr = (slope * factor) + intercept

Expand Down
8 changes: 6 additions & 2 deletions pcmdi_metrics/variability_mode/lib/lib_variability_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,14 @@ def diff_month(date1, date2):
return (date2.year - date1.year) * 12 + date2.month - date1.month + 1


def debug_print(string, debug):
def debug_print(to_check, debug):
if debug:
nowtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print("debug: " + nowtime + " " + string)
if isinstance(to_check, str):
print("debug: " + nowtime + " " + to_check)
else:
print("debug: " + nowtime)
print(to_check)


def pick_year_last_day(ds):
Expand Down
44 changes: 17 additions & 27 deletions pcmdi_metrics/variability_mode/lib/plot_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,15 @@


def plot_map(
mode, model, syear, eyear, season, eof_Nth, frac_Nth, output_file_name, debug=False
mode: str,
model: str,
syear: int,
eyear: int,
season: str,
eof_pattern: xr.DataArray,
eof_variance_fraction: float,
output_file_name: str,
debug=False,
):
"""Plot dive down map and save

Expand All @@ -35,9 +43,9 @@ def plot_map(
End year from analysis
season : str
season ("DJF", "MAM", "JJA", "SON", "monthly", or "yearly") that was used for analysis and will be shown in figure title
eof_Nth : cdms2.TransientVariable
eof_pattern : cdms2.TransientVariable
EOF pattern to plot, 2D cdms2 TransientVariable with lat/lon coordinates attached
frac_Nth : float
eof_variance_fraction : float
Fraction of explained variability (0 to 1), which will be shown in the figure as percentage after multiplying 100
output_file_name : str
Name of output image file (e.g., "output_file.png")
Expand All @@ -55,26 +63,14 @@ def plot_map(
sys.exit("Projection for " + mode + "is not defined.")

# title
if frac_Nth != -999:
if eof_variance_fraction != -999:
percentage = (
str(round(float(frac_Nth * 100.0), 1)) + "%"
str(round(float(eof_variance_fraction * 100.0), 1)) + "%"
) # % with one floating number
else:
percentage = ""

plot_title = (
mode
+ ": "
+ model
+ "\n"
+ str(syear)
+ "-"
+ str(eyear)
+ " "
+ season
+ " "
+ percentage
)
plot_title = f"{mode}: {model}\n{syear}-{eyear} {season} {percentage}"

debug_print(
"plot_map: projection, plot_title:" + projection + ", " + plot_title, debug
Expand Down Expand Up @@ -102,13 +98,7 @@ def plot_map(
central_longitude = 180

# Convert cdms variable to xarray
lon = get_longitude(eof_Nth)
lat = get_latitude(eof_Nth)
data = np.array(eof_Nth)
lon, lat = np.meshgrid(lon, lat)
data_array = xr.DataArray(
data, coords={"lon": lon[0, :], "lat": lat[:, 0]}, dims=("lat", "lon")
)
data_array = eof_pattern
data_array = data_array.where(data_array != 1e20, np.nan)

plot_map_cartopy(
Expand Down Expand Up @@ -164,8 +154,8 @@ def plot_map_cartopy(

debug_print("plot_map_cartopy starts", debug)

lon = data_array.lon
lat = data_array.lat
lon = get_longitude(data_array)
lat = get_latitude(data_array)

# Determine the extent based on the longitude range where data exists
lon_min = lon.min().item()
Expand Down
53 changes: 33 additions & 20 deletions pcmdi_metrics/variability_mode/variability_modes_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,12 +387,22 @@
intercept_obs,
) = linear_regression_on_globe_for_teleconnection(
pc_obs[season],
obs_timeseries_season[obs_var],
obs_timeseries_season,
obs_var,
stdv_pc_obs[season],
RmDomainMean,
EofScaling,
debug=debug,
)

obs_timeseries_season["eof_lr"] = eof_lr_obs_season
obs_timeseries_season["slope"] = slope_obs
obs_timeseries_season["intercept"] = intercept_obs

# Extract subdomain for plot
obs_timeseries_season_region = region_subset(
obs_timeseries_season, mode, regions_specs=regions_specs
)
eof_lr_obs[season] = eof_lr_obs_season
# - - - - - - - - - - - - - - - - - - - - - - - - -
# Record results
Expand All @@ -413,16 +423,14 @@
output_img_file_obs = os.path.join(
dir_paths["graphics"], output_filename_obs
)
eof_lr_obs_season_region = region_subset(
eof_lr_obs_season, mode, regions_specs
)

plot_map(
mode,
"[REF] " + obs_name,
osyear,
oeyear,
season,
eof_lr_obs_season_region,
obs_timeseries_season_region["eof_lr"],
frac_obs[season],
output_img_file_obs,
debug=debug,
Expand All @@ -434,7 +442,7 @@
oeyear,
season,
# eof_lr_obs[season](longitude=(lon1_global, lon2_global)),
eof_lr_obs[season],
eof_lr_obs_season,
frac_obs[season],
output_img_file_obs + "_teleconnection",
debug=debug,
Expand Down Expand Up @@ -663,36 +671,39 @@
intercept_cbf,
) = linear_regression_on_globe_for_teleconnection(
cbf_pc,
model_timeseries_season[var],
model_timeseries_season,
var,
stdv_cbf_pc,
# cbf_pc, model_timeseries_season_regrid, stdv_cbf_pc,
RmDomainMean,
EofScaling,
debug=debug,
)

model_timeseries_season["eof_lr_cbf"] = eof_lr_cbf
model_timeseries_season["slope_cbf"] = slope_cbf
model_timeseries_season["intercept_cbf"] = intercept_cbf

# Extract subdomain for statistics
# eof_lr_cbf_subdomain = eof_lr_cbf(region_subdomain)
eof_lr_cbf_subdomain = region_subset(
eof_lr_cbf, mode, regions_specs
model_timeseries_season_subdomain = region_subset(
model_timeseries_season,
mode,
regions_specs=regions_specs,
)

# Calculate fraction of variance explained by cbf pc
# Calculate fraction of variance explained by cbf pc (native grid)
frac_cbf = gain_pcs_fraction(
# model_timeseries_season_regrid_subdomain, # regridded model anomaly space
model_timeseries_season_subdomain[
var
], # native grid model anomaly space
eof_lr_cbf_subdomain,
model_timeseries_season_subdomain[var],
model_timeseries_season_subdomain["eof_lr_cbf"],
cbf_pc / stdv_cbf_pc,
debug=debug,
)

# SENSITIVITY TEST ---
# Calculate fraction of variance explained by cbf pc (on regrid domain)
# Calculate fraction of variance explained by cbf pc (regrid domain)
frac_cbf_regrid = gain_pcs_fraction(
model_timeseries_season_regrid_subdomain[var],
eof_lr_cbf_subdomain,
model_timeseries_season_subdomain["eof_lr_cbf"],
cbf_pc / stdv_cbf_pc,
debug=debug,
)
Expand All @@ -705,7 +716,7 @@
dict_head, eof_lr_cbf = calc_stats_save_dict(
mode,
dict_head,
eof_lr_cbf_subdomain,
model_timeseries_season_subdomain["eof_lr_cbf"],
eof_lr_cbf,
cbf_pc,
stdv_cbf_pc,
Expand Down Expand Up @@ -750,7 +761,7 @@
msyear,
meyear,
season,
eof_lr_cbf_subdomain,
model_timeseries_season_subdomain["eof_lr_cbf"],
frac_cbf,
output_img_file + "_cbf",
debug=debug,
Expand Down Expand Up @@ -846,6 +857,7 @@
# Metrics results -- statistics to JSON
if obs_compare:
dict_head, eof_lr = calc_stats_save_dict(
mode,
dict_head,
eof,
eof_lr,
Expand All @@ -862,6 +874,7 @@
)
else:
dict_head, eof_lr = calc_stats_save_dict(
mode,
dict_head,
eof,
eof_lr,
Expand Down
Loading