Skip to content

Commit 99172cf

Browse files
author
corink21
committed
Added docstring
1 parent 2a0af8d commit 99172cf

File tree

2 files changed

+183
-41
lines changed

2 files changed

+183
-41
lines changed

jobs/tools/camchem_ic_lbc_reggrid.py

Lines changed: 80 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,44 @@
44
from os.path import join
55
from netCDF4 import Dataset
66
from .nc_operations import VariableCreator, VariableCopier, DimensionCopier
7-
from datetime import datetime
87
from .. import tools
98

10-
#######################################################################
11-
## Script for roducing IC and LBC on regular grid from CAM-Chem output.
12-
##
13-
## Author: Corina Keller (Empa).
14-
#######################################################################
15-
169

1710
def process_ic(file_path_in, file_path_out, ic_datetime, aero_dict, prefix):
1811
"""
19-
Copy chem and aerosol fields for specified dates (no unit transformation).
20-
Splitting of aerosols into modes.
12+
Generate initial condition (IC) NetCDF files from CAM-Chem output.
13+
14+
This function copies chemical and aerosol fields for a specified datetime
15+
from an input CAM-Chem NetCDF file. Aerosol fields can be split into
16+
different modes.
17+
No unit transformation is performed.
18+
19+
Parameters
20+
----------
21+
file_path_in : str
22+
Path to the input directory containing CAM-Chem NetCDF files.
23+
file_path_out : str
24+
Path to the output directory where IC files will be saved.
25+
ic_datetime : datetime.datetime
26+
Datetime for the IC to process.
27+
aero_dict : dict
28+
Dictionary specifying how aerosol variables should be split into modes
29+
and their corresponding fractions.
30+
Format: `{aerosol_var_name: {mode_name: split_fraction, ...}, ...}`.
31+
prefix : str
32+
Filename prefix for input and output NetCDF files.
33+
34+
Returns
35+
-------
36+
None
37+
38+
Notes
39+
-----
40+
- Input files are expected to follow the naming convention: `{prefix}%Y%m%d%H.nc`.
41+
- Output files are saved as `{prefix}%Y%m%d%H_ic.nc`.
42+
- Variables not present in `aero_dict` are copied directly.
43+
- Aerosol variables are split according to the fractions defined in `aero_dict`.
2144
"""
22-
#ic_datetime = datetime.strptime(ic_date, '%Y-%m-%d %H:%M:%S')
2345

2446
in_template = prefix + '%Y%m%d%H.nc'
2547
outname_template = prefix + '%Y%m%d%H_ic.nc'
@@ -81,17 +103,58 @@ def process_ic(file_path_in, file_path_out, ic_datetime, aero_dict, prefix):
81103

