Skip to content

Commit

Permalink
Making progress.
Browse files Browse the repository at this point in the history
  • Loading branch information
aaschwanden committed Nov 25, 2024
1 parent 0de5636 commit c168bb6
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 16 deletions.
30 changes: 16 additions & 14 deletions analysis/analyze_scalar.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,6 @@ def run_delta_analysis(
filter_vars: List[str],
group_dim: str = "basin",
iter_dim: str = "time",
ensemble: str = "RAGIS",
notebook: bool = False,
) -> xr.Dataset:
"""
Expand All @@ -317,8 +316,6 @@ def run_delta_analysis(
DataFrame containing ensemble information, with a 'basin' column to group by.
filter_vars : List[str]
List of variables to filter by for sensitivity analysis.
ensemble_id : str, optional
The ensemble ID to select from the dataset, by default "RAGIS".
Returns
-------
Expand Down Expand Up @@ -354,10 +351,10 @@ def run_delta_analysis(
f" ...sensitivity indices for basin {gdim} filtered by {filter_var} ",
)

responses = ds.sel(basin=gdim, ensemble_id=ensemble)[filter_var]
responses = ds.sel({"basin": gdim})[filter_var]
responses_scattered = client.scatter(
[
responses.isel(time=k).to_numpy()
responses.isel({"time": k}).to_numpy()
for k in range(len(responses[iter_dim]))
]
)
Expand Down Expand Up @@ -522,7 +519,7 @@ def plot_obs_sims(

y_min, y_max = axs[1].get_ylim()
scaler = y_min + (y_max - y_min) * 0.05
obs_filtered = obs.sel(time=slice(f"{filter_range[0]}", f"{filter_range[-1]}"))
obs_filtered = obs.sel({"time": slice(f"{filter_range[0]}", f"{filter_range[-1]}")})
filter_range_ds = obs_filtered[mass_cumulative_varname]
filter_range_ds *= 0
filter_range_ds += scaler
Expand Down Expand Up @@ -946,6 +943,7 @@ def plot_obs_sims_3(
params = [
"calving.vonmises_calving.sigma_max",
"calving.rate_scaling.file",
"geometry.front_retreat.prescribed.file",
"ocean.th.gamma_T",
"surface.given.file",
"ocean.th.file",
Expand Down Expand Up @@ -994,7 +992,10 @@ def plot_obs_sims_3(
# fig.savefig("grounding_line_flux_unfiltered.pdf")

filtered_ds, outliers_ds = filter_outliers(
simulated_ds, outlier_range=outlier_range, outlier_variable=outlier_variable
simulated_ds,
outlier_range=outlier_range,
outlier_variable=outlier_variable,
subset={"basin": "GIS"},
)

# plot_outliers(
Expand Down Expand Up @@ -1053,9 +1054,9 @@ def plot_obs_sims_3(
filtered_all = {}
prior_posterior_list = []
for obs_mean_var, obs_std_var, sim_var in zip(
list(flux_vars.values())[:2],
list(flux_uncertainty_vars.values())[:2],
list(flux_vars.values())[:2],
list(flux_vars.values())[1:2],
list(flux_uncertainty_vars.values())[1:2],
list(flux_vars.values())[1:2],
):
print(f"Importance sampling using {obs_mean_var}")
f = importance_sampling(
Expand Down Expand Up @@ -1112,8 +1113,8 @@ def plot_obs_sims_3(
result = Parallel(n_jobs=options.n_jobs)(
delayed(plot_obs_sims)(
observed_mankoff_basins_resampled_ds.sel(basin=basin),
sim_prior.sel(basin=basin, ensemble_id=ensemble),
sim_posterior.sel(basin=basin, ensemble_id=ensemble),
sim_prior.sel(basin=basin),
sim_posterior.sel(basin=basin),
config=ragis_config,
filtering_var=obs_mean_var,
filter_range=[filter_start_year, filter_end_year],
Expand All @@ -1132,6 +1133,7 @@ def plot_obs_sims_3(
"surface.given.file": [prp.simplify_path, prp.simplify_climate],
"ocean.th.file": [prp.simplify_path, prp.simplify_ocean],
"calving.rate_scaling.file": [prp.simplify_path, prp.simplify_calving],
"geometry.front_retreat.prescribed.file": [prp.simplify_retreat],
}

# Apply the functions to the corresponding columns
Expand All @@ -1145,8 +1147,8 @@ def plot_obs_sims_3(
n_params = len(params_short_dict)
plt.rcParams["font.size"] = 4
fig, axs = plt.subplots(
5,
3,
4,
4,
sharey=True,
figsize=[6.2, 6.2],
)
Expand Down
2 changes: 1 addition & 1 deletion analysis/compute_basins_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@
basin_sums = (
xr.concat(client.gather(futures), dim="basin")
.drop_vars(["mapping", "spatial_ref"])
.sortby(["basin", "time"])
.sortby(["basin", "pism_config_axis", "time"])
)
if cf:
basin_sums["basin"] = basin_sums["basin"].astype(f"S{n_basins}")
Expand Down
1 change: 1 addition & 0 deletions pism_ragis/data/ragis_config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

'calving.vonmises_calving.sigma_max' = '$\sigma_{\mathrm{max}}$ (Pa)'
'calving.rate_scaling.file' = 'Calving'
'geometry.front_retreat.prescribed.file' = 'Retreat'
'ocean.th.gamma_T' = '$\gamma$'
'surface.given.file' = 'Climate'
'ocean.th.file' = 'Ocean'
Expand Down
44 changes: 43 additions & 1 deletion pism_ragis/processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,13 @@ def drop_nonnumeric_vars(self, errors: str = "ignore") -> xr.Dataset:
return self._obj.drop_vars(nonnumeric_vars, errors=errors)


def sort_basin(ds):
"""
Sort preprocessing.
"""
return ds.sortby(["basin", "pism_config_axis"])


@timeit
def load_ensemble(
filenames: List[Union[Path, str]], parallel: bool = True, engine: str = "netcdf4"
Expand All @@ -600,7 +607,7 @@ def load_ensemble(
ds = xr.open_mfdataset(
filenames,
parallel=parallel,
chunks={"exp_id": -1, "pism_config_axis": -1},
preprocess=sort_basin,
engine=engine,
).drop_vars(["spatial_ref", "mapping"], errors="ignore")
print("Done.")
Expand Down Expand Up @@ -793,6 +800,41 @@ def simplify_climate(my_str: str) -> str:
return "HIRHAM"


def simplify_retreat(my_str: str) -> str:
"""
Simplify climate string.
This function simplifies the input climate string by returning a standardized
climate model name based on the presence of specific substrings.
Parameters
----------
my_str : str
The input climate string.
Returns
-------
str
The standardized climate model name based on the input string.
Examples
--------
>>> simplify_climate("MAR_2020")
'MAR'
>>> simplify_climate("RACMO_2020")
'RACMO'
>>> simplify_climate("Other_2020")
'HIRHAM'
"""

if my_str in ("false", ""):
short_str = "Free Running"
else:
short_str = "Prescribed Retreat"

return short_str


def simplify_ocean(my_str: str) -> str:
"""
Simplify ocean string.
Expand Down

0 comments on commit c168bb6

Please sign in to comment.