Skip to content

Commit f32f762

Browse files
authored
Enable overriding params file with kwargs in execute_pyciam (#17)
* enable override of params file in execute_pyciam * ruff formatting
1 parent fe955ba commit f32f762

File tree

9 files changed

+32
-24
lines changed

9 files changed

+32
-24
lines changed

README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,6 @@ pyCIAM contains only a handful of public functions that a user will want to empl
5656
* `execute_pyciam`: This is the end-to-end function that represents the most likely entrypoint for users. All other public functions are called by this one.
5757
* `create_surge_lookup`: Creates a lookup table that can be leveraged to build a 2D linear spline function for calculating damages from extreme sea levels. This can drastically reduce computational expense required for simulation on large ensembles of sea level rise trajectories.
5858
* `load_ciam_inputs`: An I/O function to load SLIIDERS-like input data, storm surge damage lookup table (if specified), model parameters, and process/format these data for inclusion in pyCIAM.
59-
* `load_diaz_inputs`: A similar function to load a preprocessed SLIIDERS-like input dataset that is generated from the same input data used in Diaz 2016. This is used to generate comparisons to the Diaz 2016 results within Depsky et al. 2023.
6059
* `calc_costs`: This is the main computation engine in pyCIAM. It computes costs for all cost types, regions, years, socioeconomic and SLR trajectories, and adaptation case. It does *not* compute the optimal adaptation case, which must be computed afterward, for reasons described below.
6160
* `select_optimal_case`: This function calculates the optimal adaptation choice for a given region and returns the associated costs and NPV.
6261

notebooks/data-processing/create-diaz-pyCIAM-inputs.ipynb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -304,8 +304,7 @@
304304
" {\n",
305305
" \"long_name\": \"Surge Damage Coefficients\",\n",
306306
" \"description\": (\n",
307-
" \"Coefficients used in the original Diaz 2016 paper to estimate surge \"\n",
308-
" \"damage\"\n",
307+
" \"Coefficients used in the original Diaz 2016 paper to estimate surge damage\"\n",
309308
" ),\n",
310309
" }\n",
311310
")\n",

notebooks/data-processing/slr/sweet.ipynb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
},
1414
{
1515
"cell_type": "code",
16-
"execution_count": 2,
16+
"execution_count": null,
1717
"metadata": {},
1818
"outputs": [
1919
{
@@ -32,7 +32,7 @@
3232
"import xarray as xr\n",
3333
"from shared import open_dataarray, open_dataset, open_zarr, save\n",
3434
"\n",
35-
"from pyCIAM import spherical_nearest_neighbor as snn"
35+
"from pyCIAM.utils import spherical_nearest_neighbor as snn"
3636
]
3737
},
3838
{

notebooks/models/fit-movefactor.ipynb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1279,7 +1279,7 @@
12791279
" min_R_noadapt=this_refA.drop(\"case\"),\n",
12801280
" return_year0_hts=False,\n",
12811281
" return_RH_heights=True,\n",
1282-
" **get_model_kwargs(True)\n",
1282+
" **get_model_kwargs(True),\n",
12831283
")\n",
12841284
"\n",
12851285
"hts = RH_heights.sel(case=SOLVCASES).isel(case=this_refA.case)\n",

notebooks/models/run-pyCIAM-diaz2016.ipynb

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,6 @@
3131
"metadata": {},
3232
"outputs": [],
3333
"source": [
34-
"from pathlib import Path\n",
35-
"\n",
3634
"import distributed as dd\n",
3735
"import pandas as pd\n",
3836
"from pyCIAM.run import execute_pyciam\n",

notebooks/post-processing/pyCIAM-results-figures.ipynb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4524,18 +4524,18 @@
45244524
"seg_adm_pop_2050 = inputs.pop_2019.isel(elev=pyCIAM_elevs).sum(\n",
45254525
" \"elev\"\n",
45264526
") * inputs.pop_scale.sel(country=inputs.seg_country, year=2050)\n",
4527-
"print(f'SSP Pops in 2050 (bn): {(seg_adm_pop_2050.sum(\"seg_adm\") / 1e9).values}')\n",
4527+
"print(f\"SSP Pops in 2050 (bn): {(seg_adm_pop_2050.sum('seg_adm') / 1e9).values}\")\n",
45284528
"\n",
45294529
"seg_adm_K_2050 = inputs.K_2019.isel(elev=pyCIAM_elevs).sum(\"elev\") * inputs.K_scale.sel(\n",
45304530
" country=inputs.seg_country, year=2050\n",
45314531
")\n",
45324532
"print(\n",
45334533
" \"(IIASA) SSP Ks in 2050 ($Tn): \"\n",
4534-
" f'{(seg_adm_K_2050.sel(iam=\"IIASA\").sum(\"seg_adm\") / 1e12).values}'\n",
4534+
" f\"{(seg_adm_K_2050.sel(iam='IIASA').sum('seg_adm') / 1e12).values}\"\n",
45354535
")\n",
45364536
"print(\n",
45374537
" \"(OECD) SSP Ks in 2050 ($Tn): \"\n",
4538-
" f'{(seg_adm_K_2050.sel(iam=\"OECD\").sum(\"seg_adm\") / 1e12).values}'\n",
4538+
" f\"{(seg_adm_K_2050.sel(iam='OECD').sum('seg_adm') / 1e12).values}\"\n",
45394539
")"
45404540
]
45414541
},
@@ -4867,7 +4867,7 @@
48674867
" linewidth=0,\n",
48684868
" alpha=0.8,\n",
48694869
" zorder=10,\n",
4870-
" **kwargs\n",
4870+
" **kwargs,\n",
48714871
" )\n",
48724872
"\n",
48734873
" if filename is not None:\n",

pyCIAM/__init__.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
from pyCIAM.io import load_ciam_inputs, load_diaz_inputs
1+
from pyCIAM.io import load_ciam_inputs
22
from pyCIAM.run import calc_costs, execute_pyciam, select_optimal_case
33
from pyCIAM.surge.lookup import create_surge_lookup
4-
from pyCIAM.utils import spherical_nearest_neighbor
4+
5+
__all__ = [
6+
"load_ciam_inputs",
7+
"calc_costs",
8+
"execute_pyciam",
9+
"select_optimal_case",
10+
"create_surge_lookup",
11+
]

pyCIAM/io.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
"""
1010

1111
import tempfile
12-
from collections.abc import Iterable
1312
from io import BytesIO
1413
from pathlib import Path
1514
from zipfile import ZipFile
@@ -548,9 +547,9 @@ def save_to_zarr_region(ds_in, store, already_aligned=False, storage_options={})
548547
n_valid = len(valid_ixs)
549548
st = valid_ixs[0]
550549
end = valid_ixs[-1]
551-
assert (
552-
end - st == n_valid - 1
553-
), f"Indices are not continuous along dimension {r}"
550+
assert end - st == n_valid - 1, (
551+
f"Indices are not continuous along dimension {r}"
552+
)
554553
regions[r] = slice(st, end + 1)
555554

556555
# align coords
@@ -692,7 +691,7 @@ def load_ciam_inputs(
692691
seg_vals,
693692
# dropping the "refA_scenario_selectors" b/c this doesn't need to be added to
694693
# the input dataset object
695-
constants=params[params.map(type) != dict].to_dict(),
694+
constants=params[params.map(type) != dict].to_dict(), # noqa: E721
696695
seg_var=seg_var,
697696
selectors=selectors,
698697
storage_options=storage_options,
@@ -791,7 +790,7 @@ def load_diaz_inputs(
791790
inputs = prep_sliiders(
792791
input_store,
793792
seg_vals,
794-
constants=params[params.map(type) != dict].to_dict(),
793+
constants=params[params.map(type) != dict].to_dict(), # noqa: E721
795794
seg_var="seg",
796795
calc_popdens_with_wetland_area=False,
797796
storage_options=storage_options,
@@ -861,7 +860,7 @@ def download_and_extract_partial_zip(lpath, url, zip_glob, n_retries=5):
861860
if not fl.is_file():
862861
retries = 0
863862
while retries < n_retries:
864-
print(f"...Downloading {fl.name} (attempt {retries+1}/{n_retries})")
863+
print(f"...Downloading {fl.name} (attempt {retries + 1}/{n_retries})")
865864
try:
866865
data = z.cat_file(fr)
867866
break

pyCIAM/run.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import pandas as pd
1616
import xarray as xr
1717
from cloudpathlib import AnyPath, CloudPath
18-
from distributed import Client, wait
18+
from distributed import Client
1919
from rhg_compute_tools.xarray import dataarray_from_delayed
2020

2121
from pyCIAM.constants import CASE_DICT, CASES, COSTTYPES, PLIST, RLIST, SOLVCASES
@@ -951,6 +951,7 @@ def execute_pyciam(
951951
diaz_config=False,
952952
dask_client_func=Client,
953953
storage_options=None,
954+
params_override={},
954955
**model_kwargs,
955956
):
956957
"""Execute the full pyCIAM model. The following inputs are assumed:
@@ -1082,6 +1083,8 @@ def execute_pyciam(
10821083
reflected in `storage_options["token"]`. Other cloud storage providers will have
10831084
different authentication methods and have not yet been tested with this
10841085
function.
1086+
params_override : dict, default {}
1087+
Used to override params specified in `params_path`
10851088
**model_kwargs
10861089
Passed directly to :py:func:`pyCIAM.calc_costs`
10871090
"""
@@ -1115,6 +1118,7 @@ def execute_pyciam(
11151118

11161119
# read parameters
11171120
params = pd.read_json(params_path)["values"]
1121+
params.update(params_override)
11181122

11191123
# determine whether to check for finished jobs
11201124
if output_path is None:
@@ -1276,6 +1280,10 @@ def execute_pyciam(
12761280
compute=False,
12771281
mode="w",
12781282
storage_options=storage_options,
1283+
encoding={
1284+
"costs": {"fill_value": "NaN"},
1285+
"optimal_case": {"fill_value": 255},
1286+
},
12791287
)
12801288

12811289
####################################################
@@ -1469,8 +1477,6 @@ def execute_pyciam(
14691477
.costs.notnull()
14701478
.all()
14711479
)
1472-
client.cluster.close()
1473-
client.close()
14741480
if remove_tmpfile:
14751481
if isinstance(tmp_output_path, CloudPath):
14761482
tmp_output_path.rmtree()

0 commit comments

Comments
 (0)