82104
def process_lbc(file_path_in, file_path_out, start_time, end_time, inc, prefix,
83105
suffix, nameformat, var_mw_dict, aero_dict):
84-
"""
85-
Unit transformation [mol/mol] --> [kg/kg] for chem fields.
86-
Splitting, renaming and unit transformation [kg/kg] --> [ug/kg] for aerosols.
87106
"""
88-
# Files in the input folder
89-
#files = [f for f in os.listdir(file_path) if f.startswith('camchem_') and f.endswith('.nc')]
90-
#for file in files:
107+
Generate lateral boundary condition (LBC) NetCDF files from CAM-Chem output.
108+
109+
This function processes CAM-Chem NetCDF files and produces LBC files with
110+
appropriate unit transformations.
111+
Chemical fields are converted from [mol/mol] to [kg/kg], while aerosol fields
112+
are split into modes and converted from [kg/kg] to [μg/kg].
113+
114+
Parameters
115+
----------
116+
file_path_in : str
117+
Path to the input directory containing CAM-Chem NetCDF files.
118+
file_path_out : str
119+
Path to the output directory where LBC files will be saved.
120+
start_time : datetime.datetime
121+
Start datetime for the LBC processing range.
122+
end_time : datetime.datetime
123+
End datetime for the LBC processing range.
124+
inc : int
125+
Time increment in hours between consecutive files to process.
126+
prefix : str
127+
Filename prefix used for both input and output files.
128+
suffix : str
129+
Filename suffix used for both input and output files (e.g., '.nc').
130+
nameformat : str
131+
Datetime format string used in the filenames (e.g., '%Y%m%d%H').
132+
var_mw_dict : dict
133+
Dictionary mapping chemical variable names to their molecular weights
134+
for unit conversion. Format: `{var_name: molecular_weight, ...}`.
135+
aero_dict : dict
136+
Dictionary specifying how aerosol variables should be split into modes
137+
and their corresponding fractions.
138+
Format: `{aerosol_var_name: {mode_name: split_fraction, ...}, ...}`.
139+
140+
Returns
141+
-------
142+
None
143+
144+
Notes
145+
-----
146+
- Input files are iterated over using specified increments between `start_time`
147+
and `end_time`.
148+
- Chemical fields are converted from [mol/mol] to [kg/kg] using the molecular
149+
weight of air (28.96 g/mol) and the variable-specific molecular weight.
150+
- Aerosol fields are split into modes and converted from [kg/kg] to [μg/kg].
151+
- Essential variables like coordinates and pressure are copied directly
152+
- Output files are saved with `_lbc` appended to the original filename.
153+
"""
154+
91155
for time in tools.iter_hours(start_time, end_time, inc):
92156

93157
# -- Extract datetime information from the filename
94-
#datetime_str = file.split('_')[1].split('.')[0]
95158
in_file = os.path.join(file_path_in,
96159
time.strftime(prefix + nameformat + suffix))
97160
with Dataset(in_file, 'r') as ds:

jobs/tools/camchem_interpolation.py

Lines changed: 103 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,27 @@
1919

2020

2121
def time_intpl(file_path, prefix):
22-
""" Interpolation of chemistry fields with respect to time variable.
22+
2323
"""
24+
Interpolate chemistry fields with respect to time between consecutive NetCDF files.
25+
26+
This function generates new NetCDF files at intermediate times between existing
27+
CAM-Chem output files. Takes the arithmetic mean of chemical and surface pressure
28+
fields and creates interpolated 'time' and 'datesec' variables.
29+
30+
Parameters
31+
----------
32+
file_path : str
33+
Path to the directory containing the input NetCDF files.
34+
prefix : str
35+
Filename prefix for identifying the input NetCDF files to interpolate.
36+
37+
Returns
38+
-------
39+
None
40+
41+
"""
42+
2443
files = sorted([f for f in os.listdir(file_path) if f.startswith(prefix)])
2544

2645
for i in range(len(files) - 1):
@@ -160,15 +179,25 @@ def date_from_days_since_ref(days_since_ref, ref_date):
160179

161180
def extract_timeslice(in_file, out_file_template, spec_intpl, ref_date):
162181
"""
163-
- Extract a time slice from the input NetCDF file.
164-
- Adjust longitude from [0, 360) to (-180, 180].
165-
166-
Parameters:
167-
- in_file (str): Path to the input NetCDF file containing data for each time step.
168-
- out_file_template (str): Template for the output NetCDF file name with strftime placeholder.
169-
- spec_intpl (list): List with species to be copied from in_file.
170-
171-
Returns:
182+
Extract a single time slice from a NetCDF file and adjust longitudes.
183+
184+
Copies selected species and metadata from an input NetCDF file into a new
185+
NetCDF file for each time step.
186+
Longitudes are adjusted from [0, 360) to [-180, 180).
187+
188+
Parameters
189+
----------
190+
in_file : str
191+
Path to the input NetCDF file.
192+
out_file_template : str
193+
Template string for the output filename.
194+
spec_intpl : list of str
195+
List of chemical species to extract from the input file.
196+
ref_date : str
197+
Reference date (YYYY-MM-DD HH:MM:SS) used to convert time variables.
198+
199+
Returns
200+
-------
172201
None
173202
"""
174203

