jcm 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jcm/__init__.py +1 -0
- jcm/config/config.yaml +11 -0
- jcm/config/hydra/help/custom_help.yaml +32 -0
- jcm/config/model/default.yaml +4 -0
- jcm/constants.py +5 -0
- jcm/data/__init__.py +0 -0
- jcm/data/bc/__init__.py +0 -0
- jcm/data/bc/compile.py +88 -0
- jcm/data/bc/compile_test.py +9 -0
- jcm/data/bc/interpolate.py +144 -0
- jcm/data/bc/interpolate_test.py +9 -0
- jcm/data/bc/t30/anom/sea_surface_temperature_anomaly.nc +0 -0
- jcm/data/bc/t30/clim/forcing.nc +0 -0
- jcm/data/bc/t30/clim/land.nc +0 -0
- jcm/data/bc/t30/clim/sea_ice.nc +0 -0
- jcm/data/bc/t30/clim/sea_surface_temperature.nc +0 -0
- jcm/data/bc/t30/clim/snow.nc +0 -0
- jcm/data/bc/t30/clim/soil.nc +0 -0
- jcm/data/bc/t30/clim/surface.nc +0 -0
- jcm/data/bc/t30/clim/terrain.nc +0 -0
- jcm/data/test/cbmf.npy +0 -0
- jcm/data/test/dfqa.npy +0 -0
- jcm/data/test/dfse.npy +0 -0
- jcm/data/test/iptop.npy +0 -0
- jcm/data/test/precnv.npy +0 -0
- jcm/data/test/qdif.npy +0 -0
- jcm/data/test/t30/default_statistics.nc +0 -0
- jcm/data/test/t30/generate_default_stats.py +44 -0
- jcm/date.py +76 -0
- jcm/date_test.py +40 -0
- jcm/diffusion.py +27 -0
- jcm/dynamics_units_table.csv +7 -0
- jcm/forcing.py +152 -0
- jcm/geometry.py +253 -0
- jcm/geometry_test.py +126 -0
- jcm/main.py +38 -0
- jcm/model.py +538 -0
- jcm/model_test.py +300 -0
- jcm/physics/__init__.py +0 -0
- jcm/physics/held_suarez/__init__.py +0 -0
- jcm/physics/held_suarez/held_suarez_physics.py +103 -0
- jcm/physics/held_suarez/held_suarez_test.py +40 -0
- jcm/physics/speedy/__init__.py +0 -0
- jcm/physics/speedy/convection.py +236 -0
- jcm/physics/speedy/convection_test.py +292 -0
- jcm/physics/speedy/forcing.py +39 -0
- jcm/physics/speedy/humidity.py +101 -0
- jcm/physics/speedy/humidity_test.py +281 -0
- jcm/physics/speedy/large_scale_condensation.py +85 -0
- jcm/physics/speedy/large_scale_condensation_test.py +141 -0
- jcm/physics/speedy/longwave_radiation.py +226 -0
- jcm/physics/speedy/longwave_radiation_test.py +286 -0
- jcm/physics/speedy/orographic_correction.py +293 -0
- jcm/physics/speedy/orographic_correction_test.py +605 -0
- jcm/physics/speedy/params.py +294 -0
- jcm/physics/speedy/physical_constants.py +50 -0
- jcm/physics/speedy/physics_data.py +525 -0
- jcm/physics/speedy/shortwave_radiation.py +456 -0
- jcm/physics/speedy/shortwave_radiation_test.py +574 -0
- jcm/physics/speedy/speedy_physics.py +135 -0
- jcm/physics/speedy/speedy_physics_test.py +22 -0
- jcm/physics/speedy/surface_flux.py +304 -0
- jcm/physics/speedy/surface_flux_test.py +611 -0
- jcm/physics/speedy/test_utils.py +17 -0
- jcm/physics/speedy/units_table.csv +74 -0
- jcm/physics/speedy/vertical_diffusion.py +137 -0
- jcm/physics/speedy/vertical_diffusion_test.py +106 -0
- jcm/physics_interface.py +415 -0
- jcm/physics_interface_test.py +63 -0
- jcm/utils.py +146 -0
- jcm-1.0.0.dist-info/METADATA +23 -0
- jcm-1.0.0.dist-info/RECORD +75 -0
- jcm-1.0.0.dist-info/WHEEL +5 -0
- jcm-1.0.0.dist-info/licenses/LICENSE +201 -0
- jcm-1.0.0.dist-info/top_level.txt +1 -0
jcm/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "1.0.0"
|
jcm/config/config.yaml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
app_name: JCM
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
template: |
|
|
5
|
+
|
|
6
|
+
${hydra.help.app_name}:
|
|
7
|
+
----
|
|
8
|
+
Runs atmospheric simulations using configurable parameters.
|
|
9
|
+
|
|
10
|
+
Usage Examples:
|
|
11
|
+
---------------
|
|
12
|
+
Basic run:
|
|
13
|
+
python main.py
|
|
14
|
+
python main.py model.time_step=20
|
|
15
|
+
|
|
16
|
+
Parameter sweep:
|
|
17
|
+
python main.py -m model.time_step=10,20,30
|
|
18
|
+
python main.py -m model.time_step=10,20 model.layers=4,8
|
|
19
|
+
|
|
20
|
+
Available Parameters:
|
|
21
|
+
---------------------
|
|
22
|
+
time_step: Model time step in minutes (default: 10)
|
|
23
|
+
save_interval: Save interval in days (default: 10)
|
|
24
|
+
total_time: Total simulation time in days (default: 10)
|
|
25
|
+
layers: Number of vertical layers (default: 8)
|
|
26
|
+
|
|
27
|
+
Output:
|
|
28
|
+
-------
|
|
29
|
+
Creates in ./outputs:
|
|
30
|
+
- model_state.nc: Model predictions
|
|
31
|
+
- .hydra/: Run configuration
|
|
32
|
+
- run.log: Execution log
|
jcm/constants.py
ADDED
jcm/data/__init__.py
ADDED
|
File without changes
|
jcm/data/bc/__init__.py
ADDED
|
File without changes
|
jcm/data/bc/compile.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import xarray as xr
|
|
2
|
+
import sys
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
import numpy as np
|
|
5
|
+
from jcm.physics.speedy.physical_constants import sd2sc, swcap, swwil
|
|
6
|
+
|
|
7
|
+
# Set the input directory path
|
|
8
|
+
input_dir = Path(__file__).parent / 't30/clim'
|
|
9
|
+
output_file, terrain_file = Path(__file__).parent / 't30/clim/forcing.nc', Path(__file__).parent / 't30/clim/terrain.nc'
|
|
10
|
+
file_names = ['land.nc', 'sea_ice.nc', 'sea_surface_temperature.nc', 'snow.nc', 'soil.nc', 'surface.nc']
|
|
11
|
+
|
|
12
|
+
def process_forcing(ds):
|
|
13
|
+
"""Convert compiled speedy.f90 boundary conditions to format expected by jcm.
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
ds (xarray.Dataset): Dataset containing boundary conditions.
|
|
17
|
+
|
|
18
|
+
"""
|
|
19
|
+
# Reorder coordinates to match jcm expectations
|
|
20
|
+
ds = ds.sortby('lat', ascending=True)
|
|
21
|
+
for var in ds.data_vars:
|
|
22
|
+
if 'time' in ds[var].dims:
|
|
23
|
+
ds[var] = ds[var].transpose('lon', 'lat', 'time')
|
|
24
|
+
else:
|
|
25
|
+
ds[var] = ds[var].transpose('lon', 'lat')
|
|
26
|
+
|
|
27
|
+
# Fill nan temperatures with mean, other nans with 0
|
|
28
|
+
for var in ds.data_vars:
|
|
29
|
+
arr = ds[var]
|
|
30
|
+
mask = arr == 9.96921e36
|
|
31
|
+
fill_val = arr.where(~mask).mean() if var in ['stl', 'sst'] else 0.
|
|
32
|
+
ds[var] = arr.where(~mask, fill_val)
|
|
33
|
+
|
|
34
|
+
# Compute soil moisture variable used by jcm
|
|
35
|
+
def compute_soilw_am(veg_high, veg_low, swl1, swl2):
|
|
36
|
+
assert np.all(0.0 <= veg_high) and np.all(veg_high <= 1.0)
|
|
37
|
+
assert np.all(0.0 <= veg_low) and np.all(veg_low <= 1.0)
|
|
38
|
+
veg = veg_high + 0.8 * veg_low
|
|
39
|
+
idep2 = 3
|
|
40
|
+
rsw = 1.0 / (swcap + idep2 * (swcap - swwil))
|
|
41
|
+
swl2_raw = veg[:, :, np.newaxis] * idep2 * (swl2 - swwil)
|
|
42
|
+
soilw_raw = rsw * (swl1 + np.maximum(0.0, swl2_raw))
|
|
43
|
+
return np.minimum(1.0, soilw_raw)
|
|
44
|
+
|
|
45
|
+
soilw_am = compute_soilw_am(ds.vegh.values, ds.vegl.values, ds.swl1.values, ds.swl2.values)
|
|
46
|
+
ds['soilw_am'] = xr.DataArray(soilw_am, dims=ds['swl1'].dims, coords=ds['swl1'].coords)
|
|
47
|
+
|
|
48
|
+
ds['snowc'] = ds['snowd'] / sd2sc # Convert snow depth to snow cover
|
|
49
|
+
|
|
50
|
+
ds_terrain = ds[['lsm', 'orog']]
|
|
51
|
+
return ds.drop_vars({'swl1', 'swl2', 'swl3', 'vegh', 'vegl', 'snowd', 'orog', 'lsm'}), ds_terrain
|
|
52
|
+
|
|
53
|
+
def main(argv=None):
|
|
54
|
+
"""Run main entrypoint for compile CLI and for importable use.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
argv (list|None): list of command-line args (not including program name).
|
|
58
|
+
If None, uses sys.argv[1:].
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
int: exit code (0 = success)
|
|
62
|
+
|
|
63
|
+
"""
|
|
64
|
+
if argv is None:
|
|
65
|
+
argv = sys.argv[1:]
|
|
66
|
+
|
|
67
|
+
try:
|
|
68
|
+
print("Compiling dataset...")
|
|
69
|
+
with xr.open_mfdataset([input_dir / fname for fname in file_names], combine='by_coords') as merged_ds:
|
|
70
|
+
print("Processing dataset...")
|
|
71
|
+
processed_ds, ds_terrain = process_forcing(merged_ds)
|
|
72
|
+
|
|
73
|
+
print(f"Saving processed dataset to {output_file}")
|
|
74
|
+
processed_ds.to_netcdf(output_file)
|
|
75
|
+
|
|
76
|
+
print(f"Saving terrain to {terrain_file}")
|
|
77
|
+
ds_terrain.to_netcdf(terrain_file)
|
|
78
|
+
|
|
79
|
+
print("Done!")
|
|
80
|
+
return 0
|
|
81
|
+
|
|
82
|
+
except Exception:
|
|
83
|
+
import traceback
|
|
84
|
+
traceback.print_exc()
|
|
85
|
+
return 1
|
|
86
|
+
|
|
87
|
+
if __name__ == "__main__":
|
|
88
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import xarray as xr
|
|
2
|
+
import numpy as np
|
|
3
|
+
import pandas as pd
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import argparse
|
|
6
|
+
from jcm.utils import VALID_TRUNCATIONS, get_coords
|
|
7
|
+
|
|
8
|
+
def interpolate_to_daily(ds_monthly: xr.Dataset) -> xr.Dataset:
|
|
9
|
+
# validate that time coordinate is monthly
|
|
10
|
+
time = pd.DatetimeIndex(ds_monthly["time"].values)
|
|
11
|
+
if len(time) != 12:
|
|
12
|
+
raise ValueError(f"'time' has {len(time)} entries, expected 12 monthly timestamps.")
|
|
13
|
+
elif pd.infer_freq(time) not in ("MS", "M"):
|
|
14
|
+
raise ValueError("Timestamps do not have a monthly frequency")
|
|
15
|
+
|
|
16
|
+
time_vars = [var for var in ds_monthly.data_vars if 'time' in ds_monthly[var].dims]
|
|
17
|
+
non_time_vars = [var for var in ds_monthly.data_vars if 'time' not in ds_monthly[var].dims]
|
|
18
|
+
|
|
19
|
+
# pad monthly data with dec/jan of adjacent years
|
|
20
|
+
pad_n = 1
|
|
21
|
+
previous_year_padding = [ds_monthly[time_vars].isel(time=i) for i in range(12 - pad_n, 12)]
|
|
22
|
+
next_year_padding = [ds_monthly[time_vars].isel(time=i) for i in range(pad_n)]
|
|
23
|
+
extended_monthly_time_vars = xr.concat(previous_year_padding + [ds_monthly[time_vars]] + next_year_padding, dim='time')
|
|
24
|
+
extended_time = pd.date_range(start=f'1980-{13-pad_n:02}-01', end=f'1982-{pad_n:02}-01', freq='MS')
|
|
25
|
+
extended_monthly_time_vars['time'] = extended_time
|
|
26
|
+
|
|
27
|
+
daily_time_vars = extended_monthly_time_vars.resample(time='1D').interpolate('linear')
|
|
28
|
+
daily_time_vars = daily_time_vars.sel(time=slice('1981-01-01', '1981-12-31'))
|
|
29
|
+
return xr.merge([daily_time_vars, ds_monthly[non_time_vars]])
|
|
30
|
+
|
|
31
|
+
def _upsample_ds(ds: xr.Dataset, target_resolution: int) -> xr.Dataset:
|
|
32
|
+
grid = get_coords(spectral_truncation=target_resolution).horizontal
|
|
33
|
+
|
|
34
|
+
# Pad latitude with extra rows at poles so data can be interpolated to higher latitudes than exist in T30 grid
|
|
35
|
+
south_pole = ds.isel(lat=0).mean(dim="lon", keep_attrs=True)
|
|
36
|
+
north_pole = ds.isel(lat=-1).mean(dim="lon", keep_attrs=True)
|
|
37
|
+
ds_pad = xr.concat([
|
|
38
|
+
south_pole.expand_dims(lon=ds.lon, lat=[-90]).transpose(*ds.dims),
|
|
39
|
+
ds,
|
|
40
|
+
north_pole.expand_dims(lon=ds.lon, lat=[90]).transpose(*ds.dims),
|
|
41
|
+
], dim="lat")
|
|
42
|
+
|
|
43
|
+
# Pad longitude to enforce periodicity
|
|
44
|
+
lon = ds_pad['lon'].values
|
|
45
|
+
ds_pad = xr.concat([
|
|
46
|
+
ds_pad.assign_coords(lon=lon - 360),
|
|
47
|
+
ds_pad,
|
|
48
|
+
ds_pad.assign_coords(lon=lon + 360)
|
|
49
|
+
], dim='lon')
|
|
50
|
+
|
|
51
|
+
# Interpolate to new grid
|
|
52
|
+
ds_interp = ds_pad.interp(
|
|
53
|
+
lat=grid.latitudes * 180 / np.pi,
|
|
54
|
+
lon=grid.longitudes * 180 / np.pi,
|
|
55
|
+
method="linear"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
return ds_interp
|
|
59
|
+
|
|
60
|
+
def upsample_forcings_ds(ds: xr.Dataset, target_resolution: int) -> xr.Dataset:
|
|
61
|
+
ds_interp = _upsample_ds(ds, target_resolution)
|
|
62
|
+
for v in ds_interp.data_vars:
|
|
63
|
+
ds_interp[v] = ds_interp[v].clip(min=0.)
|
|
64
|
+
for v in ['icec', 'soilw_am', 'alb']:
|
|
65
|
+
ds_interp[v] = ds_interp[v].clip(max=1.)
|
|
66
|
+
return ds_interp
|
|
67
|
+
|
|
68
|
+
def upsample_terrain_ds(ds: xr.Dataset, target_resolution: int) -> xr.Dataset:
|
|
69
|
+
ds_interp = _upsample_ds(ds, target_resolution)
|
|
70
|
+
ds_interp['lsm'] = ds_interp['lsm'].clip(0.0, 1.0)
|
|
71
|
+
# not clamping orog to avoid erasing real areas below sea level, but this might allow bad extrapolated values at the extreme latitudes
|
|
72
|
+
return ds_interp
|
|
73
|
+
|
|
74
|
+
def interpolate(target_resolution):
|
|
75
|
+
cwd = Path(__file__).resolve().parent
|
|
76
|
+
forcing_original_file = cwd / "t30/clim/forcing.nc"
|
|
77
|
+
forcing_daily_file = cwd / "t30/clim/forcing_daily.nc"
|
|
78
|
+
forcing_upscaled_file = cwd / f"forcing_t{target_resolution}.nc"
|
|
79
|
+
|
|
80
|
+
if forcing_upscaled_file.exists():
|
|
81
|
+
print(f"{forcing_upscaled_file.name} already exists.")
|
|
82
|
+
|
|
83
|
+
else:
|
|
84
|
+
if not forcing_daily_file.exists():
|
|
85
|
+
print(f"Interpolating {forcing_original_file.name} to daily resolution...")
|
|
86
|
+
with xr.open_dataset(forcing_original_file) as ds_monthly:
|
|
87
|
+
ds_daily = interpolate_to_daily(ds_monthly)
|
|
88
|
+
ds_daily.to_netcdf(forcing_daily_file)
|
|
89
|
+
print(f"Generated {forcing_daily_file.name}")
|
|
90
|
+
|
|
91
|
+
print(f"Interpolating {forcing_daily_file.name} to T{target_resolution} resolution...")
|
|
92
|
+
with xr.open_dataset(forcing_daily_file) as ds_forcing:
|
|
93
|
+
ds_forcing_interp = upsample_forcings_ds(ds_forcing, target_resolution)
|
|
94
|
+
ds_forcing_interp.to_netcdf(forcing_upscaled_file)
|
|
95
|
+
print(f"Generated {forcing_upscaled_file.name}")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
terrain_original_file = cwd / "t30/clim/terrain.nc"
|
|
99
|
+
terrain_upscaled_file = cwd / f"terrain_t{target_resolution}.nc"
|
|
100
|
+
|
|
101
|
+
if terrain_upscaled_file.exists():
|
|
102
|
+
print(f"{terrain_upscaled_file.name} already exists.")
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
print(f"Interpolating {terrain_original_file.name} to T{target_resolution} resolution...")
|
|
106
|
+
with xr.open_dataset(terrain_original_file) as ds_terrain:
|
|
107
|
+
ds_terrain_interp = upsample_terrain_ds(ds_terrain, target_resolution)
|
|
108
|
+
ds_terrain_interp.to_netcdf(terrain_upscaled_file)
|
|
109
|
+
print(f"Generated {terrain_upscaled_file.name}")
|
|
110
|
+
|
|
111
|
+
def main(argv=None) -> int:
|
|
112
|
+
"""CLI entrypoint. Parse argv and call `interpolate`.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
argv (list[str] | None): list of command-line args (not including program name).
|
|
116
|
+
If None, uses sys.argv[1:].
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
int: exit code (0 = success, non-zero = failure)
|
|
120
|
+
|
|
121
|
+
"""
|
|
122
|
+
parser = argparse.ArgumentParser(
|
|
123
|
+
description="Upscale forcing file to target horizontal spatial resolution."
|
|
124
|
+
)
|
|
125
|
+
parser.add_argument(
|
|
126
|
+
"target_resolution",
|
|
127
|
+
type=int,
|
|
128
|
+
choices=list(VALID_TRUNCATIONS),
|
|
129
|
+
help=f"Target horizontal resolution (choices: {VALID_TRUNCATIONS})"
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# let argparse handle argument errors (it raises SystemExit on bad args)
|
|
133
|
+
args = parser.parse_args(argv) # uses sys.argv[1:] if argv is None
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
interpolate(args.target_resolution)
|
|
137
|
+
return 0
|
|
138
|
+
except Exception:
|
|
139
|
+
import traceback
|
|
140
|
+
traceback.print_exc()
|
|
141
|
+
return 1
|
|
142
|
+
|
|
143
|
+
if __name__ == "__main__":
|
|
144
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from jcm.data.bc.interpolate import main
|
|
3
|
+
|
|
4
|
+
class TestInterpolateUnit(unittest.TestCase):
|
|
5
|
+
|
|
6
|
+
def test_interpolate(self):
|
|
7
|
+
# Just test that the interpolate main function runs without error (even if run multiple times)
|
|
8
|
+
self.assertEqual(main(['31']), 0)
|
|
9
|
+
self.assertEqual(main(['31']), 0)
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
jcm/data/test/cbmf.npy
ADDED
|
Binary file
|
jcm/data/test/dfqa.npy
ADDED
|
Binary file
|
jcm/data/test/dfse.npy
ADDED
|
Binary file
|
jcm/data/test/iptop.npy
ADDED
|
Binary file
|
jcm/data/test/precnv.npy
ADDED
|
Binary file
|
jcm/data/test/qdif.npy
ADDED
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
default_stat_vars = ['u_wind', 'v_wind', 'temperature', 'geopotential', 'specific_humidity',
|
|
4
|
+
'normalized_surface_pressure','humidity.rh','shortwave_rad.ftop','longwave_rad.ftop',
|
|
5
|
+
'shortwave_rad.cloudstr','shortwave_rad.qcloud','convection.precnv','condensation.precls']
|
|
6
|
+
|
|
7
|
+
def run_default_speedy_model(save_interval=None):
|
|
8
|
+
"""Run the speedy physics at default settings with realistic forcing and terrain
|
|
9
|
+
T31, 40min timestep
|
|
10
|
+
"""
|
|
11
|
+
from jcm.model import Model
|
|
12
|
+
from jcm.geometry import Geometry
|
|
13
|
+
from jcm.forcing import ForcingData
|
|
14
|
+
|
|
15
|
+
forcing_dir = Path(__file__).resolve().parent / '../../bc/t30/clim'
|
|
16
|
+
|
|
17
|
+
# Load the terrain and forcing data
|
|
18
|
+
|
|
19
|
+
realistic_geometry = Geometry.from_file(forcing_dir / 'terrain.nc', target_resolution=31)
|
|
20
|
+
realistic_forcing = ForcingData.from_file(forcing_dir / 'forcing.nc', target_resolution=31)
|
|
21
|
+
|
|
22
|
+
# in the default scenario output every timestep and don't average
|
|
23
|
+
# in the test scenario, output as designated and average
|
|
24
|
+
time_step = 40.0 # default time step in minutes
|
|
25
|
+
output_averages = False
|
|
26
|
+
if save_interval is None:
|
|
27
|
+
save_interval = time_step/1440.
|
|
28
|
+
else:
|
|
29
|
+
save_interval = save_interval
|
|
30
|
+
output_averages = True
|
|
31
|
+
|
|
32
|
+
model = Model(
|
|
33
|
+
geometry=realistic_geometry,
|
|
34
|
+
time_step=time_step,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
predictions = model.run(
|
|
38
|
+
save_interval=save_interval,
|
|
39
|
+
total_time=90., # 90 days
|
|
40
|
+
output_averages=output_averages,
|
|
41
|
+
forcing=realistic_forcing,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
return model, predictions
|
jcm/date.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import jax.numpy as jnp
|
|
4
|
+
import tree_math
|
|
5
|
+
import jax_datetime as jdt
|
|
6
|
+
|
|
7
|
+
_DAYS_YEAR = 365.2425
|
|
8
|
+
|
|
9
|
+
@tree_math.struct
|
|
10
|
+
class DateData:
|
|
11
|
+
tyear: jnp.float32 # Fractional time of year, should possibly be part of the model itself (i.e. not in physics_data)
|
|
12
|
+
model_year: jnp.int32
|
|
13
|
+
model_step: jnp.int32
|
|
14
|
+
dt_seconds: jnp.float32 # Model timestep in seconds
|
|
15
|
+
|
|
16
|
+
@classmethod
|
|
17
|
+
def zeros(cls, tyear=None, model_year=None, model_step=None, dt_seconds=None):
|
|
18
|
+
return cls(
|
|
19
|
+
tyear=tyear if tyear is not None else jnp.float32(0.0),
|
|
20
|
+
model_year=model_year if model_year is not None else jnp.int32(1950),
|
|
21
|
+
model_step=model_step if model_step is not None else jnp.int32(0),
|
|
22
|
+
dt_seconds=dt_seconds if dt_seconds is not None else jnp.float32(1800.0))
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def set_date(cls, model_time, model_step=None, dt_seconds=None):
|
|
26
|
+
return cls(
|
|
27
|
+
tyear=fraction_of_year_elapsed(model_time),
|
|
28
|
+
model_year=get_year(model_time),
|
|
29
|
+
model_step=model_step if model_step is not None else jnp.int32(0),
|
|
30
|
+
dt_seconds=dt_seconds if dt_seconds is not None else jnp.float32(1800.0))
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def ones(cls, tyear=None, model_year=None, model_step=None, dt_seconds=None):
|
|
34
|
+
return cls(
|
|
35
|
+
tyear=tyear if tyear is not None else jnp.float32(1.0),
|
|
36
|
+
model_year=model_year if model_year is not None else jnp.int32(1950),
|
|
37
|
+
model_step=model_step if model_step is not None else jnp.int32(0),
|
|
38
|
+
dt_seconds=dt_seconds if dt_seconds is not None else jnp.float32(1800.0))
|
|
39
|
+
|
|
40
|
+
def model_day(self):
|
|
41
|
+
return jnp.round(self.tyear*_DAYS_YEAR).astype(jnp.int32)
|
|
42
|
+
|
|
43
|
+
def copy(self, tyear=None, model_year=None, model_step=None, dt_seconds=None):
|
|
44
|
+
return DateData(
|
|
45
|
+
tyear=tyear if tyear is not None else self.tyear,
|
|
46
|
+
model_year=model_year if model_year is not None else self.model_year,
|
|
47
|
+
model_step=model_step if model_step is not None else self.model_step,
|
|
48
|
+
dt_seconds=dt_seconds if dt_seconds is not None else self.dt_seconds)
|
|
49
|
+
|
|
50
|
+
def get_year(dt: jdt.Datetime):
|
|
51
|
+
"""Get the year from a Datetime JAX object.
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
dt: A Datetime JAX object
|
|
55
|
+
|
|
56
|
+
"""
|
|
57
|
+
return jnp.int32(1970 + dt.delta.days // _DAYS_YEAR)
|
|
58
|
+
|
|
59
|
+
def fraction_of_year_elapsed(dt: jdt.Datetime):
|
|
60
|
+
"""Calculate the fraction of the year that has elapsed at the given datetime.
|
|
61
|
+
|
|
62
|
+
This deals with leap years by just assuming that every year has 365.2425 days. This is a simplification, but it should be close
|
|
63
|
+
enough for most purposes (especially just e.g. annually varying solar radiation calculations). Speedy does something similar.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
dt: A Datetime JAX object
|
|
67
|
+
|
|
68
|
+
"""
|
|
69
|
+
# Get days elapsed since start of year, without using non-traceable datetime64
|
|
70
|
+
days_elapsed_in_year = jnp.floor(dt.delta.days % _DAYS_YEAR)
|
|
71
|
+
|
|
72
|
+
# Add the seconds to the days elapsed
|
|
73
|
+
days_elapsed_in_year += dt.delta.seconds / (24 * 60 * 60)
|
|
74
|
+
|
|
75
|
+
# Calculate the fraction of the year elapsed
|
|
76
|
+
return jnp.float32(days_elapsed_in_year / _DAYS_YEAR)
|
jcm/date_test.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from jcm.date import fraction_of_year_elapsed, DateData
|
|
3
|
+
import jax_datetime as jdt
|
|
4
|
+
|
|
5
|
+
class TestDateUnit(unittest.TestCase):
|
|
6
|
+
|
|
7
|
+
def test_fraction_of_year(self):
|
|
8
|
+
# Test the fraction of the year elapsed function
|
|
9
|
+
|
|
10
|
+
# Test leap year
|
|
11
|
+
# Note, the below test incorrectly loops back to the beginning of the year, this doesn't matter for the fraction of the year
|
|
12
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2000-01-01')), 1.0, places=2)
|
|
13
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2000-07-02')), 0.5, places=2)
|
|
14
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2000-12-31')), 365/366, places=2)
|
|
15
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2000-02-29')), (31+28)/366, places=2)
|
|
16
|
+
|
|
17
|
+
# Test non-leap year
|
|
18
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2001-01-01')), 0.0, places=2)
|
|
19
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2001-07-02 12:00:00')), 0.5, places=2)
|
|
20
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2001-12-31')), 364/365, places=2)
|
|
21
|
+
self.assertAlmostEqual(fraction_of_year_elapsed(jdt.to_datetime('2001-02-28')), (31+27)/365, places=2)
|
|
22
|
+
|
|
23
|
+
def test_date_data(self):
|
|
24
|
+
# Test the DateData class
|
|
25
|
+
|
|
26
|
+
# Test with no input
|
|
27
|
+
d = DateData.zeros()
|
|
28
|
+
self.assertEqual(d.tyear, 0.0)
|
|
29
|
+
|
|
30
|
+
# Test with input
|
|
31
|
+
d = DateData.set_date(jdt.to_datetime('2000-07-02'))
|
|
32
|
+
self.assertAlmostEqual(d.tyear, 0.5, places=2)
|
|
33
|
+
|
|
34
|
+
# Test copy
|
|
35
|
+
d2 = d.copy()
|
|
36
|
+
self.assertAlmostEqual(d2.tyear, 0.5, places=2)
|
|
37
|
+
|
|
38
|
+
# Test copy with input
|
|
39
|
+
d3 = d.copy(0.25)
|
|
40
|
+
self.assertAlmostEqual(d3.tyear, 0.25, places=2)
|
jcm/diffusion.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import jax.numpy as jnp
|
|
2
|
+
import tree_math
|
|
3
|
+
from jax import tree_util
|
|
4
|
+
|
|
5
|
+
@tree_math.struct
|
|
6
|
+
class DiffusionFilter:
|
|
7
|
+
vor_q_timescale: jnp.float_ # Diffusion timescale (s)
|
|
8
|
+
vor_q_order: jnp.int_ # Order of diffusion operator for tendencies
|
|
9
|
+
temp_timescale: jnp.float_ # Diffusion timescale (s)
|
|
10
|
+
temp_order: jnp.int_ # Order of diffusion operator for state variables
|
|
11
|
+
div_timescale: jnp.float_ # Diffusion timescale (s)
|
|
12
|
+
div_order: jnp.int_ # Order of diffusion operator for state variables
|
|
13
|
+
|
|
14
|
+
@classmethod
|
|
15
|
+
def default(cls):
|
|
16
|
+
return cls(
|
|
17
|
+
div_timescale = 2*60*60, # Diffusion timescale (s)
|
|
18
|
+
div_order = 1, # Order of diffusion operator for tendencies
|
|
19
|
+
vor_q_timescale = 12*60*60, # Diffusion timescale (s)
|
|
20
|
+
vor_q_order = 2, # Order of diffusion operator for state variables
|
|
21
|
+
temp_timescale = 24*60*60, # Diffusion timescale (s)
|
|
22
|
+
temp_order = 2, # Order of diffusion operator for state variables
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
def isnan(self):
|
|
26
|
+
return tree_util.tree_map(jnp.isnan, self)
|
|
27
|
+
|