@@ -325,6 +354,26 @@ def extract_timeslice(in_file, out_file_template, spec_intpl, ref_date):
325354

326355

327356
def log_intpl_timeslice(pres_m, pres, var_data):
357+
"""
358+
Perform vertical interpolation of chemical data using log-pressure weighting.
359+
360+
For each chemistry level, the two nearest meteorological levels are identified
361+
and a logarithmic interpolation is applied.
362+
363+
Parameters
364+
----------
365+
pres_m : ndarray
366+
Pressure on meteorological levels (Pa).
367+
pres : ndarray
368+
Pressure on chemical levels (Pa).
369+
var_data : ndarray
370+
Chemical field data to interpolate.
371+
372+
Returns
373+
-------
374+
ndarray
375+
Interpolated chemical field on meteorological levels.
376+
"""
328377
pres_m_flipped = np.flip(pres_m, axis=0)
329378
pres_flipped = np.flip(pres, axis=0)
330379
var_data_flipped = np.flip(var_data, axis=0)
@@ -375,8 +424,24 @@ def log_intpl_timeslice(pres_m, pres, var_data):
375424

376425

377426
def hybrid_pressure_interpolation(in_ds, out_ds, var_name, time_indices):
378-
"""Perform vertical interpolation of 'var_name'.
379-
The interpolation is linear with the log pressure.
427+
"""
428+
Interpolate chemical variable vertically using log-pressure interpolation.
429+
430+
Parameters
431+
----------
432+
in_ds : netCDF4.Dataset
433+
Input dataset containing the chemical variable.
434+
out_ds : netCDF4.Dataset
435+
Output dataset with meteorological levels.
436+
var_name : str
437+
Name of the chemical variable to interpolate.
438+
time_indices : list of int
439+
Time indices to process in the datasets.
440+
441+
Returns
442+
-------
443+
ndarray
444+
Array of vertically interpolated variable on meteorological levels.
380445
"""
381446
# Pressure on vertical levels of meteo data
382447
pres_m = out_ds['pres_m'][:]
@@ -398,19 +463,33 @@ def hybrid_pressure_interpolation(in_ds, out_ds, var_name, time_indices):
398463

399464
def vert_intpl(chem_filename, meteo_filename, out_filename, spec, start_chunk,
400465
end_chunk, ref_date):
401-
"""Perform vertical interpolation of atmospheric chemical fields using meteorological data.
402-
403-
Parameters:
404-
- chem_filename (str): Path to the netCDF file containing atmospheric chemical data.
405-
- meteo_filename (str): Path to the netCDF file containing meteorological data.
406-
- out_filename (str): Path to the output netCDF file for interpolated data.
407-
- species (list): List of chemical species names to be interpolated.
408-
- start_chunk (datetime object): Start of simulation time.
409-
- end_chunk (datetime object): End of simulation time.
410-
411-
Returns:
466+
"""
467+
Perform vertical interpolation of chemical fields using meteorological data.
468+
469+
This function interpolates chemical species from their CAM-Chem vertical levels
470+
onto the hybrid sigma-pressure levels of the meteorological dataset.
471+
472+
Parameters
473+
----------
474+
chem_filename : str
475+
Path to the NetCDF file containing chemical data.
476+
meteo_filename : str
477+
Path to the NetCDF file containing meteorological data.
478+
out_filename : str
479+
Path for the output NetCDF file with interpolated results.
480+
spec : list of str
481+
List of chemical species to interpolate.
482+
start_chunk : datetime.datetime
483+
Start of the simulation time window to process.
484+
end_chunk : datetime.datetime
485+
End of the simulation time window to process.
486+
ref_date : str
487+
Reference date (YYYY-MM-DD HH:MM:SS) used to convert time variables.
488+
489+
Returns
490+
-------
412491
None
413-
492+
414493
"""
415494

416495
with Dataset(chem_filename, 'r') as c_ds, Dataset(meteo_filename,

0 commit comments

Comments
 (0)