MPTRAC
Loading...
Searching...
No Matches
mptrac.h File Reference

MPTRAC library declarations. More...

#include <ctype.h>
#include <float.h>
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_randist.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_spline.h>
#include <gsl/gsl_statistics.h>
#include <math.h>
#include <netcdf.h>
#include <omp.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include "mpi.h"
#include <netcdf_par.h>

Go to the source code of this file.

Data Structures

struct  ctl_t
 Control parameters. More...
 
struct  atm_t
 Air parcel data. More...
 
struct  particle_t
 Particle data. More...
 
struct  cache_t
 Cache data structure. More...
 
struct  depo_t
 Ground inventories of deposited radionuclides. More...
 
struct  clim_photo_t
 Climatological data in the form of photolysis rates. More...
 
struct  clim_ts_t
 Climatological data in the form of time series. More...
 
struct  clim_zm_t
 Climatological data in the form of zonal means. More...
 
struct  clim_t
 Climatological data. More...
 
struct  met_t
 Meteo data structure. More...
 
struct  dd_t
 Domain decomposition data structure. More...
 

Macros

#define codes_handle   void*
 Placeholder when ECCODES is not available.
 
#define AVO   6.02214076e23
 Avogadro constant [1/mol].
 
#define CPD   1003.5
 Specific heat of dry air at constant pressure [J/(kg K)].
 
#define EPS   (MH2O / MA)
 Ratio of the specific gas constant of dry air and water vapor [1].
 
#define G0   9.80665
 Standard gravity [m/s^2].
 
#define H0   7.0
 Scale height [km].
 
#define LV   2501000.
 Latent heat of vaporization of water [J/kg].
 
#define KARMAN   0.40
 Karman's constant.
 
#define KB   1.3806504e-23
 Boltzmann constant [kg m^2/(K s^2)].
 
#define MA   28.9644
 Molar mass of dry air [g/mol].
 
#define MH2O   18.01528
 Molar mass of water vapor [g/mol].
 
#define MO3   48.00
 Molar mass of ozone [g/mol].
 
#define P0   1013.25
 Standard pressure [hPa].
 
#define RA   (1e3 * RI / MA)
 Specific gas constant of dry air [J/(kg K)].
 
#define RE   6367.421
 Mean radius of Earth [km].
 
#define RI   8.3144598
 Ideal gas constant [J/(mol K)].
 
#define KAPPA   0.286
 Exponent used for potential-temperature calculations [1].
 
#define OMEGA_EARTH   7.2921e-5
 Angular velocity of Earth [s^-1].
 
#define DOBSON_UNIT   2.1415e-5
 Ozone column mass corresponding to one Dobson unit [kg/m^2].
 
#define M_AIR_MOLECULE   4.8096e-26
 Mean mass of an air molecule [kg].
 
#define CHEM_REF_TEMP   298.15
 Reference temperature for chemical equilibrium constants [K].
 
#define H2O2_SO2_RATE_REF   9.1e7
 Reference rate for aqueous H2O2-SO2 chemistry [L^2/(mol^2 s)].
 
#define H2O2_SO2_RATE_TEMP   29700.
 Temperature parameter for the aqueous H2O2-SO2 rate [K].
 
#define SO2_HENRY_REF   1.3e-2
 SO2 Henry constant at CHEM_REF_TEMP [mol/(m^3 Pa)].
 
#define SO2_HENRY_TEMP   2900.
 Temperature dependence of the SO2 Henry constant [K].
 
#define H2O2_HENRY_REF   8.3e2
 H2O2 Henry constant at CHEM_REF_TEMP [mol/(m^3 Pa)].
 
#define H2O2_HENRY_TEMP   7600.
 Temperature dependence of the H2O2 Henry constant [K].
 
#define SO2_CORR_A   3.12541941e-06
 Scale factor of the high-SO2 correction for fractional SO2 mole fraction.
 
#define SO2_CORR_B   -5.72532259e-01
 Exponent of the high-SO2 correction [1].
 
#define O1D_RATE_CCL4_A   2.607e-10
 O(1D) parent-destruction pre-factor for CCl4 [cm^3 molecule^-1 s^-1].
 
#define O1D_RATE_CCL4_B   0.
 O(1D) reaction temperature parameter for CCl4 [K].
 
#define O1D_RATE_CFC11_A   2.070e-10
 O(1D) parent-destruction pre-factor for CFC-11 [cm^3 molecule^-1 s^-1].
 
#define O1D_RATE_CFC11_B   0.
 O(1D) reaction temperature parameter for CFC-11 [K].
 
#define O1D_RATE_CFC12_A   1.204e-10
 O(1D) parent-destruction pre-factor for CFC-12 [cm^3 molecule^-1 s^-1].
 
#define O1D_RATE_CFC12_B   -25.
 O(1D) reaction temperature parameter for CFC-12 [K].
 
#define O1D_RATE_N2O_A   1.19e-10
 O(1D) parent-destruction pre-factor for N2O [cm^3 molecule^-1 s^-1].
 
#define O1D_RATE_N2O_B   -20.
 O(1D) reaction temperature parameter for N2O [K].
 
#define SO2_DISS_K1_REF   1.23e-2
 First SO2 dissociation constant at CHEM_REF_TEMP [mol/L].
 
#define SO2_DISS_K1_TEMP   2.01e3
 Temperature dependence of the first SO2 dissociation constant [K].
 
#define SO2_DISS_K2_REF   6e-8
 Second SO2 dissociation constant at CHEM_REF_TEMP [mol/L].
 
#define SO2_DISS_K2_TEMP   1.12e3
 Temperature dependence of the second SO2 dissociation constant [K].
 
#define WET_DEPO_T_LIQUID   T0
 Upper temperature of the ice-cloud retention transition [K].
 
#define WET_DEPO_T_ICE   238.15
 Lower temperature of the ice-cloud retention transition [K].
 
#define WET_DEPO_T_LIQUID_BC   270.
 Temperature threshold for below-cloud retention [K].
 
#define RADIO_HALF_LIFE_RN222   (3.8235 * 86400.0)
 Half-life of Rn-222 [s].
 
#define RADIO_HALF_LIFE_PB210   (22.3 * 365.25 * 86400.0)
 Half-life of Pb-210 [s].
 
#define RADIO_HALF_LIFE_BE7   (53.22 * 86400.0)
 Half-life of Be-7 [s].
 
#define RADIO_HALF_LIFE_CS137   (30.05 * 365.25 * 86400.0)
 Half-life of Cs-137 [s].
 
#define RADIO_HALF_LIFE_I131   (8.02 * 86400.0)
 Half-life of I-131 [s].
 
#define RADIO_HALF_LIFE_XE133   (5.2474 * 86400.0)
 Half-life of Xe-133 [s].
 
#define RADIO_DRY_VDEP_PB210   0.002
 Dry deposition velocity of Pb-210 [m/s].
 
#define RADIO_DRY_VDEP_BE7   0.001
 Dry deposition velocity of Be-7 [m/s].
 
#define RADIO_DRY_VDEP_CS137   0.002
 Dry deposition velocity of Cs-137 [m/s].
 
#define RADIO_DRY_VDEP_I131   0.0005
 Dry deposition velocity of aerosol-bound I-131 [m/s].
 
#define RADIO_WET_COEFF_PB210   1e-4
 Wet deposition coefficient of Pb-210 [s^-1 (mm h^-1)^-1].
 
#define RADIO_WET_COEFF_BE7   5e-5
 Wet deposition coefficient of Be-7 [s^-1 (mm h^-1)^-1].
 
#define RADIO_WET_COEFF_CS137   1e-4
 Wet deposition coefficient of Cs-137 [s^-1 (mm h^-1)^-1].
 
#define RADIO_WET_COEFF_I131   5e-5
 Wet deposition coefficient of aerosol-bound I-131 [s^-1 (mm h^-1)^-1].
 
#define T0   273.15
 Standard temperature [K].
 
#define EP   140
 Maximum number of pressure levels for meteo data.
 
#define EX   1444
 Maximum number of longitudes for meteo data.
 
#define EY   724
 Maximum number of latitudes for meteo data.
 
#define LEN   5000
 Maximum length of ASCII data lines.
 
#define METVAR   13
 Number of 3-D meteorological variables.
 
#define NP   10000000
 Maximum number of atmospheric data points.
 
#define NQ   15
 Maximum number of quantities per data point.
 
#define NCSI   1000000
 Maximum number of data points for CSI calculation.
 
#define NENS   2000
 Maximum number of data points for ensemble analysis.
 
#define NOBS   10000000
 Maximum number of observation data points.
 
#define NTHREADS   512
 Maximum number of OpenMP threads.
 
#define CY   250
 Maximum number of latitudes for climatological data.
 
#define CO3   30
 Maximum number of total column ozone data for climatological data.
 
#define CP   70
 Maximum number of pressure levels for climatological data.
 
#define CSZA   50
 Maximum number of solar zenith angles for climatological data.
 
#define CT   12
 Maximum number of time steps for climatological data.
 
#define CTS   1000
 Maximum number of data points of climatological time series.
 
#define DD_EX_GLOB   (EX * 16)
 Maximum number of longitudes of global meteo data.
 
#define DD_EY_GLOB   (EY * 16)
 Maximum number of latitudes of global meteo data.
 
#define ALLOC(ptr, type, n)
 Allocate memory for a pointer with error handling.
 
#define ARRAY_2D(ix, iy, ny)
 Macro for computing the linear index of a 2D array element.
 
#define ARRAY_3D(ix, iy, ny, iz, nz)
 Compute the linear index of a 3D array element.
 
#define ARRHENIUS(a, b, t)
 Calculate the Arrhenius rate constant.
 
#define CLAMP(v, lo, hi)
 Clamp a value to a specified range.
 
#define COMPRESS_SPEED(nbytes, dt)
 Calculate compression throughput in MiB/s.
 
#define COMPRESS_RATIO(raw_size, stored_size)
 Calculate the compression ratio from raw and stored byte counts.
 
#define COMPRESS_BPV(n, stored_size)
 Calculate bits per value from stored size and element count.
 
#define DEG2DX(dlon, lat)
 Convert a longitude difference to a distance in the x-direction (east-west) at a specific latitude.
 
#define DEG2DY(dlat)
 Convert a latitude difference to a distance in the y-direction (north-south).
 
#define DEG2RAD(deg)
 Converts degrees to radians.
 
#define DP2DZ(dp, p)
 Convert a pressure difference to a height difference in the vertical direction.
 
#define DX2DEG(dx, lat)
 Convert a distance in kilometers to degrees longitude at a given latitude.
 
#define DY2DEG(dy)
 Convert a distance in kilometers to degrees latitude.
 
#define DZ2DP(dz, p)
 Convert a change in altitude to a change in pressure.
 
#define DX2COORD(met, dx, lat)
 Convert a distance in meters to a coordinate value based on grid type.
 
#define DY2COORD(met, dy)
 Convert a distance to coordinate value based on grid type.
 
#define DIST(a, b)
 Calculate the distance between two points in Cartesian coordinates.
 
#define DIST2(a, b)
 Calculate the squared Euclidean distance between two points in Cartesian coordinates.
 
#define DOTP(a, b)
 Calculate the dot product of two vectors.
 
#define ECC(cmd)
 Execute an ECCODES command and check for errors.
 
#define ECC_READ_2D(variable, target, scaling_factor, found_flag)
 Writes 2-D data from a grib message into the meteo struct.
 
#define ECC_READ_3D(variable, level, target, scaling_factor, found_flag)
 Writes 3D data from a grib message into the meteo struct.
 
#define FMOD(x, y)
 Calculate the floating-point remainder of dividing x by y.
 
#define DT_ALIGNED(dt, dt_mod)
 
#define OBS_TIME_WINDOW(ctl, t, t0, t1)
 Set the half-open observation window for a model output time.
 
#define FREAD(ptr, type, size, in)
 Read data from a file stream and store it in memory.
 
#define FWRITE(ptr, type, size, out)
 Write data from memory to a file stream.
 
#define INTPOL_INIT    double cw[4] = {0.0, 0.0, 0.0, 0.0}; int ci[3] = {0, 0, 0};
 Initialize arrays for interpolation.
 
#define INTPOL_2D(var, init)
 Perform 2D interpolation for a meteorological variable.
 
#define INTPOL_3D(var, init)
 Perform 3D interpolation for a meteorological variable.
 
#define INTPOL_SPACE_ALL(p, lon, lat)
 Interpolate multiple meteorological variables in space.
 
#define INTPOL_TIME_ALL(time, p, lon, lat)
 Interpolate multiple meteorological variables in time.
 
#define LAPSE(p1, t1, p2, t2)
 Calculate lapse rate.
 
#define LIN(x0, y0, x1, y1, x)
 Linear interpolation.
 
#define MAX(a, b)
 Macro to determine the maximum of two values.
 
#define MET_HEADER
 Write header for meteorological data file.
 
#define MIN(a, b)
 Macro to determine the minimum of two values.
 
#define MOLEC_DENS(p, t)
 Calculate the molecular number density of air.
 
#define NC(cmd)
 Execute a NetCDF command and check for errors.
 
#define NC_DEF_VAR(varname, type, ndims, dims, long_name, units, level, quant)
 Define a NetCDF variable with attributes.
 
#define NC_DEF_VAR_QUANTIZE(quant)
 
#define NC_GET_DOUBLE(varname, ptr, force)
 Retrieve a double-precision variable from a NetCDF file.
 
#define NC_INQ_DIM(dimname, ptr, min, max, check)
 Inquire the length of a dimension in a NetCDF file.
 
#define NC_PUT_DOUBLE(varname, ptr, hyperslab)
 Write double precision data to a NetCDF variable.
 
#define NC_PUT_FLOAT(varname, ptr, hyperslab)
 Write a float array to a NetCDF file.
 
#define NC_PUT_INT(varname, ptr, hyperslab)
 Write integer data to a NetCDF variable.
 
#define NC_PUT_ATT(varname, attname, text)
 Add a text attribute to a NetCDF variable.
 
#define NC_PUT_ATT_GLOBAL(attname, text)
 Add a global text attribute to a NetCDF file.
 
#define NN(x0, y0, x1, y1, x)
 Perform nearest-neighbor interpolation.
 
#define PARTICLE_LOOP(ip0, ip1, check_dt, ...)
 Loop over particle indices with OpenACC acceleration.
 
#define P(z)
 Compute pressure at given altitude.
 
#define PSAT(t)
 Compute saturation pressure over water.
 
#define PSICE(t)
 Compute saturation pressure over ice (WMO, 2018).
 
#define PW(p, h2o)
 Calculate partial water vapor pressure.
 
#define RAD2DEG(rad)
 Converts radians to degrees.
 
#define RH(p, t, h2o)
 Compute relative humidity over water.
 
#define RHICE(p, t, h2o)
 Compute relative humidity over ice.
 
#define RHO(p, t)
 Compute density of air.
 
#define SET_ATM(qnt, val)
 Set atmospheric quantity value.
 
#define SET_QNT(qnt, name, longname, unit)
 Set atmospheric quantity index.
 
#define SH(h2o)
 Compute specific humidity from water vapor volume mixing ratio.
 
#define SQR(x)
 Compute the square of a value.
 
#define SWAP(x, y, type)
 Swap two values.
 
#define TDEW(p, h2o)
 Calculate dew point temperature.
 
#define TICE(p, h2o)
 Calculate frost point temperature (WMO, 2018).
 
#define THETA(p, t)
 Compute potential temperature.
 
#define THETAVIRT(p, t, h2o)
 Compute virtual potential temperature.
 
#define TOK(line, tok, format, var)
 Get string tokens.
 
#define TVIRT(t, h2o)
 Compute virtual temperature.
 
#define USAGE
 Print usage information on -h or --help.
 
#define Z(p)
 Convert pressure to altitude.
 
#define ZDIFF(lnp0, t0, h2o0, lnp1, t1, h2o1)
 Calculate geopotential height difference.
 
#define ZETA(ps, p, t)
 Computes the value of the zeta vertical coordinate.
 
#define LOGLEV   2
 Level of log messages (0=none, 1=basic, 2=detailed, 3=debug).
 
#define LOG(level, ...)
 Print a log message with a specified logging level.
 
#define WARN(...)
 Print a warning message with contextual information.
 
#define ERRMSG(...)
 Print an error message with contextual information and terminate the program.
 
#define PRINT(format, var)
 Print the value of a variable with contextual information.
 
#define NTIMER   100
 Maximum number of timers.
 
#define PRINT_TIMERS
 Print the current state of all timers.
 
#define SELECT_TIMER(id, group)
 Select and start a timer with specific attributes.
 

Functions

void broadcast_large_data (void *data, size_t N)
 Broadcasts large data across all processes in an MPI communicator.
 
void cart2geo (const double *x, double *z, double *lon, double *lat)
 Converts Cartesian coordinates to geographic coordinates.
 
double clim_oh (const ctl_t *ctl, const clim_t *clim, const double t, const double lon, const double lat, const double p)
 Calculates the hydroxyl radical (OH) concentration from climatology data, with an optional diurnal correction based on solar zenith angle.
 
void clim_oh_diurnal_correction (const ctl_t *ctl, clim_t *clim)
 Applies a diurnal correction to the hydroxyl radical (OH) concentration in climatology data.
 
double clim_photo (const double rate[CP][CSZA][CO3], const clim_photo_t *photo, const double p, const double sza, const double o3c)
 Calculates the photolysis rate for a given set of atmospheric conditions.
 
double clim_tropo (const clim_t *clim, const double t, const double lat)
 Calculates the tropopause pressure based on climatological data.
 
void clim_tropo_init (clim_t *clim)
 Initializes the tropopause data in the climatology structure.
 
double clim_ts (const clim_ts_t *ts, const double t)
 Interpolates a time series of climatological variables.
 
double clim_zm (const clim_zm_t *zm, const double t, const double lat, const double p)
 Interpolates monthly mean zonal mean climatological variables.
 
void compress_log_level (FILE *out, const char *codec, const char *varname, const size_t lev, const double plev, const double ratio, const double bpv, const double t_comp, const double t_decomp, const size_t n, const size_t nbytes, const float *org, const float *cmp)
 Write one row of per-level compression diagnostics.
 
void compress_log_levels_3d (FILE *out, const char *codec, const char *varname, const met_t *met, const float *org_all, const float *cmp_all, const size_t nxy, const size_t nz, const double ratio, const double bpv, const double t_comp, const double t_decomp, const size_t nbytes)
 Write per-level compression diagnostics for a full 3-D field.
 
void compress_cms (const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
 Compresses or decompresses a 3-D meteorological field using cmultiscale.
 
void compress_scale_to_unit (float *array, const size_t nxy, const size_t nz, double *off, double *scl)
 Scales each vertical level of a 3-D field independently to the interval [0,1].
 
void compress_unscale_from_unit (float *array, const size_t nxy, const size_t nz, const double *off, const double *scl)
 Restores a levelwise [0,1]-scaled 3-D field to physical units.
 
int compress_read_lossy_scale (FILE *in, const size_t nz, double **off, double **scl)
 Read optional lossyscaling metadata for a 3-D field.
 
void compress_write_lossy_scale (FILE *out, const int enabled, float *array, const size_t nxy, const size_t nz, double **off, double **scl)
 Write optional lossyscaling metadata for a 3-D field.
 
int compress_metvar_index (const char *varname)
 Maps a meteorological variable name to its internal MPTRAC variable index.
 
void compress_pck (const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
 Compresses or decompresses a 3‑D float array using the PCK format.
 
void compress_sz3 (const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
 Compresses or decompresses a 3-D float array using the SZ3 library.
 
void compress_zfp (const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
 Compresses or decompresses a 3D array of floats using the ZFP library.
 
void compress_zstd (const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
 Compresses or decompresses a float array using ZSTD.
 
void compress_lz4 (const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
 Compresses or decompresses a float array using LZ4.
 
double cos_sza (const double sec, const double lon, const double lat)
 Calculates the cosine of the solar zenith angle.
 
void day2doy (const int year, const int mon, const int day, int *doy)
 Get day of year from date.
 
void dd_assign_subdomains (const ctl_t *ctl, const dd_t *dd, atm_t *atm, const int init)
 Assign or update particle subdomain ownership.
 
void dd_atm2particles (const ctl_t *ctl, cache_t *cache, atm_t *atm, particle_t *particles, const int npart)
 Copy migratable atmospheric particles from the ATM state into a particle buffer.
 
void dd_pack_compact (const ctl_t *ctl, cache_t *cache, atm_t *atm, dd_t *dd, particle_t *particles, const int nkeep, const int npart)
 Pack outgoing particles and compact local arrays without sorting.
 
int dd_calc_subdomain_from_coords (const ctl_t *ctl, const dd_t *dd, const double lon, const double lat)
 Determine MPI subdomain from particle coordinates.
 
void dd_communicate_particles (const ctl_t *ctl, const dd_t *dd, particle_t **particles, int *npart, int *capacity)
 Exchange particles between MPI ranks according to their destination rank.
 
void dd_init (const ctl_t *ctl, dd_t *dd, atm_t *atm)
 Initialize the domain decomposition infrastructure.
 
void dd_normalize_lon_lat (const dd_t *dd, double *lon, double *lat)
 Normalize geographic coordinates to the global grid convention.
 
void dd_particles2atm (const ctl_t *ctl, cache_t *cache, const particle_t *particles, const int npart, atm_t *atm)
 Copy received particles from the communication buffer into the atmospheric state.
 
void dd_push (const ctl_t *ctl, atm_t *atm, cache_t *cache, int *npart)
 Compact and stage non-local particles for domain decomposition transfer.
 
void dd_count_outgoing (const ctl_t *ctl, const atm_t *atm, dd_t *dd, int *nkeep, int *npart)
 Classify particles before direct packing and compaction.
 
void dd_read_met_nc_grid (dd_t *dd, const ctl_t *ctl, met_t *met, const int ncid)
 Read meteorological grid information and construct the domain-decomposed grid with halo regions.
 
void dd_sort (const ctl_t *ctl, const met_t *met0, cache_t *cache, atm_t *atm, dd_t *dd, int *npart)
 Sort local atmospheric particles and determine export counts for domain decomposition.
 
void doy2day (const int year, const int doy, int *mon, int *day)
 Converts a given day of the year (DOY) to a date (month and day).
 
void fft_help (double *fcReal, double *fcImag, const int n)
 Computes the Fast Fourier Transform (FFT) of a complex sequence.
 
void geo2cart (const double z, const double lon, const double lat, double *x)
 Converts geographic coordinates (longitude, latitude, altitude) to Cartesian coordinates.
 
void get_met_filename (const ctl_t *ctl, const double t, const int direct, const char *metbase, const double dt_met, char *filename)
 Generates a formatted filename for meteorological data files based on the input parameters.
 
void get_met_replace (char *orig, const char *search, const char *repl)
 Replaces occurrences of a substring in a string with another substring.
 
void get_tropo (const int met_tropo, ctl_t *ctl, const clim_t *clim, met_t *met, const double *lons, const int nx, const double *lats, const int ny, double *pt, double *zt, double *tt, double *qt, double *o3t, double *ps, double *zs)
 Calculate tropopause data.
 
void intpol_check_lon_lat (const double *lons, const int nlon, const double *lats, const int nlat, const double lon, const double lat, double *lon2, double *lat2)
 Adjusts longitude and latitude to ensure they fall within valid bounds.
 
void intpol_check_cartesian (const double *lons, const int nlon, const double *lats, const int nlat, const double lon, const double lat, double *lon2, double *lat2)
 Clamps UTM coordinates to the valid bounds.
 
void intpol_met_4d_zeta (const met_t *met0, float height0[EX][EY][EP], float array0[EX][EY][EP], const met_t *met1, float height1[EX][EY][EP], float array1[EX][EY][EP], const double ts, const double height, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
 Interpolates meteorological variables to a given position and time.
 
void intpol_met_space_3d (const met_t *met, float array[EX][EY][EP], const double p, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
 Interpolates meteorological variables in 3D space.
 
void intpol_met_space_2d (const met_t *met, float array[EX][EY], const double lon, const double lat, double *var, int *ci, double *cw, const int init)
 Interpolates meteorological variables in 2D space.
 
void intpol_met_time_3d (const met_t *met0, float array0[EX][EY][EP], const met_t *met1, float array1[EX][EY][EP], const double ts, const double p, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
 Interpolates meteorological data in 3D space and time.
 
void intpol_met_time_2d (const met_t *met0, float array0[EX][EY], const met_t *met1, float array1[EX][EY], const double ts, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
 Interpolates meteorological data in 2D space and time.
 
void intpol_tropo_3d (const double time0, float array0[EX][EY], const double time1, float array1[EX][EY], const double lons[EX], const double lats[EY], const int nlon, const int nlat, const double time, const double lon, const double lat, const int method, double *var, double *sigma)
 Interpolates tropopause data in 3D (latitude, longitude, and time).
 
void jsec2time (const double jsec, int *year, int *mon, int *day, int *hour, int *min, int *sec, double *remain)
 Converts Julian seconds to calendar date and time components.
 
double kernel_weight (const double kz[EP], const double kw[EP], const int nk, const double p)
 Calculates the kernel weight based on altitude and given kernel data.
 
double lapse_rate (const double t, const double h2o)
 Calculates the moist adiabatic lapse rate in Kelvin per kilometer.
 
void level_definitions (ctl_t *ctl)
 Defines pressure levels for meteorological data.
 
int locate_irr (const double *xx, const int n, const double x)
 Locate the index of the interval containing a given value in a sorted array.
 
int locate_irr_float (const float *xx, const int n, const double x, const int ig)
 Locate the index of the interval containing a given value in an irregularly spaced array.
 
int locate_reg (const double *xx, const int n, const double x)
 Locate the index of the interval containing a given value in a regular grid.
 
void locate_vert (float profiles[EX][EY][EP], const int np, const int lon_ap_ind, const int lat_ap_ind, const double alt_ap, int *ind)
 Locate the four vertical indizes of a box for a given height value.
 
void module_advect (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Advances particle positions using different advection schemes.
 
void module_advect_init (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Initializes the advection module by setting up pressure fields.
 
void module_bound_cond (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Apply boundary conditions to particles based on meteorological and climatological data.
 
void module_chem_grid (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, const double t)
 Computes gridded chemical tracer concentrations (volume mixing ratio) from individual air parcel mass data and assigns them back to the parcels.
 
void module_chem_init (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Initializes the chemistry modules by setting atmospheric composition.
 
void module_convection (const ctl_t *ctl, cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Performs convective mixing of atmospheric particles.
 
void module_dd (double t, const ctl_t *ctl, cache_t *cache, dd_t *dd, atm_t *atm, met_t **met)
 Perform domain decomposition and exchange particles between MPI ranks.
 
void module_decay (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, atm_t *atm)
 Simulate exponential decay processes for atmospheric particles.
 
void module_diff_meso (const ctl_t *ctl, cache_t *cache, const met_t *met0, const met_t *met1, atm_t *atm)
 Simulate mesoscale diffusion for atmospheric particles.
 
void module_diff_pbl (const ctl_t *ctl, cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Computes particle diffusion within the planetary boundary layer (PBL).
 
void module_diff_turb (const ctl_t *ctl, cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Applies turbulent diffusion processes to atmospheric particles.
 
void module_dry_depo (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Simulate dry deposition of atmospheric particles.
 
void module_h2o2_chem (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Apply aqueous H2O2 oxidation of SO2 in liquid cloud water.
 
void module_isosurf_init (const ctl_t *ctl, cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, const int initial, const double model_t)
 Initialize the isosurface module based on atmospheric data.
 
void module_isosurf (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Apply the isosurface module to adjust atmospheric properties.
 
void module_kpp_chem (ctl_t *ctl, cache_t *cache, clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 KPP chemistry module.
 
void module_meteo (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Update atmospheric properties using meteorological data.
 
void module_mixing (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, atm_t *atm, const double t)
 Update atmospheric properties through interparcel mixing.
 
void module_mixing_help (const ctl_t *ctl, atm_t *atm, const int *ixs, const int *iys, const int *izs, const double *mixparam, const int qnt_idx, const int use_ensemble)
 Perform subgrid-scale interparcel mixing of a given quantity.
 
void module_oh_chem (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Perform hydroxyl chemistry calculations for atmospheric particles.
 
void module_position (const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, const int reflect)
 Update the positions and pressure levels of atmospheric particles.
 
void module_rng_init (const int ntask)
 Initialize random number generators for parallel tasks.
 
void module_rng (const ctl_t *ctl, double *rs, const size_t n, const int method)
 Generate random numbers using various methods and distributions.
 
void module_radio_decay (const ctl_t *ctl, const cache_t *cache, atm_t *atm)
 Apply radioactive decay to atmospheric tracer species.
 
void module_radio_depo (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, depo_t *depo)
 Deposit supported radionuclides from air parcels onto the ground grid.
 
void module_sedi (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Simulate sedimentation of particles in the atmosphere.
 
void sort_array (double *array, const int *perm, double *tmp, const int np)
 Reorder a double array according to particle source indices.
 
void sort_uvwp (cache_t *cache, const int *perm, double *tmp, const int np)
 Reorder particle-specific wind perturbations.
 
void module_sort (const ctl_t *ctl, const met_t *met0, cache_t *cache, atm_t *atm)
 Sort particles according to box index.
 
void module_timesteps (const ctl_t *ctl, cache_t *cache, const met_t *met0, atm_t *atm, const double t)
 Calculate time steps for air parcels based on specified conditions.
 
void module_timesteps_init (ctl_t *ctl, const atm_t *atm)
 Initialize start time and time interval for time-stepping.
 
void module_tracer_chem (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
 Simulate chemical reactions involving long-lived atmospheric tracers.
 
void module_wet_depo (const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
 Perform wet deposition calculations for air parcels.
 
void mptrac_alloc (ctl_t **ctl, cache_t **cache, clim_t **clim, met_t **met0, met_t **met1, atm_t **atm, depo_t **depo, dd_t **dd)
 Allocates and initializes memory resources for MPTRAC.
 
void mptrac_free (ctl_t *ctl, cache_t *cache, clim_t *clim, met_t *met0, met_t *met1, atm_t *atm, depo_t *depo, dd_t *dd)
 Frees memory resources allocated for MPTRAC.
 
void mptrac_get_met (ctl_t *ctl, clim_t *clim, const double t, met_t **met0, met_t **met1, dd_t *dd)
 Retrieves meteorological data for the specified time.
 
void mptrac_init (ctl_t *ctl, cache_t *cache, clim_t *clim, atm_t *atm, depo_t *depo, const int ntask)
 Initializes the MPTRAC model and its associated components.
 
int mptrac_read_atm (const char *filename, const ctl_t *ctl, atm_t *atm)
 Reads air parcel data from a specified file into the given atmospheric structure.
 
void mptrac_read_clim (const ctl_t *ctl, clim_t *clim)
 Reads various climatological data and populates the given climatology structure.
 
void mptrac_read_ctl (const char *filename, int argc, char *argv[], ctl_t *ctl)
 Reads control parameters from a configuration file and populates the given structure.
 
int mptrac_read_met (const char *filename, const ctl_t *ctl, const clim_t *clim, met_t *met, dd_t *dd)
 Reads meteorological data from a file, supporting multiple formats and MPI broadcasting.
 
void mptrac_run_timestep (ctl_t *ctl, cache_t *cache, clim_t *clim, met_t **met0, met_t **met1, atm_t *atm, depo_t *depo, double t, dd_t *dd)
 Executes a single timestep of the MPTRAC model simulation.
 
void mptrac_write_atm (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes air parcel data to a file in various formats.
 
void mptrac_write_met (const char *filename, const ctl_t *ctl, met_t *met)
 Writes meteorological data to a file, supporting multiple formats and compression options.
 
void mptrac_write_output (const char *dirname, const ctl_t *ctl, met_t *met0, met_t *met1, atm_t *atm, depo_t *depo, const double t)
 Writes various types of output data to files in a specified directory.
 
void mptrac_update_device (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t **met0, met_t **met1, const atm_t *atm)
 Updates device memory for specified data structures.
 
void mptrac_update_host (const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t **met0, met_t **met1, const atm_t *atm)
 Updates host memory for specified data structures.
 
double nat_temperature (const double p, const double h2o, const double hno3)
 Calculates the nitric acid trihydrate (NAT) temperature.
 
double pbl_weight (const ctl_t *ctl, const atm_t *atm, const int ip, const double pbl, const double ps)
 Computes a weighting factor based on planetary boundary layer pressure.
 
int read_atm_asc (const char *filename, const ctl_t *ctl, atm_t *atm)
 Reads air parcel data from an ASCII file and populates the given atmospheric structure.
 
int read_atm_bin (const char *filename, const ctl_t *ctl, atm_t *atm)
 Reads air parcel data from a binary file and populates the given atmospheric structure.
 
int read_atm_clams (const char *filename, const ctl_t *ctl, atm_t *atm)
 Reads atmospheric data from a CLAMS NetCDF file.
 
int read_atm_nc (const char *filename, const ctl_t *ctl, atm_t *atm)
 Reads air parcel data from a generic netCDF file and populates the given atmospheric structure.
 
void read_clim_photo (const char *filename, clim_photo_t *photo)
 Reads photolysis rates from a NetCDF file and populates the given photolysis structure.
 
void read_clim_photo_help (const int ncid, const char *varname, const clim_photo_t *photo, double var[CP][CSZA][CO3])
 Reads a 3D climatological photochemistry variable from a NetCDF file.
 
int read_clim_ts (const char *filename, clim_ts_t *ts)
 Reads a climatological time series from a file and populates the given time series structure.
 
void read_clim_zm (const char *filename, const char *varname, clim_zm_t *zm)
 Reads zonally averaged climatological data from a netCDF file and populates the given structure.
 
void read_kernel (const char *filename, double kz[EP], double kw[EP], int *nk)
 Reads kernel function data from a file and populates the provided arrays.
 
int read_met_bin (const char *filename, const ctl_t *ctl, met_t *met)
 Reads meteorological data from a binary file.
 
void read_met_bin_2d (FILE *in, const met_t *met, float var[EX][EY], const char *varname)
 Reads a 2-dimensional meteorological variable from a binary file and stores it in the provided array.
 
void read_met_bin_3d (FILE *in, const ctl_t *ctl, const met_t *met, float var[EX][EY][EP], const char *varname, const float bound_min, const float bound_max)
 Reads 3D meteorological data from a binary file, potentially using different compression methods.
 
void read_met_cape (const ctl_t *ctl, const clim_t *clim, met_t *met)
 Calculates Convective Available Potential Energy (CAPE) for each grid point.
 
void read_met_cloud (met_t *met)
 Calculates cloud-related variables for each grid point.
 
void read_met_detrend (const ctl_t *ctl, met_t *met)
 Detrends meteorological data.
 
void read_met_extrapolate (met_t *met)
 Extrapolates meteorological data.
 
void read_met_geopot (const ctl_t *ctl, met_t *met)
 Calculates geopotential heights from meteorological data.
 
int read_met_grib (const char *filename, const ctl_t *ctl, met_t *met)
 Reads meteorological data from a grib file and processes it.
 
void read_met_grib_grid (codes_handle **handles, int count_handles, met_t *met)
 Reads global meteorological information from a grib file.
 
void read_met_grib_levels (codes_handle **handles, const int num_messages, const ctl_t *ctl, met_t *met)
 Reads meteorological variables at different vertical levels from a grib file.
 
void read_met_grib_surface (codes_handle **handles, const int num_messages, const ctl_t *ctl, met_t *met)
 Reads surface meteorological data from a grib file and stores it in the meteorological data structure.
 
void read_met_ml2pl (const ctl_t *ctl, const met_t *met, float var[EX][EY][EP], const char *varname)
 Interpolates meteorological data to specified pressure levels.
 
void read_met_monotonize (const ctl_t *ctl, met_t *met)
 Makes zeta and pressure profiles monotone.
 
int read_met_nc (const char *filename, const ctl_t *ctl, met_t *met, dd_t *dd, int *pv_supplied)
 Reads meteorological data from a NetCDF file and processes it.
 
void read_met_nc_grid (const char *filename, const int ncid, const ctl_t *ctl, met_t *met, dd_t *dd)
 Reads meteorological grid data from NetCDF files with domain decomposition.
 
int read_met_nc_levels (const int ncid, const ctl_t *ctl, met_t *met, dd_t *dd)
 Reads and processes meteorological level data from NetCDF files with domain decomposition.
 
void read_met_nc_surface (const int ncid, const ctl_t *ctl, met_t *met, dd_t *dd)
 Reads and processes surface meteorological data from NetCDF files with domain decomposition.
 
int read_met_nc_2d (const int ncid, const char *const varnames[], const size_t nvarnames, const ctl_t *ctl, const met_t *met, dd_t *dd, float dest[EX][EY], const float scl, const int init)
 Reads a 2-dimensional meteorological variable from a NetCDF file.
 
int read_met_nc_3d (const int ncid, const char *const varnames[], const size_t nvarnames, const ctl_t *ctl, const met_t *met, dd_t *dd, float dest[EX][EY][EP], const float scl)
 Reads a 3-dimensional meteorological variable from a NetCDF file.
 
void read_met_pbl (const ctl_t *ctl, met_t *met)
 Computes the planetary boundary layer (PBL) pressure based on meteorological data.
 
void read_met_periodic (met_t *met)
 Applies periodic boundary conditions to meteorological data along longitudinal axis.
 
void read_met_polar_winds (met_t *met)
 Applies a fix for polar winds in meteorological data.
 
void read_met_pv (met_t *met)
 Calculates potential vorticity (PV) from meteorological data.
 
void read_met_ozone (met_t *met)
 Calculates the total column ozone from meteorological ozone data.
 
void read_met_sample (const ctl_t *ctl, met_t *met)
 Downsamples meteorological data based on specified parameters.
 
void read_met_tropo (const ctl_t *ctl, const clim_t *clim, met_t *met)
 Calculates the tropopause and related meteorological variables based on various methods and stores the results in the meteorological data structure.
 
void read_obs (const char *filename, const ctl_t *ctl, double *rt, double *rz, double *rlon, double *rlat, double *robs, int *nobs)
 Reads observation data from a file and stores it in arrays.
 
void read_obs_asc (const char *filename, double *rt, double *rz, double *rlon, double *rlat, double *robs, int *nobs)
 Reads observation data from an ASCII file.
 
void read_obs_nc (const char *filename, double *rt, double *rz, double *rlon, double *rlat, double *robs, int *nobs)
 Reads observation data from a NetCDF file.
 
double scan_ctl (const char *filename, int argc, char *argv[], const char *varname, const int arridx, const char *defvalue, char *value)
 Scans a control file or command-line arguments for a specified variable.
 
double sedi (const double p, const double T, const double rp, const double rhop)
 Calculates the sedimentation velocity of a particle in air.
 
void spline (const double *x, const double *y, const int n, const double *x2, double *y2, const int n2, const int method)
 Performs spline interpolation or linear interpolation.
 
void stats_welford_update (const double x, const double w, const double weight_old, double *mean, double *m2)
 Update a weighted mean and second central moment with one value.
 
float stddev (const float *data, const int n)
 Calculates the standard deviation of a set of data.
 
void time2jsec (const int year, const int mon, const int day, const int hour, const int min, const int sec, const double remain, double *jsec)
 Converts time components to seconds since January 1, 2000, 12:00:00 UTC.
 
void timer (const char *name, const char *group, const int output)
 Measures and reports elapsed time for named and grouped timers.
 
double time_from_filename (const char *filename, const int offset, const int with_seconds)
 Extracts and converts a timestamp from a filename to Julian seconds.
 
double tropo_weight (const ctl_t *ctl, const clim_t *clim, const atm_t *atm, const int ip)
 Computes a weighting factor based on tropopause pressure.
 
void write_atm_asc (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes air parcel data to an ASCII file or gnuplot.
 
void write_atm_bin (const char *filename, const ctl_t *ctl, const atm_t *atm)
 Writes air parcel data to a binary file.
 
void write_atm_clams (const char *filename, const ctl_t *ctl, const atm_t *atm)
 Writes air parcel data to a NetCDF file in the CLaMS format.
 
void write_atm_clams_traj (const char *dirname, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes CLaMS trajectory data to a NetCDF file.
 
void write_atm_nc (const char *filename, const ctl_t *ctl, const atm_t *atm)
 Writes air parcel data to a NetCDF file.
 
void write_budget (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes a time series of the atmospheric tracer mass budget.
 
void write_csi (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes Critical Success Index (CSI) data to a file.
 
void write_csi_ens (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes ensemble-based Critical Success Index (CSI) and other verification statistics to an output file.
 
void write_ens (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes ensemble data to a file.
 
void write_depo (const char *filename, const ctl_t *ctl, const depo_t *depo, const double t)
 Convert cumulative ground inventories to Bq m^-2 and write them.
 
void write_depo_asc (const char *filename, const ctl_t *ctl, const double *data, const double t, const double *lon, const double *lat, const double *area)
 Write radioactive deposition densities as a gnuplot-compatible table.
 
void write_depo_nc (const char *filename, const ctl_t *ctl, const double *data, const double t, const double *lon, const double *lat, const double *area)
 Write radioactive deposition densities as a CF-style netCDF file.
 
void write_grid (const char *filename, const ctl_t *ctl, met_t *met0, met_t *met1, const atm_t *atm, const double t)
 Writes grid data to a file in ASCII or netCDF format.
 
void write_grid_asc (const char *filename, const ctl_t *ctl, const double *cd, double *mean[NQ], double *sigma[NQ], const double *vmr_impl, const double t, const double *z, const double *lon, const double *lat, const double *area, const double dz, const int *np)
 Writes grid data to an ASCII file.
 
void write_grid_nc (const char *filename, const ctl_t *ctl, const double *cd, double *mean[NQ], double *sigma[NQ], const double *vmr_impl, const double t, const double *z, const double *lon, const double *lat, const double *area, const double dz, const int *np)
 Writes grid data to a NetCDF file.
 
void write_met_bin (const char *filename, const ctl_t *ctl, met_t *met)
 Writes meteorological data in binary format to a specified file.
 
void write_met_bin_2d (FILE *out, met_t *met, float var[EX][EY], const char *varname)
 Writes a 2-dimensional meteorological variable to a binary file.
 
void write_met_bin_3d (FILE *out, const ctl_t *ctl, met_t *met, float var[EX][EY][EP], const char *varname, const int metvar, FILE *level_log)
 Writes a 3-dimensional meteorological variable to a binary file.
 
void write_met_nc (const char *filename, const ctl_t *ctl, met_t *met)
 Writes meteorological data to a NetCDF file.
 
void write_met_nc_2d (const int ncid, const char *varname, met_t *met, float var[EX][EY], const float scl)
 Writes a 2D meteorological variable to a NetCDF file.
 
void write_met_nc_3d (const int ncid, const char *varname, met_t *met, float var[EX][EY][EP], const float scl)
 Writes a 3D meteorological variable to a NetCDF file.
 
void write_prof (const char *filename, const ctl_t *ctl, met_t *met0, met_t *met1, const atm_t *atm, const double t)
 Writes profile data to a specified file.
 
void write_sample (const char *filename, const ctl_t *ctl, met_t *met0, met_t *met1, const atm_t *atm, const double t)
 Writes sample data to a specified file.
 
void write_station (const char *filename, const ctl_t *ctl, atm_t *atm, const double t)
 Writes station data to a specified file.
 
void write_vtk (const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
 Writes VTK (Visualization Toolkit) data to a specified file.
 

Detailed Description

MPTRAC library declarations.

Definition in file mptrac.h.

Macro Definition Documentation

◆ codes_handle

#define codes_handle   void*

Placeholder when ECCODES is not available.

Definition at line 241 of file mptrac.h.

◆ AVO

#define AVO   6.02214076e23

Avogadro constant [1/mol].

Definition at line 250 of file mptrac.h.

◆ CPD

#define CPD   1003.5

Specific heat of dry air at constant pressure [J/(kg K)].

Definition at line 255 of file mptrac.h.

◆ EPS

#define EPS   (MH2O / MA)

Ratio of the specific gas constant of dry air and water vapor [1].

Definition at line 260 of file mptrac.h.

◆ G0

#define G0   9.80665

Standard gravity [m/s^2].

Definition at line 265 of file mptrac.h.

◆ H0

#define H0   7.0

Scale height [km].

Definition at line 270 of file mptrac.h.

◆ LV

#define LV   2501000.

Latent heat of vaporization of water [J/kg].

Definition at line 275 of file mptrac.h.

◆ KARMAN

#define KARMAN   0.40

Karman's constant.

Definition at line 280 of file mptrac.h.

◆ KB

#define KB   1.3806504e-23

Boltzmann constant [kg m^2/(K s^2)].

Definition at line 285 of file mptrac.h.

◆ MA

#define MA   28.9644

Molar mass of dry air [g/mol].

Definition at line 290 of file mptrac.h.

◆ MH2O

#define MH2O   18.01528

Molar mass of water vapor [g/mol].

Definition at line 295 of file mptrac.h.

◆ MO3

#define MO3   48.00

Molar mass of ozone [g/mol].

Definition at line 300 of file mptrac.h.

◆ P0

#define P0   1013.25

Standard pressure [hPa].

Definition at line 305 of file mptrac.h.

◆ RA

#define RA   (1e3 * RI / MA)

Specific gas constant of dry air [J/(kg K)].

Definition at line 310 of file mptrac.h.

◆ RE

#define RE   6367.421

Mean radius of Earth [km].

Definition at line 315 of file mptrac.h.

◆ RI

#define RI   8.3144598

Ideal gas constant [J/(mol K)].

Definition at line 320 of file mptrac.h.

◆ KAPPA

#define KAPPA   0.286

Exponent used for potential-temperature calculations [1].

Definition at line 325 of file mptrac.h.

◆ OMEGA_EARTH

#define OMEGA_EARTH   7.2921e-5

Angular velocity of Earth [s^-1].

Definition at line 330 of file mptrac.h.

◆ DOBSON_UNIT

#define DOBSON_UNIT   2.1415e-5

Ozone column mass corresponding to one Dobson unit [kg/m^2].

Definition at line 335 of file mptrac.h.

◆ M_AIR_MOLECULE

#define M_AIR_MOLECULE   4.8096e-26

Mean mass of an air molecule [kg].

Definition at line 340 of file mptrac.h.

◆ CHEM_REF_TEMP

#define CHEM_REF_TEMP   298.15

Reference temperature for chemical equilibrium constants [K].

Definition at line 345 of file mptrac.h.

◆ H2O2_SO2_RATE_REF

#define H2O2_SO2_RATE_REF   9.1e7

Reference rate for aqueous H2O2-SO2 chemistry [L^2/(mol^2 s)].

Definition at line 350 of file mptrac.h.

◆ H2O2_SO2_RATE_TEMP

#define H2O2_SO2_RATE_TEMP   29700.

Temperature parameter for the aqueous H2O2-SO2 rate [K].

Definition at line 355 of file mptrac.h.

◆ SO2_HENRY_REF

#define SO2_HENRY_REF   1.3e-2

SO2 Henry constant at CHEM_REF_TEMP [mol/(m^3 Pa)].

Definition at line 360 of file mptrac.h.

◆ SO2_HENRY_TEMP

#define SO2_HENRY_TEMP   2900.

Temperature dependence of the SO2 Henry constant [K].

Definition at line 365 of file mptrac.h.

◆ H2O2_HENRY_REF

#define H2O2_HENRY_REF   8.3e2

H2O2 Henry constant at CHEM_REF_TEMP [mol/(m^3 Pa)].

Definition at line 370 of file mptrac.h.

◆ H2O2_HENRY_TEMP

#define H2O2_HENRY_TEMP   7600.

Temperature dependence of the H2O2 Henry constant [K].

Definition at line 375 of file mptrac.h.

◆ SO2_CORR_A

#define SO2_CORR_A   3.12541941e-06

Scale factor of the high-SO2 correction for fractional SO2 mole fraction.

Definition at line 380 of file mptrac.h.

◆ SO2_CORR_B

#define SO2_CORR_B   -5.72532259e-01

Exponent of the high-SO2 correction [1].

Definition at line 385 of file mptrac.h.

◆ O1D_RATE_CCL4_A

#define O1D_RATE_CCL4_A   2.607e-10

O(1D) parent-destruction pre-factor for CCl4 [cm^3 molecule^-1 s^-1].

Definition at line 390 of file mptrac.h.

◆ O1D_RATE_CCL4_B

#define O1D_RATE_CCL4_B   0.

O(1D) reaction temperature parameter for CCl4 [K].

Definition at line 395 of file mptrac.h.

◆ O1D_RATE_CFC11_A

#define O1D_RATE_CFC11_A   2.070e-10

O(1D) parent-destruction pre-factor for CFC-11 [cm^3 molecule^-1 s^-1].

Definition at line 400 of file mptrac.h.

◆ O1D_RATE_CFC11_B

#define O1D_RATE_CFC11_B   0.

O(1D) reaction temperature parameter for CFC-11 [K].

Definition at line 405 of file mptrac.h.

◆ O1D_RATE_CFC12_A

#define O1D_RATE_CFC12_A   1.204e-10

O(1D) parent-destruction pre-factor for CFC-12 [cm^3 molecule^-1 s^-1].

Definition at line 410 of file mptrac.h.

◆ O1D_RATE_CFC12_B

#define O1D_RATE_CFC12_B   -25.

O(1D) reaction temperature parameter for CFC-12 [K].

Definition at line 415 of file mptrac.h.

◆ O1D_RATE_N2O_A

#define O1D_RATE_N2O_A   1.19e-10

O(1D) parent-destruction pre-factor for N2O [cm^3 molecule^-1 s^-1].

Definition at line 420 of file mptrac.h.

◆ O1D_RATE_N2O_B

#define O1D_RATE_N2O_B   -20.

O(1D) reaction temperature parameter for N2O [K].

Definition at line 425 of file mptrac.h.

◆ SO2_DISS_K1_REF

#define SO2_DISS_K1_REF   1.23e-2

First SO2 dissociation constant at CHEM_REF_TEMP [mol/L].

Definition at line 430 of file mptrac.h.

◆ SO2_DISS_K1_TEMP

#define SO2_DISS_K1_TEMP   2.01e3

Temperature dependence of the first SO2 dissociation constant [K].

Definition at line 435 of file mptrac.h.

◆ SO2_DISS_K2_REF

#define SO2_DISS_K2_REF   6e-8

Second SO2 dissociation constant at CHEM_REF_TEMP [mol/L].

Definition at line 440 of file mptrac.h.

◆ SO2_DISS_K2_TEMP

#define SO2_DISS_K2_TEMP   1.12e3

Temperature dependence of the second SO2 dissociation constant [K].

Definition at line 445 of file mptrac.h.

◆ WET_DEPO_T_LIQUID

#define WET_DEPO_T_LIQUID   T0

Upper temperature of the ice-cloud retention transition [K].

Definition at line 450 of file mptrac.h.

◆ WET_DEPO_T_ICE

#define WET_DEPO_T_ICE   238.15

Lower temperature of the ice-cloud retention transition [K].

Definition at line 455 of file mptrac.h.

◆ WET_DEPO_T_LIQUID_BC

#define WET_DEPO_T_LIQUID_BC   270.

Temperature threshold for below-cloud retention [K].

Definition at line 460 of file mptrac.h.

◆ RADIO_HALF_LIFE_RN222

#define RADIO_HALF_LIFE_RN222   (3.8235 * 86400.0)

Half-life of Rn-222 [s].

Definition at line 465 of file mptrac.h.

◆ RADIO_HALF_LIFE_PB210

#define RADIO_HALF_LIFE_PB210   (22.3 * 365.25 * 86400.0)

Half-life of Pb-210 [s].

Definition at line 470 of file mptrac.h.

◆ RADIO_HALF_LIFE_BE7

#define RADIO_HALF_LIFE_BE7   (53.22 * 86400.0)

Half-life of Be-7 [s].

Definition at line 475 of file mptrac.h.

◆ RADIO_HALF_LIFE_CS137

#define RADIO_HALF_LIFE_CS137   (30.05 * 365.25 * 86400.0)

Half-life of Cs-137 [s].

Definition at line 480 of file mptrac.h.

◆ RADIO_HALF_LIFE_I131

#define RADIO_HALF_LIFE_I131   (8.02 * 86400.0)

Half-life of I-131 [s].

Definition at line 485 of file mptrac.h.

◆ RADIO_HALF_LIFE_XE133

#define RADIO_HALF_LIFE_XE133   (5.2474 * 86400.0)

Half-life of Xe-133 [s].

Definition at line 490 of file mptrac.h.

◆ RADIO_DRY_VDEP_PB210

#define RADIO_DRY_VDEP_PB210   0.002

Dry deposition velocity of Pb-210 [m/s].

Definition at line 495 of file mptrac.h.

◆ RADIO_DRY_VDEP_BE7

#define RADIO_DRY_VDEP_BE7   0.001

Dry deposition velocity of Be-7 [m/s].

Definition at line 500 of file mptrac.h.

◆ RADIO_DRY_VDEP_CS137

#define RADIO_DRY_VDEP_CS137   0.002

Dry deposition velocity of Cs-137 [m/s].

Definition at line 505 of file mptrac.h.

◆ RADIO_DRY_VDEP_I131

#define RADIO_DRY_VDEP_I131   0.0005

Dry deposition velocity of aerosol-bound I-131 [m/s].

Definition at line 510 of file mptrac.h.

◆ RADIO_WET_COEFF_PB210

#define RADIO_WET_COEFF_PB210   1e-4

Wet deposition coefficient of Pb-210 [s^-1 (mm h^-1)^-1].

Definition at line 515 of file mptrac.h.

◆ RADIO_WET_COEFF_BE7

#define RADIO_WET_COEFF_BE7   5e-5

Wet deposition coefficient of Be-7 [s^-1 (mm h^-1)^-1].

Definition at line 520 of file mptrac.h.

◆ RADIO_WET_COEFF_CS137

#define RADIO_WET_COEFF_CS137   1e-4

Wet deposition coefficient of Cs-137 [s^-1 (mm h^-1)^-1].

Definition at line 525 of file mptrac.h.

◆ RADIO_WET_COEFF_I131

#define RADIO_WET_COEFF_I131   5e-5

Wet deposition coefficient of aerosol-bound I-131 [s^-1 (mm h^-1)^-1].

Definition at line 530 of file mptrac.h.

◆ T0

#define T0   273.15

Standard temperature [K].

Definition at line 535 of file mptrac.h.

◆ EP

#define EP   140

Maximum number of pressure levels for meteo data.

Definition at line 544 of file mptrac.h.

◆ EX

#define EX   1444

Maximum number of longitudes for meteo data.

Definition at line 549 of file mptrac.h.

◆ EY

#define EY   724

Maximum number of latitudes for meteo data.

Definition at line 554 of file mptrac.h.

◆ LEN

#define LEN   5000

Maximum length of ASCII data lines.

Definition at line 559 of file mptrac.h.

◆ METVAR

#define METVAR   13

Number of 3-D meteorological variables.

Definition at line 564 of file mptrac.h.

◆ NP

#define NP   10000000

Maximum number of atmospheric data points.

Definition at line 569 of file mptrac.h.

◆ NQ

#define NQ   15

Maximum number of quantities per data point.

Definition at line 574 of file mptrac.h.

◆ NCSI

#define NCSI   1000000

Maximum number of data points for CSI calculation.

Definition at line 579 of file mptrac.h.

◆ NENS

#define NENS   2000

Maximum number of data points for ensemble analysis.

Definition at line 584 of file mptrac.h.

◆ NOBS

#define NOBS   10000000

Maximum number of observation data points.

Definition at line 589 of file mptrac.h.

◆ NTHREADS

#define NTHREADS   512

Maximum number of OpenMP threads.

Definition at line 594 of file mptrac.h.

◆ CY

#define CY   250

Maximum number of latitudes for climatological data.

Definition at line 599 of file mptrac.h.

◆ CO3

#define CO3   30

Maximum number of total column ozone data for climatological data.

Definition at line 604 of file mptrac.h.

◆ CP

#define CP   70

Maximum number of pressure levels for climatological data.

Definition at line 609 of file mptrac.h.

◆ CSZA

#define CSZA   50

Maximum number of solar zenith angles for climatological data.

Definition at line 614 of file mptrac.h.

◆ CT

#define CT   12

Maximum number of time steps for climatological data.

Definition at line 619 of file mptrac.h.

◆ CTS

#define CTS   1000

Maximum number of data points of climatological time series.

Definition at line 624 of file mptrac.h.

◆ DD_EX_GLOB

#define DD_EX_GLOB   (EX * 16)

Maximum number of longitudes of global meteo data.

Definition at line 629 of file mptrac.h.

◆ DD_EY_GLOB

#define DD_EY_GLOB   (EY * 16)

Maximum number of latitudes of global meteo data.

Definition at line 634 of file mptrac.h.

◆ ALLOC

#define ALLOC ( ptr,
type,
n )
Value:
do { \
if (((ptr) = calloc((size_t)(n), sizeof(type))) == NULL) \
ERRMSG("Out of memory!"); \
} while (0)

Allocate memory for a pointer with error handling.

This macro allocates memory for a pointer of a given type and size using the calloc function. It includes error handling to check if memory allocation was successful. If the code is being compiled with OpenACC support (_OPENACC macro defined), it additionally checks if the code is running on a GPU device, and if not, it raises an error.

Parameters
ptrPointer variable to be allocated.
typeData type of the pointer.
nNumber of elements to allocate memory for.
Note
If the code is compiled without OpenACC support, the conditional check for GPU device is skipped.
Author
Lars Hoffmann

Definition at line 668 of file mptrac.h.

668#define ALLOC(ptr, type, n) do { \
669 if (((ptr) = calloc((size_t)(n), sizeof(type))) == NULL) \
670 ERRMSG("Out of memory!"); \
671 } while (0)

◆ ARRAY_2D

#define ARRAY_2D ( ix,
iy,
ny )
Value:
((ix) * (ny) + (iy))

Macro for computing the linear index of a 2D array element.

The ARRAY_2D macro computes the linear index of a 2D array element based on the specified row index (ix), column index (iy), and number of columns (ny).

Parameters
ixInteger representing the row index of the 2D array element.
iyInteger representing the column index of the 2D array element.
nyInteger representing the number of columns in the 2D array.
Returns
The computed linear index of the 2D array element.

The macro computes the linear index using the formula: (ix) * (ny) + (iy). This formula assumes row-major storage, where elements of each row are stored sequentially in memory.

Author
Lars Hoffmann

Definition at line 692 of file mptrac.h.

692#define ARRAY_2D(ix, iy, ny) \
693 ((ix) * (ny) + (iy))

◆ ARRAY_3D

#define ARRAY_3D ( ix,
iy,
ny,
iz,
nz )
Value:
(((ix)*(ny) + (iy)) * (nz) + (iz))

Compute the linear index of a 3D array element.

This macro computes the linear index of a 3D array element based on the specified row index (ix), column index (iy), depth index (iz), number of columns (ny), and number of depths (nz).

Parameters
ixRow index of the 3D array element.
iyColumn index of the 3D array element.
nyNumber of columns in the 3D array.
izDepth index of the 3D array element.
nzNumber of depths in the 3D array.
Returns
Linear index of the 3D array element.
Author
Lars Hoffmann

Definition at line 711 of file mptrac.h.

711#define ARRAY_3D(ix, iy, ny, iz, nz) \
712 (((ix)*(ny) + (iy)) * (nz) + (iz))

◆ ARRHENIUS

#define ARRHENIUS ( a,
b,
t )
Value:
((a) * exp( -(b) / (t)))

Calculate the Arrhenius rate constant.

The Arrhenius equation is commonly used in chemical kinetics to describe the temperature dependence of reaction rates. This macro calculates the rate constant (k) based on the Arrhenius equation:

\[ k = a \times \exp( -b / T ), \]

where:

  • k is the rate constant.
  • a is the pre-exponential factor or frequency factor.
  • b is the activation energy.
  • T is the temperature in Kelvin.
Parameters
aPre-exponential factor or frequency factor.
bActivation energy.
tTemperature in Kelvin.
Returns
Calculated rate constant based on the Arrhenius equation.
Author
Mingzhao Liu

Definition at line 736 of file mptrac.h.

736#define ARRHENIUS(a, b, t) \
737 ((a) * exp( -(b) / (t)))

◆ CLAMP

#define CLAMP ( v,
lo,
hi )
Value:
(((v) < (lo)) ? (lo) : (((v) > (hi)) ? (hi) : (v)))

Clamp a value to a specified range.

Ensures that v lies between lo and hi. If v < lo, returns lo. If v > hi, returns hi. Otherwise, returns v unchanged.

This macro works with any numeric type (e.g., int, float, double). All arguments are evaluated exactly once — avoid passing expressions with side effects (e.g., ++ operators or function calls).

Parameters
vInput value to clamp.
loLower bound.
hiUpper bound.
Returns
The clamped value between lo and hi.
Author
Lars Hoffmann

Definition at line 758 of file mptrac.h.

758#define CLAMP(v, lo, hi) \
759 (((v) < (lo)) ? (lo) : (((v) > (hi)) ? (hi) : (v)))

◆ COMPRESS_SPEED

#define COMPRESS_SPEED ( nbytes,
dt )
Value:
((dt) > 0 ? ((double)(nbytes)) / ((dt) * 1024. * 1024.) : NAN)

Calculate compression throughput in MiB/s.

This helper converts a processed byte count and elapsed wall-clock time into a throughput value expressed in MiB/s.

Parameters
nbytesNumber of processed bytes.
dtElapsed time in seconds.
Returns
Throughput in MiB/s, or NAN if dt is not positive.
Author
Lars Hoffmann

Definition at line 773 of file mptrac.h.

773#define COMPRESS_SPEED(nbytes, dt) \
774 ((dt) > 0 ? ((double)(nbytes)) / ((dt) * 1024. * 1024.) : NAN)

◆ COMPRESS_RATIO

#define COMPRESS_RATIO ( raw_size,
stored_size )
Value:
((double) (raw_size) / (double) (stored_size))

Calculate the compression ratio from raw and stored byte counts.

Parameters
raw_sizeUncompressed payload size in bytes.
stored_sizeCompressed/stored payload size in bytes.
Returns
Compression ratio.
Author
Lars Hoffmann

Definition at line 785 of file mptrac.h.

785#define COMPRESS_RATIO(raw_size, stored_size) \
786 ((double) (raw_size) / (double) (stored_size))

◆ COMPRESS_BPV

#define COMPRESS_BPV ( n,
stored_size )
Value:
((8.0 * (double) (stored_size)) / (double) (n))

Calculate bits per value from stored size and element count.

Parameters
nNumber of stored values.
stored_sizeCompressed/stored payload size in bytes.
Returns
Bits per stored value.
Author
Lars Hoffmann

Definition at line 797 of file mptrac.h.

797#define COMPRESS_BPV(n, stored_size) \
798 ((8.0 * (double) (stored_size)) / (double) (n))

◆ DEG2DX

#define DEG2DX ( dlon,
lat )
Value:
(RE * DEG2RAD(dlon) * cos(DEG2RAD(lat)))
#define RE
Mean radius of Earth [km].
Definition mptrac.h:315
#define DEG2RAD(deg)
Converts degrees to radians.
Definition mptrac.h:859

Convert a longitude difference to a distance in the x-direction (east-west) at a specific latitude.

This macro calculates the distance in the x-direction (east-west) corresponding to a given longitude difference at a specific latitude using the formula:

\[ dx = dlon \times \pi \times RE / 180 times \cos(lat), \]

where:

  • dx is the distance in the x-direction (east-west).
  • dlon is the difference in longitudes in degrees.
  • RE is the Earth's radius.
  • lat is the latitude in degrees.
Parameters
dlonDifference in longitudes in degrees.
latLatitude in degrees.
Returns
Distance in the x-direction (east-west) corresponding to the given longitude difference at the specified latitude.
Author
Lars Hoffmann

Definition at line 821 of file mptrac.h.

821#define DEG2DX(dlon, lat) \
822 (RE * DEG2RAD(dlon) * cos(DEG2RAD(lat)))

◆ DEG2DY

#define DEG2DY ( dlat)
Value:
(RE * DEG2RAD(dlat))

Convert a latitude difference to a distance in the y-direction (north-south).

This macro calculates the distance in the y-direction (north-south) corresponding to a given latitude difference using the formula:

\[ dy = dlat \times \pi \times RE / 180, \]

where:

  • dy is the distance in the y-direction (north-south).
  • dlat is the difference in latitudes in degrees.
  • RE is the Earth's radius.
Parameters
dlatDifference in latitudes in degrees.
Returns
Distance in the y-direction (north-south) corresponding to the given latitude difference.
Author
Lars Hoffmann

Definition at line 842 of file mptrac.h.

842#define DEG2DY(dlat) \
843 (RE * DEG2RAD(dlat))

◆ DEG2RAD

#define DEG2RAD ( deg)
Value:
((deg) * (M_PI / 180.0))

Converts degrees to radians.

This macro converts an angle from degrees to radians using the formula: radians = degrees * (Ï€ / 180)

Parameters
degThe angle in degrees to be converted.
Returns
The angle in radians.
Note
This macro uses the M_PI constant from <math.h> for the value of π.
Author
Lars Hoffmann

Definition at line 859 of file mptrac.h.

859#define DEG2RAD(deg) \
860 ((deg) * (M_PI / 180.0))

◆ DP2DZ

#define DP2DZ ( dp,
p )
Value:
(- (dp) * H0 / (p))
#define H0
Scale height [km].
Definition mptrac.h:270

Convert a pressure difference to a height difference in the vertical direction.

This macro calculates the change in height (altitude) corresponding to a given pressure difference using the formula:

\[ dz = - (dp) \times H_0 / p \]

where:

  • dz is the change in height (altitude) in meters.
  • dp is the pressure difference in hPa.
  • H0 is a reference scale height in km.
  • p is the reference pressure in hPa.
Parameters
dpPressure difference in hPa.
pReference pressure in hPa.
Returns
Change in height (altitude) in kilometers corresponding to the given pressure difference.
Warning
Don't use this for large values of dp!
Author
Lars Hoffmann

Definition at line 884 of file mptrac.h.

884#define DP2DZ(dp, p) \
885 (- (dp) * H0 / (p))

◆ DX2DEG

#define DX2DEG ( dx,
lat )
Value:
(((lat) < -89.999 || (lat) > 89.999) ? 0 \
: (dx) * 180. / (M_PI * RE * cos(DEG2RAD(lat))))

Convert a distance in kilometers to degrees longitude at a given latitude.

This macro calculates the change in longitude in degrees corresponding to a given distance in kilometers at a specified latitude on the Earth's surface. It uses the formula:

\[ dlon = \frac{dx \times 180}{\pi \times RE \times \cos(lat)} \]

Parameters
dxDistance in kilometers.
latLatitude in degrees.
Returns
Change in longitude in degrees.
Note
The latitude must be in the range [-89.999, 89.999] degrees. Otherwise, the macro return value will be zero. This avoids issues with the singularities at the poles.
Author
Lars Hoffmann

Definition at line 906 of file mptrac.h.

906#define DX2DEG(dx, lat) \
907 (((lat) < -89.999 || (lat) > 89.999) ? 0 \
908 : (dx) * 180. / (M_PI * RE * cos(DEG2RAD(lat))))

◆ DY2DEG

#define DY2DEG ( dy)
Value:
((dy) * 180. / (M_PI * RE))

Convert a distance in kilometers to degrees latitude.

This macro calculates the change in latitude in degrees corresponding to a given distance in kilometers on the Earth's surface. It uses the formula:

\[ dlat = \frac{dy \times 180}{\pi \times RE} \]

Parameters
dyDistance in kilometers.
Returns
Change in latitude in degrees.
Author
Lars Hoffmann

Definition at line 924 of file mptrac.h.

924#define DY2DEG(dy) \
925 ((dy) * 180. / (M_PI * RE))

◆ DZ2DP

#define DZ2DP ( dz,
p )
Value:
(-(dz) * (p) / H0)

Convert a change in altitude to a change in pressure.

This macro calculates the change in pressure corresponding to a given change in altitude. It uses the hydrostatic equation:

\[ dp = -\left(dz \times \frac{p}{H_0}\right) \]

Parameters
dzChange in altitude in kilometers.
pCurrent pressure in hPa.
Returns
Change in pressure in hPa.
Warning
Don't use this for large values of dz!
Author
Lars Hoffmann

Definition at line 943 of file mptrac.h.

943#define DZ2DP(dz, p) \
944 (-(dz) * (p) / H0)

◆ DX2COORD

#define DX2COORD ( met,
dx,
lat )
Value:
(((met)->coord_type == 0)? DX2DEG((dx) / 1000.0, (lat)) : ((dx) ))
#define DX2DEG(dx, lat)
Convert a distance in kilometers to degrees longitude at a given latitude.
Definition mptrac.h:906

Convert a distance in meters to a coordinate value based on grid type.

This macro converts a distance in meters to either degrees longitude (for latitude/longitude grids) or keeps it as metres (for UTM grids), depending on the coordinate system type specified in the met_t structure.

For coord_type = 0 (latitude/longitude grid):

  • Converts meters to kilometers
  • Call DX2DEG() to convert to degrees

For coord_type = 1 (UTM grid):

  • Keeps input distance unchanged (in meters)
Parameters
metPointer to met_t structure containing coordinate system information.
dxDistance in meters to be converted.
latLatitude in degrees (used for degree conversion in lat/lon grids).
Returns
Coordinate value in either degrees longitude (for coord_type=0) or meters (for coord_type=1).
Author
Robin Brase

Definition at line 968 of file mptrac.h.

◆ DY2COORD

#define DY2COORD ( met,
dy )
Value:
(((met)->coord_type == 0)? DY2DEG((dy) / 1000.0) : ((dy) ))
#define DY2DEG(dy)
Convert a distance in kilometers to degrees latitude.
Definition mptrac.h:924

Convert a distance to coordinate value based on grid type.

This macro converts a distance in meters to either degrees latitude (for latitude/longitude grids) or keeps it as metres (for UTM grids), depending on the coordinate system type specified in the met_t structure.

For coord_type = 0 (latitude/longitude grid):

  • Converts meters to kilometers
  • Call DY2DEG() to convert to degrees

For coord_type = 1 (UTM grid):

  • Keeps input distance unchanged (in meters)
Parameters
metPointer to met_t structure containing coordinate system information.
dyDistance in meters to be converted.
Returns
Coordinate value in either degrees latitude (for coord_type=0) or meters (for coord_type=1).
Author
Robin Brase

Definition at line 991 of file mptrac.h.

◆ DIST

#define DIST ( a,
b )
Value:
sqrt(DIST2(a, b))
#define DIST2(a, b)
Calculate the squared Euclidean distance between two points in Cartesian coordinates.
Definition mptrac.h:1022

Calculate the distance between two points in Cartesian coordinates.

This macro calculates the Euclidean distance between two points in Cartesian coordinates. It uses the square root of the square of the distance obtained from the DIST2 macro.

Parameters
aCoordinates of the first point as an array of doubles.
bCoordinates of the second point as an array of doubles.
Returns
The distance between the two points.
Author
Lars Hoffmann

Definition at line 1006 of file mptrac.h.

1006#define DIST(a, b) \
1007 sqrt(DIST2(a, b))

◆ DIST2

#define DIST2 ( a,
b )
Value:
((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1])+(a[2]-b[2])*(a[2]-b[2]))

Calculate the squared Euclidean distance between two points in Cartesian coordinates.

This macro calculates the squared Euclidean distance between two points in Cartesian coordinates. It computes the sum of the squares of the differences of corresponding coordinates.

Parameters
aCoordinates of the first point as an array of doubles.
bCoordinates of the second point as an array of doubles.
Returns
The squared distance between the two points.
Author
Lars Hoffmann

Definition at line 1022 of file mptrac.h.

1022#define DIST2(a, b) \
1023 ((a[0]-b[0])*(a[0]-b[0])+(a[1]-b[1])*(a[1]-b[1])+(a[2]-b[2])*(a[2]-b[2]))

◆ DOTP

#define DOTP ( a,
b )
Value:
(a[0]*b[0]+a[1]*b[1]+a[2]*b[2])

Calculate the dot product of two vectors.

This macro computes the dot product of two vectors represented as arrays of doubles. It multiplies corresponding components of the vectors and sums the results.

Parameters
aThe first vector as an array of doubles.
bThe second vector as an array of doubles.
Returns
The dot product of the two vectors.
Author
Lars Hoffmann

Definition at line 1038 of file mptrac.h.

1038#define DOTP(a, b) \
1039 (a[0]*b[0]+a[1]*b[1]+a[2]*b[2])

◆ ECC

#define ECC ( cmd)
Value:
do { \
int ecc_result=(cmd); \
if(ecc_result!=0) \
ERRMSG("ECCODES error: %s", codes_get_error_message(ecc_result)); \
} while (0)

Execute an ECCODES command and check for errors.

This macro executes an ECCODES command and checks the result. If the result indicates an error, it prints the error message using ERRMSG.

Parameters
cmdECCODES command to execute.
Author
Nils Nobre Wittwer

Definition at line 1052 of file mptrac.h.

1052#define ECC(cmd) do { \
1053 int ecc_result=(cmd); \
1054 if(ecc_result!=0) \
1055 ERRMSG("ECCODES error: %s", codes_get_error_message(ecc_result)); \
1056 } while (0)

◆ ECC_READ_2D

#define ECC_READ_2D ( variable,
target,
scaling_factor,
found_flag )
Value:
do { \
if(strcmp(short_name, variable) == 0) { \
if ((found_flag) == 0) \
LOG(2, "Read 2-D variable: %s (GRIB)", variable); \
for (int ix = 0; ix < met->nx; ix++) \
for (int iy = 0; iy < met->ny; iy++) \
target[ix][iy] = (float)(values[iy * met->nx + ix] * scaling_factor); \
found_flag = 1; \
} \
} while (0)

Writes 2-D data from a grib message into the meteo struct.

This macro writes 2-D data from a one-dimensional grib message into the corresponding 2-D variable in the meteo struct.

Parameters
variableName of the current meteorological variable
targetPointer to the 2-D array in the meteo struct where the data will be stored.
scaling_factorScaling factor to apply to the data.
found_flagFlag to store, that the variable was found in the grib message.
Author
Nils Nobre Wittwer

Definition at line 1071 of file mptrac.h.

1071#define ECC_READ_2D(variable, target, scaling_factor, found_flag) do { \
1072 if(strcmp(short_name, variable) == 0) { \
1073 if ((found_flag) == 0) \
1074 LOG(2, "Read 2-D variable: %s (GRIB)", variable); \
1075 for (int ix = 0; ix < met->nx; ix++) \
1076 for (int iy = 0; iy < met->ny; iy++) \
1077 target[ix][iy] = (float)(values[iy * met->nx + ix] * scaling_factor); \
1078 found_flag = 1; \
1079 } \
1080 } while (0)

◆ ECC_READ_3D

#define ECC_READ_3D ( variable,
level,
target,
scaling_factor,
found_flag )
Value:
do { \
if(strcmp(short_name, variable) == 0) { \
if ((found_flag) == 0) \
LOG(2, "Read 3-D variable: %s (GRIB)", variable); \
for (int ix = 0; ix < met->nx; ix++) \
for (int iy = 0; iy < met->ny; iy++) \
target[ix][iy][level] = (float) (values[iy * met->nx + ix] * scaling_factor); \
found_flag += 1; \
} \
} while (0)

Writes 3D data from a grib message into the meteo struct.

This macro writes 3D data from a one-dimensional grib message into the corresponding 3D variable in the meteo struct.

Parameters
variableName of the current meteorological variable.
levelIndex of the vertical level in the 3D array where the data should be stored.
targetPointer to the 3D array in the meteo struct where the data will be stored.
scaling_factorScaling factor to apply to the data.
found_flagCounter to store, how many messages containing data for this variable have been read.
Author
Nils Nobre Wittwer

Definition at line 1096 of file mptrac.h.

1096#define ECC_READ_3D(variable, level, target, scaling_factor, found_flag) do { \
1097 if(strcmp(short_name, variable) == 0) { \
1098 if ((found_flag) == 0) \
1099 LOG(2, "Read 3-D variable: %s (GRIB)", variable); \
1100 for (int ix = 0; ix < met->nx; ix++) \
1101 for (int iy = 0; iy < met->ny; iy++) \
1102 target[ix][iy][level] = (float) (values[iy * met->nx + ix] * scaling_factor); \
1103 found_flag += 1; \
1104 } \
1105 } while (0)

◆ FMOD

#define FMOD ( x,
y )
Value:
((x) - (int) ((x) / (y)) * (y))

Calculate the floating-point remainder of dividing x by y.

This macro computes the floating-point remainder of dividing x by y. It calculates this remainder as x minus the integer part of (x / y) times y.

Parameters
xThe dividend.
yThe divisor.
Returns
The floating-point remainder of x divided by y.
Note
Macro has been added as a substitute when a GPU version of fmod() is missing.
Author
Lars Hoffmann

Definition at line 1123 of file mptrac.h.

1123#define FMOD(x, y) \
1124 ((x) - (int) ((x) / (y)) * (y))

◆ DT_ALIGNED

#define DT_ALIGNED ( dt,
dt_mod )
Value:
(isfinite(dt) && isfinite(dt_mod) && (dt_mod) > 0 && \
(dt) >= (dt_mod) && (dt) / (dt_mod) <= 0x1p52 && \
fabs((dt) / (dt_mod) - nearbyint((dt) / (dt_mod))) <= \
fmin(8 * DBL_EPSILON * ((dt) / (dt_mod)), 1e-8))

Definition at line 1127 of file mptrac.h.

1127#define DT_ALIGNED(dt, dt_mod) \
1128 (isfinite(dt) && isfinite(dt_mod) && (dt_mod) > 0 && \
1129 (dt) >= (dt_mod) && (dt) / (dt_mod) <= 0x1p52 && \
1130 fabs((dt) / (dt_mod) - nearbyint((dt) / (dt_mod))) <= \
1131 fmin(8 * DBL_EPSILON * ((dt) / (dt_mod)), 1e-8))

◆ OBS_TIME_WINDOW

#define OBS_TIME_WINDOW ( ctl,
t,
t0,
t1 )
Value:
do { \
(t0) = (t) - 0.5 * (ctl)->dt_mod; \
(t1) = (t) + 0.5 * (ctl)->dt_mod; \
const double remaining = (ctl)->direction * ((ctl)->t_stop - (t)); \
if (remaining > 0 && remaining < (ctl)->dt_mod) { \
const double boundary = 0.5 * ((t) + (ctl)->t_stop); \
if ((ctl)->direction > 0) (t1) = boundary; \
else (t0) = boundary; \
} else if ((t) == (ctl)->t_stop) { \
const double remainder = fmod(fabs((ctl)->t_stop - (ctl)->t_start), \
(ctl)->dt_mod); \
if (remainder > 0 && remainder < (ctl)->dt_mod) { \
const double boundary = (t) - 0.5 * (ctl)->direction * remainder; \
if ((ctl)->direction > 0) (t0) = boundary; \
else (t1) = boundary; \
} \
} \
} while (0)

Set the half-open observation window for a model output time.

The window is centered on the output time with width DT_MOD. If the final model step is shorter, adjacent windows meet at the midpoint of that step so an observation cannot belong to both output times. The output bounds are in seconds since 2000-01-01 UTC and select times in [t0, t1). Arguments must be side-effect-free because the macro evaluates them more than once; t0 and t1 must be writable variables.

Parameters
ctlPointer to the model control settings.
tCurrent model output time in seconds since 2000-01-01 UTC.
t0Variable receiving the lower observation-time bound.
t1Variable receiving the upper observation-time bound.
Author
OpenAI Codex

Definition at line 1150 of file mptrac.h.

1150#define OBS_TIME_WINDOW(ctl, t, t0, t1) do { \
1151 (t0) = (t) - 0.5 * (ctl)->dt_mod; \
1152 (t1) = (t) + 0.5 * (ctl)->dt_mod; \
1153 const double remaining = (ctl)->direction * ((ctl)->t_stop - (t)); \
1154 if (remaining > 0 && remaining < (ctl)->dt_mod) { \
1155 const double boundary = 0.5 * ((t) + (ctl)->t_stop); \
1156 if ((ctl)->direction > 0) (t1) = boundary; \
1157 else (t0) = boundary; \
1158 } else if ((t) == (ctl)->t_stop) { \
1159 const double remainder = fmod(fabs((ctl)->t_stop - (ctl)->t_start), \
1160 (ctl)->dt_mod); \
1161 if (remainder > 0 && remainder < (ctl)->dt_mod) { \
1162 const double boundary = (t) - 0.5 * (ctl)->direction * remainder; \
1163 if ((ctl)->direction > 0) (t0) = boundary; \
1164 else (t1) = boundary; \
1165 } \
1166 } \
1167 } while (0)

◆ FREAD

#define FREAD ( ptr,
type,
size,
in )
Value:
do { \
if(fread(ptr, sizeof(type), size, in)!=size) \
ERRMSG("Error while reading!"); \
} while (0)
int size
Definition mptrac.c:11234

Read data from a file stream and store it in memory.

This macro reads data of a specified type from the given input file stream and stores it in the specified memory location. It ensures that the correct amount of data is read from the file stream, and if not, it raises an error.

Parameters
ptrPointer to the memory location where the data will be stored.
typeType of the data elements to be read.
sizeNumber of elements to read.
inFile stream from which to read the data.
Author
Lars Hoffmann

Definition at line 1184 of file mptrac.h.

1184#define FREAD(ptr, type, size, in) do { \
1185 if(fread(ptr, sizeof(type), size, in)!=size) \
1186 ERRMSG("Error while reading!"); \
1187 } while (0)

◆ FWRITE

#define FWRITE ( ptr,
type,
size,
out )
Value:
do { \
if(fwrite(ptr, sizeof(type), size, out)!=size) \
ERRMSG("Error while writing!"); \
} while (0)

Write data from memory to a file stream.

This macro writes data of a specified type from the specified memory location to the given output file stream. It ensures that the correct amount of data is written to the file stream, and if not, it raises an error.

Parameters
ptrPointer to the memory location containing the data to be written.
typeType of the data elements to be written.
sizeNumber of elements to write.
outFile stream to which the data will be written.
Author
Lars Hoffmann

Definition at line 1204 of file mptrac.h.

1204#define FWRITE(ptr, type, size, out) do { \
1205 if(fwrite(ptr, sizeof(type), size, out)!=size) \
1206 ERRMSG("Error while writing!"); \
1207 } while (0)

◆ INTPOL_INIT

#define INTPOL_INIT    double cw[4] = {0.0, 0.0, 0.0, 0.0}; int ci[3] = {0, 0, 0};

Initialize arrays for interpolation.

This macro initializes arrays used for interpolation. It sets the weights cw and indices ci to zero. These arrays are used during interpolation to store the interpolation weights and indices.

Author
Lars Hoffmann

Definition at line 1219 of file mptrac.h.

1219#define INTPOL_INIT \
1220 double cw[4] = {0.0, 0.0, 0.0, 0.0}; int ci[3] = {0, 0, 0};

◆ INTPOL_2D

#define INTPOL_2D ( var,
init )
Value:
do { \
intpol_met_time_2d(met0, met0->var, met1, met1->var, \
atm->time[ip], atm->lon[ip], atm->lat[ip], \
&var, ci, cw, init); \
} while (0)

Perform 2D interpolation for a meteorological variable.

This macro performs 2D interpolation for a given meteorological variable at a specific time and location.

Parameters
varThe variable to interpolate.
initA flag indicating whether to initialize the interpolation arrays (cw and ci). Set to 1 for initialization, 0 otherwise.
Returns
The interpolated value of the variable var.
Author
Lars Hoffmann

Definition at line 1233 of file mptrac.h.

1233#define INTPOL_2D(var, init) do { \
1234 intpol_met_time_2d(met0, met0->var, met1, met1->var, \
1235 atm->time[ip], atm->lon[ip], atm->lat[ip], \
1236 &var, ci, cw, init); \
1237 } while (0)

◆ INTPOL_3D

#define INTPOL_3D ( var,
init )
Value:
do { \
intpol_met_time_3d(met0, met0->var, met1, met1->var, \
atm->time[ip], atm->p[ip], \
atm->lon[ip], atm->lat[ip], \
&var, ci, cw, init); \
} while (0)

Perform 3D interpolation for a meteorological variable.

This macro performs 3D interpolation for a given meteorological variable at a specific time, pressure level, and location.

Parameters
varThe variable to interpolate.
initA flag indicating whether to initialize the interpolation arrays (cw and ci). Set to 1 for initialization, 0 otherwise.
Returns
The interpolated value of the variable var.
Author
Lars Hoffmann

Definition at line 1251 of file mptrac.h.

1251#define INTPOL_3D(var, init) do { \
1252 intpol_met_time_3d(met0, met0->var, met1, met1->var, \
1253 atm->time[ip], atm->p[ip], \
1254 atm->lon[ip], atm->lat[ip], \
1255 &var, ci, cw, init); \
1256 } while (0)

◆ INTPOL_SPACE_ALL

#define INTPOL_SPACE_ALL ( p,
lon,
lat )

Interpolate multiple meteorological variables in space.

This macro performs spatial interpolation for multiple meteorological variables at a given pressure level, longitude, and latitude.

Parameters
pThe pressure level at which to interpolate the variables.
lonThe longitude at which to interpolate the variables.
latThe latitude at which to interpolate the variables.
Author
Lars Hofmann

Definition at line 1271 of file mptrac.h.

1271#define INTPOL_SPACE_ALL(p, lon, lat) do { \
1272 intpol_met_space_3d(met, met->z, p, lon, lat, &z, ci, cw, 1); \
1273 intpol_met_space_3d(met, met->t, p, lon, lat, &t, ci, cw, 0); \
1274 intpol_met_space_3d(met, met->u, p, lon, lat, &u, ci, cw, 0); \
1275 intpol_met_space_3d(met, met->v, p, lon, lat, &v, ci, cw, 0); \
1276 intpol_met_space_3d(met, met->w, p, lon, lat, &w, ci, cw, 0); \
1277 intpol_met_space_3d(met, met->pv, p, lon, lat, &pv, ci, cw, 0); \
1278 intpol_met_space_3d(met, met->h2o, p, lon, lat, &h2o, ci, cw, 0); \
1279 intpol_met_space_3d(met, met->o3, p, lon, lat, &o3, ci, cw, 0); \
1280 intpol_met_space_3d(met, met->lwc, p, lon, lat, &lwc, ci, cw, 0); \
1281 intpol_met_space_3d(met, met->rwc, p, lon, lat, &rwc, ci, cw, 0); \
1282 intpol_met_space_3d(met, met->iwc, p, lon, lat, &iwc, ci, cw, 0); \
1283 intpol_met_space_3d(met, met->swc, p, lon, lat, &swc, ci, cw, 0); \
1284 intpol_met_space_3d(met, met->cc, p, lon, lat, &cc, ci, cw, 0); \
1285 intpol_met_space_2d(met, met->ps, lon, lat, &ps, ci, cw, 0); \
1286 intpol_met_space_2d(met, met->ts, lon, lat, &ts, ci, cw, 0); \
1287 intpol_met_space_2d(met, met->zs, lon, lat, &zs, ci, cw, 0); \
1288 intpol_met_space_2d(met, met->us, lon, lat, &us, ci, cw, 0); \
1289 intpol_met_space_2d(met, met->vs, lon, lat, &vs, ci, cw, 0); \
1290 intpol_met_space_2d(met, met->ess, ess, lat, &ess, ci, cw, 0); \
1291 intpol_met_space_2d(met, met->nss, nss, lat, &nss, ci, cw, 0); \
1292 intpol_met_space_2d(met, met->shf, shf, lat, &shf, ci, cw, 0); \
1293 intpol_met_space_2d(met, met->lsm, lon, lat, &lsm, ci, cw, 0); \
1294 intpol_met_space_2d(met, met->sst, lon, lat, &sst, ci, cw, 0); \
1295 intpol_met_space_2d(met, met->pbl, lon, lat, &pbl, ci, cw, 0); \
1296 intpol_met_space_2d(met, met->pt, lon, lat, &pt, ci, cw, 0); \
1297 intpol_met_space_2d(met, met->tt, lon, lat, &tt, ci, cw, 0); \
1298 intpol_met_space_2d(met, met->zt, lon, lat, &zt, ci, cw, 0); \
1299 intpol_met_space_2d(met, met->h2ot, lon, lat, &h2ot, ci, cw, 0); \
1300 intpol_met_space_2d(met, met->pct, lon, lat, &pct, ci, cw, 0); \
1301 intpol_met_space_2d(met, met->pcb, lon, lat, &pcb, ci, cw, 0); \
1302 intpol_met_space_2d(met, met->cl, lon, lat, &cl, ci, cw, 0); \
1303 intpol_met_space_2d(met, met->plcl, lon, lat, &plcl, ci, cw, 0); \
1304 intpol_met_space_2d(met, met->plfc, lon, lat, &plfc, ci, cw, 0); \
1305 intpol_met_space_2d(met, met->pel, lon, lat, &pel, ci, cw, 0); \
1306 intpol_met_space_2d(met, met->cape, lon, lat, &cape, ci, cw, 0); \
1307 intpol_met_space_2d(met, met->cin, lon, lat, &cin, ci, cw, 0); \
1308 intpol_met_space_2d(met, met->o3c, lon, lat, &o3c, ci, cw, 0); \
1309 } while (0)

◆ INTPOL_TIME_ALL

#define INTPOL_TIME_ALL ( time,
p,
lon,
lat )

Interpolate multiple meteorological variables in time.

This macro performs temporal interpolation for multiple meteorological variables at a given time, pressure level, longitude, and latitude.

Parameters
timeThe time at which to interpolate the variables.
pThe pressure level at which to interpolate the variables.
lonThe longitude at which to interpolate the variables.
latThe latitude at which to interpolate the variables.
Author
Lars Hoffmann

Definition at line 1325 of file mptrac.h.

1325#define INTPOL_TIME_ALL(time, p, lon, lat) do { \
1326 intpol_met_time_3d(met0, met0->z, met1, met1->z, time, p, lon, lat, &z, ci, cw, 1); \
1327 intpol_met_time_3d(met0, met0->t, met1, met1->t, time, p, lon, lat, &t, ci, cw, 0); \
1328 intpol_met_time_3d(met0, met0->u, met1, met1->u, time, p, lon, lat, &u, ci, cw, 0); \
1329 intpol_met_time_3d(met0, met0->v, met1, met1->v, time, p, lon, lat, &v, ci, cw, 0); \
1330 intpol_met_time_3d(met0, met0->w, met1, met1->w, time, p, lon, lat, &w, ci, cw, 0); \
1331 intpol_met_time_3d(met0, met0->pv, met1, met1->pv, time, p, lon, lat, &pv, ci, cw, 0); \
1332 intpol_met_time_3d(met0, met0->h2o, met1, met1->h2o, time, p, lon, lat, &h2o, ci, cw, 0); \
1333 intpol_met_time_3d(met0, met0->o3, met1, met1->o3, time, p, lon, lat, &o3, ci, cw, 0); \
1334 intpol_met_time_3d(met0, met0->lwc, met1, met1->lwc, time, p, lon, lat, &lwc, ci, cw, 0); \
1335 intpol_met_time_3d(met0, met0->rwc, met1, met1->rwc, time, p, lon, lat, &rwc, ci, cw, 0); \
1336 intpol_met_time_3d(met0, met0->iwc, met1, met1->iwc, time, p, lon, lat, &iwc, ci, cw, 0); \
1337 intpol_met_time_3d(met0, met0->swc, met1, met1->swc, time, p, lon, lat, &swc, ci, cw, 0); \
1338 intpol_met_time_3d(met0, met0->cc, met1, met1->cc, time, p, lon, lat, &cc, ci, cw, 0); \
1339 intpol_met_time_2d(met0, met0->ps, met1, met1->ps, time, lon, lat, &ps, ci, cw, 0); \
1340 intpol_met_time_2d(met0, met0->ts, met1, met1->ts, time, lon, lat, &ts, ci, cw, 0); \
1341 intpol_met_time_2d(met0, met0->zs, met1, met1->zs, time, lon, lat, &zs, ci, cw, 0); \
1342 intpol_met_time_2d(met0, met0->us, met1, met1->us, time, lon, lat, &us, ci, cw, 0); \
1343 intpol_met_time_2d(met0, met0->vs, met1, met1->vs, time, lon, lat, &vs, ci, cw, 0); \
1344 intpol_met_time_2d(met0, met0->ess, met1, met1->ess, time, lon, lat, &ess, ci, cw, 0); \
1345 intpol_met_time_2d(met0, met0->nss, met1, met1->nss, time, lon, lat, &nss, ci, cw, 0); \
1346 intpol_met_time_2d(met0, met0->shf, met1, met1->shf, time, lon, lat, &shf, ci, cw, 0); \
1347 intpol_met_time_2d(met0, met0->lsm, met1, met1->lsm, time, lon, lat, &lsm, ci, cw, 0); \
1348 intpol_met_time_2d(met0, met0->sst, met1, met1->sst, time, lon, lat, &sst, ci, cw, 0); \
1349 intpol_met_time_2d(met0, met0->pbl, met1, met1->pbl, time, lon, lat, &pbl, ci, cw, 0); \
1350 intpol_met_time_2d(met0, met0->pt, met1, met1->pt, time, lon, lat, &pt, ci, cw, 0); \
1351 intpol_met_time_2d(met0, met0->tt, met1, met1->tt, time, lon, lat, &tt, ci, cw, 0); \
1352 intpol_met_time_2d(met0, met0->zt, met1, met1->zt, time, lon, lat, &zt, ci, cw, 0); \
1353 intpol_met_time_2d(met0, met0->h2ot, met1, met1->h2ot, time, lon, lat, &h2ot, ci, cw, 0); \
1354 intpol_met_time_2d(met0, met0->pct, met1, met1->pct, time, lon, lat, &pct, ci, cw, 0); \
1355 intpol_met_time_2d(met0, met0->pcb, met1, met1->pcb, time, lon, lat, &pcb, ci, cw, 0); \
1356 intpol_met_time_2d(met0, met0->cl, met1, met1->cl, time, lon, lat, &cl, ci, cw, 0); \
1357 intpol_met_time_2d(met0, met0->plcl, met1, met1->plcl, time, lon, lat, &plcl, ci, cw, 0); \
1358 intpol_met_time_2d(met0, met0->plfc, met1, met1->plfc, time, lon, lat, &plfc, ci, cw, 0); \
1359 intpol_met_time_2d(met0, met0->pel, met1, met1->pel, time, lon, lat, &pel, ci, cw, 0); \
1360 intpol_met_time_2d(met0, met0->cape, met1, met1->cape, time, lon, lat, &cape, ci, cw, 0); \
1361 intpol_met_time_2d(met0, met0->cin, met1, met1->cin, time, lon, lat, &cin, ci, cw, 0); \
1362 intpol_met_time_2d(met0, met0->o3c, met1, met1->o3c, time, lon, lat, &o3c, ci, cw, 0); \
1363 } while (0)

◆ LAPSE

#define LAPSE ( p1,
t1,
p2,
t2 )
Value:
(1e3 * G0 / RA * ((t2) - (t1)) / ((t2) + (t1)) \
* ((p2) + (p1)) / ((p2) - (p1)))
#define RA
Specific gas constant of dry air [J/(kg K)].
Definition mptrac.h:310
#define G0
Standard gravity [m/s^2].
Definition mptrac.h:265

Calculate lapse rate.

This macro calculates the lapse rate between two pressure levels given their temperatures and pressures.

Parameters
p1Pressure at the first level (in hPa).
t1Temperature at the first level (in K).
p2Pressure at the second level (in hPa).
t2Temperature at the second level (in K).
Returns
The lapse rate (in K/km).
Author
Lars Hoffmann

Definition at line 1379 of file mptrac.h.

1379#define LAPSE(p1, t1, p2, t2) \
1380 (1e3 * G0 / RA * ((t2) - (t1)) / ((t2) + (t1)) \
1381 * ((p2) + (p1)) / ((p2) - (p1)))

◆ LIN

#define LIN ( x0,
y0,
x1,
y1,
x )
Value:
((y0)+((y1)-(y0))/((x1)-(x0))*((x)-(x0)))

Linear interpolation.

This macro performs linear interpolation to estimate the value of y at a given x based on two points (x0, y0) and (x1, y1).

Parameters
x0X-coordinate of the first point.
y0Y-coordinate of the first point.
x1X-coordinate of the second point.
y1Y-coordinate of the second point.
xThe x-coordinate at which to estimate the y-value.
Returns
The estimated y-value at the given x-coordinate.
Author
Lars Hoffmann

Definition at line 1398 of file mptrac.h.

1398#define LIN(x0, y0, x1, y1, x) \
1399 ((y0)+((y1)-(y0))/((x1)-(x0))*((x)-(x0)))

◆ MAX

#define MAX ( a,
b )
Value:
(((a)>(b))?(a):(b))

Macro to determine the maximum of two values.

This macro evaluates to the larger of its two arguments, a and b. It uses a ternary conditional operator to compare the values of a and b and returns a if a is greater than b; otherwise, it returns b.

Parameters
aThe first value to compare. Can be of any type that supports comparison.
bThe second value to compare. Can be of any type that supports comparison.
Returns
The larger of the two values, a or b.
Note
Both a and b are evaluated twice. If a or b have side effects (e.g., increment operators, function calls), the side effects will occur more than once. This can lead to unexpected behavior.
Warning
The macro does not perform type checking, so a and b should be of compatible types to avoid potential issues with comparison and return value.
Author
Lars Hoffmann

Definition at line 1425 of file mptrac.h.

1425#define MAX(a,b) \
1426 (((a)>(b))?(a):(b))

◆ MET_HEADER

#define MET_HEADER

Write header for meteorological data file.

This macro writes a header to a meteorological data file, providing information about the variables stored in the file and their corresponding columns.

Parameters
outPointer to the file stream where the header will be written.
Author
Lars Hoffmann

Definition at line 1439 of file mptrac.h.

1439#define MET_HEADER do { \
1440 fprintf(out, \
1441 "# $1 = time [s]\n" \
1442 "# $2 = altitude [km]\n" \
1443 "# $3 = longitude [deg]\n" \
1444 "# $4 = latitude [deg]\n" \
1445 "# $5 = pressure [hPa]\n" \
1446 "# $6 = temperature [K]\n" \
1447 "# $7 = zonal wind [m/s]\n" \
1448 "# $8 = meridional wind [m/s]\n" \
1449 "# $9 = vertical velocity [hPa/s]\n" \
1450 "# $10 = H2O volume mixing ratio [ppv]\n"); \
1451 fprintf(out, \
1452 "# $11 = O3 volume mixing ratio [ppv]\n" \
1453 "# $12 = geopotential height [km]\n" \
1454 "# $13 = potential vorticity [PVU]\n" \
1455 "# $14 = surface pressure [hPa]\n" \
1456 "# $15 = surface temperature [K]\n" \
1457 "# $16 = surface geopotential height [km]\n" \
1458 "# $17 = surface zonal wind [m/s]\n" \
1459 "# $18 = surface meridional wind [m/s]\n" \
1460 "# $19 = eastward turbulent surface stress [N/m^2]\n" \
1461 "# $20 = northward turbulent surface stress [N/m^2]\n"); \
1462 fprintf(out, \
1463 "# $21 = surface sensible heat flux [W/m^2]\n" \
1464 "# $22 = land-sea mask [1]\n" \
1465 "# $23 = sea surface temperature [K]\n" \
1466 "# $24 = tropopause pressure [hPa]\n" \
1467 "# $25 = tropopause geopotential height [km]\n" \
1468 "# $26 = tropopause temperature [K]\n" \
1469 "# $27 = tropopause water vapor [ppv]\n" \
1470 "# $28 = cloud liquid water content [kg/kg]\n" \
1471 "# $29 = cloud rain water content [kg/kg]\n" \
1472 "# $30 = cloud ice water content [kg/kg]\n"); \
1473 fprintf(out, \
1474 "# $31 = cloud snow water content [kg/kg]\n" \
1475 "# $32 = cloud cover [1]\n" \
1476 "# $33 = total column cloud water [kg/m^2]\n" \
1477 "# $34 = cloud top pressure [hPa]\n" \
1478 "# $35 = cloud bottom pressure [hPa]\n" \
1479 "# $36 = pressure at lifted condensation level (LCL) [hPa]\n" \
1480 "# $37 = pressure at level of free convection (LFC) [hPa]\n" \
1481 "# $38 = pressure at equilibrium level (EL) [hPa]\n" \
1482 "# $39 = convective available potential energy (CAPE) [J/kg]\n" \
1483 "# $40 = convective inhibition (CIN) [J/kg]\n"); \
1484 fprintf(out, \
1485 "# $41 = relative humidity over water [%%]\n" \
1486 "# $42 = relative humidity over ice [%%]\n" \
1487 "# $43 = dew point temperature [K]\n" \
1488 "# $44 = frost point temperature [K]\n" \
1489 "# $45 = NAT temperature [K]\n" \
1490 "# $46 = HNO3 volume mixing ratio [ppv]\n" \
1491 "# $47 = OH volume mixing ratio [ppv]\n" \
1492 "# $48 = H2O2 volume mixing ratio [ppv]\n" \
1493 "# $49 = HO2 volume mixing ratio [ppv]\n" \
1494 "# $50 = O(1D) volume mixing ratio [ppv]\n"); \
1495 fprintf(out, \
1496 "# $51 = boundary layer pressure [hPa]\n" \
1497 "# $52 = total column ozone [DU]\n" \
1498 "# $53 = number of data points\n" \
1499 "# $54 = number of tropopause data points\n" \
1500 "# $55 = number of CAPE data points\n"); \
1501 } while (0)

◆ MIN

#define MIN ( a,
b )
Value:
(((a)<(b))?(a):(b))

Macro to determine the minimum of two values.

This macro evaluates to the smaller of its two arguments, a and b. It uses a ternary conditional operator to compare the values of a and b and returns a if a is less than b; otherwise, it returns b.

Parameters
aThe first value to compare. Can be of any type that supports comparison.
bThe second value to compare. Can be of any type that supports comparison.
Returns
The smaller of the two values, a or b.
Note
Both a and b are evaluated twice. If a or b have side effects (e.g., increment operators, function calls), the side effects will occur more than once. This can lead to unexpected behavior.
Warning
The macro does not perform type checking, so a and b should be of compatible types to avoid potential issues with comparison and return value.
Author
Lars Hoffmann

Definition at line 1527 of file mptrac.h.

1527#define MIN(a,b) \
1528 (((a)<(b))?(a):(b))

◆ MOLEC_DENS

#define MOLEC_DENS ( p,
t )
Value:
(AVO * 1e-6 * ((p) * 100) / (RI * (t)))
#define AVO
Avogadro constant [1/mol].
Definition mptrac.h:250
#define RI
Ideal gas constant [J/(mol K)].
Definition mptrac.h:320

Calculate the molecular number density of air.

This macro calculates molecular number density from the ideal gas law.

Parameters
pAir pressure in hPa.
tAir temperature in K.
Returns
Air molecular number density in molecules/cm^3.
Author
Lars Hoffmann

Definition at line 1541 of file mptrac.h.

1541#define MOLEC_DENS(p,t) \
1542 (AVO * 1e-6 * ((p) * 100) / (RI * (t)))

◆ NC

#define NC ( cmd)
Value:
do { \
int nc_result=(cmd); \
if(nc_result!=NC_NOERR) \
ERRMSG("%s", nc_strerror(nc_result)); \
} while (0)

Execute a NetCDF command and check for errors.

This macro executes a NetCDF command and checks the result. If the result indicates an error, it prints the error message using ERRMSG.

Parameters
cmdNetCDF command to execute.
Author
Lars Hoffmann

Definition at line 1555 of file mptrac.h.

1555#define NC(cmd) do { \
1556 int nc_result=(cmd); \
1557 if(nc_result!=NC_NOERR) \
1558 ERRMSG("%s", nc_strerror(nc_result)); \
1559 } while (0)

◆ NC_DEF_VAR

#define NC_DEF_VAR ( varname,
type,
ndims,
dims,
long_name,
units,
level,
quant )
Value:
do { \
NC(nc_def_var(ncid, varname, type, ndims, dims, &varid)); \
NC(nc_put_att_text(ncid, varid, "long_name", strnlen(long_name, LEN), long_name)); \
NC(nc_put_att_text(ncid, varid, "units", strnlen(units, LEN), units)); \
NC_DEF_VAR_QUANTIZE(quant); \
if((level) != 0) { \
NC(nc_def_var_deflate(ncid, varid, 1, 1, level)); \
/* unsigned int ulevel = (unsigned int)level; */ \
/* NC(nc_def_var_filter(ncid, varid, 32015, 1, (unsigned int[]){ulevel})); */ \
} \
} while (0)
#define LEN
Maximum length of ASCII data lines.
Definition mptrac.h:559

Define a NetCDF variable with attributes.

This macro defines a NetCDF variable with the specified name, data type, dimensions, long name, and units. It also sets the long_name and units attributes for the variable. It enables compression and quantizatio of the data.

Parameters
varnameName of the variable.
typeData type of the variable.
ndimsNumber of dimensions for the variable.
dimsArray of dimension IDs.
long_nameLong name of the variable.
unitsUnits of the variable.
levelzlib compression level (0 = off).
quantNumber of digits for quantization (0 = off).
Note
To enable ZSTD compression, replace nc_def_var_deflate() by nc_def_var_filter() below. Use dynamic linking, static linking does not work. Set environment variable HDF5_PLUGIN_PATH to ./libs/build/share/netcdf-plugins/.
Author
Lars Hoffmann

Definition at line 1584 of file mptrac.h.

1584#define NC_DEF_VAR(varname, type, ndims, dims, long_name, units, level, quant) do { \
1585 NC(nc_def_var(ncid, varname, type, ndims, dims, &varid)); \
1586 NC(nc_put_att_text(ncid, varid, "long_name", strnlen(long_name, LEN), long_name)); \
1587 NC(nc_put_att_text(ncid, varid, "units", strnlen(units, LEN), units)); \
1588 NC_DEF_VAR_QUANTIZE(quant); \
1589 if((level) != 0) { \
1590 NC(nc_def_var_deflate(ncid, varid, 1, 1, level)); \
1591 /* unsigned int ulevel = (unsigned int)level; */ \
1592 /* NC(nc_def_var_filter(ncid, varid, 32015, 1, (unsigned int[]){ulevel})); */ \
1593 } \
1594 } while (0)

◆ NC_DEF_VAR_QUANTIZE

#define NC_DEF_VAR_QUANTIZE ( quant)
Value:
do { \
if((quant) > 0) \
ERRMSG("NetCDF quantization is not supported by this NetCDF version"); \
} while(0)

Definition at line 1602 of file mptrac.h.

1602#define NC_DEF_VAR_QUANTIZE(quant) do { \
1603 if((quant) > 0) \
1604 ERRMSG("NetCDF quantization is not supported by this NetCDF version"); \
1605 } while(0)

◆ NC_GET_DOUBLE

#define NC_GET_DOUBLE ( varname,
ptr,
force )
Value:
do { \
if(force) { \
NC(nc_inq_varid(ncid, varname, &varid)); \
NC(nc_get_var_double(ncid, varid, ptr)); \
} else { \
if(nc_inq_varid(ncid, varname, &varid) == NC_NOERR) { \
NC(nc_get_var_double(ncid, varid, ptr)); \
} else \
WARN("netCDF variable %s is missing!", varname); \
} \
} while (0)

Retrieve a double-precision variable from a NetCDF file.

This macro retrieves a double-precision variable from a NetCDF file. It first checks if the variable exists in the file and then reads its data into the specified pointer. If the force parameter is set to true, it forces the retrieval of the variable, raising an error if the variable does not exist. If force is false, it retrieves the variable if it exists and issues a warning if it does not.

Parameters
varnameName of the variable to retrieve.
ptrPointer to the memory location where the data will be stored.
forceBoolean flag indicating whether to force retrieval (true) or not (false).
Author
Lars Hoffmann

Definition at line 1625 of file mptrac.h.

1625#define NC_GET_DOUBLE(varname, ptr, force) do { \
1626 if(force) { \
1627 NC(nc_inq_varid(ncid, varname, &varid)); \
1628 NC(nc_get_var_double(ncid, varid, ptr)); \
1629 } else { \
1630 if(nc_inq_varid(ncid, varname, &varid) == NC_NOERR) { \
1631 NC(nc_get_var_double(ncid, varid, ptr)); \
1632 } else \
1633 WARN("netCDF variable %s is missing!", varname); \
1634 } \
1635 } while (0)

◆ NC_INQ_DIM

#define NC_INQ_DIM ( dimname,
ptr,
min,
max,
check )
Value:
do { \
int dimid; size_t naux; \
NC(nc_inq_dimid(ncid, dimname, &dimid)); \
NC(nc_inq_dimlen(ncid, dimid, &naux)); \
*ptr = (int)naux; \
if (check) \
if ((*ptr) < (min) || (*ptr) > (max)) \
ERRMSG("Dimension %s is out of range!", dimname); \
} while (0)

Inquire the length of a dimension in a NetCDF file.

This macro retrieves the length of a specified dimension from a NetCDF file. It checks if the length of the dimension is within a specified range and assigns the length to the provided pointer. If the length is outside the specified range, an error message is raised.

Parameters
dimnameName of the dimension to inquire.
ptrPointer to an integer where the dimension length will be stored.
minMinimum acceptable length for the dimension.
maxMaximum acceptable length for the dimension.
checkFlag to check bounds. Set to 1 for bounds check.
Author
Lars Hoffmann
Jan Clemens

Definition at line 1655 of file mptrac.h.

1655#define NC_INQ_DIM(dimname, ptr, min, max, check) do { \
1656 int dimid; size_t naux; \
1657 NC(nc_inq_dimid(ncid, dimname, &dimid)); \
1658 NC(nc_inq_dimlen(ncid, dimid, &naux)); \
1659 *ptr = (int)naux; \
1660 if (check) \
1661 if ((*ptr) < (min) || (*ptr) > (max)) \
1662 ERRMSG("Dimension %s is out of range!", dimname); \
1663 } while (0)

◆ NC_PUT_DOUBLE

#define NC_PUT_DOUBLE ( varname,
ptr,
hyperslab )
Value:
do { \
NC(nc_inq_varid(ncid, varname, &varid)); \
if(hyperslab) { \
NC(nc_put_vara_double(ncid, varid, start, count, ptr)); \
} else { \
NC(nc_put_var_double(ncid, varid, ptr)); \
} \
} while (0)

Write double precision data to a NetCDF variable.

This macro writes data to a specified NetCDF variable. It can handle both full variable writes and hyperslab writes depending on the hyperslab parameter. If hyperslab is true, the data is written as a hyperslab; otherwise, the entire variable is written.

Parameters
varnameName of the NetCDF variable to write to.
ptrPointer to the data to be written.
hyperslabBoolean indicating whether to write the data as a hyperslab.
Author
Lars Hoffmann

Definition at line 1679 of file mptrac.h.

1679#define NC_PUT_DOUBLE(varname, ptr, hyperslab) do { \
1680 NC(nc_inq_varid(ncid, varname, &varid)); \
1681 if(hyperslab) { \
1682 NC(nc_put_vara_double(ncid, varid, start, count, ptr)); \
1683 } else { \
1684 NC(nc_put_var_double(ncid, varid, ptr)); \
1685 } \
1686 } while (0)

◆ NC_PUT_FLOAT

#define NC_PUT_FLOAT ( varname,
ptr,
hyperslab )
Value:
do { \
NC(nc_inq_varid(ncid, varname, &varid)); \
if(hyperslab) { \
NC(nc_put_vara_float(ncid, varid, start, count, ptr)); \
} else { \
NC(nc_put_var_float(ncid, varid, ptr)); \
} \
} while (0)

Write a float array to a NetCDF file.

This macro writes a float array to a specified variable in a NetCDF file. Depending on the value of the hyperslab parameter, the data can be written as a hyperslab or as a whole variable.

Parameters
varnameName of the variable to which the float array will be written.
ptrPointer to the float array to be written.
hyperslabBoolean flag indicating if the data should be written as a hyperslab.
  • If true, the data will be written as a hyperslab using the start and count arrays.
  • If false, the data will be written to the entire variable.
Author
Lars Hoffmann

Definition at line 1703 of file mptrac.h.

1703#define NC_PUT_FLOAT(varname, ptr, hyperslab) do { \
1704 NC(nc_inq_varid(ncid, varname, &varid)); \
1705 if(hyperslab) { \
1706 NC(nc_put_vara_float(ncid, varid, start, count, ptr)); \
1707 } else { \
1708 NC(nc_put_var_float(ncid, varid, ptr)); \
1709 } \
1710 } while (0)

◆ NC_PUT_INT

#define NC_PUT_INT ( varname,
ptr,
hyperslab )
Value:
do { \
NC(nc_inq_varid(ncid, varname, &varid)); \
if(hyperslab) { \
NC(nc_put_vara_int(ncid, varid, start, count, ptr)); \
} else { \
NC(nc_put_var_int(ncid, varid, ptr)); \
} \
} while (0)

Write integer data to a NetCDF variable.

This macro writes data to a specified NetCDF variable. It can handle both full variable writes and hyperslab writes depending on the hyperslab parameter. If hyperslab is true, the data is written as a hyperslab; otherwise, the entire variable is written.

Parameters
varnameName of the NetCDF variable to write to.
ptrPointer to the data to be written.
hyperslabBoolean indicating whether to write the data as a hyperslab.
Author
Lars Hoffmann

Definition at line 1726 of file mptrac.h.

1726#define NC_PUT_INT(varname, ptr, hyperslab) do { \
1727 NC(nc_inq_varid(ncid, varname, &varid)); \
1728 if(hyperslab) { \
1729 NC(nc_put_vara_int(ncid, varid, start, count, ptr)); \
1730 } else { \
1731 NC(nc_put_var_int(ncid, varid, ptr)); \
1732 } \
1733 } while (0)

◆ NC_PUT_ATT

#define NC_PUT_ATT ( varname,
attname,
text )
Value:
do { \
NC(nc_inq_varid(ncid, varname, &varid)); \
NC(nc_put_att_text(ncid, varid, attname, strnlen(text, LEN), text)); \
} while (0)

Add a text attribute to a NetCDF variable.

This macro adds a text attribute to a specified NetCDF variable. It first retrieves the variable ID using its name, then it attaches the text attribute to the variable.

Parameters
varnameName of the NetCDF variable to which the attribute will be added.
attnameName of the attribute to be added.
textText of the attribute to be added.
Author
Lars Hoffmann

Definition at line 1748 of file mptrac.h.

1748#define NC_PUT_ATT(varname, attname, text) do { \
1749 NC(nc_inq_varid(ncid, varname, &varid)); \
1750 NC(nc_put_att_text(ncid, varid, attname, strnlen(text, LEN), text)); \
1751 } while (0)

◆ NC_PUT_ATT_GLOBAL

#define NC_PUT_ATT_GLOBAL ( attname,
text )
Value:
do { \
NC(nc_put_att_text(ncid, NC_GLOBAL, attname, strnlen(text, LEN), text)); \
} while (0)

Add a global text attribute to a NetCDF file.

This macro adds a text attribute to the global attributes of a NetCDF file. It directly attaches the attribute to the file, rather than to a specific variable.

Parameters
attnameName of the global attribute to be added.
textText of the attribute to be added.
Author
Lars Hoffmann

Definition at line 1765 of file mptrac.h.

1765#define NC_PUT_ATT_GLOBAL(attname, text) do { \
1766 NC(nc_put_att_text(ncid, NC_GLOBAL, attname, strnlen(text, LEN), text)); \
1767 } while (0)

◆ NN

#define NN ( x0,
y0,
x1,
y1,
x )
Value:
(fabs((x) - (x0)) <= fabs((x) - (x1)) ? (y0) : (y1))

Perform nearest-neighbor interpolation.

This macro returns the value of the nearest neighbor (y0 or y1) for a given x value. It compares the distances between x and x0, and between x and x1, and returns the y value corresponding to the closer x value.

Parameters
x0The x-coordinate of the first point.
y0The y-coordinate of the first point.
x1The x-coordinate of the second point.
y1The y-coordinate of the second point.
xThe x-coordinate for which the nearest neighbor is to be found.
Returns
The y-coordinate of the nearest neighbor (either y0 or y1).
Author
Lars Hoffmann

Definition at line 1786 of file mptrac.h.

1786#define NN(x0, y0, x1, y1, x) \
1787 (fabs((x) - (x0)) <= fabs((x) - (x1)) ? (y0) : (y1))

◆ PARTICLE_LOOP

#define PARTICLE_LOOP ( ip0,
ip1,
check_dt,
... )
Value:
const int ip0_const = ip0; \
const int ip1_const = ip1; \
_Pragma("omp parallel for default(shared)") \
for (int ip = ip0_const; ip < ip1_const; ip++) \
if (!check_dt || cache->dt[ip] != 0)

Loop over particle indices with OpenACC acceleration.

This macro defines a loop over particle indices from ip0 to ip1 with optional checking of dt. If _OPENACC is defined, the loop is accelerated using OpenACC directives. Otherwise, OpenMP parallelization is used.

Parameters
ip0The starting index of the loop (inclusive).
ip1The ending index of the loop (exclusive).
check_dtFlag indicating whether to check the array dt for non-zero values.
...Optional pragma directives to be applied.
Author
Lars Hoffmann

Definition at line 1813 of file mptrac.h.

1813#define PARTICLE_LOOP(ip0, ip1, check_dt, ...) \
1814 const int ip0_const = ip0; \
1815 const int ip1_const = ip1; \
1816 _Pragma("omp parallel for default(shared)") \
1817 for (int ip = ip0_const; ip < ip1_const; ip++) \
1818 if (!check_dt || cache->dt[ip] != 0)

◆ P

#define P ( z)
Value:
(P0 * exp(-(z) / H0))
#define P0
Standard pressure [hPa].
Definition mptrac.h:305

Compute pressure at given altitude.

This macro calculates the pressure at a given altitude using the barometric formula.

Parameters
zThe altitude in kilometers.
Returns
The pressure in hPa at the given altitude.

The barometric formula used for this calculation is:

\[ P(z) = P_0 \times e^{-(z / H_0)}, \]

where:

  • \( P(z) \) is the pressure at altitude \( z \),
  • \( P_0 \) is the standard pressure,
  • \( H_0 \) is the scale height.
Note
The constants \( P_0 \) and \( H_0 \) must be defined before using this macro.
Author
Lars Hoffmann

Definition at line 1843 of file mptrac.h.

1843#define P(z) \
1844 (P0 * exp(-(z) / H0))

◆ PSAT

#define PSAT ( t)
Value:
(6.112 * exp(17.62 * ((t) - T0) / (243.12 + (t) - T0)))
#define T0
Standard temperature [K].
Definition mptrac.h:535

Compute saturation pressure over water.

This macro calculates the saturation pressure over water based on the WMO (2018) formula.

Parameters
tThe temperature in degrees Celsius.
Returns
The saturation pressure over water at the given temperature.

The saturation pressure over water is calculated using the formula:

\[ P_{\textrm{sat}}(t) = 6.112 \times e^{17.62 \times \frac{(t - T_0)}{243.12 + (t - T_0)}}, \]

where:

  • \( P_{\textrm{sat}}(t) \) is the saturation pressure over water at temperature \( t \),
  • \( T_0 \) is the reference temperature (0°C).
Note
The constants \( T_0 \) must be defined before using this macro.
Author
Lars Hoffmann

Definition at line 1867 of file mptrac.h.

1867#define PSAT(t) \
1868 (6.112 * exp(17.62 * ((t) - T0) / (243.12 + (t) - T0)))

◆ PSICE

#define PSICE ( t)
Value:
(6.112 * exp(22.46 * ((t) - T0) / (272.62 + (t) - T0)))

Compute saturation pressure over ice (WMO, 2018).

This macro calculates the saturation pressure over ice based on the WMO (2018) formula.

Parameters
tThe temperature in K.
Returns
The saturation pressure over ice at the given temperature.

The saturation pressure over ice is calculated using the formula:

\[ P_{\textrm{ice}}(t) = 6.112 \times e^{22.46 \times \frac{(t - T_0)}{272.62 + (t - T_0)}}, \]

where:

  • \( P_{\textrm{ice}}(t) \) is the saturation pressure over ice at temperature \( t \),
  • \( T_0 \) is the reference temperature (0°C).
Note
The constant \( T_0 \) must be defined before using this macro.
Author
Lars Hoffmann

Definition at line 1891 of file mptrac.h.

1891#define PSICE(t) \
1892 (6.112 * exp(22.46 * ((t) - T0) / (272.62 + (t) - T0)))

◆ PW

#define PW ( p,
h2o )
Value:
((p) * MAX((h2o), 0.1e-6) / (1. + (1. - EPS) * MAX((h2o), 0.1e-6)))
#define EPS
Ratio of the specific gas constant of dry air and water vapor [1].
Definition mptrac.h:260
#define MAX(a, b)
Macro to determine the maximum of two values.
Definition mptrac.h:1425

Calculate partial water vapor pressure.

This macro calculates the partial water vapor pressure using the given total pressure and water vapor mixing ratio.

Parameters
pThe total pressure in hPa (hectopascals).
h2oThe water vapor mixing ratio in ppv (parts per volume).
Returns
The partial water vapor pressure.

The partial water vapor pressure is calculated using the formula:

\[ P_{\textrm{w}}(p, h_2o) = \frac{p \times \max(h_2o, 0.1 \times 10^{-6})}{1 + (1 - \epsilon) \times \max(h_2o, 0.1 \times 10^{-6})}, \]

where:

  • \( P_{\textrm{w}}(p, h_2o) \) is the partial water vapor pressure,
  • \( p \) is the total pressure in hPa,
  • \( h_2o \) is the water vapor mixing ratio in ppv,
  • \( \epsilon \) is the factor to account for saturation vapor pressure over water.
Note
The constant \( \epsilon \) must be defined before using this macro.
Author
Lars Hoffmann

Definition at line 1918 of file mptrac.h.

1918#define PW(p, h2o) \
1919 ((p) * MAX((h2o), 0.1e-6) / (1. + (1. - EPS) * MAX((h2o), 0.1e-6)))

◆ RAD2DEG

#define RAD2DEG ( rad)
Value:
((rad) * (180.0 / M_PI))

Converts radians to degrees.

This macro converts an angle from radians to degrees using the formula: degrees = radians * (180 / π)

Parameters
radThe angle in radians to be converted.
Returns
The angle in degrees.
Note
This macro uses the M_PI constant from <math.h> for the value of π.
Author
Lars Hoffmann

Definition at line 1935 of file mptrac.h.

1935#define RAD2DEG(rad) \
1936 ((rad) * (180.0 / M_PI))

◆ RH

#define RH ( p,
t,
h2o )
Value:
(PW(p, h2o) / PSAT(t) * 100.)
#define PW(p, h2o)
Calculate partial water vapor pressure.
Definition mptrac.h:1918
#define PSAT(t)
Compute saturation pressure over water.
Definition mptrac.h:1867

Compute relative humidity over water.

This macro calculates the relative humidity over water using the given total pressure, temperature, and water vapor mixing ratio.

Parameters
pThe total pressure in hPa.
tThe temperature in K.
h2oThe water vapor mixing ratio in ppv (parts per volume).
Returns
The relative humidity over water in percentage.

The relative humidity over water is calculated using the formula:

\[ RH_{\textrm{w}}(p, t, h_2o) = \frac{P_{\textrm{w}}(p, h_2o)}{P_{\textrm{sat}}(t)} \times 100, \]

where:

  • \( RH_{\textrm{w}}(p, t, h_2o) \) is the relative humidity over water,
  • \( P_{\textrm{w}}(p, h_2o) \) is the partial water vapor pressure,
  • \( P_{\textrm{sat}}(t) \) is the saturation pressure over water at the given temperature,
  • \( p \) is the total pressure in hPa,
  • \( t \) is the temperature in Kelvin,
  • \( h_2o \) is the water vapor mixing ratio in ppv.
Note
The macros PW() and PSAT() must be defined before using this macro.
Author
Lars Hoffmann

Definition at line 1965 of file mptrac.h.

1965#define RH(p, t, h2o) \
1966 (PW(p, h2o) / PSAT(t) * 100.)

◆ RHICE

#define RHICE ( p,
t,
h2o )
Value:
(PW(p, h2o) / PSICE(t) * 100.)
#define PSICE(t)
Compute saturation pressure over ice (WMO, 2018).
Definition mptrac.h:1891

Compute relative humidity over ice.

This macro calculates the relative humidity over ice using the given total pressure, temperature, and water vapor mixing ratio.

Parameters
pThe total pressure in hPa.
tThe temperature in K.
h2oThe water vapor mixing ratio in ppv (parts per volume).
Returns
The relative humidity over ice in percentage.

The relative humidity over ice is calculated using the formula:

\[ RH_{\textrm{ice}}(p, t, h_2o) = \frac{P_{\textrm{w}}(p, h_2o)}{P_{\textrm{ice}}(t)} \times 100, \]

where:

  • \( RH_{\textrm{ice}}(p, t, h_2o) \) is the relative humidity over ice,
  • \( P_{\textrm{w}}(p, h_2o) \) is the partial water vapor pressure,
  • \( P_{\textrm{ice}}(t) \) is the saturation pressure over ice at the given temperature,
  • \( p \) is the total pressure in hPa,
  • \( t \) is the temperature in Kelvin,
  • \( h_2o \) is the water vapor mixing ratio in ppv.
Note
The macros PW() and PSICE() must be defined before using this macro.
Author
Lars Hoffmann

Definition at line 1995 of file mptrac.h.

1995#define RHICE(p, t, h2o) \
1996 (PW(p, h2o) / PSICE(t) * 100.)

◆ RHO

#define RHO ( p,
t )
Value:
(100. * (p) / (RA * (t)))

Compute density of air.

This macro calculates the density of air using the given total pressure and temperature.

Parameters
pThe total pressure in hPa.
tThe temperature in K.
Returns
The density of air in kg/m^3.

The density of air is calculated using the formula:

\[ \rho(p, t) = \frac{100 \times p}{R_a \times t}, \]

where:

  • \( \rho(p, t) \) is the density of air,
  • \( p \) is the total pressure in hPa,
  • \( t \) is the temperature in Kelvin,
  • \( R_a \) is the specific gas constant for dry air (287.05 J/(kg·K)).
Author
Lars Hoffmann

Definition at line 2020 of file mptrac.h.

2020#define RHO(p, t) \
2021 (100. * (p) / (RA * (t)))

◆ SET_ATM

#define SET_ATM ( qnt,
val )
Value:
do { \
if (ctl->qnt >= 0) \
atm->q[ctl->qnt][ip] = val; \
} while (0)

Set atmospheric quantity value.

This macro sets the value of a specific atmospheric quantity at a given index 'ip'. The macro first checks if the control index 'ctl->qnt' is non-negative before assigning the value, ensuring that the quantity index is valid.

Parameters
qntThe index representing the atmospheric quantity to set.
valThe value to set for the atmospheric quantity.
Note
The macro assumes the existence of structures 'ctl' and 'atm' containing the control indices and atmospheric data, respectively, and an index 'ip' representing the data point.
Author
Lars Hoffmann

Definition at line 2039 of file mptrac.h.

2039#define SET_ATM(qnt, val) do { \
2040 if (ctl->qnt >= 0) \
2041 atm->q[ctl->qnt][ip] = val; \
2042 } while (0)

◆ SET_QNT

#define SET_QNT ( qnt,
name,
longname,
unit )
Value:
if (strcasecmp(ctl->qnt_name[iq], name) == 0) { \
ctl->qnt = iq; \
sprintf(ctl->qnt_longname[iq], longname); \
sprintf(ctl->qnt_unit[iq], unit); \
} else

Set atmospheric quantity index.

This macro sets the index, long name, and unit of a specific atmospheric quantity based on its name. It compares the name parameter with the name of the atmospheric quantity stored in 'ctl->qnt_name'. If a match is found, it assigns the index to 'ctl->qnt', updates the long name, and updates the unit.

Parameters
qntThe index representing the atmospheric quantity.
nameThe name of the atmospheric quantity.
longnameThe long name of the atmospheric quantity.
unitThe unit of the atmospheric quantity.
Note
The macro assumes the existence of structures 'ctl' containing control information. It also assumes the presence of 'iq', representing the index of the atmospheric quantity.
Author
Lars Hoffmann

Definition at line 2063 of file mptrac.h.

2063#define SET_QNT(qnt, name, longname, unit) \
2064 if (strcasecmp(ctl->qnt_name[iq], name) == 0) { \
2065 ctl->qnt = iq; \
2066 sprintf(ctl->qnt_longname[iq], longname); \
2067 sprintf(ctl->qnt_unit[iq], unit); \
2068 } else

◆ SH

#define SH ( h2o)
Value:
(EPS * MAX((h2o), 0.1e-6))

Compute specific humidity from water vapor volume mixing ratio.

This macro calculates the specific humidity from the water vapor volume mixing ratio. Specific humidity represents the ratio of the mass of water vapor to the total mass of air and is dimensionless.

Parameters
h2oThe water vapor volume mixing ratio.
Returns
The specific humidity.
Note
The macro assumes that 'EPS' is defined and represents the ratio of the molecular weight of water vapor to the molecular weight of dry air.
Author
Lars Hoffmann

Definition at line 2084 of file mptrac.h.

2084#define SH(h2o) \
2085 (EPS * MAX((h2o), 0.1e-6))

◆ SQR

#define SQR ( x)
Value:
((x)*(x))

Compute the square of a value.

This macro computes the square of the input value.

Parameters
xThe input value.
Returns
The square of the input value.
Author
Lars Hoffmann

Definition at line 2097 of file mptrac.h.

2097#define SQR(x) \
2098 ((x)*(x))

◆ SWAP

#define SWAP ( x,
y,
type )
Value:
do {type tmp = x; x = y; y = tmp;} while(0)

Swap two values.

This macro swaps the values of two variables of the specified type.

Parameters
xThe first variable to be swapped.
yThe second variable to be swapped.
typeThe type of the variables.
Author
Lars Hoffmann

Definition at line 2111 of file mptrac.h.

2111#define SWAP(x, y, type) \
2112 do {type tmp = x; x = y; y = tmp;} while(0)

◆ TDEW

#define TDEW ( p,
h2o )
Value:
(T0 + 243.12 * log(PW((p), (h2o)) / 6.112) \
/ (17.62 - log(PW((p), (h2o)) / 6.112)))

Calculate dew point temperature.

This macro computes the dew point temperature using the formula provided by the World Meteorological Organization (WMO, 2018).

Parameters
pThe atmospheric pressure in hPa.
h2oThe water vapor volume mixing ratio.
Returns
The dew point temperature in Kelvin.

Formula:

\[ T_{\textrm{dew}} = T_0 + \frac{243.12 \times \ln\left(\frac{{P_W(p, h_{2}O)}}{6.112}\right)}{17.62 - \ln\left(\frac{{P_W(p, h_{2}O)}}{6.112}\right)} \]

where:

  • \( T_{\textrm{dew}} \) is the dew point temperature.
  • \( T_0 \) is the reference temperature in Kelvin (typically 273.15 K).
  • \( P_W(p, h_{2}O) \) is the partial water vapor pressure.
Author
Lars Hoffmann

Definition at line 2135 of file mptrac.h.

2135#define TDEW(p, h2o) \
2136 (T0 + 243.12 * log(PW((p), (h2o)) / 6.112) \
2137 / (17.62 - log(PW((p), (h2o)) / 6.112)))

◆ TICE

#define TICE ( p,
h2o )
Value:
(T0 + 272.62 * log(PW((p), (h2o)) / 6.112) \
/ (22.46 - log(PW((p), (h2o)) / 6.112)))

Calculate frost point temperature (WMO, 2018).

This macro computes the frost point temperature using the formula provided by the World Meteorological Organization (WMO, 2018).

Parameters
pThe atmospheric pressure in hPa.
h2oThe water vapor volume mixing ratio.
Returns
The frost point temperature in Kelvin.

Formula:

\[ T_{\textrm{ice}} = T_0 + \frac{272.62 \times \ln\left(\frac{{P_W(p, h_{2}O)}}{6.112}\right)}{22.46 - \ln\left(\frac{{P_W(p, h_{2}O)}}{6.112}\right)} \]

where:

  • \( T_{\textrm{ice}} \) is the frost point temperature.
  • \( T_0 \) is the reference temperature in Kelvin (typically 273.15 K).
  • \( P_W(p, h_{2}O) \) is the partial water vapor pressure.
Author
Lars Hoffmann

Definition at line 2160 of file mptrac.h.

2160#define TICE(p, h2o) \
2161 (T0 + 272.62 * log(PW((p), (h2o)) / 6.112) \
2162 / (22.46 - log(PW((p), (h2o)) / 6.112)))

◆ THETA

#define THETA ( p,
t )
Value:
((t) * pow(1000. / (p), KAPPA))
#define KAPPA
Exponent used for potential-temperature calculations [1].
Definition mptrac.h:325

Compute potential temperature.

This macro calculates the potential temperature of the atmosphere.

Parameters
pThe atmospheric pressure in hPa.
tThe temperature in Kelvin.
Returns
The potential temperature in Kelvin.

Formula:

\[ \theta = T \left( \frac{1000}{P} \right)^{\kappa} \]

where:

  • \( \theta \) is the potential temperature.
  • \( T \) is the temperature in Kelvin.
  • \( P \) is the atmospheric pressure in hPa.
Author
Lars Hoffmann

Definition at line 2184 of file mptrac.h.

2184#define THETA(p, t) \
2185 ((t) * pow(1000. / (p), KAPPA))

◆ THETAVIRT

#define THETAVIRT ( p,
t,
h2o )
Value:
(TVIRT(THETA((p), (t)), MAX((h2o), 0.1e-6)))
#define TVIRT(t, h2o)
Compute virtual temperature.
Definition mptrac.h:2259
#define THETA(p, t)
Compute potential temperature.
Definition mptrac.h:2184

Compute virtual potential temperature.

This macro calculates the virtual potential temperature of the atmosphere, which takes into account the effect of water vapor on the atmosphere's buoyancy.

Parameters
pThe atmospheric pressure in hPa.
tThe temperature in Kelvin.
h2oThe water vapor volume mixing ratio (ppv).
Returns
The virtual potential temperature in Kelvin.

Formula:

The virtual potential temperature ( \( \theta_v \)) is computed as

\[ \theta_v = \theta \left( 1 + \frac{0.61 \times q}{\epsilon} \right), \]

where:

  • \( \theta_v \) is the virtual potential temperature.
  • \( \theta \) is the potential temperature.
  • \( q \) is the specific humidity.
  • \( \epsilon \) is the ratio of the molecular weight of water vapor to dry air.
Author
Lars Hoffmann

Definition at line 2213 of file mptrac.h.

2213#define THETAVIRT(p, t, h2o) \
2214 (TVIRT(THETA((p), (t)), MAX((h2o), 0.1e-6)))

◆ TOK

#define TOK ( line,
tok,
format,
var )
Value:
{ \
if(((tok)=strtok((line), " \t"))) { \
if(sscanf(tok, format, &(var))!=1) continue; \
} else ERRMSG("Error while reading!"); \
}
#define ERRMSG(...)
Print an error message with contextual information and terminate the program.
Definition mptrac.h:2466

Get string tokens.

This macro extracts tokens from a given string, typically used for parsing input lines.

Parameters
lineThe input string containing tokens.
tokA pointer to the token string.
formatThe format string specifying the expected format of the token.
varThe variable to store the parsed token value.

The macro tokenizes the input line using space and tab characters as delimiters. It then parses each token according to the specified format string and stores the parsed value in the provided variable.

Author
Lars Hoffmann

Definition at line 2234 of file mptrac.h.

2234#define TOK(line, tok, format, var) { \
2235 if(((tok)=strtok((line), " \t"))) { \
2236 if(sscanf(tok, format, &(var))!=1) continue; \
2237 } else ERRMSG("Error while reading!"); \
2238 }

◆ TVIRT

#define TVIRT ( t,
h2o )
Value:
((t) * (1. + (1. - EPS) * MAX((h2o), 0.1e-6)))

Compute virtual temperature.

This macro calculates the virtual temperature of air given its temperature and water vapor volume mixing ratio.

Parameters
tThe temperature of the air in Kelvin.
h2oThe water vapor volume mixing ratio.
Returns
The virtual temperature of the air.

The virtual temperature (T_v) is computed as the temperature (t) multiplied by (1 + (1 - EPS) * max(h2o, 0.1e-6)), where EPS is the ratio of the molar mass of water vapor to the molar mass of dry air.

Note
EPS is typically defined as 0.622.
Author
Lars Hoffmann

Definition at line 2259 of file mptrac.h.

2259#define TVIRT(t, h2o) \
2260 ((t) * (1. + (1. - EPS) * MAX((h2o), 0.1e-6)))

◆ USAGE

#define USAGE
Value:
do { \
int iusage; \
for (iusage = 1; iusage < argc; iusage++) \
if (!strcmp(argv[iusage], "-h") \
|| !strcmp(argv[iusage], "--help")) { \
usage(); \
return EXIT_SUCCESS; \
} \
} while (0)

Print usage information on -h or --help.

Calls the local usage() function and exits successfully when any command argument is -h or --help.

Note
This macro expects local argc and argv variables and a local usage() function.
Author
Lars Hoffmann

Definition at line 2273 of file mptrac.h.

2273#define USAGE \
2274 do { \
2275 int iusage; \
2276 for (iusage = 1; iusage < argc; iusage++) \
2277 if (!strcmp(argv[iusage], "-h") \
2278 || !strcmp(argv[iusage], "--help")) { \
2279 usage(); \
2280 return EXIT_SUCCESS; \
2281 } \
2282 } while (0)

◆ Z

#define Z ( p)
Value:
(H0 * log(P0 / (p)))

Convert pressure to altitude.

This macro calculates the altitude from the given pressure using the barometric formula.

Parameters
pThe pressure in hPa (hectopascal).
Returns
The altitude in kilometers (km).

Formula:

The altitude (z) is computed as H0 times the natural logarithm of the ratio of the reference pressure (P0) to the given pressure (p), where H0 is the scale height and P0 is the reference pressure at sea level.

Note
H0 and P0 are typically defined as constants specific to the atmosphere.
Author
Lars Hoffmann

Definition at line 2303 of file mptrac.h.

2303#define Z(p) \
2304 (H0 * log(P0 / (p)))

◆ ZDIFF

#define ZDIFF ( lnp0,
t0,
h2o0,
lnp1,
t1,
h2o1 )
Value:
(RI / MA / G0 * 0.5 * (TVIRT((t0), (h2o0)) + TVIRT((t1), (h2o1))) \
* ((lnp0) - (lnp1)))
#define MA
Molar mass of dry air [g/mol].
Definition mptrac.h:290

Calculate geopotential height difference.

This macro calculates the geopotential height difference between two pressure levels using the hypsometric equation.

Parameters
lnp0The natural logarithm of the pressure at the first level.
t0The temperature at the first level in Kelvin (K).
h2o0The water vapor volume mixing ratio at the first level.
lnp1The natural logarithm of the pressure at the second level.
t1The temperature at the second level in Kelvin (K).
h2o1The water vapor volume mixing ratio at the second level.
Returns
The geopotential height difference in kilometers (km).

Formula: The geopotential height difference (dz) is computed as a function of the difference in natural logarithm of pressure (lnp) between the two levels, the average virtual temperature (ThetaVirt) of the two levels, the specific gas constant for dry air (RI), and the acceleration due to gravity at the surface of the Earth (G0).

Note
The specific gas constant for dry air (RI), the molar mass of dry air (MA), and the acceleration due to gravity at the surface of the Earth (G0) are typically defined as constants specific to the atmosphere.
Author
Lars Hoffmann

Definition at line 2334 of file mptrac.h.

2334#define ZDIFF(lnp0, t0, h2o0, lnp1, t1, h2o1) \
2335 (RI / MA / G0 * 0.5 * (TVIRT((t0), (h2o0)) + TVIRT((t1), (h2o1))) \
2336 * ((lnp0) - (lnp1)))

◆ ZETA

#define ZETA ( ps,
p,
t )
Value:
(((p) / (ps) <= 0.3 ? 1. : \
sin(M_PI / 2. * (1. - (p) / (ps)) / (1. - 0.3))) \
* THETA((p), (t)))

Computes the value of the zeta vertical coordinate.

This macro calculates the zeta vertical coordinate based on the given surface pressure (ps), pressure (p), and temperature (t). The calculation depends on the ratio p/ps:

  • If p/ps <= 0.3, the function returns 1.0 multiplied by THETA(p, t).
  • Otherwise, it computes a sine function transformation scaled by THETA(p, t).
Parameters
psSurface pressure.
pPressure at the given level.
tTemperature at the given level.
Returns
Computed zeta vertical coordinate value.
Author
Lars Hoffmann

Definition at line 2353 of file mptrac.h.

2353#define ZETA(ps, p, t) \
2354 (((p) / (ps) <= 0.3 ? 1. : \
2355 sin(M_PI / 2. * (1. - (p) / (ps)) / (1. - 0.3))) \
2356 * THETA((p), (t)))

◆ LOGLEV

#define LOGLEV   2

Level of log messages (0=none, 1=basic, 2=detailed, 3=debug).

Definition at line 2364 of file mptrac.h.

◆ LOG

#define LOG ( level,
... )
Value:
do { \
if(level >= 2) \
printf(" "); \
if(level <= LOGLEV) { \
printf(__VA_ARGS__); \
printf("\n"); \
} \
} while (0)
#define LOGLEV
Level of log messages (0=none, 1=basic, 2=detailed, 3=debug).
Definition mptrac.h:2364

Print a log message with a specified logging level.

This macro prints a formatted log message to the standard output if the specified logging level meets certain conditions. The message will be indented if the logging level is greater than or equal to 2.

Parameters
levelThe logging level of the message. This should be an integer value.
...The formatted message string and its arguments, similar to printf.

The LOG macro provides a simple way to log messages with different levels of importance. The message is only printed if the specified level is less than or equal to the pre-defined LOGLEV macro. If the level is greater than or equal to 2, the message is preceded by two spaces for indentation.

The macro expands to a block of code that:

  • Checks if the level is greater than or equal to 2, and if so, prints two spaces.
  • Checks if the level is less than or equal to LOGLEV, and if so, prints the formatted message followed by a newline.
Note
The LOGLEV macro must be defined with an appropriate logging level before using the LOG macro.
Author
Lars Hoffmann

Definition at line 2396 of file mptrac.h.

2396#define LOG(level, ...) do { \
2397 if(level >= 2) \
2398 printf(" "); \
2399 if(level <= LOGLEV) { \
2400 printf(__VA_ARGS__); \
2401 printf("\n"); \
2402 } \
2403 } while (0)

◆ WARN

#define WARN ( ...)
Value:
do { \
printf("\nWarning (%s, %s, l%d): ", __FILE__, __func__, __LINE__); \
LOG(0, __VA_ARGS__); \
} while (0)

Print a warning message with contextual information.

This macro prints a formatted warning message to the standard output, including the file name, function name, and line number where the warning occurred. The message is then passed to the LOG macro with a logging level of 0.

Parameters
...The formatted warning message string and its arguments, similar to printf.

The WARN macro is used to print warning messages with additional context about where the warning was triggered. The message includes the following contextual information:

  • The name of the source file where the macro is called (__FILE__).
  • The name of the function where the macro is called (__func__).
  • The line number in the source file where the macro is called (__LINE__).

After printing this contextual information, the macro uses the LOG macro with a logging level of 0 to print the actual warning message. This ensures that warning messages are always logged, regardless of the value of LOGLEV.

Note
The LOG macro must be defined before using the WARN macro.
Author
Lars Hoffmann

Definition at line 2433 of file mptrac.h.

2433#define WARN(...) do { \
2434 printf("\nWarning (%s, %s, l%d): ", __FILE__, __func__, __LINE__); \
2435 LOG(0, __VA_ARGS__); \
2436 } while (0)

◆ ERRMSG

#define ERRMSG ( ...)
Value:
do { \
printf("\nError (%s, %s, l%d): ", __FILE__, __func__, __LINE__); \
LOG(0, __VA_ARGS__); \
exit(EXIT_FAILURE); \
} while (0)

Print an error message with contextual information and terminate the program.

This macro prints a formatted error message to the standard output, including the file name, function name, and line number where the error occurred. After printing the message, the program is terminated with an exit status indicating failure.

Parameters
...The formatted error message string and its arguments, similar to printf.

The ERRMSG macro is used to report critical errors that require the program to terminate immediately. The message includes the following contextual information:

  • The name of the source file where the macro is called (__FILE__).
  • The name of the function where the macro is called (__func__).
  • The line number in the source file where the macro is called (__LINE__).

After printing this contextual information, the macro uses the LOG macro with a logging level of 0 to print the actual error message. Finally, the program exits with a failure status (EXIT_FAILURE).

Note
The LOG macro must be defined before using the ERRMSG macro.
Author
Lars Hoffmann

Definition at line 2466 of file mptrac.h.

2466#define ERRMSG(...) do { \
2467 printf("\nError (%s, %s, l%d): ", __FILE__, __func__, __LINE__); \
2468 LOG(0, __VA_ARGS__); \
2469 exit(EXIT_FAILURE); \
2470 } while (0)

◆ PRINT

#define PRINT ( format,
var )
Value:
do { \
printf("Print (%s, %s, l%d): %s= "format"\n", \
__FILE__, __func__, __LINE__, #var, var); \
} while (0)

Print the value of a variable with contextual information.

This macro prints the value of a variable to the standard output, including the file name, function name, and line number where the macro is called. The output also includes the variable's name and value in a formatted string.

Parameters
formatThe format string used to print the variable's value, similar to printf.
varThe variable to be printed.

The PRINT macro is used to output the value of a variable along with additional context about where the macro is called. The message includes:

  • The name of the source file where the macro is called (__FILE__).
  • The name of the function where the macro is called (__func__).
  • The line number in the source file where the macro is called (__LINE__).
  • The name of the variable being printed (#var).
  • The value of the variable, formatted according to the provided format string (format).

This macro is particularly useful for debugging purposes, providing a convenient way to trace variable values and their locations in the code.

Note
The format string must be compatible with the type of the variable being printed.
Author
Lars Hoffmann

Definition at line 2501 of file mptrac.h.

2501#define PRINT(format, var) do { \
2502 printf("Print (%s, %s, l%d): %s= "format"\n", \
2503 __FILE__, __func__, __LINE__, #var, var); \
2504 } while (0)

◆ NTIMER

#define NTIMER   100

Maximum number of timers.

Definition at line 2511 of file mptrac.h.

◆ PRINT_TIMERS

#define PRINT_TIMERS
Value:
do { \
timer("END", "END", 1); \
} while (0)

Print the current state of all timers.

This macro calls the timer function with predefined arguments to signify the end of the timer logging process. It is used to print the results of all the timers that have been tracked.

Note
The timer function must be defined elsewhere in the codebase for this macro to function correctly.
Author
Lars Hoffmann

Definition at line 2526 of file mptrac.h.

2526#define PRINT_TIMERS do { \
2527 timer("END", "END", 1); \
2528 } while (0)

◆ SELECT_TIMER

#define SELECT_TIMER ( id,
group )
Value:
do { \
timer(id, group, 0); \
} while (0)

Select and start a timer with specific attributes.

This macro stops the current timer (if any) and starts a new timer with the specified ID and group. It uses the timer function to log the timer start event.

Parameters
idThe identifier for the timer.
groupThe group name associated with the timer.
Author
Lars Hoffmann

Definition at line 2542 of file mptrac.h.

2542#define SELECT_TIMER(id, group) do { \
2543 timer(id, group, 0); \
2544 } while (0)

Function Documentation

◆ broadcast_large_data()

void broadcast_large_data ( void * data,
size_t N )

Broadcasts large data across all processes in an MPI communicator.

This function divides the data into manageable chunks and broadcasts each chunk sequentially. This approach is necessary because the data size may exceed the maximum allowable message size for a single MPI_Bcast operation.

Parameters
dataPointer to the data to be broadcasted.
NSize of the data in bytes.

The function first broadcasts the total size of the data to all processes. Then, it calculates the number of chunks needed to broadcast the entire data. Each chunk is broadcasted in sequence until the entire data has been sent.

The maximum chunk size is defined as CHUNK_SIZE (2147483647 bytes).

Note
The function assumes that the MPI environment has been initialized before calling this function and will be finalized afterward.
Author
Lars Hoffmann

Broadcasts large data across all processes in an MPI communicator.

Definition at line 47 of file mptrac.c.

49 {
50
51#define CHUNK_SIZE 2147483647
52
53 /* Broadcast the size of the data first... */
54 MPI_Bcast(&N, 1, MPI_UINT64_T, 0, MPI_COMM_WORLD);
55
56 /* Calculate the number of chunks... */
57 const size_t num_chunks = (N + CHUNK_SIZE - 1) / CHUNK_SIZE;
58
59 /* Loop over chunks... */
60 for (size_t i = 0; i < num_chunks; i++) {
61
62 /* Determine the start and end indices for the current chunk... */
63 const size_t start = i * CHUNK_SIZE;
64 const size_t end = (start + CHUNK_SIZE > N) ? N : start + CHUNK_SIZE;
65 const size_t chunk_size = end - start;
66
67 /* Broadcast the current chunk... */
68 MPI_Bcast((char *) data + start, (int) chunk_size, MPI_BYTE, 0,
69 MPI_COMM_WORLD);
70 }
71}
#define CHUNK_SIZE

◆ cart2geo()

void cart2geo ( const double * x,
double * z,
double * lon,
double * lat )

Converts Cartesian coordinates to geographic coordinates.

This function converts a point from Cartesian coordinates (x, y, z) to geographic coordinates (longitude, latitude, and altitude). It uses the spherical Earth approximation for the conversion.

Parameters
xPointer to an array containing the Cartesian coordinates (x, y, z) in kilometers.
zPointer to a double where the computed altitude (above the reference ellipsoid) will be stored, in kilometers.
lonPointer to a double where the computed longitude (in degrees) will be stored.
latPointer to a double where the computed latitude (in degrees) will be stored.
Author
Lars Hoffmann

Definition at line 76 of file mptrac.c.

80 {
81
82 const double radius = sqrt(DOTP(x, x));
83
84 *lat = RAD2DEG(asin(x[2] / radius));
85 *lon = RAD2DEG(atan2(x[1], x[0]));
86 *z = radius - RE;
87}
#define DOTP(a, b)
Calculate the dot product of two vectors.
Definition mptrac.h:1038
#define RAD2DEG(rad)
Converts radians to degrees.
Definition mptrac.h:1935

◆ clim_oh()

double clim_oh ( const ctl_t * ctl,
const clim_t * clim,
const double t,
const double lon,
const double lat,
const double p )

Calculates the hydroxyl radical (OH) concentration from climatology data, with an optional diurnal correction based on solar zenith angle.

This function retrieves OH data from a given climatology and applies a diurnal correction if the correction factor (oh_chem_beta) is greater than zero. The diurnal correction accounts for the variation in OH concentration due to changes in the solar zenith angle.

Parameters
ctlPointer to the control structure containing configuration parameters.
climPointer to the climatology structure containing OH data.
tTime at which the OH concentration is to be calculated.
lonLongitude at which the OH concentration is to be calculated.
latLatitude at which the OH concentration is to be calculated.
pPressure level at which the OH concentration is to be calculated.
Returns
The OH concentration at the specified time, location, and pressure, possibly adjusted by a diurnal correction.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 91 of file mptrac.c.

97 {
98
99 /* Set SZA threshold... */
100 const double sza_thresh = DEG2RAD(85.), csza_thresh = cos(sza_thresh);
101
102 /* Set reference coordinates... */
103 const double lat_ref =
104 ctl->met_coord_type == 0 ? lat : ctl->met_utm_ref_lat;
105 double lon_ref = ctl->met_coord_type == 0 ? lon : ctl->met_utm_ref_lon;
106 while (lon_ref < -180.0)
107 lon_ref += 360.0;
108 while (lon_ref >= 180.0)
109 lon_ref -= 360.0;
110
111 /* Get OH data from climatology... */
112 const double oh = clim_zm(&clim->oh, t, lat_ref, p);
113
114 /* Check beta... */
115 if (ctl->oh_chem_beta <= 0)
116 return oh;
117
118 /* Apply diurnal correction... */
119 const double csza = cos_sza(t, lon_ref, lat_ref);
120 const double denom = (csza >= csza_thresh) ? csza : csza_thresh;
121 return oh * exp(-ctl->oh_chem_beta / denom);
122}
double cos_sza(const double sec, const double lon, const double lat)
Calculates the cosine of the solar zenith angle.
Definition mptrac.c:1861
double clim_zm(const clim_zm_t *zm, const double t, const double lat, const double p)
Interpolates monthly mean zonal mean climatological variables.
Definition mptrac.c:418
clim_zm_t oh
OH zonal means.
Definition mptrac.h:3917
double met_utm_ref_lon
Reference longitude [deg] for UTM grid.
Definition mptrac.h:2923
double met_utm_ref_lat
Reference latitude [deg] for UTM grid.
Definition mptrac.h:2920
double oh_chem_beta
Beta parameter for diurnal variability of OH.
Definition mptrac.h:3310
int met_coord_type
Type of coordinates for meteo data (-1=detect, 0=lat/lon [deg], 1=UTM [m]).
Definition mptrac.h:2917
Here is the call graph for this function:

◆ clim_oh_diurnal_correction()

void clim_oh_diurnal_correction ( const ctl_t * ctl,
clim_t * clim )

Applies a diurnal correction to the hydroxyl radical (OH) concentration in climatology data.

This function iterates over the climatology data points for OH concentration and integrates the day/night correction factor over longitude. The correction factor is based on the solar zenith angle, and it adjusts the OH data to account for diurnal variations. The corrected OH data is scaled accordingly.

Parameters
ctlPointer to the control structure containing configuration parameters, including the correction factor (oh_chem_beta).
climPointer to the climatology structure containing OH data that will be corrected.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 126 of file mptrac.c.

128 {
129
130 /* Set SZA threshold... */
131 const double sza_thresh = DEG2RAD(85.), csza_thresh = cos(sza_thresh);
132
133 /* Loop over climatology data points... */
134 for (int it = 0; it < clim->oh.ntime; it++)
135 for (int iz = 0; iz < clim->oh.np; iz++)
136 for (int iy = 0; iy < clim->oh.nlat; iy++) {
137
138 /* Init... */
139 int n = 0;
140 double sum = 0;
141
142 /* Integrate day/night correction factor over longitude... */
143 for (double lon = -180; lon < 180; lon += 1.0) {
144 const double csza =
145 cos_sza(clim->oh.time[it], lon, clim->oh.lat[iy]);
146 const double denom = (csza >= csza_thresh) ? csza : csza_thresh;
147 sum += exp(-ctl->oh_chem_beta / denom);
148 n++;
149 }
150
151 /* Apply scaling factor to OH data... */
152 if (!isfinite(sum) || sum <= 0)
153 ERRMSG("Invalid OH_CHEM_BETA diurnal normalization!");
154 clim->oh.vmr[it][iz][iy] /= (sum / (double) n);
155 }
156}
double time[CT]
Time [s].
Definition mptrac.h:3873
int np
Number of pressure levels.
Definition mptrac.h:3870
double vmr[CT][CP][CY]
Volume mixing ratio [ppv].
Definition mptrac.h:3882
int ntime
Number of timesteps.
Definition mptrac.h:3864
int nlat
Number of latitudes.
Definition mptrac.h:3867
double lat[CY]
Latitude [deg].
Definition mptrac.h:3876
Here is the call graph for this function:

◆ clim_photo()

double clim_photo ( const double rate[CP][CSZA][CO3],
const clim_photo_t * photo,
const double p,
const double sza,
const double o3c )

Calculates the photolysis rate for a given set of atmospheric conditions.

This function computes the photolysis rate based on provided climatology data and input parameters such as pressure, solar zenith angle (SZA), and ozone column. It ensures that the input parameters are within the valid range of the climatology data and interpolates the photolysis rate accordingly.

Parameters
rate3D array containing the photolysis rates for different combinations of pressure, SZA, and ozone column.
photoPointer to the climatology data structure containing arrays of valid pressure levels, SZAs, and ozone columns.
pPressure at which the photolysis rate is to be calculated.
szaSolar zenith angle at which the photolysis rate is to be calculated.
o3cOzone column at which the photolysis rate is to be calculated.
Returns
The interpolated photolysis rate for the specified conditions. If the calculated rate is negative, it returns 0.0.

This function performs the following steps:

  1. Checks and adjusts the input parameters (pressure, SZA, and ozone column) to ensure they are within the valid range.
  2. Determines the appropriate indices in the climatology data for interpolation.
  3. Performs trilinear interpolation to calculate the photolysis rate based on the input parameters.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 160 of file mptrac.c.

165 {
166
167 /* Check pressure range... */
168 double p_help = p;
169 if (p < photo->p[photo->np - 1])
170 p_help = photo->p[photo->np - 1];
171 else if (p > photo->p[0])
172 p_help = photo->p[0];
173
174 /* Check sza range... */
175 double sza_help = sza;
176 if (sza < photo->sza[0])
177 sza_help = photo->sza[0];
178 else if (sza > photo->sza[photo->nsza - 1])
179 sza_help = photo->sza[photo->nsza - 1];
180
181 /* Check ozone column range... */
182 double o3c_help = o3c;
183 if (o3c < photo->o3c[0])
184 o3c_help = photo->o3c[0];
185 else if (o3c > photo->o3c[photo->no3c - 1])
186 o3c_help = photo->o3c[photo->no3c - 1];
187
188 /* Get indices... */
189 const int ip = locate_irr(photo->p, photo->np, p_help);
190 const int isza = locate_reg(photo->sza, photo->nsza, sza_help);
191 const int io3c = locate_reg(photo->o3c, photo->no3c, o3c_help);
192
193 /* Interpolate photolysis rate... */
194 const double aux00 = LIN(photo->p[ip], rate[ip][isza][io3c],
195 photo->p[ip + 1], rate[ip + 1][isza][io3c],
196 p_help);
197 const double aux01 = LIN(photo->p[ip], rate[ip][isza][io3c + 1],
198 photo->p[ip + 1], rate[ip + 1][isza][io3c + 1],
199 p_help);
200 const double aux10 = LIN(photo->p[ip], rate[ip][isza + 1][io3c],
201 photo->p[ip + 1], rate[ip + 1][isza + 1][io3c],
202 p_help);
203 const double aux11 = LIN(photo->p[ip], rate[ip][isza + 1][io3c + 1],
204 photo->p[ip + 1], rate[ip + 1][isza + 1][io3c + 1],
205 p_help);
206 const double aux0 =
207 LIN(photo->o3c[io3c], aux00, photo->o3c[io3c + 1], aux01, o3c_help);
208 const double aux1 =
209 LIN(photo->o3c[io3c], aux10, photo->o3c[io3c + 1], aux11, o3c_help);
210 const double aux =
211 LIN(photo->sza[isza], aux0, photo->sza[isza + 1], aux1, sza_help);
212 return MAX(aux, 0.0);
213}
int locate_reg(const double *xx, const int n, const double x)
Locate the index of the interval containing a given value in a regular grid.
Definition mptrac.c:3903
int locate_irr(const double *xx, const int n, const double x)
Locate the index of the interval containing a given value in a sorted array.
Definition mptrac.c:3839
#define LIN(x0, y0, x1, y1, x)
Linear interpolation.
Definition mptrac.h:1398
int nsza
Number of solar zenith angles.
Definition mptrac.h:3791
double sza[CSZA]
Solar zenith angle [rad].
Definition mptrac.h:3800
double p[CP]
Pressure [hPa].
Definition mptrac.h:3797
double o3c[CO3]
Total column ozone [DU].
Definition mptrac.h:3803
int np
Number of pressure levels.
Definition mptrac.h:3788
int no3c
Number of total ozone columns.
Definition mptrac.h:3794
Here is the call graph for this function:

◆ clim_tropo()

double clim_tropo ( const clim_t * clim,
const double t,
const double lat )

Calculates the tropopause pressure based on climatological data.

This function computes the tropopause pressure using climatological data for different times and latitudes. It interpolates the tropopause pressure based on the input time and latitude parameters.

Parameters
climPointer to the climatology structure containing tropopause pressure data.
tTime for which the tropopause pressure is to be calculated, in seconds since the beginning of the year.
latLatitude at which the tropopause pressure is to be calculated.
Returns
The interpolated tropopause pressure for the specified time and latitude.

This function performs the following steps:

  1. Calculates the number of seconds since the beginning of the year.
  2. Determines the appropriate indices in the climatology data for interpolation based on time and latitude.
  3. Interpolates the tropopause pressure using linear interpolation based on latitude and time.
Author
Lars Hoffmann

Definition at line 217 of file mptrac.c.

220 {
221
222 /* Get seconds since begin of year... */
223 double sec = FMOD(t, 365.25 * 86400.);
224 while (sec < 0)
225 sec += 365.25 * 86400.;
226
227 /* Get indices... */
228 const int isec = locate_irr(clim->tropo_time, clim->tropo_ntime, sec);
229 const int ilat = locate_reg(clim->tropo_lat, clim->tropo_nlat, lat);
230
231 /* Interpolate tropopause pressure... */
232 const double p0 = LIN(clim->tropo_lat[ilat],
233 clim->tropo[isec][ilat],
234 clim->tropo_lat[ilat + 1],
235 clim->tropo[isec][ilat + 1], lat);
236 const double p1 = LIN(clim->tropo_lat[ilat],
237 clim->tropo[isec + 1][ilat],
238 clim->tropo_lat[ilat + 1],
239 clim->tropo[isec + 1][ilat + 1], lat);
240 return LIN(clim->tropo_time[isec], p0, clim->tropo_time[isec + 1], p1, sec);
241}
#define FMOD(x, y)
Calculate the floating-point remainder of dividing x by y.
Definition mptrac.h:1123
int tropo_ntime
Number of tropopause timesteps.
Definition mptrac.h:3896
double tropo_lat[73]
Tropopause latitudes [deg].
Definition mptrac.h:3905
int tropo_nlat
Number of tropopause latitudes.
Definition mptrac.h:3899
double tropo[12][73]
Tropopause pressure values [hPa].
Definition mptrac.h:3908
double tropo_time[12]
Tropopause time steps [s].
Definition mptrac.h:3902
Here is the call graph for this function:

◆ clim_tropo_init()

void clim_tropo_init ( clim_t * clim)

Initializes the tropopause data in the climatology structure.

This function initializes the tropopause data in the climatology structure. It sets the time steps, latitudes, and tropopause pressure values based on predefined arrays.

Parameters
climPointer to the climatology structure to be initialized.

This function performs the following steps:

  1. Sets the number of time steps and initializes the time array.
  2. Sets the number of latitudes and initializes the latitude array.
  3. Initializes the tropopause pressure values based on predefined arrays.
  4. Computes the range of tropopause pressure values.
  5. Logs information about the initialization process.
Author
Lars Hoffmann

Definition at line 245 of file mptrac.c.

246 {
247
248 /* Write info... */
249 LOG(1, "Initialize tropopause data...");
250
251 /* Set time [s]... */
252 clim->tropo_ntime = 12;
253 double tropo_time[12] = {
254 1209600.00, 3888000.00, 6393600.00,
255 9072000.00, 11664000.00, 14342400.00,
256 16934400.00, 19612800.00, 22291200.00,
257 24883200.00, 27561600.00, 30153600.00
258 };
259 memcpy(clim->tropo_time, tropo_time, sizeof(clim->tropo_time));
260
261 /* Set latitudes [deg]... */
262 clim->tropo_nlat = 73;
263 const double tropo_lat[73] = {
264 -90, -87.5, -85, -82.5, -80, -77.5, -75, -72.5, -70, -67.5,
265 -65, -62.5, -60, -57.5, -55, -52.5, -50, -47.5, -45, -42.5,
266 -40, -37.5, -35, -32.5, -30, -27.5, -25, -22.5, -20, -17.5,
267 -15, -12.5, -10, -7.5, -5, -2.5, 0, 2.5, 5, 7.5, 10, 12.5,
268 15, 17.5, 20, 22.5, 25, 27.5, 30, 32.5, 35, 37.5, 40, 42.5,
269 45, 47.5, 50, 52.5, 55, 57.5, 60, 62.5, 65, 67.5, 70, 72.5,
270 75, 77.5, 80, 82.5, 85, 87.5, 90
271 };
272 memcpy(clim->tropo_lat, tropo_lat, sizeof(clim->tropo_lat));
273
274 /* Set tropopause pressure [hPa] (NCEP/NCAR Reanalysis 1)... */
275 const double tropo[12][73] = {
276 {324.1, 325.6, 325, 324.3, 322.5, 319.7, 314, 307.2, 301.8, 299.6,
277 297.1, 292.2, 285.6, 276.1, 264, 248.9, 231.9, 213.5, 194.4,
278 175.3, 157, 140.4, 126.7, 116.3, 109.5, 105.4, 103, 101.4, 100.4,
279 99.69, 99.19, 98.84, 98.56, 98.39, 98.39, 98.42, 98.44, 98.54,
280 98.68, 98.81, 98.89, 98.96, 99.12, 99.65, 101.4, 105.4, 113.5, 128,
281 152.1, 184.7, 214, 234.1, 247.3, 255.8, 262.6, 267.7, 271.7, 275,
282 277.2, 279, 280.1, 280.4, 280.6, 280.1, 279.3, 278.3, 276.8, 275.8,
283 275.3, 275.6, 275.4, 274.1, 273.5},
284 {337.3, 338.7, 337.8, 336.4, 333, 328.8, 321.1, 312.6, 306.6, 303.7,
285 300.2, 293.8, 285.4, 273.8, 259.6, 242.7, 224.4, 205.2, 186, 167.5,
286 150.3, 135, 122.8, 113.9, 108.2, 104.7, 102.5, 101.1, 100.2, 99.42,
287 98.88, 98.52, 98.25, 98.09, 98.07, 98.1, 98.12, 98.2, 98.25, 98.27,
288 98.26, 98.27, 98.36, 98.79, 100.2, 104.2, 113.7, 131.2, 159.5, 193,
289 220.4, 238.1, 250.2, 258.1, 264.7, 269.7, 273.7, 277.3, 280.2, 282.8,
290 284.9, 286.5, 288.1, 288.8, 289, 288.5, 287.2, 286.3, 286.1, 287.2,
291 287.5, 286.2, 285.8},
292 {335, 336, 335.7, 335.1, 332.3, 328.1, 320.6, 311.8, 305.1, 301.9,
293 297.6, 290, 280.4, 268.3, 254.6, 239.6, 223.9, 207.9, 192.2, 176.9,
294 161.7, 146.4, 132.2, 120.6, 112.3, 107.2, 104.3, 102.4, 101.3,
295 100.4, 99.86, 99.47, 99.16, 98.97, 98.94, 98.97, 99, 99.09, 99.2,
296 99.31, 99.35, 99.41, 99.51, 99.86, 101.1, 104.9, 114.3, 131, 156.8,
297 186.3, 209.3, 224.6, 236.8, 246.3, 254.9, 262.3, 268.8, 274.8,
298 279.9, 284.6, 288.6, 291.6, 294.9, 297.5, 299.8, 301.8, 303.1,
299 304.3, 304.9, 306, 306.6, 306.2, 306},
300 {306.2, 306.7, 305.7, 307.1, 307.3, 306.4, 301.8, 296.2, 292.4,
301 290.3, 287.1, 280.9, 273.4, 264.3, 254.1, 242.8, 231, 219, 207.2,
302 195.5, 183.3, 169.7, 154.7, 138.7, 124.1, 113.6, 107.8, 104.7,
303 102.8, 101.7, 100.9, 100.4, 100, 99.79, 99.7, 99.66, 99.68, 99.79,
304 99.94, 100.2, 100.5, 100.9, 101.4, 102.1, 103.4, 107, 115.2, 129.1,
305 148.7, 171, 190.8, 205.6, 218.4, 229.4, 239.6, 248.6, 256.5,
306 263.7, 270.3, 276.6, 282.6, 288.1, 294.5, 300.4, 306.3, 311.4,
307 315.1, 318.3, 320.3, 322.2, 322.8, 321.5, 321.1},
308 {266.5, 264.9, 260.8, 261, 262, 263, 261.3, 259.7, 259.2, 259.8,
309 260.1, 258.6, 256.7, 253.6, 249.5, 243.9, 237.4, 230, 222.1, 213.9,
310 205, 194.4, 180.4, 161.8, 140.7, 122.9, 112.1, 106.7, 104.1, 102.7,
311 101.8, 101.4, 101.1, 101, 101, 101, 101.1, 101.2, 101.5, 101.9,
312 102.4, 103, 103.8, 104.9, 106.8, 110.1, 115.6, 124, 135.2, 148.9,
313 165.2, 181.3, 198, 211.8, 223.5, 233.8, 242.9, 251.5, 259, 266.2,
314 273.1, 279.2, 286.2, 292.8, 299.6, 306, 311.1, 315.5, 318.8, 322.6,
315 325.3, 325.8, 325.8},
316 {220.1, 218.1, 210.8, 207.2, 207.6, 210.5, 211.4, 213.5, 217.3,
317 222.4, 227.9, 232.8, 237.4, 240.8, 242.8, 243, 241.5, 238.6, 234.2,
318 228.5, 221, 210.7, 195.1, 172.9, 147.8, 127.6, 115.6, 109.9, 107.1,
319 105.7, 105, 104.8, 104.8, 104.9, 105, 105.1, 105.3, 105.5, 105.8,
320 106.4, 107, 107.6, 108.1, 108.8, 110, 111.8, 114.2, 117.4, 121.6,
321 127.9, 137.3, 151.2, 169.5, 189, 205.8, 218.9, 229.1, 237.8, 245,
322 251.5, 257.1, 262.3, 268.2, 274, 280.4, 286.7, 292.4, 297.9, 302.9,
323 308.5, 312.2, 313.1, 313.3},
324 {187.4, 184.5, 173.3, 166.1, 165.4, 167.8, 169.6, 173.6, 179.6,
325 187.9, 198.9, 210, 220.5, 229.2, 235.7, 239.9, 241.8, 241.6, 239.6,
326 235.8, 229.4, 218.6, 200.9, 175.9, 149.4, 129.4, 118.3, 113.1,
327 110.8, 109.7, 109.3, 109.4, 109.7, 110, 110.2, 110.4, 110.5, 110.7,
328 111, 111.4, 111.8, 112.1, 112.3, 112.7, 113.2, 113.9, 115, 116.4,
329 117.9, 120.4, 124.1, 130.9, 142.2, 159.6, 179.6, 198.5, 212.9,
330 224.2, 232.7, 239.1, 243.8, 247.7, 252.4, 257.3, 263.2, 269.5,
331 275.4, 281.1, 286.3, 292, 296.3, 298.2, 298.8},
332 {166, 166.4, 155.7, 148.3, 147.1, 149, 152.1, 157, 163.6, 172.4,
333 185.3, 199.2, 212.6, 224, 233.2, 239.6, 243.3, 244.6, 243.6, 240.3,
334 233.9, 222.6, 203.7, 177, 149.5, 129.7, 119, 114, 111.7, 110.7,
335 110.3, 110.3, 110.6, 110.9, 111.1, 111.3, 111.5, 111.6, 111.9,
336 112.2, 112.5, 112.6, 112.8, 113, 113.4, 114, 115.1, 116.5, 118.3,
337 120.9, 124.4, 130.2, 139.4, 154.6, 173.8, 193.1, 208.1, 220.4,
338 230.1, 238.2, 244.7, 249.5, 254.5, 259.3, 264.5, 269.4, 273.7,
339 278.2, 282.6, 287.4, 290.9, 292.5, 293},
340 {171.9, 172.8, 166.2, 162.3, 161.4, 162.5, 165.2, 169.6, 175.3,
341 183.1, 193.8, 205.9, 218.3, 229.6, 238.5, 244.3, 246.9, 246.7,
342 243.8, 238.4, 230.2, 217.9, 199.6, 174.9, 148.9, 129.8, 119.5,
343 114.8, 112.3, 110.9, 110.3, 110.1, 110.2, 110.3, 110.4, 110.5,
344 110.6, 110.8, 111, 111.4, 111.8, 112, 112.2, 112.4, 112.9, 113.6,
345 114.7, 116.3, 118.4, 121.9, 127.1, 136.1, 149.8, 168.4, 186.9,
346 203.3, 217, 229.1, 238.7, 247, 254, 259.3, 264.3, 268.3, 272.5,
347 276.6, 280.4, 284.4, 288.4, 293.3, 297.2, 298.7, 299.1},
348 {191.6, 192.2, 189, 188.1, 190.2, 193.7, 197.8, 202.9, 208.5,
349 215.6, 224.2, 233.1, 241.2, 247.3, 250.8, 251.3, 248.9, 244.2,
350 237.3, 228.4, 217.2, 202.9, 184.5, 162.5, 140.7, 124.8, 116.2,
351 111.8, 109.4, 107.9, 107, 106.7, 106.6, 106.6, 106.7, 106.7,
352 106.8, 107, 107.4, 108, 108.7, 109.3, 109.8, 110.4, 111.2,
353 112.4, 114.2, 116.9, 121.1, 127.9, 139.3, 155.2, 173.6, 190.7,
354 206.1, 220.1, 232.3, 243, 251.8, 259.2, 265.7, 270.6, 275.3,
355 279.3, 283.3, 286.9, 289.7, 292.8, 296.1, 300.5, 303.9, 304.8,
356 305.1},
357 {241.5, 239.6, 236.8, 237.4, 239.4, 242.3, 244.2, 246.4, 249.2,
358 253.6, 258.6, 262.7, 264.8, 264.2, 260.6, 254.1, 245.5, 235.3,
359 223.9, 211.7, 198.3, 183.1, 165.6, 147.1, 130.5, 118.7, 111.9,
360 108.1, 105.8, 104.3, 103.4, 102.8, 102.5, 102.4, 102.5, 102.5,
361 102.5, 102.7, 103.1, 103.8, 104.6, 105.4, 106.1, 107, 108.2,
362 109.9, 112.8, 117.5, 126, 140.4, 161, 181.9, 201.2, 216.8, 230.4,
363 241.8, 251.4, 259.9, 266.9, 272.8, 277.4, 280.4, 282.9, 284.6,
364 286.1, 287.4, 288.3, 289.5, 290.9, 294.2, 296.9, 297.5, 297.6},
365 {301.2, 300.3, 296.6, 295.4, 295, 294.3, 291.2, 287.4, 284.9, 284.7,
366 284.1, 281.5, 277.1, 270.4, 261.7, 250.6, 237.6, 223.1, 207.9, 192,
367 175.8, 158.8, 142.1, 127.6, 116.8, 109.9, 106, 103.6, 102.1, 101.1,
368 100.4, 99.96, 99.6, 99.37, 99.32, 99.32, 99.31, 99.46, 99.77, 100.2,
369 100.7, 101.3, 101.8, 102.7, 104.1, 106.8, 111.9, 121, 136.7, 160,
370 186.9, 209.9, 228.1, 241.2, 251.5, 259.5, 265.7, 270.9, 274.8, 278,
371 280.3, 281.8, 283, 283.3, 283.7, 283.8, 283, 282.2, 281.2, 281.4,
372 281.7, 281.1, 281.2}
373 };
374 memcpy(clim->tropo, tropo, sizeof(clim->tropo));
375
376 /* Get range... */
377 double tropomin = 1e99, tropomax = -1e99;
378 for (int it = 0; it < clim->tropo_ntime; it++)
379 for (int iy = 0; iy < clim->tropo_nlat; iy++) {
380 tropomin = MIN(tropomin, clim->tropo[it][iy]);
381 tropomax = MAX(tropomax, clim->tropo[it][iy]);
382 }
383
384 /* Write info... */
385 LOG(2, "Number of time steps: %d", clim->tropo_ntime);
386 LOG(2, "Time steps: %.2f, %.2f ... %.2f s",
387 clim->tropo_time[0], clim->tropo_time[1],
388 clim->tropo_time[clim->tropo_ntime - 1]);
389 LOG(2, "Number of latitudes: %d", clim->tropo_nlat);
390 LOG(2, "Latitudes: %g, %g ... %g deg",
391 clim->tropo_lat[0], clim->tropo_lat[1],
392 clim->tropo_lat[clim->tropo_nlat - 1]);
393 LOG(2, "Tropopause altitude range: %g ... %g hPa", Z(tropomax),
394 Z(tropomin));
395 LOG(2, "Tropopause pressure range: %g ... %g hPa", tropomin, tropomax);
396}
#define MIN(a, b)
Macro to determine the minimum of two values.
Definition mptrac.h:1527
#define Z(p)
Convert pressure to altitude.
Definition mptrac.h:2303
#define LOG(level,...)
Print a log message with a specified logging level.
Definition mptrac.h:2396

◆ clim_ts()

double clim_ts ( const clim_ts_t * ts,
const double t )

Interpolates a time series of climatological variables.

This function interpolates a time series of climatological variables based on the input time and the provided data points.

Parameters
tsPointer to the time series structure containing data points.
tTime at which to interpolate the climatological variable (in seconds).
Returns
Interpolated value of the climatological variable at the given time.

This function performs linear interpolation between the closest data points to the input time t. If t is outside the range of the provided time series, the value at the nearest boundary is returned.

Author
Lars Hoffmann

Definition at line 400 of file mptrac.c.

402 {
403
404 /* Interpolate... */
405 if (t <= ts->time[0])
406 return ts->vmr[0];
407 else if (t >= ts->time[ts->ntime - 1])
408 return ts->vmr[ts->ntime - 1];
409 else {
410 const int idx = locate_irr(ts->time, ts->ntime, t);
411 return LIN(ts->time[idx], ts->vmr[idx],
412 ts->time[idx + 1], ts->vmr[idx + 1], t);
413 }
414}
double vmr[CTS]
Volume mixing ratio [ppv].
Definition mptrac.h:3850
double time[CTS]
Time [s].
Definition mptrac.h:3847
int ntime
Number of timesteps.
Definition mptrac.h:3844
Here is the call graph for this function:

◆ clim_zm()

double clim_zm ( const clim_zm_t * zm,
const double t,
const double lat,
const double p )

Interpolates monthly mean zonal mean climatological variables.

This function interpolates climatological variables based on pressure, latitude, and time. The climatological data is provided in the form of monthly mean zonal mean values.

Parameters
zmPointer to the climatological zonal mean structure containing data points.
tTime at which to interpolate the climatological variable (in seconds since the beginning of the year).
latLatitude at which to interpolate the climatological variable (in degrees).
pPressure at which to interpolate the climatological variable (in hPa).
Returns
Interpolated value of the climatological variable at the given pressure, latitude, and time.

This function performs trilinear interpolation between the nearest data points to the input time t, latitude lat, and pressure or altitude p. If the input values are outside the range of the provided data, the function extrapolates by using the nearest boundary values.

Author
Lars Hoffmann

Definition at line 418 of file mptrac.c.

422 {
423
424 /* Get seconds since begin of year... */
425 double sec = FMOD(t, 365.25 * 86400.);
426 while (sec < 0)
427 sec += 365.25 * 86400.;
428
429 /* Check pressure range... */
430 double p_help = p;
431 if (p < zm->p[zm->np - 1])
432 p_help = zm->p[zm->np - 1];
433 else if (p > zm->p[0])
434 p_help = zm->p[0];
435
436 /* Check latitude range... */
437 double lat_help = lat;
438 if (lat < zm->lat[0])
439 lat_help = zm->lat[0];
440 else if (lat > zm->lat[zm->nlat - 1])
441 lat_help = zm->lat[zm->nlat - 1];
442
443 /* Get indices... */
444 const int isec = locate_irr(zm->time, zm->ntime, sec);
445 const int ilat = locate_reg(zm->lat, zm->nlat, lat_help);
446 const int ip = locate_irr(zm->p, zm->np, p_help);
447
448 /* Interpolate climatology data... */
449 const double aux00 = LIN(zm->p[ip], zm->vmr[isec][ip][ilat],
450 zm->p[ip + 1], zm->vmr[isec][ip + 1][ilat],
451 p_help);
452 const double aux01 = LIN(zm->p[ip], zm->vmr[isec][ip][ilat + 1],
453 zm->p[ip + 1], zm->vmr[isec][ip + 1][ilat + 1],
454 p_help);
455 const double aux10 = LIN(zm->p[ip], zm->vmr[isec + 1][ip][ilat],
456 zm->p[ip + 1], zm->vmr[isec + 1][ip + 1][ilat],
457 p_help);
458 const double aux11 = LIN(zm->p[ip], zm->vmr[isec + 1][ip][ilat + 1],
459 zm->p[ip + 1], zm->vmr[isec + 1][ip + 1][ilat + 1],
460 p_help);
461 const double aux0 =
462 LIN(zm->lat[ilat], aux00, zm->lat[ilat + 1], aux01, lat_help);
463 const double aux1 =
464 LIN(zm->lat[ilat], aux10, zm->lat[ilat + 1], aux11, lat_help);
465 const double aux = LIN(zm->time[isec], aux0, zm->time[isec + 1], aux1, sec);
466 return MAX(aux, 0.0);
467}
double p[CP]
Pressure [hPa].
Definition mptrac.h:3879
Here is the call graph for this function:

◆ compress_log_level()

void compress_log_level ( FILE * out,
const char * codec,
const char * varname,
const size_t lev,
const double plev,
const double ratio,
const double bpv,
const double t_comp,
const double t_decomp,
const size_t n,
const size_t nbytes,
const float * org,
const float * cmp )

Write one row of per-level compression diagnostics.

This helper computes the error statistics for one level (from org and cmp) and writes one ASCII table row to out. If rho is NAN, the correlation coefficient is derived from org and cmp using GSL.

Parameters
[in,out]outOutput stream.
[in]codecCompression codec name.
[in]varnameVariable name.
[in]levLevel index.
[in]plevPressure level in hPa.
[in]ratioCompression ratio.
[in]bpvBits per value.
[in]t_compCompression time in seconds.
[in]t_decompDecompression time in seconds.
[in]nNumber of data values in the level slice.
[in]nbytesByte count used for throughput reporting.
[in]orgOriginal level data.
[in]cmpReconstructed level data.
Author
Lars Hoffmann

Definition at line 670 of file mptrac.c.

683 {
684
685 static FILE *last_out = NULL;
686 static char last_var[LEN] = "";
687
688 /* Calculate error statistics... */
689 double mean_err = 0.0, stddev_err = 0.0;
690 double nrmse = NAN, mean_orig = 0.0, orig_range = 0.0, rho = NAN;
691
692 double sum_err = 0.0, sumsq_err = 0.0;
693 double sum_orig = 0.0, sum_cmp = 0.0;
694 double sumsq_orig = 0.0, sumsq_cmp = 0.0, sum_org_cmp = 0.0;
695
696 double min_orig = 0.0, max_orig = 0.0;
697 double min_err = 0.0, max_err = 0.0;
698
699 /* Accumulate error, signal and cross-product sums in one pass... */
700 for (size_t i = 0; i < n; i++) {
701 const double o = (double) org[i];
702 const double c = (double) cmp[i];
703 const double e = c - o;
704
705 sum_err += e;
706 sumsq_err += e * e;
707 sum_orig += o;
708 sum_cmp += c;
709
710 sumsq_orig += o * o;
711 sumsq_cmp += c * c;
712 sum_org_cmp += o * c;
713
714 if (e < min_err || i == 0)
715 min_err = e;
716 if (e > max_err || i == 0)
717 max_err = e;
718
719 if (o < min_orig || i == 0)
720 min_orig = o;
721 if (o > max_orig || i == 0)
722 max_orig = o;
723 }
724
725 /* Derive the basic error and signal summary statistics... */
726 mean_err = sum_err / (double) n;
727 mean_orig = sum_orig / (double) n;
728 orig_range = max_orig - min_orig;
729
730 /* Convert the accumulated error sums into a standard deviation... */
731 const double var_err =
732 (sumsq_err - (sum_err * sum_err) / (double) n) / (double) n;
733 stddev_err = sqrt(var_err > 0.0 ? var_err : 0.0);
734
735 /* Normalize RMSE by the original data range if available... */
736 nrmse = (orig_range > 0.0)
737 ? sqrt(sumsq_err / (double) n) / orig_range : NAN;
738
739 /* Compute the Pearson correlation from the accumulated moments... */
740 const double nn = (double) n;
741 const double cov = sum_org_cmp - sum_orig * sum_cmp / nn;
742 const double var_orig = sumsq_orig - sum_orig * sum_orig / nn;
743 const double var_cmp = sumsq_cmp - sum_cmp * sum_cmp / nn;
744 const double denom = sqrt(var_orig * var_cmp);
745 rho = denom > 0.0 ? cov / denom : NAN;
746
747 /* Reset the variable separator state when the target file changes... */
748 if (out != last_out) {
749 last_out = out;
750 last_var[0] = '\0';
751 }
752
753 /* Separate diagnostic blocks when switching to a new variable... */
754 if (last_var[0] != '\0' && strcmp(last_var, varname) != 0)
755 fprintf(out, "\n");
756 snprintf(last_var, LEN, "%s", varname);
757
758 /* Logging... */
759 fprintf(out,
760 "%s %s %lu %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",
761 codec, varname, (unsigned long) lev, plev, ratio, bpv, rho,
762 mean_err, stddev_err, min_err, max_err, mean_orig, orig_range,
763 nrmse, t_comp, COMPRESS_SPEED(nbytes, t_comp), t_decomp,
764 COMPRESS_SPEED(nbytes, t_decomp));
765}
#define COMPRESS_SPEED(nbytes, dt)
Calculate compression throughput in MiB/s.
Definition mptrac.h:773

◆ compress_log_levels_3d()

void compress_log_levels_3d ( FILE * out,
const char * codec,
const char * varname,
const met_t * met,
const float * org_all,
const float * cmp_all,
const size_t nxy,
const size_t nz,
const double ratio,
const double bpv,
const double t_comp,
const double t_decomp,
const size_t nbytes )

Write per-level compression diagnostics for a full 3-D field.

This helper extracts each vertical level from the original and reconstructed 3-D fields and forwards the diagnostics to compress_log_level().

Parameters
[in,out]outOutput stream, or NULL to disable logging.
[in]codecCompression codec name.
[in]varnameVariable name.
[in]metMeteorological meta-data with pressure levels.
[in]org_allOriginal 3-D field in horizontal-major order.
[in]cmp_allReconstructed 3-D field in horizontal-major order.
[in]nxyNumber of horizontal points per level.
[in]nzNumber of vertical levels.
[in]ratioCompression ratio.
[in]bpvBits per value.
[in]t_compCompression time in seconds.
[in]t_decompDecompression time in seconds.
[in]nbytesByte count used for throughput reporting.
Author
Lars Hoffmann

Definition at line 769 of file mptrac.c.

782 {
783
784 if (!out)
785 return;
786
787 /* Allocate temporary buffers for one level... */
788 float *tmp_org, *tmp_cmp;
789 ALLOC(tmp_org, float,
790 nxy);
791 ALLOC(tmp_cmp, float,
792 nxy);
793
794 for (size_t lev = 0; lev < nz; lev++) {
795
796 /* Extract current level... */
797#pragma omp parallel for default(shared)
798 for (size_t ixy = 0; ixy < nxy; ixy++) {
799 tmp_org[ixy] = org_all[ixy * nz + lev];
800 tmp_cmp[ixy] = cmp_all[ixy * nz + lev];
801 }
802
803 /* Write diagnostics for the extracted level... */
804 compress_log_level(out, codec, varname, lev, met->p[lev], ratio, bpv,
805 t_comp, t_decomp, nxy, nbytes, tmp_org, tmp_cmp);
806 }
807
808 /* Free... */
809 free(tmp_org);
810 free(tmp_cmp);
811}
void compress_log_level(FILE *out, const char *codec, const char *varname, const size_t lev, const double plev, const double ratio, const double bpv, const double t_comp, const double t_decomp, const size_t n, const size_t nbytes, const float *org, const float *cmp)
Write one row of per-level compression diagnostics.
Definition mptrac.c:670
#define ALLOC(ptr, type, n)
Allocate memory for a pointer with error handling.
Definition mptrac.h:668
double p[EP]
Pressure levels [hPa].
Definition mptrac.h:3979
Here is the call graph for this function:

◆ compress_cms()

void compress_cms ( const ctl_t * ctl,
const met_t * met,
const char * varname,
float * array,
const int decompress,
FILE * level_log,
FILE * inout )

Compresses or decompresses a 3-D meteorological field using cmultiscale.

This routine compresses or decompresses a meteorological field described by the metadata in met. Compression thresholds are selected from ctl based on varname.

Parameters
[in]ctlControl/settings structure providing CMS parameters.
[in]metMeteorological metadata describing the field layout.
[in]varnameVariable name used for selecting the CMS epsilon threshold.
[in,out]arrayField data buffer (decompress: output, compress: input).
[in]decompressNon-zero to decompress; zero to compress.
[in,out]level_logOptional output stream for per-level compression diagnostics, or NULL to disable.
[in,out]inoutBinary stream used for CMS I/O (decompress: read, compress: write).
Author
Lars Hoffmann

◆ compress_scale_to_unit()

void compress_scale_to_unit ( float * array,
const size_t nxy,
const size_t nz,
double * off,
double * scl )

Scales each vertical level of a 3-D field independently to the interval [0,1].

The routine computes per-level offsets and scales from the minimum and maximum values of each vertical slice and transforms the field in place. Constant or nearly constant levels are mapped to zero and can be reconstructed exactly with the stored offsets.

Parameters
[in,out]arrayField values stored in horizontal-major order.
[in]nxyNumber of horizontal points per level.
[in]nzNumber of vertical levels.
[out]offPer-level offsets (minimum values).
[out]sclPer-level scales (ranges).
Author
Lars Hoffmann

Definition at line 815 of file mptrac.c.

820 {
821
822 /* Initialize per-level minima and maxima from the first sample... */
823 for (size_t iz = 0; iz < nz; iz++) {
824 off[iz] = array[iz];
825 scl[iz] = array[iz];
826 }
827
828 /* Scan the remaining samples to get per-level minima and maxima... */
829 for (size_t ixy = 1; ixy < nxy; ixy++)
830 for (size_t iz = 0; iz < nz; iz++) {
831 const double value = array[ixy * nz + iz];
832 if (value < off[iz])
833 off[iz] = value;
834 if (value > scl[iz])
835 scl[iz] = value;
836 }
837
838 /* Convert maxima into ranges and suppress numerically flat levels... */
839 for (size_t iz = 0; iz < nz; iz++) {
840 const double range = scl[iz] - off[iz];
841 const double ref = fmax(1.0, fmax(fabs(off[iz]), fabs(scl[iz])));
842 scl[iz] = !(range > 1e-12 * ref) ? 0.0 : range;
843 }
844
845 /* Scale each level independently to the unit interval... */
846#pragma omp parallel for default(shared)
847 for (size_t ixy = 0; ixy < nxy; ixy++)
848 for (size_t iz = 0; iz < nz; iz++)
849 if (scl[iz] > 0.0)
850 array[ixy * nz + iz] =
851 (float) ((array[ixy * nz + iz] - off[iz]) / scl[iz]);
852 else
853 array[ixy * nz + iz] = 0.0f;
854}

◆ compress_unscale_from_unit()

void compress_unscale_from_unit ( float * array,
const size_t nxy,
const size_t nz,
const double * off,
const double * scl )

Restores a levelwise [0,1]-scaled 3-D field to physical units.

This routine applies the inverse transformation of compress_scale_to_unit() using the supplied per-level offsets and scales. Constant levels are restored directly from their offsets.

Parameters
[in,out]arrayField values stored in horizontal-major order.
[in]nxyNumber of horizontal points per level.
[in]nzNumber of vertical levels.
[in]offPer-level offsets (minimum values).
[in]sclPer-level scales (ranges).
Author
Lars Hoffmann

Definition at line 858 of file mptrac.c.

863 {
864
865 /* Restore each level from unit space back to its original range... */
866#pragma omp parallel for default(shared)
867 for (size_t ixy = 0; ixy < nxy; ixy++)
868 for (size_t iz = 0; iz < nz; iz++)
869 if (scl[iz] > 0.0)
870 array[ixy * nz + iz] =
871 (float) (array[ixy * nz + iz] * scl[iz] + off[iz]);
872 else
873 array[ixy * nz + iz] = (float) off[iz];
874}

◆ compress_read_lossy_scale()

int compress_read_lossy_scale ( FILE * in,
const size_t nz,
double ** off,
double ** scl )

Read optional lossyscaling metadata for a 3-D field.

This helper reads the stored MET_LOSSY_SCALE flag and, if enabled, allocates and fills the per-level offset and scale arrays used by compress_unscale_from_unit(). The caller owns the returned arrays and must free them.

Parameters
[in,out]inInput stream.
[in]nzNumber of vertical levels.
[out]offReturned per-level offsets, or NULL if disabled.
[out]sclReturned per-level scales, or NULL if disabled.
Returns
Stored lossyscaling flag (0 or 1).
Author
Lars Hoffmann

Definition at line 878 of file mptrac.c.

882 {
883
884 int enabled;
885 *off = NULL;
886 *scl = NULL;
887
888 /* Read input... */
889 FREAD(&enabled, int,
890 1,
891 in);
892 if (enabled < 0 || enabled > 1)
893 ERRMSG("Invalid stored MET_LOSSY_SCALE flag!");
894
895 if (enabled > 0) {
896 ALLOC(*off, double,
897 nz);
898 ALLOC(*scl, double,
899 nz);
900 FREAD(*off, double,
901 nz,
902 in);
903 FREAD(*scl, double,
904 nz,
905 in);
906 }
907
908 return enabled;
909}
#define FREAD(ptr, type, size, in)
Read data from a file stream and store it in memory.
Definition mptrac.h:1184

◆ compress_write_lossy_scale()

void compress_write_lossy_scale ( FILE * out,
const int enabled,
float * array,
const size_t nxy,
const size_t nz,
double ** off,
double ** scl )

Write optional lossyscaling metadata for a 3-D field.

This helper writes the MET_LOSSY_SCALE flag and, if enabled, allocates the per-level offset and scale arrays, scales the field in place to [0,1], and writes the resulting metadata to out. The caller owns the returned arrays and must free them.

Parameters
[in,out]outOutput stream.
[in]enabledLossyscaling flag (0 or 1).
[in,out]arrayField values stored in horizontal-major order.
[in]nxyNumber of horizontal points per level.
[in]nzNumber of vertical levels.
[out]offReturned per-level offsets, or NULL if disabled.
[out]sclReturned per-level scales, or NULL if disabled.
Author
Lars Hoffmann

Definition at line 913 of file mptrac.c.

920 {
921
922 *off = NULL;
923 *scl = NULL;
924
925 /* Write output... */
926 FWRITE(&enabled, int,
927 1,
928 out);
929 if (enabled <= 0)
930 return;
931
932 /* Derive per-level scaling data... */
933 ALLOC(*off, double,
934 nz);
935 ALLOC(*scl, double,
936 nz);
937
938 compress_scale_to_unit(array, nxy, nz, *off, *scl);
939
940 FWRITE(*off, double,
941 nz,
942 out);
943 FWRITE(*scl, double,
944 nz,
945 out);
946}
void compress_scale_to_unit(float *array, const size_t nxy, const size_t nz, double *off, double *scl)
Scales each vertical level of a 3-D field independently to the interval [0,1].
Definition mptrac.c:815
#define FWRITE(ptr, type, size, out)
Write data from memory to a file stream.
Definition mptrac.h:1204
Here is the call graph for this function:

◆ compress_metvar_index()

int compress_metvar_index ( const char * varname)

Maps a meteorological variable name to its internal MPTRAC variable index.

The returned index can be used to access variable-specific control arrays such as MET_LOSSY_SCALE, MET_ZFP_PREC, and MET_SZ3_PREC.

Parameters
varnameMeteorological variable name as stored in the meteorological file.
Returns
Internal MPTRAC meteorological variable index.
Author
Lars Hoffmann

Definition at line 973 of file mptrac.c.

974 {
975
976 static const char *const names[] = {
977 "Z", "T", "U", "V", "W", "PV", "H2O", "O3",
978 "LWC", "RWC", "IWC", "SWC", "CC"
979 };
980
981 for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++)
982 if (strcasecmp(varname, names[i]) == 0)
983 return (int) i;
984
985 ERRMSG("Unknown meteorological variable name!");
986}

◆ compress_pck()

void compress_pck ( const ctl_t * ctl,
const met_t * met,
const char * varname,
float * array,
const int decompress,
FILE * level_log,
FILE * inout )

Compresses or decompresses a 3‑D float array using the PCK format.

The routine works on the regular longitude/latitude grid described by the supplied met structure (nx, ny, np and pressure levels). In compress mode the data are scaled to unsigned short values; in decompress mode the values are reconstructed.

Parameters
[in]ctlControl structure with compression parameters.
[in]metMeteorological meta‑data providing grid dimensions and pressure levels.
[in]varnameVariable name for logging and error‑bound selection.
[in,out]arrayFloat array to compress or decompress.
[in]decompressNon‑zero to decompress; zero to compress.
[in,out]level_logOptional per‑level diagnostics stream, or NULL.
[in,out]inoutFile stream for reading/writing the PCK payload.
Author
Lars Hoffmann

Definition at line 990 of file mptrac.c.

997 {
998
999 const size_t nxy = (size_t) met->nx * (size_t) met->ny;
1000 const size_t nz = (size_t) met->np;
1001 const size_t n = nxy * nz;
1002 const size_t nbytes = n * sizeof(float);
1003 const size_t pck_bytes = n * sizeof(uint16_t);
1004
1005 double vmin[EP], vmax[EP], off[EP], scl[EP];
1006 uint16_t *sarray;
1007
1008 /* PCK+ZSTD payload = scale + offset + packed 16-bit samples... */
1009 const size_t payload_len = 2 * nz * sizeof(double) + pck_bytes;
1010 size_t stored_len = payload_len;
1011 const char *codec_info = ctl->met_pck_zstd ? "PCK+ZSTD" : "PCK";
1012
1013 /* Allocate packed sample buffer... */
1014 ALLOC(sarray, uint16_t, n);
1015
1016 /* Read compressed stream and decompress array... */
1017 if (decompress) {
1018 double t_zstd = 0.0;
1019
1020 /* Read packed data... */
1021 if (ctl->met_pck_zstd) {
1022#ifdef ZSTD
1023 uint64_t magic, pck_zstd_magic = UINT64_C(0x50434b5a53544431);
1024 unsigned char *compr = NULL, *payload = NULL;
1025
1026 /* Read input... */
1027 FREAD(&magic, uint64_t, 1, inout);
1028 if (magic != pck_zstd_magic)
1029 ERRMSG("PCK+ZSTD magic mismatch! Check MET_PCK_ZSTD and file type.");
1030
1031 /* Read and decompress the outer ZSTD payload... */
1032 FREAD(&stored_len, size_t,
1033 1,
1034 inout);
1035 ALLOC(compr, unsigned char,
1036 stored_len);
1037 FREAD(compr, unsigned char,
1038 stored_len,
1039 inout);
1040 ALLOC(payload, unsigned char,
1041 payload_len);
1042 const double t0_decomp = omp_get_wtime();
1043 const size_t out_len =
1044 ZSTD_decompress(payload, payload_len, compr, stored_len);
1045 t_zstd = omp_get_wtime() - t0_decomp;
1046 if (ZSTD_isError(out_len) || out_len != payload_len)
1047 ERRMSG("PCK ZSTD decompression failed or size mismatch!");
1048
1049 /* Split payload into scale, offset and packed samples... */
1050 memcpy(scl, payload, nz * sizeof(double));
1051 memcpy(off, payload + nz * sizeof(double), nz * sizeof(double));
1052 memcpy(sarray, payload + 2 * nz * sizeof(double), pck_bytes);
1053
1054 /* Free... */
1055 free(payload);
1056 free(compr);
1057#else
1058 ERRMSG("MPTRAC was compiled without ZSTD compression!");
1059#endif
1060 } else {
1061 /* Read input... */
1062 FREAD(&scl, double,
1063 nz,
1064 inout);
1065 FREAD(&off, double,
1066 nz,
1067 inout);
1068 FREAD(sarray, uint16_t, n, inout);
1069 }
1070
1071 /* Measure the scalar unpacking step separately from optional ZSTD... */
1072 const double t0 = omp_get_wtime();
1073
1074 /* Convert packed 16-bit samples back to floating-point values... */
1075#pragma omp parallel for default(shared)
1076 for (size_t ixy = 0; ixy < nxy; ixy++)
1077 for (size_t iz = 0; iz < nz; iz++)
1078 array[ixy * nz + iz]
1079 = (float) (sarray[ixy * nz + iz] * scl[iz] + off[iz]);
1080
1081 /* Add optional ZSTD time to the scalar unpacking time... */
1082 const double t_decomp = t_zstd + omp_get_wtime() - t0;
1083
1084 /* Logging... */
1085 LOG(2, "Read 3-D variable: %s"
1086 " (%s, RATIO=%g, BPV=%g, T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1087 varname, codec_info, COMPRESS_RATIO(nbytes, stored_len),
1088 COMPRESS_BPV(n, stored_len), t_decomp, COMPRESS_SPEED(nbytes,
1089 t_decomp));
1090 }
1091
1092 /* Compress array and output compressed stream... */
1093 else {
1094 float *tmp_org, *tmp_pck;
1095 double t_comp_sum = 0, t_decomp_sum = 0, t_zstd = 0, t_zstd_decomp = 0;
1096 double t_comp_level[EP], t_decomp_level[EP];
1097
1098 /* Allocate temporary buffers for one level... */
1099 ALLOC(tmp_org, float,
1100 nxy);
1101 ALLOC(tmp_pck, float,
1102 nxy);
1103
1104 /* Derive per-level minima and maxima for the 16-bit quantization... */
1105 for (size_t iz = 0; iz < nz; iz++) {
1106 vmin[iz] = array[iz];
1107 vmax[iz] = array[iz];
1108 }
1109 for (size_t ixy = 1; ixy < nxy; ixy++)
1110 for (size_t iz = 0; iz < nz; iz++) {
1111 if (array[ixy * nz + iz] < vmin[iz])
1112 vmin[iz] = array[ixy * nz + iz];
1113 if (array[ixy * nz + iz] > vmax[iz])
1114 vmax[iz] = array[ixy * nz + iz];
1115 }
1116
1117 /* Derive per-level offset and scaling factor... */
1118 for (size_t iz = 0; iz < nz; iz++) {
1119 scl[iz] = (vmax[iz] - vmin[iz]) / 65533.;
1120 off[iz] = vmin[iz];
1121 }
1122
1123 /* Quantize each level and time encode/decode diagnostics on the fly... */
1124 for (size_t iz = 0; iz < nz; iz++) {
1125 const double t0 = omp_get_wtime();
1126
1127#pragma omp parallel for default(shared)
1128 for (size_t ixy = 0; ixy < nxy; ixy++)
1129 if (scl[iz] != 0)
1130 sarray[ixy * nz + iz] =
1131 (uint16_t) ((array[ixy * nz + iz] - off[iz]) / scl[iz] + .5);
1132 else
1133 sarray[ixy * nz + iz] = 0;
1134
1135 t_comp_level[iz] = omp_get_wtime() - t0;
1136 t_comp_sum += t_comp_level[iz];
1137
1138 const double t1 = omp_get_wtime();
1139
1140#pragma omp parallel for default(shared)
1141 for (size_t ixy = 0; ixy < nxy; ixy++) {
1142 tmp_org[ixy] = array[ixy * nz + iz];
1143 tmp_pck[ixy] = (float) (sarray[ixy * nz + iz] * scl[iz] + off[iz]);
1144 }
1145
1146 t_decomp_level[iz] = omp_get_wtime() - t1;
1147 t_decomp_sum += t_decomp_level[iz];
1148 }
1149
1150 /* Write packed data, optionally wrapped in ZSTD... */
1151 if (ctl->met_pck_zstd) {
1152#ifdef ZSTD
1153 uint64_t pck_zstd_magic = UINT64_C(0x50434b5a53544431);
1154 unsigned char *payload = NULL, *payload_chk = NULL;
1155 void *stored_data = NULL;
1156
1157 /* Pack plain PCK data into one ZSTD payload... */
1158 ALLOC(payload, unsigned char,
1159 payload_len);
1160 memcpy(payload, scl, nz * sizeof(double));
1161 memcpy(payload + nz * sizeof(double), off, nz * sizeof(double));
1162 memcpy(payload + 2 * nz * sizeof(double), sarray, pck_bytes);
1163 const size_t dst_cap = ZSTD_compressBound(payload_len);
1164 ALLOC(stored_data, char,
1165 dst_cap);
1166 ZSTD_CCtx *cctx = compress_zstd_create_cctx(ctl->met_zstd_level,
1167 ctl->met_zstd_nworkers);
1168 const double t0_comp = omp_get_wtime();
1169 stored_len =
1170 ZSTD_compress2(cctx, stored_data, dst_cap, payload, payload_len);
1171 t_zstd = omp_get_wtime() - t0_comp;
1172 ZSTD_freeCCtx(cctx);
1173 if (ZSTD_isError(stored_len))
1174 ERRMSG("PCK ZSTD compression failed!");
1175
1176 /* Decompress once for validation and timing... */
1177 ALLOC(payload_chk, unsigned char,
1178 payload_len);
1179 const double t0_decomp2 = omp_get_wtime();
1180 const size_t out_len2 =
1181 ZSTD_decompress(payload_chk, payload_len, stored_data, stored_len);
1182 t_zstd_decomp = omp_get_wtime() - t0_decomp2;
1183 if (ZSTD_isError(out_len2) || out_len2 != payload_len)
1184 ERRMSG("PCK ZSTD decompression failed or size mismatch!");
1185
1186 /* Free... */
1187 free(payload_chk);
1188 free(payload);
1189
1190 /* Write output... */
1191 FWRITE(&pck_zstd_magic, uint64_t, 1, inout);
1192 FWRITE(&stored_len, size_t,
1193 1,
1194 inout);
1195 FWRITE(stored_data, unsigned char,
1196 stored_len,
1197 inout);
1198
1199 /* Free... */
1200 free(stored_data);
1201#else
1202 ERRMSG("MPTRAC was compiled without ZSTD compression!");
1203#endif
1204 } else {
1205
1206 /* Write output... */
1207 FWRITE(&scl, double,
1208 nz,
1209 inout);
1210 FWRITE(&off, double,
1211 nz,
1212 inout);
1213 FWRITE(sarray, uint16_t, n, inout);
1214 }
1215
1216 /* Combine PCK and optional ZSTD timing and size metrics... */
1217 const double ratio_out = COMPRESS_RATIO(nbytes, stored_len);
1218 const double bpv_out = COMPRESS_BPV(n, stored_len);
1219 const double t_comp = t_comp_sum + t_zstd;
1220 const double t_decomp = t_decomp_sum + t_zstd_decomp;
1221
1222 /* Logging... */
1223 LOG(2, "Write 3-D variable: %s"
1224 " (%s, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s,"
1225 " T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1226 varname, codec_info, ratio_out, bpv_out, t_comp,
1227 COMPRESS_SPEED(nbytes, t_comp), t_decomp,
1228 COMPRESS_SPEED(nbytes, t_decomp));
1229
1230 /* Distribute optional ZSTD cost across levels for diagnostics... */
1231 if (level_log) {
1232 const double t_zstd_level = t_zstd / (double) nz;
1233 const double t_zstd_decomp_level = t_zstd_decomp / (double) nz;
1234 const char *codec = ctl->met_pck_zstd ? "PCKZSTD" : "PCK";
1235 for (size_t iz = 0; iz < nz; iz++) {
1236#pragma omp parallel for default(shared)
1237
1238 /* Rebuild one decoded level for diagnostics... */
1239 for (size_t ixy = 0; ixy < nxy; ixy++) {
1240 tmp_org[ixy] = array[ixy * nz + iz];
1241 tmp_pck[ixy] = (float) (sarray[ixy * nz + iz] * scl[iz] + off[iz]);
1242 }
1243
1244 /* Logging... */
1245 compress_log_level(level_log, codec, varname, iz, met->p[iz],
1246 ratio_out, bpv_out,
1247 t_comp_level[iz] + t_zstd_level,
1248 t_decomp_level[iz] + t_zstd_decomp_level,
1249 nxy, nxy * sizeof(float), tmp_org, tmp_pck);
1250 }
1251 }
1252
1253 /* Free... */
1254 free(tmp_org);
1255 free(tmp_pck);
1256 }
1257
1258 /* Free... */
1259 free(sarray);
1260}
#define COMPRESS_BPV(n, stored_size)
Calculate bits per value from stored size and element count.
Definition mptrac.h:797
#define COMPRESS_RATIO(raw_size, stored_size)
Calculate the compression ratio from raw and stored byte counts.
Definition mptrac.h:785
#define EP
Maximum number of pressure levels for meteo data.
Definition mptrac.h:544
int met_zstd_nworkers
ZSTD number of worker threads (0=single-threaded, default=4).
Definition mptrac.h:2955
int met_zstd_level
ZSTD compression level (from -5 to 22, default=-3).
Definition mptrac.h:2952
int met_pck_zstd
Apply an additional ZSTD compression step to PCK payloads (0=off, 1=on).
Definition mptrac.h:2961
int nx
Number of longitudes.
Definition mptrac.h:3961
int ny
Number of latitudes.
Definition mptrac.h:3964
int np
Number of pressure levels.
Definition mptrac.h:3967
Here is the call graph for this function:

◆ compress_sz3()

void compress_sz3 ( const ctl_t * ctl,
const met_t * met,
const char * varname,
float * array,
const int decompress,
FILE * level_log,
FILE * inout )

Compresses or decompresses a 3-D float array using the SZ3 library.

This function either compresses a 3-D floating-point array and writes it to a file stream, or reads compressed SZ3 data from a file stream and decompresses it into the provided array. The SZ3 error bound can be specified either by relative precision (bits) or absolute tolerance.

Parameters
[in]ctlControl structure with compression parameters.
[in]metMeteorological data providing dimensions.
[in]varnameVariable name for logging.
[in,out]arrayFloat array to compress or decompress.
[in]decompressNon-zero to decompress; zero to compress.
[in,out]level_logOptional per-level diagnostics stream, or NULL.
[in,out]inoutFile stream for reading/writing compressed data.
Note
The function uses ctl->met_sz3_prec[] and ctl->met_sz3_tol[] to determine the error bound.
Exactly one of ctl->met_sz3_prec[] or ctl->met_sz3_tol[] must be set to a positive value.
The SZ3 data type is fixed to SZ_FLOAT for this function.
Exceptions
ERRMSGif input parameters are invalid, memory allocation fails, compression/decompression fails, or file I/O errors occur.
See also
SZ_compress_args
SZ_decompress
Author
Lars Hoffmann

◆ compress_zfp()

void compress_zfp ( const ctl_t * ctl,
const met_t * met,
const char * varname,
float * array,
const int decompress,
FILE * level_log,
FILE * inout )

Compresses or decompresses a 3D array of floats using the ZFP library.

This function either compresses or decompresses a 3D array of floats based on the value of the decompress parameter. Compression reduces the storage size using the ZFP compression algorithm, which supports fixed-precision or fixed-accuracy modes. Decompression restores the original float values from the compressed representation.

Parameters
[in]ctlControl structure with compression parameters.
[in]metMeteorological data providing dimensions.
[in]varnameVariable name for logging.
[in,out]arrayFloat array to compress or decompress.
[in]decompressNon-zero to decompress; zero to compress.
[in,out]level_logOptional per-level diagnostics stream, or NULL.
[in,out]inoutFile stream for reading/writing compressed data.

The function performs the following steps:

  • Allocates metadata for the 3D array and the ZFP compressed stream.
  • Sets the compression mode based on the precision or tolerance parameters.
  • Allocates a buffer for the compressed data.
  • Associates a bit stream with the allocated buffer and sets up the ZFP stream.
  • If decompressing:
    • Reads the size of the compressed data and the compressed data itself from the file.
    • Decompresses the data and stores it in the array.
  • If compressing:
    • Compresses the data and writes the compressed data size and the compressed data itself to the file.

The function logs the compression or decompression details and frees allocated resources before returning.

Note
The function uses ctl->met_zfp_prec[] and ctl->met_zfp_tol[] to determine the error bound.
Ensure that either the precision or tolerance parameter is set to a value greater than 0.
Author
Lars Hoffmann

◆ compress_zstd()

void compress_zstd ( const ctl_t * ctl,
const met_t * met,
const char * varname,
float * array,
const int decompress,
FILE * level_log,
FILE * inout )

Compresses or decompresses a float array using ZSTD.

The routine compresses or decompresses one full 3-D meteorological field as a raw byte stream. It does not apply level-wise scaling or quantization; the reconstructed field is the direct result of the ZSTD frame decode.

Parameters
[in]ctlControl structure with compression parameters.
[in]metMeteorological data providing grid dimensions and pressure levels.
[in]varnameVariable name for logging.
[in,out]arrayFloat array to compress or decompress.
[in]decompressNon-zero to decompress; zero to compress.
[in,out]level_logOptional per-level diagnostics stream, or NULL.
[in,out]inoutFile stream for reading/writing the ZSTD payload.
Note
This function uses ZSTD's advanced compression API (ZSTD_compress2) and may use multiple workers as configured in ctl.
Author
Lars Hoffmann

◆ compress_lz4()

void compress_lz4 ( const ctl_t * ctl,
const met_t * met,
const char * varname,
float * array,
const int decompress,
FILE * level_log,
FILE * inout )

Compresses or decompresses a float array using LZ4.

The routine compresses or decompresses one full 3-D meteorological field as a raw byte stream. It does not apply level-wise scaling or quantization; the reconstructed field is the direct result of the LZ4 block decode.

Parameters
[in]ctlControl structure with compression parameters.
[in]metMeteorological data providing grid dimensions and pressure levels.
[in]varnameVariable name for logging.
[in,out]arrayFloat array to compress or decompress.
[in]decompressNon-zero to decompress; zero to compress.
[in,out]level_logOptional per-level diagnostics stream, or NULL.
[in,out]inoutFile pointer for input/output. Used for reading or writing compressed data.
Note
This function uses the block API (LZ4_compress_fast / LZ4_decompress_safe).
The default acceleration factor is 1 when ctl->met_lz4_accel is not positive.
Author
Lars Hoffmann

◆ cos_sza()

double cos_sza ( const double sec,
const double lon,
const double lat )

Calculates the cosine of the solar zenith angle.

This function computes the cosine of the solar zenith angle (SZA), which describes the angle between the local zenith (straight up) and the line connecting the observer to the center of the Sun. The cosine of the SZA is often used directly in radiative transfer and photochemical calculations to avoid unnecessary use of trigonometric inverse functions.

Parameters
secSeconds elapsed since 2000-01-01T12:00Z.
lonObserver's longitude in degrees.
latObserver's latitude in degrees.
Returns
The cosine of the solar zenith angle (dimensionless, range [-1, 1]).

The cosine of the solar zenith angle is computed based on the observer's position (longitude and latitude) and the specified time in seconds elapsed since 2000-01-01T12:00Z.

Note
The input longitude and latitude must be specified in degrees.
See also
acos() — can be used to convert the returned value to the solar zenith angle in radians if needed.
Author
Lars Hoffmann

Definition at line 1861 of file mptrac.c.

1864 {
1865
1866 /* Number of days and fraction with respect to 2000-01-01T12:00Z... */
1867 const double D = sec / 86400 - 0.5;
1868
1869 /* Geocentric apparent ecliptic longitude [rad]... */
1870 const double g = DEG2RAD(357.529 + 0.98560028 * D);
1871 const double q = 280.459 + 0.98564736 * D;
1872 const double L = DEG2RAD(q + 1.915 * sin(g) + 0.020 * sin(2 * g));
1873
1874 /* Mean obliquity of the ecliptic [rad]... */
1875 const double e = DEG2RAD(23.439 - 0.00000036 * D);
1876
1877 /* Declination [rad]... */
1878 const double sindec = sin(e) * sin(L);
1879
1880 /* Right ascension [rad]... */
1881 const double ra = atan2(cos(e) * sin(L), cos(L));
1882
1883 /* Greenwich Mean Sidereal Time [h]... */
1884 const double GMST = 18.697374558 + 24.06570982441908 * D;
1885
1886 /* Local Sidereal Time [h]... */
1887 const double LST = GMST + lon / 15;
1888
1889 /* Hour angle [rad]... */
1890 const double h = LST / 12 * M_PI - ra;
1891
1892 /* Convert latitude... */
1893 const double lat_help = DEG2RAD(lat);
1894
1895 /* Return cosine of solar zenith angle... */
1896 return sin(lat_help) * sindec + cos(lat_help) * sqrt(1 -
1897 SQR(sindec)) * cos(h);
1898}
#define SQR(x)
Compute the square of a value.
Definition mptrac.h:2097

◆ day2doy()

void day2doy ( const int year,
const int mon,
const int day,
int * doy )

Get day of year from date.

Converts a given date to the day of the year (DOY).

This function computes the day of the year (DOY) for a given date specified by the year, month, and day. It takes into account whether the given year is a leap year or not.

Parameters
yearThe year of the date.
monThe month of the date (1-12).
dayThe day of the month (1-31).
doyPointer to an integer where the computed day of the year will be stored.

The function uses two arrays, d0 and d0l, which contain the cumulative number of days at the start of each month for non-leap years and leap years respectively. It checks if the year is a leap year and calculates the day of the year accordingly.

Note
The function assumes that the input date is valid.
Author
Lars Hoffmann

Definition at line 1902 of file mptrac.c.

1906 {
1907
1908 const int
1909 d0[12] = { 1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 },
1910 d0l[12] = { 1, 32, 61, 92, 122, 153, 183, 214, 245, 275, 306, 336 };
1911
1912 /* Get day of year... */
1913 if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
1914 *doy = d0l[mon - 1] + day - 1;
1915 else
1916 *doy = d0[mon - 1] + day - 1;
1917}

◆ dd_assign_subdomains()

void dd_assign_subdomains ( const ctl_t * ctl,
const dd_t * dd,
atm_t * atm,
const int init )

Assign or update particle subdomain ownership.

This routine determines whether each atmospheric particle belongs to the local MPI subdomain and updates the domain-decomposition bookkeeping quantities stored in the atmospheric state.

The particle longitude and latitude are first normalized using dd_normalize_lon_lat() to ensure consistency with the longitude convention and pole handling of the global meteorological grid stored in the domain decomposition structure.

The particle position is then mapped to global grid indices using locate_reg() for longitude and locate_irr() for latitude. These indices are compared with the index range of the local subdomain owned by the current MPI rank.

If init is nonzero, the routine performs the initial ownership assignment. Particles inside the local subdomain are assigned to the current MPI rank by setting both ctl->qnt_current_subdomain and ctl->qnt_target_subdomain to that rank. Particles outside the local subdomain are marked invalid by setting both quantities to -1.

If init is zero, the routine updates only the destination rank. Particles already marked invalid (qnt_current_subdomain == -1) are skipped. For particles that remain inside the local subdomain, ctl->qnt_target_subdomain is set to the current MPI rank. For particles that have left the local subdomain, the destination rank is recomputed with dd_calc_subdomain_from_coords().

Parameters
[in]ctlControl structure containing the indices of the domain-decomposition quantities qnt_current_subdomain and qnt_target_subdomain.
[in]ddDomain decomposition structure containing the global grid and subdomain layout information.
[in,out]atmAtmospheric state. Particle positions are read from this structure and the subdomain and/or destination quantities are updated in place.
[in]initInitialization flag. If nonzero, perform the initial subdomain assignment; otherwise only update destination ranks for particle exchange.
Note
  • The local MPI rank is obtained internally from MPI_COMM_WORLD.
  • During non-initial updates, particles already marked invalid are ignored.
  • When compiled with _OPENACC, the particle loop may execute on an accelerator.
Author
Jan Clemens
Lars Hoffmann

Definition at line 1929 of file mptrac.c.

1933 {
1934
1935 /* Set timer... */
1936 SELECT_TIMER("DD_ASSIGN_SUBDOMAINS", "DD");
1937
1938 /* Get MPI rank... */
1939 int rank;
1940 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
1941
1942 /* Determine owned core subdomain in index space... */
1943 const int zonal_rank = rank / ctl->dd_subdomains_meridional;
1944 const int merid_rank = rank % ctl->dd_subdomains_meridional;
1945
1946 const int nx_block = dd->nx_glob / ctl->dd_subdomains_zonal;
1947 const int ny_block = dd->ny_glob / ctl->dd_subdomains_meridional;
1948
1949 const int ix0 = zonal_rank * nx_block;
1950 const int iy0 = merid_rank * ny_block;
1951
1952 const int ix1 = ix0 + nx_block
1953 + (zonal_rank == ctl->dd_subdomains_zonal - 1 ?
1954 dd->nx_glob - ctl->dd_subdomains_zonal * nx_block : 0);
1955
1956 const int iy1 = iy0 + ny_block
1957 + (merid_rank == ctl->dd_subdomains_meridional - 1 ?
1958 dd->ny_glob - ctl->dd_subdomains_meridional * ny_block : 0);
1959
1960 /* Loop over particles... */
1961#ifdef _OPENACC
1962#pragma acc update device(dd->nx_glob, dd->ny_glob, \
1963 dd->lon_glob[:dd->nx_glob], \
1964 dd->lat_glob[:dd->ny_glob])
1965#pragma acc data present(atm, ctl, dd)
1966#pragma acc parallel loop independent gang vector
1967#endif
1968 for (int ip = 0; ip < atm->np; ip++) {
1969
1970 /* Skip already invalid particles... */
1971 if (!init && (int) atm->q[ctl->qnt_current_subdomain][ip] == -1)
1972 continue;
1973
1974 /* Normalize coordinates... */
1975 double lon = atm->lon[ip];
1976 double lat = atm->lat[ip];
1977 dd_normalize_lon_lat(dd, &lon, &lat);
1978
1979 /* Check whether particle is inside owned core subdomain... */
1980 const int ix = locate_reg(dd->lon_glob, dd->nx_glob, lon);
1981 const int iy = locate_irr(dd->lat_glob, dd->ny_glob, lat);
1982 const int inside = (ix >= ix0 && ix < ix1 && iy >= iy0 && iy < iy1);
1983
1984 /* Init... */
1985 if (init) {
1986 atm->q[ctl->qnt_current_subdomain][ip] = inside ? rank : -1;
1987 atm->q[ctl->qnt_target_subdomain][ip] = inside ? rank : -1;
1988 }
1989
1990 /* Reassign... */
1991 else {
1992 atm->q[ctl->qnt_target_subdomain][ip] =
1993 inside ? rank : dd_calc_subdomain_from_coords(ctl, dd, lon, lat);
1994 }
1995 }
1996}
int rank
Definition mptrac.c:11234
int dd_calc_subdomain_from_coords(const ctl_t *ctl, const dd_t *dd, double lon, double lat)
Determine MPI subdomain from particle coordinates.
Definition mptrac.c:2173
void dd_normalize_lon_lat(const dd_t *dd, double *lon, double *lat)
Normalize geographic coordinates to the global grid convention.
Definition mptrac.c:2423
#define SELECT_TIMER(id, group)
Select and start a timer with specific attributes.
Definition mptrac.h:2542
double lat[NP]
Latitude [deg].
Definition mptrac.h:3677
double lon[NP]
Longitude [deg].
Definition mptrac.h:3674
int np
Number of air parcels.
Definition mptrac.h:3665
double q[NQ][NP]
Quantity data (for various, user-defined attributes).
Definition mptrac.h:3680
int qnt_target_subdomain
Quantity array index for destination subdomain in domain decomposition.
Definition mptrac.h:2889
int qnt_current_subdomain
Quantity array index for current subdomain in domain decomposition.
Definition mptrac.h:2886
int dd_subdomains_zonal
Domain decomposition zonal subdomain number (defaults to 2 if domain decomposition is used,...
Definition mptrac.h:3631
int dd_subdomains_meridional
Domain decomposition meridional subdomain number (defaults to 2 if domain decomposition is used,...
Definition mptrac.h:3635
int nx_glob
Number of global longitudes.
Definition mptrac.h:4136
double lon_glob[DD_EX_GLOB]
Longitudes of the global grid [deg].
Definition mptrac.h:4142
double lat_glob[DD_EY_GLOB]
Latitudes of the global grid [deg].
Definition mptrac.h:4145
int ny_glob
Number of global latitudes.
Definition mptrac.h:4139
Here is the call graph for this function:

◆ dd_atm2particles()

void dd_atm2particles ( const ctl_t * ctl,
cache_t * cache,
atm_t * atm,
particle_t * particles,
const int npart )

Copy migratable atmospheric particles from the ATM state into a particle buffer.

This routine scans the domain-decomposition particle region of the atmospheric state and copies particles that must be transferred to a different MPI rank into the temporary particle communication buffer.

The routine processes atmospheric entries in the index range [atm->np, atm->np + npart). A particle is selected for export if all of the following conditions are met:

  • atm->q[ctl->qnt_target_subdomain][ip] != rank,
  • atm->q[ctl->qnt_target_subdomain][ip] >= 0,
  • atm->q[ctl->qnt_current_subdomain][ip] >= 0.

For each selected entry, the particle coordinates (time, lon, lat, p), all quantities q[iq], cache->dt[ip], and cache->uvwp[ip] are copied into particles[ip - atm->np].

After copying, the atmospheric entry is marked as inactive for local ownership by setting atm->q[ctl->qnt_current_subdomain][ip] = -1, and the cached time step cache->dt[ip] is reset to zero.

Parameters
[in]ctlPointer to the control structure containing the quantity indices qnt_target_subdomain, qnt_current_subdomain, and the number of quantities nq.
[in,out]cachePointer to the cache structure. The cached time-step values dt[ip] of exported particles are reset to zero.
[in,out]atmPointer to the atmospheric state. Particle data are read from the domain-decomposition particle region, and exported entries are marked by setting their subdomain index to -1.
[out]particlesBuffer receiving the particles selected for communication. Selected atmospheric entries are copied to index ip - atm->np.
[in]npartNumber of candidate particle entries in the atmospheric communication region.
Note
  • The current MPI rank is obtained internally from MPI_COMM_WORLD.
  • This routine does not compact the particle buffer; entries corresponding to non-selected atmospheric particles remain untouched.
  • When compiled with _OPENACC, the selection and copy loop may run on the accelerator.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2002 of file mptrac.c.

2007 {
2008
2009 /* Set timer... */
2010 SELECT_TIMER("DD_ATM2PARTICLES", "DD");
2011
2012 /* Check if particles are present... */
2013 if (npart == 0)
2014 return;
2015
2016 int rank;
2017 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2018
2019 /* Select the particles that will be send... */
2020#ifdef _OPENACC
2021#pragma acc enter data create(npart, particles[:npart])
2022#pragma acc update device(npart, particles[:npart])
2023#pragma acc parallel loop present(atm, ctl, particles, cache, npart)
2024#endif
2025 for (int ip = atm->np; ip < atm->np + npart; ip++)
2026 if (((int) (atm->q[ctl->qnt_target_subdomain][ip]) != rank)
2027 && ((int) (atm->q[ctl->qnt_target_subdomain][ip]) >= 0)
2028 && ((int) atm->q[ctl->qnt_current_subdomain][ip] >= 0)) {
2029
2030 particles[ip - atm->np].time = atm->time[ip];
2031 particles[ip - atm->np].lon = atm->lon[ip];
2032 particles[ip - atm->np].lat = atm->lat[ip];
2033 particles[ip - atm->np].p = atm->p[ip];
2034 particles[ip - atm->np].dt = cache->dt[ip];
2035 particles[ip - atm->np].iso_init = cache->iso_init[ip];
2036 for (int iq = 0; iq < ctl->nq; iq++)
2037 particles[ip - atm->np].q[iq] = atm->q[iq][ip];
2038 for (int i = 0; i < 3; i++)
2039 particles[ip - atm->np].uvwp[i] = cache->uvwp[ip][i];
2040
2041 atm->q[ctl->qnt_current_subdomain][ip] = -1;
2042 cache->dt[ip] = 0;
2043 }
2044#ifdef _OPENACC
2045#pragma acc update host( particles[:npart])
2046#pragma acc exit data delete(npart, particles)
2047#endif
2048}
double time[NP]
Time [s].
Definition mptrac.h:3668
double p[NP]
Pressure [hPa].
Definition mptrac.h:3671
double dt[NP]
Timesteps [s].
Definition mptrac.h:3747
float uvwp[NP][3]
Wind perturbations: horizontal [m/s], mesoscale vertical [hPa/s].
Definition mptrac.h:3741
uint8_t iso_init[NP]
Per-particle reference state for ISOSURF=2 or 3 (0 unset, 1 active, 2 saved).
Definition mptrac.h:3738
int nq
Number of quantities.
Definition mptrac.h:2564
uint8_t iso_init
Isosurface reference state: 0 unset, 1 active, 2 saved before a met-file boundary.
Definition mptrac.h:3716
double p
Pressure [hPa].
Definition mptrac.h:3698
double lat
Latitude [deg].
Definition mptrac.h:3704
double time
Time [s].
Definition mptrac.h:3695
double lon
Longitude [deg].
Definition mptrac.h:3701
double dt
Individual time step [s].
Definition mptrac.h:3707

◆ dd_pack_compact()

void dd_pack_compact ( const ctl_t * ctl,
cache_t * cache,
atm_t * atm,
dd_t * dd,
particle_t * particles,
const int nkeep,
const int npart )

Pack outgoing particles and compact local arrays without sorting.

This routine writes particles assigned to another MPI rank into particles, removes those particles and invalid entries from the active atmosphere, and compacts the particles retained on the current rank into the first nkeep slots. It moves time, p, lon, lat, all quantities q[iq], and the particle-specific cache values dt and uvwp together. Random values in rs are regenerated before their next use. The shared iso_ps and iso_ts cache series are not changed.

The caller must first call dd_count_outgoing() and provide space for npart outgoing particles. With OpenACC, that call also places source indices in dd->perm. This routine uses those indices to pack particles on the device before compacting the local arrays, then copies only the outgoing particle buffer to the host for MPI communication. On the CPU, packing and compaction proceed in one sequential pass.

Parameters
[in]ctlControl structure containing the subdomain quantity indices and the number of quantities.
[in,out]cacheParticle-specific cache values for retained particles are compacted with the atmosphere.
[in,out]atmAtmospheric state. On return, atm->np equals the number of retained particles.
[in]ddSource-index mapping produced by dd_count_outgoing() in OpenACC builds.
[out]particlesBuffer for npart outgoing particles, allocated by the caller.
[in]nkeepNumber of particles retained on this rank.
[in]npartNumber of particles sent to other ranks.
Note
dt and uvwp are packed for outgoing particles and preserved for retained particles. Atomic index assignment in OpenACC builds may change particle order relative to the CPU implementation.
Author
Lars Hoffmann

Definition at line 2054 of file mptrac.c.

2061 {
2062
2063 /* Set timer... */
2064 SELECT_TIMER("DD_PACK_COMPACT", "DD");
2065
2066 int rank;
2067 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2068
2069 const int np = atm->np;
2070#ifdef _OPENACC
2071 /* The permutation was built by dd_count_outgoing(): kept particles at
2072 the front and outgoing particles at the back. Pack before compacting,
2073 since the latter overwrites source slots. */
2074 if (npart > 0) {
2075 SELECT_TIMER("DD_GPU_PACK", "DD");
2076#pragma acc enter data create(particles[0:npart])
2077#pragma acc parallel loop present(ctl, atm, cache, dd, particles)
2078 for (int i = 0; i < npart; i++) {
2079 const int ip = dd->perm[np - 1 - i];
2080 particles[i].time = atm->time[ip];
2081 particles[i].p = atm->p[ip];
2082 particles[i].lon = atm->lon[ip];
2083 particles[i].lat = atm->lat[ip];
2084 particles[i].dt = cache->dt[ip];
2085 particles[i].iso_init = cache->iso_init[ip];
2086 for (int iq = 0; iq < ctl->nq; iq++)
2087 particles[i].q[iq] = atm->q[iq][ip];
2088 for (int j = 0; j < 3; j++)
2089 particles[i].uvwp[j] = cache->uvwp[ip][j];
2090 }
2091 SELECT_TIMER("DD_GPU_SEND_D2H", "DD");
2092#pragma acc update self(particles[0:npart])
2093#pragma acc exit data delete(particles[0:npart])
2094 }
2095
2096 /* sort_array stages one field in dd->tmp before writing it back.
2097 Thus no parallel read can race with a write to the original field. */
2098 if (nkeep > 0 && nkeep != np) {
2099 SELECT_TIMER("DD_GPU_COMPACT", "DD");
2100 sort_array(atm->time, dd->perm, dd->tmp, nkeep);
2101 sort_array(atm->p, dd->perm, dd->tmp, nkeep);
2102 sort_array(atm->lon, dd->perm, dd->tmp, nkeep);
2103 sort_array(atm->lat, dd->perm, dd->tmp, nkeep);
2104 for (int iq = 0; iq < ctl->nq; iq++)
2105 sort_array(atm->q[iq], dd->perm, dd->tmp, nkeep);
2106 sort_array(cache->dt, dd->perm, dd->tmp, nkeep);
2107 sort_uvwp(cache, dd->perm, dd->tmp, nkeep);
2108 }
2109
2110 const int nlost = np - nkeep - npart;
2111 if (nlost > 0)
2112 WARN("Rank %d: %d particles have invalid subdomain and will be lost",
2113 rank, nlost);
2114 atm->np = nkeep;
2115#pragma acc update device(atm->np)
2116#else
2117 (void) dd;
2118 (void) nkeep;
2119
2120 /* Pack outgoing particles and fill gaps with the remaining local ones... */
2121 int nkeep_cpu = 0, nsend = 0, nlost = 0;
2122 for (int ip = 0; ip < np; ip++) {
2123 const int current = (int) atm->q[ctl->qnt_current_subdomain][ip];
2124 const int target = (int) atm->q[ctl->qnt_target_subdomain][ip];
2125 if (current < 0 || target < 0) {
2126 nlost++;
2127 continue;
2128 }
2129
2130 if (target != rank) {
2131 particles[nsend].time = atm->time[ip];
2132 particles[nsend].p = atm->p[ip];
2133 particles[nsend].lon = atm->lon[ip];
2134 particles[nsend].lat = atm->lat[ip];
2135 particles[nsend].dt = cache->dt[ip];
2136 particles[nsend].iso_init = cache->iso_init[ip];
2137 for (int iq = 0; iq < ctl->nq; iq++)
2138 particles[nsend].q[iq] = atm->q[iq][ip];
2139 for (int i = 0; i < 3; i++)
2140 particles[nsend].uvwp[i] = cache->uvwp[ip][i];
2141 nsend++;
2142 continue;
2143 }
2144
2145 if (nkeep_cpu != ip) {
2146 atm->time[nkeep_cpu] = atm->time[ip];
2147 atm->p[nkeep_cpu] = atm->p[ip];
2148 atm->lon[nkeep_cpu] = atm->lon[ip];
2149 atm->lat[nkeep_cpu] = atm->lat[ip];
2150 for (int iq = 0; iq < ctl->nq; iq++)
2151 atm->q[iq][nkeep_cpu] = atm->q[iq][ip];
2152 cache->dt[nkeep_cpu] = cache->dt[ip];
2153 cache->iso_init[nkeep_cpu] = cache->iso_init[ip];
2154 for (int i = 0; i < 3; i++)
2155 cache->uvwp[nkeep_cpu][i] = cache->uvwp[ip][i];
2156 }
2157 nkeep_cpu++;
2158 }
2159
2160 if (nsend != npart)
2161 ERRMSG("Inconsistent number of outgoing particles!");
2162 if (nlost > 0)
2163 WARN("Rank %d: %d particles have invalid subdomain and will be lost",
2164 rank, nlost);
2165 atm->np = nkeep_cpu;
2166#endif
2167}
void sort_array(double *array, const int *perm, double *tmp, const int np)
Reorder a double array according to particle source indices.
Definition mptrac.c:2506
void sort_uvwp(cache_t *cache, const int *perm, double *tmp, const int np)
Reorder particle-specific wind perturbations.
Definition mptrac.c:2544
#define WARN(...)
Print a warning message with contextual information.
Definition mptrac.h:2433
double tmp[NP]
Auxiliary temporary array for sorting.
Definition mptrac.h:4185
int perm[NP]
Auxiliary permutation array for sorting.
Definition mptrac.h:4182
Here is the call graph for this function:

◆ dd_calc_subdomain_from_coords()

int dd_calc_subdomain_from_coords ( const ctl_t * ctl,
const dd_t * dd,
const double lon,
const double lat )

Determine MPI subdomain from particle coordinates.

This function maps a particle position to the corresponding MPI rank in the domain-decomposed grid. The longitude and latitude are first normalized using dd_normalize_lon_lat(). The corresponding global grid cell indices are then determined using locate_reg() for longitude and locate_irr() for latitude.

The grid indices are mapped to the zonal and meridional subdomain blocks defined by ctl->dd_subdomains_zonal and ctl->dd_subdomains_meridional. The resulting subdomain indices are converted to an MPI rank assuming the layout:

rank = zonal_rank * dd_subdomains_meridional + merid_rank

This implementation works for both regular and irregular latitude grids.

Parameters
ctlPointer to control structure.
ddPointer to domain decomposition structure.
lonLongitude of particle [deg].
latLatitude of particle [deg].
Returns
MPI rank of the target subdomain.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2173 of file mptrac.c.

2177 {
2178
2179 /* Normalize coordinates... */
2180 dd_normalize_lon_lat(dd, &lon, &lat);
2181
2182 /* Get grid index... */
2183 const int ix = locate_reg(dd->lon_glob, dd->nx_glob, lon);
2184 const int iy = locate_irr(dd->lat_glob, dd->ny_glob, lat);
2185
2186 /* Get zonal subdomain index... */
2187 const int nx_block = dd->nx_glob / ctl->dd_subdomains_zonal;
2188 int zonal_rank = ix / nx_block;
2189 if (zonal_rank >= ctl->dd_subdomains_zonal)
2190 zonal_rank = ctl->dd_subdomains_zonal - 1;
2191
2192 /* Get meridional subdomain index... */
2193 const int ny_block = dd->ny_glob / ctl->dd_subdomains_meridional;
2194 int merid_rank = iy / ny_block;
2195 if (merid_rank >= ctl->dd_subdomains_meridional)
2196 merid_rank = ctl->dd_subdomains_meridional - 1;
2197
2198 /* Return rank... */
2199 return zonal_rank * ctl->dd_subdomains_meridional + merid_rank;
2200}
Here is the call graph for this function:

◆ dd_communicate_particles()

void dd_communicate_particles ( const ctl_t * ctl,
const dd_t * dd,
particle_t ** particles,
int * npart,
int * capacity )

Exchange particles between MPI ranks according to their destination rank.

This routine migrates particles to their assigned destination MPI ranks using collective communication. The destination rank of each particle is read from (*particles)[ip].q[ctl->qnt_target_subdomain].

First, the routine counts how many local particles must be sent to each MPI rank, excluding particles whose destination equals the current rank. These counts are exchanged using MPI_Alltoall to determine the number of incoming particles. Temporary send and receive buffers are then allocated, the outgoing particles are packed into the send buffer, and particle data are exchanged with MPI_Alltoallv using the MPI datatype stored in dd->MPI_Particle.

After communication, the received particles replace the leading entries of the particle buffer. For each received particle, both ctl->qnt_target_subdomain and ctl->qnt_current_subdomain are reset to the current MPI rank.

If the receive buffer exceeds the currently allocated particle capacity, the particle array is automatically resized using realloc().

Parameters
[in]ctlPointer to the control structure containing the quantity indices qnt_target_subdomain and qnt_current_subdomain.
[in]ddPointer to the domain decomposition structure containing the MPI datatype MPI_Particle used for particle communication.
[in,out]particlesPointer to the particle buffer. The pointer may be updated if the buffer is resized. On output, the leading entries contain the particles received by the current MPI rank.
[in,out]npartNumber of local particles. On input, it specifies the number of valid particles stored in particles. On output, it is replaced by the number of particles received by the current MPI rank.
[in,out]capacityAllocated capacity of the particle buffer. If necessary, the routine increases this value when resizing the particle array.
Note
  • Particles whose destination rank equals the current MPI rank are not packed into the send buffer.
  • Destination ranks are validated against the number of MPI tasks and must refer to a valid MPI rank.
  • Temporary communication buffers are allocated internally and freed before returning.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2206 of file mptrac.c.

2211 {
2212
2213 /* Set timer... */
2214 SELECT_TIMER("DD_COMMUNICATE_PARTICLES", "DD");
2215
2216 int rank, size;
2217 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2218 MPI_Comm_size(MPI_COMM_WORLD, &size);
2219
2220 int *send_counts, *recv_counts;
2221 int *send_displs, *recv_displs;
2222 int *offsets;
2223
2224 particle_t *sendbuf = NULL;
2225 particle_t *recvbuf = NULL;
2226
2227 ALLOC(send_counts, int,
2228 size);
2229 ALLOC(recv_counts, int,
2230 size);
2231 ALLOC(send_displs, int,
2232 size);
2233 ALLOC(recv_displs, int,
2234 size);
2235 ALLOC(offsets, int,
2236 size);
2237
2238 /* Count particles per destination rank... */
2239#pragma omp parallel for
2240 for (int ip = 0; ip < *npart; ip++) {
2241 const int dest = (int) (*particles)[ip].q[ctl->qnt_target_subdomain];
2242 if (dest == rank)
2243 continue;
2244 if (dest < 0 || dest >= size)
2245 ERRMSG("Invalid destination rank!");
2246#pragma omp atomic
2247 send_counts[dest]++;
2248 }
2249
2250 /* Compute send displacements... */
2251 int nsend = 0;
2252 for (int i = 0; i < size; i++) {
2253 send_displs[i] = nsend;
2254 nsend += send_counts[i];
2255 }
2256#if LOGLEV >= 3
2257 LOG(3, "DD_SEND rank=%d particles=%d", rank, nsend);
2258#endif
2259
2260 /* Classify the already available MPI counts without scanning particles. */
2261#if LOGLEV >= 2
2262 if (dd_node != NULL) {
2263 dd_sent += (unsigned long long) nsend;
2264 for (int i = 0; i < size; i++) {
2265 if (dd_node[i] == dd_node[rank])
2266 dd_intra += (unsigned long long) send_counts[i];
2267 else
2268 dd_inter += (unsigned long long) send_counts[i];
2269 }
2270 }
2271#endif
2272
2273 /* Exchange particle counts... */
2274 MPI_Alltoall(send_counts, 1, MPI_INT,
2275 recv_counts, 1, MPI_INT, MPI_COMM_WORLD);
2276
2277 /* Compute receive displacements... */
2278 int nrecv = 0;
2279 for (int i = 0; i < size; i++) {
2280 recv_displs[i] = nrecv;
2281 nrecv += recv_counts[i];
2282 }
2283 if (nsend > 0)
2284 ALLOC(sendbuf, particle_t, nsend);
2285 if (nrecv > 0)
2286 ALLOC(recvbuf, particle_t, nrecv);
2287 for (int i = 0; i < size; i++)
2288 offsets[i] = send_displs[i];
2289
2290 /* Pack particles into send buffer... */
2291 for (int ip = 0; ip < *npart; ip++) {
2292 const int dest = (int) (*particles)[ip].q[ctl->qnt_target_subdomain];
2293 if (dest == rank)
2294 continue;
2295 memcpy(&sendbuf[offsets[dest]], &(*particles)[ip], sizeof(particle_t));
2296 offsets[dest]++;
2297 }
2298
2299 /* Exchange particle data... */
2300 MPI_Alltoallv(sendbuf,
2301 send_counts,
2302 send_displs,
2303 dd->MPI_Particle,
2304 recvbuf,
2305 recv_counts, recv_displs, dd->MPI_Particle, MPI_COMM_WORLD);
2306
2307 /* Resize particle buffer if necessary... */
2308 if (nrecv > *capacity) {
2309 const int newcap = nrecv + nrecv / 2 + 1;
2310 particle_t *tmp =
2311 realloc(*particles, (size_t) newcap * sizeof(particle_t));
2312 if (!tmp)
2313 ERRMSG("Out of memory!");
2314 *particles = tmp;
2315 *capacity = newcap;
2316 }
2317
2318 /* Copy received particles... */
2319#pragma omp parallel for
2320 for (int ip = 0; ip < nrecv; ip++) {
2321 (*particles)[ip] = recvbuf[ip];
2322 (*particles)[ip].q[ctl->qnt_target_subdomain] = rank;
2323 (*particles)[ip].q[ctl->qnt_current_subdomain] = rank;
2324 }
2325 *npart = nrecv;
2326
2327 /* Free temporary buffers... */
2328 if (sendbuf)
2329 free(sendbuf);
2330 if (recvbuf)
2331 free(recvbuf);
2332 free(send_counts);
2333 free(recv_counts);
2334 free(send_displs);
2335 free(recv_displs);
2336 free(offsets);
2337}
MPI_Datatype MPI_Particle
MPI datatype for particle exchange.
Definition mptrac.h:4176
Particle data.
Definition mptrac.h:3692
double q[NQ]
Quantity data (for various, user-defined attributes).
Definition mptrac.h:3710

◆ dd_init()

void dd_init ( const ctl_t * ctl,
dd_t * dd,
atm_t * atm )

Initialize the domain decomposition infrastructure.

This routine initializes the MPI-related data structures required for domain decomposition. It first verifies that the number of MPI ranks in MPI_COMM_WORLD matches the total number of requested subdomains,

ctl->dd_subdomains_meridional * ctl->dd_subdomains_zonal.

It then constructs and commits the MPI datatype dd->MPI_Particle corresponding to the particle_t structure. Its extent is set to sizeof(particle_t) so arrays use the correct stride in MPI exchanges.

Finally, the routine performs the initial particle-to-subdomain assignment by calling dd_assign_subdomains() with init = 1.

Parameters
[in]ctlPointer to the control structure containing the domain-decomposition settings, in particular the number of zonal and meridional subdomains.
[in,out]ddPointer to the domain decomposition structure. On return, the MPI datatype MPI_Particle is initialized and committed.
[in,out]atmPointer to the atmospheric state. Its domain-decomposition bookkeeping quantities are initialized by the call to dd_assign_subdomains().
Note
  • The routine aborts if the number of MPI ranks does not equal the total number of configured subdomains.
  • The committed MPI datatype stored in dd->MPI_Particle must be released later with MPI_Type_free() when the domain decomposition is finalized.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2343 of file mptrac.c.

2346 {
2347
2348 /* Check configuration... */
2349 if ((ctl->dd) &&
2351 ERRMSG("Please provide zonal and meridional subdomain numbers!");
2352 if (!ctl->dd)
2353 ERRMSG("Activate control flag DD!");
2354
2355 /* Check if enough tasks are requested... */
2356 int size;
2357 MPI_Comm_size(MPI_COMM_WORLD, &size);
2359 ERRMSG("Number of tasks and subdomains is not identical!");
2360
2361 /* Register the MPI_Particle data type... */
2362 const MPI_Datatype types[8] =
2363 { MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE,
2364 MPI_FLOAT, MPI_UNSIGNED_CHAR };
2365 const int blocklengths[8] = { 1, 1, 1, 1, 1, NQ, 3, 1 };
2366 const MPI_Aint displacements[8] =
2367 { offsetof(particle_t, time), offsetof(particle_t, p),
2368 offsetof(particle_t, lon), offsetof(particle_t, lat),
2369 offsetof(particle_t, dt), offsetof(particle_t, q),
2370 offsetof(particle_t, uvwp), offsetof(particle_t, iso_init)
2371 };
2372 MPI_Datatype fields;
2373 MPI_Type_create_struct(8, blocklengths, displacements, types, &fields);
2374 /* The trailing float array can leave padding in particle_t. Alltoallv
2375 counts and displacements must advance by the full C structure size. */
2376 MPI_Type_create_resized(fields, 0, (MPI_Aint) sizeof(particle_t),
2377 &dd->MPI_Particle);
2378 MPI_Type_free(&fields);
2379 MPI_Type_commit(&dd->MPI_Particle);
2380 MPI_Aint lower_bound, extent;
2381 MPI_Type_get_extent(dd->MPI_Particle, &lower_bound, &extent);
2382 if (lower_bound != 0 || extent != (MPI_Aint) sizeof(particle_t))
2383 ERRMSG("Invalid MPI particle datatype extent!");
2384
2385 LOG(1, "DD: %d x %d subdomains | exchange mode %d | initial particles %d",
2387 ctl->dd_exchange_mode, atm->np);
2388
2389 /* Discover node placement once when detailed logging is enabled. */
2390#if LOGLEV >= 2
2391 {
2392 int rank, local_rank, leader;
2393 MPI_Comm shared;
2394 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2395 MPI_Comm_split_type(MPI_COMM_WORLD, MPI_COMM_TYPE_SHARED, rank,
2396 MPI_INFO_NULL, &shared);
2397 MPI_Comm_rank(shared, &local_rank);
2398 leader = local_rank == 0 ? rank : -1;
2399 MPI_Bcast(&leader, 1, MPI_INT, 0, shared);
2400 ALLOC(dd_node, int, size);
2401 MPI_Allgather(&leader, 1, MPI_INT, dd_node, 1, MPI_INT,
2402 MPI_COMM_WORLD);
2403 MPI_Type_size(dd->MPI_Particle, &dd_particle_bytes);
2404 dd_sent = dd_intra = dd_inter = 0;
2405 char hostname[MPI_MAX_PROCESSOR_NAME];
2406 int hostname_len;
2407 MPI_Get_processor_name(hostname, &hostname_len);
2408 const char *gpu = getenv("CUDA_VISIBLE_DEVICES");
2409 LOG(2, "DD_NODE rank=%d leader=%d local_rank=%d host=%s gpu=%s",
2410 rank, leader, local_rank, hostname, gpu ? gpu : "-");
2411 MPI_Comm_free(&shared);
2412 }
2413#endif
2414
2415 /* Check if particles are in subdomain... */
2416 dd_assign_subdomains(ctl, dd, atm, 1);
2417}
void dd_assign_subdomains(const ctl_t *ctl, const dd_t *dd, atm_t *atm, const int init)
Assign or update particle subdomain ownership.
Definition mptrac.c:1929
#define NQ
Maximum number of quantities per data point.
Definition mptrac.h:574
int dd
Domain decomposition (0=no, 1=yes).
Definition mptrac.h:3627
int dd_exchange_mode
Particle exchange: 0=sort/push (default), 1=direct pack/compact.
Definition mptrac.h:3645
Here is the call graph for this function:

◆ dd_normalize_lon_lat()

void dd_normalize_lon_lat ( const dd_t * dd,
double * lon,
double * lat )

Normalize geographic coordinates to the global grid convention.

This helper routine normalizes a longitude/latitude pair so that it is consistent with the longitude convention of the global meteorological grid stored in the domain decomposition structure.

The function performs the following steps:

  • Normalizes longitude to the grid convention used by dd->lon_glob (either [-180,180) or [0,360)).
  • Wraps latitude values outside the physical range [-90,90] across the poles and shifts longitude by 180° accordingly.
  • Renormalizes longitude again after pole crossing.

This ensures that coordinates used for domain-decomposition checks and subdomain index calculations are always mapped consistently to the global grid representation.

Parameters
[in]ddPointer to the domain decomposition structure containing the global longitude grid (dd->lon_glob).
[in,out]lonPointer to longitude [deg]. The value is normalized in-place to match the grid convention.
[in,out]latPointer to latitude [deg]. Values outside [-90,90] are wrapped across the poles in-place.
Note
  • Uses the FMOD macro instead of fmod() to ensure compatibility with GPU/OpenACC builds.
  • The routine is marked with #pragma acc routine seq so it can be called from within OpenACC parallel loops.
Author
Lars Hoffmann

Definition at line 2423 of file mptrac.c.

2426 {
2427
2428 const double lon_min = (dd->lon_glob[0] < 0) ? -180.0 : 0.0;
2429
2430 /* Normalize longitude to match global grid convention... */
2431 *lon = FMOD(*lon - lon_min, 360.0);
2432 if (*lon < 0.0)
2433 *lon += 360.0;
2434 *lon += lon_min;
2435
2436 /* Wrap latitude across the poles and shift longitude... */
2437 if (*lat > 90.0) {
2438 *lat = 180.0 - *lat;
2439 *lon += 180.0;
2440 } else if (*lat < -90.0) {
2441 *lat = -180.0 - *lat;
2442 *lon += 180.0;
2443 }
2444
2445 /* Renormalize longitude after pole crossing... */
2446 *lon = FMOD(*lon - lon_min, 360.0);
2447 if (*lon < 0.0)
2448 *lon += 360.0;
2449 *lon += lon_min;
2450}

◆ dd_particles2atm()

void dd_particles2atm ( const ctl_t * ctl,
cache_t * cache,
const particle_t * particles,
const int npart,
atm_t * atm )

Copy received particles from the communication buffer into the atmospheric state.

This routine appends particles from the temporary domain-decomposition particle buffer to the atmospheric particle arrays. The particles are written into the index range

[atm->np, atm->np + npart)

of the atmospheric state.

For each transferred particle, the routine copies the particle coordinates (time, lon, lat, p) and all particle quantities q[iq] into the atmospheric arrays and restores the individual time step and all three uvwp components into the cache.

After all particles have been copied, the total number of atmospheric particles atm->np is increased by npart.

Parameters
[in]ctlPointer to the control structure containing the number of quantities nq.
[in,out]cachePointer to the cache structure. The cached time-step values and uvwp are restored from particles.
[in]particlesBuffer containing the particles to be appended to the atmospheric state.
[in]npartNumber of valid particles stored in particles.
[in,out]atmPointer to the atmospheric state. The particle data are appended to its arrays, and atm->np is incremented accordingly.
Note
  • The routine appends particles starting at the current value of atm->np.
  • The routine aborts if the updated number of atmospheric particles exceeds the compile-time limit NP.
  • When compiled with _OPENACC, particle data may be copied on the accelerator and the updated value of atm->np is synchronized to the device.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2456 of file mptrac.c.

2461 {
2462
2463 /* Set timer... */
2464 SELECT_TIMER("DD_PARTICLES2ATM", "DD");
2465
2466 /* Check if particles are present... */
2467 if (npart == 0)
2468 return;
2469
2470 /* Check number of particles... */
2471 if (atm->np + npart > NP)
2472 ERRMSG("Too many particles. Increase NP!");
2473
2474#ifdef _OPENACC
2475#pragma acc enter data create(npart, particles[:npart])
2476#pragma acc update device(particles[:npart], npart)
2477#pragma acc data present(atm, ctl, cache, particles, npart)
2478#pragma acc parallel loop
2479#endif
2480 for (int ip = atm->np; ip < atm->np + npart; ip++) {
2481 atm->time[ip] = particles[ip - atm->np].time;
2482 atm->lon[ip] = particles[ip - atm->np].lon;
2483 atm->lat[ip] = particles[ip - atm->np].lat;
2484 atm->p[ip] = particles[ip - atm->np].p;
2485 cache->dt[ip] = particles[ip - atm->np].dt;
2486 cache->iso_init[ip] = particles[ip - atm->np].iso_init;
2487 for (int iq = 0; iq < ctl->nq; iq++)
2488 atm->q[iq][ip] = particles[ip - atm->np].q[iq];
2489 for (int i = 0; i < 3; i++)
2490 cache->uvwp[ip][i] = particles[ip - atm->np].uvwp[i];
2491 }
2492#ifdef _OPENACC
2493#pragma acc exit data delete(npart, particles)
2494#endif
2495
2496 /* Reset size... */
2497 atm->np += npart;
2498#ifdef _OPENACC
2499#pragma acc update device(atm->np)
2500#endif
2501}
#define NP
Maximum number of atmospheric data points.
Definition mptrac.h:569

◆ dd_push()

void dd_push ( const ctl_t * ctl,
atm_t * atm,
cache_t * cache,
int * npart )

Compact and stage non-local particles for domain decomposition transfer.

This routine scans all local atmospheric particles and moves those that need to be transferred to other MPI ranks to a contiguous region at the end of the particle arrays (starting at index atm->np).

A particle is selected for transfer if:

  • atm->q[ctl->qnt_current_subdomain][ip] != -1 (particle is active), AND
  • atm->q[ctl->qnt_target_subdomain][ip] != rank (destination is not current rank)

For each selected particle:

  • All particle data (time, p, lon, lat, all quantities q[iq]) are copied to the end of the respective arrays
  • The original particle is marked as invalid by setting both q[ctl->qnt_target_subdomain][ip] = -1 and q[ctl->qnt_current_subdomain][ip] = -1
  • The cached time step cache->dt[ip] is copied to the new location and reset to zero at the original position
  • All three cache->uvwp[ip] components are copied to the staged entry
Parameters
[in]ctlPointer to the control structure containing the quantity indices qnt_target_subdomain and qnt_current_subdomain.
[in,out]atmPointer to the atmospheric state. Selected particles are copied to indices [atm->np, atm->np+npart) and original entries are invalidated.
[in,out]cachePointer to the cache structure. Time-step values and velocity perturbations follow staged particles; original time-step values are reset to zero.
[out]npartNumber of particles staged for transfer (i.e., the number of valid particles in the range [atm->np, atm->np + npart)).
Note
  • The current MPI rank is obtained internally from MPI_COMM_WORLD.
  • This routine performs a compaction operation: valid local particles remain in [0, atm->np), non-local particles are moved to [atm->np, atm->np + npart).
  • When compiled with _OPENACC, the selection and copy operations execute on the accelerator using atomic operations for the counter.
  • The routine reports an error if the active particles and staged copies exceed the compile-time capacity NP; no out-of-bounds copy is made.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2602 of file mptrac.c.

2606 {
2607 SELECT_TIMER("DD_PUSH", "DD");
2608 int rank;
2609 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2610
2611 int counter = 0;
2612
2613#ifdef _OPENACC
2614 int *counter_ptr = (int *) acc_malloc(sizeof(int));
2615 if (counter_ptr == NULL) {
2616 ERRMSG("Failed to allocate device counter memory!");
2617 }
2618 acc_memcpy_to_device(counter_ptr, &counter, sizeof(int));
2619#else
2620 int *counter_ptr = &counter;
2621#endif
2622
2623 /* Push non local particles behind the end of the atm... */
2624#ifdef _OPENACC
2625#pragma acc parallel loop present(atm, cache, ctl) deviceptr(counter_ptr)
2626#else
2627#pragma omp parallel for
2628#endif
2629 for (int ip = 0; ip < atm->np; ip++) {
2630 if ((int) atm->q[ctl->qnt_current_subdomain][ip] != -1 &&
2631 (int) atm->q[ctl->qnt_target_subdomain][ip] != rank) {
2632 int local_idx;
2633#ifdef _OPENACC
2634#pragma acc atomic capture
2635#else
2636#pragma omp atomic capture
2637#endif
2638 {
2639 local_idx = *counter_ptr;
2640 (*counter_ptr)++;
2641 }
2642 int global_index = atm->np + local_idx;
2643 if (global_index >= NP)
2644 continue;
2645 /* Copy time, pressure, longitude, and latitude... */
2646 atm->time[global_index] = atm->time[ip];
2647 atm->p[global_index] = atm->p[ip];
2648 atm->lon[global_index] = atm->lon[ip];
2649 atm->lat[global_index] = atm->lat[ip];
2650 /* Copy all quantity data (q array)... */
2651 for (int iq = 0; iq < ctl->nq; iq++) {
2652 atm->q[iq][global_index] = atm->q[iq][ip];
2653 }
2654 /* Mark the original parcel as processed... */
2655 atm->q[ctl->qnt_target_subdomain][ip] = -1;
2656 atm->q[ctl->qnt_current_subdomain][ip] = -1;
2657 /* Reset cache->dt for the shifted particle... */
2658 cache->dt[global_index] = cache->dt[ip];
2659 cache->iso_init[global_index] = cache->iso_init[ip];
2660 cache->dt[ip] = 0;
2661 for (int i = 0; i < 3; i++)
2662 cache->uvwp[global_index][i] = cache->uvwp[ip][i];
2663 }
2664 }
2665
2666#ifdef _OPENACC
2667 acc_memcpy_from_device(npart, counter_ptr, sizeof(int));
2668 acc_free(counter_ptr);
2669#else
2670 *npart = counter;
2671#endif
2672
2673 if (atm->np + *npart > NP)
2674 ERRMSG("Too many particles during DD push. Increase NP!");
2675}

◆ dd_count_outgoing()

void dd_count_outgoing ( const ctl_t * ctl,
const atm_t * atm,
dd_t * dd,
int * nkeep,
int * npart )

Classify particles before direct packing and compaction.

For DD_EXCHANGE_MODE=1, classify each active particle by its current and target subdomain indices. Particles with either index negative are invalid. Valid particles targeting the current MPI rank are retained; the other valid particles are outgoing. The routine returns the two counts without changing the atmospheric state.

With OpenACC, atomic counters also place retained source indices at the front of dd->perm and outgoing source indices at the back. Invalid particles receive no index. Only the two counts are copied to the host; particle data remain on the device. In CPU builds, the routine counts particles without filling dd->perm.

Parameters
[in]ctlControl structure containing the current and target subdomain quantity indices.
[in]atmAtmospheric state containing particles to classify.
[out]ddSource-index mapping in OpenACC builds; unused in CPU builds.
[out]nkeepNumber of valid particles retained on this rank.
[out]npartNumber of valid particles sent to other ranks.
Note
The local MPI rank is obtained from MPI_COMM_WORLD. The order of indices generated by atomic operations is not deterministic.
Author
Lars Hoffmann

Definition at line 2796 of file mptrac.c.

2801 {
2802
2803 /* Count particles that must be sent to another rank... */
2804 SELECT_TIMER("DD_COUNT_OUTGOING", "DD");
2805 int rank;
2806 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2807 const int np = atm->np;
2808#ifdef _OPENACC
2809 int counts[2] = { 0, 0 };
2810 if (np > 0) {
2811 SELECT_TIMER("DD_GPU_CLASSIFY", "DD");
2812#pragma acc data copy(counts[0:2]) present(ctl, atm, dd)
2813 {
2814#pragma acc parallel loop
2815 for (int ip = 0; ip < np; ip++) {
2816 const int current = (int) atm->q[ctl->qnt_current_subdomain][ip];
2817 const int target = (int) atm->q[ctl->qnt_target_subdomain][ip];
2818 int i;
2819 if (current < 0 || target < 0)
2820 continue;
2821 if (target == rank) {
2822#pragma acc atomic capture
2823 {
2824 i = counts[0];
2825 counts[0]++;
2826 }
2827 dd->perm[i] = ip;
2828 } else {
2829#pragma acc atomic capture
2830 {
2831 i = counts[1];
2832 counts[1]++;
2833 }
2834 dd->perm[np - 1 - i] = ip;
2835 }
2836 }
2837 }
2838 }
2839 *nkeep = counts[0];
2840 *npart = counts[1];
2841#else
2842 (void) dd;
2843 int kept = 0;
2844 int nsend = 0;
2845 for (int ip = 0; ip < np; ip++) {
2846 if ((int) atm->q[ctl->qnt_current_subdomain][ip] < 0
2847 || (int) atm->q[ctl->qnt_target_subdomain][ip] < 0)
2848 continue;
2849 if ((int) atm->q[ctl->qnt_target_subdomain][ip] == rank)
2850 kept++;
2851 else
2852 nsend++;
2853 }
2854 *nkeep = kept;
2855 *npart = nsend;
2856#endif
2857}

◆ dd_read_met_nc_grid()

void dd_read_met_nc_grid ( dd_t * dd,
const ctl_t * ctl,
met_t * met,
const int ncid )

Read meteorological grid information and construct the domain-decomposed grid with halo regions.

This routine reads the global longitude and latitude grid from a NetCDF meteorological input file and initializes the domain decomposition used for parallel processing. The global grid is partitioned into zonal and meridional subdomains according to ctl->dd_subdomains_zonal and ctl->dd_subdomains_meridional.

For the current MPI rank, the routine determines the core subdomain in index space and constructs a hyperslab describing the portion of the meteorological grid that must be read from the NetCDF file. The hyperslab is extended with inner halo cells to overlap with neighboring subdomains. For ranks located at the zonal boundaries, additional periodic boundary halos are created.

The function populates the local longitude and latitude arrays in the met_t structure for the subdomain including halos, and stores the hyperslab definitions and halo offsets in the dd_t structure.

Parameters
[out]ddDomain decomposition structure. On return it contains global grid dimensions, hyperslab definitions for the local subdomain, and halo metadata.
[in]ctlControl structure specifying the number of zonal and meridional subdomains and the halo size (dd_subdomains_zonal, dd_subdomains_meridional, dd_halos_size).
[out]metMeteorological grid structure. On return it contains the local longitude and latitude arrays and the grid dimensions (nx, ny, np) of the halo-extended subdomain.
[in]ncidNetCDF file identifier returned by nc_open().
Note
  • Requires MPI when compiled with -DMPI.
  • The domain decomposition is performed in index space; the global grid may therefore have irregular spacing (e.g. Gaussian latitudes).
  • Zonal periodicity is handled by constructing additional boundary halo hyperslabs with appropriate longitude shifts.
Author
Jan Clemens
Lars Hoffmann

Definition at line 12718 of file mptrac.c.

12722 {
12723
12724 int varid;
12725
12726 /* Get the MPI information... */
12727 int rank = 0, size = 1;
12728#ifdef MPI
12729 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
12730 MPI_Comm_size(MPI_COMM_WORLD, &size);
12731#endif
12732
12733 /* Get grid dimensions... */
12734 NC_INQ_DIM("lon", &dd->nx_glob, 0, 0, 0);
12735 NC_INQ_DIM("lat", &dd->ny_glob, 0, 0, 0);
12736
12737 LOG(2, "Number of longitudes: %d", dd->nx_glob);
12738 LOG(2, "Number of latitudes: %d", dd->ny_glob);
12739
12740 /* Check grid... */
12741 if (dd->nx_glob > DD_EX_GLOB || dd->ny_glob > DD_EY_GLOB)
12742 ERRMSG("Global grid is too large!");
12743
12744 if (ctl->dd_subdomains_zonal > dd->nx_glob)
12745 ERRMSG("Too many zonal subdomains for global x grid!");
12746
12747 if (ctl->dd_subdomains_meridional > dd->ny_glob)
12748 ERRMSG("Too many meridional subdomains for global y grid!");
12749
12750 /* Read global longitudes and latitudes... */
12751 NC_GET_DOUBLE("lon", dd->lon_glob, 1);
12752 NC_GET_DOUBLE("lat", dd->lat_glob, 1);
12753
12754 LOG(2, "Longitudes: %g, %g ... %g deg",
12755 dd->lon_glob[0], dd->lon_glob[1], dd->lon_glob[dd->nx_glob - 1]);
12756 LOG(2, "Latitudes: %g, %g ... %g deg",
12757 dd->lat_glob[0], dd->lat_glob[1], dd->lat_glob[dd->ny_glob - 1]);
12758
12759 /* Rank coordinates in DD layout... */
12760 const int zonal_rank = rank / ctl->dd_subdomains_meridional;
12761 const int merid_rank = rank % ctl->dd_subdomains_meridional;
12762
12763 /* Check for edge cases... */
12764 const int left = (zonal_rank == 0);
12765 const int right = (zonal_rank == ctl->dd_subdomains_zonal - 1);
12766 const int top = (merid_rank == 0);
12767 const int bottom = (merid_rank == ctl->dd_subdomains_meridional - 1);
12768
12769 /* Core owned block (without halos)... */
12770 const int nx_block = dd->nx_glob / ctl->dd_subdomains_zonal;
12771 const int ny_block = dd->ny_glob / ctl->dd_subdomains_meridional;
12772
12773 const int ix0 = zonal_rank * nx_block;
12774 const int iy0 = merid_rank * ny_block;
12775
12776 int nx_core = nx_block;
12777 int ny_core = ny_block;
12778
12779 if (right)
12780 nx_core += dd->nx_glob - ctl->dd_subdomains_zonal * nx_block;
12781 if (bottom)
12782 ny_core += dd->ny_glob - ctl->dd_subdomains_meridional * ny_block;
12783
12784 /* Check halo extents before converting grid indices to size_t... */
12785 const int halo = ctl->dd_halos_size;
12786 if ((!left && halo > ix0)
12787 || (!right && halo > dd->nx_glob - ix0 - nx_core)
12788 || (!top && halo > iy0)
12789 || (!bottom && halo > dd->ny_glob - iy0 - ny_core))
12790 ERRMSG("DD_HALOS_SIZE exceeds the available global grid!");
12791
12792 const int nx_local = nx_core
12793 + (ctl->dd_subdomains_zonal > 1 ? 2 * halo : 0);
12794 const int ny_local = ny_core + (!top ? halo : 0) + (!bottom ? halo : 0);
12795 if (nx_local > EX || ny_local > EY)
12796 ERRMSG("DD halo grid exceeds EX or EY. Increase the grid capacity!");
12797 if (nx_local < 2 || ny_local < 2)
12798 ERRMSG("DD halo grid needs at least two points in each direction!");
12799
12800 /* Store core met size first... */
12801 met->nx = nx_core;
12802 met->ny = ny_core;
12803
12804 /* Set hyperslab for core subdomain... */
12805 dd->subdomain_start[0] = 0;
12806 dd->subdomain_start[1] = 0;
12807 dd->subdomain_start[2] = (size_t) iy0;
12808 dd->subdomain_start[3] = (size_t) ix0;
12809
12810 dd->subdomain_count[0] = 1;
12811 dd->subdomain_count[1] = (size_t) met->np;
12812 dd->subdomain_count[2] = (size_t) ny_core;
12813 dd->subdomain_count[3] = (size_t) nx_core;
12814
12815 /* Add inner halos to read window... */
12816 if (!left && !right) {
12817 dd->subdomain_start[3] -= (size_t) ctl->dd_halos_size;
12818 dd->subdomain_count[3] += (size_t) (2 * ctl->dd_halos_size);
12819 } else if (left ^ right) {
12820 dd->subdomain_count[3] += (size_t) ctl->dd_halos_size;
12821 if (!left)
12822 dd->subdomain_start[3] -= (size_t) ctl->dd_halos_size;
12823 }
12824
12825 if (!top && !bottom) {
12826 dd->subdomain_start[2] -= (size_t) ctl->dd_halos_size;
12827 dd->subdomain_count[2] += (size_t) (2 * ctl->dd_halos_size);
12828 } else if (top ^ bottom) {
12829 dd->subdomain_count[2] += (size_t) ctl->dd_halos_size;
12830 if (!top)
12831 dd->subdomain_start[2] -= (size_t) ctl->dd_halos_size;
12832 }
12833
12834 /* Set boundary halo hyperslabs... */
12835 double lon_shift = 0.0;
12836
12837 if (left ^ right) {
12838 dd->halo_bnd_start[0] = 0;
12839 dd->halo_bnd_start[1] = 0;
12840 dd->halo_bnd_start[2] = dd->subdomain_start[2];
12841 dd->halo_bnd_start[3] =
12842 (size_t) (left ? (dd->nx_glob - ctl->dd_halos_size) : 0);
12843
12844 dd->halo_bnd_count[0] = 1;
12845 dd->halo_bnd_count[1] = (size_t) met->np;
12846 dd->halo_bnd_count[2] = dd->subdomain_count[2];
12847 dd->halo_bnd_count[3] = (size_t) ctl->dd_halos_size;
12848
12849 dd->halo_offset_start = left ? (int) dd->halo_bnd_count[3] : 0;
12850 dd->halo_offset_end = left ? 0 : (int) dd->subdomain_count[3];
12851 lon_shift = left ? -360.0 : 360.0;
12852 } else {
12853 dd->halo_bnd_start[0] = 0;
12854 dd->halo_bnd_start[1] = 0;
12855 dd->halo_bnd_start[2] = 0;
12856 dd->halo_bnd_start[3] = 0;
12857
12858 dd->halo_bnd_count[0] = 0;
12859 dd->halo_bnd_count[1] = 0;
12860 dd->halo_bnd_count[2] = 0;
12861 dd->halo_bnd_count[3] = 0;
12862
12863 dd->halo_offset_start = 0;
12864 dd->halo_offset_end = 0;
12865 }
12866
12867 /* Focus on subdomain latitudes... */
12868 for (int iy = 0; iy < (int) dd->subdomain_count[2]; iy++)
12869 met->lat[iy] = dd->lat_glob[(int) dd->subdomain_start[2] + iy];
12870
12871 /* Focus on subdomain longitudes... */
12872 for (int ix = 0; ix < (int) dd->subdomain_count[3]; ix++)
12873 met->lon[ix + dd->halo_offset_start] =
12874 dd->lon_glob[(int) dd->subdomain_start[3] + ix];
12875
12876 for (int ix = 0; ix < (int) dd->halo_bnd_count[3]; ix++)
12877 met->lon[ix + dd->halo_offset_end] =
12878 dd->lon_glob[(int) dd->halo_bnd_start[3] + ix] + lon_shift;
12879
12880 /* Reset halo-extended grid dimensions... */
12881 met->nx = (int) dd->subdomain_count[3] + (int) dd->halo_bnd_count[3];
12882 met->ny = (int) dd->subdomain_count[2];
12883
12884 LOG(2, "Define subdomain properties.");
12885 LOG(2, "MPI information: Rank %d, Size %d", rank, size);
12886 LOG(2, "Edge position: l=%d,r=%d,t=%d,b=%d", left, right, top, bottom);
12887 LOG(2, "Total size for subdomain meteo data: nx %d ny %d np %d",
12888 met->nx, met->ny, met->np);
12889 LOG(2, "Hyperslab sizes for boundary halos: nx %d ny %d np %d",
12890 (int) dd->halo_bnd_count[3], (int) dd->halo_bnd_count[2],
12891 (int) dd->halo_bnd_count[1]);
12892 LOG(2, "Hyperslab sizes for subdomain and inner halos: nx %d ny %d np %d",
12893 (int) dd->subdomain_count[3], (int) dd->subdomain_count[2],
12894 (int) dd->subdomain_count[1]);
12895 LOG(2, "Subdomain start: nx %ld ny %ld np %ld",
12896 dd->subdomain_start[3], dd->subdomain_start[2], dd->subdomain_start[1]);
12897 LOG(2, "Boundary halo start: nx %ld ny %ld np %ld",
12898 dd->halo_bnd_start[3], dd->halo_bnd_start[2], dd->halo_bnd_start[1]);
12899 LOG(2, "Offsets: nx %d ny %d", dd->halo_offset_start, dd->halo_offset_end);
12900 LOG(2, "%d Subdomain longitudes: %g, %g ... %g deg",
12901 rank, met->lon[0], met->lon[1], met->lon[met->nx - 1]);
12902 LOG(2, "%d Subdomain latitudes: %g, %g ... %g deg",
12903 rank, met->lat[0], met->lat[1], met->lat[met->ny - 1]);
12904}
#define DD_EY_GLOB
Maximum number of latitudes of global meteo data.
Definition mptrac.h:634
#define EY
Maximum number of latitudes for meteo data.
Definition mptrac.h:554
#define EX
Maximum number of longitudes for meteo data.
Definition mptrac.h:549
#define DD_EX_GLOB
Maximum number of longitudes of global meteo data.
Definition mptrac.h:629
#define NC_GET_DOUBLE(varname, ptr, force)
Retrieve a double-precision variable from a NetCDF file.
Definition mptrac.h:1625
#define NC_INQ_DIM(dimname, ptr, min, max, check)
Inquire the length of a dimension in a NetCDF file.
Definition mptrac.h:1655
int dd_halos_size
Domain decomposition halo size in grid points.
Definition mptrac.h:3639
size_t halo_bnd_count[4]
Extent of the periodic boundary halo hyperslab.
Definition mptrac.h:4161
int halo_offset_end
Offset of the periodic halo block at the end of the local x-array.
Definition mptrac.h:4167
size_t halo_bnd_start[4]
Start indices of the periodic boundary halo hyperslab.
Definition mptrac.h:4158
int halo_offset_start
Offset of the periodic halo block at the beginning of the local x-array.
Definition mptrac.h:4164
size_t subdomain_count[4]
Extent of the local subdomain hyperslab (including inner halos).
Definition mptrac.h:4155
size_t subdomain_start[4]
Start indices of the local subdomain hyperslab (including inner halos).
Definition mptrac.h:4152
double lon[EX]
Longitudes [deg].
Definition mptrac.h:3973
double lat[EY]
Latitudes [deg].
Definition mptrac.h:3976

◆ dd_sort()

void dd_sort ( const ctl_t * ctl,
const met_t * met0,
cache_t * cache,
atm_t * atm,
dd_t * dd,
int * npart )

Sort local atmospheric particles and determine export counts for domain decomposition.

This routine reorders the local atmospheric particle arrays so that particles remaining on the current MPI rank are placed first, followed by particles that must be sent to other ranks, and finally particles already marked invalid with subdomain index -1.

For each particle a sorting key is constructed:

  • particles with a valid subdomain and destination equal to the current MPI rank receive a key derived from their meteorological grid-box index,
  • particles with a valid subdomain but destination on another rank receive a key larger than any valid grid-box key,
  • particles with subdomain index -1 receive the largest keys and are moved to the end of the arrays.

The resulting permutation is applied to all particle arrays (time, p, lon, lat, and all quantities q[iq]) and their persistent particle-specific cache values (dt and uvwp). Random values in rs are regenerated before use; shared cache data remain unchanged.

After sorting, the routine

  • counts the number of particles that remain on the current rank,
  • counts the number of particles that must be exported to other ranks,
  • stores the export count in npart,
  • reduces atm->np to the number of particles kept locally.

Particles with subdomain index -1 are removed from the active particle set. A warning is issued if such particles are encountered.

Parameters
[in]ctlControl structure containing the quantity indices qnt_current_subdomain, qnt_target_subdomain, and the number of quantities nq.
[in]met0Meteorological grid used to compute sorting keys from particle longitude, latitude, and pressure.
[in,out]cacheParticle-specific cache values to reorder with the atmospheric state.
[in,out]atmAtmospheric state. Particle arrays are reordered in place and atm->np is reduced to the number of particles retained locally.
[in,out]ddDomain decomposition structure providing the temporary arrays sort_key and perm used during sorting.
[out]npartNumber of particles that must be sent to other MPI ranks.
Note
  • The current MPI rank is obtained internally from MPI_COMM_WORLD.
  • When compiled with _OPENACC, key generation, counting, and selected data movement may execute on the accelerator.
  • When compiled with THRUST, sorting may use the GPU-based thrustSortWrapper; otherwise a GSL-based index sort is used.
Author
Jan Clemens
Lars Hoffmann

Definition at line 2681 of file mptrac.c.

2687 {
2688
2689 /* Set timer... */
2690 SELECT_TIMER("DD_SORT", "DD");
2691
2692 int rank;
2693 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
2694
2695 /* Allocate... */
2696 const int np = atm->np;
2697 double amax = (met0->nx * met0->ny + met0->ny) * met0->np + met0->np;
2698#ifdef _OPENACC
2699#pragma acc enter data create(amax)
2700#pragma acc update device(amax)
2701#pragma acc data present(ctl,met0,atm,dd,amax)
2702#endif
2703
2704 /* Get box index... */
2705#ifdef _OPENACC
2706#pragma acc parallel loop independent gang vector
2707#else
2708#pragma omp parallel for default(shared)
2709#endif
2710 for (int ip = 0; ip < np; ip++) {
2711 if ((int) atm->q[ctl->qnt_current_subdomain][ip] != -1) {
2712 if ((int) atm->q[ctl->qnt_target_subdomain][ip] == rank)
2713 dd->sort_key[ip] =
2714 (double) ((locate_reg(met0->lon, met0->nx, atm->lon[ip]) *
2715 met0->ny + locate_irr(met0->lat, met0->ny, atm->lat[ip]))
2716 * met0->np + locate_irr(met0->p, met0->np, atm->p[ip]));
2717 else
2718 dd->sort_key[ip] = amax + 1;
2719 } else {
2720 dd->sort_key[ip] = amax + 2;
2721 }
2722 dd->perm[ip] = ip;
2723 }
2724
2725 /* Sorting... */
2726#ifdef THRUST
2727#ifdef _OPENACC
2728#pragma acc host_data use_device(dd->sort_key, dd->perm)
2729#endif
2730 thrustSortWrapper(dd->sort_key, np, dd->perm);
2731#else
2732 size_t *perm_sz = (size_t *) malloc((size_t) np * sizeof(size_t));
2733 if (perm_sz == NULL)
2734 ERRMSG("Out of memory!");
2735#ifdef _OPENACC
2736#pragma acc update self(dd->sort_key[0:np])
2737#endif
2738 gsl_sort_index(perm_sz, dd->sort_key, 1, (size_t) np);
2739 for (int ip = 0; ip < np; ++ip)
2740 dd->perm[ip] = (int) perm_sz[ip];
2741 free(perm_sz);
2742#ifdef _OPENACC
2743#pragma acc update device(dd->perm[0:np])
2744#endif
2745#endif
2746
2747 /* Sort data... */
2748 sort_array(atm->time, dd->perm, dd->tmp, np);
2749 sort_array(atm->p, dd->perm, dd->tmp, np);
2750 sort_array(atm->lon, dd->perm, dd->tmp, np);
2751 sort_array(atm->lat, dd->perm, dd->tmp, np);
2752 for (int iq = 0; iq < ctl->nq; iq++)
2753 sort_array(atm->q[iq], dd->perm, dd->tmp, np);
2754 sort_array(cache->dt, dd->perm, dd->tmp, np);
2755 sort_uvwp(cache, dd->perm, dd->tmp, np);
2756
2757 /* Count kept, outgoing, and invalid particles in one pass... */
2758 int nkeep = 0, nsend = 0, nlost = 0;
2759#ifdef _OPENACC
2760#pragma acc parallel loop reduction(+:nkeep,nsend,nlost) present(atm, ctl)
2761#endif
2762 for (int ip = 0; ip < np; ip++) {
2763 const int current = (int) atm->q[ctl->qnt_current_subdomain][ip];
2764 const int target = (int) atm->q[ctl->qnt_target_subdomain][ip];
2765 if (current == -1)
2766 nlost++;
2767 else if (target == rank)
2768 nkeep++;
2769 else
2770 nsend++;
2771 }
2772
2773 /* Reset sizes... */
2774 *npart = nsend;
2775
2776 if (nlost > 0)
2777 WARN
2778 ("Rank %d: removing %d inactive particle slots during DD sorting (kept: %d, to_send: %d, total_before: %d)",
2779 rank, nlost, nkeep, nsend, np);
2780
2781 atm->np = nkeep;
2782#ifdef _OPENACC
2783#pragma acc update device(atm->np)
2784#endif
2785
2786 /* Free... */
2787#ifdef _OPENACC
2788#pragma acc exit data delete(amax)
2789#endif
2790}
double sort_key[NP]
Auxiliary array for sorting.
Definition mptrac.h:4179
Here is the call graph for this function:

◆ doy2day()

void doy2day ( const int year,
const int doy,
int * mon,
int * day )

Converts a given day of the year (DOY) to a date (month and day).

This function computes the month and day for a given day of the year (DOY) and year. It accounts for whether the given year is a leap year or not.

Parameters
yearThe year corresponding to the DOY.
doyThe day of the year (1-365 or 1-366).
monPointer to an integer where the computed month will be stored.
dayPointer to an integer where the computed day of the month will be stored.

The function uses two arrays, d0 and d0l, which contain the cumulative number of days at the start of each month for non-leap years and leap years respectively. It checks if the year is a leap year and calculates the month and day of the month accordingly.

Note
The function assumes that the input DOY is valid for the given year.
Author
Lars Hoffmann

Definition at line 2862 of file mptrac.c.

2866 {
2867
2868 const int
2869 d0[12] = { 1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 },
2870 d0l[12] = { 1, 32, 61, 92, 122, 153, 183, 214, 245, 275, 306, 336 };
2871
2872 int i;
2873
2874 /* Get month and day... */
2875 if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
2876 for (i = 11; i > 0; i--)
2877 if (d0l[i] <= doy)
2878 break;
2879 *mon = i + 1;
2880 *day = doy - d0l[i] + 1;
2881 } else {
2882 for (i = 11; i > 0; i--)
2883 if (d0[i] <= doy)
2884 break;
2885 *mon = i + 1;
2886 *day = doy - d0[i] + 1;
2887 }
2888}

◆ fft_help()

void fft_help ( double * fcReal,
double * fcImag,
const int n )

Computes the Fast Fourier Transform (FFT) of a complex sequence.

This function calculates the FFT of a complex sequence represented by separate arrays for the real and imaginary parts. The input arrays fcReal and fcImag are modified in place to contain the transformed data.

Parameters
fcRealPointer to an array of doubles representing the real part of the input sequence. The array should have at least n elements.
fcImagPointer to an array of doubles representing the imaginary part of the input sequence. The array should have at least n elements.
nThe number of complex data points in the input sequence. This value should not exceed PMAX.
Precondition
fcReal and fcImag must point to arrays of at least n elements.
n must be less than or equal to PMAX.
Postcondition
The arrays fcReal and fcImag will contain the real and imaginary parts of the FFT result, respectively.
Note
This function uses the GNU Scientific Library (GSL) for computing the FFT. Ensure that GSL is properly installed and linked in your project.
Warning
If n exceeds PMAX, the function will trigger an error message and terminate.
Author
Lars Hoffmann

Definition at line 2892 of file mptrac.c.

2895 {
2896
2897 double data[2 * EX];
2898
2899 /* Check size... */
2900 if (n > EX)
2901 ERRMSG("Too many data points!");
2902
2903 /* Allocate... */
2904 gsl_fft_complex_wavetable *wavetable =
2905 gsl_fft_complex_wavetable_alloc((size_t) n);
2906 gsl_fft_complex_workspace *workspace =
2907 gsl_fft_complex_workspace_alloc((size_t) n);
2908
2909 /* Set data (real, complex)... */
2910 for (int i = 0; i < n; i++) {
2911 data[2 * i] = fcReal[i];
2912 data[2 * i + 1] = fcImag[i];
2913 }
2914
2915 /* Calculate FFT... */
2916 gsl_fft_complex_forward(data, 1, (size_t) n, wavetable, workspace);
2917
2918 /* Copy data... */
2919 for (int i = 0; i < n; i++) {
2920 fcReal[i] = data[2 * i];
2921 fcImag[i] = data[2 * i + 1];
2922 }
2923
2924 /* Free... */
2925 gsl_fft_complex_wavetable_free(wavetable);
2926 gsl_fft_complex_workspace_free(workspace);
2927}

◆ geo2cart()

void geo2cart ( const double z,
const double lon,
const double lat,
double * x )

Converts geographic coordinates (longitude, latitude, altitude) to Cartesian coordinates.

This function converts geographic coordinates specified by longitude, latitude, and altitude into Cartesian coordinates. The Earth is approximated as a sphere with radius defined by the constant RE.

Parameters
zThe altitude above the Earth's surface in kilometers.
lonThe longitude in degrees.
latThe latitude in degrees.
xPointer to an array of three doubles where the computed Cartesian coordinates (x, y, z) will be stored.

The function computes the Cartesian coordinates using the given altitude, longitude, and latitude. It assumes the Earth is a perfect sphere and uses the following formulas:

  • \( x = (\textrm{radius}) \cos(\textrm{lat in radians}) \cos(\textrm{lon in radians}) \)
  • \( y = (\textrm{radius}) \cos(\textrm{lat in radians}) \sin(\textrm{lon in radians}) \)
  • \( z = (\textrm{radius}) \sin(\textrm{lat in radians}) \)
Note
The constant RE is defined as the Earth's radius in kilometers.
Longitude and latitude should be in degrees.
See also
https://en.wikipedia.org/wiki/Geographic_coordinate_conversion
Author
Lars Hoffmann

Definition at line 2931 of file mptrac.c.

2935 {
2936
2937 const double radius = z + RE;
2938 const double latrad = DEG2RAD(lat);
2939 const double lonrad = DEG2RAD(lon);
2940 const double coslat = cos(latrad);
2941
2942 x[0] = radius * coslat * cos(lonrad);
2943 x[1] = radius * coslat * sin(lonrad);
2944 x[2] = radius * sin(latrad);
2945}

◆ get_met_filename()

void get_met_filename ( const ctl_t * ctl,
const double t,
const int direct,
const char * metbase,
const double dt_met,
char * filename )

Generates a formatted filename for meteorological data files based on the input parameters.

This function determines a rounded time interval, decodes the time components (year, month, day, hour, minute, second), and constructs a filename string for meteorological data files in various formats. The filename is adjusted based on the input control settings.

Parameters
[in]ctlPointer to the control structure containing configuration settings.
[in]tThe time value in seconds since a reference epoch.
[in]directDirection to round the time value. Use -1 for rounding down and 1 for rounding up.
[in]metbaseBase string for the filename, representing the dataset.
[in]dt_metTime interval for rounding in seconds.
[out]filenameOutput buffer to store the generated filename.
Note
The function modifies the provided filename buffer to include placeholders (e.g., YYYY, MM, DD, HH) replaced with the corresponding time values. The format of the filename depends on the values in the control structure (e.g., ctl->met_type).
Warning
Ensure that the filename buffer has sufficient size to accommodate the resulting string.
Author
Lars Hoffmann

Definition at line 2949 of file mptrac.c.

2955 {
2956
2957 char repl[LEN];
2958
2959 double t6, r;
2960
2961 int year, mon, day, hour, min, sec;
2962
2963 /* Round time to fixed intervals... */
2964 if (direct == -1)
2965 t6 = floor(t / dt_met) * dt_met;
2966 else
2967 t6 = ceil(t / dt_met) * dt_met;
2968
2969 /* Decode time... */
2970 jsec2time(t6, &year, &mon, &day, &hour, &min, &sec, &r);
2971
2972 /* Set filename of MPTRAC meteo files... */
2973 if (ctl->met_clams == 0) {
2974 if (ctl->met_type == 0)
2975 sprintf(filename, "%s_YYYY_MM_DD_HH.nc", metbase);
2976 else if (ctl->met_type == 1)
2977 sprintf(filename, "%s_YYYY_MM_DD_HH.bin", metbase);
2978 else if (ctl->met_type == 2)
2979 sprintf(filename, "%s_YYYY_MM_DD_HH.pck", metbase);
2980 else if (ctl->met_type == 3)
2981 sprintf(filename, "%s_YYYY_MM_DD_HH.zfp", metbase);
2982 else if (ctl->met_type == 4)
2983 sprintf(filename, "%s_YYYY_MM_DD_HH.zstd", metbase);
2984 else if (ctl->met_type == 5)
2985 sprintf(filename, "%s_YYYY_MM_DD_HH.cms", metbase);
2986 else if (ctl->met_type == 7)
2987 sprintf(filename, "%s_YYYY_MM_DD_HH.sz3", metbase);
2988 else if (ctl->met_type == 8)
2989 sprintf(filename, "%s_YYYY_MM_DD_HH.lz4", metbase);
2990 sprintf(repl, "%d", year);
2991 get_met_replace(filename, "YYYY", repl);
2992 sprintf(repl, "%02d", mon);
2993 get_met_replace(filename, "MM", repl);
2994 sprintf(repl, "%02d", day);
2995 get_met_replace(filename, "DD", repl);
2996 sprintf(repl, "%02d", hour);
2997 get_met_replace(filename, "HH", repl);
2998 }
2999
3000 /* Set filename of CLaMS meteo files... */
3001 else {
3002 sprintf(filename, "%s_YYMMDDHH.nc", metbase);
3003 sprintf(repl, "%d", year);
3004 get_met_replace(filename, "YYYY", repl);
3005 sprintf(repl, "%02d", year % 100);
3006 get_met_replace(filename, "YY", repl);
3007 sprintf(repl, "%02d", mon);
3008 get_met_replace(filename, "MM", repl);
3009 sprintf(repl, "%02d", day);
3010 get_met_replace(filename, "DD", repl);
3011 sprintf(repl, "%02d", hour);
3012 get_met_replace(filename, "HH", repl);
3013 }
3014}
void jsec2time(const double jsec, int *year, int *mon, int *day, int *hour, int *min, int *sec, double *remain)
Converts Julian seconds to calendar date and time components.
Definition mptrac.c:3609
void get_met_replace(char *orig, const char *search, const char *repl)
Replaces occurrences of a substring in a string with another substring.
Definition mptrac.c:3018
int met_clams
Read MPTRAC or CLaMS meteo data (0=MPTRAC, 1=CLaMS).
Definition mptrac.h:2937
int met_type
Type of meteo data files (0=netCDF, 1=binary, 2=pck, 3=ZFP, 4=ZSTD, 5=cms, 6=grib,...
Definition mptrac.h:2934
Here is the call graph for this function:

◆ get_met_replace()

void get_met_replace ( char * orig,
const char * search,
const char * repl )

Replaces occurrences of a substring in a string with another substring.

This function replaces occurrences of the substring search in the string orig with the substring repl. The replacement is performed in-place.

Parameters
origThe original string where replacements are to be made.
searchThe substring to be replaced.
replThe substring to replace occurrences of search.

The function iterates over the original string orig and replaces each occurrence of the substring search with the substring repl. It performs the replacement operation up to three times to ensure multiple occurrences are replaced.

Note
We use this function to replace the strings YYYY, MM, and DD by year, month, and day in filenames.
Ensure that orig, search, and repl are properly initialized and have sufficient memory allocated before calling this function.
Author
Lars Hoffmann

Definition at line 3018 of file mptrac.c.

3021 {
3022
3023 char buffer[LEN];
3024
3025 /* Iterate... */
3026 for (int i = 0; i < 3; i++) {
3027
3028 /* Replace sub-string... */
3029 char *ch;
3030 if (!(ch = strstr(orig, search)))
3031 return;
3032 strncpy(buffer, orig, (size_t) (ch - orig));
3033 buffer[ch - orig] = 0;
3034 sprintf(buffer + (ch - orig), "%s%s", repl, ch + strlen(search));
3035 orig[0] = 0;
3036 strcpy(orig, buffer);
3037 }
3038}

◆ get_tropo()

void get_tropo ( const int met_tropo,
ctl_t * ctl,
const clim_t * clim,
met_t * met,
const double * lons,
const int nx,
const double * lats,
const int ny,
double * pt,
double * zt,
double * tt,
double * qt,
double * o3t,
double * ps,
double * zs )

Calculate tropopause data.

This function reads and interpolates various meteorological parameters such as tropopause pressure, temperature, and ozone concentration at specified latitudes and longitudes. The interpolated data is stored in the provided arrays.

Parameters
met_tropoAn integer specifying the type of meteorological data to use.
ctlPointer to a ctl_t structure that controls the meteorological data processing.
climPointer to a clim_t structure containing climatological data.
metPointer to a met_t structure containing meteorological data.
lonsArray of longitudes at which to interpolate data. The array should have nx elements.
nxNumber of longitude points.
latsArray of latitudes at which to interpolate data. The array should have ny elements.
nyNumber of latitude points.
ptPointer to an array where the interpolated pressure values will be stored. The array should have nx * ny elements.
ztPointer to an array where the interpolated height values will be stored. The array should have nx * ny elements.
ttPointer to an array where the interpolated temperature values will be stored. The array should have nx * ny elements.
qtPointer to an array where the interpolated specific humidity values will be stored. The array should have nx * ny elements.
o3tPointer to an array where the interpolated ozone concentration values will be stored. The array should have nx * ny elements.
psPointer to an array where the interpolated surface pressure values will be stored. The array should have nx * ny elements.
zsPointer to an array where the interpolated surface height values will be stored. The array should have nx * ny elements.
Precondition
lons must have at least nx elements.
lats must have at least ny elements.
pt, zt, tt, qt, o3t, ps, and zs must have at least nx * ny elements.
Postcondition
The arrays pt, zt, tt, qt, o3t, ps, and zs will contain the interpolated meteorological data.
Note
The function utilizes OpenMP for parallel processing of the interpolation tasks.
The function uses the auxiliary functions read_met_tropo, intpol_met_space_2d, and intpol_met_space_3d for reading and interpolating the tropopause data.
Author
Lars Hoffmann

Definition at line 3042 of file mptrac.c.

3057 {
3058
3060
3061 ctl->met_tropo = met_tropo;
3062 read_met_tropo(ctl, clim, met);
3063#pragma omp parallel for default(shared) private(ci,cw)
3064 for (int ix = 0; ix < nx; ix++)
3065 for (int iy = 0; iy < ny; iy++) {
3066 intpol_met_space_2d(met, met->pt, lons[ix], lats[iy],
3067 &pt[iy * nx + ix], ci, cw, 1);
3068 intpol_met_space_2d(met, met->ps, lons[ix], lats[iy],
3069 &ps[iy * nx + ix], ci, cw, 0);
3070 intpol_met_space_2d(met, met->zs, lons[ix], lats[iy],
3071 &zs[iy * nx + ix], ci, cw, 0);
3072 intpol_met_space_3d(met, met->z, pt[iy * nx + ix], lons[ix],
3073 lats[iy], &zt[iy * nx + ix], ci, cw, 1);
3074 intpol_met_space_3d(met, met->t, pt[iy * nx + ix], lons[ix],
3075 lats[iy], &tt[iy * nx + ix], ci, cw, 0);
3076 intpol_met_space_3d(met, met->h2o, pt[iy * nx + ix], lons[ix],
3077 lats[iy], &qt[iy * nx + ix], ci, cw, 0);
3078 intpol_met_space_3d(met, met->o3, pt[iy * nx + ix], lons[ix],
3079 lats[iy], &o3t[iy * nx + ix], ci, cw, 0);
3080 }
3081}
void intpol_met_space_2d(const met_t *met, float array[EX][EY], const double lon, const double lat, double *var, int *ci, double *cw, const int init)
Interpolates meteorological variables in 2D space.
Definition mptrac.c:3379
void read_met_tropo(const ctl_t *ctl, const clim_t *clim, met_t *met)
Calculates the tropopause and related meteorological variables based on various methods and stores th...
Definition mptrac.c:13496
void intpol_met_space_3d(const met_t *met, float array[EX][EY][EP], const double p, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
Interpolates meteorological variables in 3D space.
Definition mptrac.c:3316
#define INTPOL_INIT
Initialize arrays for interpolation.
Definition mptrac.h:1219
int met_tropo
Tropopause definition (0=none, 1=clim, 2=cold point, 3=WMO_1st, 4=WMO_2nd, 5=dynamical).
Definition mptrac.h:3061
float h2o[EX][EY][EP]
Water vapor volume mixing ratio [1].
Definition mptrac.h:4084
float ps[EX][EY]
Surface pressure [hPa].
Definition mptrac.h:3994
float zs[EX][EY]
Surface geopotential height [km].
Definition mptrac.h:4000
float o3[EX][EY][EP]
Ozone volume mixing ratio [1].
Definition mptrac.h:4087
float t[EX][EY][EP]
Temperature [K].
Definition mptrac.h:4069
float pt[EX][EY]
Tropopause pressure [hPa].
Definition mptrac.h:4027
float z[EX][EY][EP]
Geopotential height [km].
Definition mptrac.h:4066
Here is the call graph for this function:

◆ intpol_check_lon_lat()

void intpol_check_lon_lat ( const double * lons,
const int nlon,
const double * lats,
const int nlat,
const double lon,
const double lat,
double * lon2,
double * lat2 )

Adjusts longitude and latitude to ensure they fall within valid bounds.

This function checks and modifies the given longitude and latitude values to fit within the specified longitude and latitude arrays. The longitude is wrapped within a 360-degree range, and the latitude is clamped within the valid range defined by the latitude array.

Parameters
[in]lonsPointer to an array of valid longitude values.
[in]nlonNumber of elements in the longitude array.
[in]latsPointer to an array of valid latitude values.
[in]nlatNumber of elements in the latitude array.
[in]lonInput longitude to be checked and adjusted.
[in]latInput latitude to be checked and adjusted.
[out]lon2Pointer to the adjusted longitude.
[out]lat2Pointer to the adjusted latitude.
Author
Lars Hoffmann

Definition at line 3085 of file mptrac.c.

3093 {
3094
3095 /* Check longitude... */
3096 *lon2 = FMOD(lon, 360.);
3097 if (*lon2 < lons[0])
3098 *lon2 += 360;
3099 else if (*lon2 > lons[nlon - 1])
3100 *lon2 -= 360;
3101
3102 /* Check latitude... */
3103 *lat2 = lat;
3104 if (lats[0] < lats[nlat - 1])
3105 *lat2 = MIN(MAX(*lat2, lats[0]), lats[nlat - 1]);
3106 else
3107 *lat2 = MIN(MAX(*lat2, lats[nlat - 1]), lats[0]);
3108}

◆ intpol_check_cartesian()

void intpol_check_cartesian ( const double * lons,
const int nlon,
const double * lats,
const int nlat,
const double lon,
const double lat,
double * lon2,
double * lat2 )

Clamps UTM coordinates to the valid bounds.

This function constrains the given UTM easting and northing values so they remain within the limits defined by the provided x and y coordinate arrays.

Parameters
[in]lonsPointer to an array of valid x/easting values.
[in]nlonNumber of elements in the x/easting array.
[in]latsPointer to an array of valid y/northing values.
[in]nlatNumber of elements in the y/northing array.
[in]lonInput x/easting coordinate to be checked and adjusted.
[in]latInput y/northing coordinate to be checked and adjusted.
[out]lon2Pointer to the adjusted x/easting coordinate.
[out]lat2Pointer to the adjusted y/northing coordinate.
Author
Robin Brase

Definition at line 3112 of file mptrac.c.

3120 {
3121
3122 *lon2 = lon;
3123 if (lons[0] < lons[nlon - 1])
3124 *lon2 = MIN(MAX(lon, lons[0]), lons[nlon - 1]);
3125 else
3126 *lon2 = MIN(MAX(lon, lons[nlon - 1]), lons[0]);
3127
3128 *lat2 = lat;
3129 if (lats[0] < lats[nlat - 1])
3130 *lat2 = MIN(MAX(lat, lats[0]), lats[nlat - 1]);
3131 else
3132 *lat2 = MIN(MAX(lat, lats[nlat - 1]), lats[0]);
3133}

◆ intpol_met_4d_zeta()

void intpol_met_4d_zeta ( const met_t * met0,
float height0[EX][EY][EP],
float array0[EX][EY][EP],
const met_t * met1,
float height1[EX][EY][EP],
float array1[EX][EY][EP],
const double ts,
const double height,
const double lon,
const double lat,
double * var,
int * ci,
double * cw,
const int init )

Interpolates meteorological variables to a given position and time.

This function interpolates meteorological variables to a specified position and time. It calculates the interpolated value based on the values provided at two time steps and performs interpolation in time, longitude, latitude, and altitude dimensions.

Parameters
met0Pointer to the meteorological data at the first time step.
height0Array containing heights at the first time step.
array0Array containing meteorological variable values at the first time step.
met1Pointer to the meteorological data at the second time step.
height1Array containing heights at the second time step.
array1Array containing meteorological variable values at the second time step.
tsAbsolute interpolation time [s] on the same time axis as met0 and met1.
heightVertical coordinate at which to interpolate (e.g., pressure or zeta).
lonLongitude at which to interpolate.
latLatitude at which to interpolate.
varPointer to store the interpolated variable value.
ciArray to store the calculated indices.
cwArray to store the weighting factors.
initFlag indicating if it's the first call (1) or not (0).

The function first restricts the longitude within the range [0, 360) degrees. It then calculates the horizontal indices (ci[0] and ci[1]) based on the provided longitude and latitude. Next, it locates the vertical indices for each edge of the column based on the provided height.

The function then calculates the weighting factors for time, longitude, latitude, and altitude. It iterates over the interpolation process to determine the altitude weighting factor. After initializing the interpolation parameters, it calculates the interpolated variable value and stores it in the memory location pointed to by var.

Time and vertical weights are not clamped, allowing extrapolation from the selected intervals. This is intended primarily to tolerate small boundary excursions from integration, diffusion, or floating-point rounding.

Note
Ensure that all arrays (height0, array0, height1, array1, ci, cw) have sufficient memory allocated before calling this function.
Author
Jan Clemens

Definition at line 3138 of file mptrac.c.

3152 {
3153
3154 if (init) {
3155
3156 /* Check longitude and latitude... */
3157 double lon2, lat2;
3158
3159 if (met0->coord_type == 0)
3160 intpol_check_lon_lat(met0->lon, met0->nx, met0->lat, met0->ny, lon, lat,
3161 &lon2, &lat2);
3162 else
3163 intpol_check_cartesian(met0->lon, met0->nx, met0->lat, met0->ny, lon,
3164 lat, &lon2, &lat2);
3165
3166 /* Get horizontal indizes... */
3167 ci[0] = locate_reg(met0->lon, met0->nx, lon2);
3168 ci[1] = locate_irr(met0->lat, met0->ny, lat2);
3169
3170 /* Locate the vertical indizes for each edge of the column... */
3171 int ind[2][4];
3172 locate_vert(heights0, met0->npl, ci[0], ci[1], height, ind[0]);
3173 locate_vert(heights1, met1->npl, ci[0], ci[1], height, ind[1]);
3174
3175 /* Find minimum and maximum indizes... */
3176 ci[2] = ind[0][0];
3177 int k_max = ind[0][0];
3178 for (int i = 0; i < 2; i++)
3179 for (int j = 0; j < 4; j++) {
3180 if (ci[2] > ind[i][j])
3181 ci[2] = ind[i][j];
3182 if (k_max < ind[i][j])
3183 k_max = ind[i][j];
3184 }
3185
3186 /* Get weighting factors for time, longitude and latitude... */
3187 cw[3] = (ts - met0->time) / (met1->time - met0->time);
3188 cw[0] = (lon2 - met0->lon[ci[0]]) /
3189 (met0->lon[ci[0] + 1] - met0->lon[ci[0]]);
3190 cw[1] = (lat2 - met0->lat[ci[1]]) /
3191 (met0->lat[ci[1] + 1] - met0->lat[ci[1]]);
3192
3193 /* Interpolate in time at the lowest level... */
3194 double height00 = cw[3] * (heights1[ci[0]][ci[1]][ci[2]]
3195 - heights0[ci[0]][ci[1]][ci[2]])
3196 + heights0[ci[0]][ci[1]][ci[2]];
3197 double height01 = cw[3] * (heights1[ci[0]][ci[1] + 1][ci[2]]
3198 - heights0[ci[0]][ci[1] + 1][ci[2]])
3199 + heights0[ci[0]][ci[1] + 1][ci[2]];
3200 double height10 = cw[3] * (heights1[ci[0] + 1][ci[1]][ci[2]]
3201 - heights0[ci[0] + 1][ci[1]][ci[2]])
3202 + heights0[ci[0] + 1][ci[1]][ci[2]];
3203 double height11 = cw[3] * (heights1[ci[0] + 1][ci[1] + 1][ci[2]]
3204 - heights0[ci[0] + 1][ci[1] + 1][ci[2]])
3205 + heights0[ci[0] + 1][ci[1] + 1][ci[2]];
3206
3207 /* Interpolate in latitude direction... */
3208 double height0 = cw[1] * (height01 - height00) + height00;
3209 double height1 = cw[1] * (height11 - height10) + height10;
3210
3211 /* Interpolate in longitude direction... */
3212 double height_bot = cw[0] * (height1 - height0) + height0;
3213
3214 /* Interpolate in time at the upper level... */
3215 height00 = cw[3] * (heights1[ci[0]][ci[1]][ci[2] + 1]
3216 - heights0[ci[0]][ci[1]][ci[2] + 1])
3217 + heights0[ci[0]][ci[1]][ci[2] + 1];
3218 height01 = cw[3] * (heights1[ci[0]][ci[1] + 1][ci[2] + 1]
3219 - heights0[ci[0]][ci[1] + 1][ci[2] + 1])
3220 + heights0[ci[0]][ci[1] + 1][ci[2] + 1];
3221 height10 = cw[3] * (heights1[ci[0] + 1][ci[1]][ci[2] + 1]
3222 - heights0[ci[0] + 1][ci[1]][ci[2] + 1])
3223 + heights0[ci[0] + 1][ci[1]][ci[2] + 1];
3224 height11 = cw[3] * (heights1[ci[0] + 1][ci[1] + 1][ci[2] + 1]
3225 - heights0[ci[0] + 1][ci[1] + 1][ci[2] + 1])
3226 + heights0[ci[0] + 1][ci[1] + 1][ci[2] + 1];
3227
3228 /* Interpolate in latitude direction... */
3229 height0 = cw[1] * (height01 - height00) + height00;
3230 height1 = cw[1] * (height11 - height10) + height10;
3231
3232 /* Interpolate in longitude direction... */
3233 double height_top = cw[0] * (height1 - height0) + height0;
3234
3235 /* Search at higher levels if height is not in box... */
3236 while (((heights0[0][0][0] > heights0[0][0][1]) &&
3237 ((height_bot <= height) || (height_top > height))
3238 && (height_bot >= height) && (ci[2] < k_max))
3239 ||
3240 ((heights0[0][0][0] < heights0[0][0][1]) &&
3241 ((height_bot >= height) || (height_top < height))
3242 && (height_bot <= height) && (ci[2] < k_max))
3243 ) {
3244
3245 ci[2]++;
3246 height_bot = height_top;
3247
3248 /* Interpolate in time at the next level... */
3249 height00 = cw[3] * (heights1[ci[0]][ci[1]][ci[2] + 1]
3250 - heights0[ci[0]][ci[1]][ci[2] + 1])
3251 + heights0[ci[0]][ci[1]][ci[2] + 1];
3252 height01 = cw[3] * (heights1[ci[0]][ci[1] + 1][ci[2] + 1]
3253 - heights0[ci[0]][ci[1] + 1][ci[2] + 1])
3254 + heights0[ci[0]][ci[1] + 1][ci[2] + 1];
3255 height10 = cw[3] * (heights1[ci[0] + 1][ci[1]][ci[2] + 1]
3256 - heights0[ci[0] + 1][ci[1]][ci[2] + 1])
3257 + heights0[ci[0] + 1][ci[1]][ci[2] + 1];
3258 height11 = cw[3] * (heights1[ci[0] + 1][ci[1] + 1][ci[2] + 1]
3259 - heights0[ci[0] + 1][ci[1] + 1][ci[2] + 1])
3260 + heights0[ci[0] + 1][ci[1] + 1][ci[2] + 1];
3261
3262 /* Interpolate in latitude direction... */
3263 height0 = cw[1] * (height01 - height00) + height00;
3264 height1 = cw[1] * (height11 - height10) + height10;
3265
3266 /* Interpolate in longitude direction... */
3267 height_top = cw[0] * (height1 - height0) + height0;
3268 }
3269
3270 /* Get vertical weighting factors... */
3271 cw[2] = (height - height_bot)
3272 / (height_top - height_bot);
3273 }
3274
3275 /* Interpolate the eight surrounding model-level values in time... */
3276 const double array000 = cw[3] * (array1[ci[0]][ci[1]][ci[2]]
3277 - array0[ci[0]][ci[1]][ci[2]])
3278 + array0[ci[0]][ci[1]][ci[2]];
3279 const double array100 = cw[3] * (array1[ci[0] + 1][ci[1]][ci[2]]
3280 - array0[ci[0] + 1][ci[1]][ci[2]])
3281 + array0[ci[0] + 1][ci[1]][ci[2]];
3282 const double array010 = cw[3] * (array1[ci[0]][ci[1] + 1][ci[2]]
3283 - array0[ci[0]][ci[1] + 1][ci[2]])
3284 + array0[ci[0]][ci[1] + 1][ci[2]];
3285 const double array110 = cw[3] * (array1[ci[0] + 1][ci[1] + 1][ci[2]]
3286 - array0[ci[0] + 1][ci[1] + 1][ci[2]])
3287 + array0[ci[0] + 1][ci[1] + 1][ci[2]];
3288 const double array001 = cw[3] * (array1[ci[0]][ci[1]][ci[2] + 1]
3289 - array0[ci[0]][ci[1]][ci[2] + 1])
3290 + array0[ci[0]][ci[1]][ci[2] + 1];
3291 const double array101 = cw[3] * (array1[ci[0] + 1][ci[1]][ci[2] + 1]
3292 - array0[ci[0] + 1][ci[1]][ci[2] + 1])
3293 + array0[ci[0] + 1][ci[1]][ci[2] + 1];
3294 const double array011 = cw[3] * (array1[ci[0]][ci[1] + 1][ci[2] + 1]
3295 - array0[ci[0]][ci[1] + 1][ci[2] + 1])
3296 + array0[ci[0]][ci[1] + 1][ci[2] + 1];
3297 const double array111 = cw[3] * (array1[ci[0] + 1][ci[1] + 1][ci[2] + 1]
3298 - array0[ci[0] + 1][ci[1] + 1][ci[2] + 1])
3299 + array0[ci[0] + 1][ci[1] + 1][ci[2] + 1];
3300
3301 /* Interpolate horizontally on the lower and upper levels... */
3302 const double array00 = cw[0] * (array100 - array000) + array000;
3303 const double array10 = cw[0] * (array110 - array010) + array010;
3304 const double array01 = cw[0] * (array101 - array001) + array001;
3305 const double array11 = cw[0] * (array111 - array011) + array011;
3306
3307 const double aux0 = cw[1] * (array10 - array00) + array00;
3308 const double aux1 = cw[1] * (array11 - array01) + array01;
3309
3310 /* Interpolate vertically... */
3311 *var = cw[2] * (aux1 - aux0) + aux0;
3312}
void intpol_check_cartesian(const double *lons, const int nlon, const double *lats, const int nlat, const double lon, const double lat, double *lon2, double *lat2)
Clamps UTM coordinates to the valid bounds.
Definition mptrac.c:3112
void locate_vert(float profiles[EX][EY][EP], const int np, const int lon_ap_ind, const int lat_ap_ind, const double height_ap, int *ind)
Locate the four vertical indizes of a box for a given height value.
Definition mptrac.c:3922
void intpol_check_lon_lat(const double *lons, const int nlon, const double *lats, const int nlat, const double lon, const double lat, double *lon2, double *lat2)
Adjusts longitude and latitude to ensure they fall within valid bounds.
Definition mptrac.c:3085
int coord_type
Definition mptrac.h:3958
int npl
Number of model levels.
Definition mptrac.h:3970
double time
Time [s].
Definition mptrac.h:3955
Here is the call graph for this function:

◆ intpol_met_space_3d()

void intpol_met_space_3d ( const met_t * met,
float array[EX][EY][EP],
const double p,
const double lon,
const double lat,
double * var,
int * ci,
double * cw,
const int init )

Interpolates meteorological variables in 3D space.

This function interpolates meteorological variables at a specified pressure level and geographic position. It calculates the interpolated value based on the values provided at neighboring grid points and performs interpolation in pressure, longitude, and latitude dimensions.

Parameters
metPointer to the meteorological data.
arrayArray containing meteorological variable values.
pPressure level at which to interpolate.
lonLongitude at which to interpolate.
latLatitude at which to interpolate.
varPointer to store the interpolated variable value.
ciArray to store the calculated indices.
cwArray to store the weighting factors.
initFlag indicating if it's the first call (1) or not (0).

The function first checks the longitude and adjusts it if necessary to ensure it falls within the valid range. It then calculates the interpolation indices based on the provided pressure level, longitude, and latitude. Next, it computes the interpolation weights for pressure, longitude, and latitude.

The function interpolates vertically first and then horizontally. The interpolated value is stored in the memory location pointed to by var.

Pressures outside the level range are linearly extrapolated using the nearest level interval, primarily to tolerate small boundary excursions.

Note
Ensure that the array, ci, and cw arrays have sufficient memory allocated before calling this function.
Author
Lars Hoffmann

Definition at line 3316 of file mptrac.c.

3325 {
3326
3327 /* Initialize interpolation... */
3328 if (init) {
3329
3330 /* Check longitude and latitude... */
3331 double lon2, lat2;
3332
3333 if (met->coord_type == 0)
3334 intpol_check_lon_lat(met->lon, met->nx, met->lat, met->ny, lon, lat,
3335 &lon2, &lat2);
3336 else
3337 intpol_check_cartesian(met->lon, met->nx, met->lat, met->ny, lon, lat,
3338 &lon2, &lat2);
3339
3340 /* Get interpolation indices... */
3341 ci[0] = locate_irr(met->p, met->np, p);
3342 ci[1] = locate_reg(met->lon, met->nx, lon2);
3343 ci[2] = locate_irr(met->lat, met->ny, lat2);
3344
3345 /* Get interpolation weights... */
3346 cw[0] = (met->p[ci[0] + 1] - p)
3347 / (met->p[ci[0] + 1] - met->p[ci[0]]);
3348 cw[1] = (met->lon[ci[1] + 1] - lon2)
3349 / (met->lon[ci[1] + 1] - met->lon[ci[1]]);
3350 cw[2] = (met->lat[ci[2] + 1] - lat2)
3351 / (met->lat[ci[2] + 1] - met->lat[ci[2]]);
3352 }
3353
3354 /* Interpolate vertically... */
3355 const double aux00 =
3356 cw[0] * (array[ci[1]][ci[2]][ci[0]] - array[ci[1]][ci[2]][ci[0] + 1])
3357 + array[ci[1]][ci[2]][ci[0] + 1];
3358 const double aux01 =
3359 cw[0] * (array[ci[1]][ci[2] + 1][ci[0]] -
3360 array[ci[1]][ci[2] + 1][ci[0] + 1])
3361 + array[ci[1]][ci[2] + 1][ci[0] + 1];
3362 const double aux10 =
3363 cw[0] * (array[ci[1] + 1][ci[2]][ci[0]] -
3364 array[ci[1] + 1][ci[2]][ci[0] + 1])
3365 + array[ci[1] + 1][ci[2]][ci[0] + 1];
3366 const double aux11 =
3367 cw[0] * (array[ci[1] + 1][ci[2] + 1][ci[0]] -
3368 array[ci[1] + 1][ci[2] + 1][ci[0] + 1])
3369 + array[ci[1] + 1][ci[2] + 1][ci[0] + 1];
3370
3371 /* Interpolate horizontally... */
3372 const double aux0 = cw[2] * (aux00 - aux01) + aux01;
3373 const double aux1 = cw[2] * (aux10 - aux11) + aux11;
3374 *var = cw[1] * (aux0 - aux1) + aux1;
3375}
Here is the call graph for this function:

◆ intpol_met_space_2d()

void intpol_met_space_2d ( const met_t * met,
float array[EX][EY],
const double lon,
const double lat,
double * var,
int * ci,
double * cw,
const int init )

Interpolates meteorological variables in 2D space.

This function interpolates meteorological variables at a specified geographic position. It calculates the interpolated value based on the values provided at neighboring grid points and performs interpolation in longitude and latitude dimensions.

Parameters
metPointer to the meteorological data.
arrayArray containing meteorological variable values.
lonLongitude at which to interpolate.
latLatitude at which to interpolate.
varPointer to store the interpolated variable value.
ciArray to store the calculated indices.
cwArray to store the weighting factors.
initFlag indicating if it's the first call (1) or not (0).

The function first checks the longitude and adjusts it if necessary to ensure it falls within the valid range. It then calculates the interpolation indices based on the provided longitude and latitude. Next, it computes the interpolation weights for longitude and latitude.

The function uses bilinear interpolation when all four corners are finite. Otherwise, it returns the nearest corner according to the interpolation weights, even if that value is nonfinite. This preserves the spatial pattern of valid and missing data; selecting only finite corners would expand valid regions, for example for a second tropopause or land-sea classifications.

Note
Ensure that the array, ci, and cw arrays have sufficient memory allocated before calling this function.
Author
Lars Hoffmann

Definition at line 3379 of file mptrac.c.

3387 {
3388
3389 /* Initialize interpolation... */
3390 if (init) {
3391
3392 /* Check longitude and latitude... */
3393 double lon2, lat2;
3394
3395 if (met->coord_type == 0)
3396 intpol_check_lon_lat(met->lon, met->nx, met->lat, met->ny, lon, lat,
3397 &lon2, &lat2);
3398 else
3399 intpol_check_cartesian(met->lon, met->nx, met->lat, met->ny, lon, lat,
3400 &lon2, &lat2);
3401
3402
3403 /* Get interpolation indices... */
3404 ci[1] = locate_reg(met->lon, met->nx, lon2);
3405 ci[2] = locate_irr(met->lat, met->ny, lat2);
3406
3407 /* Get interpolation weights... */
3408 cw[1] = (met->lon[ci[1] + 1] - lon2)
3409 / (met->lon[ci[1] + 1] - met->lon[ci[1]]);
3410 cw[2] = (met->lat[ci[2] + 1] - lat2)
3411 / (met->lat[ci[2] + 1] - met->lat[ci[2]]);
3412 }
3413
3414 /* Set variables... */
3415 const double aux00 = array[ci[1]][ci[2]];
3416 const double aux01 = array[ci[1]][ci[2] + 1];
3417 const double aux10 = array[ci[1] + 1][ci[2]];
3418 const double aux11 = array[ci[1] + 1][ci[2] + 1];
3419
3420 /* Interpolate horizontally... */
3421 if (isfinite(aux00) && isfinite(aux01)
3422 && isfinite(aux10) && isfinite(aux11)) {
3423 const double aux0 = cw[2] * (aux00 - aux01) + aux01;
3424 const double aux1 = cw[2] * (aux10 - aux11) + aux11;
3425 *var = cw[1] * (aux0 - aux1) + aux1;
3426 } else {
3427 if (cw[2] < 0.5) {
3428 if (cw[1] < 0.5)
3429 *var = aux11;
3430 else
3431 *var = aux01;
3432 } else {
3433 if (cw[1] < 0.5)
3434 *var = aux10;
3435 else
3436 *var = aux00;
3437 }
3438 }
3439}
Here is the call graph for this function:

◆ intpol_met_time_3d()

void intpol_met_time_3d ( const met_t * met0,
float array0[EX][EY][EP],
const met_t * met1,
float array1[EX][EY][EP],
const double ts,
const double p,
const double lon,
const double lat,
double * var,
int * ci,
double * cw,
const int init )

Interpolates meteorological data in 3D space and time.

This function interpolates meteorological data in three dimensions (longitude, latitude, and pressure) and time. It calculates the interpolated value based on the values provided at neighboring grid points and performs interpolation both spatially and temporally.

Parameters
met0Pointer to the meteorological data at time t0.
array03D array of meteorological data at time t0.
met1Pointer to the meteorological data at time t1.
array13D array of meteorological data at time t1.
tsTime stamp at which to interpolate.
pPressure level at which to interpolate.
lonLongitude at which to interpolate.
latLatitude at which to interpolate.
varPointer to store the interpolated value.
ciArray to store the calculated indices.
cwArray to store the weighting factors.
initFlag indicating if it's the first call (1) or not (0).

The function first performs spatial interpolation for both time instances (t0 and t1) using the intpol_met_space_3d function. It then calculates the weighting factor wt based on the time stamp ts. Finally, it performs temporal interpolation using the interpolated values at t0 and t1 along with the weighting factor to compute the final interpolated value stored in var.

Times outside the two meteorological timestamps are linearly extrapolated, primarily to tolerate small boundary excursions.

Note
Ensure that the ci and cw arrays have sufficient memory allocated before calling this function.
Author
Lars Hoffmann

Definition at line 3443 of file mptrac.c.

3455 {
3456
3457 double var0, var1;
3458
3459 /* Spatial interpolation... */
3460 intpol_met_space_3d(met0, array0, p, lon, lat, &var0, ci, cw, init);
3461 intpol_met_space_3d(met1, array1, p, lon, lat, &var1, ci, cw, 0);
3462
3463 /* Get weighting factor... */
3464 const double wt = (met1->time - ts) / (met1->time - met0->time);
3465
3466 /* Interpolate... */
3467 *var = wt * (var0 - var1) + var1;
3468}
Here is the call graph for this function:

◆ intpol_met_time_2d()

void intpol_met_time_2d ( const met_t * met0,
float array0[EX][EY],
const met_t * met1,
float array1[EX][EY],
const double ts,
const double lon,
const double lat,
double * var,
int * ci,
double * cw,
const int init )

Interpolates meteorological data in 2D space and time.

This function interpolates meteorological data in two dimensions (longitude and latitude) and time. It calculates the interpolated value based on the values provided at neighboring grid points and performs interpolation both spatially and temporally.

Parameters
met0Pointer to the meteorological data at time t0.
array02D array of meteorological data at time t0.
met1Pointer to the meteorological data at time t1.
array12D array of meteorological data at time t1.
tsTime stamp at which to interpolate.
lonLongitude at which to interpolate.
latLatitude at which to interpolate.
varPointer to store the interpolated value.
ciArray to store the calculated indices.
cwArray to store the weighting factors.
initFlag indicating if it's the first call (1) or not (0).

The function first performs spatial interpolation for both time instances (t0 and t1) using the intpol_met_space_2d function. It then calculates the weighting factor wt based on the time stamp ts. Finally, it performs temporal interpolation using the interpolated values at t0 and t1 along with the weighting factor to compute the final interpolated value stored in var. If one of the interpolated values is not finite, it selects the valid value based on the weighting factor wt.

When both spatial values are finite, times outside the two meteorological timestamps are linearly extrapolated, primarily to tolerate small boundary excursions.

Note
Ensure that the ci and cw arrays have sufficient memory allocated before calling this function.
Author
Lars Hoffmann

Definition at line 3472 of file mptrac.c.

3483 {
3484
3485 double var0, var1;
3486
3487 /* Spatial interpolation... */
3488 intpol_met_space_2d(met0, array0, lon, lat, &var0, ci, cw, init);
3489 intpol_met_space_2d(met1, array1, lon, lat, &var1, ci, cw, 0);
3490
3491 /* Get weighting factor... */
3492 const double wt = (met1->time - ts) / (met1->time - met0->time);
3493
3494 /* Interpolate... */
3495 if (isfinite(var0) && isfinite(var1))
3496 *var = wt * (var0 - var1) + var1;
3497 else if (wt < 0.5)
3498 *var = var1;
3499 else
3500 *var = var0;
3501}
Here is the call graph for this function:

◆ intpol_tropo_3d()

void intpol_tropo_3d ( const double time0,
float array0[EX][EY],
const double time1,
float array1[EX][EY],
const double lons[EX],
const double lats[EY],
const int nlon,
const int nlat,
const double time,
const double lon,
const double lat,
const int method,
double * var,
double * sigma )

Interpolates tropopause data in 3D (latitude, longitude, and time).

This function performs interpolation of tropopause data at a given latitude, longitude, and time. The interpolation can be performed using either linear interpolation or nearest neighbor interpolation. The standard deviation of the data points used in the interpolation is also computed.

Parameters
time0Time corresponding to the first data array array0.
array0A 2D array of tropopause data at time0. The dimensions are EX by EY.
time1Time corresponding to the second data array array1.
array1A 2D array of tropopause data at time1. The dimensions are EX by EY.
lonsArray of longitudes with EX elements.
latsArray of latitudes with EY elements.
nlonNumber of longitudes.
nlatNumber of latitudes.
timeThe specific time at which to interpolate the data.
lonThe specific longitude at which to interpolate the data.
latThe specific latitude at which to interpolate the data.
methodInterpolation method: 1 for linear interpolation, otherwise nearest neighbor interpolation is used.
varPointer to the variable where the interpolated value will be stored.
sigmaPointer to the variable where the standard deviation of the data points will be stored.
Precondition
array0 and array1 must be 2D arrays of size EX by EY.
lons must have at least nlon elements and lats must have at least nlat elements.
Postcondition
var will contain the interpolated value.
sigma will contain the standard deviation of the data points used in the interpolation.
Note
The function adjusts the longitude to ensure it is within the range defined by lons.
This function uses the auxiliary functions locate_reg, LIN, and NN for locating indices and performing interpolation.
Warning
Ensure that EX and EY are defined appropriately to match the dimensions of array0 and array1.
Author
Lars Hoffmann

Definition at line 3505 of file mptrac.c.

3519 {
3520
3521 double mean = 0;
3522
3523 int n = 0;
3524
3525 /* Check longitude and latitude... */
3526 double lon2, lat2;
3527 intpol_check_lon_lat(lons, nlon, lats, nlat, lon, lat, &lon2, &lat2);
3528
3529 /* Get indices... */
3530 const int ix = locate_reg(lons, (int) nlon, lon2);
3531 const int iy = locate_irr(lats, (int) nlat, lat2);
3532
3533 /* Calculate mean of finite neighboring values... */
3534 for (int dx = 0; dx < 2; dx++)
3535 for (int dy = 0; dy < 2; dy++) {
3536 if (isfinite(array0[ix + dx][iy + dy])) {
3537 mean += array0[ix + dx][iy + dy];
3538 n++;
3539 }
3540 if (isfinite(array1[ix + dx][iy + dy])) {
3541 mean += array1[ix + dx][iy + dy];
3542 n++;
3543 }
3544 }
3545
3546 /* Calculate population standard deviation in double precision... */
3547 *sigma = 0;
3548 if (n > 0) {
3549 mean /= n;
3550 for (int dx = 0; dx < 2; dx++)
3551 for (int dy = 0; dy < 2; dy++) {
3552 if (isfinite(array0[ix + dx][iy + dy])) {
3553 const double diff = (double) array0[ix + dx][iy + dy] - mean;
3554 *sigma += diff * diff;
3555 }
3556 if (isfinite(array1[ix + dx][iy + dy])) {
3557 const double diff = (double) array1[ix + dx][iy + dy] - mean;
3558 *sigma += diff * diff;
3559 }
3560 }
3561 *sigma = sqrt(*sigma / n);
3562 }
3563
3564 /* Linear interpolation... */
3565 if (method == 1 && isfinite(array0[ix][iy])
3566 && isfinite(array0[ix][iy + 1])
3567 && isfinite(array0[ix + 1][iy])
3568 && isfinite(array0[ix + 1][iy + 1])
3569 && isfinite(array1[ix][iy])
3570 && isfinite(array1[ix][iy + 1])
3571 && isfinite(array1[ix + 1][iy])
3572 && isfinite(array1[ix + 1][iy + 1])) {
3573
3574 const double aux00 = LIN(lons[ix], array0[ix][iy],
3575 lons[ix + 1], array0[ix + 1][iy], lon2);
3576 const double aux01 = LIN(lons[ix], array0[ix][iy + 1],
3577 lons[ix + 1], array0[ix + 1][iy + 1], lon2);
3578 const double aux0 = LIN(lats[iy], aux00, lats[iy + 1], aux01, lat2);
3579
3580 const double aux10 = LIN(lons[ix], array1[ix][iy],
3581 lons[ix + 1], array1[ix + 1][iy], lon2);
3582 const double aux11 = LIN(lons[ix], array1[ix][iy + 1],
3583 lons[ix + 1], array1[ix + 1][iy + 1], lon2);
3584 const double aux1 = LIN(lats[iy], aux10, lats[iy + 1], aux11, lat2);
3585
3586 *var = LIN(time0, aux0, time1, aux1, time);
3587 }
3588
3589 /* Nearest neighbor interpolation... */
3590 else {
3591 const double aux00 = NN(lons[ix], array0[ix][iy],
3592 lons[ix + 1], array0[ix + 1][iy], lon2);
3593 const double aux01 = NN(lons[ix], array0[ix][iy + 1],
3594 lons[ix + 1], array0[ix + 1][iy + 1], lon2);
3595 const double aux0 = NN(lats[iy], aux00, lats[iy + 1], aux01, lat2);
3596
3597 const double aux10 = NN(lons[ix], array1[ix][iy],
3598 lons[ix + 1], array1[ix + 1][iy], lon2);
3599 const double aux11 = NN(lons[ix], array1[ix][iy + 1],
3600 lons[ix + 1], array1[ix + 1][iy + 1], lon2);
3601 const double aux1 = NN(lats[iy], aux10, lats[iy + 1], aux11, lat2);
3602
3603 *var = NN(time0, aux0, time1, aux1, time);
3604 }
3605}
#define NN(x0, y0, x1, y1, x)
Perform nearest-neighbor interpolation.
Definition mptrac.h:1786
Here is the call graph for this function:

◆ jsec2time()

void jsec2time ( const double jsec,
int * year,
int * mon,
int * day,
int * hour,
int * min,
int * sec,
double * remain )

Converts Julian seconds to calendar date and time components.

This function converts Julian seconds to calendar date and time components, including year, month, day, hour, minute, and second. It also calculates the fractional part of the seconds.

Parameters
jsecJulian seconds to convert.
yearPointer to store the year.
monPointer to store the month.
dayPointer to store the day.
hourPointer to store the hour.
minPointer to store the minute.
secPointer to store the second.
remainPointer to store the fractional part of seconds.

The function initializes a time structure t0 with a fixed starting date and time. It then converts the Julian seconds to a time_t type by adding the seconds to the epoch time. Next, it converts the time_t value to a UTC time structure t1. Finally, it extracts the year, month, day, hour, minute, and second components from t1 and calculates the fractional part of seconds, which is stored in remain.

Author
Lars Hoffmann

Definition at line 3609 of file mptrac.c.

3617 {
3618
3619 struct tm t0, *t1;
3620
3621 t0.tm_year = 100;
3622 t0.tm_mon = 0;
3623 t0.tm_mday = 1;
3624 t0.tm_hour = 0;
3625 t0.tm_min = 0;
3626 t0.tm_sec = 0;
3627
3628 const time_t jsec0 = (time_t) jsec + timegm(&t0);
3629 t1 = gmtime(&jsec0);
3630
3631 *year = t1->tm_year + 1900;
3632 *mon = t1->tm_mon + 1;
3633 *day = t1->tm_mday;
3634 *hour = t1->tm_hour;
3635 *min = t1->tm_min;
3636 *sec = t1->tm_sec;
3637 *remain = jsec - floor(jsec);
3638}

◆ kernel_weight()

double kernel_weight ( const double kz[EP],
const double kw[EP],
const int nk,
const double p )

Calculates the kernel weight based on altitude and given kernel data.

This function calculates the kernel weight based on altitude and given kernel data. It takes arrays of altitudes (kz) and corresponding weights (kw), the number of data points (nk), and the current altitude (p) as input.

Parameters
kzArray of altitudes.
kwArray of corresponding weights.
nkNumber of data points.
pCurrent altitude.
Returns
The calculated kernel weight.

If the number of data points is less than 2 (nk < 2), the function returns a default weight of 1.0.

The function first computes the altitude z based on the current altitude p. Then it checks whether z is outside the range of altitudes in the kernel data. If so, it returns the corresponding weight at the nearest altitude boundary. Otherwise, it interpolates linearly between the two closest altitudes in the kernel data to determine the weight at altitude z.

Author
Lars Hoffmann

Definition at line 3642 of file mptrac.c.

3646 {
3647
3648 /* Check number of data points... */
3649 if (nk < 2)
3650 return 1.0;
3651
3652 /* Get altitude... */
3653 const double z = Z(p);
3654
3655 /* Get weighting factor... */
3656 if (z < kz[0])
3657 return kw[0];
3658 else if (z > kz[nk - 1])
3659 return kw[nk - 1];
3660 else {
3661 const int idx = locate_irr(kz, nk, z);
3662 return LIN(kz[idx], kw[idx], kz[idx + 1], kw[idx + 1], z);
3663 }
3664}
Here is the call graph for this function:

◆ lapse_rate()

double lapse_rate ( const double t,
const double h2o )

Calculates the moist adiabatic lapse rate in Kelvin per kilometer.

This function calculates the moist adiabatic lapse rate in Kelvin per kilometer from the given temperature (t) in Kelvin and water vapor volume mixing ratio (h2o).

Parameters
tTemperature in Kelvin.
h2oWater vapor volume mixing ratio.
Returns
The moist adiabatic lapse rate in Kelvin per kilometer.

The moist adiabatic lapse rate is calculated using the formula:

\[ \Gamma = \frac{{1000 \times g \times \left(a + L_v \times r \times T\right)}} {{C_{pd} \times a + L_v^2 \times r \times \epsilon}} \]

where:

  • \( \Gamma \) is the lapse rate in Kelvin per kilometer.
  • \( g \) is the acceleration due to gravity (constant).
  • \( a = R_a \times T^2 \) is a term based on the gas constant for dry air and temperature squared.
  • \( R_a \) is the gas constant for dry air.
  • \( T \) is the temperature in Kelvin.
  • \( L_v \) is the latent heat of vaporization.
  • \( r = \frac{{S_h(h_2o)}}{{1 - S_h(h_2o)}} \) is a term based on the water vapor mixing ratio.
  • \( S_h(h_2o) \) is the saturation vapor pressure relative to the pressure at saturation.
  • \( C_{pd} \) is the specific heat of dry air at constant pressure.
  • \( \epsilon \) is the ratio of the gas constants for dry air and water vapor.

The constants used in the calculation are defined externally:

  • \( g \): Acceleration due to gravity (constant).
  • \( R_a \): Gas constant for dry air.
  • \( L_v \): Latent heat of vaporization.
  • \( C_{pd} \): Specific heat of dry air at constant pressure.
  • \( \epsilon \): Ratio of the gas constants for dry air and water vapor.
See also
Wikipedia - Lapse rate
Author
Lars Hoffmann

Definition at line 3668 of file mptrac.c.

3670 {
3671
3672 /*
3673 Calculate moist adiabatic lapse rate [K/km] from temperature [K]
3674 and water vapor volume mixing ratio [1].
3675
3676 Reference: https://en.wikipedia.org/wiki/Lapse_rate
3677 */
3678
3679 const double a = RA * SQR(t), r = SH(h2o) / (1. - SH(h2o));
3680
3681 return 1e3 * G0 * (a + LV * r * t) / (CPD * a + SQR(LV) * r * EPS);
3682}
#define SH(h2o)
Compute specific humidity from water vapor volume mixing ratio.
Definition mptrac.h:2084
#define LV
Latent heat of vaporization of water [J/kg].
Definition mptrac.h:275
#define CPD
Specific heat of dry air at constant pressure [J/(kg K)].
Definition mptrac.h:255

◆ level_definitions()

void level_definitions ( ctl_t * ctl)

Defines pressure levels for meteorological data.

This function defines pressure levels for meteorological data based on the given control structure (ctl). Pressure levels are defined differently based on the value of met_press_level_def in ctl.

Parameters
ctlControl structure containing information about pressure level definitions.

The function determines the number of pressure levels (met_np) and the corresponding pressure values (met_p) based on the value of met_press_level_def in the control structure ctl. It initializes the met_np and met_p fields accordingly.

Note
Valid values for met_press_level_def are:
  • 3: Define 147 pressure levels.
  • 4: Define 101 pressure levels.
  • 5: Define 62 pressure levels.
  • 6: Define 137 pressure levels.
  • 7: Define 59 pressure levels. Values 0, 1, and 2 are disabled and any other value will result in an error message.
Author
Jan Clemens

Definition at line 3686 of file mptrac.c.

3687 {
3688
3689 if (0 == ctl->met_press_level_def) {
3690
3691 ERRMSG
3692 ("MET_PRESS_LEVEL_DEF=0 is disabled. Use 3 for the extended L137 set.");
3693
3694 } else if (1 == ctl->met_press_level_def) {
3695
3696 ERRMSG
3697 ("MET_PRESS_LEVEL_DEF=1 is disabled. Use 4 for the extended L91 set.");
3698
3699 } else if (2 == ctl->met_press_level_def) {
3700
3701 ERRMSG
3702 ("MET_PRESS_LEVEL_DEF=2 is disabled. Use 5 for the extended L60 set.");
3703
3704 } else if (3 == ctl->met_press_level_def) {
3705
3706 ctl->met_np = 147;
3707
3708 const double press[147] = {
3709 0.0200, 0.0310, 0.0467, 0.0683, 0.0975, 0.1361, 0.1861, 0.2499,
3710 0.3299, 0.4288, 0.5496, 0.6952, 0.8690, 1.0742, 1.3143, 1.5928, 1.9134,
3711 2.2797, 2.6954, 3.1642, 3.6898, 4.2759, 4.9262, 5.6441, 6.4334, 7.2974,
3712 8.2397, 9.2634, 10.3720, 11.5685, 12.8561, 14.2377, 15.7162, 17.2945,
3713 18.9752, 20.7610, 22.6543, 24.6577, 26.7735, 29.0039, 31.3512, 33.8174,
3714 36.4047, 39.1149, 41.9493, 44.9082, 47.9915, 51.1990, 54.5299, 57.9834,
3715 61.5607, 65.2695, 69.1187, 73.1187, 77.2810, 81.6182, 86.1450, 90.8774,
3716 95.8280, 101.0047, 106.4153, 112.0681, 117.9714, 124.1337, 130.5637,
3717 137.2703, 144.2624, 151.5493, 159.1403, 167.0450, 175.2731, 183.8344,
3718 192.7389, 201.9969, 211.6186, 221.6146, 231.9954, 242.7719, 253.9549,
3719 265.5556, 277.5852, 290.0548, 302.9762, 316.3607, 330.2202, 344.5663,
3720 359.4111, 374.7666, 390.6450, 407.0583, 424.0190, 441.5395, 459.6321,
3721 478.3096, 497.5845, 517.4198, 537.7195, 558.3430, 579.1926, 600.1668,
3722 621.1624, 642.0764, 662.8084, 683.2620, 703.3467, 722.9795, 742.0855,
3723 760.5996, 778.4661, 795.6396, 812.0847, 827.7756, 842.6959, 856.8376,
3724 870.2004, 882.7910, 894.6222, 905.7116, 916.0815, 925.7571, 934.7666,
3725 943.1399, 950.9082, 958.1037, 964.7584, 970.9046, 976.5737, 981.7968,
3726 986.6036, 991.0230, 995.0824, 998.8081, 1002.2250, 1005.3562, 1008.2239,
3727 1010.8487, 1013.25, 1016.37, 1019.49, 1022.61, 1025.73, 1028.85,
3728 1031.97,
3729 1035.09, 1038.21, 1041.33, 1044.45
3730 };
3731
3732 for (int ip = 0; ip < ctl->met_np; ip++)
3733 ctl->met_p[ctl->met_np - ip - 1] = press[ip];
3734
3735 } else if (4 == ctl->met_press_level_def) {
3736
3737 ctl->met_np = 101;
3738
3739 const double press[101] = {
3740 0.0200, 0.0398, 0.0739, 0.1291, 0.2141, 0.3395, 0.5175, 0.7617,
3741 1.0872, 1.5099, 2.0464, 2.7136, 3.5282, 4.5069, 5.6652, 7.0181,
3742 8.5795, 10.3617, 12.3759, 14.6316, 17.1371, 19.8987, 22.9216, 26.2090,
3743 29.7630, 33.5843, 37.6720, 42.0242, 46.6378, 51.5086, 56.6316, 61.9984,
3744 67.5973, 73.4150, 79.4434, 85.7016, 92.2162, 99.0182, 106.1445,
3745 113.6382,
3746 121.5502, 129.9403, 138.8558, 148.3260, 158.3816, 169.0545, 180.3786,
3747 192.3889, 205.1222, 218.6172, 232.9140, 248.0547, 264.0833, 281.0456,
3748 298.9895, 317.9651, 338.0245, 359.2221, 381.6144, 405.2606, 430.2069,
3749 456.4813, 483.8505, 512.0662, 540.8577, 569.9401, 599.0310, 627.9668,
3750 656.6129, 684.8491, 712.5573, 739.5739, 765.7697, 791.0376, 815.2774,
3751 838.3507, 860.1516, 880.6080, 899.6602, 917.2205, 933.2247, 947.6584,
3752 960.5245, 971.8169, 981.5301, 989.7322, 996.8732, 1002.8013,
3753 1007.4431, 1010.8487, 1013.25, 1016.37, 1019.49, 1022.61, 1025.73,
3754 1028.85, 1031.97,
3755 1035.09, 1038.21, 1041.33, 1044.45
3756 };
3757
3758 for (int ip = 0; ip < ctl->met_np; ip++)
3759 ctl->met_p[ctl->met_np - ip - 1] = press[ip];
3760
3761 } else if (5 == ctl->met_press_level_def) {
3762
3763 ctl->met_np = 62;
3764
3765 const double press[62] = {
3766 0.01, 0.1361, 0.2499, 0.4288, 0.6952, 1.0742,
3767 2.2797, 3.1642, 4.2759, 7.2974, 9.2634, 11.5685, 14.2377, 20.761,
3768 24.6577, 33.8174, 39.1149, 51.199, 57.9834, 73.1187, 81.6182,
3769 90.8774, 101.005, 112.068, 124.134, 137.27, 151.549, 167.045, 183.834,
3770 201.997, 221.615, 242.772, 265.556, 290.055, 316.361, 344.566, 374.767,
3771 407.058, 441.539, 478.31, 517.42, 558.343, 600.167, 683.262, 722.979,
3772 760.6, 795.64, 827.776, 856.838, 882.791, 905.712, 925.757, 943.14,
3773 958.104, 972.495, 986.886, 1001.28, 1015.67, 1030.06, 1034.86, 1039.65,
3774 1044.45
3775 };
3776
3777 for (int ip = 0; ip < ctl->met_np; ip++)
3778 ctl->met_p[ctl->met_np - ip - 1] = press[ip];
3779
3780 } else if (6 == ctl->met_press_level_def) {
3781
3782 ctl->met_np = 137;
3783
3784 const double press[137] = {
3785 0.01, 0.02, 0.031, 0.0467, 0.0683, 0.0975, 0.1361, 0.1861,
3786 0.2499, 0.3299, 0.4288, 0.5496, 0.6952, 0.869, 1.0742,
3787 1.3143, 1.5928, 1.9134, 2.2797, 2.6954, 3.1642, 3.6898,
3788 4.2759, 4.9262, 5.6441, 6.4334, 7.2974, 8.2397, 9.2634,
3789 10.372, 11.5685, 12.8561, 14.2377, 15.7162, 17.2945, 18.9752,
3790 20.761, 22.6543, 24.6577, 26.7735, 29.0039, 31.3512, 33.8174,
3791 36.4047, 39.1149, 41.9493, 44.9082, 47.9915, 51.199, 54.5299,
3792 57.9834, 61.5607, 65.2695, 69.1187, 73.1187, 77.281, 81.6182,
3793 86.145, 90.8774, 95.828, 101.005, 106.415, 112.068, 117.971,
3794 124.134, 130.564, 137.27, 144.262, 151.549, 159.14, 167.045,
3795 175.273, 183.834, 192.739, 201.997, 211.619, 221.615, 231.995,
3796 242.772, 253.955, 265.556, 277.585, 290.055, 302.976, 316.361,
3797 330.22, 344.566, 359.411, 374.767, 390.645, 407.058, 424.019,
3798 441.539, 459.632, 478.31, 497.584, 517.42, 537.72, 558.343,
3799 579.193, 600.167, 621.162, 642.076, 662.808, 683.262, 703.347,
3800 722.979, 742.086, 760.6, 778.466, 795.64, 812.085, 827.776,
3801 842.696, 856.838, 870.2, 882.791, 894.622, 905.712, 916.081,
3802 925.757, 934.767, 943.14, 950.908, 958.104, 965.299, 972.495,
3803 979.69, 986.886, 994.081, 1001.28, 1008.47, 1015.67, 1022.86,
3804 1030.06, 1037.25, 1044.45
3805 };
3806
3807 for (int ip = 0; ip < ctl->met_np; ip++)
3808 ctl->met_p[ctl->met_np - ip - 1] = press[ip];
3809
3810 } else if (7 == ctl->met_press_level_def) {
3811
3812 ctl->met_np = 59;
3813
3814 const double press[59] = {
3815 0.1, 0.2, 0.3843, 0.6365, 0.9564, 1.3448, 1.8058, 2.3478,
3816 2.985, 3.7397, 4.6462, 5.7565, 7.1322, 8.8366, 10.9483,
3817 13.5647, 16.8064, 20.8227, 25.7989, 31.9642, 39.6029, 49.0671,
3818 60.1802, 73.0663, 87.7274, 104.229, 122.614, 142.902, 165.089,
3819 189.147, 215.025, 242.652, 272.059, 303.217, 336.044, 370.407,
3820 406.133, 443.009, 480.791, 519.209, 557.973, 596.777, 635.306,
3821 673.24, 710.263, 746.063, 780.346, 812.83, 843.263, 871.42,
3822 897.112, 920.189, 940.551, 958.148, 975.744, 993.341, 1010.94,
3823 1028.53, 1046.13
3824 };
3825
3826 for (int ip = 0; ip < ctl->met_np; ip++)
3827 ctl->met_p[ctl->met_np - ip - 1] = press[ip];
3828
3829 } else {
3830 ERRMSG("Use values between 3 and 7.");
3831 }
3832
3833 if (ctl->met_np > EP)
3834 ERRMSG("Recompile with larger EP to use this pressure level definition!");
3835}
int met_press_level_def
Use predefined pressure levels or not.
Definition mptrac.h:3027
int met_np
Number of target pressure levels.
Definition mptrac.h:3021
double met_p[EP]
Target pressure levels [hPa].
Definition mptrac.h:3024

◆ locate_irr()

int locate_irr ( const double * xx,
const int n,
const double x )

Locate the index of the interval containing a given value in a sorted array.

This function locates the index of the interval containing a given value in a sorted array. It uses a binary search algorithm to efficiently find the interval.

Parameters
xxPointer to the sorted array.
nSize of the array.
xValue to be located.
Returns
Index of the interval containing the value x.

The function assumes that the array xx is sorted in ascending order. It returns the index of the interval where the value x is located. If the value x is outside the range of the array, the function returns the index of the closest interval.

Author
Lars Hoffmann

Definition at line 3839 of file mptrac.c.

3842 {
3843
3844 int ilo = 0;
3845 int ihi = n - 1;
3846 int i = (ihi + ilo) >> 1;
3847
3848 if (xx[i] < xx[i + 1])
3849 while (ihi > ilo + 1) {
3850 i = (ihi + ilo) >> 1;
3851 if (xx[i] > x)
3852 ihi = i;
3853 else
3854 ilo = i;
3855 } else
3856 while (ihi > ilo + 1) {
3857 i = (ihi + ilo) >> 1;
3858 if (xx[i] <= x)
3859 ihi = i;
3860 else
3861 ilo = i;
3862 }
3863
3864 return ilo;
3865}

◆ locate_irr_float()

int locate_irr_float ( const float * xx,
const int n,
const double x,
const int ig )

Locate the index of the interval containing a given value in an irregularly spaced array.

This function performs a binary search to locate the interval in the array xx such that xx[ig] <= x < xx[ig + 1]. If the value x lies within the interval specified by the initial guess index ig, the function returns ig. Otherwise, it searches the array to find the correct interval.

Parameters
xxPointer to the array of floats representing the irregularly spaced intervals. The array must be of size n.
nThe number of elements in the array xx.
xThe value to locate within the intervals of the array xx.
igThe initial guess index. If the interval [xx[ig], xx[ig+1]) contains x, the function returns ig directly.
Returns
The index i such that xx[i] <= x < xx[i + 1]. If x is out of bounds, it returns the index of the closest interval.
Note
The function assumes that the array xx contains at least two elements.
The function can handle both increasing and decreasing sequences in the array xx.
Warning
The behavior is undefined if the array xx is not sorted in either increasing or decreasing order, or if it contains less than two elements.
Author
Lars Hoffmann

Definition at line 3869 of file mptrac.c.

3873 {
3874
3875 int ilo = 0;
3876 int ihi = n - 1;
3877 int i = (ihi + ilo) >> 1;
3878
3879 if ((xx[ig] <= x && x < xx[ig + 1]) || (xx[ig] >= x && x > xx[ig + 1]))
3880 return ig;
3881
3882 if (xx[i] < xx[i + 1])
3883 while (ihi > ilo + 1) {
3884 i = (ihi + ilo) >> 1;
3885 if (xx[i] > x)
3886 ihi = i;
3887 else
3888 ilo = i;
3889 } else
3890 while (ihi > ilo + 1) {
3891 i = (ihi + ilo) >> 1;
3892 if (xx[i] <= x)
3893 ihi = i;
3894 else
3895 ilo = i;
3896 }
3897
3898 return ilo;
3899}

◆ locate_reg()

int locate_reg ( const double * xx,
const int n,
const double x )

Locate the index of the interval containing a given value in a regular grid.

This function locates the index of the interval containing a given value in a regular grid. It calculates the index based on the spacing between grid points and the value to be located.

Parameters
xxPointer to the array representing the regular grid.
nSize of the grid (number of grid points).
xValue to be located.
Returns
Index of the interval containing the value x.

The function assumes that the array xx represents a regular grid with equally spaced points. It calculates the index of the interval where the value x is located based on the spacing between grid points. If the value x is outside the range of the grid, the function returns the index of the closest interval.

Author
Lars Hoffmann

Definition at line 3903 of file mptrac.c.

3906 {
3907
3908 /* Calculate index... */
3909 const int i = (int) ((x - xx[0]) / (xx[1] - xx[0]));
3910
3911 /* Check range... */
3912 if (i < 0)
3913 return 0;
3914 else if (i > n - 2)
3915 return n - 2;
3916 else
3917 return i;
3918}

◆ locate_vert()

void locate_vert ( float profiles[EX][EY][EP],
const int np,
const int lon_ap_ind,
const int lat_ap_ind,
const double alt_ap,
int * ind )

Locate the four vertical indizes of a box for a given height value.

This function locates the vertical indices corresponding to a given height in a 3D irregular grid. It calculates the indices based on the specified longitude and latitude indices of the grid.

Parameters
profiles3D array representing the irregular grid.
npSize of the profile (number of data points).
lon_ap_indIndex of the longitude.
lat_ap_indIndex of the latitude.
alt_apHeight value.
indPointer to an array to store the resulting indices.

The function calculates the indices corresponding to the specified height in the 3D irregular grid. It stores the resulting indices in the array pointed to by ind. The indices are calculated based on the specified longitude and latitude indices of the grid.

Author
Lars Hoffmann

Definition at line 3922 of file mptrac.c.

3928 {
3929
3930 ind[0] = locate_irr_float(profiles[lon_ap_ind][lat_ap_ind],
3931 np, height_ap, 0);
3932 ind[1] = locate_irr_float(profiles[lon_ap_ind + 1][lat_ap_ind],
3933 np, height_ap, ind[0]);
3934 ind[2] = locate_irr_float(profiles[lon_ap_ind][lat_ap_ind + 1],
3935 np, height_ap, ind[1]);
3936 ind[3] = locate_irr_float(profiles[lon_ap_ind + 1][lat_ap_ind + 1],
3937 np, height_ap, ind[2]);
3938}
int locate_irr_float(const float *xx, const int n, const double x, const int ig)
Locate the index of the interval containing a given value in an irregularly spaced array.
Definition mptrac.c:3869
Here is the call graph for this function:

◆ module_advect()

void module_advect ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Advances particle positions using different advection schemes.

This function updates particle positions using omega, zeta tendency, or eta tendency as the vertical velocity, according to advect_vert_coord. The advection is performed over a number of integration nodes, using meteorological data interpolated in time and space.

Parameters
[in]ctlPointer to the control structure containing configuration settings.
[in]cachePointer to the cache structure storing precomputed time step values.
[in]met0Pointer to the meteorological data structure at the initial time.
[in]met1Pointer to the meteorological data structure at the next time step.
[in,out]atmPointer to the atmospheric data structure containing particle states.
  • Modes 0 and 2 use omega on pressure and native model levels, respectively.
  • Modes 1 and 3 integrate zeta and eta tendencies on native model levels.
  • The function interpolates meteorological data either on pressure levels or model levels.
  • The advection scheme supports Euler and explicit midpoint integration.
  • The function updates longitude and latitude; modes 0 and 2 update pressure directly, while modes 1 and 3 convert the updated coordinate to pressure.
Author
Lars Hoffmann
Jan Clemens

Definition at line 3942 of file mptrac.c.

3947 {
3948
3949 /* Set timer... */
3950 SELECT_TIMER("MODULE_ADVECT", "PHYSICS");
3951
3952 /* Use omega vertical velocity... */
3953 if (ctl->advect_vert_coord == 0 || ctl->advect_vert_coord == 2) {
3954
3955 /* Loop over particles... */
3956 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
3957
3958 /* Init... */
3960 double dts, u[2], um = 0, v[2], vm = 0, w[2], wm = 0,
3961 x[3] = { 0, 0, 0 };
3962
3963 /* Loop over integration nodes... */
3964 for (int i = 0; i < ctl->advect; i++) {
3965
3966 /* Set position... */
3967 if (i == 0) {
3968 dts = 0.0;
3969 x[0] = atm->lon[ip];
3970 x[1] = atm->lat[ip];
3971 x[2] = atm->p[ip];
3972 } else {
3973 dts = 0.5 * cache->dt[ip];
3974 x[0] = atm->lon[ip] + DX2COORD(met0, dts * u[i - 1], atm->lat[ip]);
3975 x[1] = atm->lat[ip] + DY2COORD(met0, dts * v[i - 1]);
3976 x[2] = atm->p[ip] + dts * w[i - 1];
3977 }
3978 const double tm = atm->time[ip] + dts;
3979
3980 /* Interpolate meteo data on pressure levels... */
3981 if (ctl->advect_vert_coord == 0) {
3982 intpol_met_time_3d(met0, met0->u, met1, met1->u,
3983 tm, x[2], x[0], x[1], &u[i], ci, cw, 1);
3984 intpol_met_time_3d(met0, met0->v, met1, met1->v,
3985 tm, x[2], x[0], x[1], &v[i], ci, cw, 0);
3986 intpol_met_time_3d(met0, met0->w, met1, met1->w,
3987 tm, x[2], x[0], x[1], &w[i], ci, cw, 0);
3988 }
3989
3990 /* Interpolate meteo data on model levels... */
3991 else {
3992 intpol_met_4d_zeta(met0, met0->pl, met0->ul,
3993 met1, met1->pl, met1->ul,
3994 tm, x[2], x[0], x[1], &u[i], ci, cw, 1);
3995 intpol_met_4d_zeta(met0, met0->pl, met0->vl,
3996 met1, met1->pl, met1->vl,
3997 tm, x[2], x[0], x[1], &v[i], ci, cw, 0);
3998 intpol_met_4d_zeta(met0, met0->pl, met0->wl,
3999 met1, met1->pl, met1->wl,
4000 tm, x[2], x[0], x[1], &w[i], ci, cw, 0);
4001 }
4002
4003 /* Get mean wind... */
4004 const double k = (ctl->advect == 2 && i == 0 ? 0.0 : 1.0);
4005 um += k * u[i];
4006 vm += k * v[i];
4007 wm += k * w[i];
4008 }
4009
4010 /* Set new position... */
4011 atm->time[ip] += cache->dt[ip];
4012 atm->lon[ip] += DX2COORD(met0, cache->dt[ip] * um,
4013 (ctl->advect == 2 ? x[1] : atm->lat[ip]));
4014 atm->lat[ip] += DY2COORD(met0, cache->dt[ip] * vm);
4015 atm->p[ip] += cache->dt[ip] * wm;
4016
4017 }
4018 }
4019
4020 /* Use zeta or eta vertical velocity... */
4021 else if (ctl->advect_vert_coord == 1 || ctl->advect_vert_coord == 3) {
4022
4023 /* Select quantity index depending on coordinate... */
4024 const int qnt = (ctl->advect_vert_coord == 1
4025 ? ctl->qnt_zeta : ctl->qnt_eta);
4026
4027 /* Loop over particles... */
4028 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
4029
4030 /* Convert pressure to vertical coordinate (zeta or eta)... */
4032 intpol_met_4d_zeta(met0, met0->pl, met0->zetal,
4033 met1, met1->pl, met1->zetal,
4034 atm->time[ip], atm->p[ip],
4035 atm->lon[ip], atm->lat[ip],
4036 &atm->q[qnt][ip], ci, cw, 1);
4037
4038 /* Init... */
4039 double dts, u[2], um = 0, v[2], vm = 0, wdot[2],
4040 wdotm = 0, x[3] = { 0, 0, 0 };
4041
4042 /* Loop over integration nodes... */
4043 for (int i = 0; i < ctl->advect; i++) {
4044
4045 /* Set position... */
4046 if (i == 0) {
4047 dts = 0.0;
4048 x[0] = atm->lon[ip];
4049 x[1] = atm->lat[ip];
4050 x[2] = atm->q[qnt][ip];
4051 } else {
4052 dts = 0.5 * cache->dt[ip];
4053 x[0] = atm->lon[ip] + DX2COORD(met0, dts * u[i - 1], atm->lat[ip]);
4054 x[1] = atm->lat[ip] + DY2COORD(met0, dts * v[i - 1]);
4055 x[2] = atm->q[qnt][ip] + dts * wdot[i - 1];
4056 }
4057
4058 const double tm = atm->time[ip] + dts;
4059
4060 /* Interpolate meteo data... */
4061 intpol_met_4d_zeta(met0, met0->zetal, met0->ul,
4062 met1, met1->zetal, met1->ul,
4063 tm, x[2], x[0], x[1], &u[i], ci, cw, 1);
4064 intpol_met_4d_zeta(met0, met0->zetal, met0->vl,
4065 met1, met1->zetal, met1->vl,
4066 tm, x[2], x[0], x[1], &v[i], ci, cw, 0);
4067 intpol_met_4d_zeta(met0, met0->zetal, met0->zeta_dotl,
4068 met1, met1->zetal, met1->zeta_dotl,
4069 tm, x[2], x[0], x[1], &wdot[i], ci, cw, 0);
4070
4071 /* Select Euler or midpoint wind... */
4072 const double k = (ctl->advect == 2 && i == 0 ? 0.0 : 1.0);
4073
4074 um += k * u[i];
4075 vm += k * v[i];
4076 wdotm += k * wdot[i];
4077 }
4078
4079 /* Update particle position... */
4080 atm->time[ip] += cache->dt[ip];
4081 atm->lon[ip] += DX2COORD(met0, cache->dt[ip] * um,
4082 (ctl->advect == 2 ? x[1] : atm->lat[ip]));
4083 atm->lat[ip] += DY2COORD(met0, cache->dt[ip] * vm);
4084 atm->q[qnt][ip] += cache->dt[ip] * wdotm;
4085
4086 /* Convert vertical coordinate (zeta or eta) back to pressure... */
4087 intpol_met_4d_zeta(met0, met0->zetal, met0->pl,
4088 met1, met1->zetal, met1->pl,
4089 atm->time[ip],
4090 atm->q[qnt][ip], atm->lon[ip], atm->lat[ip],
4091 &atm->p[ip], ci, cw, 1);
4092 }
4093 }
4094}
void intpol_met_time_3d(const met_t *met0, float array0[EX][EY][EP], const met_t *met1, float array1[EX][EY][EP], const double ts, const double p, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
Interpolates meteorological data in 3D space and time.
Definition mptrac.c:3443
void intpol_met_4d_zeta(const met_t *met0, float heights0[EX][EY][EP], float array0[EX][EY][EP], const met_t *met1, float heights1[EX][EY][EP], float array1[EX][EY][EP], const double ts, const double height, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
Interpolates meteorological variables to a given position and time.
Definition mptrac.c:3138
#define PARTICLE_LOOP(ip0, ip1, check_dt,...)
Loop over particle indices with OpenACC acceleration.
Definition mptrac.h:1813
#define DX2COORD(met, dx, lat)
Convert a distance in meters to a coordinate value based on grid type.
Definition mptrac.h:968
#define DY2COORD(met, dy)
Convert a distance to coordinate value based on grid type.
Definition mptrac.h:991
int qnt_eta
Quantity array index for eta vertical coordinate.
Definition mptrac.h:2783
int advect
Advection scheme (1=Euler, 2=midpoint).
Definition mptrac.h:3096
int qnt_zeta
Quantity array index for zeta vertical coordinate.
Definition mptrac.h:2774
int advect_vert_coord
Vertical velocity of air parcels (0=omega_on_plev, 1=zetadot_on_mlev, 2=omega_on_mlev,...
Definition mptrac.h:3100
float zeta_dotl[EX][EY][EP]
Vertical velocity on model levels [K/s].
Definition mptrac.h:4120
float w[EX][EY][EP]
Vertical velocity [hPa/s].
Definition mptrac.h:4078
float wl[EX][EY][EP]
Vertical velocity on model levels [hPa/s].
Definition mptrac.h:4114
float vl[EX][EY][EP]
Meridional wind on model levels [m/s].
Definition mptrac.h:4111
float u[EX][EY][EP]
Zonal wind [m/s].
Definition mptrac.h:4072
float ul[EX][EY][EP]
Zonal wind on model levels [m/s].
Definition mptrac.h:4108
float v[EX][EY][EP]
Meridional wind [m/s].
Definition mptrac.h:4075
float pl[EX][EY][EP]
Pressure on model levels [hPa].
Definition mptrac.h:4105
float zetal[EX][EY][EP]
Zeta on model levels [K].
Definition mptrac.h:4117
Here is the call graph for this function:

◆ module_advect_init()

void module_advect_init ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Initializes the advection module by setting up pressure fields.

This function initializes the advection module, setting up the air parcel pressure to be consistent with the given zeta vertical coordinate. It utilizes meteorological data from two time steps and interpolates the pressure values accordingly.

Parameters
ctlPointer to the control structure containing configuration flags.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the initial meteorological data structure.
met1Pointer to the final meteorological data structure.
atmPointer to the air parcel data structure.

The function performs the following operations:

  • Sets up a timer labeled "MODULE_ADVECT_INIT" within the "PHYSICS" category.
  • If ctl->advect_vert_coord == 1, it initializes the pressure fields to be consistent with the zeta coordinate using 4D interpolation.
  • Initial particle times must be identical; mptrac_init checks this once.
Author
Jan Clemens

Definition at line 4098 of file mptrac.c.

4103 {
4104
4105 /* Check parameters... */
4106 if (ctl->advect_vert_coord != 1)
4107 return;
4108
4109 /* Set timer... */
4110 SELECT_TIMER("MODULE_ADVECT_INIT", "PHYSICS");
4111
4112 /* Loop over particles... */
4113 PARTICLE_LOOP(0, atm->np, 0, "acc data present(ctl,met0,met1,atm)") {
4114
4115 /* Initialize pressure consistent with zeta... */
4117 intpol_met_4d_zeta(met0, met0->zetal, met0->pl, met1, met1->zetal,
4118 met1->pl, atm->time[ip], atm->q[ctl->qnt_zeta][ip],
4119 atm->lon[ip], atm->lat[ip], &atm->p[ip], ci, cw, 1);
4120 }
4121}
Here is the call graph for this function:

◆ module_bound_cond()

void module_bound_cond ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Apply boundary conditions to particles based on meteorological and climatological data.

This function applies boundary conditions to particles based on specified criteria, including latitude, pressure, surface layer parameters, and climatological data. It loops over each particle and checks whether it satisfies the specified boundary conditions. If a particle satisfies the conditions, its properties such as mass, volume mixing ratio, and the age-of-air reference timestamp are updated accordingly.

It checks for quantity flags to determine which properties need to be updated. If the latitude or pressure of a particle falls outside the specified ranges, it skips the particle. It also considers surface layer parameters such as surface pressure, height, zeta range, and planetary boundary layer. If a particle is within the specified surface layer boundaries, its properties are updated accordingly.

The function updates properties such as mass and volume mixing ratio if the corresponding flags are set. It retrieves volume mixing ratio values for various trace gases (e.g., CFC-10, CFC-11, N2O, SF6) from climatological time series data and updates the particle properties accordingly. Additionally, it resets aoa to the current particle time [s since 2000-01-01 00:00 UTC]. Elapsed age is observation time minus this reference timestamp.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climatological data structure containing time series data.
met0Pointer to the meteorological data structure at the initial time step.
met1Pointer to the meteorological data structure at the next time step.
atmPointer to the atmospheric data structure containing particle information.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 4125 of file mptrac.c.

4131 {
4132
4133 /* Set timer... */
4134 SELECT_TIMER("MODULE_BOUND_COND", "PHYSICS");
4135
4136 /* Check quantity flags... */
4137 if (ctl->qnt_m < 0 && ctl->qnt_vmr < 0 && ctl->qnt_Cccl4 < 0
4138 && ctl->qnt_Cccl3f < 0 && ctl->qnt_Cccl2f2 < 0
4139 && ctl->qnt_Cn2o < 0 && ctl->qnt_Csf6 < 0 && ctl->qnt_aoa < 0)
4140 return;
4141
4142 /* Loop over particles... */
4143 PARTICLE_LOOP(0, atm->np, 1,
4144 "acc data present(ctl,cache,clim,met0,met1,atm)") {
4145
4146 /* Check latitude and pressure range... */
4147 if (atm->lat[ip] < ctl->bound_lat0 || atm->lat[ip] > ctl->bound_lat1
4148 || atm->p[ip] > ctl->bound_p0 || atm->p[ip] < ctl->bound_p1)
4149 continue;
4150
4151 /* Check surface layer... */
4152 if (ctl->bound_dps > 0 || ctl->bound_dzs > 0
4153 || ctl->bound_zetas > 0 || ctl->bound_pbl) {
4154
4155 /* Get surface pressure... */
4156 double ps;
4158 INTPOL_2D(ps, 1);
4159
4160 /* Check pressure... */
4161 if (ctl->bound_dps > 0 && atm->p[ip] < ps - ctl->bound_dps)
4162 continue;
4163
4164 /* Check height... */
4165 if (ctl->bound_dzs > 0 && Z(atm->p[ip]) > Z(ps) + ctl->bound_dzs)
4166 continue;
4167
4168 /* Check zeta range... */
4169 if (ctl->bound_zetas > 0) {
4170 double t;
4171 INTPOL_3D(t, 1);
4172 if (ZETA(ps, atm->p[ip], t) > ctl->bound_zetas)
4173 continue;
4174 }
4175
4176 /* Check planetary boundary layer... */
4177 if (ctl->bound_pbl) {
4178 double pbl;
4179 INTPOL_2D(pbl, 0);
4180 if (atm->p[ip] < pbl)
4181 continue;
4182 }
4183 }
4184
4185 /* Set mass and volume mixing ratio... */
4186 if (ctl->qnt_m >= 0 && ctl->bound_mass >= 0)
4187 atm->q[ctl->qnt_m][ip] =
4188 ctl->bound_mass + ctl->bound_mass_trend * atm->time[ip];
4189 if (ctl->qnt_vmr >= 0 && ctl->bound_vmr >= 0)
4190 atm->q[ctl->qnt_vmr][ip] =
4191 ctl->bound_vmr + ctl->bound_vmr_trend * atm->time[ip];
4192
4193 /* Set CFC-10 volume mixing ratio... */
4194 if (ctl->qnt_Cccl4 >= 0 && ctl->clim_ccl4_timeseries[0] != '-')
4195 atm->q[ctl->qnt_Cccl4][ip] = clim_ts(&clim->ccl4, atm->time[ip]);
4196
4197 /* Set CFC-11 volume mixing ratio... */
4198 if (ctl->qnt_Cccl3f >= 0 && ctl->clim_ccl3f_timeseries[0] != '-')
4199 atm->q[ctl->qnt_Cccl3f][ip] = clim_ts(&clim->ccl3f, atm->time[ip]);
4200
4201 /* Set CFC-12 volume mixing ratio... */
4202 if (ctl->qnt_Cccl2f2 >= 0 && ctl->clim_ccl2f2_timeseries[0] != '-')
4203 atm->q[ctl->qnt_Cccl2f2][ip] = clim_ts(&clim->ccl2f2, atm->time[ip]);
4204
4205 /* Set N2O volume mixing ratio... */
4206 if (ctl->qnt_Cn2o >= 0 && ctl->clim_n2o_timeseries[0] != '-')
4207 atm->q[ctl->qnt_Cn2o][ip] = clim_ts(&clim->n2o, atm->time[ip]);
4208
4209 /* Set SF6 volume mixing ratio... */
4210 if (ctl->qnt_Csf6 >= 0 && ctl->clim_sf6_timeseries[0] != '-')
4211 atm->q[ctl->qnt_Csf6][ip] = clim_ts(&clim->sf6, atm->time[ip]);
4212
4213 /* Reset age-clock reference to the current particle time... */
4214 if (ctl->qnt_aoa >= 0)
4215 atm->q[ctl->qnt_aoa][ip] = atm->time[ip];
4216 }
4217}
double clim_ts(const clim_ts_t *ts, const double t)
Interpolates a time series of climatological variables.
Definition mptrac.c:400
#define INTPOL_3D(var, init)
Perform 3D interpolation for a meteorological variable.
Definition mptrac.h:1251
#define ZETA(ps, p, t)
Computes the value of the zeta vertical coordinate.
Definition mptrac.h:2353
#define INTPOL_2D(var, init)
Perform 2D interpolation for a meteorological variable.
Definition mptrac.h:1233
clim_ts_t ccl2f2
CFC-12 time series.
Definition mptrac.h:3935
clim_ts_t sf6
SF6 time series.
Definition mptrac.h:3941
clim_ts_t ccl4
CFC-10 time series.
Definition mptrac.h:3929
clim_ts_t ccl3f
CFC-11 time series.
Definition mptrac.h:3932
clim_ts_t n2o
N2O time series.
Definition mptrac.h:3938
int qnt_Cccl2f2
Quantity array index for CFC-12 volume mixing ratio (chemistry code).
Definition mptrac.h:2855
int qnt_m
Quantity array index for mass.
Definition mptrac.h:2588
int qnt_aoa
Quantity array index for the age-of-air reference timestamp [s since 2000-01-01 00:00 UTC].
Definition mptrac.h:2865
char clim_n2o_timeseries[LEN]
Filename of N2O time series.
Definition mptrac.h:3235
double bound_dzs
Boundary conditions surface layer depth [km].
Definition mptrac.h:3184
int qnt_Cccl4
Quantity array index for CFC-10 volume mixing ratio (chemistry code).
Definition mptrac.h:2849
double bound_mass
Boundary conditions mass per particle [kg].
Definition mptrac.h:3157
int qnt_vmr
Quantity array index for volume mixing ratio.
Definition mptrac.h:2591
double bound_lat1
Boundary conditions maximum longitude [deg].
Definition mptrac.h:3172
int bound_pbl
Boundary conditions planetary boundary layer (0=no, 1=yes).
Definition mptrac.h:3190
double bound_p1
Boundary conditions top pressure [hPa].
Definition mptrac.h:3178
double bound_vmr
Boundary conditions volume mixing ratio [ppv].
Definition mptrac.h:3163
double bound_lat0
Boundary conditions minimum longitude [deg].
Definition mptrac.h:3169
double bound_vmr_trend
Boundary conditions volume mixing ratio trend [ppv/s].
Definition mptrac.h:3166
int qnt_Cn2o
Quantity array index for N2O volume mixing ratio (chemistry code).
Definition mptrac.h:2858
int qnt_Cccl3f
Quantity array index for CFC-11 volume mixing ratio (chemistry code).
Definition mptrac.h:2852
int qnt_Csf6
Quantity array index for SF6 volume mixing ratio (chemistry code).
Definition mptrac.h:2861
double bound_dps
Boundary conditions surface layer depth [hPa].
Definition mptrac.h:3181
double bound_mass_trend
Boundary conditions mass per particle trend [kg/s].
Definition mptrac.h:3160
double bound_p0
Boundary conditions bottom pressure [hPa].
Definition mptrac.h:3175
char clim_ccl4_timeseries[LEN]
Filename of CFC-10 time series.
Definition mptrac.h:3226
char clim_sf6_timeseries[LEN]
Filename of SF6 time series.
Definition mptrac.h:3238
char clim_ccl3f_timeseries[LEN]
Filename of CFC-11 time series.
Definition mptrac.h:3229
char clim_ccl2f2_timeseries[LEN]
Filename of CFC-12 time series.
Definition mptrac.h:3232
double bound_zetas
Boundary conditions surface layer zeta [K].
Definition mptrac.h:3187
Here is the call graph for this function:

◆ module_chem_grid()

void module_chem_grid ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm,
const double t )

Computes gridded chemical tracer concentrations (volume mixing ratio) from individual air parcel mass data and assigns them back to the parcels.

This function aggregates the mass of tracer particles onto a 3D chemical grid (longitude × latitude × altitude), accounting for either single or ensemble simulations depending on ctl->nens. It then interpolates meteorological temperature fields and computes volume mixing ratios, storing them in the specified tracer quantity (e.g., ctl->qnt_Cx).

If the molar mass is undefined or required quantity indices are missing, the function exits early.

Parallelization is supported via OpenMP or OpenACC.

Parameters
[in]ctlPointer to the control structure containing configuration parameters, including grid dimensions, tracer indices, and simulation mode.
[in]cachePointer to individual particle timesteps; zero-step particles are excluded from the chemistry grid.
[in]met0Pointer to the meteorological data at the beginning of the interpolation interval.
[in]met1Pointer to the meteorological data at the end of the interpolation interval.
[in,out]atmPointer to the atmospheric state, including parcel coordinates, time, mass, and output tracer fields.
[in]tCentral time step used for output and interpolation.
Note
  • Requires ctl->molmass > 0, and ctl->qnt_m and ctl->qnt_Cx to be set.
  • Uses ensemble mode if ctl->nens > 0 and assigns each parcel to its ensemble member via ctl->qnt_ens.
  • Grid box volume mixing ratios are computed assuming ideal gas law and a layered spherical grid.
  • The output quantity qnt_Cx is a dimensionless mole fraction, not ppbv.
See also
intpol_met_time_3d()
P(), Z(), RHO()
ARRAY_3D macro
Author
Mingzhao Liu
Lars Hoffmann

Definition at line 4221 of file mptrac.c.

4227 {
4228
4229 if (met0->coord_type != 0)
4230 ERRMSG("Only lat/lon grid supported");
4231
4232 /* Check quantities... */
4233 if (ctl->qnt_m < 0 || ctl->qnt_Cx < 0)
4234 return;
4235 if (ctl->molmass <= 0)
4236 ERRMSG("Molar mass is not defined!");
4237
4238 /* Set timer... */
4239 SELECT_TIMER("MODULE_CHEM_GRID", "PHYSICS");
4240
4241 /* Allocate... */
4242 const int ensemble_mode = (ctl->nens > 0);
4243 const int np = atm->np;
4244 const int nz = ctl->chemgrid_nz;
4245 const int nx = ctl->chemgrid_nx;
4246 const int ny = ctl->chemgrid_ny;
4247 const int ngrid = nx * ny * nz;
4248 const int nens = ensemble_mode ? ctl->nens : 1;
4249
4250 double *restrict const z = (double *) malloc((size_t) nz * sizeof(double));
4251 double *restrict const press =
4252 (double *) malloc((size_t) nz * sizeof(double));
4253 double *restrict const mass =
4254 (double *) calloc((size_t) ngrid * (size_t) nens, sizeof(double));
4255 double *restrict const area =
4256 (double *) malloc((size_t) ny * sizeof(double));
4257 double *restrict const lon =
4258 (double *) malloc((size_t) nx * sizeof(double));
4259 double *restrict const lat =
4260 (double *) malloc((size_t) ny * sizeof(double));
4261
4262 int *restrict const ixs = (int *) malloc((size_t) np * sizeof(int));
4263 int *restrict const iys = (int *) malloc((size_t) np * sizeof(int));
4264 int *restrict const izs = (int *) malloc((size_t) np * sizeof(int));
4265
4266 /* Set grid box size... */
4267 const double dz = (ctl->chemgrid_z1 - ctl->chemgrid_z0) / nz;
4268 const double dlon = (ctl->chemgrid_lon1 - ctl->chemgrid_lon0) / nx;
4269 const double dlat = (ctl->chemgrid_lat1 - ctl->chemgrid_lat0) / ny;
4270
4271 /* Set vertical coordinates... */
4272#ifdef _OPENACC
4273#pragma acc enter data create(ixs[0:np],iys[0:np],izs[0:np],z[0:nz],press[0:nz],mass[0:ngrid*nens],area[0:ny],lon[0:nx],lat[0:ny])
4274#pragma acc data present(ctl,cache,met0,met1,atm,ixs,iys,izs,z,press,mass,area,lon,lat)
4275#pragma acc parallel loop independent gang vector
4276#else
4277#pragma omp parallel for default(shared)
4278#endif
4279 for (int iz = 0; iz < nz; iz++) {
4280 z[iz] = ctl->chemgrid_z0 + dz * (iz + 0.5);
4281 press[iz] = P(z[iz]);
4282 }
4283
4284 /* Initialize mass grid... */
4285#ifdef _OPENACC
4286#pragma acc parallel loop independent gang vector
4287#endif
4288 for (int i = 0; i < ngrid * nens; i++)
4289 mass[i] = 0;
4290
4291 /* Set particle-time window for chemistry-grid sampling... */
4292 const double t0 = tt - 0.5 * ctl->dt_mod;
4293 const double t1 = tt + 0.5 * ctl->dt_mod;
4294
4295 /* Select active particles inside the chemistry grid and valid ensembles... */
4296#ifdef _OPENACC
4297#pragma acc parallel loop independent gang vector
4298#else
4299#pragma omp parallel for default(shared)
4300#endif
4301 for (int ip = 0; ip < np; ip++) {
4302 if (cache->dt[ip] == 0) {
4303 izs[ip] = -1;
4304 continue;
4305 }
4306 const double zpart = Z(atm->p[ip]);
4307 if (atm->time[ip] < t0 || atm->time[ip] > t1
4308 || atm->lon[ip] < ctl->chemgrid_lon0
4309 || atm->lon[ip] >= ctl->chemgrid_lon1
4310 || atm->lat[ip] < ctl->chemgrid_lat0
4311 || atm->lat[ip] >= ctl->chemgrid_lat1
4312 || zpart < ctl->chemgrid_z0 || zpart >= ctl->chemgrid_z1) {
4313 izs[ip] = -1;
4314 continue;
4315 }
4316 if (ensemble_mode) {
4317 const double ens = atm->q[ctl->qnt_ens][ip];
4318 if (!isfinite(ens) || ens < 0 || ens >= nens || ens != (int) ens) {
4319 izs[ip] = -1;
4320 continue;
4321 }
4322 }
4323 ixs[ip] = (int) ((atm->lon[ip] - ctl->chemgrid_lon0) / dlon);
4324 iys[ip] = (int) ((atm->lat[ip] - ctl->chemgrid_lat0) / dlat);
4325 izs[ip] = (int) ((zpart - ctl->chemgrid_z0) / dz);
4326 if (ixs[ip] >= nx || iys[ip] >= ny || izs[ip] >= nz)
4327 izs[ip] = -1;
4328 }
4329
4330 /* Set horizontal coordinates... */
4331#ifdef _OPENACC
4332#pragma acc parallel loop independent gang vector
4333#else
4334#pragma omp parallel for default(shared)
4335#endif
4336 for (int ix = 0; ix < nx; ix++)
4337 lon[ix] = ctl->chemgrid_lon0 + dlon * (ix + 0.5);
4338
4339#ifdef _OPENACC
4340#pragma acc parallel loop independent gang vector
4341#else
4342#pragma omp parallel for default(shared)
4343#endif
4344 for (int iy = 0; iy < ny; iy++) {
4345 lat[iy] = ctl->chemgrid_lat0 + dlat * (iy + 0.5);
4346 area[iy] = dlat * dlon * SQR(RE * M_PI / 180.) * cos(DEG2RAD(lat[iy]));
4347 }
4348
4349 /* Get mass per grid box... */
4350#ifdef _OPENACC
4351#pragma acc parallel loop independent gang vector
4352#endif
4353 for (int ip = 0; ip < np; ip++) {
4354 if (izs[ip] >= 0) {
4355 int mass_idx = ARRAY_3D(ixs[ip], iys[ip], ny, izs[ip], nz);
4356 if (ensemble_mode) {
4357 const int ens = (int) atm->q[ctl->qnt_ens][ip];
4358 mass_idx += ens * ngrid;
4359 }
4360#ifdef _OPENACC
4361#pragma acc atomic update
4362#endif
4363 mass[mass_idx] += atm->q[ctl->qnt_m][ip];
4364 }
4365 }
4366
4367 /* Assign grid data to air parcels ... */
4368#ifdef _OPENACC
4369#pragma acc parallel loop independent gang vector
4370#else
4371#pragma omp parallel for default(shared)
4372#endif
4373 for (int ip = 0; ip < np; ip++)
4374 if (izs[ip] >= 0) {
4375
4376 /* Interpolate temperature... */
4377 double temp;
4379 intpol_met_time_3d(met0, met0->t, met1, met1->t, tt,
4380 press[izs[ip]],
4381 lon[ixs[ip]], lat[iys[ip]], &temp, ci, cw, 1);
4382
4383 /* Set mass... */
4384 int mass_idx = ARRAY_3D(ixs[ip], iys[ip], ny, izs[ip], nz);
4385 if (ensemble_mode) {
4386 const int ens = (int) atm->q[ctl->qnt_ens][ip];
4387 mass_idx += ens * ngrid;
4388 }
4389
4390 /* Calculate volume mixing ratio... */
4391 const double m = mass[mass_idx];
4392 atm->q[ctl->qnt_Cx][ip] = MA / ctl->molmass * m
4393 / (RHO(press[izs[ip]], temp) * area[iys[ip]] * dz * 1e9);
4394 }
4395
4396 /* Free... */
4397#ifdef _OPENACC
4398#pragma acc exit data delete(ixs,iys,izs,z,press,mass,area,lon,lat)
4399#endif
4400 free(mass);
4401 free(lon);
4402 free(lat);
4403 free(area);
4404 free(z);
4405 free(press);
4406 free(ixs);
4407 free(iys);
4408 free(izs);
4409}
#define ARRAY_3D(ix, iy, ny, iz, nz)
Compute the linear index of a 3D array element.
Definition mptrac.h:711
#define P(z)
Compute pressure at given altitude.
Definition mptrac.h:1843
#define RHO(p, t)
Compute density of air.
Definition mptrac.h:2020
double molmass
Molar mass [g/mol].
Definition mptrac.h:3196
double chemgrid_z1
Upper altitude of chemistry grid [km].
Definition mptrac.h:3283
double chemgrid_z0
Lower altitude of chemistry grid [km].
Definition mptrac.h:3280
double chemgrid_lat0
Lower latitude of chemistry grid [deg].
Definition mptrac.h:3298
double chemgrid_lat1
Upper latitude of chemistry grid [deg].
Definition mptrac.h:3301
double chemgrid_lon0
Lower longitude of chemistry grid [deg].
Definition mptrac.h:3289
double chemgrid_lon1
Upper longitude of chemistry grid [deg].
Definition mptrac.h:3292
double dt_mod
Time step of simulation [s].
Definition mptrac.h:2901
int nens
Number of ensembles.
Definition mptrac.h:3473
int chemgrid_nz
Number of altitudes of chemistry grid.
Definition mptrac.h:3277
int chemgrid_nx
Number of longitudes of chemistry grid.
Definition mptrac.h:3286
int chemgrid_ny
Number of latitudes of chemistry grid.
Definition mptrac.h:3295
int qnt_ens
Quantity array index for ensemble IDs.
Definition mptrac.h:2582
int qnt_Cx
Quantity array index for trace species x volume mixing ratio (chemistry code).
Definition mptrac.h:2819
Here is the call graph for this function:

◆ module_chem_init()

void module_chem_init ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Initializes the chemistry modules by setting atmospheric composition.

This function initializes various chemical components of the atmosphere using meteorological data and climatological information. It interpolates and sets values for water vapor (H2O), ozone (O3), and several radical species such as OH, HO2, H2O2, and O1D for each air parcel.

Parameters
ctlPointer to the control structure containing quantity flags.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climatology structure containing climatological data.
met0Pointer to the initial meteorological data structure.
met1Pointer to the final meteorological data structure.
atmPointer to the air parcel data structure.

The function uses OpenMP for parallel processing, iterating over each point in the atmosphere (atm->np) to initialize chemical species concentrations. It performs the following steps:

  • Interpolates H2O and O3 data from meteorological input if the respective quantity flags (ctl->qnt_Ch2o and ctl->qnt_Co3) are set.
  • Sets the concentrations of OH, HO2, H2O2, and O1D using climatological data if the respective quantity flags are set.
Author
Mingzhao Liu

Definition at line 4413 of file mptrac.c.

4419 {
4420
4421 /* Set timer... */
4422 SELECT_TIMER("MODULE_CHEM_INIT", "PHYSICS");
4423
4424 /* Loop over particles... */
4425 PARTICLE_LOOP(0, atm->np, 0,
4426 "acc data present(ctl,cache,clim,met0,met1,atm)") {
4427
4428 /* Set H2O and O3 using meteo data... */
4430 if (ctl->qnt_Ch2o >= 0) {
4431 double h2o;
4432 INTPOL_3D(h2o, 1);
4433 SET_ATM(qnt_Ch2o, h2o);
4434 }
4435 if (ctl->qnt_Co3 >= 0) {
4436 double o3;
4437 INTPOL_3D(o3, 1);
4438 SET_ATM(qnt_Co3, o3);
4439 }
4440
4441 /* Set radical species... */
4442 const double lat_ref =
4443 ctl->met_coord_type == 0 ? atm->lat[ip] : ctl->met_utm_ref_lat;
4444 SET_ATM(qnt_Coh, clim_oh(ctl, clim, atm->time[ip],
4445 atm->lon[ip], atm->lat[ip], atm->p[ip]));
4446 SET_ATM(qnt_Cho2, clim_zm(&clim->ho2, atm->time[ip],
4447 lat_ref, atm->p[ip]));
4448 SET_ATM(qnt_Ch2o2, clim_zm(&clim->h2o2, atm->time[ip],
4449 lat_ref, atm->p[ip]));
4450 SET_ATM(qnt_Co1d, clim_zm(&clim->o1d, atm->time[ip],
4451 lat_ref, atm->p[ip]));
4452 }
4453}
double clim_oh(const ctl_t *ctl, const clim_t *clim, const double t, const double lon, const double lat, const double p)
Calculates the hydroxyl radical (OH) concentration from climatology data, with an optional diurnal co...
Definition mptrac.c:91
#define SET_ATM(qnt, val)
Set atmospheric quantity value.
Definition mptrac.h:2039
clim_zm_t ho2
HO2 zonal means.
Definition mptrac.h:3923
clim_zm_t o1d
O(1D) zonal means.
Definition mptrac.h:3926
clim_zm_t h2o2
H2O2 zonal means.
Definition mptrac.h:3920
int qnt_Ch2o
Quantity array index for H2O volume mixing ratio (chemistry code).
Definition mptrac.h:2822
int qnt_Co3
Quantity array index for O3 volume mixing ratio (chemistry code).
Definition mptrac.h:2825
Here is the call graph for this function:

◆ module_convection()

void module_convection ( const ctl_t * ctl,
cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Performs convective mixing of atmospheric particles.

Randomly redistributes particle pressure within a PBL or CAPE/EL column. A positive CIN threshold additionally limits ECP to columns with CIN at or below that threshold. ECP requires a finite EL pressure above the surface; PBL-only redistribution does not require EL. Particles with zero individual timestep are skipped. Particle number and tracer mass are not directly changed.

Parameters
[in]ctlPointer to the control structure with simulation settings.
[in,out]cachePointer to the cache structure for temporary data and random numbers.
[in]met0Pointer to the earlier meteorological data.
[in]met1Pointer to the later meteorological data.
[in,out]atmPointer to the atmospheric data structure with particle properties.
Author
Lars Hoffmann

Definition at line 4457 of file mptrac.c.

4462 {
4463
4464 /* Set timer... */
4465 SELECT_TIMER("MODULE_CONVECTION", "PHYSICS");
4466
4467 /* Create random numbers... */
4468 module_rng(ctl, cache->rs, (size_t) atm->np, 0);
4469
4470 /* Loop over particles... */
4471 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
4472
4473 /* Interpolate surface pressure... */
4474 double ps;
4476 INTPOL_2D(ps, 1);
4477
4478 /* Initialize pressure range for vertical mixing... */
4479 double pbot = ps, ptop = ps;
4480
4481 /* Mixing in the PBL... */
4482 if (ctl->conv_mix_pbl) {
4483
4484 /* Interpolate PBL... */
4485 double pbl;
4486 INTPOL_2D(pbl, 0);
4487
4488 /* Set pressure range... */
4489 ptop = pbl - ctl->conv_pbl_trans * (ps - pbl);
4490 }
4491
4492 /* Convective mixing... */
4493 if (ctl->conv_cape >= 0) {
4494
4495 /* Interpolate CAPE, CIN, and equilibrium level... */
4496 double cape, cin, pel;
4497 INTPOL_2D(cape, 0);
4498 INTPOL_2D(cin, 0);
4499 INTPOL_2D(pel, 0);
4500
4501 /* Set pressure range... */
4502 if (isfinite(cape) && cape >= ctl->conv_cape
4503 && (ctl->conv_cin <= 0 || (isfinite(cin) && cin <= ctl->conv_cin))
4504 && isfinite(pel) && pel > 0 && pel < ps)
4505 ptop = MIN(ptop, pel);
4506 }
4507
4508 /* Apply vertical mixing... */
4509 if (ptop != pbot && atm->p[ip] >= ptop) {
4510
4511 /* Get density range... */
4512 double tbot, ttop;
4513 intpol_met_time_3d(met0, met0->t, met1, met1->t, atm->time[ip],
4514 pbot, atm->lon[ip], atm->lat[ip], &tbot, ci, cw, 1);
4515 intpol_met_time_3d(met0, met0->t, met1, met1->t, atm->time[ip], ptop,
4516 atm->lon[ip], atm->lat[ip], &ttop, ci, cw, 1);
4517 const double rhobot = pbot / tbot;
4518 const double rhotop = ptop / ttop;
4519
4520 /* Get new density... */
4521 const double rho = rhobot + (rhotop - rhobot) * cache->rs[ip];
4522
4523 /* Get pressure... */
4524 atm->p[ip] = LIN(rhobot, pbot, rhotop, ptop, rho);
4525 }
4526 }
4527}
void module_rng(const ctl_t *ctl, double *rs, const size_t n, const int method)
Generate random numbers using various methods and distributions.
Definition mptrac.c:6334
double rs[3 *NP+1]
Random numbers.
Definition mptrac.h:3744
double conv_cape
CAPE threshold for convection module [J/kg].
Definition mptrac.h:3148
double conv_pbl_trans
Depth of PBL transition layer (fraction of PBL pressure thickness).
Definition mptrac.h:3145
int conv_mix_pbl
Vertical mixing in the PBL (0=off, 1=on).
Definition mptrac.h:3142
double conv_cin
CIN threshold for convection module [J/kg].
Definition mptrac.h:3151
Here is the call graph for this function:

◆ module_dd()

void module_dd ( double t,
const ctl_t * ctl,
cache_t * cache,
dd_t * dd,
atm_t * atm,
met_t ** met )

Perform domain decomposition and exchange particles between MPI ranks.

This routine redistributes atmospheric particles across MPI processes according to the current spatial domain decomposition so that each process owns the particles located inside its subdomain.

The routine performs the following steps:

  1. Determine the destination subdomain for each particle.
  2. With DD_EXCHANGE_MODE=0, use the original sort/push path; with mode 1, pack outgoing particles and compact retained particles without sorting.
  3. Convert particle data from the atmospheric structure-of-arrays representation into a temporary particle buffer (array-of-structures).
  4. Exchange particles between MPI ranks according to their destination rank.
  5. Convert the received particle data back into the atmospheric structure-of-arrays representation.

A temporary particle buffer is maintained locally and resized dynamically when necessary to hold outgoing or incoming particles. After the communication step, the atmospheric particle arrays are updated to contain only the particles owned by the current MPI rank.

Parameters
[in]tCurrent simulation time in seconds since 2000-01-01.
[in]ctlControl structure containing simulation settings and quantity indices.
[in,out]cacheCache structure used for temporary particle data during data layout transformations.
[in,out]ddDomain decomposition structure containing grid metadata and auxiliary buffers.
[in,out]atmAtmospheric particle state. Particle ownership and particle arrays are updated in place.
[in]metPointer to the meteorological data used for subdomain assignment and sorting.
Note
  • This routine is available only when MPTRAC is compiled with domain decomposition support (DD) and MPI enabled.
  • Particle exchange is performed using MPI collective communication.
Author
Jan Clemens
Lars Hoffmann

Definition at line 4532 of file mptrac.c.

4538 {
4539
4540 /* Initialize particles locally... */
4541 int npart = 0, nkeep = 0, capacity = 0;
4542 particle_t *particles = NULL;
4543
4544 /* Assign particles to new subdomains... */
4545 dd_assign_subdomains(ctl, dd, atm, 0);
4546
4547 if (ctl->dd_exchange_mode == 0) {
4548 /* Original sort/push exchange path... */
4549 if (fmod(t, ctl->dd_sort_dt) == 0)
4550 dd_sort(ctl, *met, cache, atm, dd, &npart);
4551 else
4552 dd_push(ctl, atm, cache, &npart);
4553 } else {
4554 /* Count outgoing particles for direct packing and compaction... */
4555 dd_count_outgoing(ctl, atm, dd, &nkeep, &npart);
4556 }
4557
4558 /* Ensure particle buffer is large enough for outgoing particles... */
4559 if (npart > capacity) {
4560 const int newcap = npart + npart / 2 + 1;
4561 particle_t *tmp =
4562 realloc(particles, (size_t) newcap * sizeof(particle_t));
4563 if (!tmp)
4564 ERRMSG("Out of memory!");
4565 particles = tmp;
4566 capacity = newcap;
4567 }
4568
4569 /* Transform from struct of array to array of struct... */
4570 if (ctl->dd_exchange_mode == 0)
4571 dd_atm2particles(ctl, cache, atm, particles, npart);
4572 else
4573 dd_pack_compact(ctl, cache, atm, dd, particles, nkeep, npart);
4574
4575 SELECT_TIMER("SYNC", "DD");
4576 MPI_Barrier(MPI_COMM_WORLD);
4577
4578 /* Perform the communication... */
4579 dd_communicate_particles(ctl, dd, &particles, &npart, &capacity);
4580
4581 /* Transform from array of struct to struct of array... */
4582 dd_particles2atm(ctl, cache, particles, npart, atm);
4583
4584 /* Free local particle array... */
4585 free(particles);
4586}
void dd_sort(const ctl_t *ctl, const met_t *met0, cache_t *cache, atm_t *atm, dd_t *dd, int *npart)
Sort local atmospheric particles and determine export counts for domain decomposition.
Definition mptrac.c:2681
void dd_pack_compact(const ctl_t *ctl, cache_t *cache, atm_t *atm, dd_t *dd, particle_t *particles, const int nkeep, const int npart)
Pack outgoing particles and compact local arrays without sorting.
Definition mptrac.c:2054
void dd_particles2atm(const ctl_t *ctl, cache_t *cache, const particle_t *particles, const int npart, atm_t *atm)
Copy received particles from the communication buffer into the atmospheric state.
Definition mptrac.c:2456
void dd_count_outgoing(const ctl_t *ctl, const atm_t *atm, dd_t *dd, int *nkeep, int *npart)
Classify particles before direct packing and compaction.
Definition mptrac.c:2796
void dd_atm2particles(const ctl_t *ctl, cache_t *cache, atm_t *atm, particle_t *particles, const int npart)
Copy migratable atmospheric particles from the ATM state into a particle buffer.
Definition mptrac.c:2002
void dd_communicate_particles(const ctl_t *ctl, const dd_t *dd, particle_t **particles, int *npart, int *capacity)
Exchange particles between MPI ranks according to their destination rank.
Definition mptrac.c:2206
void dd_push(const ctl_t *ctl, atm_t *atm, cache_t *cache, int *npart)
Compact and stage non-local particles for domain decomposition transfer.
Definition mptrac.c:2602
double dd_sort_dt
Sorting time interval for the compactification (DD_EXCHANGE_MODE=0).
Definition mptrac.h:3642
Here is the call graph for this function:

◆ module_decay()

void module_decay ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
atm_t * atm )

Simulate exponential decay processes for atmospheric particles.

This function simulates decay processes for atmospheric particles based on their mass or volume mixing ratio. It loops over each particle and calculates the decay rate using weighting factors for tropospheric and stratospheric lifetimes. Exponential decay is then calculated, and the mass or volume mixing ratio of particles is updated accordingly. Loss rates can also be calculated and updated based on the decay process.

The function checks for quantity flags to ensure that mass or volume mixing ratio data is available. It then calculates the weighting factor based on the particle's location in the atmosphere and sets the lifetime accordingly. Exponential decay is calculated using the time step and the lifetime, and the particle's mass or volume mixing ratio is updated. Loss rates can also be updated based on the decay process.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climate data structure containing atmospheric data.
atmPointer to the atmospheric data structure containing particle information.
Author
Lars Hoffmann

Definition at line 4591 of file mptrac.c.

4595 {
4596
4597 /* Set timer... */
4598 SELECT_TIMER("MODULE_DECAY", "PHYSICS");
4599
4600 /* Check quantity flags... */
4601 if (ctl->qnt_m < 0 && ctl->qnt_vmr < 0)
4602 ERRMSG("Module needs quantity mass or volume mixing ratio!");
4603
4604 /* Loop over particles... */
4605 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,clim,atm)") {
4606
4607 /* Get weighting factor... */
4608 const double w = tropo_weight(ctl, clim, atm, ip);
4609
4610 /* Set lifetime... */
4611 const double tdec = w * ctl->tdec_trop + (1 - w) * ctl->tdec_strat;
4612
4613 /* Calculate exponential decay... */
4614 const double aux = exp(-cache->dt[ip] / tdec);
4615 if (ctl->qnt_m >= 0) {
4616 if (ctl->qnt_mloss_decay >= 0)
4617 atm->q[ctl->qnt_mloss_decay][ip]
4618 += atm->q[ctl->qnt_m][ip] * (1 - aux);
4619 atm->q[ctl->qnt_m][ip] *= aux;
4620 if (ctl->qnt_loss_rate >= 0)
4621 atm->q[ctl->qnt_loss_rate][ip] += 1. / tdec;
4622 }
4623 if (ctl->qnt_vmr >= 0)
4624 atm->q[ctl->qnt_vmr][ip] *= aux;
4625 }
4626}
double tropo_weight(const ctl_t *ctl, const clim_t *clim, const atm_t *atm, const int ip)
Computes a weighting factor based on tropopause pressure.
Definition mptrac.c:14113
int qnt_loss_rate
Quantity array index for total loss rate.
Definition mptrac.h:2747
int qnt_mloss_decay
Quantity array index for total mass loss due to exponential decay.
Definition mptrac.h:2744
double tdec_strat
Life time of particles in the stratosphere [s].
Definition mptrac.h:3202
double tdec_trop
Life time of particles in the troposphere [s].
Definition mptrac.h:3199
Here is the call graph for this function:

◆ module_diff_meso()

void module_diff_meso ( const ctl_t * ctl,
cache_t * cache,
const met_t * met0,
const met_t * met1,
atm_t * atm )

Simulate mesoscale diffusion for atmospheric particles.

This function simulates mesoscale diffusion for atmospheric particles, including horizontal and vertical wind fluctuations. It calculates standard deviations of local wind data and temporal correlations for mesoscale fluctuations. Mesoscale wind fluctuations are then calculated based on the provided random numbers and turbulence parameters. The particle positions are updated accordingly.

The function loops over each particle and calculates indices for interpolation of wind data. It then computes standard deviations of local wind data and temporal correlations for mesoscale fluctuations. Based on the turbulence parameters and provided random numbers, it calculates horizontal and vertical mesoscale wind fluctuations. Finally, it updates the particle positions based on the calculated wind fluctuations.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the meteorological data structure at the current time step.
met1Pointer to the meteorological data structure at the next time step.
atmPointer to the atmospheric data structure containing particle information.
Note
Control parameters TURB_MESOX and TURB_MESOZ define the subgrid-scale variability as a fraction of the grid-scale variance. Stohl et al. (2005) recommend a default value of 0.16 for both parameters, providing a standard approach for turbulence representation. However, recent findings by Bakels et al. (2024) suggest disabling this approach to improve model accuracy under certain conditions. It is advised to evaluate the applicability of these recommendations based on the specific simulation context and objectives.
Author
Lars Hoffmann

Definition at line 4630 of file mptrac.c.

4635 {
4636
4637 /* Set timer... */
4638 SELECT_TIMER("MODULE_DIFF_MESO", "PHYSICS");
4639
4640 /* Create random numbers... */
4641 module_rng(ctl, cache->rs, 3 * (size_t) atm->np, 1);
4642
4643 /* Loop over particles... */
4644 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
4645
4646 /* Get indices... */
4647 const int ix = locate_reg(met0->lon, met0->nx, atm->lon[ip]);
4648 const int iy = locate_irr(met0->lat, met0->ny, atm->lat[ip]);
4649 const int iz = locate_irr(met0->p, met0->np, atm->p[ip]);
4650
4651 /* Get standard deviations of local wind data... */
4652 float umean = 0, usig = 0, vmean = 0, vsig = 0, wmean = 0, wsig = 0;
4653 for (int i = 0; i < 2; i++)
4654 for (int j = 0; j < 2; j++)
4655 for (int k = 0; k < 2; k++) {
4656 umean += met0->u[ix + i][iy + j][iz + k];
4657 usig += SQR(met0->u[ix + i][iy + j][iz + k]);
4658 vmean += met0->v[ix + i][iy + j][iz + k];
4659 vsig += SQR(met0->v[ix + i][iy + j][iz + k]);
4660 wmean += met0->w[ix + i][iy + j][iz + k];
4661 wsig += SQR(met0->w[ix + i][iy + j][iz + k]);
4662
4663 umean += met1->u[ix + i][iy + j][iz + k];
4664 usig += SQR(met1->u[ix + i][iy + j][iz + k]);
4665 vmean += met1->v[ix + i][iy + j][iz + k];
4666 vsig += SQR(met1->v[ix + i][iy + j][iz + k]);
4667 wmean += met1->w[ix + i][iy + j][iz + k];
4668 wsig += SQR(met1->w[ix + i][iy + j][iz + k]);
4669 }
4670 usig = usig / 16.f - SQR(umean / 16.f);
4671 usig = (usig > 0 ? sqrtf(usig) : 0);
4672 vsig = vsig / 16.f - SQR(vmean / 16.f);
4673 vsig = (vsig > 0 ? sqrtf(vsig) : 0);
4674 wsig = wsig / 16.f - SQR(wmean / 16.f);
4675 wsig = (wsig > 0 ? sqrtf(wsig) : 0);
4676
4677 /* Set temporal correlations for mesoscale fluctuations... */
4678 const double r = 1 - 2 * fabs(cache->dt[ip]) / ctl->dt_met;
4679 const double r2 = sqrt(1 - r * r);
4680
4681 /* Calculate horizontal mesoscale wind fluctuations... */
4682 if (ctl->turb_mesox > 0) {
4683 cache->uvwp[ip][0] =
4684 (float) (r * cache->uvwp[ip][0] +
4685 r2 * cache->rs[3 * ip] * ctl->turb_mesox * usig);
4686 atm->lon[ip] +=
4687 DX2COORD(met0, cache->uvwp[ip][0] * cache->dt[ip], atm->lat[ip]);
4688
4689 cache->uvwp[ip][1] =
4690 (float) (r * cache->uvwp[ip][1] +
4691 r2 * cache->rs[3 * ip + 1] * ctl->turb_mesox * vsig);
4692 atm->lat[ip] += DY2COORD(met0, cache->uvwp[ip][1] * cache->dt[ip]);
4693 }
4694
4695 /* Calculate vertical mesoscale wind fluctuations... */
4696 if (ctl->turb_mesoz > 0) {
4697 cache->uvwp[ip][2] =
4698 (float) (r * cache->uvwp[ip][2] +
4699 r2 * cache->rs[3 * ip + 2] * ctl->turb_mesoz * wsig);
4700 atm->p[ip] += cache->uvwp[ip][2] * cache->dt[ip];
4701 }
4702 }
4703}
double turb_mesoz
Vertical scaling factor for mesoscale wind fluctuations.
Definition mptrac.h:3136
double dt_met
Time step of meteo data [s].
Definition mptrac.h:2911
double turb_mesox
Horizontal scaling factor for mesoscale wind fluctuations.
Definition mptrac.h:3133
Here is the call graph for this function:

◆ module_diff_pbl()

void module_diff_pbl ( const ctl_t * ctl,
cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Computes particle diffusion within the planetary boundary layer (PBL).

This function handles the effects of turbulence on particles within the PBL. It calculates turbulent velocity variances, Lagrangian timescales, and updates particle positions and perturbations based on random fluctuations and boundary layer physics. This module adapts the approach of Ryall and Maryon (1998) and Stohl et al. (2005).

Parameters
ctlPointer to the control structure containing model settings.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the meteorological data structure for the current timestep.
met1Pointer to the meteorological data structure for the next timestep.
atmPointer to the atmospheric data structure containing particle states.

The function:

  • Allocates memory for random numbers and generates them using module_rng.
  • Loops over all particles to compute their behavior within the boundary layer.
  • Handles both stable/neutral and unstable conditions based on the surface sensible heat flux.
  • Calculates turbulent velocity variances (sig_u, sig_w), their vertical derivatives, and Lagrangian timescales (tau_u, tau_w).
  • Updates particle velocity perturbations and positions using turbulent diffusion equations.
  • Uses ensemble-wide substeps of at most DT_PBL seconds, preserving each particle's signed individual timestep and refreshing random numbers each substep.

The function uses OpenACC directives for GPU acceleration.

Note
The function handles edge cases like zero diffusivity and imposes minimum limits on calculated values to ensure stability.
Warning
Ensure that all input pointers are properly initialized and accessible before calling this function.
Author
Lars Hoffmann

Definition at line 4707 of file mptrac.c.

4712 {
4713
4714 /* Set timer... */
4715 SELECT_TIMER("MODULE_DIFF_PBL", "PHYSICS");
4716
4717 /* Use the largest active particle timestep for a common substep count. */
4718 double dt_max = 0.0;
4719#ifdef _OPENACC
4720#pragma acc parallel loop present(cache) reduction(max:dt_max)
4721#else
4722#pragma omp parallel for reduction(max:dt_max)
4723#endif
4724 for (int ip = 0; ip < atm->np; ip++)
4725 dt_max = MAX(dt_max, fabs(cache->dt[ip]));
4726
4727 /* No stochastic update is needed if every particle is inactive. */
4728 if (dt_max == 0.0)
4729 return;
4730
4731 const double required = ceil(dt_max / ctl->dt_pbl);
4732 if (!isfinite(required) || required > INT_MAX)
4733 ERRMSG("Too many Hanna-PBL substeps; increase DT_PBL!");
4734 const int nsub = (required > 1.0 ? (int) required : 1);
4735
4736 for (int isub = 0; isub < nsub; isub++) {
4737
4738 /* Draw independent Gaussian perturbations for this ensemble substep. */
4739 module_rng(ctl, cache->rs, 3 * (size_t) atm->np, 1);
4740
4741 /* Re-evaluate local PBL statistics at the updated particle position. */
4742 PARTICLE_LOOP(0, atm->np, 1,
4743 "acc data present(ctl,cache,met0,met1,atm)") {
4744
4745 double pbl, ps, dsigw_dz = 0.0, sig_u = 0.0, sig_v = 0.0, sig_w = 0.0;
4746 double tau_u = 0.0, tau_v = 0.0, tau_w = 0.0;
4747
4748 /* Get PBL pressure... */
4750 INTPOL_2D(pbl, 1);
4751
4752 /* Clear Hanna velocities outside the PBL before a later re-entry. */
4753 if (atm->p[ip] < pbl) {
4754 cache->uvwp[ip][0] = 0.0f;
4755 cache->uvwp[ip][1] = 0.0f;
4756 cache->uvwp[ip][2] = 0.0f;
4757 continue;
4758 }
4759
4760 /* Get surface pressure... */
4761 INTPOL_2D(ps, 0);
4762
4763 /* Skip invalid or vanishing PBL layers. */
4764 if (!(ps > 0.0 && pbl > 0.0 && ps > pbl))
4765 continue;
4766
4767 /* Calculate heights [m] above ground.
4768 Z() returns altitude in km, so multiply differences by 1e3. */
4769 const double p = MIN(atm->p[ip], ps);
4770 const double zs = Z(ps);
4771 const double z_raw = 1e3 * (Z(p) - zs);
4772 const double zi = 1e3 * (Z(pbl) - zs);
4773
4774 /* Require a physically meaningful PBL depth. */
4775 if (!(zi > 1.0))
4776 continue;
4777
4778 /* Clamp height to the PBL interval for closure evaluation. */
4779 const double z = CLAMP(z_raw, 0.0, zi);
4780 const double zeta = CLAMP(z / zi, 1e-6, 1.0 - 1e-6);
4781 const double z_m = MAX(z, 1.0);
4782
4783 /* Temporarily use clamped pressure for thermodynamic interpolation.
4784 This avoids inconsistent interpolation if a particle has slipped
4785 below the surface pressure. */
4786 const double p_save = atm->p[ip];
4787 atm->p[ip] = p;
4788
4789 /* Calculate friction velocity... */
4790 double ess, nss, h2o, t;
4791 INTPOL_2D(ess, 0);
4792 INTPOL_2D(nss, 0);
4793 INTPOL_3D(t, 1);
4794 INTPOL_3D(h2o, 0);
4795 double u, v;
4796 INTPOL_3D(u, 0);
4797 INTPOL_3D(v, 0);
4798
4799 /* Restore particle pressure before any continue/update path. */
4800 atm->p[ip] = p_save;
4801
4802 const double tv = TVIRT(t, h2o);
4803 const double thetav = THETAVIRT(p, t, h2o);
4804 const double rho = RHO(p, tv);
4805 const double tau = sqrt(SQR(ess) + SQR(nss));
4806
4807 if (!(rho > 0.0))
4808 continue;
4809
4810 const double ustar = sqrt(MAX(tau / rho, 0.0));
4811 const double ust = MAX(1e-4, ustar);
4812
4813 /* Get surface sensible heat flux.
4814 Sign convention assumed here: unstable surface heating gives shf < 0,
4815 as in the existing implementation. */
4816 double shf;
4817 INTPOL_2D(shf, 1);
4818
4819 /* Estimate Monin-Obukhov length [m] to distinguish
4820 neutral, stable, and unstable cases. */
4821 double ol = 1e12;
4822 if (fabs(shf) > 1e-6)
4823 ol = thetav * rho * CPD * SQR(ust) * ust / (KARMAN * G0 * shf);
4824
4825 /* Neutral conditions... */
4826 if (zi / fabs(ol) < 1.0) {
4827
4828 /* corr has units of seconds, hence the exponential coefficients
4829 have units of s^-1. The derivative d(sig_w)/dz therefore needs
4830 the extra factor 1/ust. */
4831 const double corr = z_m / ust;
4832 const double sigw0 = 1.3 * ust * exp(-2e-4 * corr);
4833
4834 sig_u = MAX(2.0 * ust * exp(-3e-4 * corr), 1e-5);
4835 sig_v = MAX(sigw0, 1e-5);
4836 sig_w = MAX(sigw0, 1e-5);
4837 dsigw_dz = -2e-4 * sigw0 / ust;
4838
4839 tau_u = 0.5 * z_m / sig_w / (1.0 + 1.5e-3 * corr);
4840 tau_v = tau_u;
4841 tau_w = tau_u;
4842 }
4843
4844 /* Unstable conditions... */
4845 else if (ol < 0.0) {
4846
4847 /* Convective velocity scale [m/s]. */
4848 const double wstar_arg = -G0 / thetav * shf / (rho * CPD) * zi;
4849 const double wstar = pow(MAX(wstar_arg, 0.0), 1.0 / 3.0);
4850 double dsigw2_dz = 0.0;
4851
4852 /* Hanna1/FLEXPART turbulent velocity standard deviations [m/s]. */
4853 sig_u = MAX(ust * pow(MAX(12.0 - 0.5 * zi / ol, 0.0), 1.0 / 3.0), 1e-6);
4854 sig_v = sig_u;
4855
4856 /* Use the piecewise vertical-variance profile and its gradient... */
4857 if (zeta < 0.03) {
4858 const double arg = MAX(3.0 * zeta - ol / zi, 1e-12);
4859 sig_w = 0.96 * wstar * pow(arg, 1.0 / 3.0);
4860 dsigw2_dz = 1.8432 * SQR(wstar) / zi * pow(arg, -1.0 / 3.0);
4861 } else if (zeta < 0.4) {
4862 const double arg = MAX(3.0 * zeta - ol / zi, 1e-12);
4863 const double s1 = 0.96 * pow(arg, 1.0 / 3.0);
4864 const double s2 = 0.763 * pow(zeta, 0.175);
4865 if (s1 < s2) {
4866 sig_w = wstar * s1;
4867 dsigw2_dz = 1.8432 * SQR(wstar) / zi * pow(arg, -1.0 / 3.0);
4868 } else {
4869 sig_w = wstar * s2;
4870 dsigw2_dz = 0.203759 * SQR(wstar) / zi * pow(zeta, -0.65);
4871 }
4872 } else if (zeta < 0.96) {
4873 sig_w = 0.722 * wstar * pow(1.0 - zeta, 0.207);
4874 dsigw2_dz = -0.215812 * SQR(wstar) / zi * pow(1.0 - zeta, -0.586);
4875 } else {
4876 sig_w = 0.37 * wstar;
4877 dsigw2_dz = 0.0;
4878 }
4879
4880 sig_w = MAX(sig_w, 1e-6);
4881 dsigw_dz = sig_w > 1e-12 ? 0.5 * dsigw2_dz / sig_w : 0.0;
4882
4883 /* Hanna/FLEXPART Lagrangian timescales [s]. */
4884 tau_u = 0.15 * zi / MAX(sig_u, 1e-12);
4885 tau_v = tau_u;
4886
4887 if (z_m < fabs(ol)) {
4888 const double denom = 0.55 - 0.38 * fabs(z_m / ol);
4889 tau_w = 0.1 * z_m / (sig_w * MAX(denom, 0.05));
4890 } else if (zeta < 0.1)
4891 tau_w = 0.59 * z_m / sig_w;
4892 else
4893 tau_w = 0.15 * zi / sig_w * (1.0 - exp(-5.0 * zeta));
4894 }
4895
4896 /* Stable conditions... */
4897 else {
4898
4899 sig_u = MAX(2.0 * ust * (1.0 - zeta), 1e-6);
4900 sig_v = MAX(1.3 * ust * (1.0 - zeta), 1e-6);
4901 sig_w = MAX(1.3 * ust * (1.0 - zeta), 1e-6);
4902 dsigw_dz = -1.3 * ust / zi;
4903
4904 tau_u = 0.15 * zi / sig_u * sqrt(zeta);
4905 tau_v = 0.467 * tau_u;
4906 tau_w = 0.1 * zi / sig_w * pow(zeta, 0.8);
4907 }
4908
4909 /* Apply FLEXPART-consistent lower bounds for timescales. */
4910 tau_u = MAX(tau_u, 10.0);
4911 tau_v = MAX(tau_v, 10.0);
4912 tau_w = MAX(tau_w, 30.0);
4913
4914 /* Skip pathological states. */
4915 if (!(sig_u > 0.0 && sig_v > 0.0
4916 && sig_w > 0.0 && tau_u > 0.0 && tau_v > 0.0 && tau_w > 0.0))
4917 continue;
4918
4919 /* Update along-wind and cross-wind perturbations [m/s], retaining
4920 the cached velocity in geographic east/north coordinates. */
4921 const double dt = cache->dt[ip] / nsub;
4922 const double dt_abs = fabs(dt);
4923
4924 const double wind = hypot(u, v);
4925 const double cos_dir = isfinite(wind) && wind > 1e-6 ? u / wind : 1.0;
4926 const double sin_dir = isfinite(wind) && wind > 1e-6 ? v / wind : 0.0;
4927 const double along =
4928 cos_dir * cache->uvwp[ip][0] + sin_dir * cache->uvwp[ip][1];
4929 const double cross =
4930 -sin_dir * cache->uvwp[ip][0] + cos_dir * cache->uvwp[ip][1];
4931
4932 const double ru = exp(-dt_abs / tau_u);
4933 const double ru2 = sqrt(MAX(0.0, 1.0 - SQR(ru)));
4934 const double rv = exp(-dt_abs / tau_v);
4935 const double rv2 = sqrt(MAX(0.0, 1.0 - SQR(rv)));
4936
4937 const double along_new = along * ru + sig_u * ru2 * cache->rs[3 * ip];
4938 const double cross_new = cross * rv + sig_v * rv2 * cache->rs[3 * ip + 1];
4939 cache->uvwp[ip][0] = (float) (cos_dir * along_new - sin_dir * cross_new);
4940 cache->uvwp[ip][1] = (float) (sin_dir * along_new + cos_dir * cross_new);
4941
4942 /* Update vertical perturbation [m/s].
4943 The drift term is d(sig_w^2)/dz + sig_w^2/rho * d(rho)/dz.
4944 With exponential scale height H0 [km], dln(rho)/dz ~= -1/(1000 H0). */
4945 const double rw = exp(-dt_abs / tau_w);
4946 const double rw2 = sqrt(MAX(0.0, 1.0 - SQR(rw)));
4947 const double rhoaux = -1.0 / (1e3 * H0);
4948
4949 cache->uvwp[ip][2]
4950 = (float) (cache->uvwp[ip][2] * rw + sig_w * rw2 * cache->rs[3 * ip + 2]
4951 + tau_w * (1.0 - rw)
4952 * (2.0 * sig_w * dsigw_dz + rhoaux * SQR(sig_w)));
4953
4954 /* Calculate new horizontal air parcel position. */
4955 atm->lon[ip] += DX2COORD(met0, cache->uvwp[ip][0] * dt, atm->lat[ip]);
4956 atm->lat[ip] += DY2COORD(met0, cache->uvwp[ip][1] * dt);
4957
4958 /* Calculate new height and reflect robustly at surface and PBL top.
4959 Each boundary reflection reverses the vertical turbulent velocity.
4960 This loop is intentionally simple and explicit: it remains correct
4961 even if a large step crosses multiple boundaries. */
4962 double znew = z + cache->uvwp[ip][2] * dt;
4963
4964 while (znew < 0.0 || znew > zi) {
4965
4966 if (znew < 0.0) {
4967 znew = -znew;
4968 cache->uvwp[ip][2] = -cache->uvwp[ip][2];
4969 }
4970
4971 if (znew > zi) {
4972 znew = 2.0 * zi - znew;
4973 cache->uvwp[ip][2] = -cache->uvwp[ip][2];
4974 }
4975 }
4976
4977 /* Set pressure from reflected geometric height.
4978 This is more consistent than a linearized DZ2DP update for
4979 potentially large turbulent steps. */
4980 atm->p[ip] = P(zs + znew / 1000.0);
4981
4982 /* Enforce exact pressure limits of the local PBL column. */
4983 atm->p[ip] = CLAMP(atm->p[ip], pbl, ps);
4984 }
4985 }
4986}
#define KARMAN
Karman's constant.
Definition mptrac.h:280
#define CLAMP(v, lo, hi)
Clamp a value to a specified range.
Definition mptrac.h:758
#define THETAVIRT(p, t, h2o)
Compute virtual potential temperature.
Definition mptrac.h:2213
double dt_pbl
Maximum internal Hanna-PBL timestep [s] (default: 2 s).
Definition mptrac.h:3112
Here is the call graph for this function:

◆ module_diff_turb()

void module_diff_turb ( const ctl_t * ctl,
cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Applies turbulent diffusion processes to atmospheric particles.

This function calculates and applies turbulent diffusion effects, including horizontal and vertical diffusion, as well as vertical mixing in the planetary boundary layer (PBL), to a set of atmospheric particles based on input parameters and environmental conditions.

Parameters
[in]ctlPointer to the control structure containing simulation parameters.
[in,out]cachePointer to the cache structure for temporary data and random numbers.
[in]climPointer to the climate structure containing climatological data.
[in,out]met0Pointer to the meteorological data structure for the initial timestep.
[in,out]met1Pointer to the meteorological data structure for the next timestep.
[in,out]atmPointer to the atmospheric structure containing particle data.

The function performs the following operations:

  • Allocates temporary arrays for random number generation.
  • Generates random numbers for simulating diffusion effects.
  • Loops over atmospheric particles to compute and apply:
    • Horizontal turbulent diffusion, based on prescribed diffusivity values.
    • Vertical turbulent diffusion, using vertical diffusivity values.
  • Cleans up allocated resources after processing.

Turbulent diffusivity parameters are derived from control inputs and weighted based on atmospheric layer influences (PBL, troposphere, stratosphere).

Note
  • Control parameters TURB_DX_PBL, TURB_DX_TROP, TURB_DX_STRAT, TURB_DZ_PBL, TURB_DZ_TROP, and TURB_DZ_STRAT define horizontal and vertical diffusivities (in units of m**2 s**-1) in the PBL, troposphere, and stratosphere, respectively.
  • Control parameter TURB_PBL_SCHEME activates an optional PBL-specific closure scheme. If a PBL scheme is active, the fixed-K module is only applied outside the PBL.
  • Apply the following settings to reproduce Stohl et al. (2005): TURB_DX_PBL = 50 TURB_DX_TROP = 50 TURB_DX_STRAT = 0 TURB_DZ_PBL = 0 TURB_DZ_TROP = 0 TURB_DZ_STRAT = 0.1 TURB_MESOX = 0.16 TURB_MESOZ = 0.16 TURB_PBL_SCHEME = 0
  • Apply the following setting to reproduce Maryon et al. (1991) and Ryall et al. (1998): TURB_DX_PBL = 5300 TURB_DX_TROP = 1325 TURB_DX_STRAT = 1325 TURB_DZ_PBL = 0 TURB_DZ_TROP = 1.5 TURB_DZ_STRAT = 1.5 TURB_MESOX = 0 TURB_MESOZ = 0 TURB_PBL_SCHEME = 1
Author
Lars Hoffmann

Definition at line 4990 of file mptrac.c.

4996 {
4997
4998 /* Set timer... */
4999 SELECT_TIMER("MODULE_DIFF_TURB", "PHYSICS");
5000
5001 /* Create random numbers... */
5002 module_rng(ctl, cache->rs, 3 * (size_t) atm->np, 1);
5003
5004 /* Loop over particles... */
5005 PARTICLE_LOOP(0, atm->np, 1,
5006 "acc data present(ctl,cache,clim,met0,met1,atm)") {
5007
5008 /* Get PBL pressure... */
5009 double pbl;
5011 INTPOL_2D(pbl, 1);
5012
5013 /* Let optional PBL closure schemes handle turbulent diffusion inside the PBL. */
5014 if (ctl->turb_pbl_scheme > 0 && atm->p[ip] >= pbl)
5015 continue;
5016
5017 /* Get surface pressure... */
5018 double ps;
5019 INTPOL_2D(ps, 0);
5020
5021 /* Pressure at model top [hPa]. */
5022 const double ptop = met0->p[met0->np - 1];
5023
5024 /* A valid PBL top is required for the reflective Hanna partition. */
5025 if (ctl->turb_pbl_scheme == 1
5026 && !(isfinite(ps) && isfinite(pbl) && ps > pbl
5027 && pbl > ptop && ptop > 0.0))
5028 continue;
5029
5030 /* Get weighting factors at current particle position... */
5031 const double wpbl = pbl_weight(ctl, atm, ip, pbl, ps);
5032 const double wtrop = tropo_weight(ctl, clim, atm, ip) * (1.0 - wpbl);
5033 const double wstrat = 1.0 - wpbl - wtrop;
5034
5035 /* Set diffusivities [m2/s]... */
5036 const double Kx =
5037 wpbl * ctl->turb_dx_pbl
5038 + wtrop * ctl->turb_dx_trop + wstrat * ctl->turb_dx_strat;
5039
5040 const double Kz =
5041 wpbl * ctl->turb_dz_pbl
5042 + wtrop * ctl->turb_dz_trop + wstrat * ctl->turb_dz_strat;
5043
5044 /* Set time step... */
5045 const double dt_abs = fabs(cache->dt[ip]);
5046
5047 /* Horizontal turbulent diffusion...
5048 Kx [m2/s], dt [s] => sigma_h [m]. */
5049 if (Kx > 0) {
5050 const double sigma_h = sqrt(2.0 * Kx * dt_abs);
5051
5052 atm->lon[ip] +=
5053 DX2COORD(met0, cache->rs[3 * ip] * sigma_h, atm->lat[ip]);
5054
5055 atm->lat[ip] += DY2COORD(met0, cache->rs[3 * ip + 1] * sigma_h);
5056 }
5057
5058 /* Vertical turbulent diffusion... */
5059 if (Kz > 0) {
5060
5061 /* Random displacement:
5062 Kz [m2/s], dt [s] => sigma_z [m], converted to [km]. */
5063 const double sigma_z = sqrt(2.0 * Kz * dt_abs) * 1e-3;
5064
5065 /* Save current pressure because pbl_weight() and tropo_weight()
5066 use atm->p[ip]. */
5067 const double p_save = atm->p[ip];
5068
5069 /* Estimate dKz/dz by centered finite difference.
5070 eps_km = 0.01 km = 10 m.
5071 Positive z is upward; therefore p_up < p_save and p_dn > p_save. */
5072 const double eps_km = 0.01;
5073 const double p_up = p_save + DZ2DP(eps_km, p_save);
5074 const double p_dn = p_save + DZ2DP(-eps_km, p_save);
5075
5076 /* Kz above... */
5077 atm->p[ip] = MAX(ptop, MIN(ps, p_up));
5078 const double wpbl_up = pbl_weight(ctl, atm, ip, pbl, ps);
5079 const double wtrop_up =
5080 tropo_weight(ctl, clim, atm, ip) * (1.0 - wpbl_up);
5081 const double wstrat_up = 1.0 - wpbl_up - wtrop_up;
5082
5083 const double Kz_up =
5084 wpbl_up * ctl->turb_dz_pbl
5085 + wtrop_up * ctl->turb_dz_trop + wstrat_up * ctl->turb_dz_strat;
5086
5087 /* Kz below... */
5088 atm->p[ip] = MAX(ptop, MIN(ps, p_dn));
5089 const double wpbl_dn = pbl_weight(ctl, atm, ip, pbl, ps);
5090 const double wtrop_dn =
5091 tropo_weight(ctl, clim, atm, ip) * (1.0 - wpbl_dn);
5092 const double wstrat_dn = 1.0 - wpbl_dn - wtrop_dn;
5093
5094 const double Kz_dn =
5095 wpbl_dn * ctl->turb_dz_pbl
5096 + wtrop_dn * ctl->turb_dz_trop + wstrat_dn * ctl->turb_dz_strat;
5097
5098 /* Restore current pressure... */
5099 atm->p[ip] = p_save;
5100
5101 /* Well-mixed drift:
5102 w_drift = dKz/dz + Kz * dlnrho/dz
5103
5104 Units:
5105 dKz_dz [m2/s] / [m] = [m/s]
5106 dlnrho_dz [1/m]
5107 Kz*dlnrho [m2/s] * [1/m] = [m/s]
5108 dz_drift [m/s] * [s] * 1e-3 = [km]
5109
5110 With exponential atmosphere rho ~ exp(-z/H0):
5111 dlnrho/dz = -1 / (1000 * H0)
5112 because H0 is in [km]. */
5113 const double dKz_dz = (Kz_up - Kz_dn) / (2.0 * eps_km * 1e3);
5114 const double dlnrho_dz = -1.0 / (1e3 * H0);
5115 const double w_drift = dKz_dz + Kz * dlnrho_dz;
5116 const double dz_drift = w_drift * dt_abs * 1e-3;
5117
5118 /* Total vertical displacement [km]. */
5119 const double dz_tot = cache->rs[3 * ip + 2] * sigma_z + dz_drift;
5120
5121 /* Update particle pressure... */
5122 double ptrial = p_save + DZ2DP(dz_tot, p_save);
5123
5124 /* Keep Fixed-K particles that started above the PBL above its top.
5125 Fold the trial height into [z_PBL, z_model_top] so even large
5126 displacements undergo all required reflections. */
5127 if (ctl->turb_pbl_scheme == 1) {
5128 if (!(ptrial < pbl && ptrial >= ptop)) {
5129 const double z_pbl = Z(pbl);
5130 const double height = Z(ptop) - z_pbl;
5131 double z_rel = fmod(Z(p_save) + dz_tot - z_pbl, 2.0 * height);
5132 if (z_rel < 0.0)
5133 z_rel += 2.0 * height;
5134 if (z_rel > height)
5135 z_rel = 2.0 * height - z_rel;
5136 ptrial = MIN(P(z_pbl + z_rel), nextafter(pbl, 0.0));
5137 }
5138 } else {
5139 /* Reflect at surface and model top.
5140 The transformation p -> pb^2 / p corresponds to reflection in
5141 logarithmic pressure / approximate height coordinates. Use repeated
5142 reflection for robustness in case a large random step crosses more
5143 than one boundary. */
5144 for (int iter = 0; iter < 10; iter++) {
5145 if (ptrial > ps)
5146 ptrial = ps * ps / ptrial;
5147 else if (ptrial < ptop)
5148 ptrial = ptop * ptop / ptrial;
5149 else
5150 break;
5151 }
5152 }
5153
5154 /* Final safety clamp in case of an exceptionally large displacement... */
5155 atm->p[ip] = MAX(ptop, MIN(ps, ptrial));
5156 }
5157 }
5158}
double pbl_weight(const ctl_t *ctl, const atm_t *atm, const int ip, const double pbl, const double ps)
Computes a weighting factor based on planetary boundary layer pressure.
Definition mptrac.c:9365
#define DZ2DP(dz, p)
Convert a change in altitude to a change in pressure.
Definition mptrac.h:943
double turb_dz_trop
Vertical turbulent diffusion coefficient (troposphere) [m^2/s].
Definition mptrac.h:3127
double turb_dx_strat
Horizontal turbulent diffusion coefficient (stratosphere) [m^2/s].
Definition mptrac.h:3121
double turb_dx_trop
Horizontal turbulent diffusion coefficient (troposphere) [m^2/s].
Definition mptrac.h:3118
int turb_pbl_scheme
PBL turbulence scheme (0=none, 1=closure).
Definition mptrac.h:3109
double turb_dx_pbl
Horizontal turbulent diffusion coefficient (PBL) [m^2/s].
Definition mptrac.h:3115
double turb_dz_strat
Vertical turbulent diffusion coefficient (stratosphere) [m^2/s].
Definition mptrac.h:3130
double turb_dz_pbl
Vertical turbulent diffusion coefficient (PBL) [m^2/s].
Definition mptrac.h:3124
Here is the call graph for this function:

◆ module_dry_depo()

void module_dry_depo ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Simulate dry deposition of atmospheric particles.

Mode 1 uses a prescribed deposition velocity; mode 2 calculates aerosol velocity with sedi() from particle pressure, temperature, radius, and density. Within the geometric surface layer, mass and volume mixing ratio follow exponential loss using each particle's signed timestep. Negative timesteps mathematically reverse the loss. Invalid local surface pressure leaves the particle unchanged.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the meteorological data structure at the current time step.
met1Pointer to the meteorological data structure at the next time step.
atmPointer to the atmospheric data structure containing particle information.
Author
Lars Hoffmann

Definition at line 5162 of file mptrac.c.

5167 {
5168
5169 /* Set timer... */
5170 SELECT_TIMER("MODULE_DRY_DEPO", "PHYSICS");
5171
5172 /* Check quantity flags... */
5173 if (ctl->qnt_m < 0 && ctl->qnt_vmr < 0)
5174 ERRMSG("Module needs quantity mass or volume mixing ratio!");
5175
5176 const double p_factor = exp(-ctl->dry_depo_dz / (1000. * H0));
5177
5178 /* Loop over particles... */
5179 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
5180
5181 /* Get surface pressure... */
5182 double ps;
5184 INTPOL_2D(ps, 1);
5185 if (!isfinite(ps) || ps <= 0.)
5186 continue;
5187
5188 /* Check whether particle is above the surface layer... */
5189 if (atm->p[ip] < ps * p_factor)
5190 continue;
5191
5192 /* Calculate aerosol deposition velocity... */
5193 double v_dep;
5194 if (ctl->dry_depo_mode == 2) {
5195
5196 /* Get temperature... */
5197 double t;
5198 INTPOL_3D(t, 1);
5199
5200 /* Set deposition velocity... */
5201 v_dep = sedi(atm->p[ip], t, atm->q[ctl->qnt_rp][ip],
5202 atm->q[ctl->qnt_rhop][ip]);
5203 if (!isfinite(v_dep) || v_dep <= 0.)
5204 continue;
5205 }
5206
5207 /* Use prescribed deposition velocity... */
5208 else
5209 v_dep = ctl->dry_depo_vdep;
5210
5211 /* Calculate loss of mass based on deposition velocity... */
5212 const double aux = exp(-cache->dt[ip] * v_dep / ctl->dry_depo_dz);
5213 if (ctl->qnt_m >= 0) {
5214 if (ctl->qnt_mloss_dry >= 0)
5215 atm->q[ctl->qnt_mloss_dry][ip]
5216 += atm->q[ctl->qnt_m][ip] * (1 - aux);
5217 atm->q[ctl->qnt_m][ip] *= aux;
5218 if (ctl->qnt_loss_rate >= 0)
5219 atm->q[ctl->qnt_loss_rate][ip] += v_dep / ctl->dry_depo_dz;
5220 }
5221 if (ctl->qnt_vmr >= 0)
5222 atm->q[ctl->qnt_vmr][ip] *= aux;
5223 }
5224}
double sedi(const double p, const double T, const double rp, const double rhop)
Calculates the sedimentation velocity of a particle in air.
Definition mptrac.c:13843
double dry_depo_dz
Geometric dry-deposition layer thickness above the surface [m].
Definition mptrac.h:3364
int qnt_rhop
Quantity array index for particle density.
Definition mptrac.h:2597
int qnt_rp
Quantity array index for particle radius.
Definition mptrac.h:2594
int qnt_mloss_dry
Quantity array index for total mass loss due to dry deposition.
Definition mptrac.h:2741
double dry_depo_vdep
Prescribed dry deposition velocity for mode 1 [m/s].
Definition mptrac.h:3367
int dry_depo_mode
Dry deposition mode: 0=off, 1=prescribed velocity, 2=aerosol velocity.
Definition mptrac.h:3361
Here is the call graph for this function:

◆ module_h2o2_chem()

void module_h2o2_chem ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Apply aqueous H2O2 oxidation of SO2 in liquid cloud water.

This function reduces the transported SO2 mass or VMR using a pseudo-first-order aqueous oxidation rate. It uses prescribed H2O2 climatology, SO2 solubility and dissociation, and liquid cloud and rain water. H2O2 itself is not updated.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climatological data structure.
met0Pointer to the first meteorological data structure.
met1Pointer to the second meteorological data structure.
atmPointer to the atmospheric data structure containing particle information.
Note
The function assumes that the necessary control structure (ctl), climatological data structure (clim), meteorological data structures (met0, met1), and atmospheric data structure (atm) have been initialized and are accessible.
Positive liquid cloud water or rain water activates this SO2-specific approximation. Its optional high-concentration correction uses the dimensionless SO2 mole fraction stored in Cx.
The aqueous reaction coefficient uses k(T) = k(298.15 K) exp[-E/R (1/T - 1/298.15 K)].
If the particle has a quantity flag for either mass (ctl->qnt_m) or volume mixing ratio (ctl->qnt_vmr), the function updates the quantity based on the exponential decay.
If the particle has a loss rate quantity flag (ctl->qnt_loss_rate), the function accumulates the reaction rate coefficient to quantify the loss rate.
Author
Mingzhao Liu

Definition at line 5228 of file mptrac.c.

5234 {
5235
5236 if (ctl->met_coord_type != 0)
5237 ERRMSG("Only lat/lon grid supported");
5238
5239 /* Set timer... */
5240 SELECT_TIMER("MODULE_H2O2_CHEM", "PHYSICS");
5241
5242 /* Check quantity flags... */
5243 if (ctl->qnt_m < 0 && ctl->qnt_vmr < 0)
5244 ERRMSG("Module needs quantity mass or volume mixing ratio!");
5245
5246 /* Parameter of SO2 correction... */
5247 const double low = pow(1. / SO2_CORR_A, 1. / SO2_CORR_B);
5248 const int so2_correction = ctl->qnt_Cx >= 0
5249 && (ctl->species[0] == '-' || strcasecmp(ctl->species, "SO2") == 0);
5250
5251 /* Loop over particles... */
5252 PARTICLE_LOOP(0, atm->np, 1,
5253 "acc data present(ctl,cache,clim,met0,met1,atm)") {
5254
5255 /* Check whether particle is inside cloud... */
5256 double lwc, rwc;
5258 INTPOL_3D(lwc, 1);
5259 INTPOL_3D(rwc, 0);
5260 if (!isfinite(lwc) || !isfinite(rwc) || lwc < 0 || rwc < 0)
5261 continue;
5262 if (!(lwc > 0 || rwc > 0))
5263 continue;
5264
5265 /* Get temperature... */
5266 double t;
5267 INTPOL_3D(t, 0);
5268 if (!isfinite(t) || t <= 0)
5269 continue;
5270
5271 /* Get molecular density... */
5272 const double M = MOLEC_DENS(atm->p[ip], t);
5273 if (!isfinite(M) || M <= 0)
5274 continue;
5275
5276 /* Reaction rate (Berglen et al., 2004)... */
5277 const double k = H2O2_SO2_RATE_REF * exp(-H2O2_SO2_RATE_TEMP / RI * (1. / t - 1. / CHEM_REF_TEMP)); /* Maass (1999), M^(-2) */
5278
5279 /* Henry constant of SO2... */
5280 const double H_SO2 =
5282 * (1. / t - 1. / CHEM_REF_TEMP)) * RI * t;
5283 const double K_1S = SO2_DISS_K1_REF * exp(SO2_DISS_K1_TEMP * (1. / t - 1. / CHEM_REF_TEMP)); /* unit: mol/L */
5284
5285 /* Henry constant of H2O2... */
5286 const double H_h2o2 =
5288 * (1. / t - 1. / CHEM_REF_TEMP)) * RI * t;
5289
5290 /* Apply plume correction for Cx with SO2 or unspecified species... */
5291 double cor = 1.0;
5292 if (so2_correction) {
5293 if (!isfinite(atm->q[ctl->qnt_Cx][ip]))
5294 continue;
5295 cor = atm->q[ctl->qnt_Cx][ip] >
5296 low ? SO2_CORR_A * pow(atm->q[ctl->qnt_Cx][ip], SO2_CORR_B) : 1;
5297 }
5298
5299 /* Convert climatological H2O2 to dissolved concentration [mol/L]... */
5300 const double h2o2_vmr =
5301 clim_zm(&clim->h2o2, atm->time[ip], atm->lat[ip], atm->p[ip]);
5302 if (!isfinite(h2o2_vmr) || h2o2_vmr < 0)
5303 continue;
5304 const double h2o2 = H_h2o2 * h2o2_vmr
5305 * M * cor * 1000. / AVO; /* unit: mol/L */
5306
5307 /* Volume water content in cloud [m^3 m^(-3)]... */
5308 const double rho_air = atm->p[ip] / (RI * t) * MA / 10.;
5309 const double CWC = (lwc + rwc) * rho_air / 1e3;
5310
5311 /* Calculate exponential decay (Rolph et al., 1992)... */
5312 const double rate_coef = k * K_1S * h2o2 * H_SO2 * CWC;
5313 if (!isfinite(rate_coef) || rate_coef < 0)
5314 continue;
5315 const double aux = exp(-cache->dt[ip] * rate_coef);
5316 if (!isfinite(aux))
5317 continue;
5318 if (ctl->qnt_m >= 0) {
5319 if (ctl->qnt_mloss_h2o2 >= 0)
5320 atm->q[ctl->qnt_mloss_h2o2][ip] += atm->q[ctl->qnt_m][ip] * (1 - aux);
5321 atm->q[ctl->qnt_m][ip] *= aux;
5322 if (ctl->qnt_loss_rate >= 0)
5323 atm->q[ctl->qnt_loss_rate][ip] += rate_coef;
5324 }
5325 if (ctl->qnt_vmr >= 0)
5326 atm->q[ctl->qnt_vmr][ip] *= aux;
5327 }
5328}
#define SO2_CORR_B
Exponent of the high-SO2 correction [1].
Definition mptrac.h:385
#define MOLEC_DENS(p, t)
Calculate the molecular number density of air.
Definition mptrac.h:1541
#define SO2_DISS_K1_REF
First SO2 dissociation constant at CHEM_REF_TEMP [mol/L].
Definition mptrac.h:430
#define SO2_DISS_K1_TEMP
Temperature dependence of the first SO2 dissociation constant [K].
Definition mptrac.h:435
#define H2O2_HENRY_TEMP
Temperature dependence of the H2O2 Henry constant [K].
Definition mptrac.h:375
#define SO2_CORR_A
Scale factor of the high-SO2 correction for fractional SO2 mole fraction.
Definition mptrac.h:380
#define H2O2_SO2_RATE_REF
Reference rate for aqueous H2O2-SO2 chemistry [L^2/(mol^2 s)].
Definition mptrac.h:350
#define H2O2_SO2_RATE_TEMP
Temperature parameter for the aqueous H2O2-SO2 rate [K].
Definition mptrac.h:355
#define H2O2_HENRY_REF
H2O2 Henry constant at CHEM_REF_TEMP [mol/(m^3 Pa)].
Definition mptrac.h:370
#define CHEM_REF_TEMP
Reference temperature for chemical equilibrium constants [K].
Definition mptrac.h:345
#define SO2_HENRY_REF
SO2 Henry constant at CHEM_REF_TEMP [mol/(m^3 Pa)].
Definition mptrac.h:360
#define SO2_HENRY_TEMP
Temperature dependence of the SO2 Henry constant [K].
Definition mptrac.h:365
char species[LEN]
Species.
Definition mptrac.h:3193
int qnt_mloss_h2o2
Quantity array index for total mass loss due to H2O2 chemistry.
Definition mptrac.h:2732
Here is the call graph for this function:

◆ module_isosurf_init()

void module_isosurf_init ( const ctl_t * ctl,
cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm,
const int initial,
const double model_t )

Initialize the isosurface module based on atmospheric data.

This function initializes the isosurface module based on the atmospheric data provided. It calculates the reference pressure, density, or potential temperature at particle release. A reference may be saved before first activation when the loaded meteorological pair brackets the release time. Additionally, it can read balloon pressure data from a file if specified in the control structure. For modes 1-3 the reference is stored in the iso_var particle quantity; mode 4 stores a shared pressure series in the cache.

Parameters
ctlPointer to the control structure containing simulation parameters.
met0Pointer to the meteorological data structure at the current time step.
met1Pointer to the meteorological data structure at the next time step.
atmPointer to the atmospheric data structure containing particle information.
cachePointer to the cache structure for the shared balloon series.
initialWhether this is the initial model step (before timesteps are set).
model_tCurrent model time [s].
Author
Lars Hoffmann

Definition at line 5332 of file mptrac.c.

5339 {
5340
5341 /* Set timer... */
5342 SELECT_TIMER("MODULE_ISOSURF_INIT", "PHYSICS");
5343
5344 /* Save pressure... */
5345 if (ctl->isosurf == 1) {
5346 PARTICLE_LOOP(0, atm->np, 0, "acc data present(ctl,atm)") {
5347 atm->q[ctl->qnt_iso_var][ip] = atm->p[ip];
5348 }
5349 }
5350
5351 /* Save each density or potential-temperature reference at release time. */
5352 else if (ctl->isosurf == 2 || ctl->isosurf == 3) {
5353 int outside = 0;
5354 double next_t = model_t + ctl->direction * ctl->dt_mod;
5355 if (ctl->direction * (next_t - ctl->t_stop) > 0)
5356 next_t = ctl->t_stop;
5357 const int crossing =
5358 ctl->direction > 0 ? next_t > met1->time : next_t < met0->time;
5359#ifdef _OPENACC
5360#pragma acc parallel loop present(ctl,cache,met0,met1,atm) reduction(+:outside)
5361#else
5362#pragma omp parallel for reduction(+:outside)
5363#endif
5364 for (int ip = 0; ip < atm->np; ip++) {
5365 if (cache->iso_init[ip] == 1)
5366 continue;
5367 /* Promote a reference captured before release when transport starts. */
5368 if (cache->iso_init[ip] == 2) {
5369 if (!initial && cache->dt[ip] != 0)
5370 cache->iso_init[ip] = 1;
5371 continue;
5372 }
5373 if (initial) {
5374 if (ctl->direction * (atm->time[ip] - ctl->t_start) > 0)
5375 continue;
5376 } else if (cache->dt[ip] == 0) {
5377 /* Keep the release-time reference before a met-file boundary passes. */
5378 if (!crossing || ctl->direction * (atm->time[ip] - model_t) < 0
5379 || ctl->direction * (atm->time[ip] - next_t) >= 0
5380 || atm->time[ip] < met0->time || atm->time[ip] > met1->time)
5381 continue;
5382 }
5383 if (!initial &&
5384 (atm->time[ip] < met0->time || atm->time[ip] > met1->time)) {
5385 outside++;
5386 continue;
5387 }
5388 double t;
5390 INTPOL_3D(t, 1);
5391 if (ctl->isosurf == 2)
5392 atm->q[ctl->qnt_iso_var][ip] = atm->p[ip] / t;
5393 else
5394 atm->q[ctl->qnt_iso_var][ip] = THETA(atm->p[ip], t);
5395 cache->iso_init[ip] = (!initial && cache->dt[ip] == 0) ? 2 : 1;
5396 }
5397 if (outside)
5398 ERRMSG("Particle release time is outside the loaded meteorological interval for ISOSURF!");
5399 }
5400
5401 /* Read balloon pressure data... */
5402 else if (ctl->isosurf == 4) {
5403
5404 /* Write info... */
5405 LOG(1, "Read balloon pressure data: %s", ctl->balloon);
5406
5407 /* Open file... */
5408 FILE *in;
5409 if (!(in = fopen(ctl->balloon, "r")))
5410 ERRMSG("Cannot open file!");
5411
5412 /* Read pressure time series... */
5413 char line[LEN];
5414 cache->iso_n = 0;
5415 while (fgets(line, LEN, in)) {
5416 double ts, ps;
5417 if (sscanf(line, "%lg %lg", &ts, &ps) != 2)
5418 continue;
5419 if (cache->iso_n >= NP)
5420 ERRMSG("Too many balloon pressure data points!");
5421 if (!isfinite(ts) || !isfinite(ps) || ps <= 0)
5422 ERRMSG("Balloon times must be finite and pressures must be finite and positive!");
5423 if (cache->iso_n > 0 && ts <= cache->iso_ts[cache->iso_n - 1])
5424 ERRMSG("Balloon times must be strictly increasing!");
5425 cache->iso_ts[cache->iso_n] = ts;
5426 cache->iso_ps[cache->iso_n] = ps;
5427 cache->iso_n++;
5428 }
5429
5430 /* Check number of points... */
5431 if (cache->iso_n < 1)
5432 ERRMSG("Could not read any data!");
5433
5434 /* Close file... */
5435 fclose(in);
5436
5437 /* Update of cache data on device... */
5438 mptrac_update_device(NULL, cache, NULL, NULL, NULL, NULL);
5439 }
5440}
void mptrac_update_device(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t **met0, met_t **met1, const atm_t *atm)
Updates device memory for specified data structures.
Definition mptrac.c:8991
double iso_ts[NP]
Shared balloon times [s] for ISOSURF=4.
Definition mptrac.h:3732
int iso_n
Isosurface balloon number of data points.
Definition mptrac.h:3735
double iso_ps[NP]
Shared balloon pressure time series [hPa] for ISOSURF=4.
Definition mptrac.h:3729
int direction
Direction flag (1=forward calculation, -1=backward calculation).
Definition mptrac.h:2892
char balloon[LEN]
Balloon position filename.
Definition mptrac.h:3093
int isosurf
Isosurface parameter (0=none, 1=pressure, 2=density, 3=theta, 4=balloon).
Definition mptrac.h:3090
double t_stop
Stop time of simulation [s].
Definition mptrac.h:2898
double t_start
Start time of simulation [s].
Definition mptrac.h:2895
int qnt_iso_var
Quantity array index for isosurface reference (units depend on ISOSURF).
Definition mptrac.h:2771
Here is the call graph for this function:

◆ module_isosurf()

void module_isosurf ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Apply the isosurface module to adjust atmospheric properties.

This function applies the isosurface module to adjust atmospheric properties based on the initialized particle quantity or balloon cache. It interpolates and restores atmospheric pressure, density, or potential temperature according to the specified isosurface mode in the control structure.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the meteorological data structure at the current time step.
met1Pointer to the meteorological data structure at the next time step.
atmPointer to the atmospheric data structure containing particle information.
Author
Lars Hoffmann

Definition at line 5444 of file mptrac.c.

5449 {
5450
5451 /* Set timer... */
5452 SELECT_TIMER("MODULE_ISOSURF", "PHYSICS");
5453
5454 /* Loop over particles... */
5455 PARTICLE_LOOP(0, atm->np, 0, "acc data present(ctl,cache,met0,met1,atm)") {
5456
5457 if ((ctl->isosurf == 2 || ctl->isosurf == 3)
5458 && cache->iso_init[ip] != 1)
5459 continue;
5460
5461 /* Init... */
5462 double t;
5464
5465 /* Restore pressure... */
5466 if (ctl->isosurf == 1)
5467 atm->p[ip] = atm->q[ctl->qnt_iso_var][ip];
5468
5469 /* Restore density... */
5470 else if (ctl->isosurf == 2) {
5471 INTPOL_3D(t, 1);
5472 atm->p[ip] = atm->q[ctl->qnt_iso_var][ip] * t;
5473 }
5474
5475 /* Restore potential temperature... */
5476 else if (ctl->isosurf == 3) {
5477 INTPOL_3D(t, 1);
5478 atm->p[ip] = 1000. * pow(atm->q[ctl->qnt_iso_var][ip] / t, -1. / KAPPA);
5479 }
5480
5481 /* Interpolate pressure... */
5482 else if (ctl->isosurf == 4) {
5483 if (atm->time[ip] <= cache->iso_ts[0])
5484 atm->p[ip] = cache->iso_ps[0];
5485 else if (atm->time[ip] >= cache->iso_ts[cache->iso_n - 1])
5486 atm->p[ip] = cache->iso_ps[cache->iso_n - 1];
5487 else {
5488 const int idx =
5489 locate_irr(cache->iso_ts, cache->iso_n, atm->time[ip]);
5490 atm->p[ip] =
5491 LIN(cache->iso_ts[idx], cache->iso_ps[idx], cache->iso_ts[idx + 1],
5492 cache->iso_ps[idx + 1], atm->time[ip]);
5493 }
5494 }
5495 }
5496}
Here is the call graph for this function:

◆ module_kpp_chem()

void module_kpp_chem ( ctl_t * ctl,
cache_t * cache,
clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

KPP chemistry module.

Simulate chemical reactions using the Kinetic PreProcessor (KPP) integration scheme.

This function simulates chemical reactions using the Kinetic PreProcessor (KPP) integration scheme for atmospheric particles. It loops over each particle in the atmospheric data structure and integrates chemical reactions over a specified time step using the KPP algorithm.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climatological data structure.
met0Pointer to the first meteorological data structure.
met1Pointer to the second meteorological data structure.
atmPointer to the atmospheric data structure containing particle information.
Note
The function initializes a timer to measure the execution time of the chemical simulation.
Particles with a zero individual time step are skipped. Other particles are integrated over ctl->dt_kpp, regardless of timestep sign or a release within the KPP interval.
KPP initialization converts mixing ratios to molecular number densities. Results are written back only after a successful solver step with a finite, nonnegative SO2 concentration.
Author
Mingzhao Liu

◆ module_meteo()

void module_meteo ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Update atmospheric properties using meteorological data.

This function updates atmospheric properties based on meteorological data interpolated between two time steps. It calculates various atmospheric quantities such as pressure, temperature, wind speed, humidity, etc., and updates the corresponding fields in the atmospheric data structure.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climate data structure containing climatological data.
met0Pointer to the meteorological data structure at the current time step.
met1Pointer to the meteorological data structure at the next time step.
atmPointer to the atmospheric data structure containing particle information.
Author
Lars Hoffmann

Definition at line 5559 of file mptrac.c.

5565 {
5566
5567 /* Set timer... */
5568 SELECT_TIMER("MODULE_METEO", "PHYSICS");
5569
5570 /* Check quantity flags... */
5571 if (ctl->qnt_tsts >= 0)
5572 if (ctl->qnt_tice < 0 || ctl->qnt_tnat < 0)
5573 ERRMSG("Need T_ice and T_NAT to calculate T_STS!");
5574
5575 /* Loop over particles... */
5576 PARTICLE_LOOP(0, atm->np, 0,
5577 "acc data present(ctl,cache,clim,met0,met1,atm)") {
5578
5579 double ps, ts, zs, us, vs, ess, nss, shf, lsm, sst, pbl, pt, pct, pcb,
5580 cl, plcl, plfc, pel, cape, cin, o3c, pv, t, tt, u, v, w, h2o, h2ot,
5581 o3, lwc, rwc, iwc, swc, cc, z, zt, eta_d = 0, wdot = 0;
5582
5583 /* Interpolate meteo data... */
5585 INTPOL_TIME_ALL(atm->time[ip], atm->p[ip], atm->lon[ip], atm->lat[ip]);
5586
5587 /* Diagnose eta coordinate on native model levels... */
5588 if (ctl->qnt_eta_d >= 0)
5589 intpol_met_4d_zeta(met0, met0->pl, met0->zetal,
5590 met1, met1->pl, met1->zetal,
5591 atm->time[ip], atm->p[ip], atm->lon[ip],
5592 atm->lat[ip], &eta_d, ci, cw, 1);
5593
5594 /* Interpolate vertical velocity on native model levels... */
5595 if ((ctl->advect_vert_coord == 1 && ctl->qnt_zeta_dot >= 0)
5596 || (ctl->advect_vert_coord == 3 && ctl->qnt_eta_dot >= 0))
5597 intpol_met_4d_zeta(met0, met0->pl, met0->zeta_dotl,
5598 met1, met1->pl, met1->zeta_dotl,
5599 atm->time[ip], atm->p[ip], atm->lon[ip],
5600 atm->lat[ip], &wdot, ci, cw, 1);
5601
5602 /* Set quantities... */
5603 SET_ATM(qnt_ps, ps);
5604 SET_ATM(qnt_ts, ts);
5605 SET_ATM(qnt_zs, zs);
5606 SET_ATM(qnt_us, us);
5607 SET_ATM(qnt_vs, vs);
5608 SET_ATM(qnt_ess, ess);
5609 SET_ATM(qnt_nss, nss);
5610 SET_ATM(qnt_shf, shf);
5611 SET_ATM(qnt_lsm, lsm);
5612 SET_ATM(qnt_sst, sst);
5613 SET_ATM(qnt_pbl, pbl);
5614 SET_ATM(qnt_pt, pt);
5615 SET_ATM(qnt_tt, tt);
5616 SET_ATM(qnt_zt, zt);
5617 SET_ATM(qnt_h2ot, h2ot);
5618 SET_ATM(qnt_zg, z);
5619 SET_ATM(qnt_p, atm->p[ip]);
5620 SET_ATM(qnt_t, t);
5621 SET_ATM(qnt_rho, RHO(atm->p[ip], t));
5622 SET_ATM(qnt_u, u);
5623 SET_ATM(qnt_v, v);
5624 SET_ATM(qnt_w, w);
5625 SET_ATM(qnt_h2o, h2o);
5626 SET_ATM(qnt_o3, o3);
5627 SET_ATM(qnt_lwc, lwc);
5628 SET_ATM(qnt_rwc, rwc);
5629 SET_ATM(qnt_iwc, iwc);
5630 SET_ATM(qnt_swc, swc);
5631 SET_ATM(qnt_cc, cc);
5632 SET_ATM(qnt_pct, pct);
5633 SET_ATM(qnt_pcb, pcb);
5634 SET_ATM(qnt_cl, cl);
5635 SET_ATM(qnt_plcl, plcl);
5636 SET_ATM(qnt_plfc, plfc);
5637 SET_ATM(qnt_pel, pel);
5638 SET_ATM(qnt_cape, cape);
5639 SET_ATM(qnt_cin, cin);
5640 SET_ATM(qnt_o3c, o3c);
5641
5642 /* Add prescribed chemical climatologies at the particle position... */
5643 const double lat_ref =
5644 ctl->met_coord_type == 0 ? atm->lat[ip] : ctl->met_utm_ref_lat;
5645 SET_ATM(qnt_hno3,
5646 clim_zm(&clim->hno3, atm->time[ip], lat_ref, atm->p[ip]));
5647 SET_ATM(qnt_oh, clim_oh(ctl, clim, atm->time[ip],
5648 atm->lon[ip], atm->lat[ip], atm->p[ip]));
5649 SET_ATM(qnt_h2o2, clim_zm(&clim->h2o2, atm->time[ip],
5650 lat_ref, atm->p[ip]));
5651 SET_ATM(qnt_ho2, clim_zm(&clim->ho2, atm->time[ip], lat_ref, atm->p[ip]));
5652 SET_ATM(qnt_o1d, clim_zm(&clim->o1d, atm->time[ip], lat_ref, atm->p[ip]));
5653
5654 /* Diagnose wind speed, vertical speed, and thermodynamic quantities... */
5655 SET_ATM(qnt_vh, sqrt(u * u + v * v));
5656 SET_ATM(qnt_vz, -1e3 * H0 / atm->p[ip] * w);
5657 SET_ATM(qnt_psat, PSAT(t));
5658 SET_ATM(qnt_psice, PSICE(t));
5659 SET_ATM(qnt_pw, PW(atm->p[ip], h2o));
5660 SET_ATM(qnt_sh, SH(h2o));
5661 SET_ATM(qnt_rh, RH(atm->p[ip], t, h2o));
5662 SET_ATM(qnt_rhice, RHICE(atm->p[ip], t, h2o));
5663 SET_ATM(qnt_theta, THETA(atm->p[ip], t));
5664 SET_ATM(qnt_zeta, atm->q[ctl->qnt_zeta][ip]);
5665 SET_ATM(qnt_zeta_d, ZETA(ps, atm->p[ip], t));
5666 SET_ATM(qnt_eta, atm->q[ctl->qnt_eta][ip]);
5667 SET_ATM(qnt_eta_d, eta_d);
5668 if (ctl->advect_vert_coord == 1) {
5669 SET_ATM(qnt_zeta_dot, wdot);
5670 } else if (ctl->advect_vert_coord == 3) {
5671 SET_ATM(qnt_eta_dot, wdot);
5672 }
5673 SET_ATM(qnt_tvirt, TVIRT(t, h2o));
5674 SET_ATM(qnt_lapse, lapse_rate(t, h2o));
5675 SET_ATM(qnt_pv, pv);
5676 SET_ATM(qnt_tdew, TDEW(atm->p[ip], h2o));
5677 SET_ATM(qnt_tice, TICE(atm->p[ip], h2o));
5678 SET_ATM(qnt_tnat,
5679 nat_temperature(atm->p[ip], h2o,
5680 clim_zm(&clim->hno3, atm->time[ip],
5681 atm->lat[ip], atm->p[ip])));
5682 SET_ATM(qnt_tsts,
5683 0.5 * (atm->q[ctl->qnt_tice][ip] + atm->q[ctl->qnt_tnat][ip]));
5684 }
5685}
double nat_temperature(const double p, const double h2o, const double hno3)
Calculates the nitric acid trihydrate (NAT) temperature.
Definition mptrac.c:9341
double lapse_rate(const double t, const double h2o)
Calculates the moist adiabatic lapse rate in Kelvin per kilometer.
Definition mptrac.c:3668
#define TICE(p, h2o)
Calculate frost point temperature (WMO, 2018).
Definition mptrac.h:2160
#define RHICE(p, t, h2o)
Compute relative humidity over ice.
Definition mptrac.h:1995
#define INTPOL_TIME_ALL(time, p, lon, lat)
Interpolate multiple meteorological variables in time.
Definition mptrac.h:1325
#define RH(p, t, h2o)
Compute relative humidity over water.
Definition mptrac.h:1965
#define TDEW(p, h2o)
Calculate dew point temperature.
Definition mptrac.h:2135
clim_zm_t hno3
HNO3 zonal means.
Definition mptrac.h:3914
int qnt_eta_d
Quantity array index for diagnosed eta vertical coordinate.
Definition mptrac.h:2786
int qnt_tnat
Quantity array index for T_NAT.
Definition mptrac.h:2816
int qnt_eta_dot
Quantity array index for velocity of eta vertical coordinate.
Definition mptrac.h:2789
int qnt_tice
Quantity array index for T_ice.
Definition mptrac.h:2810
int qnt_zeta_dot
Quantity array index for velocity of zeta vertical coordinate.
Definition mptrac.h:2780
int qnt_tsts
Quantity array index for T_STS.
Definition mptrac.h:2813
Here is the call graph for this function:

◆ module_mixing()

void module_mixing ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
atm_t * atm,
const double t )

Update atmospheric properties through interparcel mixing.

This function updates atmospheric properties by performing interparcel mixing based on the given meteorological and climatological data. It calculates the indices of grid boxes and performs mixing for various quantities such as mass, volume mixing ratio, and other chemical species concentrations. Only particles with nonzero individual time steps participate. Geographic mixing boxes are evaluated locally on each MPI rank.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure containing individual time steps.
climPointer to the climate data structure containing climatological data.
atmPointer to the atmospheric data structure containing particle information.
tTime at which mixing is performed.
Author
Mingzhao Liu
Lars Hoffmann

Definition at line 5689 of file mptrac.c.

5694 {
5695
5696 /* Set timer... */
5697 SELECT_TIMER("MODULE_MIXING", "PHYSICS");
5698
5699 if (atm->np == 0)
5700 return;
5701
5702 /* Allocate... */
5703 const int np = atm->np;
5704 int *restrict const ixs = (int *) malloc((size_t) np * sizeof(int));
5705 int *restrict const iys = (int *) malloc((size_t) np * sizeof(int));
5706 int *restrict const izs = (int *) malloc((size_t) np * sizeof(int));
5707 double *restrict const mixparam =
5708 (double *) malloc((size_t) np * sizeof(double));
5709 if (ixs == NULL || iys == NULL || izs == NULL || mixparam == NULL)
5710 ERRMSG("Out of memory!");
5711
5712 /* Set grid box size... */
5713 const double dz = (ctl->mixing_z1 - ctl->mixing_z0) / ctl->mixing_nz;
5714 const double dlon = (ctl->mixing_lon1 - ctl->mixing_lon0) / ctl->mixing_nx;
5715 const double dlat = (ctl->mixing_lat1 - ctl->mixing_lat0) / ctl->mixing_ny;
5716
5717 /* Set time interval... */
5718 const double t0 = t - 0.5 * ctl->dt_mod;
5719 const double t1 = t + 0.5 * ctl->dt_mod;
5720 const double dt_mix = ctl->mixing_dt > 0 ? ctl->mixing_dt : ctl->dt_mod;
5721
5722 /* Select active particles and calculate their local mixing fractions... */
5723#ifdef _OPENACC
5724#pragma acc enter data create(ixs[0:np],iys[0:np],izs[0:np],mixparam[0:np])
5725#pragma acc data present(ctl,cache,clim,atm,ixs,iys,izs,mixparam)
5726#pragma acc parallel loop independent gang vector
5727#else
5728#pragma omp parallel for default(shared)
5729#endif
5730 for (int ip = 0; ip < np; ip++) {
5731 if (cache->dt[ip] == 0) {
5732 izs[ip] = -1;
5733 continue;
5734 }
5735 const double zpart = Z(atm->p[ip]);
5736 if (atm->time[ip] < t0 || atm->time[ip] > t1
5737 || atm->lon[ip] < ctl->mixing_lon0
5738 || atm->lon[ip] >= ctl->mixing_lon1
5739 || atm->lat[ip] < ctl->mixing_lat0
5740 || atm->lat[ip] >= ctl->mixing_lat1
5741 || zpart < ctl->mixing_z0 || zpart >= ctl->mixing_z1) {
5742 izs[ip] = -1;
5743 continue;
5744 }
5745 ixs[ip] = (int) ((atm->lon[ip] - ctl->mixing_lon0) / dlon);
5746 iys[ip] = (int) ((atm->lat[ip] - ctl->mixing_lat0) / dlat);
5747 izs[ip] = (int) ((zpart - ctl->mixing_z0) / dz);
5748 if (ixs[ip] >= ctl->mixing_nx || iys[ip] >= ctl->mixing_ny
5749 || izs[ip] >= ctl->mixing_nz) {
5750 izs[ip] = -1;
5751 continue;
5752 }
5753 const double w = tropo_weight(ctl, clim, atm, ip);
5754 const double rate =
5755 w / ctl->mixing_tau_trop + (1.0 - w) / ctl->mixing_tau_strat;
5756 mixparam[ip] = -expm1(-dt_mix * rate);
5757 }
5758
5759 /* Calculate interparcel mixing... */
5760 const int use_ensemble = (ctl->nens > 0);
5761
5762 const int quantities[] = {
5763 ctl->qnt_m, ctl->qnt_vmr, ctl->qnt_Ch2o, ctl->qnt_Co3,
5764 ctl->qnt_Cco, ctl->qnt_Coh, ctl->qnt_Ch, ctl->qnt_Cho2,
5765 ctl->qnt_Ch2o2, ctl->qnt_Co1d, ctl->qnt_Co3p, ctl->qnt_Cccl4,
5766 ctl->qnt_Cccl3f, ctl->qnt_Cccl2f2, ctl->qnt_Cn2o,
5767 ctl->qnt_Csf6, ctl->qnt_aoa, ctl->qnt_Arn222, ctl->qnt_Apb210,
5768 ctl->qnt_Abe7, ctl->qnt_Acs137, ctl->qnt_Ai131, ctl->qnt_Axe133
5769 };
5770 const int n_qnt = sizeof(quantities) / sizeof(quantities[0]);
5771
5772 for (int i = 0; i < n_qnt; i++)
5773 if (quantities[i] >= 0)
5774 module_mixing_help(ctl, atm, ixs, iys, izs, mixparam, quantities[i],
5775 use_ensemble);
5776
5777 /* Free... */
5778#ifdef _OPENACC
5779#pragma acc exit data delete(ixs,iys,izs,mixparam)
5780#endif
5781 free(ixs);
5782 free(iys);
5783 free(izs);
5784 free(mixparam);
5785}
void module_mixing_help(const ctl_t *ctl, atm_t *atm, const int *ixs, const int *iys, const int *izs, const double *mixparam, const int qnt_idx, const int use_ensemble)
Perform subgrid-scale interparcel mixing of a given quantity.
Definition mptrac.c:5789
int qnt_Coh
Quantity array index for OH volume mixing ratio (chemistry code).
Definition mptrac.h:2831
int mixing_nx
Number of longitudes of mixing grid.
Definition mptrac.h:3259
double mixing_z1
Upper altitude of mixing grid [km].
Definition mptrac.h:3256
int qnt_Co1d
Quantity array index for O(1D) volume mixing ratio (chemistry code).
Definition mptrac.h:2843
int qnt_Acs137
Quantity array index for radioactive activity of Cs-137.
Definition mptrac.h:2877
double mixing_z0
Lower altitude of mixing grid [km].
Definition mptrac.h:3253
int qnt_Cco
Quantity array index for CO volume mixing ratio (chemistry code).
Definition mptrac.h:2828
int mixing_ny
Number of latitudes of mixing grid.
Definition mptrac.h:3268
int qnt_Ch
Quantity array index for H volume mixing ratio (chemistry code).
Definition mptrac.h:2834
double mixing_lat0
Lower latitude of mixing grid [deg].
Definition mptrac.h:3271
int qnt_Ai131
Quantity array index for radioactive activity of I-131.
Definition mptrac.h:2880
double mixing_tau_trop
E-folding time for interparcel mixing in the troposphere [s].
Definition mptrac.h:3244
int qnt_Apb210
Quantity array index for radioactive activity of Pb-210.
Definition mptrac.h:2871
int qnt_Cho2
Quantity array index for HO2 volume mixing ratio (chemistry code).
Definition mptrac.h:2837
int mixing_nz
Number of altitudes of mixing grid.
Definition mptrac.h:3250
double mixing_lon0
Lower longitude of mixing grid [deg].
Definition mptrac.h:3262
double mixing_lat1
Upper latitude of mixing grid [deg].
Definition mptrac.h:3274
int qnt_Axe133
Quantity array index for radioactive activity of Xe-133.
Definition mptrac.h:2883
int qnt_Co3p
Quantity array index for O(3P) volume mixing ratio (chemistry code).
Definition mptrac.h:2846
int qnt_Abe7
Quantity array index for radioactive activity of Be-7.
Definition mptrac.h:2874
double mixing_dt
Time interval for mixing [s].
Definition mptrac.h:3241
double mixing_tau_strat
E-folding time for interparcel mixing in the stratosphere [s].
Definition mptrac.h:3247
int qnt_Arn222
Quantity array index for radioactive activity of Rn-222.
Definition mptrac.h:2868
int qnt_Ch2o2
Quantity array index for H2O2 volume mixing ratio (chemistry code).
Definition mptrac.h:2840
double mixing_lon1
Upper longitude of mixing grid [deg].
Definition mptrac.h:3265
Here is the call graph for this function:

◆ module_mixing_help()

void module_mixing_help ( const ctl_t * ctl,
atm_t * atm,
const int * ixs,
const int * iys,
const int * izs,
const double * mixparam,
const int qnt_idx,
const int use_ensemble )

Perform subgrid-scale interparcel mixing of a given quantity.

This function computes the mixing-parameter-weighted mean of a specified quantity within each subgrid box (and optionally for each ensemble member) and applies a mixing adjustment to particle values based on the computed local mean. The weighted mean conserves the unweighted sum of the quantity within each rank-local box and ensemble when the mixing parameter varies between particles. Air-mass-weighted conservation requires additional assumptions about the mass represented by each particle.

The mixing accounts for differences in tropospheric and stratospheric mixing via a weighted parameterization. It supports both ensemble and non-ensemble modes using the use_ensemble flag.

Parameters
[in]ctlPointer to control/configuration structure.
[in,out]atmPointer to atmospheric state (includes particles).
[in]ixsArray of x-grid indices for each particle.
[in]iysArray of y-grid indices for each particle.
[in]izsArray of z-grid indices for each particle (-1 for invalid).
[in]mixparamMixing parameter for each particle.
[in]qnt_idxIndex of the quantity in atm->q to be mixed.
[in]use_ensembleFlag indicating whether to use ensemble-aware logic (0 = no, 1 = yes).
Note
Particles with izs[ip] < 0 are excluded from mixing.
Uses OpenACC or OpenMP for parallelism depending on compilation options.
Requires ctl->qnt_ens to be valid if use_ensemble is true.
Author
Mingzhao Liu
Lars Hoffmann

Definition at line 5789 of file mptrac.c.

5797 {
5798
5799 const int np = atm->np;
5800 const int ngrid = ctl->mixing_nx * ctl->mixing_ny * ctl->mixing_nz;
5801 const int nens = use_ensemble ? ctl->nens : 1;
5802 const int total_grid = ngrid * nens;
5803
5804 double *restrict const cmean =
5805 (double *) malloc((size_t) total_grid * sizeof(double));
5806 double *restrict const cweight =
5807 (double *) malloc((size_t) total_grid * sizeof(double));
5808 if (cmean == NULL || cweight == NULL)
5809 ERRMSG("Out of memory!");
5810
5811 /* Init... */
5812#ifdef _OPENACC
5813#pragma acc enter data create(cmean[0:total_grid],cweight[0:total_grid])
5814#pragma acc data present(ctl,atm,ixs,iys,izs,mixparam,cmean,cweight)
5815#pragma acc parallel loop independent gang vector
5816#else
5817#ifdef __NVCOMPILER
5818#pragma novector
5819#endif
5820#pragma omp parallel for
5821#endif
5822 for (int i = 0; i < total_grid; i++) {
5823 cmean[i] = 0.0;
5824 cweight[i] = 0.0;
5825 }
5826
5827 /* Loop over particles... */
5828#ifdef _OPENACC
5829#pragma acc parallel loop independent gang vector
5830#endif
5831 for (int ip = 0; ip < np; ip++)
5832 if (izs[ip] >= 0) {
5833 const int ens = use_ensemble ? (int) atm->q[ctl->qnt_ens][ip] : 0;
5834 if (ens < 0 || ens >= nens)
5835 continue;
5836 const int idx =
5837 ens * ngrid + ARRAY_3D(ixs[ip], iys[ip], ctl->mixing_ny, izs[ip],
5838 ctl->mixing_nz);
5839#ifdef _OPENACC
5840#pragma acc atomic update
5841#endif
5842 cmean[idx] += mixparam[ip] * atm->q[qnt_idx][ip];
5843#ifdef _OPENACC
5844#pragma acc atomic update
5845#endif
5846 cweight[idx] += mixparam[ip];
5847 }
5848
5849 /* Compute means... */
5850#ifdef _OPENACC
5851#pragma acc parallel loop independent gang vector
5852#else
5853#ifdef __NVCOMPILER
5854#pragma novector
5855#endif
5856#pragma omp parallel for
5857#endif
5858 for (int i = 0; i < total_grid; i++)
5859 if (cweight[i] > 0)
5860 cmean[i] /= cweight[i];
5861
5862 /* Interparcel mixing... */
5863#ifdef _OPENACC
5864#pragma acc parallel loop independent gang vector
5865#else
5866#pragma omp parallel for
5867#endif
5868 for (int ip = 0; ip < np; ip++) {
5869 if (izs[ip] >= 0) {
5870 const int ens = use_ensemble ? (int) atm->q[ctl->qnt_ens][ip] : 0;
5871
5872 if (ens < 0 || ens >= nens)
5873 continue;
5874 const int idx =
5875 ens * ngrid + ARRAY_3D(ixs[ip], iys[ip], ctl->mixing_ny, izs[ip],
5876 ctl->mixing_nz);
5877 atm->q[qnt_idx][ip] +=
5878 (cmean[idx] - atm->q[qnt_idx][ip]) * mixparam[ip];
5879 }
5880 }
5881
5882 /* Free... */
5883#ifdef _OPENACC
5884#pragma acc exit data delete(cmean,cweight)
5885#endif
5886 free(cmean);
5887 free(cweight);
5888}

◆ module_oh_chem()

void module_oh_chem ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Perform hydroxyl chemistry calculations for atmospheric particles.

This function calculates generic OH chemistry for each atmospheric particle based on the specified reaction mechanism and updates the particle quantities accordingly. The OH chemistry includes bimolecular and termolecular reactions, and the reaction rates are calculated based on the provided climatological data and atmospheric conditions. The function supports both mass and volume mixing ratio quantities for the particles. The empirical high-concentration SO2 correction applies when Cx is configured and SPECIES is SO2 or unspecified; it is not used for an explicitly selected different species.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climate data structure containing climatological data.
met0Pointer to the first meteorological data structure.
met1Pointer to the second meteorological data structure.
atmPointer to the atmospheric data structure containing particle information.
Note
The function assumes that the necessary meteorological and climatological data structures have been initialized and are accessible via the pointers met0, met1, and clim, respectively.
The reaction rates are calculated based on the provided reaction mechanism and atmospheric conditions, including temperature, pressure, and the concentrations of relevant species.
The function updates the particle quantities based on the calculated reaction rates and the specified time steps. The update can include both mass and volume mixing ratio quantities, as determined by the control structure (ctl).
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 5892 of file mptrac.c.

5898 {
5899
5900 /* Set timer... */
5901 SELECT_TIMER("MODULE_OH_CHEM", "PHYSICS");
5902
5903 /* Check quantity flags... */
5904 if (ctl->qnt_m < 0 && ctl->qnt_vmr < 0)
5905 ERRMSG("Module needs quantity mass or volume mixing ratio!");
5906
5907 /* Parameter of SO2 correction... */
5908 const double a = 4.71572206e-08;
5909 const double b = -8.28782867e-01;
5910 const double low = pow(1. / a, 1. / b);
5911 const int so2_correction = ctl->qnt_Cx >= 0
5912 && (ctl->species[0] == '-' || strcasecmp(ctl->species, "SO2") == 0);
5913
5914 /* Loop over particles... */
5915 PARTICLE_LOOP(0, atm->np, 1,
5916 "acc data present(ctl,cache,clim,met0,met1,atm)") {
5917
5918 /* Get temperature... */
5919 double t;
5921 INTPOL_3D(t, 1);
5922 if (!isfinite(t) || t <= 0)
5923 continue;
5924
5925 /* Calculate molecular density... */
5926 const double M = MOLEC_DENS(atm->p[ip], t);
5927 if (!isfinite(M) || M <= 0)
5928 continue;
5929
5930 /* Use constant reaction rate... */
5931 double k = NAN;
5932 if (ctl->oh_chem_reaction == 1)
5933 k = ctl->oh_chem[0];
5934
5935 /* Calculate bimolecular reaction rate... */
5936 else if (ctl->oh_chem_reaction == 2)
5937 k = ctl->oh_chem[0] * exp(-ctl->oh_chem[1] / t);
5938
5939 /* Calculate termolecular reaction rate... */
5940 if (ctl->oh_chem_reaction == 3) {
5941
5942 /* Calculate rate coefficient for X + OH + M -> XOH + M
5943 (JPL Publication 19-05) ... */
5944 const double k0 =
5945 ctl->oh_chem[0] * (ctl->oh_chem[1] !=
5946 0 ? pow(298. / t, ctl->oh_chem[1]) : 1.);
5947 const double ki =
5948 ctl->oh_chem[2] * (ctl->oh_chem[3] !=
5949 0 ? pow(298. / t, ctl->oh_chem[3]) : 1.);
5950 const double c = log10(k0 * M / ki);
5951 k = k0 * M / (1. + k0 * M / ki) * pow(0.6, 1. / (1. + c * c));
5952 }
5953 if (!isfinite(k) || k < 0)
5954 continue;
5955
5956 /* Apply plume correction for Cx with SO2 or unspecified species... */
5957 double cor = 1;
5958 if (so2_correction) {
5959 if (!isfinite(atm->q[ctl->qnt_Cx][ip]))
5960 continue;
5961 cor =
5962 atm->q[ctl->qnt_Cx][ip] >
5963 low ? a * pow(atm->q[ctl->qnt_Cx][ip], b) : 1;
5964 }
5965
5966 /* Calculate exponential decay... */
5967 const double oh = clim_oh(ctl, clim, atm->time[ip], atm->lon[ip],
5968 atm->lat[ip], atm->p[ip]);
5969 if (!isfinite(oh) || oh < 0)
5970 continue;
5971 const double rate_coef = k * oh * M * cor;
5972 if (!isfinite(rate_coef) || rate_coef < 0)
5973 continue;
5974 const double aux = exp(-cache->dt[ip] * rate_coef);
5975 if (!isfinite(aux))
5976 continue;
5977 if (ctl->qnt_m >= 0) {
5978 if (ctl->qnt_mloss_oh >= 0)
5979 atm->q[ctl->qnt_mloss_oh][ip]
5980 += atm->q[ctl->qnt_m][ip] * (1 - aux);
5981 atm->q[ctl->qnt_m][ip] *= aux;
5982 if (ctl->qnt_loss_rate >= 0)
5983 atm->q[ctl->qnt_loss_rate][ip] += rate_coef;
5984 }
5985 if (ctl->qnt_vmr >= 0)
5986 atm->q[ctl->qnt_vmr][ip] *= aux;
5987 }
5988}
double oh_chem[4]
Coefficients for OH reaction rate (A, E/R or k0, n, kinf, m).
Definition mptrac.h:3307
int oh_chem_reaction
OH reaction type (0=off, 1=constant, 2=bimolecular, 3=termolecular).
Definition mptrac.h:3304
int qnt_mloss_oh
Quantity array index for total mass loss due to OH chemistry.
Definition mptrac.h:2729
Here is the call graph for this function:

◆ module_position()

void module_position ( const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm,
const int reflect )

Update the positions and pressure levels of atmospheric particles.

This function updates the positions and pressure levels of atmospheric particles based on the meteorological data and the specified time step. It loops over each particle in the atmospheric data structure and performs the following operations:

  • Initializes variables required for interpolation.
  • Calculates modulo for longitude and latitude to ensure they remain within valid ranges.
  • Adjusts latitude if it exceeds the range [-90, 90] degrees.
  • Adjusts longitude if it exceeds the range [-180, 180] degrees.
  • Clamps or reflects pressure at the model top and local surface, as selected by reflect.
Parameters
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the first meteorological data structure.
met1Pointer to the second meteorological data structure.
atmPointer to the atmospheric data structure containing particle information.
reflectSelect reflection (1) or clamping (0) at vertical boundaries.
Note
The function initializes a timer to measure the execution time of the position update process.
Position and pressure updates are performed for each particle using linear interpolation.
Longitude and latitude are adjusted to ensure they remain within valid ranges.
Author
Lars Hoffmann

Definition at line 5992 of file mptrac.c.

5997 {
5998
5999 /* Set timer... */
6000 SELECT_TIMER("MODULE_POSITION", "PHYSICS");
6001
6002 /* Loop over particles... */
6003 PARTICLE_LOOP(0, atm->np, 1, "acc data present(cache,met0,met1,atm)") {
6004
6005 /* Init... */
6006 double ps;
6008
6009 if (met0->coord_type == 0) {
6010 /* Calculate modulo... */
6011 atm->lon[ip] = FMOD(atm->lon[ip], 360.);
6012 atm->lat[ip] = FMOD(atm->lat[ip], 360.);
6013
6014 /* Check latitude... */
6015 while (atm->lat[ip] < -90 || atm->lat[ip] > 90) {
6016 if (atm->lat[ip] > 90) {
6017 atm->lat[ip] = 180 - atm->lat[ip];
6018 atm->lon[ip] += 180;
6019 }
6020 if (atm->lat[ip] < -90) {
6021 atm->lat[ip] = -180 - atm->lat[ip];
6022 atm->lon[ip] += 180;
6023 }
6024 }
6025
6026 /* Check longitude... */
6027 while (atm->lon[ip] < -180)
6028 atm->lon[ip] += 360;
6029 while (atm->lon[ip] >= 180)
6030 atm->lon[ip] -= 360;
6031 } else {
6032 intpol_check_cartesian(met0->lon, met0->nx, met0->lat, met0->ny,
6033 atm->lon[ip], atm->lat[ip], &atm->lon[ip],
6034 &atm->lat[ip]);
6035 }
6036
6037 /* Check pressure... */
6038 const double ptop = met0->p[met0->np - 1];
6039 if (atm->p[ip] < ptop) {
6040 atm->p[ip] = reflect ? ptop * ptop / atm->p[ip] : ptop;
6041 } else if (atm->p[ip] > 300.) {
6042 INTPOL_2D(ps, 1);
6043 if (atm->p[ip] > ps)
6044 atm->p[ip] = reflect ? ps * ps / atm->p[ip] : ps;
6045 }
6046 }
6047}
Here is the call graph for this function:

◆ module_rng_init()

void module_rng_init ( const int ntask)

Initialize random number generators for parallel tasks.

This function initializes random number generators for parallel tasks using GSL (GNU Scientific Library), Squares, and cuRAND (NVIDIA CUDA Random Number Generation Library) if available. GSL generators are seeded per OpenMP thread, cuRAND is seeded per task, and Squares starts at a task-dependent counter offset.

Parameters
ntaskTask identifier used to initialize the generator streams.
Note
This function must be called before using any random number generation functions to ensure proper initialization of random number generators.
GSL random number generators are initialized for each OpenMP thread, while cuRAND is initialized per task.
If cuRAND is not available (CURAND macro not defined), the cuRAND initialization section is skipped.
Squares spaces initial counters by 2^48 values; task 0 retains the original sequence. Streams can overlap after that many draws, counter wraparound, or reuse of task identifiers.
Author
Lars Hoffmann

Definition at line 6300 of file mptrac.c.

6301 {
6302
6303 /* Separate Squares counter ranges by task (task 0 keeps its sequence)... */
6304 rng_ctr = (uint64_t) (unsigned int) ntask << 48;
6305
6306 /* Initialize GSL random number generators... */
6307 gsl_rng_env_setup();
6308 if (omp_get_max_threads() > NTHREADS)
6309 ERRMSG("Too many threads!");
6310 for (int i = 0; i < NTHREADS; i++) {
6311 rng[i] = gsl_rng_alloc(gsl_rng_default);
6312 gsl_rng_set(rng[i], gsl_rng_default_seed
6313 + (long unsigned) (ntask * NTHREADS + i));
6314 }
6315
6316 /* Initialize cuRAND random number generators... */
6317#ifdef CURAND
6318 if (curandCreateGenerator(&rng_curand, CURAND_RNG_PSEUDO_DEFAULT) !=
6319 CURAND_STATUS_SUCCESS)
6320 ERRMSG("Cannot create random number generator!");
6321 if (curandSetPseudoRandomGeneratorSeed(rng_curand, ntask) !=
6322 CURAND_STATUS_SUCCESS)
6323 ERRMSG("Cannot set seed for random number generator!");
6324 if (curandSetStream
6325 (rng_curand,
6326 (cudaStream_t) acc_get_cuda_stream(acc_async_sync)) !=
6327 CURAND_STATUS_SUCCESS)
6328 ERRMSG("Cannot set stream for random number generator!");
6329#endif
6330}
#define NTHREADS
Maximum number of OpenMP threads.
Definition mptrac.h:594

◆ module_rng()

void module_rng ( const ctl_t * ctl,
double * rs,
const size_t n,
const int method )

Generate random numbers using various methods and distributions.

This function generates random numbers using different methods and distributions based on the specified method and random number generator type. It supports uniform and normal distributions and can utilize GSL, Squares (Widynski, 2022), or cuRAND random number generators.

Parameters
ctlPointer to the control structure containing parameters and settings.
rsPointer to the array where the generated random numbers will be stored.
nThe number of random numbers to generate.
methodThe method for generating random numbers:
  • 0: Uniform distribution
  • 1: Normal distribution
Note
The function selects the appropriate random number generator based on the specified method and the random number generator type defined in the control structure (ctl->rng_type).
For uniform distribution, the generated random numbers are in the range [0, 1).
For normal distribution, the Box-Muller transform is used to generate pairs of random numbers and transform them into a normal distribution.
If cuRAND is not available (CURAND macro not defined), the function returns an error message.
Author
Lars Hoffmann

Definition at line 6334 of file mptrac.c.

6338 {
6339
6340 /* Use GSL random number generators... */
6341 if (ctl->rng_type == 0) {
6342
6343 /* Uniform distribution... */
6344 if (method == 0) {
6345#pragma omp parallel for default(shared)
6346 for (size_t i = 0; i < n; ++i)
6347 rs[i] = gsl_rng_uniform(rng[omp_get_thread_num()]);
6348 }
6349
6350 /* Normal distribution... */
6351 else if (method == 1) {
6352#pragma omp parallel for default(shared)
6353 for (size_t i = 0; i < n; ++i)
6354 rs[i] = gsl_ran_gaussian_ziggurat(rng[omp_get_thread_num()], 1.0);
6355 }
6356
6357 /* Update of random numbers on device... */
6358#ifdef _OPENACC
6359 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
6360#pragma acc update device(rs[:n])
6361#endif
6362 }
6363
6364 /* Use Squares random number generator (Widynski, 2022)... */
6365 else if (ctl->rng_type == 1) {
6366
6367 /* Set key (don't change this!)... */
6368 const uint64_t key = 0xc8e4fd154ce32f6d;
6369
6370 /* Uniform distribution... */
6371#ifdef _OPENACC
6372#pragma acc data present(rs)
6373#pragma acc parallel loop independent gang vector
6374#else
6375#pragma omp parallel for default(shared)
6376#endif
6377 for (size_t i = 0; i < n + 1; ++i) {
6378 uint64_t r, t, x, y, z;
6379 y = x = (rng_ctr + i) * key;
6380 z = y + key;
6381 x = x * x + y;
6382 x = (x >> 32) | (x << 32);
6383 x = x * x + z;
6384 x = (x >> 32) | (x << 32);
6385 x = x * x + y;
6386 x = (x >> 32) | (x << 32);
6387 t = x = x * x + z;
6388 x = (x >> 32) | (x << 32);
6389 r = t ^ ((x * x + y) >> 32);
6390 rs[i] = (double) r / (double) UINT64_MAX;
6391 }
6392 rng_ctr += n + 1;
6393
6394 /* Normal distribution... */
6395 if (method == 1) {
6396#ifdef _OPENACC
6397#pragma acc parallel loop independent gang vector
6398#else
6399#pragma omp parallel for default(shared)
6400#endif
6401 for (size_t i = 0; i < n; i += 2) {
6402 const double r = sqrt(-2.0 * log(rs[i]));
6403 const double phi = 2.0 * M_PI * rs[i + 1];
6404 rs[i] = r * cosf((float) phi);
6405 rs[i + 1] = r * sinf((float) phi);
6406 }
6407 }
6408 }
6409
6410 /* Use cuRAND random number generators... */
6411 else if (ctl->rng_type == 2) {
6412#ifdef CURAND
6413#pragma acc host_data use_device(rs)
6414 {
6415
6416 /* Uniform distribution... */
6417 if (method == 0) {
6418 if (curandGenerateUniformDouble(rng_curand, rs, (n < 4 ? 4 : n)) !=
6419 CURAND_STATUS_SUCCESS)
6420 ERRMSG("Cannot create random numbers!");
6421 }
6422
6423 /* Normal distribution... */
6424 else if (method == 1 && n > 0) {
6425 if (n > 3 * (size_t) NP)
6426 ERRMSG("Too many random numbers requested!");
6427 const size_t n_generate = (n < 4 ? 4 : n + (n & 1));
6428 if (curandGenerateNormalDouble
6429 (rng_curand, rs, n_generate, 0.0,
6430 1.0) != CURAND_STATUS_SUCCESS)
6431 ERRMSG("Cannot create random numbers!");
6432 }
6433 }
6434#else
6435 ERRMSG("MPTRAC was compiled without cuRAND!");
6436#endif
6437 }
6438}
int rng_type
Random number generator (0=GSL, 1=Squares, 2=cuRAND).
Definition mptrac.h:3103

◆ module_radio_decay()

void module_radio_decay ( const ctl_t * ctl,
const cache_t * cache,
atm_t * atm )

Apply radioactive decay to atmospheric tracer species.

This routine updates radionuclide activities [Bq] carried by atmospheric particles by applying exponential decay over the current particle timestep. The decay constants are derived from the half-lives of the respective isotopes.

Implemented isotopes:

  • Rn-222
  • Pb-210
  • Be-7
  • Cs-137
  • I-131
  • Xe-133

For each particle, activity follows \( A(t+\Delta t) = A(t) \exp(-\lambda \Delta t) \), where \(\lambda\) is the decay constant and \(\Delta t\) is the particle timestep.

Additionally, the decay of Rn-222 contributes to the production of Pb-210 via a simplified parent–daughter relationship. Negative particle timesteps mathematically reverse the exponential decay.

The update is performed only if the corresponding tracer index in the control structure is non-negative.

Parameters
[in]ctlControl structure containing tracer indices.
[in]cacheCache structure providing particle timesteps.
[in,out]atmAtmospheric state containing particle tracer fields that are updated in place.
Author
Lars Hoffmann

Definition at line 6051 of file mptrac.c.

6054 {
6055
6056 /* Set timer... */
6057 SELECT_TIMER("MODULE_RADIO_DECAY", "PHYSICS");
6058
6059 /* Set decay constants of radioactive species [s^-1]... */
6060 const double lambda_rn222 = log(2.0) / RADIO_HALF_LIFE_RN222;
6061 const double lambda_pb210 = log(2.0) / RADIO_HALF_LIFE_PB210;
6062 const double lambda_be7 = log(2.0) / RADIO_HALF_LIFE_BE7;
6063 const double lambda_cs137 = log(2.0) / RADIO_HALF_LIFE_CS137;
6064 const double lambda_i131 = log(2.0) / RADIO_HALF_LIFE_I131;
6065 const double lambda_xe133 = log(2.0) / RADIO_HALF_LIFE_XE133;
6066
6067 /* Loop over particles... */
6068 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,atm)") {
6069
6070 /* Set timestep... */
6071 const double dt = cache->dt[ip];
6072
6073 /* Loss for Pb-210... */
6074 if (ctl->qnt_Apb210 >= 0)
6075 atm->q[ctl->qnt_Apb210][ip] *= exp(-dt * lambda_pb210);
6076
6077 /* Loss for Rn-222... */
6078 if (ctl->qnt_Arn222 >= 0) {
6079 const double old = atm->q[ctl->qnt_Arn222][ip];
6080 const double aux = exp(-dt * lambda_rn222);
6081 const double lost = old * (1.0 - aux);
6082 atm->q[ctl->qnt_Arn222][ip] = old * aux;
6083
6084 /* Approximate Pb-210 activity produced by decayed Rn-222... */
6085 if (ctl->qnt_Apb210 >= 0)
6086 atm->q[ctl->qnt_Apb210][ip] += lost * lambda_pb210 / lambda_rn222;
6087 }
6088
6089 /* Loss for Be-7... */
6090 if (ctl->qnt_Abe7 >= 0)
6091 atm->q[ctl->qnt_Abe7][ip] *= exp(-dt * lambda_be7);
6092
6093 /* Loss for Cs-137... */
6094 if (ctl->qnt_Acs137 >= 0)
6095 atm->q[ctl->qnt_Acs137][ip] *= exp(-dt * lambda_cs137);
6096
6097 /* Loss for I-131... */
6098 if (ctl->qnt_Ai131 >= 0)
6099 atm->q[ctl->qnt_Ai131][ip] *= exp(-dt * lambda_i131);
6100
6101 /* Loss for Xe-133... */
6102 if (ctl->qnt_Axe133 >= 0)
6103 atm->q[ctl->qnt_Axe133][ip] *= exp(-dt * lambda_xe133);
6104 }
6105}
#define RADIO_HALF_LIFE_CS137
Half-life of Cs-137 [s].
Definition mptrac.h:480
#define RADIO_HALF_LIFE_I131
Half-life of I-131 [s].
Definition mptrac.h:485
#define RADIO_HALF_LIFE_BE7
Half-life of Be-7 [s].
Definition mptrac.h:475
#define RADIO_HALF_LIFE_RN222
Half-life of Rn-222 [s].
Definition mptrac.h:465
#define RADIO_HALF_LIFE_PB210
Half-life of Pb-210 [s].
Definition mptrac.h:470
#define RADIO_HALF_LIFE_XE133
Half-life of Xe-133 [s].
Definition mptrac.h:490

◆ module_radio_depo()

void module_radio_depo ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm,
depo_t * depo )

Deposit supported radionuclides from air parcels onto the ground grid.

Applies fixed dry-deposition velocities within DRY_DEPO_DZ metres above the local surface and precipitation-dependent wet scavenging to Apb210, Abe7, Acs137, and Ai131. Air-parcel activities are reduced exponentially and the removed activity is accumulated in depo. When RADIO_DECAY is enabled, ground inventories are referenced to the simulation start for decay-correct output. Backward or zero-length particle timesteps are ignored.

Note
This module requires a latitude/longitude meteorological grid and is not currently supported with domain decomposition (DD).
Parameters
[in]ctlControl parameters, quantity indices, and deposition grid.
[in]cachePer-particle model timesteps.
[in]met0Meteorological field at the earlier bracketing time.
[in]met1Meteorological field at the later bracketing time.
[in,out]atmAir-parcel positions and activities [Bq].
[in,out]depoCumulative ground inventories [Bq per grid cell].
Author
Lars Hoffmann

Definition at line 6109 of file mptrac.c.

6115 {
6116
6117 /* Set timer... */
6118 SELECT_TIMER("MODULE_RADIO_DEPO", "PHYSICS");
6119
6120 /* Decay constants of deposited radionuclides [s^-1]... */
6121 const double lambda_pb210 = log(2.0) / RADIO_HALF_LIFE_PB210;
6122 const double lambda_be7 = log(2.0) / RADIO_HALF_LIFE_BE7;
6123 const double lambda_cs137 = log(2.0) / RADIO_HALF_LIFE_CS137;
6124 const double lambda_i131 = log(2.0) / RADIO_HALF_LIFE_I131;
6125
6126 /* Set horizontal grid increments... */
6127 const double dlon = (ctl->grid_lon1 - ctl->grid_lon0) / ctl->grid_nx;
6128 const double dlat = (ctl->grid_lat1 - ctl->grid_lat0) / ctl->grid_ny;
6129 const double p_factor = exp(-ctl->dry_depo_dz / (1000. * H0));
6130
6131 /* Loop over particles... */
6132 PARTICLE_LOOP(0, atm->np, 1,
6133 "acc data present(ctl,cache,met0,met1,atm,depo)") {
6134
6135 /* Deposition is only defined for forward integration... */
6136 const double dt = cache->dt[ip];
6137 if (dt <= 0)
6138 continue;
6139
6140 /* Get surface pressure... */
6141 double ps;
6143 INTPOL_2D(ps, 1);
6144
6145 /* Calculate dry deposition rate [s^-1]... */
6146 double dry_pb210 = 0, dry_be7 = 0, dry_cs137 = 0, dry_i131 = 0;
6147 if (isfinite(ps) && ps > 0. && atm->p[ip] >= ps * p_factor) {
6148 const double dz = ctl->dry_depo_dz;
6149 dry_pb210 = RADIO_DRY_VDEP_PB210 / dz;
6150 dry_be7 = RADIO_DRY_VDEP_BE7 / dz;
6151 dry_cs137 = RADIO_DRY_VDEP_CS137 / dz;
6152 dry_i131 = RADIO_DRY_VDEP_I131 / dz;
6153 }
6154
6155 /* Calculate wet deposition rate [s^-1]... */
6156 double wet_pb210 = 0, wet_be7 = 0, wet_cs137 = 0, wet_i131 = 0;
6157 double pct;
6158 INTPOL_2D(pct, 1);
6159 if (isfinite(pct) && atm->p[ip] > pct) {
6160 double cl;
6161 INTPOL_2D(cl, 0);
6162 if (cl > 0) {
6163 const double Is =
6164 pow(cl / ctl->wet_depo_pre[0], 1. / ctl->wet_depo_pre[1]);
6165 if (isfinite(Is) && Is >= 0.01) {
6166 double lwc, rwc, iwc, swc, t;
6167 INTPOL_3D(lwc, 1);
6168 INTPOL_3D(rwc, 0);
6169 INTPOL_3D(iwc, 0);
6170 INTPOL_3D(swc, 0);
6171 INTPOL_3D(t, 0);
6172 if (isfinite(t) && t > 0.) {
6173 /* Select cloud-regime and temperature-dependent retention... */
6174 const int inside = (lwc > 0 || rwc > 0 || iwc > 0 || swc > 0);
6175 double eta;
6176 if (inside) {
6177 if (t > WET_DEPO_T_LIQUID)
6178 eta = 1;
6179 else if (t <= WET_DEPO_T_ICE)
6180 eta = ctl->wet_depo_ic_ret_ratio;
6181 else
6183 ctl->wet_depo_ic_ret_ratio, t);
6184 } else
6185 eta =
6187 wet_pb210 = RADIO_WET_COEFF_PB210 * Is * eta;
6188 wet_be7 = RADIO_WET_COEFF_BE7 * Is * eta;
6189 wet_cs137 = RADIO_WET_COEFF_CS137 * Is * eta;
6190 wet_i131 = RADIO_WET_COEFF_I131 * Is * eta;
6191 }
6192 }
6193 }
6194 }
6195
6196 /* Ignore invalid wet rates without suppressing valid dry deposition... */
6197 if (!isfinite(wet_pb210) || wet_pb210 < 0.)
6198 wet_pb210 = 0.;
6199 if (!isfinite(wet_be7) || wet_be7 < 0.)
6200 wet_be7 = 0.;
6201 if (!isfinite(wet_cs137) || wet_cs137 < 0.)
6202 wet_cs137 = 0.;
6203 if (!isfinite(wet_i131) || wet_i131 < 0.)
6204 wet_i131 = 0.;
6205
6206 /* Get deposition grid index... */
6207 const int ingrid =
6208 (atm->lon[ip] >= ctl->grid_lon0
6209 && atm->lon[ip] < ctl->grid_lon1
6210 && atm->lat[ip] >= ctl->grid_lat0 && atm->lat[ip] < ctl->grid_lat1);
6211 const int ix = ingrid
6212 ? (int) ((atm->lon[ip] - ctl->grid_lon0) / dlon) : 0;
6213 const int iy = ingrid
6214 ? (int) ((atm->lat[ip] - ctl->grid_lat0) / dlat) : 0;
6215 const int idx = (ingrid ? ARRAY_2D(ix, iy, ctl->grid_ny) : 0);
6216
6217 /* Reference deposited Bq to model start for output-time decay... */
6218 const double tref = atm->time[ip] - ctl->t_start;
6219
6220 /* Deposit Pb-210... */
6221 const double rate_pb210 = dry_pb210 + wet_pb210;
6222 if (ctl->qnt_Apb210 >= 0 && isfinite(rate_pb210) && rate_pb210 >= 0.) {
6223 const double old = atm->q[ctl->qnt_Apb210][ip];
6224 const double aux = exp(-dt * rate_pb210);
6225 const double lost = old * (1. - aux);
6226 const double deposited = lost
6227 * (ctl->radio_decay ? exp(lambda_pb210 * tref) : 1.0);
6228 atm->q[ctl->qnt_Apb210][ip] = old * aux;
6229 if (ingrid && lost > 0) {
6230#ifdef _OPENACC
6231#pragma acc atomic update
6232#else
6233#pragma omp atomic update
6234#endif
6235 depo->Apb210[idx] += deposited;
6236 }
6237 }
6238
6239 /* Deposit Be-7... */
6240 const double rate_be7 = dry_be7 + wet_be7;
6241 if (ctl->qnt_Abe7 >= 0 && isfinite(rate_be7) && rate_be7 >= 0.) {
6242 const double old = atm->q[ctl->qnt_Abe7][ip];
6243 const double aux = exp(-dt * rate_be7);
6244 const double lost = old * (1. - aux);
6245 const double deposited = lost
6246 * (ctl->radio_decay ? exp(lambda_be7 * tref) : 1.0);
6247 atm->q[ctl->qnt_Abe7][ip] = old * aux;
6248 if (ingrid && lost > 0) {
6249#ifdef _OPENACC
6250#pragma acc atomic update
6251#else
6252#pragma omp atomic update
6253#endif
6254 depo->Abe7[idx] += deposited;
6255 }
6256 }
6257
6258 /* Deposit Cs-137... */
6259 const double rate_cs137 = dry_cs137 + wet_cs137;
6260 if (ctl->qnt_Acs137 >= 0 && isfinite(rate_cs137) && rate_cs137 >= 0.) {
6261 const double old = atm->q[ctl->qnt_Acs137][ip];
6262 const double aux = exp(-dt * rate_cs137);
6263 const double lost = old * (1. - aux);
6264 const double deposited = lost
6265 * (ctl->radio_decay ? exp(lambda_cs137 * tref) : 1.0);
6266 atm->q[ctl->qnt_Acs137][ip] = old * aux;
6267 if (ingrid && lost > 0) {
6268#ifdef _OPENACC
6269#pragma acc atomic update
6270#else
6271#pragma omp atomic update
6272#endif
6273 depo->Acs137[idx] += deposited;
6274 }
6275 }
6276
6277 /* Deposit aerosol-bound I-131... */
6278 const double rate_i131 = dry_i131 + wet_i131;
6279 if (ctl->qnt_Ai131 >= 0 && isfinite(rate_i131) && rate_i131 >= 0.) {
6280 const double old = atm->q[ctl->qnt_Ai131][ip];
6281 const double aux = exp(-dt * rate_i131);
6282 const double lost = old * (1. - aux);
6283 const double deposited = lost
6284 * (ctl->radio_decay ? exp(lambda_i131 * tref) : 1.0);
6285 atm->q[ctl->qnt_Ai131][ip] = old * aux;
6286 if (ingrid && lost > 0) {
6287#ifdef _OPENACC
6288#pragma acc atomic update
6289#else
6290#pragma omp atomic update
6291#endif
6292 depo->Ai131[idx] += deposited;
6293 }
6294 }
6295 }
6296}
#define RADIO_DRY_VDEP_I131
Dry deposition velocity of aerosol-bound I-131 [m/s].
Definition mptrac.h:510
#define RADIO_DRY_VDEP_CS137
Dry deposition velocity of Cs-137 [m/s].
Definition mptrac.h:505
#define RADIO_DRY_VDEP_PB210
Dry deposition velocity of Pb-210 [m/s].
Definition mptrac.h:495
#define ARRAY_2D(ix, iy, ny)
Macro for computing the linear index of a 2D array element.
Definition mptrac.h:692
#define WET_DEPO_T_ICE
Lower temperature of the ice-cloud retention transition [K].
Definition mptrac.h:455
#define RADIO_WET_COEFF_BE7
Wet deposition coefficient of Be-7 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:520
#define RADIO_WET_COEFF_CS137
Wet deposition coefficient of Cs-137 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:525
#define RADIO_WET_COEFF_I131
Wet deposition coefficient of aerosol-bound I-131 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:530
#define RADIO_DRY_VDEP_BE7
Dry deposition velocity of Be-7 [m/s].
Definition mptrac.h:500
#define WET_DEPO_T_LIQUID
Upper temperature of the ice-cloud retention transition [K].
Definition mptrac.h:450
#define WET_DEPO_T_LIQUID_BC
Temperature threshold for below-cloud retention [K].
Definition mptrac.h:460
#define RADIO_WET_COEFF_PB210
Wet deposition coefficient of Pb-210 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:515
int grid_nx
Number of longitudes of gridded data.
Definition mptrac.h:3515
double grid_lat0
Lower latitude of gridded data [deg].
Definition mptrac.h:3527
double grid_lon0
Lower longitude of gridded data [deg].
Definition mptrac.h:3518
int radio_decay
RADIO_DECAY switch for airborne and deposited activity (0=off, 1=on, default: 0).
Definition mptrac.h:3325
double grid_lon1
Upper longitude of gridded data [deg].
Definition mptrac.h:3521
double wet_depo_pre[2]
Positive coefficients for the column-condensate precipitation proxy.
Definition mptrac.h:3331
int grid_ny
Number of latitudes of gridded data.
Definition mptrac.h:3524
double wet_depo_bc_ret_ratio
Coefficients for wet deposition below cloud: retention ratio.
Definition mptrac.h:3358
double wet_depo_ic_ret_ratio
Coefficients for wet deposition in cloud: retention ratio.
Definition mptrac.h:3355
double grid_lat1
Upper latitude of gridded data [deg].
Definition mptrac.h:3530
double Ai131[EX *EY]
Deposited I-131 activity [Bq].
Definition mptrac.h:3774
double Abe7[EX *EY]
Deposited Be-7 activity [Bq].
Definition mptrac.h:3768
double Acs137[EX *EY]
Deposited Cs-137 activity [Bq].
Definition mptrac.h:3771
double Apb210[EX *EY]
Deposited Pb-210 activity [Bq].
Definition mptrac.h:3765

◆ module_sedi()

void module_sedi ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Simulate sedimentation of particles in the atmosphere.

This function calculates the sedimentation velocity of particles based on atmospheric pressure, temperature, and particle properties such as radius and density. It then updates the pressure of each particle based on the sedimentation velocity and the specified time step.

Parameters
ctlPointer to the control structure containing parameters and settings.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the meteorological data at the current time step.
met1Pointer to the meteorological data at the next time step.
atmPointer to the atmospheric data containing particle information.
Note
The sedimentation velocity is calculated using the sedi function, which takes atmospheric pressure, temperature, particle radius, and particle density as inputs.
The pressure change for each particle is calculated based on the sedimentation velocity and the specified time step using the DZ2DP function.
Author
Lars Hoffmann

Definition at line 6442 of file mptrac.c.

6447 {
6448
6449 /* Set timer... */
6450 SELECT_TIMER("MODULE_SEDI", "PHYSICS");
6451 /* Loop over particles... */
6452 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
6453
6454 /* Get temperature... */
6455 double t;
6457 INTPOL_3D(t, 1);
6458
6459 /* Sedimentation velocity... */
6460 const double v_s = sedi(atm->p[ip], t, atm->q[ctl->qnt_rp][ip],
6461 atm->q[ctl->qnt_rhop][ip]);
6462
6463 /* Calculate pressure change... */
6464 atm->p[ip] -= DZ2DP(v_s * cache->dt[ip] / 1000., atm->p[ip]);
6465 }
6466}
Here is the call graph for this function:

◆ sort_array()

void sort_array ( double * array,
const int * perm,
double * tmp,
const int np )

Reorder a double array according to particle source indices.

The destination element at index i receives the original value at perm[i]. Values are first gathered into tmp and then copied back, so parallel writes cannot overwrite source values still being read. The caller provides both the permutation and a distinct temporary buffer; this function does not allocate memory.

Parameters
[in,out]arrayData array to reorder. It must contain every source index referenced by perm.
[in]permSource index for each of the np destination values.
[out]tmpTemporary buffer with room for at least np doubles.
[in]npNumber of destination values to reorder.
Note
In OpenACC builds, the arrays must already be present on the device. The two copy passes run on the device; CPU builds use OpenMP.
Author
Lars Hoffmann

Definition at line 2506 of file mptrac.c.

2510 {
2511
2512 if (np == 0)
2513 return;
2514
2515 /* The caller keeps all three buffers resident on the device. */
2516#ifdef _OPENACC
2517#pragma acc data present(array[0:np],perm[0:np],tmp[0:np])
2518#endif
2519 {
2520
2521 /* perm maps each destination index to its original source index. Gather
2522 every source value before any destination can overwrite it. */
2523#ifdef _OPENACC
2524#pragma acc parallel loop independent gang vector
2525#else
2526#pragma omp parallel for default(shared)
2527#endif
2528 for (int ip = 0; ip < np; ip++)
2529 tmp[ip] = array[perm[ip]];
2530
2531 /* The staging pass is complete, so writes to array are independent. */
2532#ifdef _OPENACC
2533#pragma acc parallel loop independent gang vector
2534#else
2535#pragma omp parallel for default(shared)
2536#endif
2537 for (int ip = 0; ip < np; ip++)
2538 array[ip] = tmp[ip];
2539 }
2540}

◆ sort_uvwp()

void sort_uvwp ( cache_t * cache,
const int * perm,
double * tmp,
const int np )

Reorder particle-specific wind perturbations.

Applies the same source-index mapping as sort_array() to all three components of cache->uvwp. Each float component is staged in the caller-provided double buffer before being written back. The particle's isosurface initialization state is reordered as well; shared balloon data are not modified.

Parameters
[in,out]cacheCache containing the wind perturbations to reorder.
[in]permSource index for each of the np destination particles.
[out]tmpTemporary buffer with room for at least np doubles.
[in]npNumber of destination particles to reorder.
Note
In OpenACC builds, cache, perm, and tmp must already be present on the device. CPU builds use OpenMP.
Author
Lars Hoffmann

Definition at line 2544 of file mptrac.c.

2548 {
2549
2550 if (np == 0)
2551 return;
2552
2553 /* Reuse the caller's device-resident permutation and staging buffer. */
2554#ifdef _OPENACC
2555#pragma acc data present(cache,perm[0:np],tmp[0:np])
2556#endif
2557 {
2558
2559 /* The three float components share one double staging buffer. Finish
2560 both passes for a component before reusing the buffer for the next. */
2561 for (int j = 0; j < 3; j++) {
2562 /* Gather first so in-place writes cannot race with source reads. */
2563#ifdef _OPENACC
2564#pragma acc parallel loop
2565#else
2566#pragma omp parallel for
2567#endif
2568 for (int ip = 0; ip < np; ip++)
2569 tmp[ip] = cache->uvwp[perm[ip]][j];
2570
2571 /* Every float value is represented exactly while staged as double. */
2572#ifdef _OPENACC
2573#pragma acc parallel loop
2574#else
2575#pragma omp parallel for
2576#endif
2577 for (int ip = 0; ip < np; ip++)
2578 cache->uvwp[ip][j] = (float) tmp[ip];
2579 }
2580
2581 /* Reorder the particle-specific isosurface initialization state. */
2582#ifdef _OPENACC
2583#pragma acc parallel loop
2584#else
2585#pragma omp parallel for
2586#endif
2587 for (int ip = 0; ip < np; ip++)
2588 tmp[ip] = cache->iso_init[perm[ip]];
2589#ifdef _OPENACC
2590#pragma acc parallel loop
2591#else
2592#pragma omp parallel for
2593#endif
2594 for (int ip = 0; ip < np; ip++)
2595 cache->iso_init[ip] = (uint8_t) tmp[ip];
2596 }
2597}

◆ module_sort()

void module_sort ( const ctl_t * ctl,
const met_t * met0,
cache_t * cache,
atm_t * atm )

Sort particles according to box index.

This function sorts particles within the atmosphere data structure based on their geographical coordinates (longitude and latitude) and pressure level. It allocates temporary arrays to store indices and auxiliary data for sorting, then performs the sorting operation. After sorting, it updates the order of particles and their persistent particle-specific cache values (dt, uvwp, and iso_init). Random values in rs are regenerated before use; shared cache data remain unchanged.

Parameters
ctlPointer to the control structure containing parameters and settings.
met0Pointer to the meteorological data at the current time step.
cachePointer to the particle-specific cache data to reorder.
atmPointer to the atmospheric data containing particle information.
Note
The function utilizes the locate_reg and locate_irr functions to determine the appropriate index for sorting particles based on their longitude, latitude, and pressure level.
With THRUST enabled, particle indices are sorted using the optional Thrust wrapper. Otherwise, GSL (gsl_sort_index) computes the permutation on the CPU; in OpenACC builds, sorting keys are copied to the host and the resulting permutation is copied back to the device.
The calling physics driver invokes this routine when SORT_DT is positive and the time matches the configured interval, independently of DD_EXCHANGE_MODE. SORT_DT controls spatial sorting, whereas DD_SORT_DT controls sorting for the legacy DD exchange path (mode 0).
After sorting, the function updates the order of particle-related data arrays in the atmosphere data structure to maintain consistency.
Author
Lars Hoffmann

Definition at line 6470 of file mptrac.c.

6474 {
6475
6476 /* Set timer... */
6477 SELECT_TIMER("MODULE_SORT", "PHYSICS");
6478
6479 /* Allocate... */
6480 const int np = atm->np;
6481 double *restrict const a = (double *) malloc((size_t) np * sizeof(double));
6482 int *restrict const p = (int *) malloc((size_t) np * sizeof(int));
6483 if (a == NULL || p == NULL)
6484 ERRMSG("Out of memory!");
6485
6486#ifdef _OPENACC
6487#pragma acc enter data create(a[0:np],p[0:np])
6488#pragma acc data present(ctl,met0,cache,atm,a,p)
6489#endif
6490
6491 /* Get box index... */
6492#ifdef _OPENACC
6493#pragma acc parallel loop independent gang vector
6494#else
6495#pragma omp parallel for default(shared)
6496#endif
6497 for (int ip = 0; ip < np; ip++) {
6498 a[ip] =
6499 (double) ((locate_reg(met0->lon, met0->nx, atm->lon[ip]) * met0->ny +
6500 locate_irr(met0->lat, met0->ny, atm->lat[ip]))
6501 * met0->np + locate_irr(met0->p, met0->np, atm->p[ip]));
6502 p[ip] = ip;
6503 }
6504
6505 /* Sorting... */
6506#ifdef THRUST
6507#ifdef _OPENACC
6508#pragma acc host_data use_device(a,p)
6509#endif
6510 thrustSortWrapper(a, np, p);
6511#else
6512 size_t *perm_sz = (size_t *) malloc((size_t) np * sizeof(size_t));
6513 if (perm_sz == NULL)
6514 ERRMSG("Out of memory!");
6515#ifdef _OPENACC
6516#pragma acc update self(a[0:np])
6517#endif
6518 gsl_sort_index(perm_sz, a, 1, (size_t) np);
6519 for (int ip = 0; ip < np; ++ip)
6520 p[ip] = (int) perm_sz[ip];
6521 free(perm_sz);
6522#ifdef _OPENACC
6523#pragma acc update device(p[0:np])
6524#endif
6525#endif
6526
6527 /* Sort data... */
6528 sort_array(atm->time, p, a, np);
6529 sort_array(atm->p, p, a, np);
6530 sort_array(atm->lon, p, a, np);
6531 sort_array(atm->lat, p, a, np);
6532 for (int iq = 0; iq < ctl->nq; iq++)
6533 sort_array(atm->q[iq], p, a, np);
6534 sort_array(cache->dt, p, a, np);
6535 sort_uvwp(cache, p, a, np);
6536
6537 /* Free... */
6538#ifdef _OPENACC
6539#pragma acc exit data delete(a,p)
6540#endif
6541 free(a);
6542 free(p);
6543}
Here is the call graph for this function:

◆ module_timesteps()

void module_timesteps ( const ctl_t * ctl,
cache_t * cache,
const met_t * met0,
atm_t * atm,
const double t )

Calculate time steps for air parcels based on specified conditions.

This function calculates the time steps for air parcels based on specified conditions, including the direction of simulation, start and stop times, and a given target time. It adjusts the time step for each air parcel accordingly and checks for horizontal boundary conditions of local meteorological data.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the initial meteorological data structure.
atmPointer to the atmospheric data structure containing air parcel information.
tThe target time for which time steps are calculated.
Note
The function sets the time step for each air parcel based on its current time relative to the start and stop times of the simulation, as well as the specified target time t.
It also checks for horizontal boundaries of local meteorological data and adjusts the time step accordingly if necessary.
Author
Lars Hoffmann

Definition at line 6547 of file mptrac.c.

6552 {
6553
6554 /* Set timer... */
6555 SELECT_TIMER("MODULE_TIMESTEPS", "PHYSICS");
6556
6557 const double latmin = gsl_stats_min(met0->lat, 1, (size_t) met0->ny),
6558 latmax = gsl_stats_max(met0->lat, 1, (size_t) met0->ny);
6559
6560 const int local =
6561 (fabs(met0->lon[met0->nx - 1] - met0->lon[0] - 360.0) >= 0.01);
6562
6563 /* Loop over particles... */
6564 PARTICLE_LOOP(0, atm->np, 0, "acc data present(ctl,cache,met0,atm)") {
6565
6566 /* Set time step for each air parcel... */
6567 if ((ctl->direction * (atm->time[ip] - ctl->t_start) >= 0
6568 && ctl->direction * (atm->time[ip] - ctl->t_stop) <= 0
6569 && ctl->direction * (atm->time[ip] - t) < 0))
6570 cache->dt[ip] = t - atm->time[ip];
6571 else
6572 cache->dt[ip] = 0.0;
6573
6574 /* Check horizontal boundaries of local meteo data... */
6575#ifdef DD
6576 /* With domain decomposition, the subdomain rather than the meteo grid
6577 defines the boundaries of a trajectory... */
6578 int dd = (ctl->dd) ? 0 : 1;
6579#else
6580 int dd = 1;
6581#endif
6582 if (dd) {
6583 if (local && (atm->lon[ip] <= met0->lon[0]
6584 || atm->lon[ip] >= met0->lon[met0->nx - 1]
6585 || atm->lat[ip] <= latmin || atm->lat[ip] >= latmax))
6586 cache->dt[ip] = 0.0;
6587 } else {
6588 if ((int) atm->q[ctl->qnt_current_subdomain][ip] == -1)
6589 cache->dt[ip] = 0;
6590 }
6591 }
6592}
float * local
Definition mptrac.c:11232

◆ module_timesteps_init()

void module_timesteps_init ( ctl_t * ctl,
const atm_t * atm )

Initialize start time and time interval for time-stepping.

This function initializes the start time and time interval for time-stepping based on the direction of simulation and the provided atmospheric data. It sets the start time according to the minimum or maximum time in the atmospheric data, depending on the simulation direction. Additionally, it checks the time interval and adjusts the start time accordingly for rounding purposes.

Parameters
ctlPointer to the control structure containing simulation parameters.
atmPointer to the atmospheric data structure containing air parcel information.
Note
The function sets the start time based on the direction of simulation and the minimum or maximum time in the atmospheric data.
It checks the time interval to ensure that there is a valid time range for simulation and adjusts the start time for rounding purposes.
Author
Lars Hoffmann

Definition at line 6596 of file mptrac.c.

6598 {
6599
6600 /* Set timer... */
6601 SELECT_TIMER("MODULE_TIMESTEPS_INIT", "PHYSICS");
6602
6603 /* Set start time... */
6604 if (ctl->direction == 1) {
6605 ctl->t_start = gsl_stats_min(atm->time, 1, (size_t) atm->np);
6606 if (ctl->t_stop > 1e99)
6607 ctl->t_stop = gsl_stats_max(atm->time, 1, (size_t) atm->np);
6608 } else {
6609 ctl->t_start = gsl_stats_max(atm->time, 1, (size_t) atm->np);
6610 if (ctl->t_stop > 1e99)
6611 ctl->t_stop = gsl_stats_min(atm->time, 1, (size_t) atm->np);
6612 }
6613
6614 /* Check time interval... */
6615 if (ctl->direction * (ctl->t_stop - ctl->t_start) <= 0)
6616 ERRMSG("Nothing to do! Check T_STOP and DIRECTION!");
6617
6618 /* Round start time... */
6619 if (ctl->direction == 1)
6620 ctl->t_start = floor(ctl->t_start / ctl->dt_mod) * ctl->dt_mod;
6621 else
6622 ctl->t_start = ceil(ctl->t_start / ctl->dt_mod) * ctl->dt_mod;
6623}

◆ module_tracer_chem()

void module_tracer_chem ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm )

Simulate chemical reactions involving long-lived atmospheric tracers.

This function simulates chemical reactions involving atmospheric tracers, such as CFC-10, CFC-11, CFC-12, and N2O. It calculates the change in tracer concentrations over time based on reaction rates and environmental factors such as temperature, ozone concentration, solar zenith angle, and O(1D) volume mixing ratio.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
climPointer to the climatological data structure.
met0Pointer to the first meteorological data structure.
met1Pointer to the second meteorological data structure.
atmPointer to the atmospheric data structure containing particle information.
Note
The function assumes that the necessary control structure (ctl), climatological data structure (clim), meteorological data structures (met0, met1), and atmospheric data structure (atm) have been initialized and are accessible.
Chemical reactions involving CFC-10, CFC-11, CFC-12, and N2O are simulated for each particle in the atmospheric data structure.
The function calculates reaction rates based on temperature, solar zenith angle, total column ozone, and the volume mixing ratio of O(1D).
The exponential decay of tracer concentrations due to chemical reactions is calculated using reaction rate coefficients and the time step (dt) for each particle.
If the particle has a quantity flag for the tracer species (e.g., ctl->qnt_Cccl4, ctl->qnt_Cccl3f, ctl->qnt_Cccl2f2, ctl->qnt_Cn2o), the function updates the concentration of the tracer based on the exponential decay.
Author
Mingzhao Liu
Lars Hoffmann

Definition at line 6627 of file mptrac.c.

6633 {
6634
6635 if (ctl->met_coord_type != 0)
6636 ERRMSG("Only lat/lon grid supported");
6637
6638 /* Set timer... */
6639 SELECT_TIMER("MODULE_TRACER_CHEM", "PHYSICS");
6640
6641 /* Loop over particles... */
6642 PARTICLE_LOOP(0, atm->np, 1,
6643 "acc data present(ctl,cache,clim,met0,met1,atm)") {
6644
6645 /* Get temperature... */
6646 double t;
6648 INTPOL_3D(t, 1);
6649 if (!isfinite(t) || t <= 0.)
6650 continue;
6651
6652 /* Get molecular density... */
6653 const double M = MOLEC_DENS(atm->p[ip], t);
6654 if (!isfinite(M) || M <= 0.)
6655 continue;
6656
6657 /* Get total column ozone... */
6658 double o3c;
6659 INTPOL_2D(o3c, 1);
6660
6661 /* Get solar zenith angle... */
6662 const double sza =
6663 acos(cos_sza(atm->time[ip], atm->lon[ip], atm->lat[ip]));
6664
6665 /* Get O(1D) volume mixing ratio... */
6666 const double o1d =
6667 clim_zm(&clim->o1d, atm->time[ip], atm->lat[ip], atm->p[ip]);
6668 if (!isfinite(o1d) || o1d < 0.)
6669 continue;
6670
6671 /* Reactions for CFC-10... */
6672 if (ctl->qnt_Cccl4 >= 0) {
6673 const double K_o1d =
6675 const double K_hv = clim_photo(clim->photo.ccl4, &(clim->photo),
6676 atm->p[ip], sza, o3c);
6677 if (isfinite(K_hv) && K_hv >= 0. && isfinite(K_o1d)
6678 && K_o1d >= 0.)
6679 atm->q[ctl->qnt_Cccl4][ip] *= exp(-cache->dt[ip] * (K_hv + K_o1d));
6680 }
6681
6682 /* Reactions for CFC-11... */
6683 if (ctl->qnt_Cccl3f >= 0) {
6684 const double K_o1d =
6686 const double K_hv = clim_photo(clim->photo.ccl3f, &(clim->photo),
6687 atm->p[ip], sza, o3c);
6688 if (isfinite(K_hv) && K_hv >= 0. && isfinite(K_o1d)
6689 && K_o1d >= 0.)
6690 atm->q[ctl->qnt_Cccl3f][ip] *= exp(-cache->dt[ip] * (K_hv + K_o1d));
6691 }
6692
6693 /* Reactions for CFC-12... */
6694 if (ctl->qnt_Cccl2f2 >= 0) {
6695 const double K_o1d =
6697 const double K_hv = clim_photo(clim->photo.ccl2f2, &(clim->photo),
6698 atm->p[ip], sza, o3c);
6699 if (isfinite(K_hv) && K_hv >= 0. && isfinite(K_o1d)
6700 && K_o1d >= 0.)
6701 atm->q[ctl->qnt_Cccl2f2][ip] *= exp(-cache->dt[ip] * (K_hv + K_o1d));
6702 }
6703
6704 /* Reactions for N2O... */
6705 if (ctl->qnt_Cn2o >= 0) {
6706 const double K_o1d =
6708 const double K_hv = clim_photo(clim->photo.n2o, &(clim->photo),
6709 atm->p[ip], sza, o3c);
6710 if (isfinite(K_hv) && K_hv >= 0. && isfinite(K_o1d)
6711 && K_o1d >= 0.)
6712 atm->q[ctl->qnt_Cn2o][ip] *= exp(-cache->dt[ip] * (K_hv + K_o1d));
6713 }
6714 }
6715}
double clim_photo(const double rate[CP][CSZA][CO3], const clim_photo_t *photo, const double p, const double sza, const double o3c)
Calculates the photolysis rate for a given set of atmospheric conditions.
Definition mptrac.c:160
#define O1D_RATE_CFC12_B
O(1D) reaction temperature parameter for CFC-12 [K].
Definition mptrac.h:415
#define O1D_RATE_N2O_A
O(1D) parent-destruction pre-factor for N2O [cm^3 molecule^-1 s^-1].
Definition mptrac.h:420
#define O1D_RATE_CFC12_A
O(1D) parent-destruction pre-factor for CFC-12 [cm^3 molecule^-1 s^-1].
Definition mptrac.h:410
#define O1D_RATE_N2O_B
O(1D) reaction temperature parameter for N2O [K].
Definition mptrac.h:425
#define O1D_RATE_CCL4_B
O(1D) reaction temperature parameter for CCl4 [K].
Definition mptrac.h:395
#define O1D_RATE_CFC11_A
O(1D) parent-destruction pre-factor for CFC-11 [cm^3 molecule^-1 s^-1].
Definition mptrac.h:400
#define O1D_RATE_CCL4_A
O(1D) parent-destruction pre-factor for CCl4 [cm^3 molecule^-1 s^-1].
Definition mptrac.h:390
#define ARRHENIUS(a, b, t)
Calculate the Arrhenius rate constant.
Definition mptrac.h:736
#define O1D_RATE_CFC11_B
O(1D) reaction temperature parameter for CFC-11 [K].
Definition mptrac.h:405
double ccl2f2[CP][CSZA][CO3]
CCl2F2 photolysis rate [1/s].
Definition mptrac.h:3815
double ccl3f[CP][CSZA][CO3]
CCl3F photolysis rate [1/s].
Definition mptrac.h:3812
double n2o[CP][CSZA][CO3]
N2O photolysis rate [1/s].
Definition mptrac.h:3806
double ccl4[CP][CSZA][CO3]
CCl4 photolysis rate [1/s].
Definition mptrac.h:3809
clim_photo_t photo
Photolysis rates.
Definition mptrac.h:3911
Here is the call graph for this function:

◆ module_wet_depo()

void module_wet_depo ( const ctl_t * ctl,
const cache_t * cache,
met_t * met0,
met_t * met1,
atm_t * atm )

Perform wet deposition calculations for air parcels.

This function calculates the wet deposition process for each air parcel based on provided atmospheric and meteorological data. It estimates the precipitation rate and scavenging coefficients for particles and gases inside and below cloud layers. The scavenging coefficients are used to calculate the exponential decay of mass or volume mixing ratio over time due to wet deposition.

Parameters
ctlPointer to the control structure containing simulation parameters.
cachePointer to the cache structure for temporary data and random numbers.
met0Pointer to the initial meteorological data structure.
met1Pointer to the updated meteorological data structure.
atmPointer to the atmospheric data structure containing air parcel information.
Note
The function calculates the wet deposition process for particles and gases based on precipitation rate and scavenging coefficients inside and below cloud layers.
It estimates the exponential decay of mass or volume mixing ratio over time due to wet deposition.
Positive empirical A takes precedence over Henry coefficients in each cloud branch; an unconfigured branch has zero scavenging. For empirical coefficient examples see Bakels et al. (2024).
For Henry's law constants see Sander (2023) or https://henrys-law.org/.
Some species (e.g. SO2) require an effective Henry constant to account not only for physical solubility in water but also for chemical reactions, such as hydrolysis and ionization, which significantly enhance dissolution in aqueous solutions. The SO2 pH correction applies to the in-cloud Henry branch only; see Liu et al. (2023), https://doi.org/10.5194/gmd-16-5197-2023. The mass update uses each particle's signed timestep; negative timesteps reverse the exponential loss mathematically.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 6719 of file mptrac.c.

6724 {
6725
6726 /* Set timer... */
6727 SELECT_TIMER("MODULE_WET_DEPO", "PHYSICS");
6728
6729 /* Check quantity flags... */
6730 if (ctl->qnt_m < 0 && ctl->qnt_vmr < 0)
6731 ERRMSG("Module needs quantity mass or volume mixing ratio!");
6732
6733 /* Loop over particles... */
6734 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,cache,met0,met1,atm)") {
6735
6736 /* Check whether particle is below cloud top... */
6737 double pct;
6739 INTPOL_2D(pct, 1);
6740 if (!isfinite(pct) || atm->p[ip] <= pct)
6741 continue;
6742
6743 /* Get cloud bottom pressure... */
6744 double pcb;
6745 INTPOL_2D(pcb, 0);
6746
6747 /* Estimate precipitation rate (Pisso et al., 2019)... */
6748 double cl;
6749 INTPOL_2D(cl, 0);
6750 const double Is =
6751 pow(1. / ctl->wet_depo_pre[0] * cl, 1. / ctl->wet_depo_pre[1]);
6752 if (!isfinite(Is) || Is < 0.01)
6753 continue;
6754
6755 /* Check whether particle is inside or below cloud... */
6756 double lwc, rwc, iwc, swc;
6757 INTPOL_3D(lwc, 1);
6758 INTPOL_3D(rwc, 0);
6759 INTPOL_3D(iwc, 0);
6760 INTPOL_3D(swc, 0);
6761 const int inside = (lwc > 0 || rwc > 0 || iwc > 0 || swc > 0);
6762
6763 /* Get temperature... */
6764 double t;
6765 INTPOL_3D(t, 0);
6766 if (!isfinite(t) || t <= 0.)
6767 continue;
6768
6769 /* Calculate in-cloud scavenging coefficient... */
6770 double lambda = 0;
6771 if (inside) {
6772
6773 /* Calculate retention factor... */
6774 double eta;
6775 if (t > WET_DEPO_T_LIQUID)
6776 eta = 1;
6777 else if (t <= WET_DEPO_T_ICE)
6778 eta = ctl->wet_depo_ic_ret_ratio;
6779 else
6780 eta =
6782 ctl->wet_depo_ic_ret_ratio, t);
6783
6784 /* Use exponential dependency for particles (Bakels et al., 2024)... */
6785 if (ctl->wet_depo_ic_a > 0)
6786 lambda = ctl->wet_depo_ic_a * pow(Is, ctl->wet_depo_ic_b) * eta;
6787
6788 /* Use Henry's law for gases... */
6789 else if (ctl->wet_depo_ic_h[0] > 0) {
6790
6791 /* Get Henry's constant (Burkholder et al., 2019; Sander, 2023)... */
6792 double h = ctl->wet_depo_ic_h[0]
6793 * exp(ctl->wet_depo_ic_h[1] * (1. / t - 1. / CHEM_REF_TEMP));
6794
6795 /* Use effective Henry's constant for SO2
6796 (Berglen, 2004; Simpson, 2012)... */
6797 if (ctl->wet_depo_so2_ph > 0) {
6798 const double H_ion = pow(10., -ctl->wet_depo_so2_ph);
6799 const double K_1 = SO2_DISS_K1_REF
6800 * exp(SO2_DISS_K1_TEMP * (1. / t - 1. / CHEM_REF_TEMP));
6801 const double K_2 = SO2_DISS_K2_REF
6802 * exp(SO2_DISS_K2_TEMP * (1. / t - 1. / CHEM_REF_TEMP));
6803 h *= (1. + K_1 / H_ion + K_1 * K_2 / SQR(H_ion));
6804 }
6805
6806 /* Estimate depth of cloud layer... */
6807 const double dz = 1e3 * (Z(pct) - Z(pcb));
6808 if (!isfinite(dz) || dz <= 0.)
6809 continue;
6810
6811 /* Calculate scavenging coefficient... */
6812 lambda = h * RI * t * Is / 3.6e6 / dz * eta;
6813 }
6814 }
6815
6816 /* Calculate below-cloud scavenging coefficient... */
6817 else {
6818
6819 /* Calculate retention factor... */
6820 double eta;
6821 if (t > WET_DEPO_T_LIQUID_BC)
6822 eta = 1;
6823 else
6824 eta = ctl->wet_depo_bc_ret_ratio;
6825
6826 /* Use exponential dependency for particles (Bakels et al., 2024)... */
6827 if (ctl->wet_depo_bc_a > 0)
6828 lambda = ctl->wet_depo_bc_a * pow(Is, ctl->wet_depo_bc_b) * eta;
6829
6830 /* Use Henry's law for gases... */
6831 else if (ctl->wet_depo_bc_h[0] > 0) {
6832
6833 /* Get Henry's constant (Burkholder et al., 2019; Sander, 2023)... */
6834 const double h = ctl->wet_depo_bc_h[0]
6835 * exp(ctl->wet_depo_bc_h[1] * (1. / t - 1. / CHEM_REF_TEMP));
6836
6837 /* Estimate depth of cloud layer... */
6838 const double dz = 1e3 * (Z(pct) - Z(pcb));
6839 if (!isfinite(dz) || dz <= 0.)
6840 continue;
6841
6842 /* Calculate scavenging coefficient... */
6843 lambda = h * RI * t * Is / 3.6e6 / dz * eta;
6844 }
6845 }
6846
6847 /* Calculate exponential decay of mass... */
6848 if (!isfinite(lambda) || lambda < 0.)
6849 continue;
6850 const double aux = exp(-cache->dt[ip] * lambda);
6851 if (ctl->qnt_m >= 0) {
6852 if (ctl->qnt_mloss_wet >= 0)
6853 atm->q[ctl->qnt_mloss_wet][ip]
6854 += atm->q[ctl->qnt_m][ip] * (1 - aux);
6855 atm->q[ctl->qnt_m][ip] *= aux;
6856 if (ctl->qnt_loss_rate >= 0)
6857 atm->q[ctl->qnt_loss_rate][ip] += lambda;
6858 }
6859 if (ctl->qnt_vmr >= 0)
6860 atm->q[ctl->qnt_vmr][ip] *= aux;
6861 }
6862}
#define SO2_DISS_K2_TEMP
Temperature dependence of the second SO2 dissociation constant [K].
Definition mptrac.h:445
#define SO2_DISS_K2_REF
Second SO2 dissociation constant at CHEM_REF_TEMP [mol/L].
Definition mptrac.h:440
double wet_depo_ic_a
Coefficient A for wet deposition in cloud (exponential form).
Definition mptrac.h:3340
double wet_depo_bc_a
Coefficient A for wet deposition below cloud (exponential form).
Definition mptrac.h:3334
int qnt_mloss_wet
Quantity array index for total mass loss due to wet deposition.
Definition mptrac.h:2738
double wet_depo_so2_ph
pH value used to calculate effective Henry constant of SO2.
Definition mptrac.h:3352
double wet_depo_bc_h[2]
Below-cloud Henry coefficients (reference solubility, temperature coefficient).
Definition mptrac.h:3349
double wet_depo_ic_h[2]
In-cloud Henry coefficients (reference solubility, temperature coefficient).
Definition mptrac.h:3346
double wet_depo_ic_b
Coefficient B for wet deposition in cloud (exponential form).
Definition mptrac.h:3343
double wet_depo_bc_b
Coefficient B for wet deposition below cloud (exponential form).
Definition mptrac.h:3337

◆ mptrac_alloc()

void mptrac_alloc ( ctl_t ** ctl,
cache_t ** cache,
clim_t ** clim,
met_t ** met0,
met_t ** met1,
atm_t ** atm,
depo_t ** depo,
dd_t ** dd )

Allocates and initializes memory resources for MPTRAC.

This function handles memory allocation for various data structures and sets up GPU resources if available. It also creates the necessary data regions on GPUs for OpenACC-enabled execution. Each output parameter is optional; pass NULL for structures that are not needed.

Parameters
[out]ctlPointer to the control structure (ctl_t).
[out]cachePointer to the cache structure (cache_t).
[out]climPointer to the climatology structure (clim_t).
[out]met0Pointer to the first meteorology structure (met_t).
[out]met1Pointer to the second meteorology structure (met_t).
[out]atmPointer to the atmospheric structure (atm_t).
[out]depoPointer to the radionuclide ground-inventory structure (depo_t).
[out]ddpointer to an dd_t structure containing MPI information, including rank and neighbours.
Note
This function uses OpenACC for GPU initialization and memory management. If OpenACC is not enabled, the GPU-specific code is ignored.
Precondition
The function requires an environment supporting OpenACC for GPU operations. MPI support is optional but assumed if compiled with MPI.
Postcondition
Allocated structures are ready for use, and data regions on GPUs are initialized if OpenACC is enabled.
Exceptions
Runtimeerror if no GPU devices are available when OpenACC is enabled.
Author
Lars Hoffmann

Definition at line 6866 of file mptrac.c.

6874 {
6875
6876 /* Initialize GPU... */
6877#ifdef _OPENACC
6878 if (ctl != NULL || cache != NULL || clim != NULL || met0 != NULL
6879 || met1 != NULL || atm != NULL || depo != NULL || dd != NULL) {
6880 SELECT_TIMER("ACC_INIT", "INIT");
6881 if (acc_get_num_devices(acc_device_nvidia) <= 0)
6882 ERRMSG("Not running on a GPU device!");
6883 acc_device_t device_type = acc_get_device_type();
6884 acc_init(device_type);
6885 }
6886#endif
6887
6888 /* Allocate... */
6889 SELECT_TIMER("ALLOC", "MEMORY");
6890 if (ctl != NULL)
6891 ALLOC(*ctl, ctl_t, 1);
6892 if (cache != NULL)
6893 ALLOC(*cache, cache_t, 1);
6894 if (clim != NULL)
6895 ALLOC(*clim, clim_t, 1);
6896 if (met0 != NULL)
6897 ALLOC(*met0, met_t, 1);
6898 if (met1 != NULL)
6899 ALLOC(*met1, met_t, 1);
6900 if (atm != NULL)
6901 ALLOC(*atm, atm_t, 1);
6902 if (depo != NULL)
6903 ALLOC(*depo, depo_t, 1);
6904 if (dd != NULL) {
6905 ALLOC(*dd, dd_t, 1);
6906
6907 /* Initialize the MPI datatype such that mptrac_free() knows whether
6908 dd_init() has created it... */
6909#ifdef DD
6910 (*dd)->MPI_Particle = MPI_DATATYPE_NULL;
6911#endif
6912 }
6913
6914 /* Create data region on GPU... */
6915#ifdef _OPENACC
6916 SELECT_TIMER("CREATE_DATA_REGION", "MEMORY");
6917 if (ctl != NULL) {
6918 ctl_t *ctlup = *ctl;
6919#pragma acc enter data create(ctlup[:1])
6920 }
6921 if (cache != NULL) {
6922 cache_t *cacheup = *cache;
6923#pragma acc enter data create(cacheup[:1])
6924 }
6925 if (clim != NULL) {
6926 clim_t *climup = *clim;
6927#pragma acc enter data create(climup[:1])
6928 }
6929 if (met0 != NULL) {
6930 met_t *met0up = *met0;
6931#pragma acc enter data create(met0up[:1])
6932 }
6933 if (met1 != NULL) {
6934 met_t *met1up = *met1;
6935#pragma acc enter data create(met1up[:1])
6936 }
6937 if (atm != NULL) {
6938 atm_t *atmup = *atm;
6939#pragma acc enter data create(atmup[:1])
6940 }
6941 if (depo != NULL) {
6942 depo_t *depoup = *depo;
6943#pragma acc enter data create(depoup[:1])
6944 }
6945#ifdef DD
6946 if (dd != NULL) {
6947 dd_t *ddup = *dd;
6948#pragma acc enter data create(ddup[:1])
6949 }
6950#endif
6951#endif
6952}
Air parcel data.
Definition mptrac.h:3662
Cache data structure.
Definition mptrac.h:3726
Climatological data.
Definition mptrac.h:3893
Control parameters.
Definition mptrac.h:2557
Domain decomposition data structure.
Definition mptrac.h:4129
Ground inventories of deposited radionuclides.
Definition mptrac.h:3762
Meteo data structure.
Definition mptrac.h:3952

◆ mptrac_free()

void mptrac_free ( ctl_t * ctl,
cache_t * cache,
clim_t * clim,
met_t * met0,
met_t * met1,
atm_t * atm,
depo_t * depo,
dd_t * dd )

Frees memory resources allocated for MPTRAC.

This function releases the memory allocated for various data structures and deletes any associated data regions on GPUs if OpenACC is enabled. Every argument may be NULL.

Parameters
[in]ctlPointer to the control structure (ctl_t) to be freed.
[in]cachePointer to the cache structure (cache_t) to be freed.
[in]climPointer to the climatology structure (clim_t) to be freed.
[in]met0Pointer to the first meteorology structure (met_t) to be freed.
[in]met1Pointer to the second meteorology structure (met_t) to be freed.
[in]atmPointer to the atmospheric structure (atm_t) to be freed.
[in]depoPointer to the radionuclide ground-inventory structure (depo_t) to be freed.
[in]ddPointer to an dd_t structure containing MPI information, including rank and neighbours.
Note
This function uses OpenACC for GPU memory management. If OpenACC is not enabled, the GPU-specific code is ignored.
Precondition
Non-NULL input pointers must have been returned through the corresponding argument of mptrac_alloc().
Postcondition
All input pointers are freed, and the associated data regions on GPUs are deleted if OpenACC is enabled.
Warning
Ensure that the input pointers are not used after calling this function as they will be invalidated.
Author
Lars Hoffmann

Definition at line 6956 of file mptrac.c.

6964 {
6965
6966#ifdef DD
6967#if LOGLEV >= 2
6968 if (dd_node != NULL) {
6969 int rank;
6970 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
6971 LOG(2, "DD_COMM rank=%d sent=%llu intra=%llu inter=%llu "
6972 "intra_bytes=%llu inter_bytes=%llu particle_bytes=%d",
6973 rank, dd_sent, dd_intra, dd_inter,
6974 dd_intra * (unsigned long long) dd_particle_bytes,
6975 dd_inter * (unsigned long long) dd_particle_bytes,
6976 dd_particle_bytes);
6977 free(dd_node);
6978 dd_node = NULL;
6979 }
6980#endif
6981#endif
6982
6983 /* Delete data region on GPU... */
6984#ifdef _OPENACC
6985 SELECT_TIMER("DELETE_DATA_REGION", "MEMORY");
6986 if (ctl != NULL) {
6987#pragma acc exit data delete(ctl[:1])
6988 }
6989 if (cache != NULL) {
6990#pragma acc exit data delete(cache[:1])
6991 }
6992 if (clim != NULL) {
6993#pragma acc exit data delete(clim[:1])
6994 }
6995 if (met0 != NULL) {
6996#pragma acc exit data delete(met0[:1])
6997 }
6998 if (met1 != NULL) {
6999#pragma acc exit data delete(met1[:1])
7000 }
7001 if (atm != NULL) {
7002#pragma acc exit data delete(atm[:1])
7003 }
7004 if (depo != NULL) {
7005#pragma acc exit data delete(depo[:1])
7006 }
7007#ifdef DD
7008 if (dd != NULL) {
7009#pragma acc exit data delete(dd[:1])
7010 }
7011#endif
7012#endif
7013
7014 /* Free... */
7015 SELECT_TIMER("FREE", "MEMORY");
7016 free(atm);
7017 free(depo);
7018 free(ctl);
7019 free(cache);
7020 free(clim);
7021 free(met0);
7022 free(met1);
7023
7024 /* Free MPI datatype... */
7025#ifdef DD
7026 if (dd != NULL && dd->MPI_Particle != MPI_DATATYPE_NULL)
7027 MPI_Type_free(&dd->MPI_Particle);
7028#endif
7029 free(dd);
7030}

◆ mptrac_get_met()

void mptrac_get_met ( ctl_t * ctl,
clim_t * clim,
const double t,
met_t ** met0,
met_t ** met1,
dd_t * dd )

Retrieves meteorological data for the specified time.

This function retrieves meteorological data for the given time t and updates the provided pointers to the met0 and met1 structures accordingly. It handles both the initialization and subsequent updates of the meteorological data based on the direction of time integration.

Parameters
ctlPointer to the control structure containing configuration settings.
climPointer to the climate structure.
tThe current time for which meteorological data is to be retrieved.
met0Pointer to the pointer of the first meteorological data structure.
met1Pointer to the pointer of the second meteorological data structure.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.

The function performs the following steps:

  • Initializes meteorological data on the first call or when the simulation restarts.
  • Reads new meteorological data when advancing forward or backward in time.
  • Swaps pointers to manage double buffering of the meteorological data.
  • Performs caching to optimize subsequent data retrieval.
  • Ensures consistency of the meteorological grids.
Note
This function utilizes GPU acceleration with OpenACC directives if enabled.
Ensure that ctl, clim, met0, and met1 are properly initialized before calling this function.
See also
get_met_filename
read_met
SELECT_TIMER
LOG
ERRMSG
WARN
Author
Lars Hoffmann

Definition at line 7034 of file mptrac.c.

7040 {
7041
7042 static int init;
7043
7044 met_t *mets;
7045
7046 char cachefile[LEN], cmd[2 * LEN], filename[LEN];
7047
7048 /* Set timer... */
7049 SELECT_TIMER("GET_MET", "INPUT");
7050
7051 /* Init... */
7052 if (t == ctl->t_start || !init) {
7053 init = 1;
7054
7055 /* Read meteo data... */
7056 get_met_filename(ctl, t + (ctl->direction == -1 ? -1 : 0), -1,
7057 ctl->metbase, ctl->dt_met, filename);
7058 if (!mptrac_read_met(filename, ctl, clim, *met0, dd))
7059 ERRMSG("Cannot open file!");
7060
7061 get_met_filename(ctl, t + (ctl->direction == 1 ? 1 : 0), 1,
7062 ctl->metbase, ctl->dt_met, filename);
7063 if (!mptrac_read_met(filename, ctl, clim, *met1, dd))
7064 ERRMSG("Cannot open file!");
7065
7066 /* Update GPU... */
7067 mptrac_update_device(NULL, NULL, NULL, met0, met1, NULL);
7068 SELECT_TIMER("GET_MET", "INPUT");
7069
7070 /* Caching... */
7071 if (ctl->met_cache && t != ctl->t_stop) {
7072 get_met_filename(ctl, t + 1.1 * ctl->dt_met * ctl->direction,
7073 ctl->direction, ctl->metbase, ctl->dt_met, cachefile);
7074 sprintf(cmd, "cat %s > /dev/null &", cachefile);
7075 LOG(1, "Caching: %s", cachefile);
7076 if (system(cmd) != 0)
7077 WARN("Caching command failed!");
7078 }
7079 }
7080
7081 /* Read new data for forward trajectories... */
7082 if (t > (*met1)->time) {
7083
7084 /* Pointer swap... */
7085 mets = *met1;
7086 *met1 = *met0;
7087 *met0 = mets;
7088
7089 /* Read new meteo data... */
7090 get_met_filename(ctl, t, 1, ctl->metbase, ctl->dt_met, filename);
7091 if (!mptrac_read_met(filename, ctl, clim, *met1, dd))
7092 ERRMSG("Cannot open file!");
7093
7094 /* Update GPU... */
7095 mptrac_update_device(NULL, NULL, NULL, NULL, met1, NULL);
7096 SELECT_TIMER("GET_MET", "INPUT");
7097
7098 /* Caching... */
7099 if (ctl->met_cache && t != ctl->t_stop) {
7100 get_met_filename(ctl, t + ctl->dt_met, 1, ctl->metbase, ctl->dt_met,
7101 cachefile);
7102 sprintf(cmd, "cat %s > /dev/null &", cachefile);
7103 LOG(1, "Caching: %s", cachefile);
7104 if (system(cmd) != 0)
7105 WARN("Caching command failed!");
7106 }
7107 }
7108
7109 /* Read new data for backward trajectories... */
7110 if (t < (*met0)->time) {
7111
7112 /* Pointer swap... */
7113 mets = *met1;
7114 *met1 = *met0;
7115 *met0 = mets;
7116
7117 /* Read new meteo data... */
7118 get_met_filename(ctl, t, -1, ctl->metbase, ctl->dt_met, filename);
7119 if (!mptrac_read_met(filename, ctl, clim, *met0, dd))
7120 ERRMSG("Cannot open file!");
7121
7122 /* Update GPU... */
7123 mptrac_update_device(NULL, NULL, NULL, met0, NULL, NULL);
7124 SELECT_TIMER("GET_MET", "INPUT");
7125
7126 /* Caching... */
7127 if (ctl->met_cache && t != ctl->t_stop) {
7128 get_met_filename(ctl, t - ctl->dt_met, -1, ctl->metbase, ctl->dt_met,
7129 cachefile);
7130 sprintf(cmd, "cat %s > /dev/null &", cachefile);
7131 LOG(1, "Caching: %s", cachefile);
7132 if (system(cmd) != 0)
7133 WARN("Caching command failed!");
7134 }
7135 }
7136
7137 if (!((*met0)->time < (*met1)->time))
7138 ERRMSG("Meteo times must be strictly increasing!");
7139
7140 if ((*met0)->coord_type != (*met1)->coord_type)
7141 ERRMSG("Coordinate types do not match!");
7142
7143 /* Check that grids are consistent... */
7144 if ((*met0)->nx != 0 && (*met1)->nx != 0) {
7145 if ((*met0)->nx != (*met1)->nx
7146 || (*met0)->ny != (*met1)->ny || (*met0)->np != (*met1)->np)
7147 ERRMSG("Meteo grid dimensions do not match!");
7148 if ((ctl->advect_vert_coord == 1
7149 || (ctl->advect > 0 && ctl->advect_vert_coord > 1)
7150 || ctl->qnt_eta_d >= 0
7151 || (ctl->advect_vert_coord == 3 && ctl->qnt_eta_dot >= 0))
7152 && ((*met0)->npl < 2 || (*met0)->npl != (*met1)->npl))
7153 ERRMSG("Meteo native level counts do not match!");
7154 for (int ix = 0; ix < (*met0)->nx; ix++)
7155 if (fabs((*met0)->lon[ix] - (*met1)->lon[ix]) > 0.001)
7156 ERRMSG("Meteo grid longitudes do not match!");
7157 for (int iy = 0; iy < (*met0)->ny; iy++)
7158 if (fabs((*met0)->lat[iy] - (*met1)->lat[iy]) > 0.001)
7159 ERRMSG("Meteo grid latitudes do not match!");
7160 for (int ip = 0; ip < (*met0)->np; ip++)
7161 if (fabs((*met0)->p[ip] - (*met1)->p[ip]) > 0.001)
7162 ERRMSG("Meteo grid pressure levels do not match!");
7163 }
7164}
void get_met_filename(const ctl_t *ctl, const double t, const int direct, const char *metbase, const double dt_met, char *filename)
Generates a formatted filename for meteorological data files based on the input parameters.
Definition mptrac.c:2949
int mptrac_read_met(const char *filename, const ctl_t *ctl, const clim_t *clim, met_t *met, dd_t *dd)
Reads meteorological data from a file, supporting multiple formats and MPI broadcasting.
Definition mptrac.c:8673
int met_cache
Preload meteo data into disk cache (0=no, 1=yes).
Definition mptrac.h:3076
char metbase[LEN]
Basename for meteo data.
Definition mptrac.h:2908
Here is the call graph for this function:

◆ mptrac_init()

void mptrac_init ( ctl_t * ctl,
cache_t * cache,
clim_t * clim,
atm_t * atm,
depo_t * depo,
const int ntask )

Initializes the MPTRAC model and its associated components.

This function sets up the necessary components and subsystems for the MPTRAC module, including timesteps, random number generation, and GPU memory updates.

Parameters
ctlPointer to the control structure containing configuration and state information.
cachePointer to the cache structure used for data storage and retrieval.
climPointer to the climatology structure containing climate-related data.
atmPointer to the atmospheric structure containing atmospheric state data.
depoPointer to inventories allocated and zero-initialized by mptrac_alloc().
ntaskNumber of tasks or threads to initialize for the random number generator.

The function performs the following operations:

  • Initializes the timesteps using the module_timesteps_init function.
  • Initializes the random number generator using the module_rng_init function.
  • Updates GPU memory using the mptrac_update_device function.
Author
Lars Hoffmann

Definition at line 7168 of file mptrac.c.

7174 {
7175
7176 if (ctl->advect_vert_coord == 1)
7177 for (int ip = 1; ip < atm->np; ip++)
7178 if (atm->time[ip] != atm->time[0])
7179 ERRMSG("Zeta advection requires identical particle initialization times!");
7180
7181 /* Initialize timesteps... */
7182 module_timesteps_init(ctl, atm);
7183
7184 /* Reset per-particle isosurface initialization between tasks. */
7185 if (ctl->isosurf == 2 || ctl->isosurf == 3)
7186 memset(cache->iso_init, 0, (size_t) atm->np * sizeof(cache->iso_init[0]));
7187
7188 /* Initialize random number generator... */
7189 module_rng_init(ntask);
7190
7191 /* Update GPU memory... */
7192 mptrac_update_device(ctl, cache, clim, NULL, NULL, atm);
7193#ifdef _OPENACC
7194#pragma acc update device(depo[:1])
7195#else
7196 (void) depo;
7197#endif
7198}
void module_timesteps_init(ctl_t *ctl, const atm_t *atm)
Initialize start time and time interval for time-stepping.
Definition mptrac.c:6596
void module_rng_init(const int ntask)
Initialize random number generators for parallel tasks.
Definition mptrac.c:6300
Here is the call graph for this function:

◆ mptrac_read_atm()

int mptrac_read_atm ( const char * filename,
const ctl_t * ctl,
atm_t * atm )

Reads air parcel data from a specified file into the given atmospheric structure.

This function reads air parcel data from a file and populates the provided atm_t structure based on the type of data specified in the ctl_t control structure. It supports various data formats including ASCII, binary, netCDF, and CLaMS.

Parameters
filenameThe name of the file containing the atmospheric data.
ctlA pointer to the control structure (ctl_t) that specifies the type of data.
atmA pointer to the atmospheric structure (atm_t) that will be populated with the data.
Returns
Returns 1 on success, and 0 on failure.

This function performs the following steps:

  • Sets a timer for performance measurement.
  • Initializes the atmospheric structure.
  • Logs the file being read.
  • Reads data from the file based on the specified type (ctl->atm_type):
    • 0 for ASCII data
    • 1 for binary data
    • 2 for netCDF data
    • 3 or 4 for CLaMS data
  • Handles errors if the data type is not supported.
  • Checks the result of the data reading function and ensures data was read successfully.
  • Logs information about the number of air parcels and the ranges of various parameters (time, altitude, pressure, longitude, latitude, and other quantities).

The function utilizes several helper functions and macros:

  • SELECT_TIMER for setting the timer.
  • LOG for logging information.
  • ERRMSG for handling error messages.
  • gsl_stats_minmax for calculating minimum and maximum values.
  • Z for converting altitude.
Author
Lars Hoffmann

Definition at line 7202 of file mptrac.c.

7205 {
7206
7207 int result;
7208
7209 /* Set timer... */
7210 SELECT_TIMER("READ_ATM", "INPUT");
7211
7212 /* Init... */
7213 atm->np = 0;
7214
7215 /* Write info... */
7216 LOG(1, "Read atmospheric data: %s", filename);
7217
7218 /* Read ASCII data... */
7219 if (ctl->atm_type == 0)
7220 result = read_atm_asc(filename, ctl, atm);
7221
7222 /* Read binary data... */
7223 else if (ctl->atm_type == 1)
7224 result = read_atm_bin(filename, ctl, atm);
7225
7226 /* Read netCDF data... */
7227 else if (ctl->atm_type == 2)
7228 result = read_atm_nc(filename, ctl, atm);
7229
7230 /* Read CLaMS data... */
7231 else if (ctl->atm_type == 3 || ctl->atm_type == 4)
7232 result = read_atm_clams(filename, ctl, atm);
7233
7234 /* Error... */
7235 else
7236 ERRMSG("Atmospheric data type not supported!");
7237
7238 /* Check result... */
7239 if (result != 1)
7240 return 0;
7241
7242 /* Check number of air parcels... */
7243 if (atm->np < 1)
7244 ERRMSG("Can not read any data!");
7245
7246 /* Write info... */
7247 double mini, maxi;
7248 LOG(2, "Number of particles: %d", atm->np);
7249 gsl_stats_minmax(&mini, &maxi, atm->time, 1, (size_t) atm->np);
7250 LOG(2, "Time range: %.2f ... %.2f s", mini, maxi);
7251 gsl_stats_minmax(&mini, &maxi, atm->p, 1, (size_t) atm->np);
7252 LOG(2, "Altitude range: %g ... %g km", Z(maxi), Z(mini));
7253 LOG(2, "Pressure range: %g ... %g hPa", maxi, mini);
7254 gsl_stats_minmax(&mini, &maxi, atm->lon, 1, (size_t) atm->np);
7255 LOG(2, "%s range: %g ... %g %s",
7256 ctl->met_coord_type == 0 ? "Longitude" : "X coordinate", mini, maxi,
7257 ctl->met_coord_type == 0 ? "deg" : "m");
7258 gsl_stats_minmax(&mini, &maxi, atm->lat, 1, (size_t) atm->np);
7259 LOG(2, "%s range: %g ... %g %s",
7260 ctl->met_coord_type == 0 ? "Latitude" : "Y coordinate", mini, maxi,
7261 ctl->met_coord_type == 0 ? "deg" : "m");
7262 for (int iq = 0; iq < ctl->nq; iq++) {
7263 char msg[5 * LEN];
7264 sprintf(msg, "Quantity %s range: %s ... %s %s",
7265 ctl->qnt_name[iq], ctl->qnt_format[iq],
7266 ctl->qnt_format[iq], ctl->qnt_unit[iq]);
7267 gsl_stats_minmax(&mini, &maxi, atm->q[iq], 1, (size_t) atm->np);
7268 LOG(2, msg, mini, maxi);
7269 }
7270
7271 /* Return success... */
7272 return 1;
7273}
int read_atm_nc(const char *filename, const ctl_t *ctl, atm_t *atm)
Reads air parcel data from a generic netCDF file and populates the given atmospheric structure.
Definition mptrac.c:9552
int read_atm_bin(const char *filename, const ctl_t *ctl, atm_t *atm)
Reads air parcel data from a binary file and populates the given atmospheric structure.
Definition mptrac.c:9431
int read_atm_clams(const char *filename, const ctl_t *ctl, atm_t *atm)
Reads atmospheric data from a CLAMS NetCDF file.
Definition mptrac.c:9489
int read_atm_asc(const char *filename, const ctl_t *ctl, atm_t *atm)
Reads air parcel data from an ASCII file and populates the given atmospheric structure.
Definition mptrac.c:9387
char qnt_format[NQ][LEN]
Quantity output format.
Definition mptrac.h:2576
int atm_type
Type of atmospheric data files (0=ASCII, 1=binary, 2=netCDF, 3=CLaMS_traj, 4=CLaMS_pos).
Definition mptrac.h:3405
char qnt_unit[NQ][LEN]
Quantity units.
Definition mptrac.h:2573
char qnt_name[NQ][LEN]
Quantity names.
Definition mptrac.h:2567
Here is the call graph for this function:

◆ mptrac_read_clim()

void mptrac_read_clim ( const ctl_t * ctl,
clim_t * clim )

Reads various climatological data and populates the given climatology structure.

This function reads a range of climatological datasets based on the specified control settings and stores the data in the provided clim_t structure. It handles initialization of tropopause climatology, photolysis rates, and multiple gas species' climatologies and time series.

Parameters
ctlA pointer to the control structure (ctl_t) that specifies file names and parameters for climatology data.
climA pointer to the climatology structure (clim_t) that will be populated with the data.

This function performs the following steps:

  • Sets a timer for reading climatology data.
  • Initializes the tropopause climatology.
  • Reads photolysis rates if specified in ctl.
  • Reads HNO3 climatology if specified in ctl.
  • Reads OH climatology if specified in ctl and applies a diurnal correction if specified.
  • Reads H2O2, HO2, O(1D) climatologies if specified in ctl.
  • Reads time series data for various gases (CFC-10, CFC-11, CFC-12, N2O, SF6) if specified in ctl.

The function utilizes several helper functions:

  • clim_tropo_init for initializing tropopause climatology.
  • read_clim_photo for reading photolysis rates.
  • read_clim_zm for reading zonal mean climatologies.
  • clim_oh_diurnal_correction for applying diurnal correction to OH climatology.
  • read_clim_ts for reading time series data.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 7277 of file mptrac.c.

7279 {
7280
7281 /* Set timer... */
7282 SELECT_TIMER("READ_CLIM", "INPUT");
7283
7284 /* Init tropopause climatology... */
7285 clim_tropo_init(clim);
7286
7287 /* Read photolysis rates... */
7288 if (ctl->clim_photo[0] != '-')
7289 read_clim_photo(ctl->clim_photo, &clim->photo);
7290
7291 /* Read HNO3 climatology... */
7292 if (ctl->clim_hno3_filename[0] != '-')
7293 read_clim_zm(ctl->clim_hno3_filename, "HNO3", &clim->hno3);
7294
7295 /* Read OH climatology... */
7296 if (ctl->clim_oh_filename[0] != '-') {
7297 read_clim_zm(ctl->clim_oh_filename, "OH", &clim->oh);
7298 }
7299 if (ctl->oh_chem_reaction > 0
7300 && (clim->oh.ntime < 2 || clim->oh.nlat < 2 || clim->oh.np < 2))
7301 ERRMSG("OH_CHEM_REACTION requires a valid CLIM_OH_FILENAME climatology!");
7302 if (ctl->oh_chem_beta > 0 && clim->oh.ntime >= 2)
7303 clim_oh_diurnal_correction(ctl, clim);
7304
7305 /* Read H2O2 climatology... */
7306 if (ctl->clim_h2o2_filename[0] != '-')
7307 read_clim_zm(ctl->clim_h2o2_filename, "H2O2", &clim->h2o2);
7308 if (ctl->h2o2_chem_reaction > 0
7309 && (clim->h2o2.ntime < 2 || clim->h2o2.nlat < 2
7310 || clim->h2o2.np < 2))
7311 ERRMSG("H2O2_CHEM_REACTION requires a valid CLIM_H2O2_FILENAME climatology!");
7312
7313 /* Read HO2 climatology... */
7314 if (ctl->clim_ho2_filename[0] != '-')
7315 read_clim_zm(ctl->clim_ho2_filename, "HO2", &clim->ho2);
7316
7317 /* Read O(1D) climatology... */
7318 if (ctl->clim_o1d_filename[0] != '-')
7319 read_clim_zm(ctl->clim_o1d_filename, "O1D", &clim->o1d);
7320 if (ctl->tracer_chem && (ctl->qnt_Cccl4 >= 0 || ctl->qnt_Cccl3f >= 0
7321 || ctl->qnt_Cccl2f2 >= 0 || ctl->qnt_Cn2o >= 0)) {
7322 if (clim->photo.np < 2 || clim->photo.nsza < 2 || clim->photo.no3c < 2)
7323 ERRMSG("TRACER_CHEM requires a valid CLIM_PHOTO climatology!");
7324 if (clim->o1d.ntime < 2 || clim->o1d.nlat < 2 || clim->o1d.np < 2)
7325 ERRMSG("TRACER_CHEM requires a valid CLIM_O1D_FILENAME climatology!");
7326 }
7327
7328 /* Read CFC-10 time series... */
7329 if (ctl->clim_ccl4_timeseries[0] != '-')
7331
7332 /* Read CFC-11 time series... */
7333 if (ctl->clim_ccl3f_timeseries[0] != '-')
7335
7336 /* Read CFC-12 time series... */
7337 if (ctl->clim_ccl2f2_timeseries[0] != '-')
7339
7340 /* Read N2O time series... */
7341 if (ctl->clim_n2o_timeseries[0] != '-')
7342 read_clim_ts(ctl->clim_n2o_timeseries, &clim->n2o);
7343
7344 /* Read SF6 time series... */
7345 if (ctl->clim_sf6_timeseries[0] != '-')
7346 read_clim_ts(ctl->clim_sf6_timeseries, &clim->sf6);
7347}
void read_clim_photo(const char *filename, clim_photo_t *photo)
Reads photolysis rates from a NetCDF file and populates the given photolysis structure.
Definition mptrac.c:9585
int read_clim_ts(const char *filename, clim_ts_t *ts)
Reads a climatological time series from a file and populates the given time series structure.
Definition mptrac.c:9704
void read_clim_zm(const char *filename, const char *varname, clim_zm_t *zm)
Reads zonally averaged climatological data from a netCDF file and populates the given structure.
Definition mptrac.c:9758
void clim_tropo_init(clim_t *clim)
Initializes the tropopause data in the climatology structure.
Definition mptrac.c:245
void clim_oh_diurnal_correction(const ctl_t *ctl, clim_t *clim)
Applies a diurnal correction to the hydroxyl radical (OH) concentration in climatology data.
Definition mptrac.c:126
char clim_ho2_filename[LEN]
Filename of HO2 climatology.
Definition mptrac.h:3217
char clim_o1d_filename[LEN]
Filename of O(1D) climatology.
Definition mptrac.h:3220
char clim_photo[LEN]
Filename of photolysis rates climatology.
Definition mptrac.h:3205
char clim_h2o2_filename[LEN]
Filename of H2O2 climatology.
Definition mptrac.h:3214
int tracer_chem
Switch for first order tracer chemistry module (0=off, 1=on).
Definition mptrac.h:3322
char clim_oh_filename[LEN]
Filename of OH climatology.
Definition mptrac.h:3211
int h2o2_chem_reaction
Reaction type for H2O2 chemistry (0=none, 1=SO2).
Definition mptrac.h:3313
char clim_hno3_filename[LEN]
Filename of HNO3 climatology.
Definition mptrac.h:3208
Here is the call graph for this function:

◆ mptrac_read_ctl()

void mptrac_read_ctl ( const char * filename,
int argc,
char * argv[],
ctl_t * ctl )

Reads control parameters from a configuration file and populates the given structure.

This function reads control parameters from a specified configuration file and command line arguments, populating the provided ctl_t structure with the parsed data. It handles a wide range of parameters, performing necessary checks and providing default values where applicable.

Parameters
filenameA string containing the path to the configuration file.
argcAn integer representing the number of command line arguments.
argvAn array of strings containing the command line arguments.
ctlA pointer to the structure (ctl_t) that will be populated with the control parameters.

The function performs the following steps:

  • Sets a timer for reading the control file.
  • Logs information about the MPTRAC executable version and compilation details.
  • Initializes quantity indices.
  • Reads and sets various control parameters such as quantities, vertical coordinates, time steps, meteorological data, sorting options, isosurface parameters, random number generator type, advection parameters, diffusion parameters, convection parameters, boundary conditions, species parameters, molar mass, OH chemistry parameters, H2O2 chemistry parameters, KPP chemistry parameters, first order tracer chemistry parameters, wet deposition parameters, dry deposition parameters, climatological data paths, mixing parameters, chemistry grid parameters, exponential decay parameters, PSC analysis parameters, output parameters for atmospheric data, CSI data, ensemble data, grid data, profile data, sample data, station data, and VTK data.
Author
Lars Hoffmann

Definition at line 7351 of file mptrac.c.

7355 {
7356
7357 /* Set timer... */
7358 SELECT_TIMER("READ_CTL", "INPUT");
7359
7360 /* Write info... */
7361 LOG(1, "\nMassive-Parallel Trajectory Calculations (MPTRAC)\n"
7362 "(executable: %s | version: %s | compiled: %s, %s)\n",
7363 argv[0], VERSION, __DATE__, __TIME__);
7364
7365 /* Initialize quantity indices... */
7366 ctl->qnt_idx = -1;
7367 ctl->qnt_ens = -1;
7368 ctl->qnt_stat = -1;
7369 ctl->qnt_m = -1;
7370 ctl->qnt_vmr = -1;
7371 ctl->qnt_rp = -1;
7372 ctl->qnt_rhop = -1;
7373 ctl->qnt_ps = -1;
7374 ctl->qnt_ts = -1;
7375 ctl->qnt_zs = -1;
7376 ctl->qnt_us = -1;
7377 ctl->qnt_vs = -1;
7378 ctl->qnt_ess = -1;
7379 ctl->qnt_nss = -1;
7380 ctl->qnt_shf = -1;
7381 ctl->qnt_lsm = -1;
7382 ctl->qnt_sst = -1;
7383 ctl->qnt_pbl = -1;
7384 ctl->qnt_pt = -1;
7385 ctl->qnt_tt = -1;
7386 ctl->qnt_zt = -1;
7387 ctl->qnt_h2ot = -1;
7388 ctl->qnt_zg = -1;
7389 ctl->qnt_p = -1;
7390 ctl->qnt_t = -1;
7391 ctl->qnt_rho = -1;
7392 ctl->qnt_u = -1;
7393 ctl->qnt_v = -1;
7394 ctl->qnt_w = -1;
7395 ctl->qnt_h2o = -1;
7396 ctl->qnt_o3 = -1;
7397 ctl->qnt_lwc = -1;
7398 ctl->qnt_rwc = -1;
7399 ctl->qnt_iwc = -1;
7400 ctl->qnt_swc = -1;
7401 ctl->qnt_cc = -1;
7402 ctl->qnt_pct = -1;
7403 ctl->qnt_pcb = -1;
7404 ctl->qnt_cl = -1;
7405 ctl->qnt_plcl = -1;
7406 ctl->qnt_plfc = -1;
7407 ctl->qnt_pel = -1;
7408 ctl->qnt_cape = -1;
7409 ctl->qnt_cin = -1;
7410 ctl->qnt_o3c = -1;
7411 ctl->qnt_hno3 = -1;
7412 ctl->qnt_oh = -1;
7413 ctl->qnt_h2o2 = -1;
7414 ctl->qnt_ho2 = -1;
7415 ctl->qnt_o1d = -1;
7416 ctl->qnt_mloss_oh = -1;
7417 ctl->qnt_mloss_h2o2 = -1;
7418 ctl->qnt_mloss_kpp = -1;
7419 ctl->qnt_mloss_wet = -1;
7420 ctl->qnt_mloss_dry = -1;
7421 ctl->qnt_mloss_decay = -1;
7422 ctl->qnt_loss_rate = -1;
7423 ctl->qnt_psat = -1;
7424 ctl->qnt_psice = -1;
7425 ctl->qnt_pw = -1;
7426 ctl->qnt_sh = -1;
7427 ctl->qnt_rh = -1;
7428 ctl->qnt_rhice = -1;
7429 ctl->qnt_theta = -1;
7430 ctl->qnt_iso_var = -1;
7431 ctl->qnt_zeta = -1;
7432 ctl->qnt_zeta_d = -1;
7433 ctl->qnt_zeta_dot = -1;
7434 ctl->qnt_eta = -1;
7435 ctl->qnt_eta_d = -1;
7436 ctl->qnt_eta_dot = -1;
7437 ctl->qnt_tvirt = -1;
7438 ctl->qnt_lapse = -1;
7439 ctl->qnt_vh = -1;
7440 ctl->qnt_vz = -1;
7441 ctl->qnt_pv = -1;
7442 ctl->qnt_tdew = -1;
7443 ctl->qnt_tice = -1;
7444 ctl->qnt_tsts = -1;
7445 ctl->qnt_tnat = -1;
7446 ctl->qnt_Cx = -1;
7447 ctl->qnt_Ch2o = -1;
7448 ctl->qnt_Co3 = -1;
7449 ctl->qnt_Cco = -1;
7450 ctl->qnt_Coh = -1;
7451 ctl->qnt_Ch = -1;
7452 ctl->qnt_Cho2 = -1;
7453 ctl->qnt_Ch2o2 = -1;
7454 ctl->qnt_Co1d = -1;
7455 ctl->qnt_Co3p = -1;
7456 ctl->qnt_Cccl4 = -1;
7457 ctl->qnt_Cccl3f = -1;
7458 ctl->qnt_Cccl2f2 = -1;
7459 ctl->qnt_Cn2o = -1;
7460 ctl->qnt_Csf6 = -1;
7461 ctl->qnt_aoa = -1;
7462 ctl->qnt_Arn222 = -1;
7463 ctl->qnt_Apb210 = -1;
7464 ctl->qnt_Abe7 = -1;
7465 ctl->qnt_Acs137 = -1;
7466 ctl->qnt_Ai131 = -1;
7467 ctl->qnt_Axe133 = -1;
7468 ctl->qnt_current_subdomain = -1;
7469 ctl->qnt_target_subdomain = -1;
7470
7471 /* Read quantities... */
7472 ctl->nq = (int) scan_ctl(filename, argc, argv, "NQ", -1, "0", NULL);
7473 if (ctl->nq > NQ)
7474 ERRMSG("Too many quantities!");
7475 for (int iq = 0; iq < ctl->nq; iq++) {
7476
7477 /* Read quantity name and format... */
7478 scan_ctl(filename, argc, argv, "QNT_NAME", iq, "", ctl->qnt_name[iq]);
7479 scan_ctl(filename, argc, argv, "QNT_LONGNAME", iq, ctl->qnt_name[iq],
7480 ctl->qnt_longname[iq]);
7481 scan_ctl(filename, argc, argv, "QNT_FORMAT", iq, "%g",
7482 ctl->qnt_format[iq]);
7483 if (strcasecmp(ctl->qnt_name[iq], "aoa") == 0)
7484 sprintf(ctl->qnt_format[iq], "%%.2f");
7485
7486 /* Try to identify quantity... */
7487 SET_QNT(qnt_idx, "idx", "particle index", "-")
7488 SET_QNT(qnt_ens, "ens", "ensemble index", "-")
7489 SET_QNT(qnt_stat, "stat", "station flag", "-")
7490 SET_QNT(qnt_m, "m", "mass", "kg")
7491 SET_QNT(qnt_vmr, "vmr", "volume mixing ratio", "ppv")
7492 SET_QNT(qnt_rp, "rp", "particle radius", "microns")
7493 SET_QNT(qnt_rhop, "rhop", "particle density", "kg/m^3")
7494 SET_QNT(qnt_ps, "ps", "surface pressure", "hPa")
7495 SET_QNT(qnt_ts, "ts", "surface temperature", "K")
7496 SET_QNT(qnt_zs, "zs", "surface height", "km")
7497 SET_QNT(qnt_us, "us", "surface zonal wind", "m/s")
7498 SET_QNT(qnt_vs, "vs", "surface meridional wind", "m/s")
7499 SET_QNT(qnt_ess, "ess", "eastward turbulent surface stress", "N/m^2")
7500 SET_QNT(qnt_nss, "nss", "northward turbulent surface stress", "N/m^2")
7501 SET_QNT(qnt_shf, "shf", "surface sensible heat flux", "W/m^2")
7502 SET_QNT(qnt_lsm, "lsm", "land-sea mask", "1")
7503 SET_QNT(qnt_sst, "sst", "sea surface temperature", "K")
7504 SET_QNT(qnt_pbl, "pbl", "planetary boundary layer", "hPa")
7505 SET_QNT(qnt_pt, "pt", "tropopause pressure", "hPa")
7506 SET_QNT(qnt_tt, "tt", "tropopause temperature", "K")
7507 SET_QNT(qnt_zt, "zt", "tropopause geopotential height", "km")
7508 SET_QNT(qnt_h2ot, "h2ot", "tropopause water vapor", "ppv")
7509 SET_QNT(qnt_zg, "zg", "geopotential height", "km")
7510 SET_QNT(qnt_p, "p", "pressure", "hPa")
7511 SET_QNT(qnt_t, "t", "temperature", "K")
7512 SET_QNT(qnt_rho, "rho", "air density", "kg/m^3")
7513 SET_QNT(qnt_u, "u", "zonal wind", "m/s")
7514 SET_QNT(qnt_v, "v", "meridional wind", "m/s")
7515 SET_QNT(qnt_w, "w", "vertical velocity", "hPa/s")
7516 SET_QNT(qnt_h2o, "h2o", "water vapor", "ppv")
7517 SET_QNT(qnt_o3, "o3", "ozone", "ppv")
7518 SET_QNT(qnt_lwc, "lwc", "cloud liquid water content", "kg/kg")
7519 SET_QNT(qnt_rwc, "rwc", "cloud rain water content", "kg/kg")
7520 SET_QNT(qnt_iwc, "iwc", "cloud ice water content", "kg/kg")
7521 SET_QNT(qnt_swc, "swc", "cloud snow water content", "kg/kg")
7522 SET_QNT(qnt_cc, "cc", "cloud cover", "1")
7523 SET_QNT(qnt_pct, "pct", "cloud top pressure", "hPa")
7524 SET_QNT(qnt_pcb, "pcb", "cloud bottom pressure", "hPa")
7525 SET_QNT(qnt_cl, "cl", "total column cloud water", "kg/m^2")
7526 SET_QNT(qnt_plcl, "plcl", "lifted condensation level", "hPa")
7527 SET_QNT(qnt_plfc, "plfc", "level of free convection", "hPa")
7528 SET_QNT(qnt_pel, "pel", "equilibrium level", "hPa")
7529 SET_QNT(qnt_cape, "cape", "convective available potential energy",
7530 "J/kg")
7531 SET_QNT(qnt_cin, "cin", "convective inhibition", "J/kg")
7532 SET_QNT(qnt_o3c, "o3c", "total column ozone", "DU")
7533 SET_QNT(qnt_hno3, "hno3", "nitric acid", "ppv")
7534 SET_QNT(qnt_oh, "oh", "hydroxyl radical", "ppv")
7535 SET_QNT(qnt_h2o2, "h2o2", "hydrogen peroxide", "ppv")
7536 SET_QNT(qnt_ho2, "ho2", "hydroperoxyl radical", "ppv")
7537 SET_QNT(qnt_o1d, "o1d", "atomic oxygen", "ppv")
7538 SET_QNT(qnt_mloss_oh, "mloss_oh", "mass loss due to OH chemistry", "kg")
7539 SET_QNT(qnt_mloss_h2o2, "mloss_h2o2",
7540 "mass loss due to H2O2 chemistry", "kg")
7541 SET_QNT(qnt_mloss_kpp, "mloss_kpp", "mass loss due to kpp chemistry",
7542 "kg")
7543 SET_QNT(qnt_mloss_wet, "mloss_wet", "mass loss due to wet deposition",
7544 "kg")
7545 SET_QNT(qnt_mloss_dry, "mloss_dry", "mass loss due to dry deposition",
7546 "kg")
7547 SET_QNT(qnt_mloss_decay, "mloss_decay",
7548 "mass loss due to exponential decay", "kg")
7549 SET_QNT(qnt_loss_rate, "loss_rate", "total loss rate", "s^-1")
7550 SET_QNT(qnt_psat, "psat", "saturation pressure over water", "hPa")
7551 SET_QNT(qnt_psice, "psice", "saturation pressure over ice", "hPa")
7552 SET_QNT(qnt_pw, "pw", "partial water vapor pressure", "hPa")
7553 SET_QNT(qnt_sh, "sh", "specific humidity", "kg/kg")
7554 SET_QNT(qnt_rh, "rh", "relative humidity", "%%")
7555 SET_QNT(qnt_rhice, "rhice", "relative humidity over ice", "%%")
7556 SET_QNT(qnt_theta, "theta", "potential temperature", "K")
7557 SET_QNT(qnt_iso_var, "iso_var", "isosurface reference value", "varies")
7558 SET_QNT(qnt_zeta, "zeta", "zeta coordinate", "K")
7559 SET_QNT(qnt_zeta_d, "zeta_d", "diagnosed zeta coordinate", "K")
7560 SET_QNT(qnt_zeta_dot, "zeta_dot", "velocity of zeta coordinate",
7561 "K/day")
7562 SET_QNT(qnt_eta, "eta", "eta coordinate", "1")
7563 SET_QNT(qnt_eta_d, "eta_d", "diagnosed eta coordinate", "1")
7564 SET_QNT(qnt_eta_dot, "eta_dot", "velocity of eta coordinate", "1/s")
7565 SET_QNT(qnt_tvirt, "tvirt", "virtual temperature", "K")
7566 SET_QNT(qnt_lapse, "lapse", "temperature lapse rate", "K/km")
7567 SET_QNT(qnt_vh, "vh", "horizontal velocity", "m/s")
7568 SET_QNT(qnt_vz, "vz", "vertical velocity", "m/s")
7569 SET_QNT(qnt_pv, "pv", "potential vorticity", "PVU")
7570 SET_QNT(qnt_tdew, "tdew", "dew point temperature", "K")
7571 SET_QNT(qnt_tice, "tice", "frost point temperature", "K")
7572 SET_QNT(qnt_tsts, "tsts", "STS existence temperature", "K")
7573 SET_QNT(qnt_tnat, "tnat", "NAT existence temperature", "K")
7574 SET_QNT(qnt_Cx, "Cx", "Trace species x volume mixing ratio", "ppv")
7575 SET_QNT(qnt_Ch2o, "Ch2o", "H2O volume mixing ratio", "ppv")
7576 SET_QNT(qnt_Co3, "Co3", "O3 volume mixing ratio", "ppv")
7577 SET_QNT(qnt_Cco, "Cco", "CO volume mixing ratio", "ppv")
7578 SET_QNT(qnt_Coh, "Coh", "HO volume mixing ratio", "ppv")
7579 SET_QNT(qnt_Ch, "Ch", "H radical volume mixing ratio", "ppv")
7580 SET_QNT(qnt_Cho2, "Cho2", "HO2 volume mixing ratio", "ppv")
7581 SET_QNT(qnt_Ch2o2, "Ch2o2", "H2O2 volume mixing ratio", "ppv")
7582 SET_QNT(qnt_Co1d, "Co1d", "O(1D) volume mixing ratio", "ppv")
7583 SET_QNT(qnt_Co3p, "Co3p", "O(3P) radical volume mixing ratio", "ppv")
7584 SET_QNT(qnt_Cccl4, "Cccl4", "CCl4 (CFC-10) volume mixing ratio", "ppv")
7585 SET_QNT(qnt_Cccl3f, "Cccl3f", "CCl3F (CFC-11) volume mixing ratio",
7586 "ppv")
7587 SET_QNT(qnt_Cccl2f2, "Cccl2f2", "CCl2F2 (CFC-12) volume mixing ratio",
7588 "ppv")
7589 SET_QNT(qnt_Cn2o, "Cn2o", "N2O volume mixing ratio", "ppv")
7590 SET_QNT(qnt_Csf6, "Csf6", "SF6 volume mixing ratio", "ppv")
7591 SET_QNT(qnt_aoa, "aoa",
7592 "age-of-air reference timestamp (s since 2000-01-01 00:00 UTC)",
7593 "s")
7594 SET_QNT(qnt_Arn222, "Arn222", "Rn-222 activity", "Bq")
7595 SET_QNT(qnt_Apb210, "Apb210", "Pb-210 activity", "Bq")
7596 SET_QNT(qnt_Abe7, "Abe7", "Be-7 activity", "Bq")
7597 SET_QNT(qnt_Acs137, "Acs137", "Cs-137 activity", "Bq")
7598 SET_QNT(qnt_Ai131, "Ai131", "I-131 activity", "Bq")
7599 SET_QNT(qnt_Axe133, "Axe133", "Xe-133 activity", "Bq")
7600 SET_QNT(qnt_current_subdomain, "current_subdomain",
7601 "current subdomain rank", "-")
7602 SET_QNT(qnt_target_subdomain, "target_subdomain",
7603 "target subdomain rank", "-")
7604 scan_ctl(filename, argc, argv, "QNT_UNIT", iq, "", ctl->qnt_unit[iq]);
7605 }
7606
7607 ctl->met_coord_type =
7608 (int) scan_ctl(filename, argc, argv, "MET_COORD_TYPE", -1, "0", NULL);
7609 if (ctl->met_coord_type < 0 || ctl->met_coord_type > 1)
7610 ERRMSG("MET_COORD_TYPE must be 0 or 1!");
7611 ctl->met_utm_ref_lat = 0.0;
7612 ctl->met_utm_ref_lon = 0.0;
7613 if (ctl->met_coord_type == 1) {
7614 ctl->met_utm_ref_lat =
7615 scan_ctl(filename, argc, argv, "MET_UTM_REF_LAT", -1, "", NULL);
7616 ctl->met_utm_ref_lon =
7617 scan_ctl(filename, argc, argv, "MET_UTM_REF_LON", -1, "", NULL);
7618 }
7619
7620 /* Vertical coordinate and velocity... */
7621 ctl->advect_vert_coord =
7622 (int) scan_ctl(filename, argc, argv, "ADVECT_VERT_COORD", -1, "0", NULL);
7623 if (ctl->advect_vert_coord < 0 || ctl->advect_vert_coord > 3)
7624 ERRMSG("ADVECT_VERT_COORD must be 0, 1, 2, or 3!");
7625
7626 if (ctl->advect_vert_coord == 1 && ctl->qnt_zeta < 0)
7627 ERRMSG("Add quantity zeta for diabatic advection!");
7628 if (ctl->advect_vert_coord == 3 && ctl->qnt_eta < 0)
7629 ERRMSG("Add quantity eta for etadot avection!");
7630
7631 ctl->met_vert_coord =
7632 (int) scan_ctl(filename, argc, argv, "MET_VERT_COORD", -1, "0", NULL);
7633 if (ctl->met_vert_coord < 0 || ctl->met_vert_coord > 4)
7634 ERRMSG("MET_VERT_COORD must be 0, 1, 2, 3, or 4!");
7635 if (ctl->qnt_eta_d >= 0
7636 && ctl->met_vert_coord != 2 && ctl->met_vert_coord != 3)
7637 ERRMSG("Quantity eta_d requires full-level A and B coefficients!");
7638
7639 if (ctl->advect_vert_coord == 2 && ctl->met_vert_coord == 0)
7640 ERRMSG
7641 ("Using ADVECT_VERT_COORD = 2 requires meteo data on model levels!");
7642 if (ctl->advect_vert_coord == 3 && ctl->met_vert_coord != 3)
7643 ERRMSG
7644 ("Using ADVECT_VERT_COORD = 3 requires A and B model level coefficients!");
7645
7646 ctl->met_gp2z =
7647 (int) scan_ctl(filename, argc, argv, "MET_GP2Z", -1, "0", NULL);
7648 if (ctl->met_gp2z != 0 && ctl->met_gp2z != 1)
7649 ERRMSG("Set MET_GP2Z to 0 or 1!");
7650
7651 /* Time steps of simulation... */
7652 ctl->direction =
7653 (int) scan_ctl(filename, argc, argv, "DIRECTION", -1, "1", NULL);
7654 if (ctl->direction != -1 && ctl->direction != 1)
7655 ERRMSG("Set DIRECTION to -1 or 1!");
7656 ctl->t_stop = scan_ctl(filename, argc, argv, "T_STOP", -1, "1e100", NULL);
7657 ctl->dt_mod = scan_ctl(filename, argc, argv, "DT_MOD", -1, "180", NULL);
7658 if (!isfinite(ctl->dt_mod) || ctl->dt_mod <= 0)
7659 ERRMSG("DT_MOD must be finite and positive!");
7660
7661 /* Meteo data... */
7662 scan_ctl(filename, argc, argv, "METBASE", -1, "-", ctl->metbase);
7663 ctl->dt_met = scan_ctl(filename, argc, argv, "DT_MET", -1, "3600", NULL);
7664 if (ctl->dt_mod > ctl->dt_met)
7665 ERRMSG("DT_MOD must not exceed DT_MET!");
7666 ctl->met_convention =
7667 (int) scan_ctl(filename, argc, argv, "MET_CONVENTION", -1, "0", NULL);
7668 ctl->met_type =
7669 (int) scan_ctl(filename, argc, argv, "MET_TYPE", -1, "0", NULL);
7670 if (ctl->advect_vert_coord == 1 && ctl->met_type != 0)
7671 ERRMSG
7672 ("Please use meteo files in netcdf format for diabatic calculations.");
7673 if (ctl->advect_vert_coord == 3 && ctl->met_type != 0)
7674 ERRMSG
7675 ("Please use meteo files in netcdf format for etadot calculations.");
7676 ctl->met_clams =
7677 (int) scan_ctl(filename, argc, argv, "MET_CLAMS", -1, "0", NULL);
7678 ctl->met_nc_scale =
7679 (int) scan_ctl(filename, argc, argv, "MET_NC_SCALE", -1, "1", NULL);
7680 ctl->met_nc_read_mode =
7681 (int) scan_ctl(filename, argc, argv, "MET_NC_READ_MODE", -1, "0", NULL);
7682 if (ctl->met_nc_read_mode < 0 || ctl->met_nc_read_mode > 1)
7683 ERRMSG("Set MET_NC_READ_MODE to 0 or 1!");
7684 ctl->met_nc_level =
7685 (int) scan_ctl(filename, argc, argv, "MET_NC_LEVEL", -1, "0", NULL);
7686 ctl->met_nc_quant =
7687 (int) scan_ctl(filename, argc, argv, "MET_NC_QUANT", -1, "0", NULL);
7688 ctl->met_zstd_level =
7689 (int) scan_ctl(filename, argc, argv, "MET_ZSTD_LEVEL", -1, "-3", NULL);
7690 ctl->met_zstd_nworkers =
7691 (int) scan_ctl(filename, argc, argv, "MET_ZSTD_NWORKERS", -1, "4", NULL);
7692 ctl->met_lz4_accel =
7693 (int) scan_ctl(filename, argc, argv, "MET_LZ4_ACCEL", -1, "8", NULL);
7694 ctl->met_pck_zstd =
7695 (int) scan_ctl(filename, argc, argv, "MET_PCK_ZSTD", -1, "0", NULL);
7696 if (ctl->met_pck_zstd != 0 && ctl->met_pck_zstd != 1)
7697 ERRMSG("Set MET_PCK_ZSTD to 0 or 1!");
7698#ifndef ZSTD
7699 if (ctl->met_type == 2 && ctl->met_pck_zstd)
7700 ERRMSG("MET_PCK_ZSTD requires MPTRAC to be compiled with ZSTD support!");
7701#endif
7702 const int def_lossy_scale =
7703 (int) scan_ctl(filename, argc, argv, "MET_LOSSY_SCALE", -1, "0", NULL);
7704 for (int i = 0; i < METVAR; i++) {
7705 char defprec_zfp[LEN] = "7", deftol_zfp[LEN] = "0.0";
7706 char defprec_sz3[LEN] = "6", deftol_sz3[LEN] = "0.0";
7707 if (i == 0) { /* geopotential height */
7708 sprintf(defprec_zfp, "12");
7709 sprintf(defprec_sz3, "11");
7710 } else if (i == 1) { /* temperature */
7711 sprintf(defprec_zfp, "11");
7712 sprintf(defprec_sz3, "7");
7713 } else if (i == 2 || i == 3) { /* horizontal wind */
7714 sprintf(defprec_zfp, "7");
7715 sprintf(defprec_sz3, "7");
7716 } else if (i == 4) { /* vertical wind */
7717 sprintf(defprec_zfp, "6");
7718 sprintf(defprec_sz3, "13");
7719 } else if (i == 5) { /* potential vorticity */
7720 sprintf(defprec_zfp, "7");
7721 sprintf(defprec_sz3, "20");
7722 } else if (i == 6) { /* water vapor */
7723 sprintf(defprec_zfp, "10");
7724 sprintf(defprec_sz3, "18");
7725 } else if (i == 7) { /* ozone */
7726 sprintf(defprec_zfp, "9");
7727 sprintf(defprec_sz3, "10");
7728 } else if (i >= 8 && i <= 11) { /* cloud water fields */
7729 sprintf(defprec_zfp, "6");
7730 sprintf(defprec_sz3, "13");
7731 } else if (i == 12) { /* cloud cover */
7732 sprintf(defprec_zfp, "9");
7733 sprintf(defprec_sz3, "6");
7734 }
7735 ctl->met_zfp_prec[i] =
7736 (int) scan_ctl(filename, argc, argv, "MET_ZFP_PREC", i, defprec_zfp,
7737 NULL);
7738 ctl->met_zfp_tol[i] =
7739 scan_ctl(filename, argc, argv, "MET_ZFP_TOL", i, deftol_zfp, NULL);
7740 ctl->met_sz3_prec[i] =
7741 (int) scan_ctl(filename, argc, argv, "MET_SZ3_PREC", i, defprec_sz3,
7742 NULL);
7743 ctl->met_sz3_tol[i] =
7744 scan_ctl(filename, argc, argv, "MET_SZ3_TOL", i, deftol_sz3, NULL);
7745 char defscale[LEN];
7746 snprintf(defscale, LEN, "%d", def_lossy_scale);
7747 ctl->met_lossy_scale[i] =
7748 (int) scan_ctl(filename, argc, argv, "MET_LOSSY_SCALE", i, defscale,
7749 NULL);
7750 if (ctl->met_lossy_scale[i] < 0 || ctl->met_lossy_scale[i] > 1)
7751 ERRMSG("Set MET_LOSSY_SCALE to 0 or 1!");
7752 }
7753
7754 /* Scan compression diagnostics file... */
7755 scan_ctl(filename, argc, argv, "MET_COMP_LOGFILE", -1, "-",
7756 ctl->met_comp_logfile);
7757 ctl->met_cms_batch =
7758 (int) scan_ctl(filename, argc, argv, "MET_CMS_BATCH", -1, "-1", NULL);
7759 ctl->met_cms_zstd =
7760 (int) scan_ctl(filename, argc, argv, "MET_CMS_ZSTD", -1, "1", NULL);
7761 ctl->met_cms_nd0x =
7762 (int) scan_ctl(filename, argc, argv, "MET_CMS_ND0X", -1, "48", NULL);
7763 ctl->met_cms_nd0y =
7764 (int) scan_ctl(filename, argc, argv, "MET_CMS_ND0Y", -1, "24", NULL);
7765 ctl->met_cms_maxlev =
7766 (int) scan_ctl(filename, argc, argv, "MET_CMS_MAXLEV", -1, "6", NULL);
7767 for (int i = 0; i < METVAR; i++) {
7768 char defeps[LEN] = "1.0";
7769 if (i == 1 || i == 2 || i == 3)
7770 sprintf(defeps, "0.05");
7771 ctl->met_cms_eps[i] =
7772 scan_ctl(filename, argc, argv, "MET_CMS_EPS", i, defeps, NULL);
7773 }
7774 ctl->met_dx = (int) scan_ctl(filename, argc, argv, "MET_DX", -1, "1", NULL);
7775 ctl->met_dy = (int) scan_ctl(filename, argc, argv, "MET_DY", -1, "1", NULL);
7776 ctl->met_dp = (int) scan_ctl(filename, argc, argv, "MET_DP", -1, "1", NULL);
7777 if (ctl->met_dx < 1 || ctl->met_dy < 1 || ctl->met_dp < 1)
7778 ERRMSG("MET_DX, MET_DY, and MET_DP need to be greater than zero!");
7779 ctl->met_sx = (int) scan_ctl(filename, argc, argv, "MET_SX", -1, "1", NULL);
7780 ctl->met_sy = (int) scan_ctl(filename, argc, argv, "MET_SY", -1, "1", NULL);
7781 ctl->met_sp = (int) scan_ctl(filename, argc, argv, "MET_SP", -1, "1", NULL);
7782 if (ctl->met_sx < 1 || ctl->met_sy < 1 || ctl->met_sp < 1)
7783 ERRMSG("MET_SX, MET_SY, and MET_SP need to be greater than zero!");
7784 ctl->met_detrend =
7785 scan_ctl(filename, argc, argv, "MET_DETREND", -1, "-999", NULL);
7786 ctl->met_np = (int) scan_ctl(filename, argc, argv, "MET_NP", -1, "0", NULL);
7787 if (ctl->met_np > EP)
7788 ERRMSG("Too many pressure levels!");
7789 ctl->met_press_level_def =
7790 (int) scan_ctl(filename, argc, argv, "MET_PRESS_LEVEL_DEF", -1, "-1",
7791 NULL);
7792 if (ctl->met_press_level_def >= 0) {
7793 level_definitions(ctl);
7794 } else {
7795 if (ctl->met_np > 0) {
7796 for (int ip = 0; ip < ctl->met_np; ip++)
7797 ctl->met_p[ip] =
7798 scan_ctl(filename, argc, argv, "MET_P", ip, "", NULL);
7799 }
7800 }
7801 ctl->met_nlev =
7802 (int) scan_ctl(filename, argc, argv, "MET_NLEV", -1, "0", NULL);
7803 if (ctl->met_nlev > EP)
7804 ERRMSG("Too many model levels!");
7805 for (int ip = 0; ip < ctl->met_nlev; ip++)
7806 ctl->met_lev_hyam[ip] =
7807 scan_ctl(filename, argc, argv, "MET_LEV_HYAM", ip, "", NULL);
7808 for (int ip = 0; ip < ctl->met_nlev; ip++)
7809 ctl->met_lev_hybm[ip] =
7810 scan_ctl(filename, argc, argv, "MET_LEV_HYBM", ip, "", NULL);
7811 ctl->met_geopot_sx =
7812 (int) scan_ctl(filename, argc, argv, "MET_GEOPOT_SX", -1, "-1", NULL);
7813 ctl->met_geopot_sy =
7814 (int) scan_ctl(filename, argc, argv, "MET_GEOPOT_SY", -1, "-1", NULL);
7815 ctl->met_relhum =
7816 (int) scan_ctl(filename, argc, argv, "MET_RELHUM", -1, "0", NULL);
7817 ctl->met_cape =
7818 (int) scan_ctl(filename, argc, argv, "MET_CAPE", -1, "1", NULL);
7819 if (ctl->met_cape < 0 || ctl->met_cape > 1)
7820 ERRMSG("Set MET_CAPE to 0 or 1!");
7821 ctl->met_pbl =
7822 (int) scan_ctl(filename, argc, argv, "MET_PBL", -1, "3", NULL);
7823 if (ctl->met_pbl < 0 || ctl->met_pbl > 3)
7824 ERRMSG("Set MET_PBL to 0 ... 3!");
7825 ctl->met_pbl_min =
7826 scan_ctl(filename, argc, argv, "MET_PBL_MIN", -1, "0.1", NULL);
7827 ctl->met_pbl_max =
7828 scan_ctl(filename, argc, argv, "MET_PBL_MAX", -1, "5.0", NULL);
7829 ctl->met_tropo =
7830 (int) scan_ctl(filename, argc, argv, "MET_TROPO", -1, "3", NULL);
7831 if (ctl->met_tropo < 0 || ctl->met_tropo > 5)
7832 ERRMSG("Set MET_TROPO to 0 ... 5!");
7833 ctl->met_tropo_pv =
7834 scan_ctl(filename, argc, argv, "MET_TROPO_PV", -1, "3.5", NULL);
7835 ctl->met_tropo_theta =
7836 scan_ctl(filename, argc, argv, "MET_TROPO_THETA", -1, "380", NULL);
7837 ctl->met_tropo_spline =
7838 (int) scan_ctl(filename, argc, argv, "MET_TROPO_SPLINE", -1, "1", NULL);
7839 ctl->met_dt_out =
7840 scan_ctl(filename, argc, argv, "MET_DT_OUT", -1, "0.1", NULL);
7841 const int meteo_sampled =
7842 (ctl->qnt_ps >= 0 || ctl->qnt_ts >= 0 || ctl->qnt_zs >= 0
7843 || ctl->qnt_us >= 0 || ctl->qnt_vs >= 0 || ctl->qnt_ess >= 0
7844 || ctl->qnt_nss >= 0 || ctl->qnt_shf >= 0 || ctl->qnt_lsm >= 0
7845 || ctl->qnt_sst >= 0 || ctl->qnt_pbl >= 0 || ctl->qnt_pt >= 0
7846 || ctl->qnt_tt >= 0 || ctl->qnt_zt >= 0 || ctl->qnt_h2ot >= 0
7847 || ctl->qnt_zg >= 0 || ctl->qnt_p >= 0 || ctl->qnt_t >= 0
7848 || ctl->qnt_rho >= 0 || ctl->qnt_u >= 0 || ctl->qnt_v >= 0
7849 || ctl->qnt_w >= 0 || ctl->qnt_h2o >= 0 || ctl->qnt_o3 >= 0
7850 || ctl->qnt_lwc >= 0 || ctl->qnt_rwc >= 0 || ctl->qnt_iwc >= 0
7851 || ctl->qnt_swc >= 0 || ctl->qnt_cc >= 0 || ctl->qnt_pct >= 0
7852 || ctl->qnt_pcb >= 0 || ctl->qnt_cl >= 0 || ctl->qnt_plcl >= 0
7853 || ctl->qnt_plfc >= 0 || ctl->qnt_pel >= 0 || ctl->qnt_cape >= 0
7854 || ctl->qnt_cin >= 0 || ctl->qnt_o3c >= 0 || ctl->qnt_hno3 >= 0
7855 || ctl->qnt_oh >= 0 || ctl->qnt_h2o2 >= 0 || ctl->qnt_ho2 >= 0
7856 || ctl->qnt_o1d >= 0 || ctl->qnt_vh >= 0 || ctl->qnt_vz >= 0
7857 || ctl->qnt_psat >= 0 || ctl->qnt_psice >= 0 || ctl->qnt_pw >= 0
7858 || ctl->qnt_sh >= 0 || ctl->qnt_rh >= 0 || ctl->qnt_rhice >= 0
7859 || ctl->qnt_theta >= 0 || ctl->qnt_zeta >= 0
7860 || ctl->qnt_zeta_d >= 0 || ctl->qnt_eta >= 0
7861 || ctl->qnt_eta_d >= 0 || ctl->qnt_zeta_dot >= 0
7862 || ctl->qnt_eta_dot >= 0 || ctl->qnt_tvirt >= 0
7863 || ctl->qnt_lapse >= 0 || ctl->qnt_pv >= 0
7864 || ctl->qnt_tdew >= 0 || ctl->qnt_tice >= 0
7865 || ctl->qnt_tnat >= 0 || ctl->qnt_tsts >= 0);
7866 if (meteo_sampled && !isfinite(ctl->met_dt_out))
7867 ERRMSG("MET_DT_OUT must be finite when meteorological sampling is enabled!");
7868 if (meteo_sampled && ctl->met_dt_out >= ctl->dt_mod
7869 && !DT_ALIGNED(ctl->met_dt_out, ctl->dt_mod))
7870 WARN("MET_DT_OUT is not an integer multiple of DT_MOD; meteorological sampling may be skipped!");
7871 ctl->met_cache =
7872 (int) scan_ctl(filename, argc, argv, "MET_CACHE", -1, "0", NULL);
7873 ctl->met_mpi_share =
7874 (int) scan_ctl(filename, argc, argv, "MET_MPI_SHARE", -1, "0", NULL);
7875
7876 /* Sorting... */
7877 ctl->sort_dt = scan_ctl(filename, argc, argv, "SORT_DT", -1, "-999", NULL);
7878
7879 /* Isosurface parameters... */
7880 const double isosurf =
7881 scan_ctl(filename, argc, argv, "ISOSURF", -1, "0", NULL);
7882 if (!isfinite(isosurf) || isosurf < 0 || isosurf > 4
7883 || floor(isosurf) != isosurf)
7884 ERRMSG("Set ISOSURF to an integer between 0 and 4!");
7885 ctl->isosurf = (int) isosurf;
7886 if (ctl->isosurf >= 1 && ctl->isosurf <= 3 && ctl->qnt_iso_var < 0)
7887 ERRMSG("Add quantity iso_var for ISOSURF=1, 2, or 3!");
7888 scan_ctl(filename, argc, argv, "BALLOON", -1, "-", ctl->balloon);
7889
7890 /* Random number generator... */
7891 ctl->rng_type =
7892 (int) scan_ctl(filename, argc, argv, "RNG_TYPE", -1, "1", NULL);
7893 if (ctl->rng_type < 0 || ctl->rng_type > 2)
7894 ERRMSG("Set RNG_TYPE to 0, 1, or 2!");
7895
7896 /* Advection parameters... */
7897 ctl->advect = (int) scan_ctl(filename, argc, argv, "ADVECT", -1, "2", NULL);
7898 if (!(ctl->advect == 1 || ctl->advect == 2))
7899 ERRMSG("Set ADVECT to 1 (Euler) or 2 (midpoint)!");
7900
7901 /* Diffusion parameters... */
7902 ctl->diffusion
7903 = (int) scan_ctl(filename, argc, argv, "DIFFUSION", -1, "0", NULL);
7904 if (ctl->diffusion < 0 || ctl->diffusion > 1)
7905 ERRMSG("Set DIFFUSION to 0 or 1!");
7906 ctl->turb_pbl_scheme =
7907 (int) scan_ctl(filename, argc, argv, "TURB_PBL_SCHEME", -1, "0", NULL);
7908 if (ctl->turb_pbl_scheme < 0 || ctl->turb_pbl_scheme > 1)
7909 ERRMSG("Set TURB_PBL_SCHEME to 0 or 1!");
7910 ctl->dt_pbl = scan_ctl(filename, argc, argv, "DT_PBL", -1, "2", NULL);
7911 if (ctl->diffusion && ctl->turb_pbl_scheme == 1
7912 && (!isfinite(ctl->dt_pbl) || ctl->dt_pbl <= 0.0))
7913 ERRMSG("DT_PBL must be finite and positive when Hanna-PBL diffusion is active!");
7914 ctl->turb_dx_pbl =
7915 scan_ctl(filename, argc, argv, "TURB_DX_PBL", -1, "50", NULL);
7916 ctl->turb_dx_trop =
7917 scan_ctl(filename, argc, argv, "TURB_DX_TROP", -1, "50", NULL);
7918 ctl->turb_dx_strat =
7919 scan_ctl(filename, argc, argv, "TURB_DX_STRAT", -1, "0", NULL);
7920 ctl->turb_dz_pbl =
7921 scan_ctl(filename, argc, argv, "TURB_DZ_PBL", -1, "0", NULL);
7922 ctl->turb_dz_trop =
7923 scan_ctl(filename, argc, argv, "TURB_DZ_TROP", -1, "0", NULL);
7924 ctl->turb_dz_strat =
7925 scan_ctl(filename, argc, argv, "TURB_DZ_STRAT", -1, "0.1", NULL);
7926 ctl->turb_mesox =
7927 scan_ctl(filename, argc, argv, "TURB_MESOX", -1,
7928 ctl->turb_pbl_scheme == 1 ? "0" : "0.16", NULL);
7929 ctl->turb_mesoz =
7930 scan_ctl(filename, argc, argv, "TURB_MESOZ", -1,
7931 ctl->turb_pbl_scheme == 1 ? "0" : "0.16", NULL);
7932 if (ctl->diffusion && ctl->turb_pbl_scheme == 1
7933 && (ctl->turb_mesox != 0 || ctl->turb_mesoz != 0))
7934 ERRMSG
7935 ("Hanna PBL turbulence cannot be combined with nonzero TURB_MESOX or TURB_MESOZ!");
7936 ctl->turb_pbl_trans =
7937 scan_ctl(filename, argc, argv, "TURB_PBL_TRANS", -1, "0", NULL);
7938 if (ctl->turb_pbl_trans < 0 || ctl->turb_pbl_trans > 1)
7939 ERRMSG("TURB_PBL_TRANS must be in the range [0, 1]!");
7940
7941 /* Convection... */
7942 ctl->conv_mix_pbl
7943 = (int) scan_ctl(filename, argc, argv, "CONV_MIX_PBL", -1, "0", NULL);
7944 ctl->conv_pbl_trans
7945 = scan_ctl(filename, argc, argv, "CONV_PBL_TRANS", -1, "0", NULL);
7946 if (ctl->conv_pbl_trans < 0 || ctl->conv_pbl_trans > 1)
7947 ERRMSG("CONV_PBL_TRANS must be in the range [0, 1]!");
7948 ctl->conv_cape
7949 = scan_ctl(filename, argc, argv, "CONV_CAPE", -1, "-999", NULL);
7950 ctl->conv_cin
7951 = scan_ctl(filename, argc, argv, "CONV_CIN", -1, "-999", NULL);
7952 ctl->conv_dt = scan_ctl(filename, argc, argv, "CONV_DT", -1, "-999", NULL);
7953 if (ctl->conv_cape >= 0 || ctl->conv_mix_pbl) {
7954 if (!isfinite(ctl->conv_dt))
7955 ERRMSG("CONV_DT must be finite!");
7956 if (ctl->conv_dt > 0 && !DT_ALIGNED(ctl->conv_dt, ctl->dt_mod))
7957 ERRMSG("CONV_DT must be an integer multiple of DT_MOD!");
7958 }
7959 if (ctl->conv_cape >= 0 && ctl->met_cape == 0
7960 && (ctl->met_type == 0 || ctl->met_type == 6))
7961 ERRMSG("ECP with MET_CAPE=0 requires binary meteo data with EL pressure; netCDF and GRIB readers do not load EL!");
7962
7963 /* Boundary conditions... */
7964 ctl->bound_mass =
7965 scan_ctl(filename, argc, argv, "BOUND_MASS", -1, "-999", NULL);
7966 ctl->bound_mass_trend =
7967 scan_ctl(filename, argc, argv, "BOUND_MASS_TREND", -1, "0", NULL);
7968 ctl->bound_vmr =
7969 scan_ctl(filename, argc, argv, "BOUND_VMR", -1, "-999", NULL);
7970 ctl->bound_vmr_trend =
7971 scan_ctl(filename, argc, argv, "BOUND_VMR_TREND", -1, "0", NULL);
7972 ctl->bound_lat0 =
7973 scan_ctl(filename, argc, argv, "BOUND_LAT0", -1, "-999", NULL);
7974 ctl->bound_lat1 =
7975 scan_ctl(filename, argc, argv, "BOUND_LAT1", -1, "-999", NULL);
7976 ctl->bound_p0 =
7977 scan_ctl(filename, argc, argv, "BOUND_P0", -1, "-999", NULL);
7978 ctl->bound_p1 =
7979 scan_ctl(filename, argc, argv, "BOUND_P1", -1, "-999", NULL);
7980 ctl->bound_dps =
7981 scan_ctl(filename, argc, argv, "BOUND_DPS", -1, "-999", NULL);
7982 ctl->bound_dzs =
7983 scan_ctl(filename, argc, argv, "BOUND_DZS", -1, "-999", NULL);
7984 ctl->bound_zetas =
7985 scan_ctl(filename, argc, argv, "BOUND_ZETAS", -1, "-999", NULL);
7986 ctl->bound_pbl =
7987 (int) scan_ctl(filename, argc, argv, "BOUND_PBL", -1, "0", NULL);
7988
7989 /* Species parameters... */
7990 scan_ctl(filename, argc, argv, "SPECIES", -1, "-", ctl->species);
7991 if (strcasecmp(ctl->species, "CF2Cl2") == 0) {
7992 ctl->molmass = 120.907;
7993 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 3e-5;
7994 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 3500.0;
7995 } else if (strcasecmp(ctl->species, "CFCl3") == 0) {
7996 ctl->molmass = 137.359;
7997 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 1.1e-4;
7998 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 3300.0;
7999 } else if (strcasecmp(ctl->species, "CH4") == 0) {
8000 ctl->molmass = 16.043;
8001 ctl->oh_chem_reaction = 2;
8002 ctl->oh_chem[0] = 2.45e-12;
8003 ctl->oh_chem[1] = 1775;
8004 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 1.4e-5;
8005 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 1600.0;
8006 } else if (strcasecmp(ctl->species, "CO") == 0) {
8007 ctl->molmass = 28.01;
8008 ctl->oh_chem_reaction = 3;
8009 ctl->oh_chem[0] = 6.9e-33;
8010 ctl->oh_chem[1] = 2.1;
8011 ctl->oh_chem[2] = 1.1e-12;
8012 ctl->oh_chem[3] = -1.3;
8013 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 9.7e-6;
8014 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 1300.0;
8015 } else if (strcasecmp(ctl->species, "CO2") == 0) {
8016 ctl->molmass = 44.009;
8017 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 3.3e-4;
8018 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 2400.0;
8019 } else if (strcasecmp(ctl->species, "H2O") == 0) {
8020 ctl->molmass = 18.01528;
8021 } else if (strcasecmp(ctl->species, "N2O") == 0) {
8022 ctl->molmass = 44.013;
8023 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 2.4e-4;
8024 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 2600.;
8025 } else if (strcasecmp(ctl->species, "NH3") == 0) {
8026 ctl->molmass = 17.031;
8027 ctl->oh_chem_reaction = 2;
8028 ctl->oh_chem[0] = 1.7e-12;
8029 ctl->oh_chem[1] = 710;
8030 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 5.9e-1;
8031 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 4200.0;
8032 } else if (strcasecmp(ctl->species, "HNO3") == 0) {
8033 ctl->molmass = 63.012;
8034 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 2.1e3;
8035 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 8700.0;
8036 } else if (strcasecmp(ctl->species, "NO") == 0) {
8037 ctl->molmass = 30.006;
8038 ctl->oh_chem_reaction = 3;
8039 ctl->oh_chem[0] = 7.1e-31;
8040 ctl->oh_chem[1] = 2.6;
8041 ctl->oh_chem[2] = 3.6e-11;
8042 ctl->oh_chem[3] = 0.1;
8043 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 1.9e-5;
8044 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 1600.0;
8045 } else if (strcasecmp(ctl->species, "NO2") == 0) {
8046 ctl->molmass = 46.005;
8047 ctl->oh_chem_reaction = 3;
8048 ctl->oh_chem[0] = 1.8e-30;
8049 ctl->oh_chem[1] = 3.0;
8050 ctl->oh_chem[2] = 2.8e-11;
8051 ctl->oh_chem[3] = 0.0;
8052 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 1.2e-4;
8053 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 2400.0;
8054 } else if (strcasecmp(ctl->species, "O3") == 0) {
8055 ctl->molmass = 47.997;
8056 ctl->oh_chem_reaction = 2;
8057 ctl->oh_chem[0] = 1.7e-12;
8058 ctl->oh_chem[1] = 940;
8059 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 1e-4;
8060 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 2800.0;
8061 } else if (strcasecmp(ctl->species, "SF6") == 0) {
8062 ctl->molmass = 146.048;
8063 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = 2.4e-6;
8064 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = 3100.0;
8065 } else if (strcasecmp(ctl->species, "SO2") == 0) {
8066 ctl->molmass = 64.066;
8067 ctl->oh_chem_reaction = 3;
8068 ctl->oh_chem[0] = 2.9e-31;
8069 ctl->oh_chem[1] = 4.1;
8070 ctl->oh_chem[2] = 1.7e-12;
8071 ctl->oh_chem[3] = -0.2;
8072 ctl->wet_depo_ic_h[0] = ctl->wet_depo_bc_h[0] = SO2_HENRY_REF;
8073 ctl->wet_depo_ic_h[1] = ctl->wet_depo_bc_h[1] = SO2_HENRY_TEMP;
8074 }
8075
8076 /* Molar mass... */
8077 char defstr[LEN];
8078 sprintf(defstr, "%g", ctl->molmass);
8079 ctl->molmass = scan_ctl(filename, argc, argv, "MOLMASS", -1, defstr, NULL);
8080
8081 /* OH chemistry... */
8082 sprintf(defstr, "%d", ctl->oh_chem_reaction);
8083 const double oh_chem_reaction =
8084 scan_ctl(filename, argc, argv, "OH_CHEM_REACTION", -1, defstr, NULL);
8085 if (oh_chem_reaction != 0. && oh_chem_reaction != 1.
8086 && oh_chem_reaction != 2. && oh_chem_reaction != 3.)
8087 ERRMSG("OH_CHEM_REACTION must be 0, 1, 2, or 3!");
8088 ctl->oh_chem_reaction = (int) oh_chem_reaction;
8089 for (int ip = 0; ip < 4; ip++) {
8090 sprintf(defstr, "%g", ctl->oh_chem[ip]);
8091 ctl->oh_chem[ip] =
8092 scan_ctl(filename, argc, argv, "OH_CHEM", ip, defstr, NULL);
8093 }
8094 ctl->oh_chem_beta =
8095 scan_ctl(filename, argc, argv, "OH_CHEM_BETA", -1, "0", NULL);
8096 if (ctl->oh_chem_reaction > 0) {
8097 if (!isfinite(ctl->oh_chem_beta))
8098 ERRMSG("OH_CHEM_BETA must be finite!");
8099 if (!isfinite(ctl->oh_chem[0]) || ctl->oh_chem[0] < 0
8100 || (ctl->oh_chem_reaction == 3 && ctl->oh_chem[0] == 0))
8101 ERRMSG("Invalid OH_CHEM[0] for selected reaction!");
8102 if (ctl->oh_chem_reaction >= 2 && !isfinite(ctl->oh_chem[1]))
8103 ERRMSG("OH_CHEM[1] must be finite!");
8104 if (ctl->oh_chem_reaction == 3
8105 && (!isfinite(ctl->oh_chem[2]) || ctl->oh_chem[2] <= 0
8106 || !isfinite(ctl->oh_chem[3])))
8107 ERRMSG("Termolecular OH_CHEM[2] must be positive and [3] finite!");
8108 }
8109
8110 /* H2O2 chemistry... */
8111 const double h2o2_chem_reaction =
8112 scan_ctl(filename, argc, argv, "H2O2_CHEM_REACTION", -1, "0", NULL);
8113 if (h2o2_chem_reaction != 0. && h2o2_chem_reaction != 1.)
8114 ERRMSG("H2O2_CHEM_REACTION must be 0 or 1!");
8115 ctl->h2o2_chem_reaction = (int) h2o2_chem_reaction;
8116
8117 /* KPP chemistry... */
8118 ctl->kpp_chem =
8119 (int) scan_ctl(filename, argc, argv, "KPP_CHEM", -1, "0", NULL);
8120 ctl->dt_kpp = scan_ctl(filename, argc, argv, "DT_KPP", -1, "1800", NULL);
8121 if (ctl->kpp_chem && !DT_ALIGNED(ctl->dt_kpp, ctl->dt_mod))
8122 ERRMSG("DT_KPP must be a positive integer multiple of DT_MOD!");
8123 if (ctl->kpp_chem && (ctl->qnt_m < 0 || ctl->qnt_Cx < 0))
8124 ERRMSG("KPP_CHEM requires quantities m and Cx!");
8125
8126 /* First order tracer chemistry... */
8127 const double tracer_chem =
8128 scan_ctl(filename, argc, argv, "TRACER_CHEM", -1, "0", NULL);
8129 if (tracer_chem != 0. && tracer_chem != 1.)
8130 ERRMSG("TRACER_CHEM must be 0 or 1!");
8131 ctl->tracer_chem = (int) tracer_chem;
8132
8133 /* Radioactive decay... */
8134 const double radio_decay =
8135 scan_ctl(filename, argc, argv, "RADIO_DECAY", -1, "0", NULL);
8136 const double radio_depo =
8137 scan_ctl(filename, argc, argv, "RADIO_DEPO", -1, "0", NULL);
8138 if (radio_decay != 0. && radio_decay != 1.)
8139 ERRMSG("RADIO_DECAY must be 0 or 1!");
8140 if (radio_depo != 0. && radio_depo != 1.)
8141 ERRMSG("RADIO_DEPO must be 0 or 1!");
8142 ctl->radio_decay = (int) radio_decay;
8143 ctl->radio_depo = (int) radio_depo;
8144 if (ctl->radio_depo && ctl->met_coord_type != 0)
8145 ERRMSG("Radioactive deposition requires a lat/lon meteorological grid!");
8146
8147 /* Wet deposition... */
8148 for (int ip = 0; ip < 2; ip++) {
8149 sprintf(defstr, "%g", ctl->wet_depo_ic_h[ip]);
8150 ctl->wet_depo_ic_h[ip] =
8151 scan_ctl(filename, argc, argv, "WET_DEPO_IC_H", ip, defstr, NULL);
8152 }
8153 for (int ip = 0; ip < 2; ip++) {
8154 sprintf(defstr, "%g", ctl->wet_depo_bc_h[ip]);
8155 ctl->wet_depo_bc_h[ip] =
8156 scan_ctl(filename, argc, argv, "WET_DEPO_BC_H", ip, defstr, NULL);
8157 }
8158 ctl->wet_depo_so2_ph =
8159 scan_ctl(filename, argc, argv, "WET_DEPO_SO2_PH", -1, "0", NULL);
8160 ctl->wet_depo_ic_a =
8161 scan_ctl(filename, argc, argv, "WET_DEPO_IC_A", -1, "0", NULL);
8162 ctl->wet_depo_ic_b =
8163 scan_ctl(filename, argc, argv, "WET_DEPO_IC_B", -1, "0", NULL);
8164 ctl->wet_depo_bc_a =
8165 scan_ctl(filename, argc, argv, "WET_DEPO_BC_A", -1, "0", NULL);
8166 ctl->wet_depo_bc_b =
8167 scan_ctl(filename, argc, argv, "WET_DEPO_BC_B", -1, "0", NULL);
8168 ctl->wet_depo_pre[0] =
8169 scan_ctl(filename, argc, argv, "WET_DEPO_PRE", 0, "0.5", NULL);
8170 ctl->wet_depo_pre[1] =
8171 scan_ctl(filename, argc, argv, "WET_DEPO_PRE", 1, "0.36", NULL);
8173 scan_ctl(filename, argc, argv, "WET_DEPO_IC_RET_RATIO", -1, "1", NULL);
8175 scan_ctl(filename, argc, argv, "WET_DEPO_BC_RET_RATIO", -1, "1", NULL);
8176 if (!isfinite(ctl->wet_depo_ic_a) || ctl->wet_depo_ic_a < 0.
8177 || !isfinite(ctl->wet_depo_bc_a) || ctl->wet_depo_bc_a < 0.
8178 || !isfinite(ctl->wet_depo_ic_h[0]) || ctl->wet_depo_ic_h[0] < 0.
8179 || !isfinite(ctl->wet_depo_bc_h[0]) || ctl->wet_depo_bc_h[0] < 0.)
8180 ERRMSG
8181 ("Wet-deposition activation coefficients must be finite and nonnegative!");
8182 const int wet_ic = ctl->wet_depo_ic_a > 0. || ctl->wet_depo_ic_h[0] > 0.;
8183 const int wet_bc = ctl->wet_depo_bc_a > 0. || ctl->wet_depo_bc_h[0] > 0.;
8184 if (wet_ic || wet_bc || ctl->radio_depo > 0) {
8185 for (int ip = 0; ip < 2; ip++)
8186 if (!isfinite(ctl->wet_depo_pre[ip]) || ctl->wet_depo_pre[ip] <= 0.)
8187 ERRMSG("WET_DEPO_PRE coefficients must be finite and positive!");
8188 }
8189 if ((wet_ic || ctl->radio_depo > 0)
8190 && (!isfinite(ctl->wet_depo_ic_ret_ratio)
8191 || ctl->wet_depo_ic_ret_ratio < 0.
8192 || ctl->wet_depo_ic_ret_ratio > 1.))
8193 ERRMSG("WET_DEPO_IC_RET_RATIO must be finite and within [0, 1]!");
8194 if ((wet_bc || ctl->radio_depo > 0)
8195 && (!isfinite(ctl->wet_depo_bc_ret_ratio)
8196 || ctl->wet_depo_bc_ret_ratio < 0.
8197 || ctl->wet_depo_bc_ret_ratio > 1.))
8198 ERRMSG("WET_DEPO_BC_RET_RATIO must be finite and within [0, 1]!");
8199 if (ctl->wet_depo_ic_a > 0. && !isfinite(ctl->wet_depo_ic_b))
8200 ERRMSG("WET_DEPO_IC_B must be finite when WET_DEPO_IC_A is positive!");
8201 if (ctl->wet_depo_bc_a > 0. && !isfinite(ctl->wet_depo_bc_b))
8202 ERRMSG("WET_DEPO_BC_B must be finite when WET_DEPO_BC_A is positive!");
8203 if (ctl->wet_depo_ic_a == 0. && ctl->wet_depo_ic_h[0] > 0.
8204 && !isfinite(ctl->wet_depo_ic_h[1]))
8205 ERRMSG("WET_DEPO_IC_H[1] must be finite for Henry-law scavenging!");
8206 if (ctl->wet_depo_bc_a == 0. && ctl->wet_depo_bc_h[0] > 0.
8207 && !isfinite(ctl->wet_depo_bc_h[1]))
8208 ERRMSG("WET_DEPO_BC_H[1] must be finite for Henry-law scavenging!");
8209 if (ctl->wet_depo_ic_a == 0. && ctl->wet_depo_ic_h[0] > 0.
8210 && !isfinite(ctl->wet_depo_so2_ph))
8211 ERRMSG("WET_DEPO_SO2_PH must be finite for in-cloud Henry-law scavenging!");
8212 if (ctl->wet_depo_so2_ph > 0. && ctl->wet_depo_ic_a == 0.
8213 && ctl->wet_depo_ic_h[0] > 0.
8214 && ctl->species[0] != '-' && strcasecmp(ctl->species, "SO2") != 0)
8215 ERRMSG
8216 ("WET_DEPO_SO2_PH requires SPECIES=SO2 for in-cloud Henry-law scavenging!");
8217
8218 /* Dry deposition... */
8219 const double dry_depo_mode =
8220 scan_ctl(filename, argc, argv, "DRY_DEPO_MODE", -1, "0", NULL);
8221 if (dry_depo_mode != 0. && dry_depo_mode != 1. && dry_depo_mode != 2.)
8222 ERRMSG("Set DRY_DEPO_MODE to 0 (off), 1 (prescribed), or 2 (aerosol)!");
8223 ctl->dry_depo_mode = (int) dry_depo_mode;
8224 ctl->dry_depo_vdep =
8225 scan_ctl(filename, argc, argv, "DRY_DEPO_VDEP", -1, "0", NULL);
8226 ctl->dry_depo_dz =
8227 scan_ctl(filename, argc, argv, "DRY_DEPO_DZ", -1, "30", NULL);
8228 if (ctl->dry_depo_mode > 0 || ctl->radio_depo > 0) {
8229 if (!isfinite(ctl->dry_depo_dz) || ctl->dry_depo_dz <= 0.)
8230 ERRMSG("DRY_DEPO_DZ must be finite and positive!");
8231 }
8232 if (ctl->dry_depo_mode > 0) {
8233 if (ctl->dry_depo_mode == 1
8234 && (!isfinite(ctl->dry_depo_vdep) || ctl->dry_depo_vdep <= 0.))
8235 ERRMSG("DRY_DEPO_VDEP must be finite and positive in mode 1!");
8236 if (ctl->dry_depo_mode == 2
8237 && (ctl->qnt_rp < 0 || ctl->qnt_rhop < 0))
8238 ERRMSG("DRY_DEPO_MODE=2 requires quantities rp and rhop!");
8239 }
8240
8241 /* Climatological data... */
8242 scan_ctl(filename, argc, argv, "CLIM_PHOTO", -1,
8243 "../../data/clams_photolysis_rates.nc", ctl->clim_photo);
8244 scan_ctl(filename, argc, argv, "CLIM_HNO3_FILENAME", -1,
8245 "../../data/gozcards_HNO3.nc", ctl->clim_hno3_filename);
8246 scan_ctl(filename, argc, argv, "CLIM_OH_FILENAME", -1,
8247 "../../data/clams_radical_species_vmr.nc", ctl->clim_oh_filename);
8248 scan_ctl(filename, argc, argv, "CLIM_H2O2_FILENAME", -1,
8249 "../../data/cams_H2O2.nc", ctl->clim_h2o2_filename);
8250 scan_ctl(filename, argc, argv, "CLIM_HO2_FILENAME", -1,
8251 "../../data/clams_radical_species_vmr.nc", ctl->clim_ho2_filename);
8252 scan_ctl(filename, argc, argv, "CLIM_O1D_FILENAME", -1,
8253 "../../data/clams_radical_species_vmr.nc", ctl->clim_o1d_filename);
8254 scan_ctl(filename, argc, argv, "CLIM_CCL4_TIMESERIES", -1,
8255 "../../data/noaa_gml_ccl4.tab", ctl->clim_ccl4_timeseries);
8256 scan_ctl(filename, argc, argv, "CLIM_CCL3F_TIMESERIES", -1,
8257 "../../data/noaa_gml_cfc11.tab", ctl->clim_ccl3f_timeseries);
8258 scan_ctl(filename, argc, argv, "CLIM_CCL2F2_TIMESERIES", -1,
8259 "../../data/noaa_gml_cfc12.tab", ctl->clim_ccl2f2_timeseries);
8260 scan_ctl(filename, argc, argv, "CLIM_N2O_TIMESERIES", -1,
8261 "../../data/noaa_gml_n2o.tab", ctl->clim_n2o_timeseries);
8262 scan_ctl(filename, argc, argv, "CLIM_SF6_TIMESERIES", -1,
8263 "../../data/noaa_gml_sf6.tab", ctl->clim_sf6_timeseries);
8264
8265 /* Mixing... */
8266 ctl->mixing_dt =
8267 scan_ctl(filename, argc, argv, "MIXING_DT", -1, "3600.", NULL);
8268 ctl->mixing_tau_trop =
8269 scan_ctl(filename, argc, argv, "MIXING_TAU_TROP", -1, "-999", NULL);
8270 ctl->mixing_tau_strat =
8271 scan_ctl(filename, argc, argv, "MIXING_TAU_STRAT", -1, "-999", NULL);
8272 ctl->mixing_z0 =
8273 scan_ctl(filename, argc, argv, "MIXING_Z0", -1, "-5", NULL);
8274 ctl->mixing_z1 =
8275 scan_ctl(filename, argc, argv, "MIXING_Z1", -1, "85", NULL);
8276 ctl->mixing_nz =
8277 (int) scan_ctl(filename, argc, argv, "MIXING_NZ", -1, "90", NULL);
8278 ctl->mixing_lon0 =
8279 scan_ctl(filename, argc, argv, "MIXING_LON0", -1, "-180", NULL);
8280 ctl->mixing_lon1 =
8281 scan_ctl(filename, argc, argv, "MIXING_LON1", -1, "180", NULL);
8282 ctl->mixing_nx =
8283 (int) scan_ctl(filename, argc, argv, "MIXING_NX", -1, "360", NULL);
8284 ctl->mixing_lat0 =
8285 scan_ctl(filename, argc, argv, "MIXING_LAT0", -1, "-90", NULL);
8286 ctl->mixing_lat1 =
8287 scan_ctl(filename, argc, argv, "MIXING_LAT1", -1, "90", NULL);
8288 ctl->mixing_ny =
8289 (int) scan_ctl(filename, argc, argv, "MIXING_NY", -1, "180", NULL);
8290 if (ctl->mixing_nx < 1 || ctl->mixing_ny < 1 || ctl->mixing_nz < 1
8291 || ctl->mixing_lon0 >= ctl->mixing_lon1
8292 || ctl->mixing_lat0 >= ctl->mixing_lat1
8293 || ctl->mixing_z0 >= ctl->mixing_z1
8294 || ctl->mixing_lat0 < -90 || ctl->mixing_lat1 > 90)
8295 ERRMSG("Invalid mixing grid!");
8296 if ((ctl->mixing_tau_trop > 0) != (ctl->mixing_tau_strat > 0)
8297 || ctl->mixing_tau_trop == 0 || ctl->mixing_tau_strat == 0)
8298 ERRMSG("Mixing times must either both be positive or both be disabled!");
8299 if (ctl->mixing_tau_trop > 0) {
8300 if (!isfinite(ctl->mixing_dt))
8301 ERRMSG("MIXING_DT must be finite!");
8302 if (ctl->mixing_dt > 0 && !DT_ALIGNED(ctl->mixing_dt, ctl->dt_mod))
8303 ERRMSG("MIXING_DT must be an integer multiple of DT_MOD!");
8304 }
8305 if (ctl->mixing_tau_trop > 0 && ctl->met_coord_type == 1)
8306 ERRMSG("Interparcel mixing requires geographic coordinates (MET_COORD_TYPE=0)!");
8307
8308 /* Chemistry grid... */
8309 ctl->chemgrid_z0 =
8310 scan_ctl(filename, argc, argv, "CHEMGRID_Z0", -1, "-5", NULL);
8311 ctl->chemgrid_z1 =
8312 scan_ctl(filename, argc, argv, "CHEMGRID_Z1", -1, "85", NULL);
8313 ctl->chemgrid_nz =
8314 (int) scan_ctl(filename, argc, argv, "CHEMGRID_NZ", -1, "90", NULL);
8315 ctl->chemgrid_lon0 =
8316 scan_ctl(filename, argc, argv, "CHEMGRID_LON0", -1, "-180", NULL);
8317 ctl->chemgrid_lon1 =
8318 scan_ctl(filename, argc, argv, "CHEMGRID_LON1", -1, "180", NULL);
8319 ctl->chemgrid_nx =
8320 (int) scan_ctl(filename, argc, argv, "CHEMGRID_NX", -1, "360", NULL);
8321 ctl->chemgrid_lat0 =
8322 scan_ctl(filename, argc, argv, "CHEMGRID_LAT0", -1, "-90", NULL);
8323 ctl->chemgrid_lat1 =
8324 scan_ctl(filename, argc, argv, "CHEMGRID_LAT1", -1, "90", NULL);
8325 ctl->chemgrid_ny =
8326 (int) scan_ctl(filename, argc, argv, "CHEMGRID_NY", -1, "180", NULL);
8327 if (ctl->chemgrid_nx < 1 || ctl->chemgrid_ny < 1 || ctl->chemgrid_nz < 1
8328 || ctl->chemgrid_lon0 >= ctl->chemgrid_lon1
8329 || ctl->chemgrid_lat0 >= ctl->chemgrid_lat1
8330 || ctl->chemgrid_z0 >= ctl->chemgrid_z1
8331 || ctl->chemgrid_lat0 < -90 || ctl->chemgrid_lat1 > 90)
8332 ERRMSG("Invalid chemistry grid!");
8333
8334 /* Exponential decay... */
8335 ctl->tdec_trop = scan_ctl(filename, argc, argv, "TDEC_TROP", -1, "0", NULL);
8336 ctl->tdec_strat =
8337 scan_ctl(filename, argc, argv, "TDEC_STRAT", -1, "0", NULL);
8338 if (!((ctl->tdec_trop == 0. && ctl->tdec_strat == 0.)
8339 || (isfinite(ctl->tdec_trop) && ctl->tdec_trop > 0.
8340 && isfinite(ctl->tdec_strat) && ctl->tdec_strat > 0.)))
8341 ERRMSG("TDEC_TROP and TDEC_STRAT must both be zero or finite and positive!");
8342
8343 /* PSC analysis... */
8344 ctl->psc_h2o = scan_ctl(filename, argc, argv, "PSC_H2O", -1, "4e-6", NULL);
8345 ctl->psc_hno3 =
8346 scan_ctl(filename, argc, argv, "PSC_HNO3", -1, "9e-9", NULL);
8347
8348 /* Output of atmospheric data... */
8349 scan_ctl(filename, argc, argv, "ATM_BASENAME", -1, "-", ctl->atm_basename);
8350 scan_ctl(filename, argc, argv, "ATM_GPFILE", -1, "-", ctl->atm_gpfile);
8351 ctl->atm_dt_out =
8352 scan_ctl(filename, argc, argv, "ATM_DT_OUT", -1, "86400", NULL);
8353 if (ctl->atm_basename[0] != '-'
8354 && (!isfinite(ctl->atm_dt_out) || ctl->atm_dt_out <= 0))
8355 ERRMSG("ATM_DT_OUT must be finite and positive when output is enabled!");
8356 if (ctl->atm_basename[0] != '-' && ctl->atm_dt_out > 0
8357 && !DT_ALIGNED(ctl->atm_dt_out, ctl->dt_mod))
8358 WARN("ATM_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8359 ctl->atm_filter =
8360 (int) scan_ctl(filename, argc, argv, "ATM_FILTER", -1, "0", NULL);
8361 ctl->atm_stride =
8362 (int) scan_ctl(filename, argc, argv, "ATM_STRIDE", -1, "1", NULL);
8363 ctl->atm_type =
8364 (int) scan_ctl(filename, argc, argv, "ATM_TYPE", -1, "0", NULL);
8365 ctl->atm_type_out =
8366 (int) scan_ctl(filename, argc, argv, "ATM_TYPE_OUT", -1, "-1", NULL);
8367 if (ctl->atm_type_out == -1)
8368 ctl->atm_type_out = ctl->atm_type;
8369 ctl->atm_nc_level =
8370 (int) scan_ctl(filename, argc, argv, "ATM_NC_LEVEL", -1, "0", NULL);
8371 for (int iq = 0; iq < ctl->nq; iq++)
8372 ctl->atm_nc_quant[iq] =
8373 (int) scan_ctl(filename, argc, argv, "ATM_NC_QUANT", iq, "0", NULL);
8374 ctl->obs_type =
8375 (int) scan_ctl(filename, argc, argv, "OBS_TYPE", -1, "0", NULL);
8376
8377 /* Output of mass budget data... */
8378 scan_ctl(filename, argc, argv, "BUDGET_BASENAME", -1, "-",
8379 ctl->budget_basename);
8380 ctl->budget_dt_out =
8381 scan_ctl(filename, argc, argv, "BUDGET_DT_OUT", -1, "86400", NULL);
8382 if (ctl->budget_basename[0] != '-'
8383 && (!isfinite(ctl->budget_dt_out) || ctl->budget_dt_out <= 0))
8384 ERRMSG("BUDGET_DT_OUT must be finite and positive when output is enabled!");
8385 if (ctl->budget_basename[0] != '-' && ctl->budget_dt_out > 0
8386 && !DT_ALIGNED(ctl->budget_dt_out, ctl->dt_mod))
8387 WARN("BUDGET_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8388
8389 /* Output of radioactive deposition data... */
8390 scan_ctl(filename, argc, argv, "DEPO_BASENAME", -1, "-",
8391 ctl->depo_basename);
8392 ctl->depo_dt_out =
8393 scan_ctl(filename, argc, argv, "DEPO_DT_OUT", -1, "86400", NULL);
8394 if (ctl->depo_basename[0] != '-'
8395 && (!isfinite(ctl->depo_dt_out) || ctl->depo_dt_out <= 0))
8396 ERRMSG("DEPO_DT_OUT must be finite and positive when output is enabled!");
8397 if (ctl->depo_basename[0] != '-' && ctl->depo_dt_out > 0
8398 && !DT_ALIGNED(ctl->depo_dt_out, ctl->dt_mod))
8399 WARN("DEPO_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8400 ctl->depo_type =
8401 (int) scan_ctl(filename, argc, argv, "DEPO_TYPE", -1, "0", NULL);
8402
8403 /* Output of CSI data... */
8404 scan_ctl(filename, argc, argv, "CSI_BASENAME", -1, "-", ctl->csi_basename);
8405 scan_ctl(filename, argc, argv, "CSI_KERNEL", -1, "-", ctl->csi_kernel);
8406 ctl->csi_dt_out =
8407 scan_ctl(filename, argc, argv, "CSI_DT_OUT", -1, "86400", NULL);
8408 if (ctl->csi_basename[0] != '-'
8409 && (!isfinite(ctl->csi_dt_out) || ctl->csi_dt_out <= 0))
8410 ERRMSG("CSI_DT_OUT must be finite and positive when output is enabled!");
8411 if (ctl->csi_basename[0] != '-' && ctl->csi_dt_out > 0
8412 && !DT_ALIGNED(ctl->csi_dt_out, ctl->dt_mod))
8413 WARN("CSI_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8414 scan_ctl(filename, argc, argv, "CSI_OBSFILE", -1, "-", ctl->csi_obsfile);
8415 ctl->csi_obsmin =
8416 scan_ctl(filename, argc, argv, "CSI_OBSMIN", -1, "0", NULL);
8417 ctl->csi_modmin =
8418 scan_ctl(filename, argc, argv, "CSI_MODMIN", -1, "0", NULL);
8419 ctl->csi_z0 = scan_ctl(filename, argc, argv, "CSI_Z0", -1, "-5", NULL);
8420 ctl->csi_z1 = scan_ctl(filename, argc, argv, "CSI_Z1", -1, "85", NULL);
8421 ctl->csi_nz = (int) scan_ctl(filename, argc, argv, "CSI_NZ", -1, "1", NULL);
8422 ctl->csi_lon0 =
8423 scan_ctl(filename, argc, argv, "CSI_LON0", -1, "-180", NULL);
8424 ctl->csi_lon1 = scan_ctl(filename, argc, argv, "CSI_LON1", -1, "180", NULL);
8425 ctl->csi_nx =
8426 (int) scan_ctl(filename, argc, argv, "CSI_NX", -1, "360", NULL);
8427 ctl->csi_lat0 = scan_ctl(filename, argc, argv, "CSI_LAT0", -1, "-90", NULL);
8428 ctl->csi_lat1 = scan_ctl(filename, argc, argv, "CSI_LAT1", -1, "90", NULL);
8429 ctl->csi_ny =
8430 (int) scan_ctl(filename, argc, argv, "CSI_NY", -1, "180", NULL);
8431 if (ctl->csi_nx < 1 || ctl->csi_ny < 1 || ctl->csi_nz < 1
8432 || ctl->csi_lon0 >= ctl->csi_lon1
8433 || ctl->csi_lat0 >= ctl->csi_lat1 || ctl->csi_z0 >= ctl->csi_z1
8434 || ctl->csi_lat0 < -90 || ctl->csi_lat1 > 90)
8435 ERRMSG("Invalid CSI grid!");
8436 if (ctl->csi_basename[0] != '-' && ctl->met_coord_type == 0
8437 && (!isfinite(ctl->csi_lon0) || !isfinite(ctl->csi_lon1)
8438 || ctl->csi_lon0 < -180 || ctl->csi_lon1 > 180))
8439 ERRMSG("CSI_LON0/1 must be within [-180, 180] for geographic output!");
8440
8441 /* Output of ensemble data... */
8442 ctl->nens = (int) scan_ctl(filename, argc, argv, "NENS", -1, "0", NULL);
8443 if (ctl->nens < 0)
8444 ERRMSG("NENS must not be negative!");
8445 if (ctl->nens > 0 && ctl->qnt_ens < 0)
8446 ERRMSG("Add quantity ens for ensemble calculations!");
8447 scan_ctl(filename, argc, argv, "ENS_BASENAME", -1, "-", ctl->ens_basename);
8448 ctl->ens_dt_out =
8449 scan_ctl(filename, argc, argv, "ENS_DT_OUT", -1, "86400", NULL);
8450 if (ctl->ens_basename[0] != '-'
8451 && (!isfinite(ctl->ens_dt_out) || ctl->ens_dt_out <= 0))
8452 ERRMSG("ENS_DT_OUT must be finite and positive when output is enabled!");
8453 if (ctl->ens_basename[0] != '-' && ctl->ens_dt_out > 0
8454 && !DT_ALIGNED(ctl->ens_dt_out, ctl->dt_mod))
8455 WARN("ENS_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8456
8457 /* Output of grid data... */
8458 scan_ctl(filename, argc, argv, "GRID_BASENAME", -1, "-",
8459 ctl->grid_basename);
8460 scan_ctl(filename, argc, argv, "GRID_KERNEL", -1, "-", ctl->grid_kernel);
8461 scan_ctl(filename, argc, argv, "GRID_GPFILE", -1, "-", ctl->grid_gpfile);
8462 ctl->grid_dt_out =
8463 scan_ctl(filename, argc, argv, "GRID_DT_OUT", -1, "86400", NULL);
8464 if (ctl->grid_basename[0] != '-'
8465 && (!isfinite(ctl->grid_dt_out) || ctl->grid_dt_out <= 0))
8466 ERRMSG("GRID_DT_OUT must be finite and positive when output is enabled!");
8467 if (ctl->grid_basename[0] != '-' && ctl->grid_dt_out > 0
8468 && !DT_ALIGNED(ctl->grid_dt_out, ctl->dt_mod))
8469 WARN("GRID_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8470 ctl->grid_sparse =
8471 (int) scan_ctl(filename, argc, argv, "GRID_SPARSE", -1, "0", NULL);
8472 ctl->grid_nc_level =
8473 (int) scan_ctl(filename, argc, argv, "GRID_NC_LEVEL", -1, "0", NULL);
8474 for (int iq = 0; iq < ctl->nq; iq++)
8475 ctl->grid_nc_quant[iq] =
8476 (int) scan_ctl(filename, argc, argv, "GRID_NC_QUANT", iq, "0", NULL);
8477 ctl->grid_stddev =
8478 (int) scan_ctl(filename, argc, argv, "GRID_STDDEV", -1, "0", NULL);
8479 ctl->grid_z0 = scan_ctl(filename, argc, argv, "GRID_Z0", -1, "-5", NULL);
8480 ctl->grid_z1 = scan_ctl(filename, argc, argv, "GRID_Z1", -1, "85", NULL);
8481 ctl->grid_nz =
8482 (int) scan_ctl(filename, argc, argv, "GRID_NZ", -1, "1", NULL);
8483 ctl->grid_lon0 =
8484 scan_ctl(filename, argc, argv, "GRID_LON0", -1, "-180", NULL);
8485 ctl->grid_lon1 =
8486 scan_ctl(filename, argc, argv, "GRID_LON1", -1, "180", NULL);
8487 ctl->grid_nx =
8488 (int) scan_ctl(filename, argc, argv, "GRID_NX", -1, "360", NULL);
8489 ctl->grid_lat0 =
8490 scan_ctl(filename, argc, argv, "GRID_LAT0", -1, "-90", NULL);
8491 ctl->grid_lat1 =
8492 scan_ctl(filename, argc, argv, "GRID_LAT1", -1, "90", NULL);
8493 ctl->grid_ny =
8494 (int) scan_ctl(filename, argc, argv, "GRID_NY", -1, "180", NULL);
8495 ctl->grid_type =
8496 (int) scan_ctl(filename, argc, argv, "GRID_TYPE", -1, "0", NULL);
8497 if (ctl->grid_nx < 1 || ctl->grid_nx > EX
8498 || ctl->grid_ny < 1 || ctl->grid_ny > EY || ctl->grid_nz < 1)
8499 ERRMSG("Invalid output grid dimensions!");
8500 if (ctl->grid_lon0 >= ctl->grid_lon1
8501 || ctl->grid_lat0 >= ctl->grid_lat1 || ctl->grid_z0 >= ctl->grid_z1
8502 || ctl->grid_lat0 < -90 || ctl->grid_lat1 > 90)
8503 ERRMSG("Invalid output grid boundaries!");
8504 if ((ctl->grid_basename[0] != '-' || ctl->depo_basename[0] != '-')
8505 && ctl->met_coord_type == 0
8506 && (!isfinite(ctl->grid_lon0) || !isfinite(ctl->grid_lon1)
8507 || ctl->grid_lon0 < -180 || ctl->grid_lon1 > 180))
8508 ERRMSG("GRID_LON0/1 must be within [-180, 180] for geographic output!");
8509 if (ctl->depo_basename[0] != '-'
8510 && (ctl->depo_type < 0 || ctl->depo_type > 1))
8511 ERRMSG("Invalid radioactive deposition output settings!");
8512
8513 /* Output of profile data... */
8514 scan_ctl(filename, argc, argv, "PROF_BASENAME", -1, "-",
8515 ctl->prof_basename);
8516 scan_ctl(filename, argc, argv, "PROF_OBSFILE", -1, "-", ctl->prof_obsfile);
8517 ctl->prof_z0 = scan_ctl(filename, argc, argv, "PROF_Z0", -1, "0", NULL);
8518 ctl->prof_z1 = scan_ctl(filename, argc, argv, "PROF_Z1", -1, "60", NULL);
8519 ctl->prof_nz =
8520 (int) scan_ctl(filename, argc, argv, "PROF_NZ", -1, "60", NULL);
8521 ctl->prof_lon0 =
8522 scan_ctl(filename, argc, argv, "PROF_LON0", -1, "-180", NULL);
8523 ctl->prof_lon1 =
8524 scan_ctl(filename, argc, argv, "PROF_LON1", -1, "180", NULL);
8525 ctl->prof_nx =
8526 (int) scan_ctl(filename, argc, argv, "PROF_NX", -1, "360", NULL);
8527 ctl->prof_lat0 =
8528 scan_ctl(filename, argc, argv, "PROF_LAT0", -1, "-90", NULL);
8529 ctl->prof_lat1 =
8530 scan_ctl(filename, argc, argv, "PROF_LAT1", -1, "90", NULL);
8531 ctl->prof_ny =
8532 (int) scan_ctl(filename, argc, argv, "PROF_NY", -1, "180", NULL);
8533 if (ctl->prof_nx < 1 || ctl->prof_ny < 1 || ctl->prof_nz < 1
8534 || ctl->prof_lon0 >= ctl->prof_lon1
8535 || ctl->prof_lat0 >= ctl->prof_lat1 || ctl->prof_z0 >= ctl->prof_z1
8536 || ctl->prof_lat0 < -90 || ctl->prof_lat1 > 90)
8537 ERRMSG("Invalid profile grid!");
8538 if (ctl->prof_basename[0] != '-' && ctl->met_coord_type == 0
8539 && (!isfinite(ctl->prof_lon0) || !isfinite(ctl->prof_lon1)
8540 || ctl->prof_lon0 < -180 || ctl->prof_lon1 > 180))
8541 ERRMSG("PROF_LON0/1 must be within [-180, 180] for geographic output!");
8542
8543 /* Output of sample data... */
8544 scan_ctl(filename, argc, argv, "SAMPLE_BASENAME", -1, "-",
8545 ctl->sample_basename);
8546 scan_ctl(filename, argc, argv, "SAMPLE_KERNEL", -1, "-",
8547 ctl->sample_kernel);
8548 scan_ctl(filename, argc, argv, "SAMPLE_OBSFILE", -1, "-",
8549 ctl->sample_obsfile);
8550 ctl->sample_dx =
8551 scan_ctl(filename, argc, argv, "SAMPLE_DX", -1, "50", NULL);
8552 ctl->sample_dz =
8553 scan_ctl(filename, argc, argv, "SAMPLE_DZ", -1, "-999", NULL);
8554
8555 /* Output of station data... */
8556 scan_ctl(filename, argc, argv, "STAT_BASENAME", -1, "-",
8557 ctl->stat_basename);
8558 ctl->stat_lon = scan_ctl(filename, argc, argv, "STAT_LON", -1, "0", NULL);
8559 ctl->stat_lat = scan_ctl(filename, argc, argv, "STAT_LAT", -1, "0", NULL);
8560 ctl->stat_r = scan_ctl(filename, argc, argv, "STAT_R", -1, "50", NULL);
8561 ctl->stat_t0 =
8562 scan_ctl(filename, argc, argv, "STAT_T0", -1, "-1e100", NULL);
8563 ctl->stat_t1 = scan_ctl(filename, argc, argv, "STAT_T1", -1, "1e100", NULL);
8564
8565 /* Output of VTK data... */
8566 scan_ctl(filename, argc, argv, "VTK_BASENAME", -1, "-", ctl->vtk_basename);
8567 ctl->vtk_dt_out =
8568 scan_ctl(filename, argc, argv, "VTK_DT_OUT", -1, "86400", NULL);
8569 if (ctl->vtk_basename[0] != '-'
8570 && (!isfinite(ctl->vtk_dt_out) || ctl->vtk_dt_out <= 0))
8571 ERRMSG("VTK_DT_OUT must be finite and positive when output is enabled!");
8572 if (ctl->vtk_basename[0] != '-' && ctl->vtk_dt_out > 0
8573 && !DT_ALIGNED(ctl->vtk_dt_out, ctl->dt_mod))
8574 WARN("VTK_DT_OUT is not an integer multiple of DT_MOD; output may be skipped!");
8575 ctl->vtk_stride =
8576 (int) scan_ctl(filename, argc, argv, "VTK_STRIDE", -1, "1", NULL);
8577 ctl->vtk_scale =
8578 scan_ctl(filename, argc, argv, "VTK_SCALE", -1, "1.0", NULL);
8579 ctl->vtk_offset =
8580 scan_ctl(filename, argc, argv, "VTK_OFFSET", -1, "0.0", NULL);
8581 ctl->vtk_sphere =
8582 (int) scan_ctl(filename, argc, argv, "VTK_SPHERE", -1, "0", NULL);
8583
8584 /* Domain decomposition... */
8585
8586 /* Only the trac tool sets this flag after reading the control parameters... */
8587 ctl->dd_supported = 0;
8588#ifdef DD
8589 /* Domain decomposition is only implemented by the trac tool and only works
8590 if the executable was started with one task per subdomain. Therefore, use
8591 it by default only if MPI has been initialized by the calling tool and if
8592 more than one task is running; otherwise, stay in serial mode. */
8593 int mpi_initialized = 0;
8594 int mpi_size = 1;
8595 MPI_Initialized(&mpi_initialized);
8596 if (mpi_initialized)
8597 MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
8598 ctl->dd =
8599 (int) scan_ctl(filename, argc, argv, "DD", -1,
8600 (mpi_initialized && mpi_size > 1) ? "1" : "0", NULL);
8601#else
8602 ctl->dd = (int) scan_ctl(filename, argc, argv, "DD", -1, "0", NULL);
8603#endif
8604
8606 (int) scan_ctl(filename, argc, argv, "DD_SUBDOMAINS_MERIDIONAL", -1,
8607 (ctl->dd == 1) ? "2" : "1", NULL);
8608 ctl->dd_subdomains_zonal =
8609 (int) scan_ctl(filename, argc, argv, "DD_SUBDOMAINS_ZONAL", -1,
8610 (ctl->dd == 1) ? "2" : "1", NULL);
8611 ctl->dd_halos_size =
8612 (int) scan_ctl(filename, argc, argv, "DD_HALOS_SIZE", -1, "1", NULL);
8613 ctl->dd_sort_dt =
8614 (double) scan_ctl(filename, argc, argv, "DD_SORT_DT", -1, "1800", NULL);
8615 ctl->dd_exchange_mode =
8616 (int) scan_ctl(filename, argc, argv, "DD_EXCHANGE_MODE", -1, "0", NULL);
8617 if (ctl->dd_exchange_mode < 0 || ctl->dd_exchange_mode > 1)
8618 ERRMSG("Set DD_EXCHANGE_MODE to 0 (sort/push) or 1 (no sort)!");
8619 if (ctl->met_nc_read_mode == 1 &&
8620 (!ctl->dd || ctl->met_type != 0 || ctl->met_convention != 0))
8621 ERRMSG("MET_NC_READ_MODE=1 requires MPI DD, NetCDF, and MET_CONVENTION=0!");
8622#ifndef DD
8623 if (ctl->met_nc_read_mode == 1)
8624 ERRMSG("MET_NC_READ_MODE=1 requires a DD build!");
8625#endif
8626
8627#ifdef DD
8628 /* Check the domain decomposition configuration... */
8629 if (ctl->dd) {
8630 if (!mpi_initialized)
8631 ERRMSG
8632 ("Domain decomposition requires to start the executable with one task per subdomain!");
8633 if (ctl->dd_halos_size < 0)
8634 ERRMSG("DD_HALOS_SIZE must be non-negative!");
8635 if (ctl->dd_subdomains_zonal < 1 || ctl->dd_subdomains_meridional < 1)
8636 ERRMSG("The number of subdomains has to be positive!");
8637 if (ctl->dd_subdomains_zonal * ctl->dd_subdomains_meridional == 1)
8638 ERRMSG("Please provide zonal and meridional subdomain numbers!");
8639 if (mpi_size != ctl->dd_subdomains_zonal * ctl->dd_subdomains_meridional)
8640 ERRMSG("Number of tasks and subdomains is not identical!");
8641 if (ctl->qnt_current_subdomain < 0 || ctl->qnt_target_subdomain < 0)
8642 ERRMSG
8643 ("Domain decomposition requires the quantities current_subdomain and target_subdomain!");
8644 if (ctl->met_coord_type != 0)
8645 ERRMSG("Domain decomposition requires a lat/lon meteorological grid!");
8646 if (ctl->radio_depo)
8647 ERRMSG
8648 ("Radioactive deposition is not supported with domain decomposition!");
8649 }
8650#endif
8651
8652 if (fabs(ctl->dt_mod - nearbyint(ctl->dt_mod)) >
8653 8 * DBL_EPSILON * ctl->dt_mod
8654 && ((meteo_sampled && ctl->met_dt_out >= ctl->dt_mod)
8655 || ((ctl->conv_cape >= 0 || ctl->conv_mix_pbl)
8656 && ctl->conv_dt > 0)
8657 || (ctl->mixing_tau_trop > 0 && ctl->mixing_dt > 0)
8658 || (ctl->kpp_chem && ctl->dt_kpp > 0)
8659 || (ctl->atm_basename[0] != '-' && ctl->atm_dt_out > 0)
8660 || (ctl->budget_basename[0] != '-' && ctl->budget_dt_out > 0)
8661 || (ctl->depo_basename[0] != '-' && ctl->depo_dt_out > 0)
8662 || (ctl->csi_basename[0] != '-' && ctl->csi_dt_out > 0)
8663 || (ctl->ens_basename[0] != '-' && ctl->ens_dt_out > 0)
8664 || (ctl->grid_basename[0] != '-' && ctl->grid_dt_out > 0)
8665 || (ctl->vtk_basename[0] != '-' && ctl->vtk_dt_out > 0)
8666 || ctl->sort_dt > 0
8667 || (ctl->dd && ctl->dd_exchange_mode == 0 && ctl->dd_sort_dt > 0)))
8668 WARN("Fractional DT_MOD may cause periodic events to be missed due to floating-point rounding in exact fmod comparisons!");
8669}
void level_definitions(ctl_t *ctl)
Defines pressure levels for meteorological data.
Definition mptrac.c:3686
double scan_ctl(const char *filename, int argc, char *argv[], const char *varname, const int arridx, const char *defvalue, char *value)
Scans a control file or command-line arguments for a specified variable.
Definition mptrac.c:13771
#define METVAR
Number of 3-D meteorological variables.
Definition mptrac.h:564
#define SET_QNT(qnt, name, longname, unit)
Set atmospheric quantity index.
Definition mptrac.h:2063
#define DT_ALIGNED(dt, dt_mod)
Definition mptrac.h:1127
double grid_z0
Lower altitude of gridded data [km].
Definition mptrac.h:3509
int qnt_o3
Quantity array index for ozone volume mixing ratio.
Definition mptrac.h:2669
double csi_lat1
Upper latitude of gridded CSI data [deg].
Definition mptrac.h:3470
char csi_obsfile[LEN]
Observation data file for CSI analysis.
Definition mptrac.h:3437
int met_nc_scale
Check netCDF scaling factors (0=no, 1=yes).
Definition mptrac.h:2940
int qnt_pel
Quantity array index for pressure at equilibrium level (EL).
Definition mptrac.h:2702
int csi_nz
Number of altitudes of gridded CSI data.
Definition mptrac.h:3446
int qnt_p
Quantity array index for pressure.
Definition mptrac.h:2648
char atm_gpfile[LEN]
Gnuplot file for atmospheric data.
Definition mptrac.h:3392
int qnt_swc
Quantity array index for cloud snow water content.
Definition mptrac.h:2681
double csi_obsmin
Minimum observation index to trigger detection.
Definition mptrac.h:3440
int qnt_pcb
Quantity array index for cloud bottom pressure.
Definition mptrac.h:2690
double csi_lon1
Upper longitude of gridded CSI data [deg].
Definition mptrac.h:3461
int qnt_u
Quantity array index for zonal wind.
Definition mptrac.h:2657
double stat_lon
Longitude of station [deg].
Definition mptrac.h:3587
double sort_dt
Time step for sorting of particle data [s].
Definition mptrac.h:3086
double stat_r
Search radius around station [km].
Definition mptrac.h:3593
int csi_ny
Number of latitudes of gridded CSI data.
Definition mptrac.h:3464
int vtk_sphere
Spherical projection for VTK data (0=no, 1=yes).
Definition mptrac.h:3617
double met_pbl_min
Minimum depth of planetary boundary layer [km].
Definition mptrac.h:3054
int qnt_iwc
Quantity array index for cloud ice water content.
Definition mptrac.h:2678
int qnt_pw
Quantity array index for partial water vapor pressure.
Definition mptrac.h:2756
char prof_basename[LEN]
Basename for profile output file.
Definition mptrac.h:3536
double grid_z1
Upper altitude of gridded data [km].
Definition mptrac.h:3512
int met_dp
Stride for pressure levels.
Definition mptrac.h:3006
double met_dt_out
Time step for sampling of meteo data along trajectories [s].
Definition mptrac.h:3073
int qnt_h2o2
Quantity array index for H2O2 volume mixing ratio (climatology).
Definition mptrac.h:2720
int qnt_vh
Quantity array index for horizontal wind.
Definition mptrac.h:2798
int csi_nx
Number of longitudes of gridded CSI data.
Definition mptrac.h:3455
double csi_lat0
Lower latitude of gridded CSI data [deg].
Definition mptrac.h:3467
int met_pbl
Planetary boundary layer data (0=file, 1=z2p, 2=Richardson, 3=theta).
Definition mptrac.h:3051
int qnt_lwc
Quantity array index for cloud liquid water content.
Definition mptrac.h:2672
int grid_nc_level
zlib compression level of netCDF grid data files (0=off).
Definition mptrac.h:3497
int qnt_ts
Quantity array index for surface temperature.
Definition mptrac.h:2603
int qnt_plfc
Quantity array index for pressure at level of free convection (LCF).
Definition mptrac.h:2699
int qnt_o1d
Quantity array index for O(1D) volume mixing ratio (climatology).
Definition mptrac.h:2726
int met_tropo_spline
Tropopause interpolation method (0=linear, 1=spline).
Definition mptrac.h:3070
char sample_kernel[LEN]
Kernel data file for sample output.
Definition mptrac.h:3572
int qnt_tvirt
Quantity array index for virtual temperature.
Definition mptrac.h:2792
int met_geopot_sy
Latitudinal smoothing of geopotential heights.
Definition mptrac.h:3042
char grid_gpfile[LEN]
Gnuplot file for gridded data.
Definition mptrac.h:3488
int qnt_lsm
Quantity array index for land-sea mask.
Definition mptrac.h:2624
int qnt_theta
Quantity array index for potential temperature.
Definition mptrac.h:2768
double stat_t1
Stop time for station output [s].
Definition mptrac.h:3599
char csi_kernel[LEN]
Kernel data file for CSI output.
Definition mptrac.h:3431
int grid_type
Type of grid data files (0=ASCII, 1=netCDF).
Definition mptrac.h:3533
double csi_lon0
Lower longitude of gridded CSI data [deg].
Definition mptrac.h:3458
int qnt_pbl
Quantity array index for boundary layer pressure.
Definition mptrac.h:2630
int grid_stddev
Include standard deviations in grid output (0=no, 1=yes).
Definition mptrac.h:3503
int met_nc_read_mode
NetCDF DD input (0=local hyperslabs, 1=global 2-D slices via MPI).
Definition mptrac.h:2943
int qnt_psice
Quantity array index for saturation pressure over ice.
Definition mptrac.h:2753
int met_geopot_sx
Longitudinal smoothing of geopotential heights.
Definition mptrac.h:3039
int met_sy
Smoothing for latitudes.
Definition mptrac.h:3012
int qnt_ps
Quantity array index for surface pressure.
Definition mptrac.h:2600
char prof_obsfile[LEN]
Observation data file for profile output.
Definition mptrac.h:3539
int qnt_zs
Quantity array index for surface geopotential height.
Definition mptrac.h:2606
int prof_nz
Number of altitudes of gridded profile data.
Definition mptrac.h:3542
double csi_dt_out
Time step for CSI output [s].
Definition mptrac.h:3434
int met_cape
Convective available potential energy data (0=file, 1=calculate).
Definition mptrac.h:3048
double csi_modmin
Minimum column density to trigger detection [kg/m^2].
Definition mptrac.h:3443
int met_sx
Smoothing for longitudes.
Definition mptrac.h:3009
double depo_dt_out
DEPO_DT_OUT time interval for radioactive deposition output [s] (default: 86400).
Definition mptrac.h:3383
char grid_kernel[LEN]
Kernel data file for grid output.
Definition mptrac.h:3485
double prof_z0
Lower altitude of gridded profile data [km].
Definition mptrac.h:3545
int qnt_w
Quantity array index for vertical velocity.
Definition mptrac.h:2663
double met_tropo_pv
Dynamical tropopause potential vorticity threshold [PVU].
Definition mptrac.h:3064
int prof_nx
Number of longitudes of gridded profile data.
Definition mptrac.h:3551
int qnt_stat
Quantity array index for station flag.
Definition mptrac.h:2585
int dd_supported
Whether the executable implements the domain decomposition.
Definition mptrac.h:3650
int met_mpi_share
Use MPI to share meteo (0=no, 1=yes).
Definition mptrac.h:3079
int qnt_vz
Quantity array index for vertical velocity.
Definition mptrac.h:2801
int qnt_ho2
Quantity array index for HO2 volume mixing ratio (climatology).
Definition mptrac.h:2723
double csi_z1
Upper altitude of gridded CSI data [km].
Definition mptrac.h:3452
double stat_t0
Start time for station output [s].
Definition mptrac.h:3596
int atm_type_out
Type of atmospheric data files for output (-1=same as ATM_TYPE, 0=ASCII, 1=binary,...
Definition mptrac.h:3410
int met_cms_nd0x
cmultiscale number of cells of coarsest grid in x-direction.
Definition mptrac.h:2988
int met_nlev
Number of meteo data model levels.
Definition mptrac.h:3030
double dt_kpp
Time step for KPP chemistry [s].
Definition mptrac.h:3319
char csi_basename[LEN]
Basename of CSI data files.
Definition mptrac.h:3428
int qnt_shf
Quantity array index for surface sensible heat flux.
Definition mptrac.h:2621
int qnt_vs
Quantity array index for surface meridional wind.
Definition mptrac.h:2612
double vtk_dt_out
Time step for VTK data output [s].
Definition mptrac.h:3605
double conv_dt
Time interval for convection module [s].
Definition mptrac.h:3154
char sample_obsfile[LEN]
Observation data file for sample output.
Definition mptrac.h:3575
int qnt_hno3
Quantity array index for HNO3 volume mixing ratio (climatology).
Definition mptrac.h:2714
char grid_basename[LEN]
Basename of grid data files.
Definition mptrac.h:3482
char met_comp_logfile[LEN]
Filename for per-level compression diagnostics ("-" disables output).
Definition mptrac.h:2979
int qnt_h2ot
Quantity array index for tropopause water vapor volume mixing ratio.
Definition mptrac.h:2642
int qnt_rh
Quantity array index for relative humidity over water.
Definition mptrac.h:2762
int met_gp2z
Convert surface geopotential to geopotential height (0=no, 1=yes).
Definition mptrac.h:2930
double met_pbl_max
Maximum depth of planetary boundary layer [km].
Definition mptrac.h:3057
int met_dx
Stride for longitudes.
Definition mptrac.h:3000
int met_convention
Meteo data layout (0=[lev, lat, lon], 1=[lon, lat, lev]).
Definition mptrac.h:2914
char depo_basename[LEN]
DEPO_BASENAME for radioactive deposition files (default: disabled with "-").
Definition mptrac.h:3380
int qnt_zeta_d
Quantity array index for diagnosed zeta vertical coordinate.
Definition mptrac.h:2777
int diffusion
Diffusion switch (0=off, 1=on).
Definition mptrac.h:3106
double budget_dt_out
Time step for mass budget output [s].
Definition mptrac.h:3425
int qnt_zg
Quantity array index for geopotential height.
Definition mptrac.h:2645
double vtk_offset
Vertical offset for VTK data [km].
Definition mptrac.h:3614
int qnt_v
Quantity array index for meridional wind.
Definition mptrac.h:2660
double met_zfp_tol[METVAR]
ZFP compression tolerance.
Definition mptrac.h:2967
int qnt_oh
Quantity array index for OH volume mixing ratio (climatology).
Definition mptrac.h:2717
int met_sz3_prec[METVAR]
SZ3 compression precision.
Definition mptrac.h:2970
int qnt_h2o
Quantity array index for water vapor volume mixing ratio.
Definition mptrac.h:2666
int prof_ny
Number of latitudes of gridded profile data.
Definition mptrac.h:3560
int qnt_rhice
Quantity array index for relative humidity over ice.
Definition mptrac.h:2765
int qnt_rho
Quantity array index for density of air.
Definition mptrac.h:2654
double sample_dz
Layer depth for sample output [km].
Definition mptrac.h:3581
int obs_type
Type of observation data files (0=ASCII, 1=netCDF).
Definition mptrac.h:3419
int grid_nc_quant[NQ]
Number of digits for quantization of netCDF grid data files (0=off).
Definition mptrac.h:3500
int qnt_us
Quantity array index for surface zonal wind.
Definition mptrac.h:2609
int depo_type
DEPO_TYPE of deposition files (0=ASCII, 1=netCDF, default: 0).
Definition mptrac.h:3386
char budget_basename[LEN]
Basename of mass budget data file.
Definition mptrac.h:3422
char atm_basename[LEN]
Basename of atmospheric data files.
Definition mptrac.h:3389
int qnt_pt
Quantity array index for tropopause pressure.
Definition mptrac.h:2633
int qnt_cl
Quantity array index for total column cloud water.
Definition mptrac.h:2693
double prof_z1
Upper altitude of gridded profile data [km].
Definition mptrac.h:3548
double met_lev_hyam[EP]
Meteo data model level a coefficients.
Definition mptrac.h:3033
int qnt_t
Quantity array index for temperature.
Definition mptrac.h:2651
int atm_filter
Time filter for atmospheric data output (0=none, 1=missval, 2=remove).
Definition mptrac.h:3398
int kpp_chem
Switch for KPP chemistry module (0=off, 1=on).
Definition mptrac.h:3316
int met_lz4_accel
LZ4 acceleration factor (>=1, default=8).
Definition mptrac.h:2958
char ens_basename[LEN]
Basename of ensemble data file.
Definition mptrac.h:3476
int met_vert_coord
Vertical coordinate of input meteo data (0=plev, 1=mlev_p_file, 2=mlev_ab_file, 3=mlev_ab_full,...
Definition mptrac.h:2927
double csi_z0
Lower altitude of gridded CSI data [km].
Definition mptrac.h:3449
int qnt_lapse
Quantity array index for lapse rate.
Definition mptrac.h:2795
double stat_lat
Latitude of station [deg].
Definition mptrac.h:3590
double met_detrend
FWHM of horizontal Gaussian used for detrending [km].
Definition mptrac.h:3018
double met_cms_eps[METVAR]
cmultiscale compression epsilon.
Definition mptrac.h:2997
int qnt_cape
Quantity array index for convective available potential energy (CAPE).
Definition mptrac.h:2705
int met_cms_nd0y
cmultiscale number of cells of coarsest grid in y-direction.
Definition mptrac.h:2991
int qnt_o3c
Quantity array index for total column ozone.
Definition mptrac.h:2711
int grid_nz
Number of altitudes of gridded data.
Definition mptrac.h:3506
int qnt_nss
Quantity array index for northward turbulent surface stress.
Definition mptrac.h:2618
double ens_dt_out
Time step for ensemble output [s].
Definition mptrac.h:3479
char sample_basename[LEN]
Basename of sample data file.
Definition mptrac.h:3569
int atm_stride
Particle index stride for atmospheric data files.
Definition mptrac.h:3401
int met_relhum
Try to read relative humidity (0=no, 1=yes).
Definition mptrac.h:3045
double atm_dt_out
Time step for atmospheric data output [s].
Definition mptrac.h:3395
int met_lossy_scale[METVAR]
Apply levelwise [0,1] scaling before lossy compression (0=off, 1=on).
Definition mptrac.h:2976
double prof_lat1
Upper latitude of gridded profile data [deg].
Definition mptrac.h:3566
int met_cms_batch
cmultiscale batch size.
Definition mptrac.h:2982
double psc_h2o
H2O volume mixing ratio for PSC analysis.
Definition mptrac.h:3370
int met_sp
Smoothing for pressure levels.
Definition mptrac.h:3015
double prof_lon0
Lower longitude of gridded profile data [deg].
Definition mptrac.h:3554
int qnt_pct
Quantity array index for cloud top pressure.
Definition mptrac.h:2687
int qnt_mloss_kpp
Quantity array index for total mass loss due to KPP chemistry.
Definition mptrac.h:2735
int qnt_psat
Quantity array index for saturation pressure over water.
Definition mptrac.h:2750
double met_lev_hybm[EP]
Meteo data model level b coefficients.
Definition mptrac.h:3036
double prof_lat0
Lower latitude of gridded profile data [deg].
Definition mptrac.h:3563
int qnt_cin
Quantity array index for convective inhibition (CIN).
Definition mptrac.h:2708
double turb_pbl_trans
Depth of turbulent PBL transition layer (fraction of PBL pressure thickness).
Definition mptrac.h:3139
double psc_hno3
HNO3 volume mixing ratio for PSC analysis.
Definition mptrac.h:3373
double prof_lon1
Upper longitude of gridded profile data [deg].
Definition mptrac.h:3557
int met_nc_quant
Number of digits for quantization of netCDF meteo files (0=off).
Definition mptrac.h:2949
int atm_nc_quant[NQ]
Number of digits for quantization of netCDF atmospheric data files (0=off).
Definition mptrac.h:3416
int met_cms_zstd
cmultiscale ZSTD compression (0=off, 1=on).
Definition mptrac.h:2985
int met_cms_maxlev
cmultiscale maximum refinement level.
Definition mptrac.h:2994
int grid_sparse
Sparse output in grid data files (0=no, 1=yes).
Definition mptrac.h:3494
double met_sz3_tol[METVAR]
SZ3 compression tolerance.
Definition mptrac.h:2973
char vtk_basename[LEN]
Basename of VTK data files.
Definition mptrac.h:3602
int qnt_tt
Quantity array index for tropopause temperature.
Definition mptrac.h:2636
int met_nc_level
zlib compression level of netCDF meteo files (0=off).
Definition mptrac.h:2946
double vtk_scale
Vertical scaling factor for VTK data.
Definition mptrac.h:3611
int qnt_pv
Quantity array index for potential vorticity.
Definition mptrac.h:2804
int qnt_sst
Quantity array index for sea surface temperature.
Definition mptrac.h:2627
int atm_nc_level
zlib compression level of netCDF atmospheric data files (0=off).
Definition mptrac.h:3413
int qnt_sh
Quantity array index for specific humidity.
Definition mptrac.h:2759
int qnt_ess
Quantity array index for eastward turbulent surface stress.
Definition mptrac.h:2615
int met_dy
Stride for latitudes.
Definition mptrac.h:3003
int radio_depo
RADIO_DEPO switch for radionuclide deposition (0=off, 1=on, default: 0).
Definition mptrac.h:3328
int qnt_idx
Quantity array index for air parcel IDs.
Definition mptrac.h:2579
double met_tropo_theta
Dynamical tropopause potential temperature threshold [K].
Definition mptrac.h:3067
int qnt_rwc
Quantity array index for cloud rain water content.
Definition mptrac.h:2675
char qnt_longname[NQ][LEN]
Quantity long names.
Definition mptrac.h:2570
int met_zfp_prec[METVAR]
ZFP compression precision.
Definition mptrac.h:2964
double sample_dx
Horizontal radius for sample output [km].
Definition mptrac.h:3578
int vtk_stride
Particle index stride for VTK data.
Definition mptrac.h:3608
char stat_basename[LEN]
Basename of station data file.
Definition mptrac.h:3584
int qnt_zt
Quantity array index for tropopause geopotential height.
Definition mptrac.h:2639
int qnt_cc
Quantity array index for cloud cover.
Definition mptrac.h:2684
int qnt_plcl
Quantity array index for pressure at lifted condensation level (LCL).
Definition mptrac.h:2696
double grid_dt_out
Time step for gridded data output [s].
Definition mptrac.h:3491
int qnt_tdew
Quantity array index for dew point temperature.
Definition mptrac.h:2807
Here is the call graph for this function:

◆ mptrac_read_met()

int mptrac_read_met ( const char * filename,
const ctl_t * ctl,
const clim_t * clim,
met_t * met,
dd_t * dd )

Reads meteorological data from a file, supporting multiple formats and MPI broadcasting.

This function reads meteorological data from a file specified by the filename parameter. It supports both NetCDF and binary formats based on the met_type field in the ctl_t structure. The function can also handle parallel processing with MPI, broadcasting the data across ranks if required by the configuration.

Parameters
filenameA constant character pointer representing the name of the file to read the meteorological data from.
ctlA pointer to a ctl_t structure, which holds control parameters including the type of meteorological data, MPI sharing flags, and configuration details.
climA pointer to a clim_t structure, which contains climatological data to be used in the process, if applicable.
metA pointer to a met_t structure that will store the meteorological data read from the file.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.
Returns
Returns an integer, where 1 indicates success.
Note
  • The function logs the action of reading meteorological data, including the file name.
  • It supports MPI parallelization and will share the data across multiple processes if the met_mpi_share flag is set in the control structure.
  • If ctl->met_type is 0, the data is read from a NetCDF file using the read_met_nc function.
  • If ctl->met_type is between 1 and 5, or equals 7 or 8, the data is read from a binary file using the read_met_bin function.
  • If ctl->met_type is 6, the data is read from grib files using the read_met_grib function.
  • If the met_type is not recognized, an error message is generated.
Author
Lars Hoffmann

Definition at line 8673 of file mptrac.c.

8678 {
8679
8680 /* Write info... */
8681 LOG(1, "Read meteo data: %s", filename);
8682
8683#ifdef DD
8684 /* With domain decomposition, each task reads the meteo data of its own
8685 subdomain only, which is not what the tools operating on the full meteo
8686 grid expect... */
8687 if (ctl->dd && !ctl->dd_supported)
8688 ERRMSG("The domain decomposition is only implemented by the trac tool!");
8689#endif
8690
8691 /* Set rank... */
8692 int rank = 0;
8693 int pv_supplied = 0;
8694
8695 /* Check whether the meteo data is shared between the tasks... */
8696 int share = ctl->met_mpi_share;
8697#ifdef MPI
8698 /* Sharing the meteo data between the tasks requires to start the executable
8699 with a parallel launcher. If MPI has not been initialized, the meteo data
8700 is read by the single task itself... */
8701 int mpi_initialized = 0;
8702 MPI_Initialized(&mpi_initialized);
8703 if (share && !mpi_initialized) {
8704 WARN("Cannot share meteo data because MPI has not been initialized!");
8705 share = 0;
8706 }
8707 if (share)
8708 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
8709#endif
8710
8711 /* Check rank... */
8712 if (!share || rank == 0) {
8713
8714 /* Read netCDF data... */
8715 if (ctl->met_type == 0) {
8716 if (read_met_nc(filename, ctl, met, dd, &pv_supplied) != 1)
8717 return 0;
8718 }
8719
8720 /* Read binary data... */
8721 else if ((ctl->met_type >= 1 && ctl->met_type <= 5)
8722 || ctl->met_type == 7 || ctl->met_type == 8) {
8723 if (read_met_bin(filename, ctl, met) != 1)
8724 return 0;
8725 }
8726#ifdef ECCODES
8727 /* Read grib data... */
8728 else if (ctl->met_type == 6) {
8729 if (read_met_grib(filename, ctl, met) != 1)
8730 return 0;
8731 }
8732#endif
8733
8734 /* Not implemented... */
8735 else
8736 ERRMSG("MET_TYPE not implemented!");
8737
8738 /* Check geographic longitude coordinates... */
8739 if (met->coord_type == 0)
8740 for (int ix = 1; ix < met->nx; ix++)
8741 if (!(met->lon[ix] > met->lon[ix - 1]))
8742 ERRMSG("Geographic longitudes must be strictly increasing!");
8743
8744 /* Check active latitude and pressure coordinates... */
8745 for (int iy = 0; iy < met->ny; iy++) {
8746 if (!isfinite(met->lat[iy]))
8747 ERRMSG("Meteo latitudes must be finite!");
8748 if (met->coord_type == 0 && fabs(met->lat[iy]) > 90.)
8749 ERRMSG("Geographic latitudes must be within [-90, 90] degrees!");
8750 }
8751 if (met->np < 2)
8752 ERRMSG("At least two pressure levels are required!");
8753 for (int ip = 0; ip < met->np; ip++) {
8754 if (!isfinite(met->p[ip]))
8755 ERRMSG("Meteo pressure levels must be finite!");
8756 if (ip > 0 && !(met->p[ip - 1] > met->p[ip]))
8757 ERRMSG("Meteo pressure levels must be strictly descending!");
8758 }
8759
8760 /* Preprocessing for netCDF and grib files... */
8761 if (ctl->met_type == 0 || ctl->met_type == 6) {
8762
8763 /* Extrapolate data for lower boundary... */
8765
8766 /* Fix polar winds... */
8768
8769 /* Create periodic boundary conditions... */
8770#ifdef DD
8771 /* Zonal DD halos provide periodic boundaries only when there is more
8772 than one zonal subdomain. With a single zonal subdomain, append the
8773 periodic endpoint locally as in a run without DD. */
8774 if (!ctl->dd || ctl->dd_subdomains_zonal == 1)
8775 read_met_periodic(met);
8776#else
8777 read_met_periodic(met);
8778#endif
8779
8780 /* Downsampling... */
8781 read_met_sample(ctl, met);
8782
8783 /* Calculate geopotential heights... */
8784 read_met_geopot(ctl, met);
8785
8786 /* Calculate PV only when the input does not supply it... */
8787 if (!pv_supplied)
8788 read_met_pv(met);
8789
8790 /* Calculate boundary layer data... */
8791 read_met_pbl(ctl, met);
8792
8793 /* Calculate tropopause data... */
8794 read_met_tropo(ctl, clim, met);
8795
8796 /* Calculate cloud properties... */
8797 read_met_cloud(met);
8798
8799 /* Calculate convective available potential energy... */
8800 read_met_cape(ctl, clim, met);
8801
8802 /* Calculate total column ozone... */
8803 read_met_ozone(met);
8804
8805 /* Detrending... */
8806 read_met_detrend(ctl, met);
8807
8808 /* Check meteo data and smooth zeta profiles ... */
8809 read_met_monotonize(ctl, met);
8810 }
8811 }
8812
8813 /* Broadcast data via MPI... */
8814#ifdef MPI
8815 if (share) {
8816
8817 /* Set timer... */
8818 SELECT_TIMER("READ_MET_MPI_BCAST", "COMM");
8819 LOG(2, "Broadcast data on rank %d...", rank);
8820
8821 /* Broadcast... */
8822 broadcast_large_data(met, sizeof(met_t));
8823 }
8824#endif
8825
8826 /* Return success... */
8827 return 1;
8828}
void read_met_geopot(const ctl_t *ctl, met_t *met)
Calculates geopotential heights from meteorological data.
Definition mptrac.c:10527
void read_met_extrapolate(met_t *met)
Extrapolates meteorological data.
Definition mptrac.c:10487
void read_met_sample(const ctl_t *ctl, met_t *met)
Downsamples meteorological data based on specified parameters.
Definition mptrac.c:13317
void read_met_cloud(met_t *met)
Calculates cloud-related variables for each grid point.
Definition mptrac.c:10323
void read_met_pbl(const ctl_t *ctl, met_t *met)
Computes the planetary boundary layer (PBL) pressure based on meteorological data.
Definition mptrac.c:12908
void read_met_detrend(const ctl_t *ctl, met_t *met)
Detrends meteorological data.
Definition mptrac.c:10380
void read_met_monotonize(const ctl_t *ctl, met_t *met)
Makes zeta and pressure profiles monotone.
Definition mptrac.c:12570
void read_met_periodic(met_t *met)
Applies periodic boundary conditions to meteorological data along longitudinal axis.
Definition mptrac.c:13045
int read_met_nc(const char *filename, const ctl_t *ctl, met_t *met, dd_t *dd, int *pv_supplied)
Reads meteorological data from a NetCDF file and processes it.
Definition mptrac.c:12655
void read_met_ozone(met_t *met)
Calculates the total column ozone from meteorological ozone data.
Definition mptrac.c:13288
void broadcast_large_data(void *data, size_t N)
State variables of cuRAND random number generator.
Definition mptrac.c:47
void read_met_pv(met_t *met)
Calculates potential vorticity (PV) from meteorological data.
Definition mptrac.c:13169
int read_met_bin(const char *filename, const ctl_t *ctl, met_t *met)
Reads meteorological data from a binary file.
Definition mptrac.c:9904
void read_met_polar_winds(met_t *met)
Applies a fix for polar winds in meteorological data.
Definition mptrac.c:13107
void read_met_cape(const ctl_t *ctl, const clim_t *clim, met_t *met)
Calculates Convective Available Potential Energy (CAPE) for each grid point.
Definition mptrac.c:10203
int read_met_grib(const char *filename, const ctl_t *ctl, met_t *met)
Reads meteorological data from a grib file and processes it.
Here is the call graph for this function:

◆ mptrac_run_timestep()

void mptrac_run_timestep ( ctl_t * ctl,
cache_t * cache,
clim_t * clim,
met_t ** met0,
met_t ** met1,
atm_t * atm,
depo_t * depo,
double t,
dd_t * dd )

Executes a single timestep of the MPTRAC model simulation.

This function performs all operations required to advance the model simulation by one timestep. It includes updating air parcel positions, applying advection, diffusion, convection, and other processes such as sedimentation, chemistry, and deposition. Each process is conditionally executed based on the control settings provided in the ctl structure.

Parameters
ctlPointer to the control structure containing model parameters and settings.
cachePointer to the cache structure used for intermediate calculations.
climPointer to the climatology structure containing climatological data.
met0Pointer to the current meteorological data structure.
met1Pointer to the next meteorological data structure.
atmPointer to the atmosphere structure containing air parcel data.
depoPointer to cumulative radionuclide ground inventories.
tCurrent simulation time in seconds.
ddMPI information required for the domain decomposition.
Author
Lars Hoffmann

Definition at line 8832 of file mptrac.c.

8841 {
8842
8843 /* Initialize modules... */
8844 if (t == ctl->t_start) {
8845
8846 /* Initialize isosurface data... */
8847 if (ctl->isosurf >= 1 && ctl->isosurf <= 4)
8848 module_isosurf_init(ctl, cache, *met0, *met1, atm, 1, t);
8849
8850 /* Initialize advection... */
8851 module_advect_init(ctl, cache, *met0, *met1, atm);
8852
8853 /* Initialize chemistry... */
8854 module_chem_init(ctl, cache, clim, *met0, *met1, atm);
8855 }
8856
8857 /* Set time steps of air parcels... */
8858 module_timesteps(ctl, cache, *met0, atm, t);
8859
8860 /* Initialize delayed isosurface references before particle movement. */
8861 if (ctl->isosurf == 2 || ctl->isosurf == 3)
8862 module_isosurf_init(ctl, cache, *met0, *met1, atm, 0, t);
8863
8864 /* Sort particles... */
8865 if (ctl->sort_dt > 0 && fmod(t, ctl->sort_dt) == 0)
8866 module_sort(ctl, *met0, cache, atm);
8867
8868 /* Check positions (initial)... */
8869 module_position(cache, *met0, *met1, atm, 0);
8870
8871 /* Advection... */
8872 if (ctl->advect > 0)
8873 module_advect(ctl, cache, *met0, *met1, atm);
8874
8875 /* Turbulent diffusion... */
8876 if (ctl->diffusion
8877 && (ctl->turb_dx_pbl > 0 || ctl->turb_dz_pbl > 0
8878 || ctl->turb_dx_trop > 0 || ctl->turb_dz_trop > 0
8879 || ctl->turb_dx_strat > 0 || ctl->turb_dz_strat > 0))
8880 module_diff_turb(ctl, cache, clim, *met0, *met1, atm);
8881
8882 /* Optional PBL-specific diffusion scheme... */
8883 if (ctl->diffusion && ctl->turb_pbl_scheme == 1)
8884 module_diff_pbl(ctl, cache, *met0, *met1, atm);
8885
8886 /* Mesoscale diffusion... */
8887 if (ctl->diffusion && (ctl->turb_mesox > 0 || ctl->turb_mesoz > 0))
8888 module_diff_meso(ctl, cache, *met0, *met1, atm);
8889
8890 /* Convection... */
8891 if ((ctl->conv_mix_pbl || ctl->conv_cape >= 0)
8892 && (ctl->conv_dt <= 0 || fmod(t, ctl->conv_dt) == 0))
8893 module_convection(ctl, cache, *met0, *met1, atm);
8894
8895 /* Sedimentation... */
8896 if (ctl->qnt_rp >= 0 && ctl->qnt_rhop >= 0)
8897 module_sedi(ctl, cache, *met0, *met1, atm);
8898
8899 /* Isosurface... */
8900 if (ctl->isosurf >= 1 && ctl->isosurf <= 4)
8901 module_isosurf(ctl, cache, *met0, *met1, atm);
8902
8903 /* Check positions (final)... */
8904 module_position(cache, *met0, *met1, atm, 1);
8905
8906 /* Domain decomposition... */
8907#ifdef DD
8908 if (ctl->dd)
8909 module_dd(t, ctl, cache, dd, atm, met0);
8910#else
8911 (void) dd;
8912#endif
8913
8914 /* Interpolate meteo data... */
8915 if (ctl->met_dt_out > 0
8916 && (ctl->met_dt_out < ctl->dt_mod || fmod(t, ctl->met_dt_out) == 0))
8917 module_meteo(ctl, cache, clim, *met0, *met1, atm);
8918
8919 /* Check boundary conditions (initial)... */
8920 if ((ctl->bound_lat0 < ctl->bound_lat1)
8921 && (ctl->bound_p0 > ctl->bound_p1))
8922 module_bound_cond(ctl, cache, clim, *met0, *met1, atm);
8923
8924 /* Initialize quantity of total loss rate... */
8925 if (ctl->qnt_loss_rate >= 0) {
8926 PARTICLE_LOOP(0, atm->np, 1, "acc data present(ctl,atm)") {
8927 atm->q[ctl->qnt_loss_rate][ip] = 0;
8928 }
8929 }
8930
8931 /* Decay of particle mass... */
8932 if (ctl->tdec_trop > 0 && ctl->tdec_strat > 0)
8933 module_decay(ctl, cache, clim, atm);
8934
8935 /* Interparcel mixing... */
8936 if (ctl->mixing_tau_trop > 0 && ctl->mixing_tau_strat > 0
8937 && (ctl->mixing_dt <= 0 || fmod(t, ctl->mixing_dt) == 0))
8938 module_mixing(ctl, cache, clim, atm, t);
8939
8940 /* Calculate the tracer vmr in the chemistry grid... */
8941 if (ctl->oh_chem_reaction != 0 || ctl->h2o2_chem_reaction != 0
8942 || (ctl->kpp_chem && fmod(t, ctl->dt_kpp) == 0))
8943 module_chem_grid(ctl, cache, *met0, *met1, atm, t);
8944
8945 /* OH chemistry... */
8946 if (ctl->oh_chem_reaction != 0)
8947 module_oh_chem(ctl, cache, clim, *met0, *met1, atm);
8948
8949 /* H2O2 chemistry (for SO2 aqueous phase oxidation)... */
8950 if (ctl->h2o2_chem_reaction != 0)
8951 module_h2o2_chem(ctl, cache, clim, *met0, *met1, atm);
8952
8953 /* First-order tracer chemistry... */
8954 if (ctl->tracer_chem)
8955 module_tracer_chem(ctl, cache, clim, *met0, *met1, atm);
8956
8957 /* Radioactive decay... */
8958 if (ctl->radio_decay)
8959 module_radio_decay(ctl, cache, atm);
8960
8961 /* Radioactive deposition... */
8962 if (ctl->radio_depo)
8963 module_radio_depo(ctl, cache, *met0, *met1, atm, depo);
8964
8965 /* KPP chemistry... */
8966 if (ctl->kpp_chem && fmod(t, ctl->dt_kpp) == 0) {
8967#ifdef KPP
8968 module_kpp_chem(ctl, cache, clim, *met0, *met1, atm);
8969#else
8970 ERRMSG("Code was compiled without KPP!");
8971#endif
8972 }
8973
8974 /* Wet deposition... */
8975 if (ctl->wet_depo_ic_a > 0 || ctl->wet_depo_ic_h[0] > 0
8976 || ctl->wet_depo_bc_a > 0 || ctl->wet_depo_bc_h[0] > 0)
8977 module_wet_depo(ctl, cache, *met0, *met1, atm);
8978
8979 /* Dry deposition... */
8980 if (ctl->dry_depo_mode > 0)
8981 module_dry_depo(ctl, cache, *met0, *met1, atm);
8982
8983 /* Check boundary conditions (final)... */
8984 if ((ctl->bound_lat0 < ctl->bound_lat1)
8985 && (ctl->bound_p0 > ctl->bound_p1))
8986 module_bound_cond(ctl, cache, clim, *met0, *met1, atm);
8987}
void module_advect(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Advances particle positions using different advection schemes.
Definition mptrac.c:3942
void module_meteo(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Update atmospheric properties using meteorological data.
Definition mptrac.c:5559
void module_decay(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, atm_t *atm)
Simulate exponential decay processes for atmospheric particles.
Definition mptrac.c:4591
void module_chem_init(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Initializes the chemistry modules by setting atmospheric composition.
Definition mptrac.c:4413
void module_mixing(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, atm_t *atm, const double t)
Update atmospheric properties through interparcel mixing.
Definition mptrac.c:5689
void module_wet_depo(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Perform wet deposition calculations for air parcels.
Definition mptrac.c:6719
void module_isosurf_init(const ctl_t *ctl, cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, const int initial, const double model_t)
Initialize the isosurface module based on atmospheric data.
Definition mptrac.c:5332
void module_sedi(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Simulate sedimentation of particles in the atmosphere.
Definition mptrac.c:6442
void module_convection(const ctl_t *ctl, cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Performs convective mixing of atmospheric particles.
Definition mptrac.c:4457
void module_bound_cond(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Apply boundary conditions to particles based on meteorological and climatological data.
Definition mptrac.c:4125
void module_advect_init(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Initializes the advection module by setting up pressure fields.
Definition mptrac.c:4098
void module_position(const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, const int reflect)
Update the positions and pressure levels of atmospheric particles.
Definition mptrac.c:5992
void module_radio_decay(const ctl_t *ctl, const cache_t *cache, atm_t *atm)
Apply radioactive decay to atmospheric tracer species.
Definition mptrac.c:6051
void module_chem_grid(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, const double tt)
Computes gridded chemical tracer concentrations (volume mixing ratio) from individual air parcel mass...
Definition mptrac.c:4221
void module_diff_meso(const ctl_t *ctl, cache_t *cache, const met_t *met0, const met_t *met1, atm_t *atm)
Simulate mesoscale diffusion for atmospheric particles.
Definition mptrac.c:4630
void module_sort(const ctl_t *ctl, const met_t *met0, cache_t *cache, atm_t *atm)
Sort particles according to box index.
Definition mptrac.c:6470
void module_diff_turb(const ctl_t *ctl, cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Applies turbulent diffusion processes to atmospheric particles.
Definition mptrac.c:4990
void module_timesteps(const ctl_t *ctl, cache_t *cache, const met_t *met0, atm_t *atm, const double t)
Calculate time steps for air parcels based on specified conditions.
Definition mptrac.c:6547
void module_tracer_chem(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Simulate chemical reactions involving long-lived atmospheric tracers.
Definition mptrac.c:6627
void module_h2o2_chem(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Apply aqueous H2O2 oxidation of SO2 in liquid cloud water.
Definition mptrac.c:5228
void module_diff_pbl(const ctl_t *ctl, cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Computes particle diffusion within the planetary boundary layer (PBL).
Definition mptrac.c:4707
void module_isosurf(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Apply the isosurface module to adjust atmospheric properties.
Definition mptrac.c:5444
void module_oh_chem(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
Perform hydroxyl chemistry calculations for atmospheric particles.
Definition mptrac.c:5892
void module_dd(double t, const ctl_t *ctl, cache_t *cache, dd_t *dd, atm_t *atm, met_t **met)
Perform domain decomposition and exchange particles between MPI ranks.
Definition mptrac.c:4532
void module_dry_depo(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm)
Simulate dry deposition of atmospheric particles.
Definition mptrac.c:5162
void module_radio_depo(const ctl_t *ctl, const cache_t *cache, met_t *met0, met_t *met1, atm_t *atm, depo_t *depo)
Deposit supported radionuclides from air parcels onto the ground grid.
Definition mptrac.c:6109
void module_kpp_chem(ctl_t *ctl, cache_t *cache, clim_t *clim, met_t *met0, met_t *met1, atm_t *atm)
KPP chemistry module.
Here is the call graph for this function:

◆ mptrac_write_atm()

void mptrac_write_atm ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes air parcel data to a file in various formats.

The mptrac_write_atm function writes the air parcel data stored in the atm structure to a file specified by filename. The format of the output file is determined by the atm_type_out field in the ctl control structure.

Parameters
filenameA string representing the name of the file to write the data to.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.
tThe current time, used for certain output formats.

The function performs the following steps:

  • Sets a timer for the write operation using the SELECT_TIMER macro.
  • Logs the beginning of the write operation with the specified filename.
  • Depending on the atm_type_out value in the ctl structure, writes the data in one of the following formats:
    • ASCII (atm_type_out == 0): Calls write_atm_asc.
    • Binary (atm_type_out == 1): Calls write_atm_bin.
    • netCDF (atm_type_out == 2): Calls write_atm_nc.
    • CLaMS trajectory data (atm_type_out == 3): Calls write_atm_clams_traj.
    • CLaMS position data (atm_type_out == 4): Calls write_atm_clams.
  • If the atm_type_out value is not supported, triggers an error message.
  • Logs various statistics about the atmospheric data, including the number of particles, time range, altitude range, pressure range, longitude range, and latitude range.
  • Logs the range for each quantity specified in the ctl structure.
Author
Lars Hoffmann

Definition at line 9103 of file mptrac.c.

9107 {
9108
9109 /* Set timer... */
9110 SELECT_TIMER("WRITE_ATM", "OUTPUT");
9111
9112 /* Write info... */
9113 LOG(1, "Write atmospheric data: %s", filename);
9114
9115 /* Write ASCII data... */
9116 if (ctl->atm_type_out == 0)
9117 write_atm_asc(filename, ctl, atm, t);
9118
9119 /* Write binary data... */
9120 else if (ctl->atm_type_out == 1)
9121 write_atm_bin(filename, ctl, atm);
9122
9123 /* Write netCDF data... */
9124 else if (ctl->atm_type_out == 2)
9125 write_atm_nc(filename, ctl, atm);
9126
9127 /* Write CLaMS trajectory data... */
9128 else if (ctl->atm_type_out == 3)
9129 write_atm_clams_traj(filename, ctl, atm, t);
9130
9131 /* Write CLaMS pos data... */
9132 else if (ctl->atm_type_out == 4)
9133 write_atm_clams(filename, ctl, atm);
9134
9135 /* Error... */
9136 else
9137 ERRMSG("Atmospheric data type not supported!");
9138
9139 /* Write info... */
9140 double mini, maxi;
9141 LOG(2, "Number of particles: %d", atm->np);
9142 gsl_stats_minmax(&mini, &maxi, atm->time, 1, (size_t) atm->np);
9143 LOG(2, "Time range: %.2f ... %.2f s", mini, maxi);
9144 gsl_stats_minmax(&mini, &maxi, atm->p, 1, (size_t) atm->np);
9145 LOG(2, "Altitude range: %g ... %g km", Z(maxi), Z(mini));
9146 LOG(2, "Pressure range: %g ... %g hPa", maxi, mini);
9147 gsl_stats_minmax(&mini, &maxi, atm->lon, 1, (size_t) atm->np);
9148 LOG(2, "%s range: %g ... %g %s",
9149 ctl->met_coord_type == 0 ? "Longitude" : "X coordinate", mini, maxi,
9150 ctl->met_coord_type == 0 ? "deg" : "m");
9151 gsl_stats_minmax(&mini, &maxi, atm->lat, 1, (size_t) atm->np);
9152 LOG(2, "%s range: %g ... %g %s",
9153 ctl->met_coord_type == 0 ? "Latitude" : "Y coordinate", mini, maxi,
9154 ctl->met_coord_type == 0 ? "deg" : "m");
9155 for (int iq = 0; iq < ctl->nq; iq++) {
9156 char msg[5 * LEN];
9157 sprintf(msg, "Quantity %s range: %s ... %s %s",
9158 ctl->qnt_name[iq], ctl->qnt_format[iq],
9159 ctl->qnt_format[iq], ctl->qnt_unit[iq]);
9160 gsl_stats_minmax(&mini, &maxi, atm->q[iq], 1, (size_t) atm->np);
9161 LOG(2, msg, mini, maxi);
9162 }
9163}
void write_atm_clams_traj(const char *dirname, const ctl_t *ctl, const atm_t *atm, const double t)
Writes CLaMS trajectory data to a NetCDF file.
Definition mptrac.c:14345
void write_atm_asc(const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
Writes air parcel data to an ASCII file or gnuplot.
Definition mptrac.c:14139
void write_atm_clams(const char *filename, const ctl_t *ctl, const atm_t *atm)
Writes air parcel data to a NetCDF file in the CLaMS format.
Definition mptrac.c:14287
void write_atm_bin(const char *filename, const ctl_t *ctl, const atm_t *atm)
Writes air parcel data to a binary file.
Definition mptrac.c:14237
void write_atm_nc(const char *filename, const ctl_t *ctl, const atm_t *atm)
Writes air parcel data to a NetCDF file.
Definition mptrac.c:14513
Here is the call graph for this function:

◆ mptrac_write_met()

void mptrac_write_met ( const char * filename,
const ctl_t * ctl,
met_t * met )

Writes meteorological data to a file, supporting multiple formats and compression options.

This function handles writing meteorological data based on the specified control (ctl_t) and meteorological data (met_t) structures. The file format and compression type are determined by the met_type in the control structure. The function supports netCDF, binary output, and various compression methods (ZFP, ZSTD, CMS), while providing error handling for unsupported configurations.

Parameters
filenameA constant character pointer representing the name of the file to write the meteorological data to.
ctlA pointer to a ctl_t structure, which holds the configuration and control parameters for the output, including the type of meteorological data and compression method.
metA pointer to a met_t structure that holds the meteorological data to be written to the file.
Note
  • The function selects a timer for performance profiling or debugging.
  • It logs the action of writing meteorological data, including the file name.
Warning
  • If ctl->met_type is 3, ZFP compression is required, and the function will generate an error if compiled without ZFP support.
  • If ctl->met_type is 4, ZSTD compression is required, and the function will generate an error if compiled without ZSTD support.
  • If ctl->met_type is 5, CMS compression is required, and the function will generate an error if compiled without CMS support.
  • If ctl->met_type is 7, SZ3 compression is required, and the function will generate an error if compiled without SZ3 support.
  • If ctl->met_type is 8, LZ4 compression is required, and the function will generate an error if compiled without LZ4 support.
Note
  • If ctl->met_type is 0, the function writes data in netCDF format via write_met_nc.
  • If ctl->met_type is between 1 and 5, or equals 7 or 8, the function writes data in binary format via write_met_bin.
  • If ctl->met_type is not recognized, an error message is generated.
Author
Lars Hoffmann

Definition at line 9167 of file mptrac.c.

9170 {
9171
9172 /* Set timer... */
9173 SELECT_TIMER("WRITE_MET", "OUTPUT");
9174
9175 /* Write info... */
9176 LOG(1, "Write meteo data: %s", filename);
9177
9178 /* Check compression flags... */
9179#ifndef ZFP
9180 if (ctl->met_type == 3)
9181 ERRMSG("MPTRAC was compiled without ZFP compression!");
9182#endif
9183#ifndef ZSTD
9184 if (ctl->met_type == 4)
9185 ERRMSG("MPTRAC was compiled without ZSTD compression!");
9186#endif
9187#ifndef LZ4
9188 if (ctl->met_type == 8)
9189 ERRMSG("MPTRAC was compiled without LZ4 compression!");
9190#endif
9191#ifndef CMS
9192 if (ctl->met_type == 5)
9193 ERRMSG("MPTRAC was compiled without cmultiscale compression!");
9194#endif
9195#ifndef SZ3
9196 if (ctl->met_type == 7)
9197 ERRMSG("MPTRAC was compiled without SZ3 compression!");
9198#endif
9199
9200 /* Write netCDF data... */
9201 if (ctl->met_type == 0)
9202 write_met_nc(filename, ctl, met);
9203
9204 /* Write binary data... */
9205 else if ((ctl->met_type >= 1 && ctl->met_type <= 5)
9206 || ctl->met_type == 7 || ctl->met_type == 8)
9207 write_met_bin(filename, ctl, met);
9208
9209 /* Not implemented... */
9210 else
9211 ERRMSG("MET_TYPE not implemented!");
9212}
void write_met_nc(const char *filename, const ctl_t *ctl, met_t *met)
Writes meteorological data to a NetCDF file.
Definition mptrac.c:15928
void write_met_bin(const char *filename, const ctl_t *ctl, met_t *met)
Writes meteorological data in binary format to a specified file.
Definition mptrac.c:15676
Here is the call graph for this function:

◆ mptrac_write_output()

void mptrac_write_output ( const char * dirname,
const ctl_t * ctl,
met_t * met0,
met_t * met1,
atm_t * atm,
depo_t * depo,
const double t )

Writes various types of output data to files in a specified directory.

The mptrac_write_output function writes various types of output data to files in the directory specified by the dirname parameter. The function takes control parameters (ctl), two meteorological data structures (met0 and met1), an atmospheric data structure (atm), and a time value (t) as input.

Parameters
dirnameA string representing the directory path where output files will be written.
ctlA pointer to a ctl_t structure containing control parameters.
met0A pointer to a met_t structure representing the first set of meteorological data.
met1A pointer to a met_t structure representing the second set of meteorological data.
atmA pointer to an atm_t structure representing atmospheric data.
depoA pointer to the cumulative radionuclide ground inventories.
tA double value representing the time at which the output is being written.

The function performs the following steps:

  • Parses the input time (t) to extract year, month, day, hour, minute, and second.
  • Updates host memory if necessary based on control parameters.
  • Writes atmospheric data to files if specified by control parameters.
  • Writes gridded data to files if specified by control parameters.
  • Writes cumulative radionuclide deposition if specified by control parameters.
  • Writes CSI (Critical Success Index) data to files if specified by control parameters.
  • Writes ensemble data to files if specified by control parameters.
  • Writes profile data to files if specified by control parameters.
  • Writes sample data to files if specified by control parameters.
  • Writes station data to files if specified by control parameters.
  • Writes VTK (Visualization Toolkit) data to files if specified by control parameters.
Note
This function orchestrates the writing of various types of output data to files based on control parameters and the current simulation time.
Author
Lars Hoffmann

Definition at line 9216 of file mptrac.c.

9223 {
9224
9225 char ext[10], filename[2 * LEN];
9226
9227 double r;
9228
9229 int year, mon, day, hour, min, sec;
9230
9231 /* Get time... */
9232 jsec2time(t, &year, &mon, &day, &hour, &min, &sec, &r);
9233
9234 /* Decide which particle outputs are due, including the final step... */
9235 const int final = (t == ctl->t_stop);
9236 const int output_atm = ctl->atm_basename[0] != '-'
9237 && (fmod(t, ctl->atm_dt_out) == 0 || final);
9238 const int output_grid = ctl->grid_basename[0] != '-'
9239 && (fmod(t, ctl->grid_dt_out) == 0 || final);
9240 const int output_budget = ctl->budget_basename[0] != '-'
9241 && (fmod(t, ctl->budget_dt_out) == 0 || final);
9242 const int output_depo = ctl->depo_basename[0] != '-'
9243 && (fmod(t, ctl->depo_dt_out) == 0 || final);
9244 const int output_ens = ctl->ens_basename[0] != '-'
9245 && (fmod(t, ctl->ens_dt_out) == 0 || final);
9246 const int output_vtk = ctl->vtk_basename[0] != '-'
9247 && (fmod(t, ctl->vtk_dt_out) == 0 || final);
9248
9249 /* Update host... */
9250 if (output_atm || output_grid || output_budget || output_ens || output_vtk
9251 || ctl->csi_basename[0] != '-' || ctl->prof_basename[0] != '-'
9252 || ctl->sample_basename[0] != '-' || ctl->stat_basename[0] != '-')
9253 mptrac_update_host(NULL, NULL, NULL, NULL, NULL, atm);
9254
9255 /* Write atmospheric data... */
9256 if (output_atm) {
9257 if (ctl->atm_type_out == 3) {
9258 /* CLaMS trajectory output creates its own files in the task directory. */
9259 mptrac_write_atm(dirname, ctl, atm, t);
9260 } else {
9261 if (ctl->atm_type_out == 0)
9262 sprintf(ext, "tab");
9263 else if (ctl->atm_type_out == 1)
9264 sprintf(ext, "bin");
9265 else if (ctl->atm_type_out >= 2)
9266 sprintf(ext, "nc");
9267 sprintf(filename, "%s/%s_%04d_%02d_%02d_%02d_%02d_%02d.%s",
9268 dirname, ctl->atm_basename, year, mon, day, hour, min, sec, ext);
9269 mptrac_write_atm(filename, ctl, atm, t);
9270 }
9271 }
9272
9273 /* Write gridded data... */
9274 if (output_grid) {
9275 sprintf(filename, "%s/%s_%04d_%02d_%02d_%02d_%02d_%02d.%s",
9276 dirname, ctl->grid_basename, year, mon, day, hour, min, sec,
9277 ctl->grid_type == 0 ? "tab" : "nc");
9278 write_grid(filename, ctl, met0, met1, atm, t);
9279 }
9280
9281 /* Write mass budget data... */
9282 if (output_budget) {
9283 sprintf(filename, "%s/%s.tab", dirname, ctl->budget_basename);
9284 write_budget(filename, ctl, atm, t);
9285 }
9286
9287 /* Write radioactive deposition data... */
9288 if (output_depo) {
9289#ifdef _OPENACC
9290#pragma acc update host(depo[:1])
9291#endif
9292 sprintf(filename, "%s/%s_%04d_%02d_%02d_%02d_%02d_%02d.%s",
9293 dirname, ctl->depo_basename, year, mon, day, hour, min, sec,
9294 ctl->depo_type == 0 ? "tab" : "nc");
9295 write_depo(filename, ctl, depo, t);
9296 }
9297
9298 /* Write CSI data... */
9299 if (ctl->csi_basename[0] != '-') {
9300 sprintf(filename, "%s/%s.tab", dirname, ctl->csi_basename);
9301 write_csi(filename, ctl, atm, t);
9302 }
9303
9304 /* Write ensemble data... */
9305 if (output_ens) {
9306 sprintf(filename, "%s/%s_%04d_%02d_%02d_%02d_%02d_%02d.tab",
9307 dirname, ctl->ens_basename, year, mon, day, hour, min, sec);
9308 write_ens(filename, ctl, atm, t);
9309 }
9310
9311 /* Write profile data... */
9312 if (ctl->prof_basename[0] != '-') {
9313 sprintf(filename, "%s/%s.tab", dirname, ctl->prof_basename);
9314 write_prof(filename, ctl, met0, met1, atm, t);
9315 }
9316
9317 /* Write sample data... */
9318 if (ctl->sample_basename[0] != '-') {
9319 sprintf(filename, "%s/%s.tab", dirname, ctl->sample_basename);
9320 write_sample(filename, ctl, met0, met1, atm, t);
9321 }
9322
9323 /* Write station data... */
9324 if (ctl->stat_basename[0] != '-') {
9325 sprintf(filename, "%s/%s.tab", dirname, ctl->stat_basename);
9326 write_station(filename, ctl, atm, t);
9327 }
9328
9329 /* Write VTK data... */
9330 if (output_vtk) {
9331 static int nvtk;
9332 if (t == ctl->t_start)
9333 nvtk = 0;
9334 sprintf(filename, "%s/%s_%05d.vtk", dirname, ctl->vtk_basename, ++nvtk);
9335 write_vtk(filename, ctl, atm, t);
9336 }
9337}
void write_depo(const char *filename, const ctl_t *ctl, const depo_t *depo, const double t)
Convert cumulative ground inventories to Bq m^-2 and write them.
Definition mptrac.c:15057
void mptrac_write_atm(const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
Writes air parcel data to a file in various formats.
Definition mptrac.c:9103
void write_ens(const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
Writes ensemble data to a file.
Definition mptrac.c:14952
void write_prof(const char *filename, const ctl_t *ctl, met_t *met0, met_t *met1, const atm_t *atm, const double t)
Writes profile data to a specified file.
Definition mptrac.c:16171
void mptrac_update_host(const ctl_t *ctl, const cache_t *cache, const clim_t *clim, met_t **met0, met_t **met1, const atm_t *atm)
Updates host memory for specified data structures.
Definition mptrac.c:9047
void write_station(const char *filename, const ctl_t *ctl, atm_t *atm, const double t)
Writes station data to a specified file.
Definition mptrac.c:16567
void write_budget(const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
Writes a time series of the atmospheric tracer mass budget.
Definition mptrac.c:14562
void write_vtk(const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
Writes VTK (Visualization Toolkit) data to a specified file.
Definition mptrac.c:16673
void write_sample(const char *filename, const ctl_t *ctl, met_t *met0, met_t *met1, const atm_t *atm, const double t)
Writes sample data to a specified file.
Definition mptrac.c:16396
void write_grid(const char *filename, const ctl_t *ctl, met_t *met0, met_t *met1, const atm_t *atm, const double t)
Writes grid data to a file in ASCII or netCDF format.
Definition mptrac.c:15234
void write_csi(const char *filename, const ctl_t *ctl, const atm_t *atm, const double t)
Writes Critical Success Index (CSI) data to a file.
Definition mptrac.c:14658
Here is the call graph for this function:

◆ mptrac_update_device()

void mptrac_update_device ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t ** met0,
met_t ** met1,
const atm_t * atm )

Updates device memory for specified data structures.

This function updates the GPU memory with the data from the provided host data structures (ctl, cache, clim, atm) using OpenACC directives. It ensures that the host data is transferred to the device for further computation.

Parameters
[in]ctlPointer to the ctl_t structure. If not NULL, the corresponding device memory for ctl is updated.
[in]cachePointer to the cache_t structure. If not NULL, the corresponding device memory for cache is updated.
[in]climPointer to the clim_t structure. If not NULL, the corresponding device memory for clim is updated.
[in]met0Pointer to the first met_t structure. If not NULL, the corresponding device memory for met0 is updated.
[in]met1Pointer to the second met_t structure. If not NULL, the corresponding device memory for met1 is updated.
[in]atmPointer to the atm_t structure. If not NULL, the corresponding device memory for atm is updated.
Note
The function assumes that OpenACC is enabled and uses the #pragma acc update directive for device memory synchronization. Each update operation is wrapped with a timer labeled as "UPDATE_DEVICE" for performance tracking.
Warning
Ensure that the pointers passed to this function are valid and properly initialized before calling this function. Passing invalid or uninitialized pointers may lead to undefined behavior.
Author
Lars Hoffmann

Definition at line 8991 of file mptrac.c.

8997 {
8998
8999 /* Update GPU... */
9000 if (ctl != NULL) {
9001#ifdef _OPENACC
9002 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
9003#pragma acc update device(ctl[:1])
9004#endif
9005 }
9006
9007 if (cache != NULL) {
9008#ifdef _OPENACC
9009 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
9010#pragma acc update device(cache[:1])
9011#endif
9012 }
9013
9014 if (clim != NULL) {
9015#ifdef _OPENACC
9016 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
9017#pragma acc update device(clim[:1])
9018#endif
9019 }
9020
9021 if (met0 != NULL) {
9022#ifdef _OPENACC
9023 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
9024 met_t *met0up = *met0;
9025#pragma acc update device(met0up[:1])
9026#endif
9027 }
9028
9029 if (met1 != NULL) {
9030#ifdef _OPENACC
9031 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
9032 met_t *met1up = *met1;
9033#pragma acc update device(met1up[:1])
9034#endif
9035 }
9036
9037 if (atm != NULL) {
9038#ifdef _OPENACC
9039 SELECT_TIMER("UPDATE_DEVICE", "MEMORY");
9040#pragma acc update device(atm[:1])
9041#endif
9042 }
9043}

◆ mptrac_update_host()

void mptrac_update_host ( const ctl_t * ctl,
const cache_t * cache,
const clim_t * clim,
met_t ** met0,
met_t ** met1,
const atm_t * atm )

Updates host memory for specified data structures.

This function transfers data from the device (GPU) memory back to the host memory for the provided data structures (ctl, cache, clim, atm) using OpenACC directives. It ensures that the latest data from the device is synchronized with the host.

Parameters
[in]ctlPointer to the ctl_t structure. If not NULL, the corresponding host memory for ctl is updated from the device.
[in]cachePointer to the cache_t structure. If not NULL, the corresponding host memory for cache is updated from the device.
[in]climPointer to the clim_t structure. If not NULL, the corresponding host memory for clim is updated from the device.
[in]met0Pointer to the first met_t structure. If not NULL, the corresponding host memory for met0 is updated.
[in]met1Pointer to the second met_t structure. If not NULL, the corresponding host memory for met1 is updated.
[in]atmPointer to the atm_t structure. If not NULL, the corresponding host memory for atm is updated from the device.
Note
The function assumes that OpenACC is enabled and uses the #pragma acc update directive for host memory synchronization. Each update operation is wrapped with a timer labeled as "UPDATE_HOST" for performance tracking.
Warning
Ensure that the pointers passed to this function are valid and properly initialized before calling this function
Author
Lars Hoffmann

Definition at line 9047 of file mptrac.c.

9053 {
9054
9055 /* Update GPU... */
9056 if (ctl != NULL) {
9057#ifdef _OPENACC
9058 SELECT_TIMER("UPDATE_HOST", "MEMORY");
9059#pragma acc update host(ctl[:1])
9060#endif
9061 }
9062
9063 if (cache != NULL) {
9064#ifdef _OPENACC
9065 SELECT_TIMER("UPDATE_HOST", "MEMORY");
9066#pragma acc update host(cache[:1])
9067#endif
9068 }
9069
9070 if (clim != NULL) {
9071#ifdef _OPENACC
9072 SELECT_TIMER("UPDATE_HOST", "MEMORY");
9073#pragma acc update host(clim[:1])
9074#endif
9075 }
9076
9077 if (met0 != NULL) {
9078#ifdef _OPENACC
9079 SELECT_TIMER("UPDATE_HOST", "MEMORY");
9080 met_t *met0up = *met0;
9081#pragma acc update host(met0up[:1])
9082#endif
9083 }
9084
9085 if (met1 != NULL) {
9086#ifdef _OPENACC
9087 SELECT_TIMER("UPDATE_HOST", "MEMORY");
9088 met_t *met1up = *met1;
9089#pragma acc update host(met1up[:1])
9090#endif
9091 }
9092
9093 if (atm != NULL) {
9094#ifdef _OPENACC
9095 SELECT_TIMER("UPDATE_HOST", "MEMORY");
9096#pragma acc update host(atm[:1])
9097#endif
9098 }
9099}

◆ nat_temperature()

double nat_temperature ( const double p,
const double h2o,
const double hno3 )

Calculates the nitric acid trihydrate (NAT) temperature.

This function computes the temperature at which nitric acid trihydrate (NAT) can form given the partial pressures of water vapor and nitric acid in the atmosphere.

Parameters
pThe total atmospheric pressure (in hPa).
h2oThe volume mixing ratio of water vapor (H2O).
hno3The volume mixing ratio of nitric acid (HNO3).
Returns
The NAT temperature (in Kelvin).

This function follows these steps:

  • Ensures the water vapor volume mixing ratio is above a minimum threshold.
  • Converts the volume mixing ratios of H2O and HNO3 to partial pressures.
  • Uses these partial pressures to compute coefficients for the quadratic equation that determines the NAT temperature.
  • Solves the quadratic equation to find the NAT temperature.

The calculations are based on empirical relationships involving logarithms of the partial pressures of H2O and HNO3.

Note
The constants and formulae used are specific to the context of atmospheric chemistry and the formation of NAT.
Author
Lars Hoffmann

Definition at line 9341 of file mptrac.c.

9344 {
9345
9346 /* Check water vapor volume mixing ratio... */
9347 const double h2o_help = MAX(h2o, 0.1e-6);
9348
9349 /* Calculate T_NAT... */
9350 const double p_hno3 = hno3 * p / 1.333224;
9351 const double p_h2o = h2o_help * p / 1.333224;
9352 const double a = 0.009179 - 0.00088 * log10(p_h2o);
9353 const double b = (38.9855 - log10(p_hno3) - 2.7836 * log10(p_h2o)) / a;
9354 const double c = -11397.0 / a;
9355 double tnat = (-b + sqrt(b * b - 4. * c)) / 2.;
9356 double x2 = (-b - sqrt(b * b - 4. * c)) / 2.;
9357 if (x2 > 0)
9358 tnat = x2;
9359
9360 return tnat;
9361}

◆ pbl_weight()

double pbl_weight ( const ctl_t * ctl,
const atm_t * atm,
const int ip,
const double pbl,
const double ps )

Computes a weighting factor based on planetary boundary layer pressure.

This function calculates a weighting factor that determines the contribution of a pressure level to processes within the planetary boundary layer. The factor is based on the relative position of the pressure within a linear transition range defined by pbl, ps, and TURB_PBL_TRANS, expressed as a fraction of the PBL pressure thickness (ps - pbl).

Parameters
ctlPointer to the control structure containing configuration parameters.
atmPointer to the atmospheric data structure containing pressure levels.
ipIndex of the pressure level in the atmospheric data array.
pblPressure at the planetary boundary layer.
psSurface pressure.
Returns
Weighting factor for the specified pressure level:
  • Returns 1.0 if the pressure is above the upper boundary (p0).
  • Returns 0.0 if the pressure is below the lower boundary (p1).
  • Returns a linearly interpolated value between 1.0 and 0.0 for pressures within the transition range.
Author
Lars Hoffmann

Definition at line 9365 of file mptrac.c.

9370 {
9371
9372 /* Get pressure range... */
9373 const double p1 = pbl - ctl->turb_pbl_trans * (ps - pbl);
9374 const double p0 = pbl;
9375
9376 /* Get weighting factor... */
9377 if (atm->p[ip] > p0)
9378 return 1;
9379 else if (atm->p[ip] < p1)
9380 return 0;
9381 else
9382 return LIN(p0, 1.0, p1, 0.0, atm->p[ip]);
9383}

◆ read_atm_asc()

int read_atm_asc ( const char * filename,
const ctl_t * ctl,
atm_t * atm )

Reads air parcel data from an ASCII file and populates the given atmospheric structure.

This function reads air parcel data from an ASCII file and stores the data in the provided atm_t structure. It reads each line of the file, extracts the necessary data fields, and converts the altitude to pressure.

Parameters
filenameThe name of the ASCII file containing the atmospheric data.
ctlA pointer to the control structure (ctl_t) that specifies the number of quantities.
atmA pointer to the atmospheric structure (atm_t) that will be populated with the data.
Returns
Returns 1 on success, and 0 on failure.

This function performs the following steps:

  • Attempts to open the specified file for reading.
  • Logs a warning and returns 0 if the file cannot be opened.
  • Reads each line of the file and extracts data values for time, altitude, longitude, latitude, and other specified quantities.
  • Converts the altitude to pressure.
  • Increments the data point counter.
  • Checks if the number of data points exceeds the maximum allowed (NP) and logs an error message if so.
  • Closes the file after reading all data.
  • Returns 1 to indicate successful data reading.

The function utilizes several macros and helper functions:

  • WARN for logging warnings.
  • ERRMSG for handling error messages.
  • TOK for tokenizing and reading values from the line.
  • P for converting altitude to pressure.
Author
Lars Hoffmann

Definition at line 9387 of file mptrac.c.

9390 {
9391
9392 /* Open file... */
9393 FILE *in;
9394 if (!(in = fopen(filename, "r"))) {
9395 WARN("Cannot open file!");
9396 return 0;
9397 }
9398
9399 /* Read line... */
9400 char line[LEN];
9401 while (fgets(line, LEN, in)) {
9402
9403 if (atm->np >= NP)
9404 ERRMSG("Too many data points!");
9405
9406 /* Read data... */
9407 char *tok;
9408 TOK(line, tok, "%lg", atm->time[atm->np]);
9409 TOK(NULL, tok, "%lg", atm->p[atm->np]);
9410 TOK(NULL, tok, "%lg", atm->lon[atm->np]);
9411 TOK(NULL, tok, "%lg", atm->lat[atm->np]);
9412 for (int iq = 0; iq < ctl->nq; iq++)
9413 TOK(NULL, tok, "%lg", atm->q[iq][atm->np]);
9414
9415 /* Convert altitude to pressure... */
9416 atm->p[atm->np] = P(atm->p[atm->np]);
9417
9418 /* Increment data point counter... */
9419 ++atm->np;
9420 }
9421
9422 /* Close file... */
9423 fclose(in);
9424
9425 /* Return success... */
9426 return 1;
9427}
#define TOK(line, tok, format, var)
Get string tokens.
Definition mptrac.h:2234

◆ read_atm_bin()

int read_atm_bin ( const char * filename,
const ctl_t * ctl,
atm_t * atm )

Reads air parcel data from a binary file and populates the given atmospheric structure.

This function reads air parcel data from a binary file and stores the data in the provided atm_t structure. It checks the version of the binary data, reads the data values, and verifies the integrity of the data read.

Parameters
filenameThe name of the binary file containing the atmospheric data.
ctlA pointer to the control structure (ctl_t) that specifies the number of quantities.
atmA pointer to the atmospheric structure (atm_t) that will be populated with the data.
Returns
Returns 1 on success, and 0 on failure.

This function performs the following steps:

  • Attempts to open the specified file for reading.
  • Returns 0 if the file cannot be opened.
  • Checks the version of the binary data and logs an error message if the version is incorrect.
  • Reads the number of data points (np).
  • Reads the data arrays for time, pressure, longitude, latitude, and other specified quantities.
  • Checks a final flag to ensure the data was read correctly.
  • Logs an error message if the final flag is incorrect.
  • Closes the file after reading all data.
  • Returns 1 to indicate successful data reading.

The function utilizes several macros and helper functions:

  • ERRMSG for handling error messages.
  • FREAD for reading data from the binary file.
Author
Lars Hoffmann

Definition at line 9431 of file mptrac.c.

9434 {
9435
9436 /* Open file... */
9437 FILE *in;
9438 if (!(in = fopen(filename, "r")))
9439 return 0;
9440
9441 /* Check version of binary data... */
9442 int version;
9443 FREAD(&version, int,
9444 1,
9445 in);
9446 if (version != 100)
9447 ERRMSG("Wrong version of binary data!");
9448
9449 /* Read data... */
9450 FREAD(&atm->np, int,
9451 1,
9452 in);
9453 if (atm->np < 1 || atm->np > NP)
9454 ERRMSG("Number of particles in binary data is out of range!");
9455 FREAD(atm->time, double,
9456 (size_t) atm->np,
9457 in);
9458 FREAD(atm->p, double,
9459 (size_t) atm->np,
9460 in);
9461 FREAD(atm->lon, double,
9462 (size_t) atm->np,
9463 in);
9464 FREAD(atm->lat, double,
9465 (size_t) atm->np,
9466 in);
9467 for (int iq = 0; iq < ctl->nq; iq++)
9468 FREAD(atm->q[iq], double,
9469 (size_t) atm->np,
9470 in);
9471
9472 /* Read final flag... */
9473 int final;
9474 FREAD(&final, int,
9475 1,
9476 in);
9477 if (final != 999)
9478 ERRMSG("Error while reading binary data!");
9479
9480 /* Close file... */
9481 fclose(in);
9482
9483 /* Return success... */
9484 return 1;
9485}

◆ read_atm_clams()

int read_atm_clams ( const char * filename,
const ctl_t * ctl,
atm_t * atm )

Reads atmospheric data from a CLAMS NetCDF file.

This function opens a NetCDF file, reads various atmospheric parameters, and stores them in the provided atm_t structure. It handles both zeta and pressure coordinate systems depending on the control settings.

Parameters
[in]filenamePath to the NetCDF file containing atmospheric data.
[in]ctlPointer to the control structure containing configuration settings.
[out]atmPointer to the atmospheric data structure where the data will be stored.
Returns
Returns 1 on success, 0 on failure.
  • Opens the NetCDF file in read-only mode.
  • Retrieves the number of particles (NPARTS).
  • Reads initial time (TIME_INIT) or falls back to time if unavailable.
  • Depending on ctl->advect_vert_coord, reads ZETA and optionally PRESS, or reads PRESS_INIT with fallback to PRESS.
  • Reads longitude (LON) and latitude (LAT).
  • Closes the NetCDF file before returning.
Author
Jan Clemens

Definition at line 9489 of file mptrac.c.

9492 {
9493
9494 if (ctl->met_coord_type != 0)
9495 ERRMSG("CLaMS atmospheric files support only lat/lon grids");
9496
9497 int ncid, varid;
9498
9499 /* Open file... */
9500 if (nc_open(filename, NC_NOWRITE, &ncid) != NC_NOERR)
9501 return 0;
9502
9503 /* Get dimensions... */
9504 NC_INQ_DIM("NPARTS", &atm->np, 1, NP, 1);
9505
9506 /* Get time... */
9507 if (nc_inq_varid(ncid, "TIME_INIT", &varid) == NC_NOERR) {
9508 NC(nc_get_var_double(ncid, varid, atm->time));
9509 } else {
9510 WARN("TIME_INIT not found use time instead!");
9511 double time_init;
9512 NC_GET_DOUBLE("time", &time_init, 1);
9513 for (int ip = 0; ip < atm->np; ip++) {
9514 atm->time[ip] = time_init;
9515 }
9516 }
9517
9518 /* Read zeta coordinate, pressure is optional... */
9519 if (ctl->advect_vert_coord == 1) {
9520 NC_GET_DOUBLE("ZETA", atm->q[ctl->qnt_zeta], 1);
9521 NC_GET_DOUBLE("PRESS", atm->p, 0);
9522 }
9523
9524 /* Read pressure, zeta coordinate is optional... */
9525 else {
9526 if (nc_inq_varid(ncid, "PRESS_INIT", &varid) == NC_NOERR) {
9527 NC(nc_get_var_double(ncid, varid, atm->p));
9528 } else {
9529 WARN("PRESS_INIT not found use PRESS instead!");
9530 nc_inq_varid(ncid, "PRESS", &varid);
9531 NC(nc_get_var_double(ncid, varid, atm->p));
9532 }
9533 }
9534
9535 /* Read further quantities if requested... */
9536 for (int iq = 0; iq < ctl->nq; iq++)
9537 NC_GET_DOUBLE(ctl->qnt_name[iq], atm->q[iq], 0);
9538
9539 /* Read longitude and latitude... */
9540 NC_GET_DOUBLE("LON", atm->lon, 1);
9541 NC_GET_DOUBLE("LAT", atm->lat, 1);
9542
9543 /* Close file... */
9544 NC(nc_close(ncid));
9545
9546 /* Return success... */
9547 return 1;
9548}
#define NC(cmd)
Execute a NetCDF command and check for errors.
Definition mptrac.h:1555

◆ read_atm_nc()

int read_atm_nc ( const char * filename,
const ctl_t * ctl,
atm_t * atm )

Reads air parcel data from a generic netCDF file and populates the given atmospheric structure.

This function reads air parcel data from a netCDF file and stores the data in the provided atm_t structure. It retrieves the dimensions, geolocations (time, pressure, longitude, latitude), and specified variables from the file.

Parameters
filenameThe name of the netCDF file containing the atmospheric data.
ctlA pointer to the control structure (ctl_t) that specifies the number of quantities and their names.
atmA pointer to the atmospheric structure (atm_t) that will be populated with the data.
Returns
Returns 1 on success, and 0 on failure.

This function performs the following steps:

  • Attempts to open the specified netCDF file for reading.
  • Returns 0 if the file cannot be opened.
  • Retrieves the number of observations (np) from the "obs" dimension.
  • Reads the geolocation data arrays for time, pressure, longitude, and latitude.
  • Reads the specified variables into the corresponding arrays in the atm_t structure.
  • Closes the netCDF file after reading all data.
  • Returns 1 to indicate successful data reading.

The function utilizes several macros and helper functions:

  • NC_INQ_DIM for inquiring about dimensions in the netCDF file.
  • NC_GET_DOUBLE for reading double values from the netCDF file.
  • NC for checking netCDF function return values.
Author
Lars Hoffmann

Definition at line 9552 of file mptrac.c.

9555 {
9556
9557 int ncid, varid;
9558
9559 /* Open file... */
9560 if (nc_open(filename, NC_NOWRITE, &ncid) != NC_NOERR)
9561 return 0;
9562
9563 /* Get dimensions... */
9564 NC_INQ_DIM("obs", &atm->np, 1, NP, 1);
9565
9566 /* Read geolocations... */
9567 NC_GET_DOUBLE("time", atm->time, 1);
9568 NC_GET_DOUBLE("press", atm->p, 1);
9569 NC_GET_DOUBLE("lon", atm->lon, 1);
9570 NC_GET_DOUBLE("lat", atm->lat, 1);
9571
9572 /* Read variables... */
9573 for (int iq = 0; iq < ctl->nq; iq++)
9574 NC_GET_DOUBLE(ctl->qnt_name[iq], atm->q[iq], 0);
9575
9576 /* Close file... */
9577 NC(nc_close(ncid));
9578
9579 /* Return success... */
9580 return 1;
9581}

◆ read_clim_photo()

void read_clim_photo ( const char * filename,
clim_photo_t * photo )

Reads photolysis rates from a NetCDF file and populates the given photolysis structure.

This function opens a NetCDF file specified by the filename, reads various dimensions and data related to photolysis rates, and stores this data in the provided clim_photo_t structure. It includes checks for data consistency and logs detailed information about the loaded data.

Parameters
filenameA string containing the path to the NetCDF file containing photolysis rate data.
photoA pointer to the photolysis structure (clim_photo_t) that will be populated with the data.

The function performs the following steps:

  • Logs the initiation of reading photolysis rates.
  • Opens the NetCDF file in read-only mode.
  • Reads pressure data and checks for descending order.
  • Reads total column ozone data and checks for ascending order.
  • Reads solar zenith angle data and checks for ascending order.
  • Allocates memory for temporary arrays to hold the data.
  • Reads various photolysis rates (e.g., J_N2O, J_CCl4, J_CFC-11, J_CFC-12, J_O2, J_O3b, J_O3a, J_H2O2, J_H2O) and stores them in the clim_photo_t structure.
  • Frees the allocated memory for temporary arrays.
  • Closes the NetCDF file.
  • Logs detailed information about the loaded data, including pressure levels, solar zenith angles, and photolysis rates.
Author
Mingzhao Liu

Definition at line 9585 of file mptrac.c.

9587 {
9588
9589 int ncid, varid;
9590
9591 /* Write info... */
9592 LOG(1, "Read photolysis rates: %s", filename);
9593
9594 /* Open netCDF file... */
9595 if (nc_open(filename, NC_NOWRITE, &ncid) != NC_NOERR) {
9596 WARN("Photolysis rate data are missing!");
9597 return;
9598 }
9599
9600 /* Read pressure data... */
9601 NC_INQ_DIM("press", &photo->np, 2, CP, 1);
9602 NC_GET_DOUBLE("press", photo->p, 1);
9603 if (photo->p[0] < photo->p[1])
9604 ERRMSG("Pressure data are not descending!");
9605
9606 /* Read total column ozone data... */
9607 NC_INQ_DIM("total_o3col", &photo->no3c, 2, CO3, 1);
9608 NC_GET_DOUBLE("total_o3col", photo->o3c, 1);
9609 if (photo->o3c[0] > photo->o3c[1])
9610 ERRMSG("Total column ozone data are not ascending!");
9611
9612 /* Read solar zenith angle data... */
9613 NC_INQ_DIM("sza", &photo->nsza, 2, CSZA, 1);
9614 NC_GET_DOUBLE("sza", photo->sza, 1);
9615 if (photo->sza[0] > photo->sza[1])
9616 ERRMSG("Solar zenith angle data are not ascending!");
9617
9618 /* Read data... */
9619 read_clim_photo_help(ncid, "J_N2O", photo, photo->n2o);
9620 read_clim_photo_help(ncid, "J_CCl4", photo, photo->ccl4);
9621 read_clim_photo_help(ncid, "J_CFC-11", photo, photo->ccl3f);
9622 read_clim_photo_help(ncid, "J_CFC-12", photo, photo->ccl2f2);
9623 read_clim_photo_help(ncid, "J_O2", photo, photo->o2);
9624 read_clim_photo_help(ncid, "J_O3b", photo, photo->o3_1);
9625 read_clim_photo_help(ncid, "J_O3a", photo, photo->o3_2);
9626 read_clim_photo_help(ncid, "J_H2O2", photo, photo->h2o2);
9627 read_clim_photo_help(ncid, "J_H2O", photo, photo->h2o);
9628
9629 /* Close netCDF file... */
9630 NC(nc_close(ncid));
9631
9632 /* Write info... */
9633 LOG(2, "Number of pressure levels: %d", photo->np);
9634 LOG(2, "Altitude levels: %g, %g ... %g km",
9635 Z(photo->p[0]), Z(photo->p[1]), Z(photo->p[photo->np - 1]));
9636 LOG(2, "Pressure levels: %g, %g ... %g hPa",
9637 photo->p[0], photo->p[1], photo->p[photo->np - 1]);
9638 LOG(2, "Number of solar zenith angles: %d", photo->nsza);
9639 LOG(2, "Solar zenith angles: %g, %g ... %g deg",
9640 RAD2DEG(photo->sza[0]), RAD2DEG(photo->sza[1]),
9641 RAD2DEG(photo->sza[photo->nsza - 1]));
9642 LOG(2, "Number of total column ozone values: %d", photo->no3c);
9643 LOG(2, "Total column ozone: %g, %g ... %g DU",
9644 photo->o3c[0], photo->o3c[1], photo->o3c[photo->no3c - 1]);
9645 LOG(2, "N2O photolysis rate: %g, %g ... %g s**-1",
9646 photo->n2o[0][0][0], photo->n2o[1][0][0],
9647 photo->n2o[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9648 LOG(2, "CCl4 photolysis rate: %g, %g ... %g s**-1",
9649 photo->ccl4[0][0][0], photo->ccl4[1][0][0],
9650 photo->ccl4[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9651 LOG(2, "CFC-11 photolysis rate: %g, %g ... %g s**-1",
9652 photo->ccl3f[0][0][0], photo->ccl3f[1][0][0],
9653 photo->ccl3f[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9654 LOG(2, "CFC-12 photolysis rate: %g, %g ... %g s**-1",
9655 photo->ccl2f2[0][0][0], photo->ccl2f2[1][0][0],
9656 photo->ccl2f2[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9657 LOG(2, "O2 photolysis rate: %g, %g ... %g s**-1",
9658 photo->o2[0][0][0], photo->o2[1][0][0],
9659 photo->o2[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9660 LOG(2, "O3 -> O(1D) photolysis rate: %g, %g ... %g s**-1",
9661 photo->o3_1[0][0][0], photo->o3_1[1][0][0],
9662 photo->o3_1[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9663 LOG(2, "O3 -> O(3P) photolysis rate: %g, %g ... %g s**-1",
9664 photo->o3_2[0][0][0], photo->o3_2[1][0][0],
9665 photo->o3_2[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9666 LOG(2, "H2O2 photolysis rate: %g, %g ... %g s**-1",
9667 photo->h2o2[0][0][0], photo->h2o2[1][0][0],
9668 photo->h2o2[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9669 LOG(2, "H2O photolysis rate: %g, %g ... %g s**-1",
9670 photo->h2o[0][0][0], photo->h2o[1][0][0],
9671 photo->h2o[photo->np - 1][photo->nsza - 1][photo->no3c - 1]);
9672}
void read_clim_photo_help(const int ncid, const char *varname, const clim_photo_t *photo, double var[CP][CSZA][CO3])
Reads a 3D climatological photochemistry variable from a NetCDF file.
Definition mptrac.c:9676
#define CP
Maximum number of pressure levels for climatological data.
Definition mptrac.h:609
#define CO3
Maximum number of total column ozone data for climatological data.
Definition mptrac.h:604
#define CSZA
Maximum number of solar zenith angles for climatological data.
Definition mptrac.h:614
double o3_1[CP][CSZA][CO3]
O3 photolysis rate (O3 + hv = O1d + O2) [1/s].
Definition mptrac.h:3821
double o2[CP][CSZA][CO3]
O2 photolysis rate [1/s].
Definition mptrac.h:3818
double h2o2[CP][CSZA][CO3]
H2O2 photolysis rate [1/s].
Definition mptrac.h:3827
double h2o[CP][CSZA][CO3]
H2O photolysis rate [1/s].
Definition mptrac.h:3830
double o3_2[CP][CSZA][CO3]
O3 photolysis rate (O3 + hv = O3p + O2) [1/s].
Definition mptrac.h:3824
Here is the call graph for this function:

◆ read_clim_photo_help()

void read_clim_photo_help ( const int ncid,
const char * varname,
const clim_photo_t * photo,
double var[CP][CSZA][CO3] )

Reads a 3D climatological photochemistry variable from a NetCDF file.

This function reads a variable from a NetCDF file into a 3D array based on the dimensions provided by the clim_photo_t structure.

Parameters
[in]ncidNetCDF file ID.
[in]varnameName of the variable to read from the NetCDF file.
[in]photoPointer to a structure defining the data dimensions (np, nsza, no3c).
[out]var3D array to store the read data, with dimensions [CP][CSZA][CO3].
Note
Allocates temporary memory for reading and copies data into the provided array. The memory is freed after the data is copied.
Author
Lars Hoffmann

Definition at line 9676 of file mptrac.c.

9680 {
9681
9682 /* Allocate... */
9683 double *help;
9684 ALLOC(help, double,
9685 photo->np * photo->nsza * photo->no3c);
9686
9687 /* Read variable... */
9688 int varid;
9689 NC_GET_DOUBLE(varname, help, 1);
9690
9691 /* Copy data... */
9692 for (int ip = 0; ip < photo->np; ip++)
9693 for (int is = 0; is < photo->nsza; is++)
9694 for (int io = 0; io < photo->no3c; io++)
9695 var[ip][is][io] =
9696 help[ARRAY_3D(ip, is, photo->nsza, io, photo->no3c)];
9697
9698 /* Free... */
9699 free(help);
9700}

◆ read_clim_ts()

int read_clim_ts ( const char * filename,
clim_ts_t * ts )

Reads a climatological time series from a file and populates the given time series structure.

This function reads time and volume mixing ratio (VMR) data from a specified file, processes the data, and stores it in the provided clim_ts_t structure. It also includes checks for data consistency and logs detailed information about the loaded data.

Parameters
filenameA string containing the path to the file containing the climatological time series data.
tsA pointer to the time series structure (clim_ts_t) that will be populated with the data.
Returns
Returns 1 on success, and 0 on failure (e.g., if the file cannot be opened or data is invalid).

The function performs the following steps:

  • Logs the initiation of reading the climatological time series.
  • Opens the file for reading.
  • Reads time and VMR data from the file, converting years to seconds.
  • Checks for ascending order of time data and ensures the number of data points does not exceed the limit.
  • Closes the file after reading.
  • Checks if there are enough data points.
  • Logs detailed information about the loaded data, including the number of time steps and the range of VMR values.
Author
Lars Hoffmann

Definition at line 9704 of file mptrac.c.

9706 {
9707
9708 /* Write info... */
9709 LOG(1, "Read climatological time series: %s", filename);
9710
9711 /* Open file... */
9712 FILE *in;
9713 if (!(in = fopen(filename, "r"))) {
9714 WARN("Cannot open file!");
9715 return 0;
9716 }
9717
9718 /* Read data... */
9719 char line[LEN];
9720 int nh = 0;
9721 while (fgets(line, LEN, in))
9722 if (sscanf(line, "%lg %lg", &ts->time[nh], &ts->vmr[nh]) == 2) {
9723
9724 /* Convert years to seconds... */
9725 ts->time[nh] = (ts->time[nh] - 2000.0) * 365.25 * 86400.;
9726
9727 /* Check data... */
9728 if (nh > 0 && ts->time[nh] <= ts->time[nh - 1])
9729 ERRMSG("Time series must be ascending!");
9730
9731 /* Count time steps... */
9732 if ((++nh) >= CTS)
9733 ERRMSG("Too many data points!");
9734 }
9735
9736 /* Close file... */
9737 fclose(in);
9738
9739 /* Check number of data points... */
9740 ts->ntime = nh;
9741 if (nh < 2)
9742 ERRMSG("Not enough data points!");
9743
9744 /* Write info... */
9745 LOG(2, "Number of time steps: %d", ts->ntime);
9746 LOG(2, "Time steps: %.2f, %.2f ... %.2f s", ts->time[0], ts->time[1],
9747 ts->time[nh - 1]);
9748 LOG(2, "Volume mixing ratio range: %g ... %g ppv",
9749 gsl_stats_min(ts->vmr, 1, (size_t) nh), gsl_stats_max(ts->vmr, 1,
9750 (size_t) nh));
9751
9752 /* Exit success... */
9753 return 1;
9754}
#define CTS
Maximum number of data points of climatological time series.
Definition mptrac.h:624

◆ read_clim_zm()

void read_clim_zm ( const char * filename,
const char * varname,
clim_zm_t * zm )

Reads zonally averaged climatological data from a netCDF file and populates the given structure.

This function reads data from a specified netCDF file, including pressure levels, latitudes, and volume mixing ratios (VMR) for a specified variable. It performs necessary checks and logs detailed information about the loaded data.

Parameters
filenameA string containing the path to the netCDF file.
varnameA string containing the name of the variable to be read from the netCDF file.
zmA pointer to the structure (clim_zm_t) that will be populated with the data.

The function performs the following steps:

  • Logs the initiation of reading the specified data.
  • Opens the netCDF file for reading.
  • Reads pressure level data and checks for descending order.
  • Reads latitude data and checks for ascending order.
  • Sets the time data for monthly means.
  • Checks the number of time steps.
  • Reads the specified variable data from the file.
  • Fixes any gaps in the data by interpolating from valid values.
  • Logs detailed information about the loaded data, including the number of time steps, pressure levels, latitude values, and the range of the variable's volume mixing ratios.
Author
Lars Hoffmann

Definition at line 9758 of file mptrac.c.

9761 {
9762
9763 int ncid, varid, it, iy, iz, iz2, nt;
9764
9765 double *help, varmin = 1e99, varmax = -1e99;
9766
9767 /* Write info... */
9768 LOG(1, "Read %s data: %s", varname, filename);
9769
9770 /* Open netCDF file... */
9771 if (nc_open(filename, NC_NOWRITE, &ncid) != NC_NOERR) {
9772 WARN("%s climatology data are missing!", varname);
9773 return;
9774 }
9775
9776 /* Read pressure data... */
9777 NC_INQ_DIM("press", &zm->np, 2, CP, 1);
9778 NC_GET_DOUBLE("press", zm->p, 1);
9779 if (zm->p[0] < zm->p[1])
9780 ERRMSG("Pressure data are not descending!");
9781
9782 /* Read latitudes... */
9783 NC_INQ_DIM("lat", &zm->nlat, 2, CY, 1);
9784 NC_GET_DOUBLE("lat", zm->lat, 1);
9785 if (zm->lat[0] > zm->lat[1])
9786 ERRMSG("Latitude data are not ascending!");
9787
9788 /* Set time data (for monthly means)... */
9789 zm->ntime = 12;
9790 zm->time[0] = 1209600.00;
9791 zm->time[1] = 3888000.00;
9792 zm->time[2] = 6393600.00;
9793 zm->time[3] = 9072000.00;
9794 zm->time[4] = 11664000.00;
9795 zm->time[5] = 14342400.00;
9796 zm->time[6] = 16934400.00;
9797 zm->time[7] = 19612800.00;
9798 zm->time[8] = 22291200.00;
9799 zm->time[9] = 24883200.00;
9800 zm->time[10] = 27561600.00;
9801 zm->time[11] = 30153600.00;
9802
9803 /* Check number of timesteps... */
9804 NC_INQ_DIM("time", &nt, 12, 12, 1);
9805
9806 /* Read data... */
9807 ALLOC(help, double,
9808 zm->nlat * zm->np * zm->ntime);
9809 NC_GET_DOUBLE(varname, help, 1);
9810 for (it = 0; it < zm->ntime; it++)
9811 for (iz = 0; iz < zm->np; iz++)
9812 for (iy = 0; iy < zm->nlat; iy++)
9813 zm->vmr[it][iz][iy] = help[ARRAY_3D(it, iz, zm->np, iy, zm->nlat)];
9814 free(help);
9815
9816 /* Fix data gaps... */
9817 for (it = 0; it < zm->ntime; it++)
9818 for (iy = 0; iy < zm->nlat; iy++)
9819 for (iz = 0; iz < zm->np; iz++) {
9820 if (zm->vmr[it][iz][iy] < 0) {
9821 for (iz2 = 0; iz2 < zm->np; iz2++)
9822 if (zm->vmr[it][iz2][iy] >= 0) {
9823 zm->vmr[it][iz][iy] = zm->vmr[it][iz2][iy];
9824 break;
9825 }
9826 for (iz2 = zm->np - 1; iz2 >= 0; iz2--)
9827 if (zm->vmr[it][iz2][iy] >= 0) {
9828 zm->vmr[it][iz][iy] = zm->vmr[it][iz2][iy];
9829 break;
9830 }
9831 }
9832 varmin = MIN(varmin, zm->vmr[it][iz][iy]);
9833 varmax = MAX(varmax, zm->vmr[it][iz][iy]);
9834 }
9835
9836 /* Close netCDF file... */
9837 NC(nc_close(ncid));
9838
9839 /* Write info... */
9840 LOG(2, "Number of time steps: %d", zm->ntime);
9841 LOG(2, "Time steps: %.2f, %.2f ... %.2f s",
9842 zm->time[0], zm->time[1], zm->time[zm->ntime - 1]);
9843 LOG(2, "Number of pressure levels: %d", zm->np);
9844 LOG(2, "Altitude levels: %g, %g ... %g km",
9845 Z(zm->p[0]), Z(zm->p[1]), Z(zm->p[zm->np - 1]));
9846 LOG(2, "Pressure levels: %g, %g ... %g hPa", zm->p[0],
9847 zm->p[1], zm->p[zm->np - 1]);
9848 LOG(2, "Number of latitudes: %d", zm->nlat);
9849 LOG(2, "Latitudes: %g, %g ... %g deg",
9850 zm->lat[0], zm->lat[1], zm->lat[zm->nlat - 1]);
9851 LOG(2, "%s volume mixing ratio range: %g ... %g ppv", varname, varmin,
9852 varmax);
9853}
#define CY
Maximum number of latitudes for climatological data.
Definition mptrac.h:599

◆ read_kernel()

void read_kernel ( const char * filename,
double kz[EP],
double kw[EP],
int * nk )

Reads kernel function data from a file and populates the provided arrays.

This function reads kernel function data from a specified file, populating the provided arrays kz and kw with the parsed data. It also updates the variable pointed to by nk with the number of data points read. Heights must be finite and strictly increasing. Weights must be finite and nonnegative, with at least one positive weight.

Parameters
filenameA string containing the path to the file containing kernel function data.
kzA double array to store the height levels of the kernel function.
kwA double array to store the weights corresponding to the height levels.
nkA pointer to an integer variable representing the number of data points read.

The function performs the following steps:

  • Logs information indicating the kernel function file being read.
  • Attempts to open the specified file for reading.
  • Reads data from the file line by line, parsing height levels and weights.
  • Checks that the height levels are in ascending order and that the number of data points does not exceed the defined maximum.
  • Closes the file after reading.
  • Updates the value of nk with the number of data points read.
  • Normalizes the kernel function weights by dividing each weight by the maximum weight.
Author
Lars Hoffmann

Definition at line 9857 of file mptrac.c.

9861 {
9862
9863 /* Write info... */
9864 LOG(1, "Read kernel function: %s", filename);
9865
9866 /* Open file... */
9867 FILE *in;
9868 if (!(in = fopen(filename, "r")))
9869 ERRMSG("Cannot open file!");
9870
9871 /* Read data... */
9872 char line[LEN];
9873 int n = 0;
9874 while (fgets(line, LEN, in))
9875 if (sscanf(line, "%lg %lg", &kz[n], &kw[n]) == 2) {
9876 if (!isfinite(kz[n]) || !isfinite(kw[n]))
9877 ERRMSG("Kernel heights and weights must be finite!");
9878 if (kw[n] < 0)
9879 ERRMSG("Kernel weights must be nonnegative!");
9880 if (n > 0 && kz[n] <= kz[n - 1])
9881 ERRMSG("Kernel heights must be strictly increasing!");
9882 if ((++n) >= EP)
9883 ERRMSG("Too many height levels!");
9884 }
9885
9886 /* Close file... */
9887 fclose(in);
9888
9889 /* Check number of data points... */
9890 *nk = n;
9891 if (n < 2)
9892 ERRMSG("Not enough height levels!");
9893
9894 /* Preserve relative weights by scaling the maximum to one... */
9895 const double kmax = gsl_stats_max(kw, 1, (size_t) n);
9896 if (kmax <= 0)
9897 ERRMSG("Kernel requires at least one positive weight!");
9898 for (int iz = 0; iz < n; iz++)
9899 kw[iz] /= kmax;
9900}

◆ read_met_bin()

int read_met_bin ( const char * filename,
const ctl_t * ctl,
met_t * met )

Reads meteorological data from a binary file.

This function reads meteorological data from a binary file and populates the provided met_t structure with the data. It checks the binary file's format version and met_type, ensuring compatibility with the control structure (ctl_t). The function reads time, grid, surface data, and multi-level data, and supports different binary file versions.

Parameters
filenameA constant character pointer representing the name of the binary file to read the meteorological data from.
ctlA pointer to a ctl_t structure that holds control parameters such as the expected met_type and other configuration options.
metA pointer to a met_t structure that will store the meteorological data read from the binary file.
Note
  • The function logs the progress and details of the read operation, such as time, number of longitudes, latitudes, levels, and various meteorological variables.
  • It uses the FREAD macro for safe binary reading operations, which checks the integrity of the read operation.
  • The function reads and verifies the met_type and binary file version to ensure compatibility.
  • Supported binary file versions include 100, 101, and 102, each of which may include additional variables (e.g., LSM, SST, RWC, SWC, and CC).
Warning
  • The function will raise an error if the met_type in the file does not match the ctl->met_type.
  • It will raise an error if the binary file version is not supported.
  • If the dimensions of the data (e.g., number of longitudes, latitudes, or levels) are outside the expected range, an error will be raised.
Author
Lars Hoffmann

Definition at line 9904 of file mptrac.c.

9907 {
9908
9909 FILE *in;
9910
9911 double r;
9912
9913 int year, mon, day, hour, min, sec;
9914
9915 /* Set timer... */
9916 SELECT_TIMER("READ_MET_BIN", "INPUT");
9917
9918 /* Open file... */
9919 if (!(in = fopen(filename, "r"))) {
9920 WARN("Cannot open file!");
9921 return 0;
9922 }
9923
9924 /* Check type of binary data... */
9925 int met_type;
9926 FREAD(&met_type, int,
9927 1,
9928 in);
9929 if (met_type != ctl->met_type)
9930 ERRMSG("Wrong MET_TYPE of binary data!");
9931
9932 /* Check version of binary data... */
9933 int version;
9934 FREAD(&version, int,
9935 1,
9936 in);
9937 if (version != 104)
9938 ERRMSG("Wrong version of binary data!");
9939
9940 /* Read time... */
9941 FREAD(&met->time, double,
9942 1,
9943 in);
9944 jsec2time(met->time, &year, &mon, &day, &hour, &min, &sec, &r);
9945 LOG(2, "Time: %.2f (%d-%02d-%02d, %02d:%02d UTC)",
9946 met->time, year, mon, day, hour, min);
9947 if (year < 1900 || year > 2100 || mon < 1 || mon > 12
9948 || day < 1 || day > 31 || hour < 0 || hour > 23)
9949 ERRMSG("Error while reading time!");
9950
9951 /* Read dimensions... */
9952 met->coord_type = ctl->met_coord_type;
9953
9954 FREAD(&met->nx, int,
9955 1,
9956 in);
9957 LOG(2, "Number of %s: %d",
9958 (met->coord_type == 0) ? "longitudes" : "x coordinates", met->nx);
9959 if (met->nx < 2 || met->nx > EX)
9960 ERRMSG(met->coord_type == 0
9961 ? "Number of longitudes out of range!"
9962 : "Number of x coordinates out of range!");
9963
9964 FREAD(&met->ny, int,
9965 1,
9966 in);
9967 LOG(2, "Number of %s: %d",
9968 (met->coord_type == 0) ? "latitudes" : "y coordinates", met->ny);
9969 if (met->ny < 2 || met->ny > EY)
9970 ERRMSG(met->coord_type == 0
9971 ? "Number of latitudes out of range!"
9972 : "Number of y coordinates out of range!");
9973
9974 FREAD(&met->np, int,
9975 1,
9976 in);
9977 LOG(2, "Number of levels: %d", met->np);
9978 if (met->np < 2 || met->np > EP)
9979 ERRMSG("Number of levels out of range!");
9980
9981 /* Read grid... */
9982 FREAD(met->lon, double,
9983 (size_t) met->nx,
9984 in);
9985 LOG(2, "%s: %g, %g ... %g %s",
9986 met->coord_type == 0 ? "Longitudes" : "X coordinates",
9987 met->lon[0], met->lon[1], met->lon[met->nx - 1],
9988 met->coord_type == 0 ? "deg" : "m");
9989
9990 FREAD(met->lat, double,
9991 (size_t) met->ny,
9992 in);
9993 LOG(2, "%s: %g, %g ... %g %s",
9994 met->coord_type == 0 ? "Latitudes" : "Y coordinates",
9995 met->lat[0], met->lat[1], met->lat[met->ny - 1],
9996 met->coord_type == 0 ? "deg" : "m");
9997
9998 FREAD(met->p, double,
9999 (size_t) met->np,
10000 in);
10001 LOG(2, "Altitude levels: %g, %g ... %g km",
10002 Z(met->p[0]), Z(met->p[1]), Z(met->p[met->np - 1]));
10003 LOG(2, "Pressure levels: %g, %g ... %g hPa",
10004 met->p[0], met->p[1], met->p[met->np - 1]);
10005
10006 /* Read surface data... */
10007 read_met_bin_2d(in, met, met->ps, "PS");
10008 read_met_bin_2d(in, met, met->ts, "TS");
10009 read_met_bin_2d(in, met, met->zs, "ZS");
10010 read_met_bin_2d(in, met, met->us, "US");
10011 read_met_bin_2d(in, met, met->vs, "VS");
10012 read_met_bin_2d(in, met, met->ess, "ESS");
10013 read_met_bin_2d(in, met, met->nss, "NSS");
10014 read_met_bin_2d(in, met, met->shf, "SHF");
10015 read_met_bin_2d(in, met, met->lsm, "LSM");
10016 read_met_bin_2d(in, met, met->sst, "SST");
10017 read_met_bin_2d(in, met, met->pbl, "PBL");
10018 read_met_bin_2d(in, met, met->pt, "PT");
10019 read_met_bin_2d(in, met, met->tt, "TT");
10020 read_met_bin_2d(in, met, met->zt, "ZT");
10021 read_met_bin_2d(in, met, met->h2ot, "H2OT");
10022 read_met_bin_2d(in, met, met->pct, "PCT");
10023 read_met_bin_2d(in, met, met->pcb, "PCB");
10024 read_met_bin_2d(in, met, met->cl, "CL");
10025 read_met_bin_2d(in, met, met->plcl, "PLCL");
10026 read_met_bin_2d(in, met, met->plfc, "PLFC");
10027 read_met_bin_2d(in, met, met->pel, "PEL");
10028 read_met_bin_2d(in, met, met->cape, "CAPE");
10029 read_met_bin_2d(in, met, met->cin, "CIN");
10030 read_met_bin_2d(in, met, met->o3c, "O3C");
10031
10032 /* Read level data... */
10033 read_met_bin_3d(in, ctl, met, met->z, "Z", -1e34f, 1e34f);
10034 read_met_bin_3d(in, ctl, met, met->t, "T", 0, 1e34f);
10035 read_met_bin_3d(in, ctl, met, met->u, "U", -1e34f, 1e34f);
10036 read_met_bin_3d(in, ctl, met, met->v, "V", -1e34f, 1e34f);
10037 read_met_bin_3d(in, ctl, met, met->w, "W", -1e34f, 1e34f);
10038 read_met_bin_3d(in, ctl, met, met->pv, "PV", -1e34f, 1e34f);
10039 read_met_bin_3d(in, ctl, met, met->h2o, "H2O", 0, 1e34f);
10040 read_met_bin_3d(in, ctl, met, met->o3, "O3", 0, 1e34f);
10041 read_met_bin_3d(in, ctl, met, met->lwc, "LWC", 0, 1e34f);
10042 read_met_bin_3d(in, ctl, met, met->rwc, "RWC", 0, 1e34f);
10043 read_met_bin_3d(in, ctl, met, met->iwc, "IWC", 0, 1e34f);
10044 read_met_bin_3d(in, ctl, met, met->swc, "SWC", 0, 1e34f);
10045 read_met_bin_3d(in, ctl, met, met->cc, "CC", 0, 1);
10046
10047 /* Read final flag... */
10048 int final;
10049 FREAD(&final, int,
10050 1,
10051 in);
10052 if (final != 999)
10053 ERRMSG("Error while reading binary data!");
10054
10055 /* Close file... */
10056 fclose(in);
10057
10058 /* Return success... */
10059 return 1;
10060}
void read_met_bin_2d(FILE *in, const met_t *met, float var[EX][EY], const char *varname)
Reads a 2-dimensional meteorological variable from a binary file and stores it in the provided array.
Definition mptrac.c:10064
void read_met_bin_3d(FILE *in, const ctl_t *ctl, const met_t *met, float var[EX][EY][EP], const char *varname, const float bound_min, const float bound_max)
Reads 3D meteorological data from a binary file, potentially using different compression methods.
Definition mptrac.c:10093
float zt[EX][EY]
Tropopause geopotential height [km].
Definition mptrac.h:4033
float sst[EX][EY]
Sea surface temperature [K].
Definition mptrac.h:4021
float rwc[EX][EY][EP]
Cloud rain water content [kg/kg].
Definition mptrac.h:4093
float o3c[EX][EY]
Total column ozone [DU].
Definition mptrac.h:4063
float cape[EX][EY]
Convective available potential energy [J/kg].
Definition mptrac.h:4057
float pct[EX][EY]
Cloud top pressure [hPa].
Definition mptrac.h:4039
float shf[EX][EY]
Surface sensible heat flux [W/m^2].
Definition mptrac.h:4015
float lwc[EX][EY][EP]
Cloud liquid water content [kg/kg].
Definition mptrac.h:4090
float us[EX][EY]
Surface zonal wind [m/s].
Definition mptrac.h:4003
float cc[EX][EY][EP]
Cloud cover [1].
Definition mptrac.h:4102
float ts[EX][EY]
Surface temperature [K].
Definition mptrac.h:3997
float ess[EX][EY]
Eastward turbulent surface stress [N/m^2].
Definition mptrac.h:4009
float pcb[EX][EY]
Cloud bottom pressure [hPa].
Definition mptrac.h:4042
float pel[EX][EY]
Pressure at equilibrium level (EL) [hPa].
Definition mptrac.h:4054
float cin[EX][EY]
Convective inhibition [J/kg].
Definition mptrac.h:4060
float plcl[EX][EY]
Pressure at lifted condensation level (LCL) [hPa].
Definition mptrac.h:4048
float tt[EX][EY]
Tropopause temperature [K].
Definition mptrac.h:4030
float pbl[EX][EY]
Boundary layer pressure [hPa].
Definition mptrac.h:4024
float vs[EX][EY]
Surface meridional wind [m/s].
Definition mptrac.h:4006
float lsm[EX][EY]
Land-sea mask [1].
Definition mptrac.h:4018
float iwc[EX][EY][EP]
Cloud ice water content [kg/kg].
Definition mptrac.h:4096
float h2ot[EX][EY]
Tropopause water vapor volume mixing ratio [ppv].
Definition mptrac.h:4036
float pv[EX][EY][EP]
Potential vorticity [PVU].
Definition mptrac.h:4081
float cl[EX][EY]
Total column cloud water [kg/m^2].
Definition mptrac.h:4045
float nss[EX][EY]
Northward turbulent surface stress [N/m^2].
Definition mptrac.h:4012
float plfc[EX][EY]
Pressure at level of free convection (LFC) [hPa].
Definition mptrac.h:4051
float swc[EX][EY][EP]
Cloud snow water content [kg/kg].
Definition mptrac.h:4099
Here is the call graph for this function:

◆ read_met_bin_2d()

void read_met_bin_2d ( FILE * in,
const met_t * met,
float var[EX][EY],
const char * varname )

Reads a 2-dimensional meteorological variable from a binary file and stores it in the provided array.

This function reads a 2-dimensional meteorological variable from a binary file, which is assumed to be uncompressed, and stores it in the provided 2-dimensional array var. The variable name is used for logging purposes to identify the data being read.

Parameters
inA pointer to the FILE structure representing the binary file to read from.
metA pointer to a structure containing meteorological data.
varA 2-dimensional array to store the read variable.
varnameA string containing the name of the variable being read.

The function performs the following steps:

  • Allocates memory for a temporary buffer to hold the uncompressed data.
  • Logs information about the variable being read from the file.
  • Reads the uncompressed data from the file into the temporary buffer.
  • Copies the data from the temporary buffer to the provided 2-dimensional array.
  • Frees the memory allocated for the temporary buffer.
Note
The function assumes that the binary file contains uncompressed data and reads the data directly into the provided array without any additional processing.
Author
Lars Hoffmann

Definition at line 10064 of file mptrac.c.

10068 {
10069
10070 float *help;
10071
10072 /* Allocate... */
10073 ALLOC(help, float,
10074 EX * EY);
10075
10076 /* Read uncompressed... */
10077 LOG(2, "Read 2-D variable: %s (uncompressed)", varname);
10078 FREAD(help, float,
10079 (size_t) (met->nx * met->ny),
10080 in);
10081
10082 /* Copy data... */
10083 for (int ix = 0; ix < met->nx; ix++)
10084 for (int iy = 0; iy < met->ny; iy++)
10085 var[ix][iy] = help[ARRAY_2D(ix, iy, met->ny)];
10086
10087 /* Free... */
10088 free(help);
10089}

◆ read_met_bin_3d()

void read_met_bin_3d ( FILE * in,
const ctl_t * ctl,
const met_t * met,
float var[EX][EY][EP],
const char * varname,
const float bound_min,
const float bound_max )

Reads 3D meteorological data from a binary file, potentially using different compression methods.

This function reads 3-dimensional meteorological data from a binary file into a specified variable array. The data can be read in uncompressed form or using one of several supported compression methods. The data is then clamped to specified minimum and maximum bounds.

Parameters
[in]inPointer to the input file from which to read the data.
[in]ctlPointer to the control structure that contains metadata about the type of data and how it is stored.
[in]metPointer to the meteorological structure that contains the dimensions of the data.
[out]var3D array to store the read data, with dimensions [EX][EY][EP].
[in]varnameName of the variable being read, used for logging and debugging.
[in]bound_minMinimum bound to which data values should be clamped.
[in]bound_maxMaximum bound to which data values should be clamped.

The function supports the following types of data:

  • Uncompressed data
  • Packed data
  • ZFP compressed data (if compiled with ZFP support)
  • ZSTD compressed data (if compiled with ZSTD support)
  • cmultiscale compressed data (if compiled with CMS support)

Depending on the compression type specified in the control structure, the appropriate reading and decompression function is used. The data is read into a temporary buffer, then copied into the output array, applying the specified bounds to each value.

Note
The function assumes that the dimensions EX, EY, and EP are correctly defined and match the dimensions specified in the met structure.
If the appropriate compression support is not compiled, an error message is generated.
Author
Lars Hoffmann

Definition at line 10093 of file mptrac.c.

10100 {
10101
10102 float *help;
10103
10104 /* Allocate... */
10105 ALLOC(help, float,
10106 EX * EY * EP);
10107
10108 /* Read uncompressed data... */
10109 if (ctl->met_type == 1) {
10110 LOG(2, "Read 3-D variable: %s (uncompressed)", varname);
10111 FREAD(help, float,
10112 (size_t) (met->nx * met->ny * met->np),
10113 in);
10114 }
10115
10116 /* Read packed data... */
10117 else if (ctl->met_type == 2)
10118 compress_pck(ctl, met, varname, help, 1, NULL, in);
10119
10120 /* Read ZFP data... */
10121 else if (ctl->met_type == 3) {
10122#ifdef ZFP
10123 int precision;
10124 FREAD(&precision, int,
10125 1,
10126 in);
10127
10128 double tolerance;
10129 FREAD(&tolerance, double,
10130 1,
10131 in);
10132
10133 compress_zfp(ctl, met, varname, help, 1, NULL, in);
10134#else
10135 ERRMSG("MPTRAC was compiled without ZFP compression!");
10136#endif
10137 }
10138
10139 /* Read zstd data... */
10140 else if (ctl->met_type == 4) {
10141#ifdef ZSTD
10142 compress_zstd(ctl, met, varname, help, 1, NULL, in);
10143#else
10144 ERRMSG("MPTRAC was compiled without ZSTD compression!");
10145#endif
10146 }
10147
10148 /* Read LZ4 data... */
10149 else if (ctl->met_type == 8) {
10150#ifdef LZ4
10151 compress_lz4(ctl, met, varname, help, 1, NULL, in);
10152#else
10153 ERRMSG("MPTRAC was compiled without LZ4 compression!");
10154#endif
10155 }
10156
10157 /* Read cmultiscale data... */
10158 else if (ctl->met_type == 5) {
10159#ifdef CMS
10160 compress_cms(ctl, met, varname, help, 1, NULL, in);
10161#else
10162 ERRMSG("MPTRAC was compiled without cmultiscale compression!");
10163#endif
10164 }
10165
10166 /* Read SZ3 data... */
10167 else if (ctl->met_type == 7) {
10168#ifdef SZ3
10169 int precision;
10170 FREAD(&precision, int,
10171 1,
10172 in);
10173
10174 double tolerance;
10175 FREAD(&tolerance, double,
10176 1,
10177 in);
10178
10179 compress_sz3(ctl, met, varname, help, 1, NULL, in);
10180#else
10181 ERRMSG("MPTRAC was compiled without sz3 compression!");
10182#endif
10183 }
10184
10185 /* Copy data... */
10186#pragma omp parallel for default(shared) collapse(2)
10187 for (int ix = 0; ix < met->nx; ix++)
10188 for (int iy = 0; iy < met->ny; iy++)
10189 for (int ip = 0; ip < met->np; ip++) {
10190 var[ix][iy][ip] = help[ARRAY_3D(ix, iy, met->ny, ip, met->np)];
10191 if (var[ix][iy][ip] < bound_min)
10192 var[ix][iy][ip] = bound_min;
10193 else if (var[ix][iy][ip] > bound_max)
10194 var[ix][iy][ip] = bound_max;
10195 }
10196
10197 /* Free... */
10198 free(help);
10199}
void compress_pck(const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
Compresses or decompresses a 3‑D float array using the PCK format.
Definition mptrac.c:990
void compress_zfp(const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
Compresses or decompresses a 3D array of floats using the ZFP library.
void compress_sz3(const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
Compresses or decompresses a 3-D float array using the SZ3 library.
void compress_zstd(const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
Compresses or decompresses a float array using ZSTD.
void compress_cms(const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
Compresses or decompresses a 3-D meteorological field using cmultiscale.
void compress_lz4(const ctl_t *ctl, const met_t *met, const char *varname, float *array, const int decompress, FILE *level_log, FILE *inout)
Compresses or decompresses a float array using LZ4.
Here is the call graph for this function:

◆ read_met_cape()

void read_met_cape ( const ctl_t * ctl,
const clim_t * clim,
met_t * met )

Calculates Convective Available Potential Energy (CAPE) for each grid point.

This function calculates the Convective Available Potential Energy (CAPE) at each grid point based on the provided meteorological data. CAPE is a measure of the energy available for deep convection, which is essential for severe weather development.

Parameters
ctlPointer to the control structure that contains metadata about the type of data and how it is stored.
climA pointer to a structure containing climatological data.
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the calculation time.
  • Initializes variables and constants required for the computation, such as vertical spacing and pressure levels.
  • Iterates over each grid point in parallel using OpenMP.
  • Calculates CAPE by integrating the difference in virtual temperatures between the environment and the parcel, up to the level of free convection (LFC).
  • Determines the lifted condensation level (LCL), level of free convection (LFC), equilibrium level (EL), and Convective Inhibition (CIN) for each grid point.
  • Checks the results and updates the corresponding fields in the meteorological data structure.
Note
The function utilizes OpenMP for parallelization to enhance performance by distributing the computation across multiple threads.
Author
Lars Hoffmann

Definition at line 10203 of file mptrac.c.

10206 {
10207
10208 /* Check parameters... */
10209 if (ctl->met_cape != 1)
10210 return;
10211
10212 if (ctl->met_coord_type != 0)
10213 ERRMSG("Only lat/lon grid supported");
10214
10215 /* Set timer... */
10216 SELECT_TIMER("READ_MET_CAPE", "METPROC");
10217 LOG(2, "Calculate CAPE...");
10218
10219 /* Vertical spacing (about 100 m)... */
10220 const double pfac = 1.01439, dz0 = RI / MA / G0 * log(pfac);
10221
10222 /* Loop over columns... */
10223#pragma omp parallel for default(shared) collapse(2)
10224 for (int ix = 0; ix < met->nx; ix++)
10225 for (int iy = 0; iy < met->ny; iy++) {
10226
10227 /* Get potential temperature and water vapor at lowest 50 hPa... */
10228 int n = 0;
10229 double h2o = 0, t, theta = 0;
10230 double pbot = MIN(met->ps[ix][iy], met->p[0]);
10231 double ptop = pbot - 50.;
10232 for (int ip = 0; ip < met->np; ip++) {
10233 if (met->p[ip] <= pbot) {
10234 theta += THETA(met->p[ip], met->t[ix][iy][ip]);
10235 h2o += met->h2o[ix][iy][ip];
10236 n++;
10237 }
10238 if (met->p[ip] < ptop && n > 0)
10239 break;
10240 }
10241 theta /= n;
10242 h2o /= n;
10243
10244 /* Cannot compute anything if water vapor is missing... */
10245 met->plcl[ix][iy] = NAN;
10246 met->plfc[ix][iy] = NAN;
10247 met->pel[ix][iy] = NAN;
10248 met->cape[ix][iy] = NAN;
10249 met->cin[ix][iy] = NAN;
10250 if (h2o <= 0)
10251 continue;
10252
10253 /* Find lifted condensation level (LCL)... */
10254 ptop = P(20.);
10255 pbot = met->ps[ix][iy];
10256 do {
10257 met->plcl[ix][iy] = (float) (0.5 * (pbot + ptop));
10258 t = theta / pow(1000. / met->plcl[ix][iy], KAPPA);
10259 if (RH(met->plcl[ix][iy], t, h2o) > 100.)
10260 ptop = met->plcl[ix][iy];
10261 else
10262 pbot = met->plcl[ix][iy];
10263 } while (pbot - ptop > 0.1);
10264
10265 /* Calculate CIN up to LCL... */
10267 double dcape, dz, h2o_env, t_env;
10268 double p = met->ps[ix][iy];
10269 met->cape[ix][iy] = met->cin[ix][iy] = 0;
10270 do {
10271 dz = dz0 * TVIRT(t, h2o);
10272 p /= pfac;
10273 t = theta / pow(1000. / p, KAPPA);
10274 intpol_met_space_3d(met, met->t, p, met->lon[ix], met->lat[iy],
10275 &t_env, ci, cw, 1);
10276 intpol_met_space_3d(met, met->h2o, p, met->lon[ix], met->lat[iy],
10277 &h2o_env, ci, cw, 0);
10278 dcape = 1e3 * G0 * (TVIRT(t, h2o) - TVIRT(t_env, h2o_env)) /
10279 TVIRT(t_env, h2o_env) * dz;
10280 if (dcape < 0)
10281 met->cin[ix][iy] += fabsf((float) dcape);
10282 } while (p > met->plcl[ix][iy]);
10283
10284 /* Calculate level of free convection (LFC), equilibrium level (EL),
10285 and convective available potential energy (CAPE)... */
10286 dcape = 0;
10287 p = met->plcl[ix][iy];
10288 t = theta / pow(1000. / p, KAPPA);
10289 ptop = 0.75 * clim_tropo(clim, met->time,
10290 ctl->met_coord_type ==
10291 0 ? met->lat[iy] : ctl->met_utm_ref_lat);
10292 do {
10293 dz = dz0 * TVIRT(t, h2o);
10294 p /= pfac;
10295 t -= lapse_rate(t, h2o) * dz;
10296 double psat = PSAT(t);
10297 h2o = psat / (p - (1. - EPS) * psat);
10298 intpol_met_space_3d(met, met->t, p, met->lon[ix], met->lat[iy],
10299 &t_env, ci, cw, 1);
10300 intpol_met_space_3d(met, met->h2o, p, met->lon[ix], met->lat[iy],
10301 &h2o_env, ci, cw, 0);
10302 double dcape_old = dcape;
10303 dcape = 1e3 * G0 * (TVIRT(t, h2o) - TVIRT(t_env, h2o_env)) /
10304 TVIRT(t_env, h2o_env) * dz;
10305 if (dcape > 0) {
10306 met->cape[ix][iy] += (float) dcape;
10307 if (!isfinite(met->plfc[ix][iy]))
10308 met->plfc[ix][iy] = (float) p;
10309 } else if (dcape_old > 0)
10310 met->pel[ix][iy] = (float) p;
10311 if (dcape < 0 && !isfinite(met->plfc[ix][iy]))
10312 met->cin[ix][iy] += fabsf((float) dcape);
10313 } while (p > ptop);
10314
10315 /* Check results... */
10316 if (!isfinite(met->plfc[ix][iy]))
10317 met->cin[ix][iy] = NAN;
10318 }
10319}
double clim_tropo(const clim_t *clim, const double t, const double lat)
Calculates the tropopause pressure based on climatological data.
Definition mptrac.c:217
Here is the call graph for this function:

◆ read_met_cloud()

void read_met_cloud ( met_t * met)

Calculates cloud-related variables for each grid point.

This function calculates cloud-related variables, such as cloud cover, cloud top pressure, cloud bottom pressure, and total cloud water content, based on the provided meteorological data.

Parameters
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the calculation time.
  • Initializes variables and constants required for the computation.
  • Iterates over each grid point in parallel using OpenMP.
  • Determines cloud-related variables based on thresholds for liquid water content (LWC), rain water content (RWC), ice water content (IWC) and snow water content (SWC).
  • Calculates cloud cover, cloud top pressure, cloud bottom pressure, and total cloud water content for each grid point.
  • Updates the corresponding fields in the meteorological data structure.
Note
The function utilizes OpenMP for parallelization to enhance performance by distributing the computation across multiple threads.
Author
Lars Hoffmann

Definition at line 10323 of file mptrac.c.

10324 {
10325
10326 /* Set timer... */
10327 SELECT_TIMER("READ_MET_CLOUD", "METPROC");
10328 LOG(2, "Calculate cloud data...");
10329
10330 /* Thresholds for cloud detection... */
10331 const double ccmin = 0.01, cwmin = 1e-6;
10332
10333 /* Loop over columns... */
10334#pragma omp parallel for default(shared) collapse(2)
10335 for (int ix = 0; ix < met->nx; ix++)
10336 for (int iy = 0; iy < met->ny; iy++) {
10337
10338 /* Init... */
10339 met->pct[ix][iy] = NAN;
10340 met->pcb[ix][iy] = NAN;
10341 met->cl[ix][iy] = 0;
10342
10343 /* Loop over pressure levels... */
10344 for (int ip = 0; ip < met->np - 1; ip++) {
10345
10346 /* Check pressure... */
10347 if (met->p[ip] > met->ps[ix][iy] || met->p[ip] < P(20.))
10348 continue;
10349
10350 /* Check ice water and liquid water content... */
10351 if (met->cc[ix][iy][ip] > ccmin
10352 && (met->lwc[ix][iy][ip] > cwmin
10353 || met->rwc[ix][iy][ip] > cwmin
10354 || met->iwc[ix][iy][ip] > cwmin
10355 || met->swc[ix][iy][ip] > cwmin)) {
10356
10357 /* Get cloud top pressure ... */
10358 met->pct[ix][iy]
10359 = (float) (0.5 * (met->p[ip] + (float) met->p[ip + 1]));
10360
10361 /* Get cloud bottom pressure ... */
10362 if (!isfinite(met->pcb[ix][iy]))
10363 met->pcb[ix][iy]
10364 = (float) (0.5 * (met->p[ip] + met->p[MAX(ip - 1, 0)]));
10365 }
10366
10367 /* Get cloud water... */
10368 met->cl[ix][iy] += (float)
10369 (0.5 * (met->lwc[ix][iy][ip] + met->lwc[ix][iy][ip + 1]
10370 + met->rwc[ix][iy][ip] + met->rwc[ix][iy][ip + 1]
10371 + met->iwc[ix][iy][ip] + met->iwc[ix][iy][ip + 1]
10372 + met->swc[ix][iy][ip] + met->swc[ix][iy][ip + 1])
10373 * 100. * (met->p[ip] - met->p[ip + 1]) / G0);
10374 }
10375 }
10376}

◆ read_met_detrend()

void read_met_detrend ( const ctl_t * ctl,
met_t * met )

Detrends meteorological data.

This function detrends meteorological data by removing spatially varying backgrounds from each grid point. Detrending helps in removing systematic biases and trends from the data, enabling better analysis and modeling.

Parameters
ctlA pointer to a structure containing control parameters.
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Checks if detrending is enabled based on the control parameters.
  • Sets up a timer to monitor the detrending time.
  • Allocates memory for a temporary meteorological data structure.
  • Calculates the standard deviation and box size for detrending.
  • Calculates the detrended data by subtracting spatially varying backgrounds.
  • Updates the original meteorological data with the detrended values.
  • Frees the allocated memory.
Note
Detrending is performed by subtracting spatially varying backgrounds calculated from neighboring grid points.
OpenMP is utilized for parallelization to enhance performance by distributing the computation across multiple threads.
Author
Lars Hoffmann

Definition at line 10380 of file mptrac.c.

10382 {
10383
10384 met_t *help;
10385
10386 /* Check parameters... */
10387 if (ctl->met_detrend <= 0)
10388 return;
10389
10390 if (ctl->met_coord_type != 0)
10391 ERRMSG("Only lat/lon grid supported");
10392
10393 /* Set timer... */
10394 SELECT_TIMER("READ_MET_DETREND", "METPROC");
10395 LOG(2, "Detrend meteo data...");
10396
10397 /* Allocate... */
10398 ALLOC(help, met_t, 1);
10399
10400 /* Calculate standard deviation... */
10401 const double sigma = ctl->met_detrend / 2.355;
10402 const double tssq = 2. * SQR(sigma);
10403
10404 /* Calculate box size in latitude... */
10405 int sy = (int) (3. * DY2DEG(sigma) / fabs(met->lat[1] - met->lat[0]));
10406 sy = MIN(MAX(1, sy), met->ny / 2);
10407
10408 /* Calculate background... */
10409#pragma omp parallel for default(shared) collapse(2)
10410 for (int ix = 0; ix < met->nx; ix++) {
10411 for (int iy = 0; iy < met->ny; iy++) {
10412
10413 /* Calculate Cartesian coordinates... */
10414 double x0[3];
10415 geo2cart(0.0, met->lon[ix], met->lat[iy], x0);
10416
10417 /* Calculate box size in longitude... */
10418 int sx =
10419 (int) (3. * DX2DEG(sigma, met->lat[iy]) /
10420 fabs(met->lon[1] - met->lon[0]));
10421 sx = MIN(MAX(1, sx), met->nx / 2);
10422
10423 /* Init... */
10424 float wsum = 0;
10425 for (int ip = 0; ip < met->np; ip++) {
10426 help->t[ix][iy][ip] = 0;
10427 help->u[ix][iy][ip] = 0;
10428 help->v[ix][iy][ip] = 0;
10429 help->w[ix][iy][ip] = 0;
10430 }
10431
10432 /* Loop over neighboring grid points... */
10433 for (int ix2 = ix - sx; ix2 <= ix + sx; ix2++) {
10434 int ix3 = ix2;
10435 if (ix3 < 0)
10436 ix3 += met->nx;
10437 else if (ix3 >= met->nx)
10438 ix3 -= met->nx;
10439 for (int iy2 = MAX(iy - sy, 0);
10440 iy2 <= MIN(iy + sy, met->ny - 1); iy2++) {
10441
10442 /* Calculate Cartesian coordinates... */
10443 double x1[3];
10444 geo2cart(0.0, met->lon[ix3], met->lat[iy2], x1);
10445
10446 /* Calculate weighting factor... */
10447 const float w = (float) exp(-DIST2(x0, x1) / tssq);
10448
10449 /* Add data... */
10450 wsum += w;
10451 for (int ip = 0; ip < met->np; ip++) {
10452 help->t[ix][iy][ip] += w * met->t[ix3][iy2][ip];
10453 help->u[ix][iy][ip] += w * met->u[ix3][iy2][ip];
10454 help->v[ix][iy][ip] += w * met->v[ix3][iy2][ip];
10455 help->w[ix][iy][ip] += w * met->w[ix3][iy2][ip];
10456 }
10457 }
10458 }
10459
10460 /* Normalize... */
10461 for (int ip = 0; ip < met->np; ip++) {
10462 help->t[ix][iy][ip] /= wsum;
10463 help->u[ix][iy][ip] /= wsum;
10464 help->v[ix][iy][ip] /= wsum;
10465 help->w[ix][iy][ip] /= wsum;
10466 }
10467 }
10468 }
10469
10470 /* Subtract background... */
10471#pragma omp parallel for default(shared) collapse(3)
10472 for (int ix = 0; ix < met->nx; ix++)
10473 for (int iy = 0; iy < met->ny; iy++)
10474 for (int ip = 0; ip < met->np; ip++) {
10475 met->t[ix][iy][ip] -= help->t[ix][iy][ip];
10476 met->u[ix][iy][ip] -= help->u[ix][iy][ip];
10477 met->v[ix][iy][ip] -= help->v[ix][iy][ip];
10478 met->w[ix][iy][ip] -= help->w[ix][iy][ip];
10479 }
10480
10481 /* Free... */
10482 free(help);
10483}
void geo2cart(const double z, const double lon, const double lat, double *x)
Converts geographic coordinates (longitude, latitude, altitude) to Cartesian coordinates.
Definition mptrac.c:2931
Here is the call graph for this function:

◆ read_met_extrapolate()

void read_met_extrapolate ( met_t * met)

Extrapolates meteorological data.

This function extrapolates meteorological data by filling missing or invalid data points with values from the nearest valid point above. Extrapolation is performed column-wise, ensuring that missing data points are replaced with valid values.

Parameters
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the extrapolation time.
  • Loops over each grid column in parallel.
  • Finds the lowest valid data point within each column.
  • Extrapolates missing or invalid data points by copying values from the nearest valid point above.
  • Updates the meteorological data structure with the extrapolated values.
Note
Extrapolation is performed by copying values from the nearest valid point above to fill missing or invalid data points. OpenMP is utilized for parallelization to enhance performance by distributing the computation across multiple threads.
Author
Lars Hoffmann

Definition at line 10487 of file mptrac.c.

10488 {
10489
10490 /* Set timer... */
10491 SELECT_TIMER("READ_MET_EXTRAPOLATE", "METPROC");
10492 LOG(2, "Extrapolate meteo data...");
10493
10494 /* Loop over columns... */
10495#pragma omp parallel for default(shared) collapse(2)
10496 for (int ix = 0; ix < met->nx; ix++)
10497 for (int iy = 0; iy < met->ny; iy++) {
10498
10499 /* Find lowest valid data point... */
10500 int ip0;
10501 for (ip0 = met->np - 1; ip0 >= 0; ip0--)
10502 if (!isfinite(met->t[ix][iy][ip0])
10503 || !isfinite(met->u[ix][iy][ip0])
10504 || !isfinite(met->v[ix][iy][ip0])
10505 || !isfinite(met->w[ix][iy][ip0]))
10506 break;
10507
10508 /* Extrapolate... */
10509 for (int ip = ip0; ip >= 0; ip--) {
10510 met->t[ix][iy][ip] = met->t[ix][iy][ip + 1];
10511 met->u[ix][iy][ip] = met->u[ix][iy][ip + 1];
10512 met->v[ix][iy][ip] = met->v[ix][iy][ip + 1];
10513 met->w[ix][iy][ip] = met->w[ix][iy][ip + 1];
10514 met->h2o[ix][iy][ip] = met->h2o[ix][iy][ip + 1];
10515 met->o3[ix][iy][ip] = met->o3[ix][iy][ip + 1];
10516 met->lwc[ix][iy][ip] = met->lwc[ix][iy][ip + 1];
10517 met->rwc[ix][iy][ip] = met->rwc[ix][iy][ip + 1];
10518 met->iwc[ix][iy][ip] = met->iwc[ix][iy][ip + 1];
10519 met->swc[ix][iy][ip] = met->swc[ix][iy][ip + 1];
10520 met->cc[ix][iy][ip] = met->cc[ix][iy][ip + 1];
10521 }
10522 }
10523}

◆ read_met_geopot()

void read_met_geopot ( const ctl_t * ctl,
met_t * met )

Calculates geopotential heights from meteorological data.

This function calculates geopotential heights from provided meteorological data using the hydrostatic equation. Geopotential heights are computed column-wise for each grid point based on the temperature, pressure, and surface height information. Optionally, the calculated geopotential heights can be smoothed horizontally using a weighted averaging scheme.

Parameters
ctlA pointer to a structure containing control parameters.
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the geopotential height calculation time.
  • Calculates the logarithm of pressure levels for efficient computation.
  • Applies the hydrostatic equation to determine geopotential heights based on temperature, pressure, and height information.
  • Optionally, performs horizontal smoothing on the calculated geopotential heights.
  • Updates the meteorological data structure with the computed geopotential heights.
Note
The hydrostatic equation is utilized to calculate geopotential heights, ensuring consistency with atmospheric conditions. Optionally, horizontal smoothing can be applied to the calculated geopotential heights to reduce spatial variability. OpenMP is utilized for parallelization to enhance performance by distributing the computation across multiple threads.
Author
Lars Hoffmann

Definition at line 10527 of file mptrac.c.

10529 {
10530
10531 float *help;
10532
10533 double logp[EP];
10534
10535 int dx = ctl->met_geopot_sx, dy = ctl->met_geopot_sy;
10536
10537 /* Set timer... */
10538 SELECT_TIMER("READ_MET_GEOPOT", "METPROC");
10539 LOG(2, "Calculate geopotential heights...");
10540
10541 /* Allocate... */
10542 ALLOC(help, float,
10543 EX * EY * EP);
10544
10545 /* Calculate log pressure... */
10546#pragma omp parallel for default(shared)
10547 for (int ip = 0; ip < met->np; ip++)
10548 logp[ip] = log(met->p[ip]);
10549
10550 /* Apply hydrostatic equation to calculate geopotential heights... */
10551#pragma omp parallel for default(shared) collapse(2)
10552 for (int ix = 0; ix < met->nx; ix++)
10553 for (int iy = 0; iy < met->ny; iy++) {
10554
10555 /* Get surface height and pressure... */
10556 const double zs = met->zs[ix][iy];
10557 const double lnps = log(met->ps[ix][iy]);
10558
10559 /* Get temperature and water vapor at the surface... */
10560 const int ip0 = locate_irr(met->p, met->np, met->ps[ix][iy]);
10561 const double ts = LIN(met->p[ip0], met->t[ix][iy][ip0], met->p[ip0 + 1],
10562 met->t[ix][iy][ip0 + 1], met->ps[ix][iy]);
10563 const double h2os =
10564 LIN(met->p[ip0], met->h2o[ix][iy][ip0], met->p[ip0 + 1],
10565 met->h2o[ix][iy][ip0 + 1], met->ps[ix][iy]);
10566
10567 /* Upper part of profile... */
10568 met->z[ix][iy][ip0 + 1]
10569 = (float) (zs +
10570 ZDIFF(lnps, ts, h2os, logp[ip0 + 1],
10571 met->t[ix][iy][ip0 + 1], met->h2o[ix][iy][ip0 + 1]));
10572 for (int ip = ip0 + 2; ip < met->np; ip++)
10573 met->z[ix][iy][ip]
10574 = (float) (met->z[ix][iy][ip - 1] +
10575 ZDIFF(logp[ip - 1], met->t[ix][iy][ip - 1],
10576 met->h2o[ix][iy][ip - 1], logp[ip],
10577 met->t[ix][iy][ip], met->h2o[ix][iy][ip]));
10578
10579 /* Lower part of profile... */
10580 met->z[ix][iy][ip0]
10581 = (float) (zs +
10582 ZDIFF(lnps, ts, h2os, logp[ip0],
10583 met->t[ix][iy][ip0], met->h2o[ix][iy][ip0]));
10584 for (int ip = ip0 - 1; ip >= 0; ip--)
10585 met->z[ix][iy][ip]
10586 = (float) (met->z[ix][iy][ip + 1] +
10587 ZDIFF(logp[ip + 1], met->t[ix][iy][ip + 1],
10588 met->h2o[ix][iy][ip + 1], logp[ip],
10589 met->t[ix][iy][ip], met->h2o[ix][iy][ip]));
10590 }
10591
10592 /* Check control parameters... */
10593 if (dx == 0 || dy == 0)
10594 return;
10595
10596 /* Default smoothing parameters... */
10597 if (dx < 0 || dy < 0) {
10598 if (fabs(met->lon[1] - met->lon[0]) < 0.5) {
10599 dx = 3;
10600 dy = 2;
10601 } else {
10602 dx = 6;
10603 dy = 4;
10604 }
10605 }
10606
10607 /* Calculate weights for smoothing... */
10608 float ws[dx + 1][dy + 1];
10609#pragma omp parallel for default(shared) collapse(2)
10610 for (int ix = 0; ix <= dx; ix++)
10611 for (int iy = 0; iy < dy; iy++)
10612 ws[ix][iy] = (1.0f - (float) ix / (float) dx)
10613 * (1.0f - (float) iy / (float) dy);
10614
10615 /* Copy data... */
10616#pragma omp parallel for default(shared) collapse(3)
10617 for (int ix = 0; ix < met->nx; ix++)
10618 for (int iy = 0; iy < met->ny; iy++)
10619 for (int ip = 0; ip < met->np; ip++)
10620 help[ARRAY_3D(ip, ix, met->nx, iy, met->ny)] = met->z[ix][iy][ip];
10621
10622 /* Horizontal smoothing... */
10623#pragma omp parallel for default(shared) collapse(3)
10624 for (int ip = 0; ip < met->np; ip++)
10625 for (int ix = 0; ix < met->nx; ix++)
10626 for (int iy = 0; iy < met->ny; iy++) {
10627 float res = 0, wsum = 0;
10628 int iy0 = MAX(iy - dy + 1, 0);
10629 int iy1 = MIN(iy + dy - 1, met->ny - 1);
10630 for (int ix2 = ix - dx + 1; ix2 <= ix + dx - 1; ++ix2) {
10631 int ix3 = ix2;
10632 /* Wrap the smoothing stencil across the longitude boundary... */
10633 if (ix3 < 0)
10634 ix3 += met->nx;
10635 else if (ix3 >= met->nx)
10636 ix3 -= met->nx;
10637 for (int iy2 = iy0; iy2 <= iy1; ++iy2)
10638 if (isfinite(help[ARRAY_3D(ip, ix3, met->nx, iy2, met->ny)])) {
10639 float w = ws[abs(ix - ix2)][abs(iy - iy2)];
10640 res += w * help[ARRAY_3D(ip, ix3, met->nx, iy2, met->ny)];
10641 wsum += w;
10642 }
10643 }
10644 if (wsum > 0)
10645 met->z[ix][iy][ip] = res / wsum;
10646 else
10647 met->z[ix][iy][ip] = NAN;
10648 }
10649
10650 /* Free... */
10651 free(help);
10652}
#define ZDIFF(lnp0, t0, h2o0, lnp1, t1, h2o1)
Calculate geopotential height difference.
Definition mptrac.h:2334
Here is the call graph for this function:

◆ read_met_grib()

int read_met_grib ( const char * filename,
const ctl_t * ctl,
met_t * met )

Reads meteorological data from a grib file and processes it.

This function reads meteorological data from a grib file specified by the filename parameter, using the ECCODES library. It reads grid, surface, and vertical level data, processes the data and calculates various derived meteorological fields such as geopotential heights, potential vorticity, cloud properties, and convective available potential energy (CAPE).

Parameters
filenameA constant character pointer representing the name of the grib files to read the meteorological data from. The sf or ml suffixes indicating surface or multi-level data should be replaced with XX.
ctlA pointer to a ctl_t structure, which contains control parameters for reading and processing the meteorological data.
metA pointer to a met_t structure that will store the meteorological data read and processed from the NetCDF file.
Returns
Returns 1 on success, or 0 if the file cannot be opened.
Note
  • The function reads grid data, vertical level data, and surface data from the file, and processes the data to calculate additional meteorological parameters.
  • If the file cannot be opened, the function logs a warning and returns 0.
Author
Nils Nobre Wittwer

◆ read_met_grib_grid()

void read_met_grib_grid ( codes_handle ** handles,
int count_handles,
met_t * met )

Reads global meteorological information from a grib file.

This function reads meteorological grid information from a grib file, including time and spatial dimensions. The function computes the latitude and longitude grid based on the provided boundaries and increment values.

Parameters
handlesA pointer to an array of codes_handle pointers representing the grib messages.
count_handlesThe total number of grib messages in the handles array.
metA pointer to a structure to store meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the reading time for meteorological grid information.
  • Determines the time information from the data file.
  • Retrieves grid dimensions (longitude, latitude, and vertical levels) from the grib file.
  • Reads longitudes and latitudes boundaries and increments from the grib file and computes the grid.
  • Logs the retrieved grid information for verification and debugging purposes.
Author
Nils Nobre Wittwer

◆ read_met_grib_levels()

void read_met_grib_levels ( codes_handle ** handles,
const int num_messages,
const ctl_t * ctl,
met_t * met )

Reads meteorological variables at different vertical levels from a grib file.

This function reads meteorological variables such as temperature, wind components, specific humidity, ozone data, cloud parameters, and cloud cover at various vertical levels from a grib file.

Parameters
handlesA pointer to an array of codes_handle pointers representing the grib messages.
num_messagesThe total number of grib messages in the handles array.
ctlA pointer to a structure containing control parameters.
metA pointer to a structure to store meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the reading time for meteorological level data.
  • Reads meteorological variables from the grib file.
  • Checks the ordering of pressure levels to ensure they are in descending order.
Author
Nils Nobre Wittwer

◆ read_met_grib_surface()

void read_met_grib_surface ( codes_handle ** handles,
const int num_messages,
const ctl_t * ctl,
met_t * met )

Reads surface meteorological data from a grib file and stores it in the meteorological data structure.

This function reads various surface meteorological variables from a grib file and stores them in the provided meteorological data structure. Depending on the configuration, it may read data for surface pressure, geopotential height, temperature, zonal and meridional wind components, land-sea mask, and sea surface temperature.

Parameters
handlesA pointer to an array of codes_handle pointers representing the grib messages.
num_messagesThe total number of grib messages in the handles array.
ctlA pointer to a structure containing control parameters.
metA pointer to a structure to store meteorological data.

The function performs the following steps:

  • Sets a timer for performance monitoring.
  • Reads surface meteorological data based on the configuration:
  • Reads surface pressure from "lnsp", "ps", or "sp" variables.
  • Converts surface pressure to Pa.
  • Reads geopotential height at the surface from "z" or "zm" variables.
  • Reads surface temperature from "t2m" or "2t" variables.
  • Reads zonal wind at the surface from "u10m" or "10u" variables.
  • Reads meridional wind at the surface from "v10m" or "10v" variables.
  • Reads land-sea mask from "lsm" variable.
  • Reads sea surface temperature from "sstk" or "sst" variables.
Author
Nils Nobre Wittwer

◆ read_met_ml2pl()

void read_met_ml2pl ( const ctl_t * ctl,
const met_t * met,
float var[EX][EY][EP],
const char * varname )

Interpolates meteorological data to specified pressure levels.

This function interpolates meteorological data from model levels to pressure levels. The interpolation is performed in parallel over the spatial grid defined in the meteorological data structure.

Parameters
[in]ctlA pointer to a control structure containing the number of pressure levels (met_np) and the pressure levels themselves (met_p).
[in]metA pointer to a meteorological data structure containing the grid dimensions (nx, ny) and the pressure profile (pl).
[in,out]varA 3D array containing the meteorological variable to be interpolated. On output, this array will contain the interpolated values at the specified pressure levels.
[in]varnameA string representing the name of the meteorological variable being interpolated.

This function performs the following steps:

  • Sets a timer for the operation.
  • Logs the start of the interpolation process with the variable name.
  • Loops over the spatial columns (grid points).
  • For each column, copies the pressure profile.
  • Interpolates the meteorological variable to the specified pressure levels.
  • Copies the interpolated data back into the var array.
Note
The interpolation is performed in parallel using OpenMP.
Author
Lars Hoffmann

Definition at line 12528 of file mptrac.c.

12532 {
12533
12534 double aux[EP], p[EP];
12535
12536 /* Set timer... */
12537 SELECT_TIMER("READ_MET_ML2PL", "METPROC");
12538 LOG(2, "Interpolate meteo data to pressure levels: %s", varname);
12539
12540 /* Loop over columns... */
12541#pragma omp parallel for default(shared) private(aux,p) collapse(2)
12542 for (int ix = 0; ix < met->nx; ix++)
12543 for (int iy = 0; iy < met->ny; iy++) {
12544
12545 /* Copy pressure profile... */
12546 for (int ip = 0; ip < met->np; ip++)
12547 p[ip] = met->pl[ix][iy][ip];
12548
12549 /* Interpolate... */
12550 for (int ip = 0; ip < ctl->met_np; ip++) {
12551 double pt = ctl->met_p[ip];
12552 if ((pt > p[0] && p[0] > p[1]) || (pt < p[0] && p[0] < p[1]))
12553 pt = p[0];
12554 else if ((pt > p[met->np - 1] && p[1] > p[0])
12555 || (pt < p[met->np - 1] && p[1] < p[0]))
12556 pt = p[met->np - 1];
12557 const int ip2 = locate_irr(p, met->np, pt);
12558 aux[ip] = LIN(p[ip2], var[ix][iy][ip2],
12559 p[ip2 + 1], var[ix][iy][ip2 + 1], pt);
12560 }
12561
12562 /* Copy data... */
12563 for (int ip = 0; ip < ctl->met_np; ip++)
12564 var[ix][iy][ip] = (float) aux[ip];
12565 }
12566}
Here is the call graph for this function:

◆ read_met_monotonize()

void read_met_monotonize ( const ctl_t * ctl,
met_t * met )

Makes zeta and pressure profiles monotone.

This function ensures that zeta and pressure profiles are monotone increasing and decreasing with altitude. It iterates over each grid point and each level to identify inversions and linearly interpolate between them to maintain monotonicity. The interpolation is performed for both zeta and pressure profiles.

Parameters
ctlA pointer to a control parameter structure.
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets up a timer to monitor the processing time.
  • Iterates over each grid point in parallel using OpenMP.
  • Identifies inversions in both zeta and pressure profiles and interpolates linearly between them to make the profiles monotone increasing.
Note
This function is crucial for maintaining the physical consistency of meteorological profiles, ensuring accurate atmospheric simulations.
Author
Jan Clemens

Definition at line 12570 of file mptrac.c.

12572 {
12573
12574 /* Check parameters... */
12575 if (ctl->advect_vert_coord != 1)
12576 return;
12577
12578 /* Set timer... */
12579 SELECT_TIMER("READ_MET_MONOTONIZE", "METPROC");
12580 LOG(2, "Make zeta profiles monotone...");
12581
12582 /* Create monotone zeta profiles... */
12583#pragma omp parallel for default(shared) collapse(2)
12584 for (int i = 0; i < met->nx; i++)
12585 for (int j = 0; j < met->ny; j++) {
12586 int k = 1;
12587
12588 while (k < met->npl) { /* Check if there is an inversion at level k... */
12589 if ((met->zetal[i][j][k - 1] >= met->zetal[i][j][k])) {
12590 /* Find the upper level k+l over the inversion... */
12591 int l = 0;
12592 do {
12593 l++;
12594 }
12595 while ((met->zetal[i][j][k - 1] >=
12596 met->zetal[i][j][k + l]) & (k + l < met->npl));
12597
12598 /* Interpolate linear between the top and bottom
12599 of the inversion... */
12600 float s =
12601 (float) (met->zetal[i][j][k + l] - met->zetal[i][j][k - 1])
12602 / (float) (met->hybrid[k + l] - met->hybrid[k - 1]);
12603
12604 for (int m = k; m < k + l; m++) {
12605 float d = (float) (met->hybrid[m] - met->hybrid[k - 1]);
12606 met->zetal[i][j][m] = s * d + met->zetal[i][j][k - 1];
12607 }
12608
12609 /* Search for more inversions above the last inversion ... */
12610 k = k + l;
12611 } else {
12612 k++;
12613 }
12614 }
12615 }
12616
12617 /* Create monotone pressure profiles... */
12618#pragma omp parallel for default(shared) collapse(2)
12619 for (int i = 0; i < met->nx; i++)
12620 for (int j = 0; j < met->ny; j++) {
12621 int k = 1;
12622
12623 while (k < met->npl) { /* Check if there is an inversion at level k... */
12624 if ((met->pl[i][j][k - 1] <= met->pl[i][j][k])) {
12625
12626 /* Find the upper level k+l over the inversion... */
12627 int l = 0;
12628 do {
12629 l++;
12630 }
12631 while ((met->pl[i][j][k - 1] <= met->pl[i][j][k + l]) & (k + l <
12632 met->npl));
12633
12634 /* Interpolate linear between the top and bottom
12635 of the inversion... */
12636 float s = (float) (met->pl[i][j][k + l] - met->pl[i][j][k - 1])
12637 / (float) (met->hybrid[k + l] - met->hybrid[k - 1]);
12638
12639 for (int m = k; m < k + l; m++) {
12640 float d = (float) (met->hybrid[m] - met->hybrid[k - 1]);
12641 met->pl[i][j][m] = s * d + met->pl[i][j][k - 1];
12642 }
12643
12644 /* Search for more inversions above the last inversion ... */
12645 k += l;
12646 } else {
12647 k++;
12648 }
12649 }
12650 }
12651}
double hybrid[EP]
Model hybrid levels.
Definition mptrac.h:3982

◆ read_met_nc()

int read_met_nc ( const char * filename,
const ctl_t * ctl,
met_t * met,
dd_t * dd,
int * pv_supplied )

Reads meteorological data from a NetCDF file and processes it.

This function reads meteorological data from a NetCDF file specified by the filename parameter, using the NetCDF library. It reads grid, surface, and vertical level data, processes the data (including extrapolation, boundary conditions, and downsampling), and calculates various derived meteorological fields such as geopotential heights, potential vorticity, cloud properties, and convective available potential energy (CAPE).

Parameters
filenameA constant character pointer representing the name of the NetCDF file to read the meteorological data from.
ctlA pointer to a ctl_t structure, which contains control parameters for reading and processing the meteorological data.
metA pointer to a met_t structure that will store the meteorological data read and processed from the NetCDF file.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.
pv_suppliedSet to one when the input contains a PV field, or zero otherwise.
Returns
Returns 1 on success, or 0 if the file cannot be opened.
Note
  • The function opens the NetCDF file in read-only mode using nc_open and handles any errors during the file opening process.
  • The function reads grid data, vertical level data, and surface data from the file, and processes the data to calculate additional meteorological parameters.
  • If the file cannot be opened, the function logs a warning and returns 0.
  • It is important to ensure that the NetCDF file contains the expected structure for meteorological data (grid, levels, surface data).
Author
Lars Hoffmann

Definition at line 12655 of file mptrac.c.

12660 {
12661
12662 int ncid = 0;
12663 int have_ncid = 0;
12664
12665 /* With domain decomposition, all tasks collectively open the file in
12666 parallel mode and each task reads its own subdomain... */
12667#ifdef DD
12668 if (ctl->dd) {
12669 NC(nc_open_par
12670 (filename, NC_NOWRITE | NC_SHARE, MPI_COMM_WORLD, MPI_INFO_NULL,
12671 &ncid));
12672 have_ncid = 1;
12673 }
12674#endif
12675
12676 /* Without domain decomposition, the file is opened in serial mode... */
12677 if (!have_ncid && nc_open(filename, NC_NOWRITE, &ncid) != NC_NOERR) {
12678 WARN("Cannot open file!");
12679 return 0;
12680 }
12681
12682 /* Set coordinate system of meteo data... */
12683 met->coord_type = ctl->met_coord_type;
12684
12685 /* Read coordinates of meteo data... */
12686 read_met_nc_grid(filename, ncid, ctl, met, dd);
12687
12688 /* Setup for global read mode happens under the general input timer... */
12689 SELECT_TIMER("GET_MET", "INPUT");
12690#ifdef DD
12691 if (ctl->dd && ctl->met_nc_read_mode == 1)
12692 met_global_2d_init(dd, met);
12693#endif
12694
12695 /* Read surface data... */
12696 read_met_nc_surface(ncid, ctl, met, dd);
12697
12698 /* Read meteo data on vertical levels... */
12699 *pv_supplied = read_met_nc_levels(ncid, ctl, met, dd);
12700
12701 /* The remaining work happens under the general input timer... */
12702 SELECT_TIMER("GET_MET", "INPUT");
12703
12704#ifdef DD
12705 if (ctl->dd && ctl->met_nc_read_mode == 1)
12706 met_global_2d_free();
12707#endif
12708
12709 /* Close file... */
12710 NC(nc_close(ncid));
12711
12712 /* Return success... */
12713 return 1;
12714}
void read_met_nc_surface(const int ncid, const ctl_t *ctl, met_t *met, dd_t *dd)
Reads and processes surface meteorological data from NetCDF files with domain decomposition.
Definition mptrac.c:10843
void read_met_nc_grid(const char *filename, const int ncid, const ctl_t *ctl, met_t *met, dd_t *dd)
Reads meteorological grid data from NetCDF files with domain decomposition.
Definition mptrac.c:10656
int read_met_nc_levels(const int ncid, const ctl_t *ctl, met_t *met, dd_t *dd)
Reads and processes meteorological level data from NetCDF files with domain decomposition.
Definition mptrac.c:11000
Here is the call graph for this function:

◆ read_met_nc_grid()

void read_met_nc_grid ( const char * filename,
const int ncid,
const ctl_t * ctl,
met_t * met,
dd_t * dd )

Reads meteorological grid data from NetCDF files with domain decomposition.

The read_met_nc_grid function reads meteorological data from NetCDF files and processes it with domain decomposition for parallel processing. It extracts time information, grid dimensions, and coordinates, and sets up hyperslabs for subdomains and halos. It also reads pressure levels and handles model level and surface data.

Parameters
filenameA string representing the filename of the NetCDF file to read.
ncidA NetCDF file ID.
ctlA pointer to a ctl_t structure containing control parameters.
metA pointer to a met_t structure where meteorological data will be stored.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.

The function performs the following steps:

  • Sets filenames for meteorological data files.
  • Extracts time information from the filename or NetCDF file.
  • Validates the time information and logs it.
  • Retrieves global and local grid dimensions and checks for regular grid spacing.
  • Sets up hyperslabs for subdomains and halos, considering edge cases.
  • Adjusts grid dimensions and coordinates for subdomains and halos.
  • Reads pressure levels and computes the 3D pressure field.
  • Handles model level and surface data using GRIB handles.
  • Reads grid data and surface data from the respective files.
  • Computes the 3D pressure field and reads model level data.
Note
This function assumes that the input filename and structures are properly initialized. It uses MPI for parallel processing and handles domain decomposition. The function is designed to work with NetCDF and GRIB file formats. It logs various stages of processing for debugging and validation purposes.
Author
Lars Hoffmann
Jan Clemens

Definition at line 10656 of file mptrac.c.

10661 {
10662
10663 char levname[LEN], tstr[10];
10664
10665 double rtime = 0, r, r2;
10666
10667 int varid, ndims, dimids[NC_MAX_DIMS], year2, mon2, day2, hour2, min2, sec2,
10668 year, mon, day, hour, min, sec;
10669
10670 size_t dimlen;
10671
10672 /* Set timer... */
10673 SELECT_TIMER("READ_MET_NC_GRID", "INPUT");
10674 LOG(2, "Read meteo grid information...");
10675
10676 /* MPTRAC meteo files... */
10677 if (!ctl->met_clams) {
10678
10679 /* Get time from filename... */
10680 met->time = time_from_filename(filename, 16, 0);
10681
10682 /* Check time information from data file... */
10683 jsec2time(met->time, &year, &mon, &day, &hour, &min, &sec, &r);
10684 if (nc_inq_varid(ncid, "time", &varid) == NC_NOERR) {
10685 NC(nc_get_var_double(ncid, varid, &rtime));
10686 if (fabs(year * 10000. + mon * 100. + day + hour / 24. - rtime) > 1.0)
10687 WARN("Time information in meteo file does not match filename!");
10688 } else
10689 WARN("Time information in meteo file is missing!");
10690 }
10691
10692 /* CLaMS meteo files... */
10693 else {
10694
10695 /* Read time from file... */
10696 NC_GET_DOUBLE("time", &rtime, 0);
10697
10698 /* Get time from filename (considering the century)... */
10699 if (rtime < 0)
10700 sprintf(tstr, "19%.2s", &filename[strlen(filename) - 11]);
10701 else
10702 sprintf(tstr, "20%.2s", &filename[strlen(filename) - 11]);
10703 year = atoi(tstr);
10704 sprintf(tstr, "%.2s", &filename[strlen(filename) - 9]);
10705 mon = atoi(tstr);
10706 sprintf(tstr, "%.2s", &filename[strlen(filename) - 7]);
10707 day = atoi(tstr);
10708 sprintf(tstr, "%.2s", &filename[strlen(filename) - 5]);
10709 hour = atoi(tstr);
10710 time2jsec(year, mon, day, hour, 0, 0, 0, &met->time);
10711 }
10712
10713 /* Check time... */
10714 if (year < 1900 || year > 2100 || mon < 1 || mon > 12
10715 || day < 1 || day > 31 || hour < 0 || hour > 23)
10716 ERRMSG("Cannot read time from filename!");
10717 jsec2time(met->time, &year2, &mon2, &day2, &hour2, &min2, &sec2, &r2);
10718 LOG(2, "Time: %.2f (%d-%02d-%02d, %02d:%02d UTC)",
10719 met->time, year2, mon2, day2, hour2, min2);
10720
10721 /* Get vertical dimension... */
10722 if (nc_inq_varid(ncid, "u", &varid) != NC_NOERR)
10723 if (nc_inq_varid(ncid, "U", &varid) != NC_NOERR)
10724 ERRMSG
10725 ("Variable 'u' or 'U' not found, cannot determine vertical dimension!");
10726
10727 NC(nc_inq_varndims(ncid, varid, &ndims));
10728 NC(nc_inq_vardimid(ncid, varid, dimids));
10729
10730 if (ndims == 4) {
10731 NC(nc_inq_dim
10732 (ncid, dimids[ctl->met_convention == 0 ? 1 : 3], levname, &dimlen));
10733 } else if (ndims == 3) {
10734 NC(nc_inq_dim
10735 (ncid, dimids[ctl->met_convention == 0 ? 0 : 2], levname, &dimlen));
10736 } else
10737 ERRMSG("Cannot determine vertical dimension!");
10738 met->np = (int) dimlen;
10739
10740 LOG(2, "Number of levels: %d", met->np);
10741 if (met->np < 2 || met->np > EP)
10742 ERRMSG("Number of levels out of range!");
10743
10744 if (!ctl->dd) {
10745
10746 /* Get grid dimensions and coordinates... */
10747 if (met->coord_type == 0) {
10748 /* Longitude/latitude grid... */
10749 NC_INQ_DIM("lon", &met->nx, 2, EX, 1);
10750 LOG(2, "Number of longitudes: %d", met->nx);
10751
10752 NC_INQ_DIM("lat", &met->ny, 2, EY, 1);
10753 LOG(2, "Number of latitudes: %d", met->ny);
10754
10755 NC_GET_DOUBLE("lon", met->lon, 1);
10756 LOG(2, "Longitudes: %g, %g ... %g deg",
10757 met->lon[0], met->lon[1], met->lon[met->nx - 1]);
10758 NC_GET_DOUBLE("lat", met->lat, 1);
10759 LOG(2, "Latitudes: %g, %g ... %g deg",
10760 met->lat[0], met->lat[1], met->lat[met->ny - 1]);
10761
10762 } else {
10763 /* UTM grid... */
10764 NC_INQ_DIM("x", &met->nx, 2, EX, 1);
10765 LOG(2, "Number of x coordinates: %d", met->nx);
10766
10767 NC_INQ_DIM("y", &met->ny, 2, EY, 1);
10768 LOG(2, "Number of y coordinates: %d", met->ny);
10769
10770 NC_GET_DOUBLE("x", met->lon, 1);
10771 LOG(2, "X coordinates: %g, %g ... %g m",
10772 met->lon[0], met->lon[1], met->lon[met->nx - 1]);
10773 NC_GET_DOUBLE("y", met->lat, 1);
10774 LOG(2, "Y coordinates: %g, %g ... %g m",
10775 met->lat[0], met->lat[1], met->lat[met->ny - 1]);
10776 }
10777
10778 } else {
10779
10780 if (met->coord_type != 0)
10781 ERRMSG("Domain decomposition is only supported for lat/lon grids!");
10782
10783 /* Use equidistant lat-lon domain decomposition... */
10784 dd_read_met_nc_grid(dd, ctl, met, ncid);
10785
10786 }
10787
10788 /* Read pressure levels... */
10789 if (ctl->met_np <= 0) {
10790 NC_GET_DOUBLE(levname, met->p, 1);
10791 for (int ip = 0; ip < met->np; ip++)
10792 met->p[ip] /= 100.;
10793 LOG(2, "Altitude levels: %g, %g ... %g km",
10794 Z(met->p[0]), Z(met->p[1]), Z(met->p[met->np - 1]));
10795 LOG(2, "Pressure levels: %g, %g ... %g hPa",
10796 met->p[0], met->p[1], met->p[met->np - 1]);
10797 }
10798
10799 /* Read hybrid levels... */
10800 if (strcasecmp(levname, "hybrid") == 0)
10801 NC_GET_DOUBLE("hybrid", met->hybrid, 1);
10802
10803 /* Read model level coefficients from file... */
10804 if (ctl->met_vert_coord == 2) {
10805 NC_GET_DOUBLE("hyam", met->hyam, 1);
10806 NC_GET_DOUBLE("hybm", met->hybm, 1);
10807 }
10808
10809 /* Copy model level coefficients from control parameters... */
10810 else if (ctl->met_vert_coord == 3 || ctl->met_vert_coord == 4) {
10811 if (ctl->met_nlev <= 0)
10812 ERRMSG("You need to specify MET_NLEV, MET_LEV_HYAM, and MET_LEV_HYBM!");
10813 for (int ip = 0; ip < ctl->met_nlev; ip++) {
10814 met->hyam[ip] = ctl->met_lev_hyam[ip];
10815 met->hybm[ip] = ctl->met_lev_hybm[ip];
10816 }
10817 }
10818
10819 /* Calculate eta levels... */
10820 for (int k = 0; k < MAX(met->np, ctl->met_nlev); ++k) {
10821 met->eta[k] = met->hyam[k] / (100.0 * P0) + met->hybm[k];
10822 if (ctl->met_vert_coord >= 2 && k > 0 && met->eta[k] <= met->eta[k - 1])
10823 ERRMSG("Eta levels must be ascending!");
10824 }
10825
10826 /* Check horizontal grid spacing... */
10827 for (int ix = 2; ix < met->nx; ix++)
10828 if (fabs
10829 (fabs(met->lon[ix] - met->lon[ix - 1]) -
10830 fabs(met->lon[1] - met->lon[0])) > 0.001)
10831 ERRMSG("No regular grid spacing in longitudes!");
10832 for (int iy = 2; iy < met->ny; iy++)
10833 if (fabs
10834 (fabs(met->lat[iy] - met->lat[iy - 1]) -
10835 fabs(met->lat[1] - met->lat[0])) > 0.001) {
10836 WARN("No regular grid spacing in latitudes!");
10837 break;
10838 }
10839}
void dd_read_met_nc_grid(dd_t *dd, const ctl_t *ctl, met_t *met, const int ncid)
Read meteorological grid information and construct the domain-decomposed grid with halo regions.
Definition mptrac.c:12718
void time2jsec(const int year, const int mon, const int day, const int hour, const int min, const int sec, const double remain, double *jsec)
Converts time components to seconds since January 1, 2000, 12:00:00 UTC.
Definition mptrac.c:13972
double time_from_filename(const char *filename, const int offset, const int with_seconds)
Extracts and converts a timestamp from a filename to Julian seconds.
Definition mptrac.c:14071
double eta[EP]
Model level eta values.
Definition mptrac.h:3991
double hyam[EP]
Model level a coefficients [Pa].
Definition mptrac.h:3985
double hybm[EP]
Model level b coefficients.
Definition mptrac.h:3988
Here is the call graph for this function:

◆ read_met_nc_levels()

int read_met_nc_levels ( const int ncid,
const ctl_t * ctl,
met_t * met,
dd_t * dd )

Reads and processes meteorological level data from NetCDF files with domain decomposition.

The read_met_nc_levels function reads meteorological level data from a NetCDF file and processes it for use in a domain decomposition context. It handles various meteorological parameters such as temperature, wind components, humidity, ozone, cloud data, and vertical velocity. The function also processes pressure levels and interpolates data between model and pressure levels as needed.

Parameters
ncidAn integer representing the NetCDF file ID.
ctlA pointer to a ctl_t structure containing control parameters and settings.
metA pointer to a met_t structure where meteorological level data will be stored.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.

The function performs the following steps:

  • Reads temperature, horizontal wind components, and vertical velocity data.
  • Processes water vapor data, handling both specific and relative humidity.
  • Reads ozone and various cloud-related data such as liquid water content, ice water content, and cloud cover.
  • Processes zeta and zeta_dot data.
  • Stores velocities on model levels and saves the number of model levels.
  • Computes pressure on model levels using different methods based on control parameters.
  • Checks the ordering of pressure levels to ensure they are monotonic.
  • Interpolates meteorological variables from model levels to pressure levels if specified.
  • Validates the ordering of pressure levels to ensure they are in descending order.
Returns
One when the input contains a PV field, or zero otherwise.
Note
This function assumes that the NetCDF file ID and structures are properly initialized. It is designed to work with NetCDF files and uses OpenMP for parallel processing. The function logs errors and warnings for missing or unreadable data fields and handles different data formats.
Author
Lars Hoffmann
Jan Clemens

Definition at line 11000 of file mptrac.c.

11004 {
11005
11006 /* Set timer... */
11007 SELECT_TIMER("READ_MET_NC_LEVELS", "INPUT");
11008 LOG(2, "Read level data...");
11009
11010 /* Read temperature... */
11011 if (!read_met_nc_3d
11012 (ncid, (const char *const[]) { "t", "T", "temp", "TEMP" }, 4, ctl, met,
11013 dd, met->t, 1.0))
11014 ERRMSG("Cannot read temperature!");
11015
11016 /* Read horizontal wind and vertical velocity... */
11017 if (!read_met_nc_3d
11018 (ncid, (const char *const[]) { "u", "U" }, 2, ctl, met, dd, met->u,
11019 1.0))
11020 ERRMSG("Cannot read zonal wind!");
11021 if (!read_met_nc_3d
11022 (ncid, (const char *const[]) { "v", "V" }, 2, ctl, met, dd, met->v,
11023 1.0))
11024 ERRMSG("Cannot read meridional wind!");
11025 if (!read_met_nc_3d
11026 (ncid, (const char *const[]) { "w", "W", "omega", "OMEGA" }, 4, ctl,
11027 met, dd, met->w, 0.01f))
11028 WARN("Cannot read vertical velocity!");
11029
11030 /* Read water vapor... */
11031 if (!ctl->met_relhum) {
11032 if (!read_met_nc_3d
11033 (ncid, (const char *const[]) { "q", "Q", "sh", "SH" }, 4, ctl, met,
11034 dd, met->h2o,
11035 (float) (MA / MH2O)))
11036 WARN("Cannot read specific humidity!");
11037 } else {
11038 if (!read_met_nc_3d
11039 (ncid, (const char *const[]) { "rh", "RH" }, 2, ctl, met, dd,
11040 met->h2o, 0.01f))
11041 WARN("Cannot read relative humidity!");
11042#pragma omp parallel for default(shared) collapse(2)
11043 for (int ix = 0; ix < met->nx; ix++)
11044 for (int iy = 0; iy < met->ny; iy++)
11045 for (int ip = 0; ip < met->np; ip++) {
11046 double pw = met->h2o[ix][iy][ip] * PSAT(met->t[ix][iy][ip]);
11047 met->h2o[ix][iy][ip] =
11048 (float) (pw / (met->p[ip] - (1.0 - EPS) * pw));
11049 }
11050 }
11051
11052 /* Read optional potential vorticity in PVU... */
11053 const int pv_supplied = read_met_nc_3d
11054 (ncid, (const char *const[]) { "pv", "PV" }, 2, ctl, met, dd,
11055 met->pv, 1.0);
11056
11057 /* Read ozone... */
11058 if (!read_met_nc_3d
11059 (ncid, (const char *const[]) { "o3", "O3" }, 2, ctl, met, dd, met->o3,
11060 (float) (MA / MO3)))
11061 WARN("Cannot read ozone data!");
11062
11063 /* Read cloud data... */
11064 if (!read_met_nc_3d
11065 (ncid, (const char *const[]) { "clwc", "CLWC" }, 2, ctl, met, dd,
11066 met->lwc, 1.0))
11067 WARN("Cannot read cloud liquid water content!");
11068 if (!read_met_nc_3d
11069 (ncid, (const char *const[]) { "crwc", "CRWC" }, 2, ctl, met, dd,
11070 met->rwc, 1.0))
11071 WARN("Cannot read cloud rain water content!");
11072 if (!read_met_nc_3d
11073 (ncid, (const char *const[]) { "ciwc", "CIWC" }, 2, ctl, met, dd,
11074 met->iwc, 1.0))
11075 WARN("Cannot read cloud ice water content!");
11076 if (!read_met_nc_3d
11077 (ncid, (const char *const[]) { "cswc", "CSWC" }, 2, ctl, met, dd,
11078 met->swc, 1.0))
11079 WARN("Cannot read cloud snow water content!");
11080 if (!read_met_nc_3d
11081 (ncid, (const char *const[]) { "cc", "CC" }, 2, ctl, met, dd, met->cc,
11082 1.0))
11083 WARN("Cannot read cloud cover!");
11084
11085 /* Read zeta and zeta_dot... */
11086 if (ctl->advect_vert_coord == 1) {
11087 if (!read_met_nc_3d
11088 (ncid, (const char *const[]) { "ZETA", "zeta" }, 2, ctl, met, dd,
11089 met->zetal, 1.0))
11090 WARN("Cannot read ZETA!");
11091 if (!read_met_nc_3d
11092 (ncid, (const char *const[]) { "ZETA_DOT_TOT", "ZETA_DOT_clr",
11093 "zeta_dot_clr"
11094 }, 3, ctl, met, dd, met->zeta_dotl, 0.00001157407f))
11095 ERRMSG("Cannot read ZETA_DOT!");
11096 }
11097
11098 /* Set eta coordinate on native model levels... */
11099 if (ctl->advect_vert_coord == 3 || ctl->qnt_eta_d >= 0) {
11100#pragma omp parallel for default(shared)
11101 for (int ix = 0; ix < met->nx; ix++)
11102 for (int iy = 0; iy < met->ny; iy++)
11103 for (int ip = 0; ip < met->np; ip++)
11104 met->zetal[ix][iy][ip] =
11105 (float) (met->hyam[ip] / (100.0 * P0) + met->hybm[ip]);
11106 }
11107
11108 /* Read eta_dot... */
11109 if (ctl->advect_vert_coord == 3)
11110 if (!read_met_nc_3d
11111 (ncid, (const char *const[]) { "etadot", "ETADOT" }, 2, ctl, met, dd,
11112 met->zeta_dotl,
11113 1.0))
11114 ERRMSG("Cannot read eta vertical velocity!");
11115
11116 /* Store velocities on model levels... */
11117 if (ctl->met_vert_coord != 0) {
11118#pragma omp parallel for default(shared)
11119 for (int ix = 0; ix < met->nx; ix++)
11120 for (int iy = 0; iy < met->ny; iy++)
11121 for (int ip = 0; ip < met->np; ip++) {
11122 met->ul[ix][iy][ip] = met->u[ix][iy][ip];
11123 met->vl[ix][iy][ip] = met->v[ix][iy][ip];
11124 met->wl[ix][iy][ip] = met->w[ix][iy][ip];
11125 }
11126
11127 /* Save number of model levels... */
11128 met->npl = met->np;
11129 }
11130
11131 /* Get pressure on model levels... */
11132 if (ctl->met_np > 0 || ctl->met_vert_coord != 0) {
11133
11134 /* Read 3-D pressure field... */
11135 if (ctl->met_vert_coord == 1) {
11136 if (!read_met_nc_3d
11137 (ncid, (const char *const[]) { "pl", "PL", "pressure", "PRESSURE" },
11138 4, ctl, met, dd, met->pl,
11139 0.01f))
11140 if (!read_met_nc_3d
11141 (ncid, (const char *const[]) { "press", "PRESS" }, 2, ctl, met,
11142 dd, met->pl, 1.0))
11143 ERRMSG("Cannot read pressure on model levels!");
11144 }
11145
11146 /* Use a and b coefficients for full levels (at layer midpoints)... */
11147 else if (ctl->met_vert_coord == 2 || ctl->met_vert_coord == 3) {
11148
11149 /* Check number of levels... */
11150 if (ctl->met_vert_coord == 3 && met->np != ctl->met_nlev)
11151 ERRMSG("Mismatch in number of model levels!");
11152
11153 /* Calculate pressure... */
11154 for (int ix = 0; ix < met->nx; ix++)
11155 for (int iy = 0; iy < met->ny; iy++)
11156 for (int ip = 0; ip < met->np; ip++)
11157 met->pl[ix][iy][ip] =
11158 (float) (met->hyam[ip] / 100. +
11159 met->hybm[ip] * met->ps[ix][iy]);
11160 }
11161
11162 /* Use a and b coefficients for half levels (at layer interfaces)... */
11163 else if (ctl->met_vert_coord == 4) {
11164
11165 /* Check number of levels... */
11166 if (met->np + 1 != ctl->met_nlev)
11167 ERRMSG("Mismatch in number of model levels!");
11168
11169 /* Calculate pressure... */
11170#pragma omp parallel for default(shared) collapse(2)
11171 for (int ix = 0; ix < met->nx; ix++)
11172 for (int iy = 0; iy < met->ny; iy++)
11173 for (int ip = 0; ip < met->np; ip++) {
11174 const double p0 =
11175 met->hyam[ip] / 100. + met->hybm[ip] * met->ps[ix][iy];
11176 const double p1 =
11177 met->hyam[ip + 1] / 100. + met->hybm[ip + 1] * met->ps[ix][iy];
11178 met->pl[ix][iy][ip] = (float) ((p1 - p0) / log(p1 / p0));
11179 }
11180 }
11181
11182 /* Check ordering of pressure levels... */
11183 for (int ix = 0; ix < met->nx; ix++)
11184 for (int iy = 0; iy < met->ny; iy++)
11185 for (int ip = 1; ip < met->np; ip++)
11186 if ((met->pl[ix][iy][0] > met->pl[ix][iy][1]
11187 && met->pl[ix][iy][ip - 1] <= met->pl[ix][iy][ip])
11188 || (met->pl[ix][iy][0] < met->pl[ix][iy][1]
11189 && met->pl[ix][iy][ip - 1] >= met->pl[ix][iy][ip]))
11190 ERRMSG("Pressure profiles are not monotonic!");
11191 }
11192
11193 /* Interpolate from model levels to pressure levels... */
11194 if (ctl->met_np > 0) {
11195
11196 /* Interpolate variables... */
11197 read_met_ml2pl(ctl, met, met->t, "T");
11198 read_met_ml2pl(ctl, met, met->u, "U");
11199 read_met_ml2pl(ctl, met, met->v, "V");
11200 read_met_ml2pl(ctl, met, met->w, "W");
11201 read_met_ml2pl(ctl, met, met->h2o, "H2O");
11202 if (pv_supplied)
11203 read_met_ml2pl(ctl, met, met->pv, "PV");
11204 read_met_ml2pl(ctl, met, met->o3, "O3");
11205 read_met_ml2pl(ctl, met, met->lwc, "LWC");
11206 read_met_ml2pl(ctl, met, met->rwc, "RWC");
11207 read_met_ml2pl(ctl, met, met->iwc, "IWC");
11208 read_met_ml2pl(ctl, met, met->swc, "SWC");
11209 read_met_ml2pl(ctl, met, met->cc, "CC");
11210
11211 /* Set new pressure levels... */
11212 met->np = ctl->met_np;
11213 for (int ip = 0; ip < met->np; ip++)
11214 met->p[ip] = ctl->met_p[ip];
11215 }
11216
11217 /* Check ordering of pressure levels... */
11218 for (int ip = 1; ip < met->np; ip++)
11219 if (met->p[ip - 1] < met->p[ip])
11220 ERRMSG("Pressure levels must be descending!");
11221
11222 return pv_supplied;
11223}
void read_met_ml2pl(const ctl_t *ctl, const met_t *met, float var[EX][EY][EP], const char *varname)
Interpolates meteorological data to specified pressure levels.
Definition mptrac.c:12528
int read_met_nc_3d(const int ncid, const char *const varnames[], const size_t nvarnames, const ctl_t *ctl, const met_t *met, dd_t *dd, float dest[EX][EY][EP], const float scl)
Reads a 3-dimensional meteorological variable from a NetCDF file.
Definition mptrac.c:11754
#define MH2O
Molar mass of water vapor [g/mol].
Definition mptrac.h:295
#define MO3
Molar mass of ozone [g/mol].
Definition mptrac.h:300
Here is the call graph for this function:

◆ read_met_nc_surface()

void read_met_nc_surface ( const int ncid,
const ctl_t * ctl,
met_t * met,
dd_t * dd )

Reads and processes surface meteorological data from NetCDF files with domain decomposition.

The read_met_nc_surface function reads surface meteorological data from a NetCDF file and processes it for use in a domain decomposition context. It handles various surface parameters such as pressure, geopotential height, temperature, wind components, and other relevant meteorological data. The function is designed to work with different meteorological data formats and configurations.

Parameters
ncidAn integer representing the NetCDF file ID.
ctlA pointer to a ctl_t structure containing control parameters and settings.
metA pointer to a met_t structure where surface meteorological data will be stored.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.

The function performs the following steps:

  • Reads surface pressure data and converts it if necessary.
  • Handles different data formats for MPTRAC and CLaMS meteorological data.
  • Reads geopotential height at the surface and processes it based on the data format.
  • Optionally converts zm surface geopotential data from m^2 s^-2 to km when MET_GP2Z = 1.
  • Retrieves surface temperature, zonal and meridional wind, and other surface parameters.
  • Logs warnings if specific data fields cannot be read.
  • Uses helper functions to read 2D and 3D data fields from the NetCDF file.
  • Processes and stores the read data into the provided meteorological data structure.
Note
This function assumes that the NetCDF file ID and structures are properly initialized. It is designed to work with NetCDF files and uses MPI for parallel processing. The function logs warnings for missing or unreadable data fields and handles different data formats.
Author
Lars Hoffmann
Jan Clemens

Definition at line 10843 of file mptrac.c.

10847 {
10848
10849 /* Set timer... */
10850 SELECT_TIMER("READ_MET_SURFACE", "INPUT");
10851 LOG(2, "Read surface data...");
10852
10853 /* Read surface pressure... */
10854 if (read_met_nc_2d
10855 (ncid, (const char *const[]) { "lnsp", "LNSP" }, 2, ctl, met, dd,
10856 met->ps,
10857 1.0f, 1)) {
10858 for (int ix = 0; ix < met->nx; ix++)
10859 for (int iy = 0; iy < met->ny; iy++)
10860 met->ps[ix][iy] = (float) (exp(met->ps[ix][iy]) / 100.);
10861 } else
10862 if (!read_met_nc_2d
10863 (ncid, (const char *const[]) { "ps", "PS", "sp", "SP" }, 4, ctl, met,
10864 dd, met->ps,
10865 0.01f, 1)) {
10866 WARN("Cannot not read surface pressure data (use lowest level)!");
10867 for (int ix = 0; ix < met->nx; ix++)
10868 for (int iy = 0; iy < met->ny; iy++)
10869 met->ps[ix][iy]
10870 = (ctl->met_np > 0 ? (float) ctl->met_p[0] : (float) met->p[0]);
10871 }
10872
10873 /* MPTRAC meteo data... */
10874 if (ctl->met_clams == 0) {
10875
10876 /* Read geopotential height at the surface... */
10877 if (!read_met_nc_2d
10878 (ncid, (const char *const[]) { "z", "Z" }, 2, ctl, met, dd, met->zs,
10879 (float) (1. / (1000. * G0)), 1))
10880 if (!read_met_nc_2d
10881 (ncid, (const char *const[]) { "zm", "ZM" }, 2, ctl, met, dd,
10882 met->zs,
10883 (ctl->met_gp2z ? (float) (1e-3 / G0) : (float) (1. / 1000.)), 1))
10884 WARN("Cannot read surface geopotential height!");
10885 }
10886
10887 /* CLaMS meteo data... */
10888 else {
10889
10890 /* Read geopotential height at the surface
10891 (use lowermost level of 3-D data field)... */
10892 float *help;
10893 ALLOC(help, float,
10894 EX * EY * EP);
10895 memcpy(help, met->pl, sizeof(met->pl));
10896 if (!read_met_nc_3d
10897 (ncid, (const char *const[]) { "gph", "GPH" }, 2, ctl, met, dd,
10898 met->pl,
10899 (float) (1e-3 / G0)))
10900 ERRMSG("Cannot read geopotential height!");
10901 /* read_met_nc_3d hands back the levels timer... */
10902 SELECT_TIMER("READ_MET_SURFACE", "INPUT");
10903 for (int ix = 0; ix < met->nx; ix++)
10904 for (int iy = 0; iy < met->ny; iy++)
10905 met->zs[ix][iy] = met->pl[ix][iy][0];
10906 memcpy(met->pl, help, sizeof(met->pl));
10907 free(help);
10908 }
10909
10910 /* Read temperature at the surface... */
10911 if (!read_met_nc_2d
10912 (ncid, (const char *const[]) { "t2m", "T2M", "2t", "2T", "t2", "T2" },
10913 6, ctl, met, dd, met->ts, 1.0,
10914 1))
10915 WARN("Cannot read surface temperature!");
10916
10917 /* Read zonal wind at the surface... */
10918 if (!read_met_nc_2d
10919 (ncid, (const char *const[]) { "u10m", "U10M", "10u", "10U", "u10",
10920 "U10"
10921 }, 6, ctl, met, dd,
10922 met->us, 1.0, 1))
10923 WARN("Cannot read surface zonal wind!");
10924
10925 /* Read meridional wind at the surface... */
10926 if (!read_met_nc_2d
10927 (ncid, (const char *const[]) { "v10m", "V10M", "10v", "10V", "v10",
10928 "V10"
10929 }, 6, ctl, met, dd,
10930 met->vs, 1.0, 1))
10931 WARN("Cannot read surface meridional wind!");
10932
10933 /* Read eastward turbulent surface stress... */
10934 if (!read_met_nc_2d
10935 (ncid, (const char *const[]) { "iews", "IEWS" }, 2, ctl, met, dd,
10936 met->ess,
10937 1.0, 1))
10938 WARN("Cannot read eastward turbulent surface stress!");
10939
10940 /* Read northward turbulent surface stress... */
10941 if (!read_met_nc_2d
10942 (ncid, (const char *const[]) { "inss", "INSS" }, 2, ctl, met, dd,
10943 met->nss,
10944 1.0, 1))
10945 WARN("Cannot read northward turbulent surface stress!");
10946
10947 /* Read surface sensible heat flux... */
10948 if (!read_met_nc_2d
10949 (ncid, (const char *const[]) { "ishf", "ISHF" }, 2, ctl, met, dd,
10950 met->shf,
10951 1.0, 1))
10952 WARN("Cannot read surface sensible heat flux!");
10953
10954 /* Read land-sea mask... */
10955 if (!read_met_nc_2d
10956 (ncid, (const char *const[]) { "lsm", "LSM" }, 2, ctl, met, dd,
10957 met->lsm,
10958 1.0, 1))
10959 WARN("Cannot read land-sea mask!");
10960
10961 /* Read sea surface temperature... */
10962 if (!read_met_nc_2d
10963 (ncid, (const char *const[]) { "sstk", "SSTK", "sst", "SST" }, 4, ctl,
10964 met, dd, met->sst,
10965 1.0, 1))
10966 WARN("Cannot read sea surface temperature!");
10967
10968 /* Read PBL... */
10969 if (ctl->met_pbl == 0)
10970 if (!read_met_nc_2d
10971 (ncid, (const char *const[]) { "blp", "BLP" }, 2, ctl, met, dd,
10972 met->pbl,
10973 0.01f, 1))
10974 WARN("Cannot read planetary boundary layer pressure!");
10975 if (ctl->met_pbl == 1)
10976 if (!read_met_nc_2d
10977 (ncid, (const char *const[]) { "blh", "BLH" }, 2, ctl, met, dd,
10978 met->pbl,
10979 0.001f, 1))
10980 WARN("Cannot read planetary boundary layer height!");
10981
10982 /* Read CAPE... */
10983 if (ctl->met_cape == 0)
10984 if (!read_met_nc_2d
10985 (ncid, (const char *const[]) { "cape", "CAPE" }, 2, ctl, met, dd,
10986 met->cape, 1.0, 1))
10987 WARN("Cannot read CAPE!");
10988
10989 /* Read CIN... */
10990 if (ctl->met_cape == 0)
10991 if (!read_met_nc_2d
10992 (ncid, (const char *const[]) { "cin", "CIN" }, 2, ctl, met, dd,
10993 met->cin,
10994 1.0, 1))
10995 WARN("Cannot read convective inhibition!");
10996}
int read_met_nc_2d(const int ncid, const char *const varnames[], const size_t nvarnames, const ctl_t *ctl, const met_t *met, dd_t *dd, float dest[EX][EY], const float scl, const int init)
Reads a 2-dimensional meteorological variable from a NetCDF file.
Definition mptrac.c:11416
Here is the call graph for this function:

◆ read_met_nc_2d()

int read_met_nc_2d ( const int ncid,
const char *const varnames[],
const size_t nvarnames,
const ctl_t * ctl,
const met_t * met,
dd_t * dd,
float dest[EX][EY],
const float scl,
const int init )

Reads a 2-dimensional meteorological variable from a NetCDF file.

This function reads a 2-dimensional meteorological variable from a NetCDF file and stores it in a specified destination array. It supports both packed and unpacked data formats and handles missing values and scaling factors accordingly. The function also checks the meteorological data layout to ensure correct data copying.

Parameters
ncidThe NetCDF file ID.
varnamesArray of variable names in order of preference.
nvarnamesNumber of entries in varnames.
ctlA pointer to a structure containing control parameters.
metA pointer to a structure containing meteorological data.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.
destThe destination array to store the read data.
sclA scaling factor to apply to the read data.
initFlag indicating whether to initialize the destination array before reading.
Returns
Returns 1 on success, 0 on failure.

The function performs the following steps:

  • Checks if the specified variable exists in the NetCDF file.
  • Reads packed data if scaling factors are available, otherwise reads unpacked data.
  • Handles missing values and scaling factors appropriately.
  • Copies the data to the destination array, applying the scaling factor if provided.
Author
Lars Hoffmann

Definition at line 11416 of file mptrac.c.

11425 {
11426
11427 const char *varsel = NULL;
11428
11429 float offset, scalfac;
11430
11431 int varid;
11432
11433 /* Check if variable exists... */
11434 for (size_t i = 0; i < nvarnames; i++)
11435 if (nc_inq_varid(ncid, varnames[i], &varid) == NC_NOERR) {
11436 varsel = varnames[i];
11437 break;
11438 }
11439 if (varsel == NULL)
11440 return 0;
11441
11442 /* Read packed data... */
11443 if (ctl->met_nc_scale && !ctl->dd
11444 && nc_get_att_float(ncid, varid, "add_offset", &offset) == NC_NOERR
11445 && nc_get_att_float(ncid, varid, "scale_factor",
11446 &scalfac) == NC_NOERR) {
11447
11448 /* Allocate... */
11449 short *help;
11450 ALLOC(help, short,
11451 EX * EY * EP);
11452
11453 /* Read fill value and missing value... */
11454 short fillval, missval;
11455 if (nc_get_att_short(ncid, varid, "_FillValue", &fillval) != NC_NOERR)
11456 fillval = 0;
11457 if (nc_get_att_short(ncid, varid, "missing_value", &missval) != NC_NOERR)
11458 missval = 0;
11459
11460 /* Write info... */
11461 LOG(2, "Read 2-D variable: %s"
11462 " (FILL = %d, MISS = %d, SCALE = %g, OFFSET = %g)",
11463 varsel, fillval, missval, scalfac, offset);
11464
11465 /* Read data... */
11466 NC(nc_get_var_short(ncid, varid, help));
11467
11468 /* Check meteo data layout... */
11469 if (ctl->met_convention != 0)
11470 ERRMSG("Meteo data layout not implemented for packed netCDF files!");
11471
11472 /* Copy and check data... */
11473 omp_set_dynamic(1);
11474#pragma omp parallel for default(shared)
11475 for (int ix = 0; ix < met->nx; ix++)
11476 for (int iy = 0; iy < met->ny; iy++) {
11477 if (init)
11478 dest[ix][iy] = 0;
11479 const short aux = help[ARRAY_2D(iy, ix, met->nx)];
11480 if ((fillval == 0 || aux != fillval)
11481 && (missval == 0 || aux != missval)
11482 && fabsf(aux * scalfac + offset) < 1e14f)
11483 dest[ix][iy] += scl * (aux * scalfac + offset);
11484 else
11485 dest[ix][iy] = NAN;
11486 }
11487 omp_set_dynamic(0);
11488
11489 /* Free... */
11490 free(help);
11491 }
11492
11493 /* Unpacked data... */
11494 else if (!ctl->dd) {
11495
11496 /* Allocate... */
11497 float *help;
11498 ALLOC(help, float,
11499 EX * EY);
11500
11501 /* Read fill value and missing value... */
11502 float fillval, missval;
11503 if (nc_get_att_float(ncid, varid, "_FillValue", &fillval) != NC_NOERR)
11504 fillval = 0;
11505 if (nc_get_att_float(ncid, varid, "missing_value", &missval) != NC_NOERR)
11506 missval = 0;
11507
11508 /* Write info... */
11509 LOG(2, "Read 2-D variable: %s (FILL = %g, MISS = %g)",
11510 varsel, fillval, missval);
11511
11512 /* Read data... */
11513 NC(nc_get_var_float(ncid, varid, help));
11514
11515 /* Check meteo data layout... */
11516 if (ctl->met_convention == 0) {
11517
11518 /* Copy and check data (ordering: lat, lon)... */
11519 omp_set_dynamic(1);
11520#pragma omp parallel for default(shared)
11521 for (int ix = 0; ix < met->nx; ix++)
11522 for (int iy = 0; iy < met->ny; iy++) {
11523 if (init)
11524 dest[ix][iy] = 0;
11525 const float aux = help[ARRAY_2D(iy, ix, met->nx)];
11526 if ((fillval == 0 || aux != fillval)
11527 && (missval == 0 || aux != missval)
11528 && fabsf(aux) < 1e14f)
11529 dest[ix][iy] += scl * aux;
11530 else
11531 dest[ix][iy] = NAN;
11532 }
11533 omp_set_dynamic(0);
11534
11535 } else {
11536
11537 /* Copy and check data (ordering: lon, lat)... */
11538 omp_set_dynamic(1);
11539#pragma omp parallel for default(shared)
11540 for (int iy = 0; iy < met->ny; iy++)
11541 for (int ix = 0; ix < met->nx; ix++) {
11542 if (init)
11543 dest[ix][iy] = 0;
11544 const float aux = help[ARRAY_2D(ix, iy, met->ny)];
11545 if ((fillval == 0 || aux != fillval)
11546 && (missval == 0 || aux != missval)
11547 && fabsf(aux) < 1e14f)
11548 dest[ix][iy] += scl * aux;
11549 else
11550 dest[ix][iy] = NAN;
11551 }
11552 omp_set_dynamic(0);
11553 }
11554
11555 /* Free... */
11556 free(help);
11557 }
11558
11559 /* Domain decomposed data... */
11560 else {
11561
11562 /* Read fill value and missing value... */
11563 float fillval, missval;
11564 if (nc_get_att_float(ncid, varid, "_FillValue", &fillval) != NC_NOERR)
11565 fillval = 0;
11566 if (nc_get_att_float(ncid, varid, "missing_value", &missval) != NC_NOERR)
11567 missval = 0;
11568
11569 /* Write info... */
11570 LOG(2, "Read 2-D variable: %s (FILL = %g, MISS = %g)",
11571 varsel, fillval, missval);
11572
11573#ifdef DD
11574 if (ctl->met_nc_read_mode == 1) {
11575 met_global_2d_check_var(ncid, varid, 3, dd, 0);
11576 NC(nc_var_par_access(ncid, varid, NC_INDEPENDENT));
11577 const float *help = met_global_2d_read(ncid, varid, 3, varid, dd);
11578 SELECT_TIMER("MET_CONVERT", "INPUT");
11579 omp_set_dynamic(1);
11580#pragma omp parallel for default(shared)
11581 for (int iy = 0; iy < met->ny; iy++)
11582 for (int ix = 0; ix < met->nx; ix++) {
11583 const float aux = help[(size_t) iy * (size_t) met->nx + (size_t) ix];
11584 if (init)
11585 dest[ix][iy] = 0;
11586 if ((fillval == 0 || aux != fillval)
11587 && (missval == 0 || aux != missval) && fabsf(aux) < 1e14f)
11588 dest[ix][iy] += scl * aux;
11589 else
11590 dest[ix][iy] = NAN;
11591 }
11592 omp_set_dynamic(0);
11593 /* Return to the caller's timer (only called from read_met_nc_surface)... */
11594 SELECT_TIMER("READ_MET_SURFACE", "INPUT");
11595 return 1;
11596 }
11597#endif
11598
11599 /* Define hyperslab... */
11600 float *help;
11601 size_t help_subdomain_start[3];
11602 size_t help_subdomain_count[3];
11603
11604 help_subdomain_start[0] = 0;
11605 if (ctl->met_convention == 0) {
11606 help_subdomain_start[1] = dd->subdomain_start[2];
11607 help_subdomain_start[2] = dd->subdomain_start[3];
11608 } else {
11609 help_subdomain_start[1] = dd->subdomain_start[3];
11610 help_subdomain_start[2] = dd->subdomain_start[2];
11611 }
11612
11613 help_subdomain_count[0] = 1;
11614 if (ctl->met_convention == 0) {
11615 help_subdomain_count[1] = dd->subdomain_count[2]; //y
11616 help_subdomain_count[2] = dd->subdomain_count[3]; //x
11617 } else {
11618 help_subdomain_count[1] = dd->subdomain_count[3]; //x
11619 help_subdomain_count[2] = dd->subdomain_count[2]; //y
11620 }
11621
11622 ALLOC(help, float,
11623 (int) dd->subdomain_count[2] * (int) dd->subdomain_count[3]);
11624
11625 /* Read data... */
11626 SELECT_TIMER("MET_READ", "INPUT");
11627#ifdef DD
11628 nc_var_par_access(ncid, varid, NC_COLLECTIVE);
11629#endif
11630 NC(nc_get_vara_float
11631 (ncid, varid, help_subdomain_start, help_subdomain_count, help));
11632
11633 /* Read halos at boundaries... */
11634 size_t help_halo_bnd_start[3];
11635 size_t help_halo_bnd_count[3];
11636
11637 help_halo_bnd_start[0] = 0;
11638 if (ctl->met_convention == 0) {
11639 help_halo_bnd_start[1] = dd->halo_bnd_start[2];
11640 help_halo_bnd_start[2] = dd->halo_bnd_start[3];
11641 } else {
11642 help_halo_bnd_start[1] = dd->halo_bnd_start[3];
11643 help_halo_bnd_start[2] = dd->halo_bnd_start[2];
11644 }
11645
11646 help_halo_bnd_count[0] = 1;
11647 if (ctl->met_convention == 0) {
11648 help_halo_bnd_count[1] = dd->halo_bnd_count[2]; //y
11649 help_halo_bnd_count[2] = dd->halo_bnd_count[3]; //x
11650 } else {
11651 help_halo_bnd_count[1] = dd->halo_bnd_count[3]; //x
11652 help_halo_bnd_count[2] = dd->halo_bnd_count[2]; //y
11653 }
11654
11655 float *help_halo;
11656 ALLOC(help_halo, float,
11657 help_halo_bnd_count[1] * help_halo_bnd_count[2]);
11658
11659#ifdef DD
11660 nc_var_par_access(ncid, varid, NC_COLLECTIVE);
11661#endif
11662 NC(nc_get_vara_float
11663 (ncid, varid, help_halo_bnd_start, help_halo_bnd_count,
11664 help_halo));
11665
11666 SELECT_TIMER("MET_CONVERT", "INPUT");
11667
11668 /* Check meteo data layout... */
11669 if (ctl->met_convention == 0) {
11670
11671 /* Copy and check data (ordering: lat, lon)... */
11672 omp_set_dynamic(1);
11673#pragma omp parallel for default(shared)
11674 for (int ix = 0; ix < (int) help_subdomain_count[2]; ix++)
11675 for (int iy = 0; iy < (int) help_subdomain_count[1]; iy++) {
11676 if (init == 1)
11677 dest[ix + dd->halo_offset_start][iy] = 0;
11678 const float aux =
11679 help[ARRAY_2D(iy, ix, (int) help_subdomain_count[2])];
11680 if ((fillval == 0 || aux != fillval)
11681 && (missval == 0 || aux != missval)
11682 && fabsf(aux) < 1e14f) {
11683 dest[ix + dd->halo_offset_start][iy] += scl * aux;
11684 } else
11685 dest[ix + dd->halo_offset_start][iy] = NAN;
11686 }
11687
11688#pragma omp parallel for default(shared)
11689 for (int ix = 0; ix < (int) help_halo_bnd_count[2]; ix++)
11690 for (int iy = 0; iy < (int) help_halo_bnd_count[1]; iy++) {
11691 if (init == 1)
11692 dest[ix + dd->halo_offset_end][iy] = 0;
11693 const float aux =
11694 help_halo[ARRAY_2D(iy, ix, (int) help_halo_bnd_count[2])];
11695 if ((fillval == 0 || aux != fillval)
11696 && (missval == 0 || aux != missval)
11697 && fabsf(aux) < 1e14f)
11698 dest[ix + dd->halo_offset_end][iy] += scl * aux;
11699 else {
11700 dest[ix + dd->halo_offset_end][iy] = NAN;
11701 }
11702 }
11703 omp_set_dynamic(0);
11704
11705 } else {
11706
11707 /* Copy and check data (ordering: lon, lat)... */
11708 omp_set_dynamic(1);
11709#pragma omp parallel for default(shared)
11710 for (int ix = 0; ix < (int) help_subdomain_count[1]; ix++)
11711 for (int iy = 0; iy < (int) help_subdomain_count[2]; iy++) {
11712 if (init == 1)
11713 dest[ix + dd->halo_offset_start][iy] = 0;
11714 const float aux =
11715 help[ARRAY_2D(ix, iy, (int) help_subdomain_count[1])];
11716 if ((fillval == 0 || aux != fillval)
11717 && (missval == 0 || aux != missval)
11718 && fabsf(aux) < 1e14f)
11719 dest[ix + dd->halo_offset_start][iy] += scl * aux;
11720 else
11721 dest[ix + dd->halo_offset_start][iy] = NAN;
11722 }
11723
11724#pragma omp parallel for default(shared)
11725 for (int ix = 0; ix < (int) help_halo_bnd_count[1]; ix++)
11726 for (int iy = 0; iy < (int) help_halo_bnd_count[2]; iy++) {
11727 if (init == 1)
11728 dest[ix + dd->halo_offset_end][iy] = 0;
11729 const float aux =
11730 help_halo[ARRAY_2D(ix, iy, (int) help_halo_bnd_count[1])];
11731 if ((fillval == 0 || aux != fillval)
11732 && (missval == 0 || aux != missval)
11733 && fabsf(aux) < 1e14f)
11734 dest[ix + dd->halo_offset_end][iy] += scl * aux;
11735 else
11736 dest[ix + dd->halo_offset_end][iy] = NAN;
11737 }
11738 omp_set_dynamic(0);
11739 }
11740 /* Return to the caller's timer (only called from read_met_nc_surface)... */
11741 SELECT_TIMER("READ_MET_SURFACE", "INPUT");
11742
11743 /* Free... */
11744 free(help);
11745 free(help_halo);
11746 }
11747
11748 /* Return... */
11749 return 1;
11750}

◆ read_met_nc_3d()

int read_met_nc_3d ( const int ncid,
const char *const varnames[],
const size_t nvarnames,
const ctl_t * ctl,
const met_t * met,
dd_t * dd,
float dest[EX][EY][EP],
const float scl )

Reads a 3-dimensional meteorological variable from a NetCDF file.

This function reads a 3-dimensional meteorological variable from a NetCDF file and stores it in a specified destination array. It supports both packed and unpacked data formats and handles missing values and scaling factors accordingly. The function also checks the meteorological data layout to ensure correct data copying.

Parameters
ncidThe NetCDF file ID.
varnamesArray of variable names in order of preference.
nvarnamesNumber of entries in varnames.
ctlA pointer to a structure containing control parameters.
metA pointer to a structure containing meteorological data.
ddA pointer to an dd_t structure containing MPI information, including rank and neighbours.
destThe destination array to store the read data.
sclA scaling factor to apply to the read data.
Returns
Returns 1 on success, 0 on failure.

The function performs the following steps:

  • Checks if the specified variable exists in the NetCDF file.
  • Reads packed data if scaling factors are available, otherwise reads unpacked data.
  • Handles missing values and scaling factors appropriately.
  • Copies the data to the destination array, applying the scaling factor if provided.
Author
Lars Hoffmann

Definition at line 11754 of file mptrac.c.

11762 {
11763
11764 const char *varsel = NULL;
11765
11766 float offset, scalfac;
11767
11768 int varid;
11769
11770 /* Check if variable exists... */
11771 for (size_t i = 0; i < nvarnames; i++)
11772 if (nc_inq_varid(ncid, varnames[i], &varid) == NC_NOERR) {
11773 varsel = varnames[i];
11774 break;
11775 }
11776 if (varsel == NULL)
11777 return 0;
11778
11779 /* Read packed data... */
11780 if (ctl->met_nc_scale && !ctl->dd
11781 && nc_get_att_float(ncid, varid, "add_offset", &offset) == NC_NOERR
11782 && nc_get_att_float(ncid, varid, "scale_factor",
11783 &scalfac) == NC_NOERR) {
11784
11785 /* Allocate... */
11786 short *help;
11787 ALLOC(help, short,
11788 EX * EY * EP);
11789
11790 /* Read fill value and missing value... */
11791 short fillval, missval;
11792 if (nc_get_att_short(ncid, varid, "_FillValue", &fillval) != NC_NOERR)
11793 fillval = 0;
11794 if (nc_get_att_short(ncid, varid, "missing_value", &missval) != NC_NOERR)
11795 missval = 0;
11796
11797 /* Write info... */
11798 LOG(2, "Read 3-D variable: %s "
11799 "(FILL = %d, MISS = %d, SCALE = %g, OFFSET = %g)",
11800 varsel, fillval, missval, scalfac, offset);
11801
11802 /* Read data... */
11803 NC(nc_get_var_short(ncid, varid, help));
11804
11805 /* Check meteo data layout... */
11806 if (ctl->met_convention != 0)
11807 ERRMSG("Meteo data layout not implemented for packed netCDF files!");
11808
11809 /* Copy and check data... */
11810 omp_set_dynamic(1);
11811#pragma omp parallel for default(shared)
11812 for (int ix = 0; ix < met->nx; ix++)
11813 for (int iy = 0; iy < met->ny; iy++)
11814 for (int ip = 0; ip < met->np; ip++) {
11815 const short aux = help[ARRAY_3D(ip, iy, met->ny, ix, met->nx)];
11816 if ((fillval == 0 || aux != fillval)
11817 && (missval == 0 || aux != missval)
11818 && fabsf(aux * scalfac + offset) < 1e14f)
11819 dest[ix][iy][ip] = scl * (aux * scalfac + offset);
11820 else
11821 dest[ix][iy][ip] = NAN;
11822 }
11823 omp_set_dynamic(0);
11824
11825 /* Free... */
11826 free(help);
11827 }
11828
11829 /* Unpacked data... */
11830 else if (!ctl->dd) {
11831
11832 /* Allocate... */
11833 float *help;
11834 ALLOC(help, float,
11835 EX * EY * EP);
11836
11837 /* Read fill value and missing value... */
11838 float fillval, missval;
11839 if (nc_get_att_float(ncid, varid, "_FillValue", &fillval) != NC_NOERR)
11840 fillval = 0;
11841 if (nc_get_att_float(ncid, varid, "missing_value", &missval) != NC_NOERR)
11842 missval = 0;
11843
11844 /* Write info... */
11845 LOG(2, "Read 3-D variable: %s (FILL = %g, MISS = %g)",
11846 varsel, fillval, missval);
11847
11848 /* Read data... */
11849 NC(nc_get_var_float(ncid, varid, help));
11850
11851 /* Check meteo data layout... */
11852 if (ctl->met_convention == 0) {
11853
11854 /* Copy and check data (ordering: lev, lat, lon)... */
11855 omp_set_dynamic(1);
11856#pragma omp parallel for default(shared)
11857 for (int ix = 0; ix < met->nx; ix++)
11858 for (int iy = 0; iy < met->ny; iy++)
11859 for (int ip = 0; ip < met->np; ip++) {
11860 const float aux = help[ARRAY_3D(ip, iy, met->ny, ix, met->nx)];
11861 if ((fillval == 0 || aux != fillval)
11862 && (missval == 0 || aux != missval)
11863 && fabsf(aux) < 1e14f)
11864 dest[ix][iy][ip] = scl * aux;
11865 else
11866 dest[ix][iy][ip] = NAN;
11867 }
11868 omp_set_dynamic(0);
11869
11870 } else {
11871
11872 /* Copy and check data (ordering: lon, lat, lev)... */
11873 omp_set_dynamic(1);
11874#pragma omp parallel for default(shared)
11875 for (int ip = 0; ip < met->np; ip++)
11876 for (int iy = 0; iy < met->ny; iy++)
11877 for (int ix = 0; ix < met->nx; ix++) {
11878 const float aux = help[ARRAY_3D(ix, iy, met->ny, ip, met->np)];
11879 if ((fillval == 0 || aux != fillval)
11880 && (missval == 0 || aux != missval)
11881 && fabsf(aux) < 1e14f)
11882 dest[ix][iy][ip] = scl * aux;
11883 else
11884 dest[ix][iy][ip] = NAN;
11885 }
11886 omp_set_dynamic(0);
11887 }
11888
11889 /* Free... */
11890 free(help);
11891 }
11892
11893 /* Domain decomposed data... */
11894 else {
11895
11896 /* Read fill value and missing value... */
11897 float fillval, missval;
11898 if (nc_get_att_float(ncid, varid, "_FillValue", &fillval) != NC_NOERR)
11899 fillval = 0;
11900 if (nc_get_att_float(ncid, varid, "missing_value", &missval) != NC_NOERR)
11901 missval = 0;
11902
11903 /* Write info... */
11904 LOG(2, "Read 3-D variable: %s (FILL = %g, MISS = %g)",
11905 varsel, fillval, missval);
11906
11907#ifdef DD
11908 if (ctl->met_nc_read_mode == 1) {
11909 met_global_2d_check_var(ncid, varid, 4, dd, met->np);
11910 NC(nc_var_par_access(ncid, varid, NC_INDEPENDENT));
11911 for (int ip = 0; ip < met->np; ip++) {
11912 const float *help = met_global_2d_read(ncid, varid, 4, ip, dd);
11913 SELECT_TIMER("MET_CONVERT", "INPUT");
11914 omp_set_dynamic(1);
11915#pragma omp parallel for default(shared)
11916 for (int iy = 0; iy < met->ny; iy++)
11917 for (int ix = 0; ix < met->nx; ix++) {
11918 const float aux =
11919 help[(size_t) iy * (size_t) met->nx + (size_t) ix];
11920 if ((fillval == 0 || aux != fillval)
11921 && (missval == 0 || aux != missval) && fabsf(aux) < 1e14f)
11922 dest[ix][iy][ip] = scl * aux;
11923 else
11924 dest[ix][iy][ip] = NAN;
11925 }
11926 omp_set_dynamic(0);
11927 }
11928 /* Return to the caller's timer (only called from read_met_nc_levels)... */
11929 SELECT_TIMER("READ_MET_NC_LEVELS", "INPUT");
11930 return 1;
11931 }
11932#endif
11933
11934 /* Define hyperslab... */
11935 size_t help_subdomain_start[4];
11936 size_t help_subdomain_count[4];
11937 size_t help_halo_bnd_start[4];
11938 size_t help_halo_bnd_count[4];
11939
11940 if (ctl->met_convention == 0) {
11941 for (int i = 0; i < 4; i++) {
11942 help_subdomain_start[i] = dd->subdomain_start[i];
11943 help_subdomain_count[i] = dd->subdomain_count[i];
11944 help_halo_bnd_start[i] = dd->halo_bnd_start[i];
11945 help_halo_bnd_count[i] = dd->halo_bnd_count[i];
11946 }
11947 } else {
11948 help_subdomain_start[0] = dd->subdomain_start[0];
11949 help_subdomain_start[1] = dd->subdomain_start[3];
11950 help_subdomain_start[2] = dd->subdomain_start[2];
11951 help_subdomain_start[3] = dd->subdomain_start[1];
11952
11953 help_subdomain_count[0] = dd->subdomain_count[0];
11954 help_subdomain_count[1] = dd->subdomain_count[3];
11955 help_subdomain_count[2] = dd->subdomain_count[2];
11956 help_subdomain_count[3] = dd->subdomain_count[1];
11957
11958 help_halo_bnd_start[0] = dd->halo_bnd_start[0];
11959 help_halo_bnd_start[1] = dd->halo_bnd_start[3];
11960 help_halo_bnd_start[2] = dd->halo_bnd_start[2];
11961 help_halo_bnd_start[3] = dd->halo_bnd_start[1];
11962
11963 help_halo_bnd_count[0] = dd->halo_bnd_count[0];
11964 help_halo_bnd_count[1] = dd->halo_bnd_count[3];
11965 help_halo_bnd_count[2] = dd->halo_bnd_count[2];
11966 help_halo_bnd_count[3] = dd->halo_bnd_count[1];
11967 }
11968
11969 /* Allocate... */
11970 float *help;
11971 ALLOC(help, float,
11972 (int) dd->subdomain_count[0] * (int) dd->subdomain_count[1]
11973 * (int) dd->subdomain_count[2] * (int) dd->subdomain_count[3]);
11974
11975 /* Use default NetCDF parallel I/O behavior */
11976 SELECT_TIMER("MET_READ", "INPUT");
11977#ifdef DD
11978 NC(nc_var_par_access(ncid, varid, NC_INDEPENDENT));
11979#endif
11980 NC(nc_get_vara_float
11981 (ncid, varid, help_subdomain_start, help_subdomain_count, help));
11982
11983 /* Read halos separately at boundaries... */
11984 float *help_halo;
11985 ALLOC(help_halo, float,
11986 dd->halo_bnd_count[0] * dd->halo_bnd_count[1] *
11987 dd->halo_bnd_count[2] * dd->halo_bnd_count[3]);
11988
11989#ifdef DD
11990 NC(nc_var_par_access(ncid, varid, NC_INDEPENDENT));
11991#endif
11992 if (dd->halo_bnd_count[1] > 0 && dd->halo_bnd_count[2] > 0
11993 && dd->halo_bnd_count[3] > 0) {
11994 NC(nc_get_vara_float
11995 (ncid, varid, help_halo_bnd_start, help_halo_bnd_count,
11996 help_halo));
11997 }
11998
11999 SELECT_TIMER("MET_CONVERT", "INPUT");
12000
12001 /* Check meteo data layout... */
12002 if (ctl->met_convention == 0) {
12003
12004 /* Copy and check data (ordering: lev, lat, lon)... */
12005 omp_set_dynamic(1);
12006#pragma omp parallel for default(shared)
12007 for (int ix = 0; ix < (int) dd->subdomain_count[3]; ix++)
12008 for (int iy = 0; iy < (int) dd->subdomain_count[2]; iy++)
12009 for (int ip = 0; ip < met->np; ip++) {
12010 const float aux =
12011 help[ARRAY_3D(ip, iy, (int) dd->subdomain_count[2], ix,
12012 (int) dd->subdomain_count[3])];
12013 if ((fillval == 0 || aux != fillval)
12014 && (missval == 0 || aux != missval)
12015 && fabsf(aux) < 1e14f) {
12016 dest[ix + dd->halo_offset_start][iy][ip] = scl * aux;
12017
12018 } else
12019 dest[ix + dd->halo_offset_start][iy][ip] = NAN;
12020 }
12021
12022#pragma omp parallel for default(shared)
12023 for (int ix = 0; ix < (int) dd->halo_bnd_count[3]; ix++)
12024 for (int iy = 0; iy < (int) dd->halo_bnd_count[2]; iy++)
12025 for (int ip = 0; ip < met->np; ip++) {
12026 const float aux =
12027 help_halo[ARRAY_3D(ip, iy, (int) dd->halo_bnd_count[2], ix,
12028 (int) dd->halo_bnd_count[3])];
12029 if ((fillval == 0 || aux != fillval)
12030 && (missval == 0 || aux != missval)
12031 && fabsf(aux) < 1e14f)
12032 dest[ix + dd->halo_offset_end][iy][ip] = scl * aux;
12033 else
12034 dest[ix + dd->halo_offset_end][iy][ip] = NAN;
12035 }
12036 omp_set_dynamic(0);
12037
12038 } else {
12039
12040 /* Copy and check data (ordering: lon, lat, lev)... */
12041 omp_set_dynamic(1);
12042#pragma omp parallel for default(shared)
12043 for (int ip = 0; ip < met->np; ip++)
12044 for (int iy = 0; iy < (int) dd->subdomain_count[2]; iy++)
12045 for (int ix = 0; ix < (int) dd->subdomain_count[3]; ix++) {
12046 const float aux =
12047 help[ARRAY_3D
12048 (ix, iy, (int) dd->subdomain_count[2], ip, met->np)];
12049 if ((fillval == 0 || aux != fillval)
12050 && (missval == 0 || aux != missval)
12051 && fabsf(aux) < 1e14f)
12052 dest[ix + dd->halo_offset_start][iy][ip] = scl * aux;
12053 else
12054 dest[ix + dd->halo_offset_start][iy][ip] = NAN;
12055 }
12056
12057#pragma omp parallel for default(shared)
12058 for (int ip = 0; ip < met->np; ip++)
12059 for (int iy = 0; iy < (int) dd->halo_bnd_count[2]; iy++)
12060 for (int ix = 0; ix < (int) dd->halo_bnd_count[3]; ix++) {
12061 const float aux =
12062 help_halo[ARRAY_3D(ix, iy, (int) dd->halo_bnd_count[2], ip,
12063 met->np)];
12064 if ((fillval == 0 || aux != fillval)
12065 && (missval == 0 || aux != missval)
12066 && fabsf(aux) < 1e14f)
12067 dest[ix + dd->halo_offset_end][iy][ip] = scl * aux;
12068 else
12069 dest[ix + dd->halo_offset_end][iy][ip] = NAN;
12070 }
12071 omp_set_dynamic(0);
12072 }
12073 /* Return to the caller's timer (only called from read_met_nc_levels)... */
12074 SELECT_TIMER("READ_MET_NC_LEVELS", "INPUT");
12075
12076 /* Free... */
12077 free(help);
12078 free(help_halo);
12079 }
12080
12081 /* Return... */
12082 return 1;
12083}

◆ read_met_pbl()

void read_met_pbl ( const ctl_t * ctl,
met_t * met )

Computes the planetary boundary layer (PBL) pressure based on meteorological data.

This function determines the PBL pressure for each grid point using one of four methods:

  1. Read PBL pressure from meteo data file.
  2. Read PBL heights from meteo data file and convert to pressure.
  3. Determine PBL pressure based on bulk Richardson number criterion.
  4. Determine PBL pressure Based on potential temperature difference. The calculated PBL height is constrained by user-defined minimum and maximum limits.
Parameters
[in]ctlPointer to the control structure (ctl_t), which contains parameters controlling the PBL calculation.
[in,out]metPointer to the meteorological data structure (met_t), which contains grid and atmospheric data. The met->pbl array is updated with the calculated PBL pressure.

Method 0 (Precomputed PBL pressure from file):

  • Read PBL pressure from meteo data file.

Method 1 (Precomputed PBL height from file):

  • Read PBL height from meteo data file.
  • Interpolates the PBL pressure using the geopotential heights from the meteo file.

Method 2 (Richardson number criterion):

  • Implements a method based on the bulk Richardson number (critical value: Ri = 0.25).
  • Iteratively evaluates vertical levels, calculating wind shear, and thermal gradients, until the Richardson number exceeds the critical threshold.
  • Interpolates between levels to find the precise height.

Method 3 (Potential temperature difference):

  • Computes the PBL height as the altitude where the potential temperature exceeds the surface value by 2 K.
  • Interpolates between levels to find the precise height.

Final Adjustments:

  • Ensures the PBL height respects user-defined minimum and maximum thresholds.
Note
Method 2 is a standard method for estimating PBL depths, but the current implementation seems to underestimate PBL depths compared to ECMWF PBL data or Method 3. Therefore, Method 3, is selected by default. If PBL heights are available from the meteo data files, it is recommended to select Method 1.
Author
Lars Hoffmann

Definition at line 12908 of file mptrac.c.

12910 {
12911
12912 /* Set timer... */
12913 SELECT_TIMER("READ_MET_PBL", "METPROC");
12914 LOG(2, "Calculate planetary boundary layer...");
12915
12916 /* Convert PBL height from meteo file to pressure... */
12917 if (ctl->met_pbl == 1) {
12918
12919 /* Loop over grid points... */
12920#pragma omp parallel for default(shared) collapse(2)
12921 for (int ix = 0; ix < met->nx; ix++)
12922 for (int iy = 0; iy < met->ny; iy++) {
12923
12924 /* Get pressure at top of PBL... */
12925 const float z = met->zs[ix][iy] + met->pbl[ix][iy];
12926 const int ip = locate_irr_float(met->z[ix][iy], met->np, z, 0);
12927 met->pbl[ix][iy] =
12928 (float) (LIN(met->z[ix][iy][ip], met->p[ip],
12929 met->z[ix][iy][ip + 1], met->p[ip + 1], z));
12930 }
12931 }
12932
12933 /* Determine PBL based on Richardson number... */
12934 else if (ctl->met_pbl == 2) {
12935
12936 /* Parameters used to estimate the height of the PBL
12937 (e.g., Vogelezang and Holtslag, 1996; Seidel et al., 2012)... */
12938 const double rib_crit = 0.25, dz = 0.05, umin = 5.0;
12939
12940 /* Loop over grid points... */
12941#pragma omp parallel for default(shared) collapse(2)
12942 for (int ix = 0; ix < met->nx; ix++)
12943 for (int iy = 0; iy < met->ny; iy++) {
12944
12945 /* Set bottom level of PBL... */
12946 const double pbl_bot = met->ps[ix][iy] * exp(-dz / H0);
12947
12948 /* Find lowest level near the bottom... */
12949 int ip;
12950 for (ip = 1; ip < met->np; ip++)
12951 if (met->p[ip] < pbl_bot)
12952 break;
12953
12954 /* Get near surface data... */
12955 const double h2os = LIN(met->p[ip - 1], met->h2o[ix][iy][ip - 1],
12956 met->p[ip], met->h2o[ix][iy][ip], pbl_bot);
12957 const double tvs = THETAVIRT(pbl_bot, met->ts[ix][iy], h2os);
12958
12959 /* Init... */
12960 double rib_old = 0;
12961
12962 /* Loop over levels... */
12963 for (; ip < met->np; ip++) {
12964
12965 /* Get squared horizontal wind speed... */
12966 double vh2 = SQR(met->u[ix][iy][ip] - met->us[ix][iy])
12967 + SQR(met->v[ix][iy][ip] - met->vs[ix][iy]);
12968 vh2 = MAX(vh2, SQR(umin));
12969
12970 /* Calculate bulk Richardson number... */
12971 const double rib =
12972 G0 * 1e3 * (met->z[ix][iy][ip] - met->zs[ix][iy]) / tvs
12973 * (THETAVIRT(met->p[ip], met->t[ix][iy][ip],
12974 met->h2o[ix][iy][ip]) - tvs) / vh2;
12975
12976 /* Check for critical value... */
12977 if (rib >= rib_crit) {
12978 met->pbl[ix][iy] = (float) (LIN(rib_old, met->p[ip - 1],
12979 rib, met->p[ip], rib_crit));
12980 if (met->pbl[ix][iy] > pbl_bot)
12981 met->pbl[ix][iy] = (float) pbl_bot;
12982 break;
12983 }
12984
12985 /* Save Richardson number... */
12986 rib_old = rib;
12987 }
12988 }
12989 }
12990
12991 /* Determine PBL based on potential temperature... */
12992 if (ctl->met_pbl == 3) {
12993
12994 /* Parameters used to estimate the height of the PBL
12995 (following HYSPLIT model)... */
12996 const double dtheta = 2.0, zmin = 0.1;
12997
12998 /* Loop over grid points... */
12999#pragma omp parallel for default(shared) collapse(2)
13000 for (int ix = 0; ix < met->nx; ix++)
13001 for (int iy = 0; iy < met->ny; iy++) {
13002
13003 /* Potential temperature at the surface... */
13004 const double theta0 = THETA(met->ps[ix][iy], met->ts[ix][iy]);
13005
13006 /* Find topmost level where theta exceeds surface value by 2 K... */
13007 int ip;
13008 for (ip = met->np - 2; ip > 0; ip--)
13009 if (met->p[ip] >= 300.)
13010 if (met->p[ip] > met->ps[ix][iy]
13011 || THETA(met->p[ip], met->t[ix][iy][ip]) <= theta0 + dtheta)
13012 break;
13013
13014 /* Interpolate... */
13015 met->pbl[ix][iy]
13016 = (float) (LIN(THETA(met->p[ip + 1], met->t[ix][iy][ip + 1]),
13017 met->p[ip + 1],
13018 THETA(met->p[ip], met->t[ix][iy][ip]),
13019 met->p[ip], theta0 + dtheta));
13020
13021 /* Check minimum value... */
13022 double pbl_min = met->ps[ix][iy] * exp(-zmin / H0);
13023 if (met->pbl[ix][iy] > pbl_min || met->p[ip] > met->ps[ix][iy])
13024 met->pbl[ix][iy] = (float) pbl_min;
13025 }
13026 }
13027
13028 /* Loop over grid points... */
13029#pragma omp parallel for default(shared) collapse(2)
13030 for (int ix = 0; ix < met->nx; ix++)
13031 for (int iy = 0; iy < met->ny; iy++) {
13032
13033 /* Check minimum value... */
13034 double pbl_min = met->ps[ix][iy] * exp(-ctl->met_pbl_min / H0);
13035 met->pbl[ix][iy] = MIN(met->pbl[ix][iy], (float) pbl_min);
13036
13037 /* Check maximum value... */
13038 double pbl_max = met->ps[ix][iy] * exp(-ctl->met_pbl_max / H0);
13039 met->pbl[ix][iy] = MAX(met->pbl[ix][iy], (float) pbl_max);
13040 }
13041}
Here is the call graph for this function:

◆ read_met_periodic()

void read_met_periodic ( met_t * met)

Applies periodic boundary conditions to meteorological data along longitudinal axis.

This function applies periodic boundary conditions to meteorological data along the longitudinal axis. It checks if the difference between the last and first longitudes and the difference between the second and first longitudes are approximately equal to 360 degrees, indicating periodicity. If the condition is met, the function increases the longitude counter, sets the longitude value for the new grid point, and copies meteorological data from the first grid point to the last grid point to ensure periodicity.

Parameters
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets timer for performance monitoring.
  • Checks if the difference between the last and first longitudes and the difference between the second and first longitudes are approximately equal to 360 degrees, indicating periodicity.
  • If periodicity is confirmed:
    • Increases the longitude counter.
    • Sets the longitude value for the new grid point by adding the difference between the second and first longitudes to the longitude of the penultimate grid point.
    • Copies meteorological data from the first grid point to the last grid point to ensure periodicity:
      • Surface variables (e.g., pressure, temperature, wind speed, land-sea mask, sea surface temperature) are copied.
      • Meteorological variables at each pressure level are copied.
      • Meteorological variables at each hybrid pressure level are copied.
Note
This function is useful for generating continuous meteorological fields over a periodic domain, which is common in atmospheric modeling, especially for global simulations.
Author
Lars Hoffmann

Definition at line 13045 of file mptrac.c.

13046 {
13047
13048 /* Set timer... */
13049 SELECT_TIMER("READ_MET_PERIODIC", "METPROC");
13050 LOG(2, "Apply periodic boundary conditions...");
13051
13052 /* Check longitudes... */
13053 if (!(fabs(met->lon[met->nx - 1] - met->lon[0]
13054 + met->lon[1] - met->lon[0] - 360) < 0.01))
13055 return;
13056
13057 /* Increase longitude counter... */
13058 if ((++met->nx) >= EX)
13059 ERRMSG("Cannot create periodic boundary conditions!");
13060
13061 /* Set longitude... */
13062 met->lon[met->nx - 1] = met->lon[met->nx - 2] + met->lon[1] - met->lon[0];
13063
13064 /* Loop over latitudes and pressure levels... */
13065#pragma omp parallel for default(shared)
13066 for (int iy = 0; iy < met->ny; iy++) {
13067 met->ps[met->nx - 1][iy] = met->ps[0][iy];
13068 met->zs[met->nx - 1][iy] = met->zs[0][iy];
13069 met->ts[met->nx - 1][iy] = met->ts[0][iy];
13070 met->us[met->nx - 1][iy] = met->us[0][iy];
13071 met->vs[met->nx - 1][iy] = met->vs[0][iy];
13072 met->ess[met->nx - 1][iy] = met->ess[0][iy];
13073 met->nss[met->nx - 1][iy] = met->nss[0][iy];
13074 met->shf[met->nx - 1][iy] = met->shf[0][iy];
13075 met->lsm[met->nx - 1][iy] = met->lsm[0][iy];
13076 met->sst[met->nx - 1][iy] = met->sst[0][iy];
13077 met->pbl[met->nx - 1][iy] = met->pbl[0][iy];
13078 met->cape[met->nx - 1][iy] = met->cape[0][iy];
13079 met->cin[met->nx - 1][iy] = met->cin[0][iy];
13080 for (int ip = 0; ip < met->np; ip++) {
13081 met->t[met->nx - 1][iy][ip] = met->t[0][iy][ip];
13082 met->u[met->nx - 1][iy][ip] = met->u[0][iy][ip];
13083 met->v[met->nx - 1][iy][ip] = met->v[0][iy][ip];
13084 met->w[met->nx - 1][iy][ip] = met->w[0][iy][ip];
13085 met->h2o[met->nx - 1][iy][ip] = met->h2o[0][iy][ip];
13086 met->o3[met->nx - 1][iy][ip] = met->o3[0][iy][ip];
13087 met->lwc[met->nx - 1][iy][ip] = met->lwc[0][iy][ip];
13088 met->rwc[met->nx - 1][iy][ip] = met->rwc[0][iy][ip];
13089 met->iwc[met->nx - 1][iy][ip] = met->iwc[0][iy][ip];
13090 met->swc[met->nx - 1][iy][ip] = met->swc[0][iy][ip];
13091 met->cc[met->nx - 1][iy][ip] = met->cc[0][iy][ip];
13092 met->pv[met->nx - 1][iy][ip] = met->pv[0][iy][ip];
13093 }
13094 for (int ip = 0; ip < met->npl; ip++) {
13095 met->ul[met->nx - 1][iy][ip] = met->ul[0][iy][ip];
13096 met->vl[met->nx - 1][iy][ip] = met->vl[0][iy][ip];
13097 met->wl[met->nx - 1][iy][ip] = met->wl[0][iy][ip];
13098 met->pl[met->nx - 1][iy][ip] = met->pl[0][iy][ip];
13099 met->zetal[met->nx - 1][iy][ip] = met->zetal[0][iy][ip];
13100 met->zeta_dotl[met->nx - 1][iy][ip] = met->zeta_dotl[0][iy][ip];
13101 }
13102 }
13103}

◆ read_met_polar_winds()

void read_met_polar_winds ( met_t * met)

Applies a fix for polar winds in meteorological data.

This function applies a fix for polar winds in meteorological data, particularly focusing on the u and v wind components. It checks if the latitudes at the top and bottom of the grid are close to the poles. If so, it transforms the winds at 89-degree latitude into Cartesian coordinates, takes their mean, and replaces the winds at 90-degree latitude with this mean, effectively fixing the unrealistic behavior of winds at the poles.

Parameters
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets a timer for performance monitoring.
  • Checks if the latitudes at the top and bottom of the grid are close to the poles (within 0.001 degree latitude of the poles).
  • For each hemisphere (north and south):
    • Sets latitude indices for 89 degrees and 90 degrees.
    • Determines the sign of longitude adjustments based on the hemisphere.
    • Constructs lookup tables for cosine and sine of longitudes.
    • Loops over pressure levels and performs the following operations:
      • Transforms u and v wind components at 89 degrees latitude into Cartesian coordinates and calculates their mean.
      • Replaces u and v wind components at 90 degrees latitude with the calculated mean, effectively fixing the polar winds.
Note
This function is useful for correcting unrealistic behavior of winds near the poles in meteorological data, which can affect various atmospheric simulations.
Based on a Python code provided by Jens-Uwe Grooß.
Author
Lars Hoffmann

Definition at line 13107 of file mptrac.c.

13108 {
13109
13110 /* Set timer... */
13111 SELECT_TIMER("READ_MET_POLAR_WINDS", "METPROC");
13112 LOG(2, "Apply fix for polar winds...");
13113
13114 if (met->coord_type != 0)
13115 return;
13116
13117 /* Check latitudes... */
13118 if (fabs(met->lat[0]) < 89.999 || fabs(met->lat[met->ny - 1]) < 89.999)
13119 return;
13120
13121 /* Loop over hemispheres... */
13122 for (int ihem = 0; ihem < 2; ihem++) {
13123
13124 /* Set latitude indices... */
13125 int i89 = 1, i90 = 0, sign = 1;
13126 if (ihem == 1) {
13127 i89 = met->ny - 2;
13128 i90 = met->ny - 1;
13129 }
13130 if (met->lat[i90] < 0)
13131 sign = -1;
13132
13133 /* Look-up table of cosinus and sinus... */
13134 double clon[EX], slon[EX];
13135#pragma omp parallel for default(shared)
13136 for (int ix = 0; ix < met->nx; ix++) {
13137 clon[ix] = cos(sign * DEG2RAD(met->lon[ix]));
13138 slon[ix] = sin(sign * DEG2RAD(met->lon[ix]));
13139 }
13140
13141 /* Loop over levels... */
13142#pragma omp parallel for default(shared)
13143 for (int ip = 0; ip < met->np; ip++) {
13144
13145 /* Transform 89 degree u and v winds into Cartesian coordinates and take the mean... */
13146 double vel89x = 0, vel89y = 0;
13147 for (int ix = 0; ix < met->nx; ix++) {
13148 vel89x +=
13149 (met->u[ix][i89][ip] * clon[ix] -
13150 met->v[ix][i89][ip] * slon[ix]) / met->nx;
13151 vel89y +=
13152 (met->u[ix][i89][ip] * slon[ix] +
13153 met->v[ix][i89][ip] * clon[ix]) / met->nx;
13154 }
13155
13156 /* Replace 90 degree winds by 89 degree mean... */
13157 for (int ix = 0; ix < met->nx; ix++) {
13158 met->u[ix][i90][ip]
13159 = (float) (vel89x * clon[ix] + vel89y * slon[ix]);
13160 met->v[ix][i90][ip]
13161 = (float) (-vel89x * slon[ix] + vel89y * clon[ix]);
13162 }
13163 }
13164 }
13165}

◆ read_met_pv()

void read_met_pv ( met_t * met)

Calculates potential vorticity (PV) from meteorological data.

This function calculates the potential vorticity (PV) from the provided meteorological data. It employs finite difference methods to estimate gradients of temperature, wind components, and pressure in longitude, latitude, and pressure dimensions. These gradients are then used to compute PV at each grid point. Additionally, a fix for polar regions is applied to ensure smoothness of PV values in these regions.

Parameters
metA pointer to a structure containing meteorological data.

The function performs the following steps:

  • Sets a timer for performance monitoring.
  • Computes powers for pressure calculation.
  • Loops over grid points in longitude:
    • Sets latitude indices.
    • Loops over grid points in latitude:
      • Sets indices and auxiliary variables.
      • Loops over pressure levels:
        • Computes gradients in longitude, latitude, and pressure.
        • Calculates PV using computed gradients.
  • Applies a fix for polar regions to ensure smoothness of PV values.
Note
Potential vorticity is a fundamental quantity in atmospheric dynamics, representing the potential of a fluid parcel to rotate due to changes in pressure, temperature, and wind fields.
For UTM grids, this function sets PV to NaN because geographic latitude is unavailable.
Based on a Python code by Mathew Barlow (https://github.com/mathewbarlow/potential-vorticity).
Author
Lars Hoffmann

Definition at line 13169 of file mptrac.c.

13170 {
13171
13172 double pows[EP];
13173
13174 /* Set timer... */
13175 SELECT_TIMER("READ_MET_PV", "METPROC");
13176 LOG(2, "Calculate potential vorticity...");
13177
13178 /* UTM northing is not geographic latitude for the Coriolis parameter... */
13179 if (met->coord_type != 0) {
13180#pragma omp parallel for default(shared) collapse(2)
13181 for (int ix = 0; ix < met->nx; ix++)
13182 for (int iy = 0; iy < met->ny; iy++)
13183 for (int ip = 0; ip < met->np; ip++)
13184 met->pv[ix][iy][ip] = NAN;
13185 return;
13186 }
13187
13188 /* Set powers... */
13189#pragma omp parallel for default(shared)
13190 for (int ip = 0; ip < met->np; ip++)
13191 pows[ip] = pow(1000. / met->p[ip], KAPPA);
13192
13193 /* Loop over grid points... */
13194#pragma omp parallel for default(shared)
13195 for (int ix = 0; ix < met->nx; ix++) {
13196
13197 /* Set indices... */
13198 const int ix0 = MAX(ix - 1, 0);
13199 const int ix1 = MIN(ix + 1, met->nx - 1);
13200
13201 /* Loop over grid points... */
13202 for (int iy = 0; iy < met->ny; iy++) {
13203
13204 /* Set indices... */
13205 const int iy0 = MAX(iy - 1, 0);
13206 const int iy1 = MIN(iy + 1, met->ny - 1);
13207
13208 /* Set auxiliary variables... */
13209 const double latr = 0.5 * (met->lat[iy1] + met->lat[iy0]);
13210 double dx, dy, c0, c1, cr, vort;
13211
13212 /* Set geographic distances and the Coriolis term... */
13213 dx = 1000. * DEG2DX(met->lon[ix1] - met->lon[ix0], latr);
13214 dy = 1000. * DEG2DY(met->lat[iy1] - met->lat[iy0]);
13215 c0 = cos(DEG2RAD(met->lat[iy0]));
13216 c1 = cos(DEG2RAD(met->lat[iy1]));
13217 cr = cos(DEG2RAD(latr));
13218 vort = 2 * OMEGA_EARTH * sin(DEG2RAD(latr));
13219
13220 /* Loop over grid points... */
13221 for (int ip = 0; ip < met->np; ip++) {
13222
13223 /* Get gradients in longitude... */
13224 const double dtdx
13225 = (met->t[ix1][iy][ip] - met->t[ix0][iy][ip]) * pows[ip] / dx;
13226 const double dvdx = (met->v[ix1][iy][ip] - met->v[ix0][iy][ip]) / dx;
13227
13228 /* Get gradients in latitude... */
13229 const double dtdy
13230 = (met->t[ix][iy1][ip] - met->t[ix][iy0][ip]) * pows[ip] / dy;
13231 const double dudy
13232 = (met->u[ix][iy1][ip] * c1 - met->u[ix][iy0][ip] * c0) / dy;
13233
13234 /* Set indices... */
13235 const int ip0 = MAX(ip - 1, 0);
13236 const int ip1 = MIN(ip + 1, met->np - 1);
13237
13238 /* Get gradients in pressure... */
13239 double dtdp, dudp, dvdp;
13240 const double dp0 = 100. * (met->p[ip] - met->p[ip0]);
13241 const double dp1 = 100. * (met->p[ip1] - met->p[ip]);
13242 if (ip != ip0 && ip != ip1) {
13243 double denom = dp0 * dp1 * (dp0 + dp1);
13244 dtdp = (dp0 * dp0 * met->t[ix][iy][ip1] * pows[ip1]
13245 - dp1 * dp1 * met->t[ix][iy][ip0] * pows[ip0]
13246 + (dp1 * dp1 - dp0 * dp0) * met->t[ix][iy][ip] * pows[ip])
13247 / denom;
13248 dudp = (dp0 * dp0 * met->u[ix][iy][ip1]
13249 - dp1 * dp1 * met->u[ix][iy][ip0]
13250 + (dp1 * dp1 - dp0 * dp0) * met->u[ix][iy][ip])
13251 / denom;
13252 dvdp = (dp0 * dp0 * met->v[ix][iy][ip1]
13253 - dp1 * dp1 * met->v[ix][iy][ip0]
13254 + (dp1 * dp1 - dp0 * dp0) * met->v[ix][iy][ip])
13255 / denom;
13256 } else {
13257 const double denom = dp0 + dp1;
13258 dtdp =
13259 (met->t[ix][iy][ip1] * pows[ip1] -
13260 met->t[ix][iy][ip0] * pows[ip0]) / denom;
13261 dudp = (met->u[ix][iy][ip1] - met->u[ix][iy][ip0]) / denom;
13262 dvdp = (met->v[ix][iy][ip1] - met->v[ix][iy][ip0]) / denom;
13263 }
13264
13265 /* Calculate PV... */
13266 met->pv[ix][iy][ip] = (float)
13267 (1e6 * G0 *
13268 (-dtdp * (dvdx - dudy / cr + vort) + dvdp * dtdx - dudp * dtdy));
13269 }
13270 }
13271 }
13272
13273 /* Fix for polar regions... */
13274#pragma omp parallel for default(shared)
13275 for (int ix = 0; ix < met->nx; ix++)
13276 for (int ip = 0; ip < met->np; ip++) {
13277 met->pv[ix][0][ip]
13278 = met->pv[ix][1][ip]
13279 = met->pv[ix][2][ip];
13280 met->pv[ix][met->ny - 1][ip]
13281 = met->pv[ix][met->ny - 2][ip]
13282 = met->pv[ix][met->ny - 3][ip];
13283 }
13284}
#define DEG2DY(dlat)
Convert a latitude difference to a distance in the y-direction (north-south).
Definition mptrac.h:842
#define OMEGA_EARTH
Angular velocity of Earth [s^-1].
Definition mptrac.h:330
#define DEG2DX(dlon, lat)
Convert a longitude difference to a distance in the x-direction (east-west) at a specific latitude.
Definition mptrac.h:821

◆ read_met_ozone()

void read_met_ozone ( met_t * met)

Calculates the total column ozone from meteorological ozone data.

This function calculates the total column ozone from the provided meteorological ozone data. It integrates ozone concentrations over altitude to obtain the column ozone density. The result is then converted to Dobson units, which represent the thickness of the ozone layer if compressed into one layer at standard temperature and pressure.

Parameters
metA pointer to a structure containing meteorological ozone data.

The function performs the following steps:

  • Sets a timer for performance monitoring.
  • Loops over columns in longitude and latitude:
    • Integrates ozone concentrations over altitude.
    • Converts the integrated ozone density to Dobson units.
Note
Total column ozone is a critical metric for understanding ozone distribution in the atmosphere, with implications for climate, air quality, and UV radiation.
Author
Lars Hoffmann

Definition at line 13288 of file mptrac.c.

13289 {
13290
13291 /* Set timer... */
13292 SELECT_TIMER("READ_MET_OZONE", "METPROC");
13293 LOG(2, "Calculate total column ozone...");
13294
13295 /* Loop over columns... */
13296#pragma omp parallel for default(shared) collapse(2)
13297 for (int ix = 0; ix < met->nx; ix++)
13298 for (int iy = 0; iy < met->ny; iy++) {
13299
13300 /* Integrate... */
13301 double cd = 0;
13302 for (int ip = 1; ip < met->np; ip++)
13303 if (met->p[ip - 1] <= met->ps[ix][iy]) {
13304 const double vmr =
13305 0.5 * (met->o3[ix][iy][ip - 1] + met->o3[ix][iy][ip]);
13306 const double dp = met->p[ip - 1] - met->p[ip];
13307 cd += vmr * MO3 / MA * dp * 1e2 / G0;
13308 }
13309
13310 /* Convert to Dobson units... */
13311 met->o3c[ix][iy] = (float) (cd / DOBSON_UNIT);
13312 }
13313}
#define DOBSON_UNIT
Ozone column mass corresponding to one Dobson unit [kg/m^2].
Definition mptrac.h:335

◆ read_met_sample()

void read_met_sample ( const ctl_t * ctl,
met_t * met )

Downsamples meteorological data based on specified parameters.

This function downsamples meteorological data based on the provided control parameters. It reduces the resolution of meteorological data by averaging over specified intervals in longitude, latitude, and altitude.

Parameters
ctlA pointer to a structure containing control parameters for downsampling.
metA pointer to a structure containing meteorological data to be downsampled.

The function performs the following steps:

  • Checks if downsampling parameters are set to a value less than or equal to 1, if so, returns without downsampling.
  • Sets a timer for performance monitoring.
  • Allocates memory for a temporary meteorological data structure.
  • Copies metadata from the original structure to the temporary structure.
  • Performs downsampling by smoothing over specified intervals:
    • Computes weighted averages over the specified intervals.
    • Updates the temporary structure with the smoothed values.
  • Downsamples the smoothed data:
    • Updates longitude and latitude arrays with downsampled values.
    • Stores downsampled meteorological variables in the original structure.
  • Frees memory allocated for the temporary structure.
Note
Downsampling meteorological data can be useful for reducing computational cost while preserving essential features for modeling and analysis.
Author
Lars Hoffmann

Definition at line 13317 of file mptrac.c.

13319 {
13320
13321 met_t *help;
13322
13323 /* Check parameters... */
13324 if (ctl->met_dp <= 1 && ctl->met_dx <= 1 && ctl->met_dy <= 1
13325 && ctl->met_sp <= 1 && ctl->met_sx <= 1 && ctl->met_sy <= 1)
13326 return;
13327
13328 /* Set timer... */
13329 SELECT_TIMER("READ_MET_SAMPLE", "METPROC");
13330 LOG(2, "Downsampling of meteo data...");
13331
13332 /* Allocate... */
13333 ALLOC(help, met_t, 1);
13334
13335 /* Copy data... */
13336 help->nx = met->nx;
13337 help->ny = met->ny;
13338 help->np = met->np;
13339 memcpy(help->lon, met->lon, sizeof(met->lon));
13340 memcpy(help->lat, met->lat, sizeof(met->lat));
13341 memcpy(help->p, met->p, sizeof(met->p));
13342
13343 /* Smoothing... */
13344 for (int ix = 0; ix < met->nx; ix += ctl->met_dx) {
13345 for (int iy = 0; iy < met->ny; iy += ctl->met_dy) {
13346 for (int ip = 0; ip < met->np; ip += ctl->met_dp) {
13347 help->ps[ix][iy] = 0;
13348 help->zs[ix][iy] = 0;
13349 help->ts[ix][iy] = 0;
13350 help->us[ix][iy] = 0;
13351 help->vs[ix][iy] = 0;
13352 help->ess[ix][iy] = 0;
13353 help->nss[ix][iy] = 0;
13354 help->shf[ix][iy] = 0;
13355 help->lsm[ix][iy] = 0;
13356 help->sst[ix][iy] = 0;
13357 help->pbl[ix][iy] = 0;
13358 help->cape[ix][iy] = 0;
13359 help->cin[ix][iy] = 0;
13360 help->t[ix][iy][ip] = 0;
13361 help->u[ix][iy][ip] = 0;
13362 help->v[ix][iy][ip] = 0;
13363 help->w[ix][iy][ip] = 0;
13364 help->h2o[ix][iy][ip] = 0;
13365 help->o3[ix][iy][ip] = 0;
13366 help->lwc[ix][iy][ip] = 0;
13367 help->rwc[ix][iy][ip] = 0;
13368 help->iwc[ix][iy][ip] = 0;
13369 help->swc[ix][iy][ip] = 0;
13370 help->cc[ix][iy][ip] = 0;
13371 help->pv[ix][iy][ip] = 0;
13372 float wsum = 0;
13373 for (int ix2 = ix - ctl->met_sx + 1; ix2 <= ix + ctl->met_sx - 1;
13374 ix2++) {
13375 int ix3 = ix2;
13376 /* Wrap the smoothing stencil across the longitude boundary... */
13377 if (ix3 < 0)
13378 ix3 += met->nx;
13379 else if (ix3 >= met->nx)
13380 ix3 -= met->nx;
13381
13382 for (int iy2 = MAX(iy - ctl->met_sy + 1, 0);
13383 iy2 <= MIN(iy + ctl->met_sy - 1, met->ny - 1); iy2++)
13384 for (int ip2 = MAX(ip - ctl->met_sp + 1, 0);
13385 ip2 <= MIN(ip + ctl->met_sp - 1, met->np - 1); ip2++) {
13386 const float w =
13387 (1.0f - (float) abs(ix - ix2) / (float) ctl->met_sx)
13388 * (1.0f - (float) abs(iy - iy2) / (float) ctl->met_sy)
13389 * (1.0f - (float) abs(ip - ip2) / (float) ctl->met_sp);
13390 help->ps[ix][iy] += w * met->ps[ix3][iy2];
13391 help->zs[ix][iy] += w * met->zs[ix3][iy2];
13392 help->ts[ix][iy] += w * met->ts[ix3][iy2];
13393 help->us[ix][iy] += w * met->us[ix3][iy2];
13394 help->vs[ix][iy] += w * met->vs[ix3][iy2];
13395 help->ess[ix][iy] += w * met->ess[ix3][iy2];
13396 help->nss[ix][iy] += w * met->nss[ix3][iy2];
13397 help->shf[ix][iy] += w * met->shf[ix3][iy2];
13398 help->lsm[ix][iy] += w * met->lsm[ix3][iy2];
13399 help->sst[ix][iy] += w * met->sst[ix3][iy2];
13400 help->pbl[ix][iy] += w * met->pbl[ix3][iy2];
13401 help->cape[ix][iy] += w * met->cape[ix3][iy2];
13402 help->cin[ix][iy] += w * met->cin[ix3][iy2];
13403 help->t[ix][iy][ip] += w * met->t[ix3][iy2][ip2];
13404 help->u[ix][iy][ip] += w * met->u[ix3][iy2][ip2];
13405 help->v[ix][iy][ip] += w * met->v[ix3][iy2][ip2];
13406 help->w[ix][iy][ip] += w * met->w[ix3][iy2][ip2];
13407 help->h2o[ix][iy][ip] += w * met->h2o[ix3][iy2][ip2];
13408 help->o3[ix][iy][ip] += w * met->o3[ix3][iy2][ip2];
13409 help->lwc[ix][iy][ip] += w * met->lwc[ix3][iy2][ip2];
13410 help->rwc[ix][iy][ip] += w * met->rwc[ix3][iy2][ip2];
13411 help->iwc[ix][iy][ip] += w * met->iwc[ix3][iy2][ip2];
13412 help->swc[ix][iy][ip] += w * met->swc[ix3][iy2][ip2];
13413 help->cc[ix][iy][ip] += w * met->cc[ix3][iy2][ip2];
13414 help->pv[ix][iy][ip] += w * met->pv[ix3][iy2][ip2];
13415 wsum += w;
13416 }
13417 }
13418 /* Normalize the tapered stencil, including at grid edges... */
13419 help->ps[ix][iy] /= wsum;
13420 help->zs[ix][iy] /= wsum;
13421 help->ts[ix][iy] /= wsum;
13422 help->us[ix][iy] /= wsum;
13423 help->vs[ix][iy] /= wsum;
13424 help->ess[ix][iy] /= wsum;
13425 help->nss[ix][iy] /= wsum;
13426 help->shf[ix][iy] /= wsum;
13427 help->lsm[ix][iy] /= wsum;
13428 help->sst[ix][iy] /= wsum;
13429 help->pbl[ix][iy] /= wsum;
13430 help->cape[ix][iy] /= wsum;
13431 help->cin[ix][iy] /= wsum;
13432 help->t[ix][iy][ip] /= wsum;
13433 help->u[ix][iy][ip] /= wsum;
13434 help->v[ix][iy][ip] /= wsum;
13435 help->w[ix][iy][ip] /= wsum;
13436 help->h2o[ix][iy][ip] /= wsum;
13437 help->o3[ix][iy][ip] /= wsum;
13438 help->lwc[ix][iy][ip] /= wsum;
13439 help->rwc[ix][iy][ip] /= wsum;
13440 help->iwc[ix][iy][ip] /= wsum;
13441 help->swc[ix][iy][ip] /= wsum;
13442 help->cc[ix][iy][ip] /= wsum;
13443 help->pv[ix][iy][ip] /= wsum;
13444 }
13445 }
13446 }
13447
13448 /* Downsampling... */
13449 met->nx = 0;
13450 for (int ix = 0; ix < help->nx; ix += ctl->met_dx) {
13451 met->lon[met->nx] = help->lon[ix];
13452 met->ny = 0;
13453 for (int iy = 0; iy < help->ny; iy += ctl->met_dy) {
13454 met->lat[met->ny] = help->lat[iy];
13455 met->ps[met->nx][met->ny] = help->ps[ix][iy];
13456 met->zs[met->nx][met->ny] = help->zs[ix][iy];
13457 met->ts[met->nx][met->ny] = help->ts[ix][iy];
13458 met->us[met->nx][met->ny] = help->us[ix][iy];
13459 met->vs[met->nx][met->ny] = help->vs[ix][iy];
13460 met->ess[met->nx][met->ny] = help->ess[ix][iy];
13461 met->nss[met->nx][met->ny] = help->nss[ix][iy];
13462 met->shf[met->nx][met->ny] = help->shf[ix][iy];
13463 met->lsm[met->nx][met->ny] = help->lsm[ix][iy];
13464 met->sst[met->nx][met->ny] = help->sst[ix][iy];
13465 met->pbl[met->nx][met->ny] = help->pbl[ix][iy];
13466 met->cape[met->nx][met->ny] = help->cape[ix][iy];
13467 met->cin[met->nx][met->ny] = help->cin[ix][iy];
13468 met->np = 0;
13469 for (int ip = 0; ip < help->np; ip += ctl->met_dp) {
13470 met->p[met->np] = help->p[ip];
13471 met->t[met->nx][met->ny][met->np] = help->t[ix][iy][ip];
13472 met->u[met->nx][met->ny][met->np] = help->u[ix][iy][ip];
13473 met->v[met->nx][met->ny][met->np] = help->v[ix][iy][ip];
13474 met->w[met->nx][met->ny][met->np] = help->w[ix][iy][ip];
13475 met->h2o[met->nx][met->ny][met->np] = help->h2o[ix][iy][ip];
13476 met->o3[met->nx][met->ny][met->np] = help->o3[ix][iy][ip];
13477 met->lwc[met->nx][met->ny][met->np] = help->lwc[ix][iy][ip];
13478 met->rwc[met->nx][met->ny][met->np] = help->rwc[ix][iy][ip];
13479 met->iwc[met->nx][met->ny][met->np] = help->iwc[ix][iy][ip];
13480 met->swc[met->nx][met->ny][met->np] = help->swc[ix][iy][ip];
13481 met->cc[met->nx][met->ny][met->np] = help->cc[ix][iy][ip];
13482 met->pv[met->nx][met->ny][met->np] = help->pv[ix][iy][ip];
13483 met->np++;
13484 }
13485 met->ny++;
13486 }
13487 met->nx++;
13488 }
13489
13490 /* Free... */
13491 free(help);
13492}

◆ read_met_tropo()

void read_met_tropo ( const ctl_t * ctl,
const clim_t * clim,
met_t * met )

Calculates the tropopause and related meteorological variables based on various methods and stores the results in the meteorological data structure.

This function calculates the tropopause and related meteorological variables using different methods specified by the control parameters. The calculated tropopause pressure is stored in the provided meteorological data structure.

Parameters
ctlA pointer to a structure containing control parameters.
climA pointer to the climatological data structure.
metA pointer to the meteorological data structure to store the calculated tropopause pressure and related variables.

The function performs the following steps:

  • Sets a timer for performance monitoring.
  • Retrieves altitude and pressure profiles from the meteorological data structure.
  • Depending on the control parameters (ctl->met_tropo), it calculates the tropopause using one of the following methods:
    • If ctl->met_tropo == 0, it does not calculate the tropopause and assigns NaN values to the tropopause pressure.
    • If ctl->met_tropo == 1, it uses tropopause climatology to estimate the tropopause pressure based on latitude and time.
    • If ctl->met_tropo == 2, it calculates the tropopause based on the cold point method, finding the altitude where the temperature is at a minimum.
    • If ctl->met_tropo == 3 or ctl->met_tropo == 4, it calculates the tropopause using the WMO definition, which involves identifying a sharp temperature lapse rate between two pressure levels.
    • If ctl->met_tropo == 5, it calculates the dynamical tropopause based on potential vorticity and potential temperature profiles.
  • Interpolates temperature, geopotential height, and water vapor content to the tropopause pressure level using spatial interpolation.
  • Stores the interpolated values in the meteorological data structure.
Note
The function supports parallelization using OpenMP directives to improve performance.
Author
Lars Hoffmann

Definition at line 13496 of file mptrac.c.

13499 {
13500
13501 double p2[200], pv[EP], pv2[200], t[EP], t2[200], th[EP],
13502 th2[200], z[EP], z2[200];
13503
13504 /* Set timer... */
13505 SELECT_TIMER("READ_MET_TROPO", "METPROC");
13506 LOG(2, "Calculate tropopause...");
13507
13508 /* Get altitude and pressure profiles... */
13509#pragma omp parallel for default(shared)
13510 for (int iz = 0; iz < met->np; iz++)
13511 z[iz] = Z(met->p[iz]);
13512#pragma omp parallel for default(shared)
13513 for (int iz = 0; iz <= 190; iz++) {
13514 z2[iz] = 4.5 + 0.1 * iz;
13515 p2[iz] = P(z2[iz]);
13516 }
13517
13518 /* Do not calculate tropopause... */
13519 if (ctl->met_tropo == 0)
13520#pragma omp parallel for default(shared) collapse(2)
13521 for (int ix = 0; ix < met->nx; ix++)
13522 for (int iy = 0; iy < met->ny; iy++)
13523 met->pt[ix][iy] = NAN;
13524
13525 /* Use tropopause climatology... */
13526 else if (ctl->met_tropo == 1) {
13527 if (met->coord_type != 0)
13528 ERRMSG("Only lat/lon grid supported");
13529#pragma omp parallel for default(shared) collapse(2)
13530 for (int ix = 0; ix < met->nx; ix++)
13531 for (int iy = 0; iy < met->ny; iy++)
13532 met->pt[ix][iy] = (float) clim_tropo(clim, met->time, met->lat[iy]);
13533 }
13534
13535 /* Use cold point... */
13536 else if (ctl->met_tropo == 2) {
13537
13538 /* Loop over grid points... */
13539#pragma omp parallel for default(shared) private(t,t2) collapse(2)
13540 for (int ix = 0; ix < met->nx; ix++)
13541 for (int iy = 0; iy < met->ny; iy++) {
13542
13543 /* Interpolate temperature profile... */
13544 for (int iz = 0; iz < met->np; iz++)
13545 t[iz] = met->t[ix][iy][iz];
13546 spline(z, t, met->np, z2, t2, 171, ctl->met_tropo_spline);
13547
13548 /* Find minimum... */
13549 int iz = (int) gsl_stats_min_index(t2, 1, 171);
13550 if (iz > 0 && iz < 170)
13551 met->pt[ix][iy] = (float) p2[iz];
13552 else
13553 met->pt[ix][iy] = NAN;
13554 }
13555 }
13556
13557 /* Use WMO definition... */
13558 else if (ctl->met_tropo == 3 || ctl->met_tropo == 4) {
13559
13560 /* Loop over grid points... */
13561#pragma omp parallel for default(shared) private(t,t2) collapse(2)
13562 for (int ix = 0; ix < met->nx; ix++)
13563 for (int iy = 0; iy < met->ny; iy++) {
13564
13565 /* Interpolate temperature profile... */
13566 int iz;
13567 for (iz = 0; iz < met->np; iz++)
13568 t[iz] = met->t[ix][iy][iz];
13569 spline(z, t, met->np, z2, t2, 191, ctl->met_tropo_spline);
13570
13571 /* Find 1st tropopause... */
13572 met->pt[ix][iy] = NAN;
13573 for (iz = 0; iz <= 170; iz++) {
13574 int found = 1;
13575 for (int iz2 = iz + 1; iz2 <= iz + 20; iz2++)
13576 if (LAPSE(p2[iz], t2[iz], p2[iz2], t2[iz2]) > 2.0) {
13577 found = 0;
13578 break;
13579 }
13580 if (found) {
13581 if (iz > 0 && iz < 170)
13582 met->pt[ix][iy] = (float) p2[iz];
13583 break;
13584 }
13585 }
13586
13587 /* Find 2nd tropopause... */
13588 if (ctl->met_tropo == 4 && isfinite(met->pt[ix][iy])) {
13589 met->pt[ix][iy] = NAN;
13590 for (; iz <= 170; iz++) {
13591 int found = 1;
13592 for (int iz2 = iz + 1; iz2 <= iz + 10; iz2++)
13593 if (LAPSE(p2[iz], t2[iz], p2[iz2], t2[iz2]) < 3.0) {
13594 found = 0;
13595 break;
13596 }
13597 if (found)
13598 break;
13599 }
13600 for (; iz <= 170; iz++) {
13601 int found = 1;
13602 for (int iz2 = iz + 1; iz2 <= iz + 20; iz2++)
13603 if (LAPSE(p2[iz], t2[iz], p2[iz2], t2[iz2]) > 2.0) {
13604 found = 0;
13605 break;
13606 }
13607 if (found) {
13608 if (iz > 0 && iz < 170)
13609 met->pt[ix][iy] = (float) p2[iz];
13610 break;
13611 }
13612 }
13613 }
13614 }
13615 }
13616
13617 /* Use dynamical tropopause... */
13618 else if (ctl->met_tropo == 5) {
13619
13620 /* Loop over grid points... */
13621#pragma omp parallel for default(shared) private(pv,pv2,th,th2) collapse(2)
13622 for (int ix = 0; ix < met->nx; ix++)
13623 for (int iy = 0; iy < met->ny; iy++) {
13624
13625 /* Interpolate potential vorticity profile... */
13626 for (int iz = 0; iz < met->np; iz++)
13627 pv[iz] = met->pv[ix][iy][iz];
13628 spline(z, pv, met->np, z2, pv2, 171, ctl->met_tropo_spline);
13629
13630 /* Interpolate potential temperature profile... */
13631 for (int iz = 0; iz < met->np; iz++)
13632 th[iz] = THETA(met->p[iz], met->t[ix][iy][iz]);
13633 spline(z, th, met->np, z2, th2, 171, ctl->met_tropo_spline);
13634
13635 /* Find dynamical tropopause... */
13636 met->pt[ix][iy] = NAN;
13637 for (int iz = 0; iz <= 170; iz++)
13638 if (fabs(pv2[iz]) >= ctl->met_tropo_pv
13639 || th2[iz] >= ctl->met_tropo_theta) {
13640 if (iz > 0 && iz < 170)
13641 met->pt[ix][iy] = (float) p2[iz];
13642 break;
13643 }
13644 }
13645 }
13646
13647 else
13648 ERRMSG("Cannot calculate tropopause!");
13649
13650 /* Interpolate temperature, geopotential height, and water vapor... */
13651#pragma omp parallel for default(shared) collapse(2)
13652 for (int ix = 0; ix < met->nx; ix++)
13653 for (int iy = 0; iy < met->ny; iy++) {
13654 double h2ot, tt, zt;
13656 intpol_met_space_3d(met, met->t, met->pt[ix][iy], met->lon[ix],
13657 met->lat[iy], &tt, ci, cw, 1);
13658 intpol_met_space_3d(met, met->z, met->pt[ix][iy], met->lon[ix],
13659 met->lat[iy], &zt, ci, cw, 0);
13660 intpol_met_space_3d(met, met->h2o, met->pt[ix][iy], met->lon[ix],
13661 met->lat[iy], &h2ot, ci, cw, 0);
13662 met->tt[ix][iy] = (float) tt;
13663 met->zt[ix][iy] = (float) zt;
13664 met->h2ot[ix][iy] = (float) h2ot;
13665 }
13666}
void spline(const double *x, const double *y, const int n, const double *x2, double *y2, const int n2, const int method)
Performs spline interpolation or linear interpolation.
Definition mptrac.c:13879
#define LAPSE(p1, t1, p2, t2)
Calculate lapse rate.
Definition mptrac.h:1379
Here is the call graph for this function:

◆ read_obs()

void read_obs ( const char * filename,
const ctl_t * ctl,
double * rt,
double * rz,
double * rlon,
double * rlat,
double * robs,
int * nobs )

Reads observation data from a file and stores it in arrays.

This function reads observation data from a specified file in either ASCII or NetCDF format, depending on the value of the OBS_TYPE control parameter. It stores the time, altitude, longitude, latitude, and observation values in the provided arrays.

Parameters
filenameThe path to the observation data file.
ctlA pointer to a structure containing control parameters.
rtAn array to store the time values of the observations.
rzAn array to store the altitude values of the observations.
rlonAn array to store the longitude values of the observations.
rlatAn array to store the latitude values of the observations.
robsAn array to store the observation values.
nobsA pointer to an integer variable to store the number of observations read.

The function performs the following steps:

  • Logs an informational message indicating the observation data file being read.
  • Reads the observation data from the file based on the OBS_TYPE control parameter:
    • If ctl->obs_type == 0, it reads the data from an ASCII file using the read_obs_asc function.
    • If ctl->obs_type == 1, it reads the data from a NetCDF file using the read_obs_nc function.
    • If ctl->obs_type is neither 0 nor 1, it generates an error message indicating that the OBS_TYPE must be set to 0 or 1.
  • Checks if the time values are in ascending order and generates an error message if not.
  • Logs statistical information about the observation data, including the number of observations, time range, altitude range, longitude range, latitude range, and observation value range.
Note
The function assumes that the observation data file is formatted correctly and that the arrays provided have sufficient memory allocated to store the data.
Author
Lars Hoffmann
Mingzhao Liu

Definition at line 13670 of file mptrac.c.

13678 {
13679
13680 /* Write info... */
13681 LOG(1, "Read observation data: %s", filename);
13682
13683 /* Read data... */
13684 if (ctl->obs_type == 0)
13685 read_obs_asc(filename, rt, rz, rlon, rlat, robs, nobs);
13686 else if (ctl->obs_type == 1)
13687 read_obs_nc(filename, rt, rz, rlon, rlat, robs, nobs);
13688 else
13689 ERRMSG("Set OBS_TYPE to 0 or 1!");
13690
13691 /* Check time... */
13692 for (int i = 1; i < *nobs; i++)
13693 if (rt[i] < rt[i - 1])
13694 ERRMSG("Time must be ascending!");
13695
13696 /* Write info... */
13697 int n = *nobs;
13698 double mini, maxi;
13699 LOG(2, "Number of observations: %d", *nobs);
13700 gsl_stats_minmax(&mini, &maxi, rt, 1, (size_t) n);
13701 LOG(2, "Time range: %.2f ... %.2f s", mini, maxi);
13702 gsl_stats_minmax(&mini, &maxi, rz, 1, (size_t) n);
13703 LOG(2, "Altitude range: %g ... %g km", mini, maxi);
13704 gsl_stats_minmax(&mini, &maxi, rlon, 1, (size_t) n);
13705 LOG(2, "Longitude range: %g ... %g deg", mini, maxi);
13706 gsl_stats_minmax(&mini, &maxi, rlat, 1, (size_t) n);
13707 LOG(2, "Latitude range: %g ... %g deg", mini, maxi);
13708 gsl_stats_minmax(&mini, &maxi, robs, 1, (size_t) n);
13709 LOG(2, "Observation range: %g ... %g", mini, maxi);
13710}
void read_obs_asc(const char *filename, double *rt, double *rz, double *rlon, double *rlat, double *robs, int *nobs)
Reads observation data from an ASCII file.
Definition mptrac.c:13714
void read_obs_nc(const char *filename, double *rt, double *rz, double *rlon, double *rlat, double *robs, int *nobs)
Reads observation data from a NetCDF file.
Definition mptrac.c:13742
Here is the call graph for this function:

◆ read_obs_asc()

void read_obs_asc ( const char * filename,
double * rt,
double * rz,
double * rlon,
double * rlat,
double * robs,
int * nobs )

Reads observation data from an ASCII file.

This function reads observation data from a specified ASCII file. It extracts time, altitude, longitude, latitude, and observation values from each line of the file and stores them in the provided arrays.

Parameters
filenameThe path to the ASCII file containing the observation data.
rtAn array to store the time values of the observations.
rzAn array to store the altitude values of the observations.
rlonAn array to store the longitude values of the observations.
rlatAn array to store the latitude values of the observations.
robsAn array to store the observation values.
nobsA pointer to an integer variable to store the number of observations read.

The function performs the following steps:

  • Attempts to open the specified observation data file in read mode.
  • Reads each line of the file and parses it to extract the time, altitude, longitude, latitude, and observation values using the sscanf function.
  • Stores the extracted values in the respective arrays.
  • Checks if the number of observations exceeds the maximum allowed limit (NOBS) and generates an error message if so.
  • Closes the observation data file after reading all data.
Note
The function assumes that the observation data file is properly formatted and that the arrays provided have sufficient memory allocated to store the data.
Author
Lars Hoffmann

Definition at line 13714 of file mptrac.c.

13721 {
13722
13723 /* Open observation data file... */
13724 FILE *in;
13725 if (!(in = fopen(filename, "r")))
13726 ERRMSG("Cannot open file!");
13727
13728 /* Read observations... */
13729 char line[LEN];
13730 while (fgets(line, LEN, in))
13731 if (sscanf(line, "%lg %lg %lg %lg %lg", &rt[*nobs], &rz[*nobs],
13732 &rlon[*nobs], &rlat[*nobs], &robs[*nobs]) == 5)
13733 if ((++(*nobs)) >= NOBS)
13734 ERRMSG("Too many observations!");
13735
13736 /* Close observation data file... */
13737 fclose(in);
13738}
#define NOBS
Maximum number of observation data points.
Definition mptrac.h:589

◆ read_obs_nc()

void read_obs_nc ( const char * filename,
double * rt,
double * rz,
double * rlon,
double * rlat,
double * robs,
int * nobs )

Reads observation data from a NetCDF file.

This function reads observation data from a specified NetCDF file. It extracts time, altitude, longitude, latitude, and observation values from the variables in the NetCDF file and stores them in the provided arrays.

Parameters
filenameThe path to the NetCDF file containing the observation data.
rtAn array to store the time values of the observations.
rzAn array to store the altitude values of the observations.
rlonAn array to store the longitude values of the observations.
rlatAn array to store the latitude values of the observations.
robsAn array to store the observation values.
nobsA pointer to an integer variable to store the number of observations read.

The function performs the following steps:

  • Attempts to open the specified NetCDF file in read-only mode using the nc_open function.
  • Queries the dimensions of the 'nobs' variable in the NetCDF file to determine the number of observations using the NC_INQ_DIM macro.
  • Reads the 'time', 'alt', 'lon', 'lat', and 'obs' variables from the NetCDF file using the NC_GET_DOUBLE macro and stores them in the respective arrays.
  • Closes the NetCDF file after reading all data using the nc_close function.
Note
The function assumes that the NetCDF file contains the required variables ('time', 'alt', 'lon', 'lat', 'obs') and that the arrays provided have sufficient memory allocated to store the data.
Author
Lars Hoffmann

Definition at line 13742 of file mptrac.c.

13749 {
13750
13751 int ncid, varid;
13752
13753 /* Open netCDF file... */
13754 if (nc_open(filename, NC_NOWRITE, &ncid) != NC_NOERR)
13755 ERRMSG("Cannot open file!");
13756
13757 /* Read the observations from the NetCDF file... */
13758 NC_INQ_DIM("nobs", nobs, 1, NOBS, 1);
13759 NC_GET_DOUBLE("time", rt, 1);
13760 NC_GET_DOUBLE("alt", rz, 1);
13761 NC_GET_DOUBLE("lon", rlon, 1);
13762 NC_GET_DOUBLE("lat", rlat, 1);
13763 NC_GET_DOUBLE("obs", robs, 1);
13764
13765 /* Close file... */
13766 NC(nc_close(ncid));
13767}

◆ scan_ctl()

double scan_ctl ( const char * filename,
int argc,
char * argv[],
const char * varname,
const int arridx,
const char * defvalue,
char * value )

Scans a control file or command-line arguments for a specified variable.

This function scans either a control file or command-line arguments for a specified variable name and retrieves its value. It searches for the variable name in the control file or command-line arguments and returns its corresponding value. If the variable is not found, it returns a default value specified by the user.

Parameters
filenameThe name of the control file to be scanned. If NULL, only command-line arguments will be scanned.
argcThe number of command-line arguments.
argvAn array of command-line arguments.
varnameThe name of the variable to be searched.
arridxThe index of the variable array, if applicable. Set to -1 if not an array.
defvalueThe default value to be returned if the variable is not found.
valueA pointer to a character array to store the retrieved value.
Returns
The retrieved value of the variable as a double.

The function performs the following steps:

  • Attempts to open the specified control file in read mode using the fopen function. If the filename ends with a '-', the file is not opened.
  • Constructs the full variable name based on the variable name and array index provided.
  • Reads data from the control file, searching for the full variable name. If found, it sets the contain flag to 1 and breaks the loop.
  • Searches through the command-line arguments for the full variable name. If found, it sets the value and contain flag and breaks the loop.
  • Closes the control file if opened.
  • If the variable is not found, it sets the value to the default value provided or throws an error if no default value is provided.
  • Writes the variable name and its value to the log.
  • Copies the retrieved value to the value parameter if it is not NULL.
  • Returns the retrieved value as a double after converting it from a string using the atof function.
Note
This function assumes that the variable names and their values in the control file or command-line arguments are separated by whitespace.
Author
Lars Hoffmann

Definition at line 13771 of file mptrac.c.

13778 {
13779
13780 FILE *in = NULL;
13781
13782 char fullname1[LEN], fullname2[LEN], rval[LEN];
13783
13784 int contain = 0, i;
13785
13786 /* Open file... */
13787 if (filename[strlen(filename) - 1] != '-')
13788 if (!(in = fopen(filename, "r")))
13789 ERRMSG("Cannot open file!");
13790
13791 /* Set full variable name... */
13792 if (arridx >= 0) {
13793 sprintf(fullname1, "%s[%d]", varname, arridx);
13794 sprintf(fullname2, "%s[*]", varname);
13795 } else {
13796 sprintf(fullname1, "%s", varname);
13797 sprintf(fullname2, "%s", varname);
13798 }
13799
13800 /* Read data... */
13801 if (in != NULL) {
13802 char dummy[LEN], line[LEN], rvarname[LEN];
13803 while (fgets(line, LEN, in)) {
13804 if (sscanf(line, "%4999s %4999s %4999s", rvarname, dummy, rval) == 3)
13805 if (strcasecmp(rvarname, fullname1) == 0 ||
13806 strcasecmp(rvarname, fullname2) == 0) {
13807 contain = 1;
13808 break;
13809 }
13810 }
13811 }
13812 for (i = 1; i < argc - 1; i++)
13813 if (strcasecmp(argv[i], fullname1) == 0 ||
13814 strcasecmp(argv[i], fullname2) == 0) {
13815 sprintf(rval, "%s", argv[i + 1]);
13816 contain = 1;
13817 break;
13818 }
13819
13820 /* Close file... */
13821 if (in != NULL)
13822 fclose(in);
13823
13824 /* Check for missing variables... */
13825 if (!contain) {
13826 if (strlen(defvalue) > 0)
13827 sprintf(rval, "%s", defvalue);
13828 else
13829 ERRMSG("Missing variable %s!\n", fullname1);
13830 }
13831
13832 /* Write info... */
13833 LOG(1, "%s = %s", fullname1, rval);
13834
13835 /* Return values... */
13836 if (value != NULL)
13837 sprintf(value, "%s", rval);
13838 return atof(rval);
13839}

◆ sedi()

double sedi ( const double p,
const double T,
const double rp,
const double rhop )

Calculates the sedimentation velocity of a particle in air.

This function calculates the sedimentation velocity of a particle in air using the given parameters.

Parameters
pThe atmospheric pressure [hPa].
TThe temperature [K].
rpThe radius of the particle [microns].
rhopThe density of the particle [kg/m^3].
Returns
The sedimentation velocity of the particle [m/s].

The function performs the following steps:

  • Converts the radius of the particle from microns to meters.
  • Calculates the density of dry air using the given atmospheric pressure and temperature.
  • Calculates the dynamic viscosity of air using Sutherland's formula.
  • Calculates the thermal velocity of an air molecule using the given temperature.
  • Calculates the mean free path of an air molecule.
  • Computes the Knudsen number for air based on the ratio of mean free path to particle radius.
  • Applies the Cunningham slip-flow correction factor to account for particle size.
  • Computes the sedimentation velocity of the particle based on the difference in densities between the particle and air, incorporating the slip-flow correction.
Note
This function assumes that the ideal gas law and Stokes' law are applicable for calculating the sedimentation velocity of the particle.
Nonpositive or nonfinite particle radius or density gives zero velocity.
Author
Lars Hoffmann

Definition at line 13843 of file mptrac.c.

13847 {
13848
13849 if (!isfinite(rp) || rp <= 0. || !isfinite(rhop) || rhop <= 0.)
13850 return 0.;
13851
13852 /* Convert particle radius from microns to m... */
13853 const double rp_help = rp * 1e-6;
13854
13855 /* Density of dry air [kg / m^3]... */
13856 const double rho = RHO(p, T);
13857
13858 /* Dynamic viscosity of air [kg / (m s)]... */
13859 const double eta = 1.8325e-5 * (416.16 / (T + 120.)) * pow(T / 296.16, 1.5);
13860
13861 /* Thermal velocity of an air molecule [m / s]... */
13862 const double v = sqrt(8. * KB * T / (M_PI * M_AIR_MOLECULE));
13863
13864 /* Mean free path of an air molecule [m]... */
13865 const double lambda = 2. * eta / (rho * v);
13866
13867 /* Knudsen number for air (dimensionless)... */
13868 const double K = lambda / rp_help;
13869
13870 /* Cunningham slip-flow correction (dimensionless)... */
13871 const double G = 1. + K * (1.249 + 0.42 * exp(-0.87 / K));
13872
13873 /* Sedimentation velocity [m / s]... */
13874 return 2. * SQR(rp_help) * (rhop - rho) * G0 / (9. * eta) * G;
13875}
#define KB
Boltzmann constant [kg m^2/(K s^2)].
Definition mptrac.h:285
#define M_AIR_MOLECULE
Mean mass of an air molecule [kg].
Definition mptrac.h:340

◆ spline()

void spline ( const double * x,
const double * y,
const int n,
const double * x2,
double * y2,
const int n2,
const int method )

Performs spline interpolation or linear interpolation.

This function interpolates a set of data points using either cubic spline interpolation or linear interpolation, depending on the specified method.

Parameters
xThe array of x-coordinates of the data points.
yThe array of y-coordinates of the data points.
nThe number of data points.
x2The array of x-coordinates where interpolation is required.
y2The array to store the interpolated y-values.
n2The number of points to interpolate.
methodThe interpolation method: 1 for cubic spline, 0 for linear interpolation.

If the method is set to 1 (cubic spline interpolation):

  • The function initializes a cubic spline interpolator using GSL.
  • It interpolates the y-values at the specified x-coordinates using the spline.
  • The interpolated y-values are stored in the provided y2 array.

If the method is set to 0 (linear interpolation):

  • The function performs linear interpolation between adjacent data points.
  • It locates the interval where each interpolation point falls and calculates the interpolated y-value using linear interpolation.
  • The interpolated y-values are stored in the provided y2 array.
Note
The x-coordinates in both arrays (x and x2) must be sorted in ascending order.
Author
Lars Hoffmann

Definition at line 13879 of file mptrac.c.

13886 {
13887
13888 /* Cubic spline interpolation... */
13889 if (method == 1) {
13890
13891 /* Allocate... */
13892 gsl_interp_accel *acc = gsl_interp_accel_alloc();
13893 gsl_spline *s = gsl_spline_alloc(gsl_interp_cspline, (size_t) n);
13894
13895 /* Interpolate profile... */
13896 gsl_spline_init(s, x, y, (size_t) n);
13897 for (int i = 0; i < n2; i++)
13898 if (x2[i] <= x[0])
13899 y2[i] = y[0];
13900 else if (x2[i] >= x[n - 1])
13901 y2[i] = y[n - 1];
13902 else
13903 y2[i] = gsl_spline_eval(s, x2[i], acc);
13904
13905 /* Free... */
13906 gsl_spline_free(s);
13907 gsl_interp_accel_free(acc);
13908 }
13909
13910 /* Linear interpolation... */
13911 else {
13912 for (int i = 0; i < n2; i++)
13913 if (x2[i] <= x[0])
13914 y2[i] = y[0];
13915 else if (x2[i] >= x[n - 1])
13916 y2[i] = y[n - 1];
13917 else {
13918 const int idx = locate_irr(x, n, x2[i]);
13919 y2[i] = LIN(x[idx], y[idx], x[idx + 1], y[idx + 1], x2[i]);
13920 }
13921 }
13922}
Here is the call graph for this function:

◆ stats_welford_update()

void stats_welford_update ( const double x,
const double w,
const double weight_old,
double * mean,
double * m2 )

Update a weighted mean and second central moment with one value.

Uses Welford's online recurrence. The caller maintains the weight sum; weight_old is its value before adding w. m2 accumulates the weighted squared deviations, so the population variance is m2 / weight_sum and the population standard deviation is sqrt(m2 / weight_sum) for a positive final weight sum. Zero weight leaves the statistics unchanged. Negative or nonfinite weights and invalid accumulated weights cause an error. Nonfinite data values propagate to the statistics rather than being silently omitted.

Parameters
xNew data value.
wNonnegative statistical weight of the new value.
weight_oldAccumulated weight before the new value.
meanRunning weighted mean, updated in place.
m2Running weighted second central moment, updated in place.
Author
OpenAI Codex

Definition at line 13926 of file mptrac.c.

13931 {
13932
13933 if (!isfinite(w) || w < 0 || !isfinite(weight_old) || weight_old < 0)
13934 ERRMSG("Invalid statistical weight!");
13935 if (w == 0)
13936 return;
13937
13938 const double weight_new = weight_old + w;
13939 if (!isfinite(weight_new) || weight_new <= 0)
13940 ERRMSG("Invalid accumulated statistical weight!");
13941
13942 const double delta = x - *mean;
13943 *mean += (w / weight_new) * delta;
13944 *m2 += w * delta * (x - *mean);
13945}

◆ stddev()

float stddev ( const float * data,
const int n )

Calculates the standard deviation of a set of data.

This function calculates the standard deviation of a set of floating-point data values.

Parameters
dataPointer to the array of data values.
nNumber of data values in the array.
Returns
The standard deviation of the data values. If the number of data values is less than or equal to 0, returns 0.

The standard deviation is calculated using the formula:

\[ \sigma = \sqrt{\frac{\sum_{i=1}^{n} (x_i - \bar{x})^2}{n}} \]

where:

  • \( \sigma \) is the standard deviation,
  • \( x_i \) is each data value,
  • \( \bar{x} \) is the mean of the data values, and
  • \( n \) is the total number of data values.
Author
Lars Hoffmann

Definition at line 13949 of file mptrac.c.

13951 {
13952
13953 if (n <= 0)
13954 return 0;
13955
13956 /* Accumulate raw moments in double precision before the float result... */
13957 double mean = 0, var = 0;
13958
13959 for (int i = 0; i < n; ++i) {
13960 const double value = (double) data[i];
13961 mean += value;
13962 var += value * value;
13963 }
13964
13965 var = var / (double) n - SQR(mean / (double) n);
13966
13967 return (var > 0 ? (float) sqrt(var) : 0);
13968}

◆ time2jsec()

void time2jsec ( const int year,
const int mon,
const int day,
const int hour,
const int min,
const int sec,
const double remain,
double * jsec )

Converts time components to seconds since January 1, 2000, 12:00:00 UTC.

This function calculates the number of seconds elapsed since January 1, 2000, 12:00:00 UTC, based on the provided year, month, day, hour, minute, and second. It also includes a fractional part to represent the remaining seconds.

Parameters
yearThe year.
monThe month (1-12).
dayThe day of the month (1-31).
hourThe hour of the day (0-23).
minThe minute (0-59).
secThe second (0-59).
remainThe fractional part of seconds.
jsecPointer to store the calculated number of seconds since January 1, 2000, 12:00:00 UTC.

The function calculates the time elapsed since January 1, 2000, 12:00:00 UTC, up to the specified time and includes any fractional seconds indicated by the "remain" parameter.

Note
The function uses the timegm function, which is similar to mktime but operates in UTC.
Author
Lars Hoffmann

Definition at line 13972 of file mptrac.c.

13980 {
13981
13982 struct tm t0, t1;
13983
13984 t0.tm_year = 100;
13985 t0.tm_mon = 0;
13986 t0.tm_mday = 1;
13987 t0.tm_hour = 0;
13988 t0.tm_min = 0;
13989 t0.tm_sec = 0;
13990
13991 t1.tm_year = year - 1900;
13992 t1.tm_mon = mon - 1;
13993 t1.tm_mday = day;
13994 t1.tm_hour = hour;
13995 t1.tm_min = min;
13996 t1.tm_sec = sec;
13997
13998 *jsec = (double) timegm(&t1) - (double) timegm(&t0) + remain;
13999}

◆ timer()

void timer ( const char * name,
const char * group,
const int output )

Measures and reports elapsed time for named and grouped timers.

The timer function measures elapsed time for a specified named timer and an optional group of timers, accumulating time statistics such as minimum, maximum, and mean elapsed times. It also provides an option to log the timing statistics to an output.

Parameters
nameA string representing the name of the timer.
groupA string representing the group to which the timer belongs.
outputAn integer flag indicating whether to report the timing statistics (non-zero to report).

The function keeps track of multiple timers and groups. When called, it:

  • Gets the current time and calculates the elapsed time since the last call.
  • Adds the elapsed time to the current timers' statistics.
  • Reports the statistics if the output parameter is non-zero.
  • Identifies the IDs of the next timer and group based on the provided name and group.
  • Checks if the name and group are new, and if so, initializes them.
  • Saves the starting time for the next measurement.
Note
The function uses OpenMP's omp_get_wtime() to get the current wall time.
The function maintains static arrays and variables to store timer names, groups, and statistics.
The maximum number of timers and groups is defined by the NTIMER macro.
Warning
If the number of timers or groups exceeds NTIMER, the function will trigger an error message.
Author
Lars Hoffmann

Definition at line 14003 of file mptrac.c.

14006 {
14007
14008 static char names[NTIMER][100], groups[NTIMER][100];
14009
14010 static double rt_name[NTIMER], rt_group[NTIMER],
14011 rt_min[NTIMER], rt_max[NTIMER], dt, t0, t1;
14012
14013 static int iname = -1, igroup = -1, nname, ngroup, ct_name[NTIMER];
14014
14015 /* Get time... */
14016 t1 = omp_get_wtime();
14017 dt = t1 - t0;
14018
14019 /* Add elapsed time to current timers... */
14020 if (iname >= 0) {
14021 rt_name[iname] += dt;
14022 rt_min[iname] = (ct_name[iname] <= 0 ? dt : MIN(rt_min[iname], dt));
14023 rt_max[iname] = (ct_name[iname] <= 0 ? dt : MAX(rt_max[iname], dt));
14024 ct_name[iname]++;
14025 }
14026 if (igroup >= 0)
14027 rt_group[igroup] += t1 - t0;
14028
14029 /* Report timers... */
14030 if (output) {
14031 for (int i = 0; i < nname; i++)
14032 LOG(1, "TIMER_%s = %.3f s (min= %g s, mean= %g s,"
14033 " max= %g s, n= %d)", names[i], rt_name[i], rt_min[i],
14034 rt_name[i] / ct_name[i], rt_max[i], ct_name[i]);
14035 for (int i = 0; i < ngroup; i++)
14036 LOG(1, "TIMER_GROUP_%s = %.3f s", groups[i], rt_group[i]);
14037 double total = 0.0;
14038 for (int i = 0; i < nname; i++)
14039 total += rt_name[i];
14040 LOG(1, "TIMER_TOTAL = %.3f s", total);
14041 }
14042
14043 /* Identify IDs of next timer... */
14044 for (iname = 0; iname < nname; iname++)
14045 if (strcasecmp(name, names[iname]) == 0)
14046 break;
14047 for (igroup = 0; igroup < ngroup; igroup++)
14048 if (strcasecmp(group, groups[igroup]) == 0)
14049 break;
14050
14051 /* Check whether this is a new timer... */
14052 if (iname >= nname) {
14053 sprintf(names[iname], "%s", name);
14054 if ((++nname) >= NTIMER)
14055 ERRMSG("Too many timers!");
14056 }
14057
14058 /* Check whether this is a new group... */
14059 if (igroup >= ngroup) {
14060 sprintf(groups[igroup], "%s", group);
14061 if ((++ngroup) >= NTIMER)
14062 ERRMSG("Too many groups!");
14063 }
14064
14065 /* Save starting time... */
14066 t0 = t1;
14067}
#define NTIMER
Maximum number of timers.
Definition mptrac.h:2511

◆ time_from_filename()

double time_from_filename ( const char * filename,
const int offset,
const int with_seconds )

Extracts and converts a timestamp from a filename to Julian seconds.

The time_from_filename function parses a given filename to extract a timestamp and converts it to Julian seconds. The timestamp is expected to follow a specific format and position within the filename, defined by the offset parameter.

Parameters
filenameA string representing the filename containing the timestamp.
offsetAn integer indicating the position from the end of the filename where the timestamp starts.
with_secondsAn integer indicating if the filename contains seconds or not.
Returns
The time in Julian seconds as a double.

The function performs the following steps:

  • Extracts the year, month, day, hour, minute and (optionally) second components of the timestamp from the filename using the given offset.
  • Validates the extracted components to ensure they represent a valid date and time.
  • Converts the validated date and time components to Julian seconds using the time2jsec function.
  • Returns the computed time in Julian seconds.
Note
The expected formats of the timestamp in the filename are:
  • if with_seconds=0: YYYY-MM-DD_HH-MM (e.g., "2023-05-27_14-45")
  • if with_seconds=1: YYYY-MM-DD_HH-MM-SS (e.g., "2023-05-27_14-45-12")
Warning
If the extracted components do not represent a valid date and time, the function will trigger an error message.
Author
Lars Hoffmann

Definition at line 14071 of file mptrac.c.

14074 {
14075
14076 char tstr[10];
14077
14078 double t;
14079
14080 /* Get time from filename... */
14081 int len = (int) strlen(filename);
14082 sprintf(tstr, "%.4s", &filename[len - offset]);
14083 int year = atoi(tstr);
14084 sprintf(tstr, "%.2s", &filename[len - offset + 5]);
14085 int mon = atoi(tstr);
14086 sprintf(tstr, "%.2s", &filename[len - offset + 8]);
14087 int day = atoi(tstr);
14088 sprintf(tstr, "%.2s", &filename[len - offset + 11]);
14089 int hour = atoi(tstr);
14090 sprintf(tstr, "%.2s", &filename[len - offset + 14]);
14091 int min = atoi(tstr);
14092
14093 int sec = 0;
14094 if (with_seconds) {
14095 sprintf(tstr, "%.2s", &filename[len - offset + 17]);
14096 sec = atoi(tstr);
14097 }
14098
14099 /* Check time... */
14100 if (year < 1900 || year > 2100 || mon < 1 || mon > 12 || day < 1
14101 || day > 31 || hour < 0 || hour > 23 || min < 0 || min > 59)
14102 ERRMSG("Cannot read time from filename!");
14103
14104 /* Convert time to Julian seconds... */
14105 time2jsec(year, mon, day, hour, min, sec, 0.0, &t);
14106
14107 /* Return time... */
14108 return t;
14109}
Here is the call graph for this function:

◆ tropo_weight()

double tropo_weight ( const ctl_t * ctl,
const clim_t * clim,
const atm_t * atm,
const int ip )

Computes a weighting factor based on tropopause pressure.

This function calculates a weighting factor for a given pressure value in relation to the tropopause pressure. The weighting factor is determined as follows:

  • Returns 1 if the pressure is greater than a calculated upper limit.
  • Returns 0 if the pressure is less than a calculated lower limit.
  • Linearly interpolates between 1 and 0 within the range defined by the upper and lower limits.
Parameters
[in]ctlPointer to the control data structure.
[in]climPointer to the climatology data structure.
[in]atmPointer to the atmospheric data structure.
[in]ipIndex of the pressure value to evaluate within the atmospheric data.
Returns
Weighting factor (double) in the range [0, 1].
Author
Lars Hoffmann

Definition at line 14113 of file mptrac.c.

14117 {
14118
14119 /* Get tropopause pressure... */
14120 const double pt = clim_tropo(clim, atm->time[ip],
14121 ctl->met_coord_type ==
14122 0 ? atm->lat[ip] : ctl->met_utm_ref_lat);
14123
14124 /* Get pressure range... */
14125 const double p1 = pt * 0.866877899;
14126 const double p0 = pt / 0.866877899;
14127
14128 /* Get weighting factor... */
14129 if (atm->p[ip] > p0)
14130 return 1;
14131 else if (atm->p[ip] < p1)
14132 return 0;
14133 else
14134 return LIN(p0, 1.0, p1, 0.0, atm->p[ip]);
14135}
Here is the call graph for this function:

◆ write_atm_asc()

void write_atm_asc ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes air parcel data to an ASCII file or gnuplot.

The write_atm_asc function writes the atmospheric data stored in the atm structure to an ASCII file specified by filename or to pipe to gnuplot if requested.

Parameters
filenameA string representing the name of the file to write the data to.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.
tThe current time used for filtering and timestamping.

The function performs the following steps:

  • Sets the time interval for the output data based on the control parameters.
  • Checks if gnuplot output is requested and, if so, creates a pipe to gnuplot and sets up the plot.
  • If gnuplot output is not requested, creates an ASCII file for writing.
  • Writes the header information to the output file, including the description of each column.
  • Iterates over the particles in the atm structure, filtering by time if specified, and writes the data to the output file.
  • Closes the output file or gnuplot pipe.
Author
Lars Hoffmann

Definition at line 14139 of file mptrac.c.

14143 {
14144
14145 FILE *out;
14146
14147 /* Set time interval for output... */
14148 const double t0 = t - 0.5 * ctl->dt_mod;
14149 const double t1 = t + 0.5 * ctl->dt_mod;
14150
14151 /* Check if gnuplot output is requested... */
14152 if (ctl->atm_gpfile[0] != '-') {
14153
14154 /* Create gnuplot pipe... */
14155 if (!(out = popen("gnuplot", "w")))
14156 ERRMSG("Cannot create pipe to gnuplot!");
14157
14158 /* Set plot filename... */
14159 fprintf(out, "set out \"%s.png\"\n", filename);
14160
14161 /* Set time string... */
14162 double r;
14163 int year, mon, day, hour, min, sec;
14164 jsec2time(t, &year, &mon, &day, &hour, &min, &sec, &r);
14165 fprintf(out, "timestr=\"%d-%02d-%02d, %02d:%02d UTC\"\n",
14166 year, mon, day, hour, min);
14167
14168 /* Dump gnuplot file to pipe... */
14169 FILE *in;
14170 if (!(in = fopen(ctl->atm_gpfile, "r")))
14171 ERRMSG("Cannot open file!");
14172 char line[LEN];
14173 while (fgets(line, LEN, in))
14174 fprintf(out, "%s", line);
14175 fclose(in);
14176 }
14177
14178 else {
14179
14180 /* Create file... */
14181 if (!(out = fopen(filename, "w")))
14182 ERRMSG("Cannot create file!");
14183 }
14184
14185 /* Write header... */
14186
14187 if (ctl->met_coord_type == 0) {
14188 fprintf(out,
14189 "# $1 = time [s]\n"
14190 "# $2 = altitude [km]\n"
14191 "# $3 = longitude [deg]\n" "# $4 = latitude [deg]\n");
14192 } else {
14193 fprintf(out,
14194 "# $1 = time [s]\n"
14195 "# $2 = altitude [km]\n" "# $3 = x [m]\n" "# $4 = y [m]\n");
14196 }
14197
14198 for (int iq = 0; iq < ctl->nq; iq++)
14199 fprintf(out, "# $%i = %s [%s]\n", iq + 5, ctl->qnt_name[iq],
14200 ctl->qnt_unit[iq]);
14201 fprintf(out, "\n");
14202
14203 /* Write data... */
14204 for (int ip = 0; ip < atm->np; ip += ctl->atm_stride) {
14205
14206 /* Check time... */
14207 if (ctl->atm_filter == 2 && (atm->time[ip] < t0 || atm->time[ip] > t1))
14208 continue;
14209
14210 /* Write output... */
14211 if (ctl->met_coord_type == 0) {
14212 fprintf(out, "%.2f %g %g %g",
14213 atm->time[ip], Z(atm->p[ip]), atm->lon[ip], atm->lat[ip]
14214 );
14215 } else {
14216 fprintf(out, "%.2f %g %.2f %.2f",
14217 atm->time[ip], Z(atm->p[ip]), atm->lon[ip], atm->lat[ip]
14218 );
14219 }
14220
14221 for (int iq = 0; iq < ctl->nq; iq++) {
14222 fprintf(out, " ");
14223 if (ctl->atm_filter == 1 && (atm->time[ip] < t0 || atm->time[ip] > t1))
14224 fprintf(out, ctl->qnt_format[iq], NAN);
14225 else
14226 fprintf(out, ctl->qnt_format[iq], atm->q[iq][ip]);
14227 }
14228 fprintf(out, "\n");
14229 }
14230
14231 /* Close file... */
14232 fclose(out);
14233}
Here is the call graph for this function:

◆ write_atm_bin()

void write_atm_bin ( const char * filename,
const ctl_t * ctl,
const atm_t * atm )

Writes air parcel data to a binary file.

The write_atm_bin function writes the air parcel data stored in the atm structure to a binary file specified by filename. The function includes versioning information and ensures that all relevant data arrays are written in a consistent binary format.

Parameters
filenameA string representing the name of the file to write the data to.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.

The function performs the following steps:

  • Creates the binary file for writing. If the file cannot be created, it triggers an error message.
  • Writes a version number for the binary data format.
  • Writes the number of particles to the file.
  • Writes the time, pressure, longitude, and latitude arrays to the file.
  • Iterates over the quantities specified in the ctl structure and writes each quantity array to the file.
  • Writes a final flag to indicate the end of the binary data.
  • Closes the file.
Author
Lars Hoffmann

Definition at line 14237 of file mptrac.c.

14240 {
14241
14242 FILE *out;
14243
14244 /* Create file... */
14245 if (!(out = fopen(filename, "w")))
14246 ERRMSG("Cannot create file!");
14247
14248 /* Write version of binary data... */
14249 int version = 100;
14250 FWRITE(&version, int,
14251 1,
14252 out);
14253
14254 /* Write data... */
14255 FWRITE(&atm->np, int,
14256 1,
14257 out);
14258 FWRITE(atm->time, double,
14259 (size_t) atm->np,
14260 out);
14261 FWRITE(atm->p, double,
14262 (size_t) atm->np,
14263 out);
14264 FWRITE(atm->lon, double,
14265 (size_t) atm->np,
14266 out);
14267 FWRITE(atm->lat, double,
14268 (size_t) atm->np,
14269 out);
14270 for (int iq = 0; iq < ctl->nq; iq++)
14271 FWRITE(atm->q[iq], double,
14272 (size_t) atm->np,
14273 out);
14274
14275 /* Write final flag... */
14276 int final = 999;
14277 FWRITE(&final, int,
14278 1,
14279 out);
14280
14281 /* Close file... */
14282 fclose(out);
14283}

◆ write_atm_clams()

void write_atm_clams ( const char * filename,
const ctl_t * ctl,
const atm_t * atm )

Writes air parcel data to a NetCDF file in the CLaMS format.

The write_atm_clams function creates a NetCDF file and writes air parcel data into it. The data includes time, latitude, longitude, pressure, and other specified quantities. The function defines the dimensions and variables, sets global attributes, and writes the data to the file.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.

The function performs the following steps:

  • Creates the NetCDF file with the specified filename.
  • Defines the dimensions for time and the number of particles (NPARTS).
  • Defines variables for time, latitude, longitude, pressure, zeta, and other quantities.
  • Sets global attributes for the vertical coordinate name and model.
  • Writes the data into the NetCDF file.
  • Closes the NetCDF file after writing.
Author
Jan Clemens

Definition at line 14287 of file mptrac.c.

14290 {
14291
14292 if (ctl->met_coord_type != 0)
14293 ERRMSG("CLaMS atmospheric files support only lat/lon grids");
14294 if (ctl->qnt_zeta_d < 0 || ctl->qnt_zeta_d >= ctl->nq)
14295 ERRMSG("CLaMS position output requires quantity zeta_d!");
14296
14297 int tid, pid, ncid, varid;
14298 size_t start[2], count[2];
14299
14300 /* Create file... */
14301 NC(nc_create(filename, NC_NETCDF4, &ncid));
14302
14303 /* Define dimensions... */
14304 NC(nc_def_dim(ncid, "time", 1, &tid));
14305 NC(nc_def_dim(ncid, "NPARTS", (size_t) atm->np, &pid));
14306
14307 /* Define variables and their attributes... */
14308 int dim_ids[2] = { tid, pid };
14309 NC_DEF_VAR("time", NC_DOUBLE, 1, &tid, "Time",
14310 "seconds since 2000-01-01 00:00:00 UTC", ctl->atm_nc_level, 0);
14311 NC_DEF_VAR("LAT", NC_DOUBLE, 1, &pid, "Latitude", "deg",
14312 ctl->atm_nc_level, 0);
14313 NC_DEF_VAR("LON", NC_DOUBLE, 1, &pid, "Longitude", "deg",
14314 ctl->atm_nc_level, 0);
14315 NC_DEF_VAR("PRESS", NC_DOUBLE, 1, &pid, "Pressure", "hPa",
14316 ctl->atm_nc_level, 0);
14317 NC_DEF_VAR("ZETA", NC_DOUBLE, 1, &pid, "Zeta", "K", ctl->atm_nc_level, 0);
14318 for (int iq = 0; iq < ctl->nq; iq++)
14319 NC_DEF_VAR(ctl->qnt_name[iq], NC_DOUBLE, 2, dim_ids,
14320 ctl->qnt_name[iq], ctl->qnt_unit[iq],
14321 ctl->atm_nc_level, ctl->atm_nc_quant[iq]);
14322
14323 /* Define global attributes... */
14324 NC_PUT_ATT_GLOBAL("exp_VERTCOOR_name", "zeta");
14325 NC_PUT_ATT_GLOBAL("model", "MPTRAC");
14326
14327 /* End definitions... */
14328 NC(nc_enddef(ncid));
14329
14330 /* Write data... */
14331 NC_PUT_DOUBLE("time", atm->time, 0);
14332 NC_PUT_DOUBLE("LAT", atm->lat, 0);
14333 NC_PUT_DOUBLE("LON", atm->lon, 0);
14334 NC_PUT_DOUBLE("PRESS", atm->p, 0);
14335 NC_PUT_DOUBLE("ZETA", atm->q[ctl->qnt_zeta_d], 0);
14336 for (int iq = 0; iq < ctl->nq; iq++)
14337 NC_PUT_DOUBLE(ctl->qnt_name[iq], atm->q[iq], 0);
14338
14339 /* Close file... */
14340 NC(nc_close(ncid));
14341}
#define NC_PUT_ATT_GLOBAL(attname, text)
Add a global text attribute to a NetCDF file.
Definition mptrac.h:1765
#define NC_DEF_VAR(varname, type, ndims, dims, long_name, units, level, quant)
Define a NetCDF variable with attributes.
Definition mptrac.h:1584
#define NC_PUT_DOUBLE(varname, ptr, hyperslab)
Write double precision data to a NetCDF variable.
Definition mptrac.h:1679

◆ write_atm_clams_traj()

void write_atm_clams_traj ( const char * dirname,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes CLaMS trajectory data to a NetCDF file.

The write_atm_clams_traj function writes trajectory data for the CLaMS model to a NetCDF file. The file is created and populated with data including time, latitude, longitude, pressure, and other quantities. The function also handles the creation of a final initialization file at the last time step.

Parameters
dirnameA string representing the directory name where the file will be created.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.
tThe current time in seconds since a reference epoch.

The function performs the following steps:

  • Determines the start and stop times of the calculation.
  • Constructs the output filename based on the start and stop times.
  • Defines the hyperslab for the trajectory file.
  • Creates the NetCDF file if it's the first time step and defines dimensions and variables.
  • Writes the trajectory data to the NetCDF file.
  • At the last time step, creates an initialization file with the final data.
Author
Jan Clemens

Definition at line 14345 of file mptrac.c.

14349 {
14350
14351 if (ctl->met_coord_type != 0)
14352 ERRMSG("CLaMS atmospheric files support only lat/lon grids");
14353 if (ctl->qnt_zeta_d < 0 || ctl->qnt_zeta_d >= ctl->nq)
14354 ERRMSG("CLaMS trajectory output requires quantity zeta_d!");
14355 if (ctl->advect_vert_coord == 1
14356 && (ctl->qnt_zeta < 0 || ctl->qnt_zeta >= ctl->nq))
14357 ERRMSG("CLaMS diabatic trajectory output requires quantity zeta!");
14358
14359 /* Global Counter... */
14360 static size_t out_cnt = 0;
14361 if (t == ctl->t_start)
14362 out_cnt = 0;
14363
14364 double r, r_start, r_stop;
14365 int year, mon, day, hour, min, sec;
14366 int year_start, mon_start, day_start, hour_start, min_start, sec_start;
14367 int year_stop, mon_stop, day_stop, hour_stop, min_stop, sec_stop;
14368 char filename_out[2 * LEN] = "traj_fix_3d_YYYYMMDDHH_YYYYMMDDHH.nc";
14369
14370 int ncid, varid, tid, pid, cid;
14371 int dim_ids[2];
14372
14373 /* time, nparc */
14374 size_t start[2];
14375 size_t count[2];
14376
14377 /* Determine start and stop times of calculation... */
14378 jsec2time(t, &year, &mon, &day, &hour, &min, &sec, &r);
14379 jsec2time(ctl->t_start, &year_start, &mon_start, &day_start, &hour_start,
14380 &min_start, &sec_start, &r_start);
14381 jsec2time(ctl->t_stop, &year_stop, &mon_stop, &day_stop, &hour_stop,
14382 &min_stop, &sec_stop, &r_stop);
14383
14384 sprintf(filename_out,
14385 "%s/traj_fix_3d_%02d%02d%02d%02d_%02d%02d%02d%02d.nc", dirname,
14386 year_start % 100, mon_start, day_start, hour_start,
14387 year_stop % 100, mon_stop, day_stop, hour_stop);
14388 LOG(1, "Write traj file: %s", filename_out);
14389
14390 /* Define hyperslap for the traj_file... */
14391 start[0] = out_cnt;
14392 start[1] = 0;
14393 count[0] = 1;
14394 count[1] = (size_t) atm->np;
14395
14396 /* Create the file at the first timestep... */
14397 if (out_cnt == 0) {
14398
14399 /* Create file... */
14400 NC(nc_create(filename_out, NC_NETCDF4, &ncid));
14401
14402 /* Define dimensions... */
14403 NC(nc_def_dim(ncid, "time", NC_UNLIMITED, &tid));
14404 NC(nc_def_dim(ncid, "NPARTS", (size_t) atm->np, &pid));
14405 NC(nc_def_dim(ncid, "TMDT", 7, &cid));
14406 dim_ids[0] = tid;
14407 dim_ids[1] = pid;
14408
14409 /* Define variables and their attributes... */
14410 NC_DEF_VAR("time", NC_DOUBLE, 1, &tid, "Time",
14411 "seconds since 2000-01-01 00:00:00 UTC", ctl->atm_nc_level, 0);
14412 NC_DEF_VAR("LAT", NC_DOUBLE, 2, dim_ids, "Latitude", "deg",
14413 ctl->atm_nc_level, 0);
14414 NC_DEF_VAR("LON", NC_DOUBLE, 2, dim_ids, "Longitude", "deg",
14415 ctl->atm_nc_level, 0);
14416 NC_DEF_VAR("PRESS", NC_DOUBLE, 2, dim_ids, "Pressure", "hPa",
14417 ctl->atm_nc_level, 0);
14418 NC_DEF_VAR("ZETA", NC_DOUBLE, 2, dim_ids, "Zeta", "K",
14419 ctl->atm_nc_level, 0);
14420 for (int iq = 0; iq < ctl->nq; iq++)
14421 NC_DEF_VAR(ctl->qnt_name[iq], NC_DOUBLE, 2, dim_ids,
14422 ctl->qnt_name[iq], ctl->qnt_unit[iq],
14423 ctl->atm_nc_level, ctl->atm_nc_quant[iq]);
14424
14425 /* Define global attributes... */
14426 NC_PUT_ATT_GLOBAL("exp_VERTCOOR_name", "zeta");
14427 NC_PUT_ATT_GLOBAL("model", "MPTRAC");
14428
14429 /* End definitions... */
14430 NC(nc_enddef(ncid));
14431 NC(nc_close(ncid));
14432 }
14433
14434 /* Increment global counter to change hyperslap... */
14435 out_cnt++;
14436
14437 /* Open file... */
14438 NC(nc_open(filename_out, NC_WRITE, &ncid));
14439
14440 /* Write data... */
14441 NC_PUT_DOUBLE("time", &t, 1);
14442 NC_PUT_DOUBLE("LAT", atm->lat, 1);
14443 NC_PUT_DOUBLE("LON", atm->lon, 1);
14444 NC_PUT_DOUBLE("PRESS", atm->p, 1);
14445 if (ctl->advect_vert_coord == 1) {
14446 NC_PUT_DOUBLE("ZETA", atm->q[ctl->qnt_zeta], 1);
14447 } else if (ctl->qnt_zeta >= 0) {
14448 NC_PUT_DOUBLE("ZETA", atm->q[ctl->qnt_zeta_d], 1);
14449 }
14450 for (int iq = 0; iq < ctl->nq; iq++)
14451 NC_PUT_DOUBLE(ctl->qnt_name[iq], atm->q[iq], 1);
14452
14453 /* Close file... */
14454 NC(nc_close(ncid));
14455
14456 /* At the last time step create the init_fix_YYYYMMDDHH file... */
14457 if ((year == year_stop) && (mon == mon_stop)
14458 && (day == day_stop) && (hour == hour_stop)) {
14459
14460 /* Set filename... */
14461 char filename_init[2 * LEN] = "./init_fix_YYYYMMDDHH.nc";
14462 sprintf(filename_init, "%s/init_fix_%02d%02d%02d%02d.nc",
14463 dirname, year_stop % 100, mon_stop, day_stop, hour_stop);
14464 LOG(1, "Write init file: %s", filename_init);
14465
14466 /* Create file... */
14467 NC(nc_create(filename_init, NC_NETCDF4, &ncid));
14468
14469 /* Define dimensions... */
14470 NC(nc_def_dim(ncid, "time", 1, &tid));
14471 NC(nc_def_dim(ncid, "NPARTS", (size_t) atm->np, &pid));
14472 dim_ids[0] = tid;
14473 dim_ids[1] = pid;
14474
14475 /* Define variables and their attributes... */
14476 NC_DEF_VAR("time", NC_DOUBLE, 1, &tid, "Time",
14477 "seconds since 2000-01-01 00:00:00 UTC", ctl->atm_nc_level, 0);
14478 NC_DEF_VAR("LAT", NC_DOUBLE, 1, &pid, "Latitude", "deg",
14479 ctl->atm_nc_level, 0);
14480 NC_DEF_VAR("LON", NC_DOUBLE, 1, &pid, "Longitude", "deg",
14481 ctl->atm_nc_level, 0);
14482 NC_DEF_VAR("PRESS", NC_DOUBLE, 1, &pid, "Pressure", "hPa",
14483 ctl->atm_nc_level, 0);
14484 NC_DEF_VAR("ZETA", NC_DOUBLE, 1, &pid, "Zeta", "K", ctl->atm_nc_level, 0);
14485 for (int iq = 0; iq < ctl->nq; iq++)
14486 NC_DEF_VAR(ctl->qnt_name[iq], NC_DOUBLE, 2, dim_ids,
14487 ctl->qnt_name[iq], ctl->qnt_unit[iq],
14488 ctl->atm_nc_level, ctl->atm_nc_quant[iq]);
14489
14490 /* Define global attributes... */
14491 NC_PUT_ATT_GLOBAL("exp_VERTCOOR_name", "zeta");
14492 NC_PUT_ATT_GLOBAL("model", "MPTRAC");
14493
14494 /* End definitions... */
14495 NC(nc_enddef(ncid));
14496
14497 /* Write data... */
14498 NC_PUT_DOUBLE("time", &t, 0);
14499 NC_PUT_DOUBLE("LAT", atm->lat, 0);
14500 NC_PUT_DOUBLE("LON", atm->lon, 0);
14501 NC_PUT_DOUBLE("PRESS", atm->p, 0);
14502 NC_PUT_DOUBLE("ZETA", atm->q[ctl->qnt_zeta_d], 0);
14503 for (int iq = 0; iq < ctl->nq; iq++)
14504 NC_PUT_DOUBLE(ctl->qnt_name[iq], atm->q[iq], 0);
14505
14506 /* Close file... */
14507 NC(nc_close(ncid));
14508 }
14509}
Here is the call graph for this function:

◆ write_atm_nc()

void write_atm_nc ( const char * filename,
const ctl_t * ctl,
const atm_t * atm )

Writes air parcel data to a NetCDF file.

The write_atm_nc function creates a NetCDF file and writes air parcel data into it. The data includes time, pressure, longitude, latitude, and other specified quantities. The function defines the dimensions and variables, sets global attributes, and writes the data to the file.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.

The function performs the following steps:

  • Creates the NetCDF file with the specified filename.
  • Defines the dimension for the number of observations (obs).
  • Defines variables for time, pressure, longitude, latitude, and other quantities.
  • Sets global attributes for the feature type.
  • Writes the data into the NetCDF file.
  • Closes the NetCDF file after writing.
Author
Lars Hoffmann

Definition at line 14513 of file mptrac.c.

14516 {
14517
14518 int ncid, obsid, varid;
14519
14520 size_t start[2], count[2];
14521
14522 /* Create file... */
14523 NC(nc_create(filename, NC_NETCDF4, &ncid));
14524
14525 /* Define dimensions... */
14526 NC(nc_def_dim(ncid, "obs", (size_t) atm->np, &obsid));
14527
14528 /* Define variables and their attributes... */
14529 NC_DEF_VAR("time", NC_DOUBLE, 1, &obsid, "time",
14530 "seconds since 2000-01-01 00:00:00 UTC", ctl->atm_nc_level, 0);
14531 NC_DEF_VAR("press", NC_DOUBLE, 1, &obsid, "pressure", "hPa",
14532 ctl->atm_nc_level, 0);
14533 NC_DEF_VAR("lon", NC_DOUBLE, 1, &obsid, "longitude", "degrees_east",
14534 ctl->atm_nc_level, 0);
14535 NC_DEF_VAR("lat", NC_DOUBLE, 1, &obsid, "latitude", "degrees_north",
14536 ctl->atm_nc_level, 0);
14537 for (int iq = 0; iq < ctl->nq; iq++)
14538 NC_DEF_VAR(ctl->qnt_name[iq], NC_DOUBLE, 1, &obsid,
14539 ctl->qnt_longname[iq], ctl->qnt_unit[iq],
14540 ctl->atm_nc_level, ctl->atm_nc_quant[iq]);
14541
14542 /* Define global attributes... */
14543 NC_PUT_ATT_GLOBAL("featureType", "point");
14544
14545 /* End definitions... */
14546 NC(nc_enddef(ncid));
14547
14548 /* Write data... */
14549 NC_PUT_DOUBLE("time", atm->time, 0);
14550 NC_PUT_DOUBLE("press", atm->p, 0);
14551 NC_PUT_DOUBLE("lon", atm->lon, 0);
14552 NC_PUT_DOUBLE("lat", atm->lat, 0);
14553 for (int iq = 0; iq < ctl->nq; iq++)
14554 NC_PUT_DOUBLE(ctl->qnt_name[iq], atm->q[iq], 0);
14555
14556 /* Close file... */
14557 NC(nc_close(ncid));
14558}

◆ write_budget()

void write_budget ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes a time series of the atmospheric tracer mass budget.

The output contains the number of active air parcels, their total mass, and sums of the configured cumulative mass-loss quantities. If ensembles are enabled, one row per ensemble and an additional total row are written. Domain-decomposed runs report the local budget of each subdomain. Missing mass-loss quantities are reported as NaN.

Parameters
filenamePath to the budget output file.
ctlPointer to the control structure.
atmPointer to the atmospheric data structure.
tCurrent model time [s].
Author
Lars Hoffmann

Definition at line 14562 of file mptrac.c.

14566 {
14567
14568 static FILE *out;
14569
14570 /* Set timer... */
14571 SELECT_TIMER("WRITE_BUDGET", "OUTPUT");
14572
14573 /* Check quantities... */
14574 if (ctl->qnt_m < 0)
14575 ERRMSG("Need quantity mass!");
14576 const int ensemble = (ctl->nens > 0);
14577 if (ensemble && ctl->qnt_ens < 0)
14578 ERRMSG("Missing ensemble IDs!");
14579 if (ctl->nens > NENS)
14580 ERRMSG("Too many ensembles!");
14581
14582 /* Initialize output file... */
14583 if (out == NULL) {
14584 LOG(1, "Write mass budget data: %s", filename);
14585 if (!(out = fopen(filename, "w")))
14586 ERRMSG("Cannot create file!");
14587 fprintf(out,
14588 "# $1 = time [s]\n"
14589 "# $2 = ensemble ID (-999=total)\n"
14590 "# $3 = number of active air parcels [1]\n"
14591 "# $4 = total mass [kg]\n"
14592 "# $5 = mass loss due to OH chemistry [kg]\n"
14593 "# $6 = mass loss due to H2O2 chemistry [kg]\n"
14594 "# $7 = mass loss due to KPP chemistry [kg]\n"
14595 "# $8 = mass loss due to wet deposition [kg]\n"
14596 "# $9 = mass loss due to dry deposition [kg]\n"
14597 "# $10 = mass loss due to exponential decay [kg]\n"
14598 "# $11 = total tracked mass loss [kg]\n"
14599 "# $12 = accounted mass [kg]\n\n");
14600 }
14601
14602 /* Calculate mass budget... */
14603 const int nq = 7;
14604 const int qnt[7] = {
14605 ctl->qnt_m, ctl->qnt_mloss_oh, ctl->qnt_mloss_h2o2,
14606 ctl->qnt_mloss_kpp, ctl->qnt_mloss_wet, ctl->qnt_mloss_dry,
14607 ctl->qnt_mloss_decay
14608 };
14609 double sum[NENS + 1][7] = { {0} };
14610 int np[NENS + 1] = { 0 };
14611 const double t0 = t - 0.5 * ctl->dt_mod;
14612 const double t1 = t + 0.5 * ctl->dt_mod;
14613
14614 /* Sum active air parcels... */
14615 for (int ip = 0; ip < atm->np; ip++) {
14616 if (atm->time[ip] < t0 || atm->time[ip] > t1)
14617 continue;
14618 int e = 0;
14619 if (ensemble) {
14620 const double ens_id = atm->q[ctl->qnt_ens][ip];
14621 if (!isfinite(ens_id) || ens_id < 0 || ens_id >= ctl->nens
14622 || ens_id != floor(ens_id))
14623 ERRMSG("Ensemble ID out of range!");
14624 e = (int) ens_id;
14625 }
14626 np[e]++;
14627 np[NENS]++;
14628 for (int iq = 0; iq < nq; iq++)
14629 if (qnt[iq] >= 0) {
14630 sum[e][iq] += atm->q[qnt[iq]][ip];
14631 sum[NENS][iq] += atm->q[qnt[iq]][ip];
14632 }
14633 }
14634
14635 /* Write total and ensemble budgets... */
14636 for (int ie = -1; ie < (ensemble ? ctl->nens : 0); ie++) {
14637 const int e = (ie < 0 ? NENS : ie);
14638 double mloss = 0;
14639 for (int iq = 1; iq < nq; iq++)
14640 if (qnt[iq] >= 0)
14641 mloss += sum[e][iq];
14642 fprintf(out, "%.2f %d %d %g", t, ie < 0 ? -999 : ie, np[e], sum[e][0]);
14643 for (int iq = 1; iq < nq; iq++)
14644 fprintf(out, " %g", qnt[iq] >= 0 ? sum[e][iq] : NAN);
14645 fprintf(out, " %g %g\n", mloss, sum[e][0] + mloss);
14646 }
14647 fflush(out);
14648
14649 /* Finalize... */
14650 if (t == ctl->t_stop) {
14651 fclose(out);
14652 out = NULL;
14653 }
14654}
#define NENS
Maximum number of data points for ensemble analysis.
Definition mptrac.h:584

◆ write_csi()

void write_csi ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes Critical Success Index (CSI) data to a file.

The write_csi function processes air parcel and observation data to calculate and write various verification statistics, including the Critical Success Index (CSI), to a specified output file at regular intervals. The statistics include measures such as the number of hits, misses, and false alarms, bias, probability of detection, false alarm rate, equitable threat score, and correlation coefficients.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.
tA double representing the current time.

The function performs the following steps:

  • Initializes resources and sets up the output file if the current time is the start time.
  • Reads observation data and kernel data if provided.
  • Sets grid box sizes and horizontal coordinates.
  • Allocates memory for mean and count arrays.
  • Loops over observations and model data to accumulate mean values and counts.
  • Analyzes the grid cells to calculate CSI and other statistics.
  • Writes the calculated statistics to the output file at specified intervals.
  • Frees allocated resources and closes the file when the processing is complete.
Author
Lars Hoffmann

Definition at line 14658 of file mptrac.c.

14662 {
14663
14664 if (ctl->met_coord_type != 0)
14665 ERRMSG("Only lat/lon grid supported");
14666
14667 static FILE *out;
14668
14669 static double *modmean, *obsmean, *obsstd, *rt, *rz, *rlon, *rlat, *robs,
14670 *area, dlon, dlat, dz, x[NCSI], y[NCSI], obsstdn[NCSI], kz[EP], kw[EP];
14671
14672 static int *obscount, nobs, nk;
14673
14674 static int ct[NENS], cx[NENS], cy[NENS], cz[NENS], n[NENS];
14675
14676 const int ensemble = (ctl->nens > 0);
14677
14678 /* Set timer */
14679 SELECT_TIMER("WRITE_CSI", "OUTPUT");
14680
14681 /* Check quantities... */
14682 if (ctl->qnt_m < 0)
14683 ERRMSG("Need quantity mass!");
14684 if (ensemble) {
14685 if (ctl->qnt_ens < 0)
14686 ERRMSG("Missing ensemble IDs!");
14687 if (ctl->nens > NENS)
14688 ERRMSG("Too many ensembles!");
14689 }
14690
14691 /* Init... */
14692 if (t == ctl->t_start) {
14693
14694 /* Start each directory-list task with its own observations and kernel. */
14695 nobs = 0;
14696 nk = 0;
14697
14698 /* Allocate.. */
14699 ALLOC(area, double,
14700 ctl->csi_ny);
14701 ALLOC(rt, double,
14702 NOBS);
14703 ALLOC(rz, double,
14704 NOBS);
14705 ALLOC(rlon, double,
14706 NOBS);
14707 ALLOC(rlat, double,
14708 NOBS);
14709 ALLOC(robs, double,
14710 NOBS);
14711
14712 /* Read observation data... */
14713 read_obs(ctl->csi_obsfile, ctl, rt, rz, rlon, rlat, robs, &nobs);
14714
14715 /* Read kernel data... */
14716 if (ctl->csi_kernel[0] != '-')
14717 read_kernel(ctl->csi_kernel, kz, kw, &nk);
14718
14719 /* Create new file... */
14720 LOG(1, "Write CSI%s data: %s", ensemble ? " ensemble" : "", filename);
14721 if (!(out = fopen(filename, "w")))
14722 ERRMSG("Cannot create file!");
14723
14724 /* Write header... */
14725 fprintf(out,
14726 "# $1 = time [s]\n"
14727 "# $2 = ensemble ID\n"
14728 "# $3 = number of hits (cx)\n"
14729 "# $4 = number of misses (cy)\n"
14730 "# $5 = number of false alarms (cz)\n"
14731 "# $6 = number of observations (cx + cy)\n"
14732 "# $7 = number of forecasts (cx + cz)\n"
14733 "# $8 = bias (%%)\n"
14734 "# $9 = POD (%%)\n"
14735 "# $10 = FAR (%%)\n"
14736 "# $11 = CSI (%%)\n"
14737 "# $12 = hits by random chance\n"
14738 "# $13 = ETS (%%)\n"
14739 "# $14 = Pearson R\n"
14740 "# $15 = Spearman R\n"
14741 "# $16 = mean error [kg/m²]\n"
14742 "# $17 = RMSE [kg/m²]\n"
14743 "# $18 = MAE [kg/m²]\n"
14744 "# $19 = log-likelihood\n" "# $20 = number of points\n\n");
14745
14746 /* Set grid box size... */
14747 dz = (ctl->csi_z1 - ctl->csi_z0) / ctl->csi_nz;
14748 dlon = (ctl->csi_lon1 - ctl->csi_lon0) / ctl->csi_nx;
14749 dlat = (ctl->csi_lat1 - ctl->csi_lat0) / ctl->csi_ny;
14750
14751 /* Set horizontal coordinates... */
14752 for (int iy = 0; iy < ctl->csi_ny; iy++) {
14753 const double lat = ctl->csi_lat0 + dlat * (iy + 0.5);
14754 area[iy] = dlat * dlon * SQR(RE * M_PI / 180.0) * cos(DEG2RAD(lat));
14755 }
14756 }
14757
14758 /* Select an independent, half-open observation window for this snapshot... */
14759 double t0, t1;
14760 OBS_TIME_WINDOW(ctl, t, t0, t1);
14761
14762 /* Allocate... */
14763 int grid_size = ctl->csi_nx * ctl->csi_ny * ctl->csi_nz;
14764 ALLOC(modmean, double,
14765 (ensemble ? ctl->nens : 1) * grid_size);
14766 ALLOC(obsmean, double,
14767 grid_size);
14768 ALLOC(obscount, int,
14769 grid_size);
14770 ALLOC(obsstd, double,
14771 grid_size);
14772
14773 /* Init... */
14774 for (int i = 0; i < (ensemble ? ctl->nens : 1); i++)
14775 ct[i] = cx[i] = cy[i] = cz[i] = n[i] = 0;
14776
14777 /* Loop over observations... */
14778 for (int i = 0; i < nobs; i++) {
14779 if (rt[i] < t0 || rt[i] >= t1 || !isfinite(robs[i]))
14780 continue;
14781
14782 /* Check grid boundaries and calculate indices... */
14783 if (rlon[i] < ctl->csi_lon0 || rlon[i] >= ctl->csi_lon1
14784 || rlat[i] < ctl->csi_lat0 || rlat[i] >= ctl->csi_lat1
14785 || rz[i] < ctl->csi_z0 || rz[i] >= ctl->csi_z1)
14786 continue;
14787 const int ix = (int) ((rlon[i] - ctl->csi_lon0) / dlon);
14788 const int iy = (int) ((rlat[i] - ctl->csi_lat0) / dlat);
14789 const int iz = (int) ((rz[i] - ctl->csi_z0) / dz);
14790 if (ix >= ctl->csi_nx || iy >= ctl->csi_ny || iz >= ctl->csi_nz)
14791 continue;
14792
14793 /* Get mean observation index... */
14794 const int idx = ARRAY_3D(ix, iy, ctl->csi_ny, iz, ctl->csi_nz);
14795 stats_welford_update(robs[i], 1., (double) obscount[idx],
14796 &obsmean[idx], &obsstd[idx]);
14797 obscount[idx]++;
14798 }
14799
14800 /* Analyze model data... */
14801 for (int ip = 0; ip < atm->np; ip++) {
14802
14803 /* Check time... */
14804 if (atm->time[ip] < t0 || atm->time[ip] >= t1)
14805 continue;
14806
14807 /* Get ensemble ID... */
14808 int ens_id = 0;
14809 if (ensemble) {
14810 const double value = atm->q[ctl->qnt_ens][ip];
14811 if (!isfinite(value) || value < 0 || value >= ctl->nens
14812 || value != floor(value))
14813 ERRMSG("Ensemble ID out of range!");
14814 ens_id = (int) value;
14815 }
14816
14817 /* Check grid boundaries and get indices... */
14818 const double zpart = Z(atm->p[ip]);
14819 if (atm->lon[ip] < ctl->csi_lon0
14820 || atm->lon[ip] >= ctl->csi_lon1
14821 || atm->lat[ip] < ctl->csi_lat0
14822 || atm->lat[ip] >= ctl->csi_lat1
14823 || zpart < ctl->csi_z0 || zpart >= ctl->csi_z1)
14824 continue;
14825 const int ix = (int) ((atm->lon[ip] - ctl->csi_lon0) / dlon);
14826 const int iy = (int) ((atm->lat[ip] - ctl->csi_lat0) / dlat);
14827 const int iz = (int) ((zpart - ctl->csi_z0) / dz);
14828 if (ix >= ctl->csi_nx || iy >= ctl->csi_ny || iz >= ctl->csi_nz)
14829 continue;
14830
14831 /* Get total mass in grid cell... */
14832 const int idx =
14833 ens_id * grid_size + ARRAY_3D(ix, iy, ctl->csi_ny, iz, ctl->csi_nz);
14834 modmean[idx] +=
14835 kernel_weight(kz, kw, nk, atm->p[ip]) * atm->q[ctl->qnt_m][ip];
14836 }
14837 for (int e = 0; e < (ensemble ? ctl->nens : 1); e++) {
14838 /* Analyze all grid cells... */
14839 for (int ix = 0; ix < ctl->csi_nx; ix++)
14840 for (int iy = 0; iy < ctl->csi_ny; iy++)
14841 for (int iz = 0; iz < ctl->csi_nz; iz++) {
14842
14843 /* Calculate mean observation index... */
14844 const int idx = ARRAY_3D(ix, iy, ctl->csi_ny, iz, ctl->csi_nz);
14845 if (e == 0)
14846 if (obscount[idx]) {
14847 obsstd[idx] =
14848 (obsstd[idx] < 0 ? 0 : sqrt(obsstd[idx] / obscount[idx]));
14849 }
14850
14851 /* Calculate model mean per ensemble... */
14852 const int midx = e * grid_size + idx;
14853 if (modmean[midx] > 0)
14854 modmean[midx] /= (1e6 * area[iy]);
14855
14856 /* Check number of observations... */
14857 if (obscount[idx]) {
14858
14859 /* Calculate CSI... */
14860 ct[e]++;
14861 if (obsmean[idx] >= ctl->csi_obsmin
14862 && modmean[midx] >= ctl->csi_modmin)
14863 cx[e]++;
14864 else if (obsmean[idx] >= ctl->csi_obsmin)
14865 cy[e]++;
14866 else if (modmean[midx] >= ctl->csi_modmin)
14867 cz[e]++;
14868
14869 /* Save data for other verification statistics... */
14870 if (obsmean[idx] >= ctl->csi_obsmin
14871 || modmean[midx] >= ctl->csi_modmin) {
14872 x[n[e]] = modmean[midx];
14873 y[n[e]] = obsmean[idx];
14874 obsstdn[n[e]] = obsstd[idx];
14875 if ((++n[e]) >= NCSI)
14876 ERRMSG("Too many points for statistics!");
14877 }
14878 }
14879 }
14880 /* Write output... */
14881 if (fmod(t, ctl->csi_dt_out) == 0 || t == ctl->t_stop) {
14882
14883 if (n[e] == 0)
14884 continue;
14885
14886 /* Calculate verification statistics
14887 (https://www.cawcr.gov.au/projects/verification/) ... */
14888 static double work[2 * NCSI], work2[2 * NCSI];
14889 const int n_obs = cx[e] + cy[e];
14890 const int n_for = cx[e] + cz[e];
14891 const double cx_rd = (ct[e] > 0) ? (1. * n_obs * n_for) / ct[e] : NAN;
14892 const double bias = (n_obs > 0) ? 100. * n_for / n_obs : NAN;
14893 const double pod = (n_obs > 0) ? 100. * cx[e] / n_obs : NAN;
14894 const double far = (n_for > 0) ? 100. * cz[e] / n_for : NAN;
14895 const double csi =
14896 (cx[e] + cy[e] + cz[e] >
14897 0) ? 100. * cx[e] / (cx[e] + cy[e] + cz[e]) : NAN;
14898 const double ets =
14899 (cx[e] + cy[e] + cz[e] - cx_rd >
14900 0) ? 100. * (cx[e] - cx_rd) / (cx[e] + cy[e] + cz[e] - cx_rd) : NAN;
14901 const double rho_p = gsl_stats_correlation(x, 1, y, 1, (size_t) n[e]);
14902 const double rho_s =
14903 gsl_stats_spearman(x, 1, y, 1, (size_t) n[e], work);
14904 for (int i = 0; i < n[e]; i++) {
14905 work[i] = x[i] - y[i];
14906 work2[i] = (obsstdn[i] != 0) ? work[i] / obsstdn[i] : 0;
14907 }
14908 const double mean = gsl_stats_mean(work, 1, (size_t) n[e]);
14909 const double rmse =
14910 gsl_stats_sd_with_fixed_mean(work, 1, (size_t) n[e], 0.0);
14911 const double absdev = gsl_stats_absdev_m(work, 1, (size_t) n[e], 0.0);
14912 const double loglikelihood =
14913 gsl_stats_tss_m(work2, 1, (size_t) n[e], 0.0) * -0.5;
14914
14915 /* Write... */
14916 fprintf(out,
14917 "%.2f %d %d %d %d %d %d %g %g %g %g %g %g %g %g %g %g %g %g %d\n",
14918 t, ensemble ? e : -999, cx[e], cy[e], cz[e], n_obs, n_for, bias,
14919 pod, far, csi, cx_rd, ets, rho_p, rho_s, mean, rmse, absdev,
14920 loglikelihood, n[e]);
14921
14922 /* Set counters to zero... */
14923 for (int i = 0; i < n[e]; i++)
14924 work[i] = work2[i] = x[i] = y[i] = obsstdn[i] = 0;
14925 ct[e] = cx[e] = cy[e] = cz[e] = n[e] = 0;
14926 }
14927 }
14928 /* Free... */
14929 free(modmean);
14930 free(obsmean);
14931 free(obscount);
14932 free(obsstd);
14933
14934 /* Finalize... */
14935 if (t == ctl->t_stop) {
14936
14937 /* Close output file... */
14938 fclose(out);
14939
14940 /* Free... */
14941 free(area);
14942 free(rt);
14943 free(rz);
14944 free(rlon);
14945 free(rlat);
14946 free(robs);
14947 }
14948}
void read_obs(const char *filename, const ctl_t *ctl, double *rt, double *rz, double *rlon, double *rlat, double *robs, int *nobs)
Reads observation data from a file and stores it in arrays.
Definition mptrac.c:13670
void stats_welford_update(const double x, const double w, const double weight_old, double *mean, double *m2)
Update a weighted mean and second central moment with one value.
Definition mptrac.c:13926
void read_kernel(const char *filename, double kz[EP], double kw[EP], int *nk)
Reads kernel function data from a file and populates the provided arrays.
Definition mptrac.c:9857
double kernel_weight(const double kz[EP], const double kw[EP], const int nk, const double p)
Calculates the kernel weight based on altitude and given kernel data.
Definition mptrac.c:3642
#define OBS_TIME_WINDOW(ctl, t, t0, t1)
Set the half-open observation window for a model output time.
Definition mptrac.h:1150
#define NCSI
Maximum number of data points for CSI calculation.
Definition mptrac.h:579
Here is the call graph for this function:

◆ write_csi_ens()

void write_csi_ens ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes ensemble-based Critical Success Index (CSI) and other verification statistics to an output file.

This function computes and writes various statistical verification metrics that assess the performance of ensemble forecasts compared to observations. The output includes, for each ensemble member:

  • Critical Success Index (CSI)
  • Equitable Threat Score (ETS)
  • Bias (forecast/observation ratio)
  • Probability of Detection (POD)
  • False Alarm Rate (FAR)
  • Correlation coefficients (Pearson, Spearman)
  • Error metrics (mean error, RMSE, mean absolute error)
  • Log-likelihood of the normalized errors

On the first invocation (when t == ctl->t_start), the function loads observation data and kernel weights, allocates necessary arrays, and creates a new output file with a descriptive header. On the final call (when t == ctl->t_stop), the function closes the file and frees all persistent memory.

Output is written at time steps divisible by ctl->csi_dt_out.

Parameters
[in]filenamePath to the output file where statistics will be written.
[in]ctlPointer to control structure containing configuration, ensemble settings, and spatial/time grid info.
[in]atmPointer to atmospheric data structure holding model output.
[in]tCurrent simulation/model time.
Note
This function maintains internal static buffers and handles memory management across time steps. It validates input configuration and will terminate with an error message if required quantities are missing or if limits (e.g., number of ensembles or data points) are exceeded.
Exceptions
Ifrequired quantities (mass or ensemble IDs) are undefined, if ensemble IDs are out of bounds, or if the output file cannot be created.
Author
Mingzhao Liu

◆ write_ens()

void write_ens ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes ensemble data to a file.

The write_ens function processes air parcel data to calculate ensemble means and standard deviations for various quantities and writes them to a specified output file. It handles ensemble members and calculates statistics such as means and standard deviations for each ensemble, along with latitude, longitude, altitude, and time information.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure containing atmospheric data.
tA double representing the current time.

The function performs the following steps:

  • Initializes resources and sets up necessary variables.
  • Sets a time interval for processing data.
  • Loops over air parcels to accumulate means and standard deviations for each ensemble member.
  • Creates an output file and writes header information.
  • Writes ensemble data, including time, altitude, latitude, longitude, means, standard deviations, and the number of members.
  • Closes the output file.
Author
Lars Hoffmann

Definition at line 14952 of file mptrac.c.

14956 {
14957
14958 if (ctl->met_coord_type != 0)
14959 ERRMSG("Only lat/lon grid supported");
14960
14961 static FILE *out;
14962
14963 static double dummy, lat, lon, qm[NQ][NENS], qs[NQ][NENS], xm[NENS][3],
14964 x[3], zm[NENS];
14965
14966 static int n[NENS];
14967
14968 /* Set timer... */
14969 SELECT_TIMER("WRITE_ENS", "OUTPUT");
14970
14971 /* Check quantities... */
14972 if (ctl->qnt_ens < 0)
14973 ERRMSG("Missing ensemble IDs!");
14974 if (ctl->nens > NENS)
14975 ERRMSG("Too many ensembles!");
14976
14977 /* Set time interval... */
14978 const double t0 = t - 0.5 * ctl->dt_mod;
14979 const double t1 = t + 0.5 * ctl->dt_mod;
14980
14981 /* Init... */
14982 for (int i = 0; i < NENS; i++) {
14983 for (int iq = 0; iq < ctl->nq; iq++)
14984 qm[iq][i] = qs[iq][i] = 0;
14985 xm[i][0] = xm[i][1] = xm[i][2] = zm[i] = 0;
14986 n[i] = 0;
14987 }
14988
14989 /* Loop over air parcels... */
14990 for (int ip = 0; ip < atm->np; ip++) {
14991
14992 /* Check time... */
14993 if (atm->time[ip] < t0 || atm->time[ip] > t1)
14994 continue;
14995
14996 /* Check ensemble ID... */
14997 const double ens_value = atm->q[ctl->qnt_ens][ip];
14998 const int ens_limit = ctl->nens > 0 ? ctl->nens : NENS;
14999 if (!isfinite(ens_value) || ens_value < 0 || ens_value >= ens_limit
15000 || ens_value != floor(ens_value))
15001 ERRMSG("Ensemble ID is out of range!");
15002
15003 /* Accumulate ensemble means and central moments... */
15004 const int ens = (int) ens_value;
15005 geo2cart(0, atm->lon[ip], atm->lat[ip], x);
15006 for (int iq = 0; iq < ctl->nq; iq++)
15007 stats_welford_update(atm->q[iq][ip], 1., (double) n[ens],
15008 &qm[iq][ens], &qs[iq][ens]);
15009 xm[ens][0] += x[0];
15010 xm[ens][1] += x[1];
15011 xm[ens][2] += x[2];
15012 zm[ens] += Z(atm->p[ip]);
15013 n[ens]++;
15014 }
15015
15016 /* Create file... */
15017 LOG(1, "Write ensemble data: %s", filename);
15018 if (!(out = fopen(filename, "w")))
15019 ERRMSG("Cannot create file!");
15020
15021 /* Write header... */
15022 fprintf(out,
15023 "# $1 = time [s]\n"
15024 "# $2 = altitude [km]\n"
15025 "# $3 = longitude [deg]\n" "# $4 = latitude [deg]\n");
15026 for (int iq = 0; iq < ctl->nq; iq++)
15027 fprintf(out, "# $%d = %s (mean) [%s]\n", 5 + iq,
15028 ctl->qnt_name[iq], ctl->qnt_unit[iq]);
15029 for (int iq = 0; iq < ctl->nq; iq++)
15030 fprintf(out, "# $%d = %s (sigma) [%s]\n", 5 + ctl->nq + iq,
15031 ctl->qnt_name[iq], ctl->qnt_unit[iq]);
15032 fprintf(out, "# $%d = number of members\n\n", 5 + 2 * ctl->nq);
15033
15034 /* Write data... */
15035 for (int i = 0; i < NENS; i++)
15036 if (n[i] > 0) {
15037 cart2geo(xm[i], &dummy, &lon, &lat);
15038 fprintf(out, "%.2f %g %g %g", t, zm[i] / n[i], lon, lat);
15039 for (int iq = 0; iq < ctl->nq; iq++) {
15040 fprintf(out, " ");
15041 fprintf(out, ctl->qnt_format[iq], qm[iq][i]);
15042 }
15043 for (int iq = 0; iq < ctl->nq; iq++) {
15044 fprintf(out, " ");
15045 fprintf(out, ctl->qnt_format[iq],
15046 (qs[iq][i] < 0 ? 0 : sqrt(qs[iq][i] / n[i])));
15047 }
15048 fprintf(out, " %d\n", n[i]);
15049 }
15050
15051 /* Close file... */
15052 fclose(out);
15053}
void cart2geo(const double *x, double *z, double *lon, double *lat)
Converts Cartesian coordinates to geographic coordinates.
Definition mptrac.c:76
Here is the call graph for this function:

◆ write_depo()

void write_depo ( const char * filename,
const ctl_t * ctl,
const depo_t * depo,
const double t )

Convert cumulative ground inventories to Bq m^-2 and write them.

Cell centers and areas are derived from GRID_LON*, GRID_LAT*, GRID_NX, and GRID_NY. If RADIO_DECAY is enabled, inventories are decayed to t. Output format is selected by DEPO_TYPE.

Parameters
[in]filenameOutput filename.
[in]ctlGrid, format, compression, and decay settings.
[in]depoCumulative radionuclide inventories.
[in]tOutput validity time [s since 2000-01-01 00:00 UTC].

Definition at line 15057 of file mptrac.c.

15061 {
15062
15063 double *area, *data, *lat, *lon;
15064
15065 /* Set timer... */
15066 SELECT_TIMER("WRITE_DEPO", "OUTPUT");
15067 LOG(1, "Write radioactive deposition data: %s", filename);
15068
15069 /* Allocate output arrays... */
15070 const int nxy = ctl->grid_nx * ctl->grid_ny;
15071 ALLOC(area, double,
15072 ctl->grid_ny);
15073 ALLOC(data, double,
15074 4 * nxy);
15075 ALLOC(lat, double,
15076 ctl->grid_ny);
15077 ALLOC(lon, double,
15078 ctl->grid_nx);
15079
15080 /* Set horizontal coordinates and grid-cell areas... */
15081 const double dlon = (ctl->grid_lon1 - ctl->grid_lon0) / ctl->grid_nx;
15082 const double dlat = (ctl->grid_lat1 - ctl->grid_lat0) / ctl->grid_ny;
15083 for (int ix = 0; ix < ctl->grid_nx; ix++)
15084 lon[ix] = ctl->grid_lon0 + dlon * (ix + 0.5);
15085 for (int iy = 0; iy < ctl->grid_ny; iy++) {
15086 lat[iy] = ctl->grid_lat0 + dlat * (iy + 0.5);
15087 area[iy] = 1e6 * dlat * dlon * SQR(RE * M_PI / 180.)
15088 * cos(DEG2RAD(lat[iy]));
15089 }
15090
15091 /* Convert inventories to activity densities at output time... */
15092 const double lambda[4] = {
15093 log(2.0) / RADIO_HALF_LIFE_PB210,
15094 log(2.0) / RADIO_HALF_LIFE_BE7,
15095 log(2.0) / RADIO_HALF_LIFE_CS137,
15096 log(2.0) / RADIO_HALF_LIFE_I131
15097 };
15098 const double *inventory[4] = {
15099 depo->Apb210, depo->Abe7, depo->Acs137, depo->Ai131
15100 };
15101 for (int iq = 0; iq < 4; iq++) {
15102 const double decay = ctl->radio_decay
15103 ? exp(-lambda[iq] * (t - ctl->t_start)) : 1.0;
15104 for (int ix = 0; ix < ctl->grid_nx; ix++)
15105 for (int iy = 0; iy < ctl->grid_ny; iy++) {
15106 const int idx = ARRAY_2D(ix, iy, ctl->grid_ny);
15107 data[iq * nxy + idx] = inventory[iq][idx] * decay / area[iy];
15108 }
15109 }
15110
15111 /* Write output... */
15112 if (ctl->depo_type == 0)
15113 write_depo_asc(filename, ctl, data, t, lon, lat, area);
15114 else if (ctl->depo_type == 1)
15115 write_depo_nc(filename, ctl, data, t, lon, lat, area);
15116 else
15117 ERRMSG("Radioactive deposition output type unknown!");
15118
15119 /* Free... */
15120 free(area);
15121 free(data);
15122 free(lat);
15123 free(lon);
15124}
void write_depo_asc(const char *filename, const ctl_t *ctl, const double *data, const double t, const double *lon, const double *lat, const double *area)
Write radioactive deposition densities as a gnuplot-compatible table.
Definition mptrac.c:15128
void write_depo_nc(const char *filename, const ctl_t *ctl, const double *data, const double t, const double *lon, const double *lat, const double *area)
Write radioactive deposition densities as a CF-style netCDF file.
Definition mptrac.c:15168
Here is the call graph for this function:

◆ write_depo_asc()

void write_depo_asc ( const char * filename,
const ctl_t * ctl,
const double * data,
const double t,
const double * lon,
const double * lat,
const double * area )

Write radioactive deposition densities as a gnuplot-compatible table.

Parameters
[in]filenameOutput filename.
[in]ctlDeposition grid dimensions.
[in]dataFour consecutive fields in Bq m^-2.
[in]tOutput validity time [s since 2000-01-01 00:00 UTC].
[in]lonGrid-cell center longitudes [deg].
[in]latGrid-cell center latitudes [deg].
[in]areaGrid-cell areas by latitude [m^2].

Definition at line 15128 of file mptrac.c.

15135 {
15136
15137 FILE *out;
15138 if (!(out = fopen(filename, "w")))
15139 ERRMSG("Cannot create file!");
15140
15141 fprintf(out,
15142 "# $1 = time [s]\n"
15143 "# $2 = longitude [deg]\n"
15144 "# $3 = latitude [deg]\n"
15145 "# $4 = area [m^2]\n"
15146 "# $5 = deposited Pb-210 activity [Bq/m^2]\n"
15147 "# $6 = deposited Be-7 activity [Bq/m^2]\n"
15148 "# $7 = deposited Cs-137 activity [Bq/m^2]\n"
15149 "# $8 = deposited I-131 activity [Bq/m^2]\n\n");
15150
15151 const int nxy = ctl->grid_nx * ctl->grid_ny;
15152 for (int ix = 0; ix < ctl->grid_nx; ix++) {
15153 for (int iy = 0; iy < ctl->grid_ny; iy++) {
15154 const int idx = ARRAY_2D(ix, iy, ctl->grid_ny);
15155 fprintf(out, "%.2f %g %g %g %g %g %g %g\n",
15156 t, lon[ix], lat[iy], area[iy],
15157 data[idx], data[nxy + idx],
15158 data[2 * nxy + idx], data[3 * nxy + idx]);
15159 }
15160 fprintf(out, "\n");
15161 }
15162
15163 fclose(out);
15164}

◆ write_depo_nc()

void write_depo_nc ( const char * filename,
const ctl_t * ctl,
const double * data,
const double t,
const double * lon,
const double * lat,
const double * area )

Write radioactive deposition densities as a CF-style netCDF file.

Parameters
[in]filenameOutput filename.
[in]ctlDeposition grid dimensions and netCDF compression setting.
[in]dataFour consecutive fields in Bq m^-2.
[in]tOutput validity time [s since 2000-01-01 00:00 UTC].
[in]lonGrid-cell center longitudes [deg].
[in]latGrid-cell center latitudes [deg].
[in]areaGrid-cell areas by latitude [m^2].

Definition at line 15168 of file mptrac.c.

15175 {
15176
15177 double *help;
15178 int ncid, dimid[3], varid;
15179 size_t start[2], count[2];
15180
15181 const int nxy = ctl->grid_nx * ctl->grid_ny;
15182 ALLOC(help, double,
15183 nxy);
15184
15185 /* Create file and dimensions... */
15186 NC(nc_create(filename, NC_NETCDF4, &ncid));
15187 NC(nc_def_dim(ncid, "time", 1, &dimid[0]));
15188 NC(nc_def_dim(ncid, "lat", (size_t) ctl->grid_ny, &dimid[1]));
15189 NC(nc_def_dim(ncid, "lon", (size_t) ctl->grid_nx, &dimid[2]));
15190
15191 /* Define variables... */
15192 NC_DEF_VAR("time", NC_DOUBLE, 1, &dimid[0], "time",
15193 "seconds since 2000-01-01 00:00:00 UTC", 0, 0);
15194 NC_DEF_VAR("lat", NC_DOUBLE, 1, &dimid[1], "latitude",
15195 "degrees_north", 0, 0);
15196 NC_DEF_VAR("lon", NC_DOUBLE, 1, &dimid[2], "longitude",
15197 "degrees_east", 0, 0);
15198 NC_DEF_VAR("area", NC_DOUBLE, 1, &dimid[1], "surface area", "m**2", 0, 0);
15199 NC_DEF_VAR("depo_pb210", NC_DOUBLE, 3, dimid,
15200 "ground inventory of Pb-210", "Bq m**-2", ctl->grid_nc_level, 0);
15201 NC_DEF_VAR("depo_be7", NC_DOUBLE, 3, dimid,
15202 "ground inventory of Be-7", "Bq m**-2", ctl->grid_nc_level, 0);
15203 NC_DEF_VAR("depo_cs137", NC_DOUBLE, 3, dimid,
15204 "ground inventory of Cs-137", "Bq m**-2", ctl->grid_nc_level, 0);
15205 NC_DEF_VAR("depo_i131", NC_DOUBLE, 3, dimid,
15206 "ground inventory of aerosol-bound I-131", "Bq m**-2",
15207 ctl->grid_nc_level, 0);
15208 NC(nc_enddef(ncid));
15209
15210 /* Write coordinates... */
15211 NC_PUT_DOUBLE("time", &t, 0);
15212 NC_PUT_DOUBLE("lon", lon, 0);
15213 NC_PUT_DOUBLE("lat", lat, 0);
15214 NC_PUT_DOUBLE("area", area, 0);
15215
15216 /* Write fields in netCDF dimension order... */
15217 const char *varname[4] = {
15218 "depo_pb210", "depo_be7", "depo_cs137", "depo_i131"
15219 };
15220 for (int iq = 0; iq < 4; iq++) {
15221 for (int ix = 0; ix < ctl->grid_nx; ix++)
15222 for (int iy = 0; iy < ctl->grid_ny; iy++)
15223 help[ARRAY_2D(iy, ix, ctl->grid_nx)] =
15224 data[iq * nxy + ARRAY_2D(ix, iy, ctl->grid_ny)];
15225 NC_PUT_DOUBLE(varname[iq], help, 0);
15226 }
15227
15228 NC(nc_close(ncid));
15229 free(help);
15230}

◆ write_grid()

void write_grid ( const char * filename,
const ctl_t * ctl,
met_t * met0,
met_t * met1,
const atm_t * atm,
const double t )

Writes grid data to a file in ASCII or netCDF format.

The write_grid function processes air parcel data to calculate various grid-based statistics such as column density, mean, and standard deviation for specified quantities. It then writes this data to a specified output file either in ASCII or netCDF format based on the configuration parameters provided in the ctl structure.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
met0A pointer to a met_t structure containing meteorological data for the initial time step.
met1A pointer to a met_t structure containing meteorological data for the final time step.
atmA pointer to an atm_t structure containing atmospheric data.
tA double representing the current time.

The function performs the following steps:

  • Initializes resources and sets up necessary variables.
  • Reads kernel data if it is specified in the control parameters.
  • Allocates memory for various arrays to store grid data.
  • Determines the grid box size and sets up vertical and horizontal coordinates.
  • Sets a time interval for output data processing.
  • Calculates grid box indices for atmospheric model data.
  • Computes kernel-weighted quantity means and standard deviations within each grid box when GRID_KERNEL is set; an empty total weight gives NaN.
  • Calculates column density and volume mixing ratio.
  • Writes data to the output file either in ASCII or netCDF format based on the specified grid_type in the control parameters.
  • Frees allocated memory.
Note
The function supports parallel processing using OpenMP for certain computational tasks to improve performance.
Author
Lars Hoffmann

Definition at line 15234 of file mptrac.c.

15240 {
15241
15242 if (ctl->met_coord_type != 0)
15243 ERRMSG("Only lat/lon grid supported");
15244
15245 static double kz[EP], kw[EP];
15246
15247 static int nk;
15248
15249 double *cd, *mean[NQ], *sigma[NQ], *vmr_impl, *z, *lon, *lat, *area, *press,
15250 *weight;
15251
15252 int *ixs, *iys, *izs, *np;
15253
15254 /* Set timer... */
15255 SELECT_TIMER("WRITE_GRID", "OUTPUT");
15256
15257 /* Write info... */
15258 LOG(1, "Write grid data: %s", filename);
15259
15260 /* Init... */
15261 if (ctl->grid_kernel[0] == '-')
15262 nk = 0;
15263 else if (nk == 0 || t == ctl->t_start)
15264 read_kernel(ctl->grid_kernel, kz, kw, &nk);
15265
15266 /* Allocate... */
15267 ALLOC(cd, double,
15268 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15269 for (int iq = 0; iq < ctl->nq; iq++) {
15270 ALLOC(mean[iq], double,
15271 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15272 ALLOC(sigma[iq], double,
15273 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15274 }
15275 ALLOC(vmr_impl, double,
15276 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15277 ALLOC(z, double,
15278 ctl->grid_nz);
15279 ALLOC(lon, double,
15280 ctl->grid_nx);
15281 ALLOC(lat, double,
15282 ctl->grid_ny);
15283 ALLOC(area, double,
15284 ctl->grid_ny);
15285 ALLOC(press, double,
15286 ctl->grid_nz);
15287 ALLOC(np, int,
15288 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15289 ALLOC(weight, double,
15290 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15291 ALLOC(ixs, int,
15292 atm->np);
15293 ALLOC(iys, int,
15294 atm->np);
15295 ALLOC(izs, int,
15296 atm->np);
15297
15298 /* Set grid box size... */
15299 const double dz = (ctl->grid_z1 - ctl->grid_z0) / ctl->grid_nz;
15300 const double dlon = (ctl->grid_lon1 - ctl->grid_lon0) / ctl->grid_nx;
15301 const double dlat = (ctl->grid_lat1 - ctl->grid_lat0) / ctl->grid_ny;
15302
15303 /* Set vertical coordinates... */
15304#pragma omp parallel for default(shared)
15305 for (int iz = 0; iz < ctl->grid_nz; iz++) {
15306 z[iz] = ctl->grid_z0 + dz * (iz + 0.5);
15307 press[iz] = P(z[iz]);
15308 }
15309
15310 /* Set horizontal coordinates... */
15311 for (int ix = 0; ix < ctl->grid_nx; ix++)
15312 lon[ix] = ctl->grid_lon0 + dlon * (ix + 0.5);
15313#pragma omp parallel for default(shared)
15314 for (int iy = 0; iy < ctl->grid_ny; iy++) {
15315 lat[iy] = ctl->grid_lat0 + dlat * (iy + 0.5);
15316 area[iy] = dlat * dlon * SQR(RE * M_PI / 180.) * cos(DEG2RAD(lat[iy]));
15317 }
15318
15319 /* Set time interval for output... */
15320 const double t0 = t - 0.5 * ctl->dt_mod;
15321 const double t1 = t + 0.5 * ctl->dt_mod;
15322
15323 /* Get grid box indices... */
15324#pragma omp parallel for default(shared)
15325 for (int ip = 0; ip < atm->np; ip++) {
15326 const double zpart = Z(atm->p[ip]);
15327 if (atm->time[ip] < t0 || atm->time[ip] > t1
15328 || atm->lon[ip] < ctl->grid_lon0
15329 || atm->lon[ip] >= ctl->grid_lon1
15330 || atm->lat[ip] < ctl->grid_lat0
15331 || atm->lat[ip] >= ctl->grid_lat1
15332 || zpart < ctl->grid_z0 || zpart >= ctl->grid_z1) {
15333 izs[ip] = -1;
15334 continue;
15335 }
15336 ixs[ip] = (int) ((atm->lon[ip] - ctl->grid_lon0) / dlon);
15337 iys[ip] = (int) ((atm->lat[ip] - ctl->grid_lat0) / dlat);
15338 izs[ip] = (int) ((zpart - ctl->grid_z0) / dz);
15339 if (ixs[ip] >= ctl->grid_nx || iys[ip] >= ctl->grid_ny
15340 || izs[ip] >= ctl->grid_nz)
15341 izs[ip] = -1;
15342 }
15343
15344 /* Count particles and accumulate kernel-weighted central moments... */
15345 for (int ip = 0; ip < atm->np; ip++)
15346 if (izs[ip] >= 0) {
15347 const int idx =
15348 ARRAY_3D(ixs[ip], iys[ip], ctl->grid_ny, izs[ip], ctl->grid_nz);
15349 const double kernel = kernel_weight(kz, kw, nk, atm->p[ip]);
15350 const double weight_old = weight[idx];
15351 np[idx]++;
15352 if (ctl->qnt_m >= 0)
15353 cd[idx] += kernel * atm->q[ctl->qnt_m][ip];
15354 for (int iq = 0; iq < ctl->nq; iq++)
15355 stats_welford_update(atm->q[iq][ip], kernel, weight_old,
15356 &mean[iq][idx], &sigma[iq][idx]);
15357 weight[idx] += kernel;
15358 }
15359
15360 /* Calculate column density and volume mixing ratio... */
15361#pragma omp parallel for default(shared)
15362 for (int ix = 0; ix < ctl->grid_nx; ix++)
15363 for (int iy = 0; iy < ctl->grid_ny; iy++)
15364 for (int iz = 0; iz < ctl->grid_nz; iz++) {
15365
15366 /* Get grid index... */
15367 const int idx = ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz);
15368
15369 /* Calculate column density... */
15370 if (ctl->qnt_m >= 0)
15371 cd[idx] /= (1e6 * area[iy]);
15372 else
15373 cd[idx] = NAN;
15374
15375 /* Calculate volume mixing ratio (implicit)... */
15376 vmr_impl[idx] = NAN;
15377 if (ctl->qnt_m >= 0 && ctl->molmass > 0 && met0 != NULL
15378 && met1 != NULL) {
15379 vmr_impl[idx] = 0;
15380 if (cd[idx] > 0) {
15381
15382 /* Get temperature... */
15383 double temp;
15385 intpol_met_time_3d(met0, met0->t, met1, met1->t, t, press[iz],
15386 lon[ix], lat[iy], &temp, ci, cw, 1);
15387
15388 /* Calculate volume mixing ratio... */
15389 vmr_impl[idx] =
15390 MA / ctl->molmass * cd[idx] / (RHO(press[iz], temp) * dz * 1e3);
15391 }
15392 }
15393
15394 /* Normalize weighted means and variances by total kernel weight... */
15395 if (weight[idx] > 0)
15396 for (int iq = 0; iq < ctl->nq; iq++) {
15397 sigma[iq][idx] =
15398 (sigma[iq][idx] < 0 ? 0 : sqrt(sigma[iq][idx] / weight[idx]));
15399 } else
15400 for (int iq = 0; iq < ctl->nq; iq++) {
15401 mean[iq][idx] = NAN;
15402 sigma[iq][idx] = NAN;
15403 }
15404 }
15405
15406 /* Write ASCII data... */
15407 if (ctl->grid_type == 0)
15408 write_grid_asc(filename, ctl, cd, mean, sigma, vmr_impl,
15409 t, z, lon, lat, area, dz, np);
15410
15411 /* Write netCDF data... */
15412 else if (ctl->grid_type == 1)
15413 write_grid_nc(filename, ctl, cd, mean, sigma, vmr_impl,
15414 t, z, lon, lat, area, dz, np);
15415
15416 /* Error message... */
15417 else
15418 ERRMSG("Grid data format GRID_TYPE unknown!");
15419
15420 /* Free... */
15421 free(cd);
15422 for (int iq = 0; iq < ctl->nq; iq++) {
15423 free(mean[iq]);
15424 free(sigma[iq]);
15425 }
15426 free(vmr_impl);
15427 free(z);
15428 free(lon);
15429 free(lat);
15430 free(area);
15431 free(press);
15432 free(np);
15433 free(weight);
15434 free(ixs);
15435 free(iys);
15436 free(izs);
15437}
void write_grid_asc(const char *filename, const ctl_t *ctl, const double *cd, double *mean[NQ], double *sigma[NQ], const double *vmr_impl, const double t, const double *z, const double *lon, const double *lat, const double *area, const double dz, const int *np)
Writes grid data to an ASCII file.
Definition mptrac.c:15441
void write_grid_nc(const char *filename, const ctl_t *ctl, const double *cd, double *mean[NQ], double *sigma[NQ], const double *vmr_impl, const double t, const double *z, const double *lon, const double *lat, const double *area, const double dz, const int *np)
Writes grid data to a NetCDF file.
Definition mptrac.c:15545
Here is the call graph for this function:

◆ write_grid_asc()

void write_grid_asc ( const char * filename,
const ctl_t * ctl,
const double * cd,
double * mean[NQ],
double * sigma[NQ],
const double * vmr_impl,
const double t,
const double * z,
const double * lon,
const double * lat,
const double * area,
const double dz,
const int * np )

Writes grid data to an ASCII file.

The write_grid_asc function writes gridded air parcel data, including column density, mean and standard deviation for specified quantities, and volume mixing ratio (if available), to an ASCII file. The function also supports writing gnuplot commands to generate plots if requested in the control parameters.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
cdAn array of doubles representing column density values.
meanAn array of arrays of doubles representing the mean values for specified quantities.
sigmaAn array of arrays of doubles representing the standard deviation values for specified quantities.
vmr_implAn array of doubles representing the volume mixing ratio (implicit) values.
tA double representing the current time.
zAn array of doubles representing vertical coordinates (altitude).
lonAn array of doubles representing longitudinal coordinates.
latAn array of doubles representing latitudinal coordinates.
areaAn array of doubles representing surface area values.
dzA double representing the layer depth.
npAn array of integers representing the number of particles.

The function performs the following steps:

  • Checks if gnuplot output is requested in the control parameters and sets up a gnuplot pipe if needed.
  • If gnuplot output is requested, sets the plot filename and time string, and dumps gnuplot file contents to the pipe.
  • Otherwise, creates the output file for writing in ASCII format.
  • Writes the header information to the output file, including column labels.
  • Writes the grid data to the output file, including time, altitude, coordinates, surface area, layer depth, column density, volume mixing ratio, number of particles, mean values for specified quantities, and standard deviation values if requested.
  • Closes the output file.
Note
The function supports writing gnuplot commands to generate plots if requested in the control parameters. It also supports writing mean and standard deviation values for specified quantities if requested.
Author
Lars Hoffmann

Definition at line 15441 of file mptrac.c.

15454 {
15455
15456 FILE *out;
15457
15458 /* Check if gnuplot output is requested... */
15459 if (ctl->grid_gpfile[0] != '-') {
15460
15461 /* Create gnuplot pipe... */
15462 if (!(out = popen("gnuplot", "w")))
15463 ERRMSG("Cannot create pipe to gnuplot!");
15464
15465 /* Set plot filename... */
15466 fprintf(out, "set out \"%s.png\"\n", filename);
15467
15468 /* Set time string... */
15469 double r;
15470 int year, mon, day, hour, min, sec;
15471 jsec2time(t, &year, &mon, &day, &hour, &min, &sec, &r);
15472 fprintf(out, "timestr=\"%d-%02d-%02d, %02d:%02d UTC\"\n",
15473 year, mon, day, hour, min);
15474
15475 /* Dump gnuplot file to pipe... */
15476 FILE *in;
15477 char line[LEN];
15478 if (!(in = fopen(ctl->grid_gpfile, "r")))
15479 ERRMSG("Cannot open file!");
15480 while (fgets(line, LEN, in))
15481 fprintf(out, "%s", line);
15482 fclose(in);
15483 }
15484
15485 else {
15486
15487 /* Create file... */
15488 if (!(out = fopen(filename, "w")))
15489 ERRMSG("Cannot create file!");
15490 }
15491
15492 /* Write header... */
15493 fprintf(out,
15494 "# $1 = time [s]\n"
15495 "# $2 = altitude [km]\n"
15496 "# $3 = longitude [deg]\n"
15497 "# $4 = latitude [deg]\n"
15498 "# $5 = surface area [km^2]\n"
15499 "# $6 = layer depth [km]\n"
15500 "# $7 = column density (implicit) [kg/m^2]\n"
15501 "# $8 = volume mixing ratio (implicit) [ppv]\n"
15502 "# $9 = number of particles [1]\n");
15503 for (int iq = 0; iq < ctl->nq; iq++)
15504 fprintf(out, "# $%i = %s (mean) [%s]\n", 10 + iq, ctl->qnt_name[iq],
15505 ctl->qnt_unit[iq]);
15506 if (ctl->grid_stddev)
15507 for (int iq = 0; iq < ctl->nq; iq++)
15508 fprintf(out, "# $%i = %s (stddev) [%s]\n", 10 + ctl->nq + iq,
15509 ctl->qnt_name[iq], ctl->qnt_unit[iq]);
15510 fprintf(out, "\n");
15511
15512 /* Write data... */
15513 for (int ix = 0; ix < ctl->grid_nx; ix++) {
15514 if (ix > 0 && ctl->grid_ny > 1 && !ctl->grid_sparse)
15515 fprintf(out, "\n");
15516 for (int iy = 0; iy < ctl->grid_ny; iy++) {
15517 if (iy > 0 && ctl->grid_nz > 1 && !ctl->grid_sparse)
15518 fprintf(out, "\n");
15519 for (int iz = 0; iz < ctl->grid_nz; iz++) {
15520 int idx = ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz);
15521 if (!ctl->grid_sparse || vmr_impl[idx] > 0) {
15522 fprintf(out, "%.2f %g %g %g %g %g %g %g %d", t, z[iz], lon[ix],
15523 lat[iy], area[iy], dz, cd[idx], vmr_impl[idx], np[idx]);
15524 for (int iq = 0; iq < ctl->nq; iq++) {
15525 fprintf(out, " ");
15526 fprintf(out, ctl->qnt_format[iq], mean[iq][idx]);
15527 }
15528 if (ctl->grid_stddev)
15529 for (int iq = 0; iq < ctl->nq; iq++) {
15530 fprintf(out, " ");
15531 fprintf(out, ctl->qnt_format[iq], sigma[iq][idx]);
15532 }
15533 fprintf(out, "\n");
15534 }
15535 }
15536 }
15537 }
15538
15539 /* Close file... */
15540 fclose(out);
15541}
Here is the call graph for this function:

◆ write_grid_nc()

void write_grid_nc ( const char * filename,
const ctl_t * ctl,
const double * cd,
double * mean[NQ],
double * sigma[NQ],
const double * vmr_impl,
const double t,
const double * z,
const double * lon,
const double * lat,
const double * area,
const double dz,
const int * np )

Writes grid data to a NetCDF file.

The write_grid_nc function writes gridded air parcel data, including column density, mean and standard deviation for specified quantities, and volume mixing ratio (if available), to a NetCDF file. NetCDF is a self-describing, machine-independent data format for storing scientific data.

Parameters
filenameA string representing the name of the output file.
ctlA pointer to a ctl_t structure containing control parameters.
cdAn array of doubles representing column density values.
meanAn array of arrays of doubles representing the mean values for specified quantities.
sigmaAn array of arrays of doubles representing the standard deviation values for specified quantities.
vmr_implAn array of doubles representing the volume mixing ratio (implicit) values.
tA double representing the current time.
zAn array of doubles representing vertical coordinates (altitude).
lonAn array of doubles representing longitudinal coordinates.
latAn array of doubles representing latitudinal coordinates.
areaAn array of doubles representing surface area values.
dzA double representing the layer depth.
npAn array of integers representing the number of particles.

The function performs the following steps:

  • Allocates memory for temporary arrays required for writing data.
  • Creates a NetCDF file with the specified filename.
  • Defines dimensions and variables in the NetCDF file, along with their attributes.
  • Writes the data arrays to the NetCDF file.
  • Closes the NetCDF file.
  • Frees allocated memory.
Note
NetCDF files are commonly used in scientific computing and can be accessed by various programming languages and software packages. Additionally, the function supports writing mean and standard deviation values for specified quantities if requested.
Author
Lars Hoffmann

Definition at line 15545 of file mptrac.c.

15558 {
15559
15560 char longname[2 * LEN], varname[2 * LEN];
15561
15562 double *help;
15563
15564 int *help2, ncid, dimid[10], varid;
15565
15566 size_t start[2], count[2];
15567
15568 /* Allocate... */
15569 ALLOC(help, double,
15570 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15571 ALLOC(help2, int,
15572 ctl->grid_nx * ctl->grid_ny * ctl->grid_nz);
15573
15574 /* Create file... */
15575 NC(nc_create(filename, NC_NETCDF4, &ncid));
15576
15577 /* Define dimensions... */
15578 NC(nc_def_dim(ncid, "time", 1, &dimid[0]));
15579 NC(nc_def_dim(ncid, "z", (size_t) ctl->grid_nz, &dimid[1]));
15580 NC(nc_def_dim(ncid, "lat", (size_t) ctl->grid_ny, &dimid[2]));
15581 NC(nc_def_dim(ncid, "lon", (size_t) ctl->grid_nx, &dimid[3]));
15582 NC(nc_def_dim(ncid, "dz", 1, &dimid[4]));
15583
15584 /* Define variables and their attributes... */
15585 NC_DEF_VAR("time", NC_DOUBLE, 1, &dimid[0], "time",
15586 "seconds since 2000-01-01 00:00:00 UTC", 0, 0);
15587 NC_DEF_VAR("z", NC_DOUBLE, 1, &dimid[1], "altitude", "km", 0, 0);
15588 NC_DEF_VAR("lat", NC_DOUBLE, 1, &dimid[2], "latitude", "degrees_north", 0,
15589 0);
15590 NC_DEF_VAR("lon", NC_DOUBLE, 1, &dimid[3], "longitude", "degrees_east", 0,
15591 0);
15592 NC_DEF_VAR("dz", NC_DOUBLE, 1, &dimid[4], "layer depth", "km", 0, 0);
15593 NC_DEF_VAR("area", NC_DOUBLE, 1, &dimid[2], "surface area", "km**2", 0, 0);
15594
15595 NC_DEF_VAR("cd", NC_FLOAT, 4, dimid, "column density", "kg m**-2",
15596 ctl->grid_nc_level, 0);
15597 NC_DEF_VAR("vmr_impl", NC_FLOAT, 4, dimid,
15598 "volume mixing ratio (implicit)", "ppv", ctl->grid_nc_level, 0);
15599 NC_DEF_VAR("np", NC_INT, 4, dimid, "number of particles", "1", 0, 0);
15600 for (int iq = 0; iq < ctl->nq; iq++) {
15601 sprintf(varname, "%s_mean", ctl->qnt_name[iq]);
15602 sprintf(longname, "%s (mean)", ctl->qnt_longname[iq]);
15603 NC_DEF_VAR(varname, NC_DOUBLE, 4, dimid, longname, ctl->qnt_unit[iq],
15604 ctl->grid_nc_level, ctl->grid_nc_quant[iq]);
15605 if (ctl->grid_stddev) {
15606 sprintf(varname, "%s_stddev", ctl->qnt_name[iq]);
15607 sprintf(longname, "%s (stddev)", ctl->qnt_longname[iq]);
15608 NC_DEF_VAR(varname, NC_DOUBLE, 4, dimid, longname, ctl->qnt_unit[iq],
15609 ctl->grid_nc_level, ctl->grid_nc_quant[iq]);
15610 }
15611 }
15612 /* End definitions... */
15613 NC(nc_enddef(ncid));
15614
15615 /* Write data... */
15616 NC_PUT_DOUBLE("time", &t, 0);
15617 NC_PUT_DOUBLE("lon", lon, 0);
15618 NC_PUT_DOUBLE("lat", lat, 0);
15619 NC_PUT_DOUBLE("z", z, 0);
15620 NC_PUT_DOUBLE("area", area, 0);
15621 NC_PUT_DOUBLE("dz", &dz, 0);
15622
15623 /* Reorder internal lon/lat/z arrays to netCDF z/lat/lon order... */
15624 for (int ix = 0; ix < ctl->grid_nx; ix++)
15625 for (int iy = 0; iy < ctl->grid_ny; iy++)
15626 for (int iz = 0; iz < ctl->grid_nz; iz++)
15627 help[ARRAY_3D(iz, iy, ctl->grid_ny, ix, ctl->grid_nx)] =
15628 cd[ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz)];
15629 NC_PUT_DOUBLE("cd", help, 0);
15630
15631 for (int ix = 0; ix < ctl->grid_nx; ix++)
15632 for (int iy = 0; iy < ctl->grid_ny; iy++)
15633 for (int iz = 0; iz < ctl->grid_nz; iz++)
15634 help[ARRAY_3D(iz, iy, ctl->grid_ny, ix, ctl->grid_nx)] =
15635 vmr_impl[ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz)];
15636 NC_PUT_DOUBLE("vmr_impl", help, 0);
15637
15638 for (int ix = 0; ix < ctl->grid_nx; ix++)
15639 for (int iy = 0; iy < ctl->grid_ny; iy++)
15640 for (int iz = 0; iz < ctl->grid_nz; iz++)
15641 help2[ARRAY_3D(iz, iy, ctl->grid_ny, ix, ctl->grid_nx)] =
15642 np[ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz)];
15643 NC_PUT_INT("np", help2, 0);
15644
15645 for (int iq = 0; iq < ctl->nq; iq++) {
15646 sprintf(varname, "%s_mean", ctl->qnt_name[iq]);
15647 for (int ix = 0; ix < ctl->grid_nx; ix++)
15648 for (int iy = 0; iy < ctl->grid_ny; iy++)
15649 for (int iz = 0; iz < ctl->grid_nz; iz++)
15650 help[ARRAY_3D(iz, iy, ctl->grid_ny, ix, ctl->grid_nx)] =
15651 mean[iq][ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz)];
15652 NC_PUT_DOUBLE(varname, help, 0);
15653 }
15654
15655 if (ctl->grid_stddev)
15656 for (int iq = 0; iq < ctl->nq; iq++) {
15657 sprintf(varname, "%s_stddev", ctl->qnt_name[iq]);
15658 for (int ix = 0; ix < ctl->grid_nx; ix++)
15659 for (int iy = 0; iy < ctl->grid_ny; iy++)
15660 for (int iz = 0; iz < ctl->grid_nz; iz++)
15661 help[ARRAY_3D(iz, iy, ctl->grid_ny, ix, ctl->grid_nx)] =
15662 sigma[iq][ARRAY_3D(ix, iy, ctl->grid_ny, iz, ctl->grid_nz)];
15663 NC_PUT_DOUBLE(varname, help, 0);
15664 }
15665
15666 /* Close file... */
15667 NC(nc_close(ncid));
15668
15669 /* Free... */
15670 free(help);
15671 free(help2);
15672}
#define NC_PUT_INT(varname, ptr, hyperslab)
Write integer data to a NetCDF variable.
Definition mptrac.h:1726

◆ write_met_bin()

void write_met_bin ( const char * filename,
const ctl_t * ctl,
met_t * met )

Writes meteorological data in binary format to a specified file.

This function writes meteorological data from the met_t structure to a binary file. The data includes grid and surface data, as well as multi-level data such as temperature, velocity components, and atmospheric properties. The compression options for multi-level data (ZFP) are controlled via the ctl_t structure. The function supports multiple variables, such as surface pressure, temperature, wind components, and cloud properties.

Parameters
filenameA constant character pointer representing the name of the file to write the binary data to.
ctlA pointer to a ctl_t structure, which holds control parameters including the type of meteorological data, compression settings, and grid dimensions.
metA pointer to a met_t structure that contains the meteorological data to be written to the binary file.
Note
  • The function creates a new file to write the data. If the file cannot be created, an error is generated.
  • The type of meteorological data (ctl->met_type) and the version of the binary format are written at the beginning of the file.
  • Grid data such as longitude, latitude, pressure levels, and time are written to the file.
  • Surface data (e.g., pressure, temperature, wind components) are written using the write_met_bin_2d helper function.
  • Multi-level (3D) data such as geopotential height, temperature, and wind velocity are written using the write_met_bin_3d function with optional ZFP compression settings.
Author
Lars Hoffmann

Definition at line 15676 of file mptrac.c.

15679 {
15680
15681 /* Create file... */
15682 FILE *out, *level_log = NULL;
15683 if (!(out = fopen(filename, "w")))
15684 ERRMSG("Cannot create file!");
15685
15686 /* Create diagnostics file... */
15687 if (strcmp(ctl->met_comp_logfile, "-") != 0) {
15688
15689 if (!(level_log = fopen(ctl->met_comp_logfile, "w")))
15690 ERRMSG("Cannot create compression log file!");
15691 LOG(1, "Write compression diagnostics: %s", ctl->met_comp_logfile);
15692
15693 /* Write header... */
15694 fprintf(level_log,
15695 "# $1 = compression codec name [-]\n"
15696 "# $2 = variable name [-]\n"
15697 "# $3 = level index [-]\n"
15698 "# $4 = pressure level [hPa]\n"
15699 "# $5 = compression ratio [-]\n"
15700 "# $6 = bits per value [bit/value]\n"
15701 "# $7 = correlation coefficient [-]\n"
15702 "# $8 = mean compression error [-]\n"
15703 "# $9 = standard deviation of compression error [-]\n"
15704 "# $10 = minimum compression error [-]\n"
15705 "# $11 = maximum compression error [-]\n"
15706 "# $12 = mean value of original field [-]\n"
15707 "# $13 = value range of original field [-]\n"
15708 "# $14 = normalized root mean square error [-]\n"
15709 "# $15 = compression time [s]\n"
15710 "# $16 = compression speed [MiB/s]\n"
15711 "# $17 = decompression time [s]\n"
15712 "# $18 = decompression speed [MiB/s]\n\n");
15713 }
15714
15715 /* Write type of binary data... */
15716 FWRITE(&ctl->met_type, int,
15717 1,
15718 out);
15719
15720 /* Write version of binary data... */
15721 int version = 104;
15722 FWRITE(&version, int,
15723 1,
15724 out);
15725
15726 /* Write grid data... */
15727 FWRITE(&met->time, double,
15728 1,
15729 out);
15730 FWRITE(&met->nx, int,
15731 1,
15732 out);
15733 FWRITE(&met->ny, int,
15734 1,
15735 out);
15736 FWRITE(&met->np, int,
15737 1,
15738 out);
15739 FWRITE(met->lon, double,
15740 (size_t) met->nx,
15741 out);
15742 FWRITE(met->lat, double,
15743 (size_t) met->ny,
15744 out);
15745 FWRITE(met->p, double,
15746 (size_t) met->np,
15747 out);
15748
15749 /* Write surface data... */
15750 write_met_bin_2d(out, met, met->ps, "PS");
15751 write_met_bin_2d(out, met, met->ts, "TS");
15752 write_met_bin_2d(out, met, met->zs, "ZS");
15753 write_met_bin_2d(out, met, met->us, "US");
15754 write_met_bin_2d(out, met, met->vs, "VS");
15755 write_met_bin_2d(out, met, met->ess, "ESS");
15756 write_met_bin_2d(out, met, met->nss, "NSS");
15757 write_met_bin_2d(out, met, met->shf, "SHF");
15758 write_met_bin_2d(out, met, met->lsm, "LSM");
15759 write_met_bin_2d(out, met, met->sst, "SST");
15760 write_met_bin_2d(out, met, met->pbl, "PBL");
15761 write_met_bin_2d(out, met, met->pt, "PT");
15762 write_met_bin_2d(out, met, met->tt, "TT");
15763 write_met_bin_2d(out, met, met->zt, "ZT");
15764 write_met_bin_2d(out, met, met->h2ot, "H2OT");
15765 write_met_bin_2d(out, met, met->pct, "PCT");
15766 write_met_bin_2d(out, met, met->pcb, "PCB");
15767 write_met_bin_2d(out, met, met->cl, "CL");
15768 write_met_bin_2d(out, met, met->plcl, "PLCL");
15769 write_met_bin_2d(out, met, met->plfc, "PLFC");
15770 write_met_bin_2d(out, met, met->pel, "PEL");
15771 write_met_bin_2d(out, met, met->cape, "CAPE");
15772 write_met_bin_2d(out, met, met->cin, "CIN");
15773 write_met_bin_2d(out, met, met->o3c, "O3C");
15774
15775 /* Write level data... */
15776 write_met_bin_3d(out, ctl, met, met->z, "Z", 0, level_log);
15777 write_met_bin_3d(out, ctl, met, met->t, "T", 1, level_log);
15778 write_met_bin_3d(out, ctl, met, met->u, "U", 2, level_log);
15779 write_met_bin_3d(out, ctl, met, met->v, "V", 3, level_log);
15780 write_met_bin_3d(out, ctl, met, met->w, "W", 4, level_log);
15781 write_met_bin_3d(out, ctl, met, met->pv, "PV", 5, level_log);
15782 write_met_bin_3d(out, ctl, met, met->h2o, "H2O", 6, level_log);
15783 write_met_bin_3d(out, ctl, met, met->o3, "O3", 7, level_log);
15784 write_met_bin_3d(out, ctl, met, met->lwc, "LWC", 8, level_log);
15785 write_met_bin_3d(out, ctl, met, met->rwc, "RWC", 9, level_log);
15786 write_met_bin_3d(out, ctl, met, met->iwc, "IWC", 10, level_log);
15787 write_met_bin_3d(out, ctl, met, met->swc, "SWC", 11, level_log);
15788 write_met_bin_3d(out, ctl, met, met->cc, "CC", 12, level_log);
15789 if (METVAR != 13)
15790 ERRMSG("Number of meteo variables doesn't match!");
15791
15792 /* Write final flag... */
15793 int final = 999;
15794 FWRITE(&final, int,
15795 1,
15796 out);
15797
15798 /* Close file... */
15799 if (level_log)
15800 fclose(level_log);
15801 fclose(out);
15802}
void write_met_bin_3d(FILE *out, const ctl_t *ctl, met_t *met, float var[EX][EY][EP], const char *varname, const int metvar, FILE *level_log)
Writes a 3-dimensional meteorological variable to a binary file.
Definition mptrac.c:15835
void write_met_bin_2d(FILE *out, met_t *met, float var[EX][EY], const char *varname)
Writes a 2-dimensional meteorological variable to a binary file.
Definition mptrac.c:15806
Here is the call graph for this function:

◆ write_met_bin_2d()

void write_met_bin_2d ( FILE * out,
met_t * met,
float var[EX][EY],
const char * varname )

Writes a 2-dimensional meteorological variable to a binary file.

The write_met_bin_2d function writes a 2-dimensional meteorological variable to a binary file specified by the out parameter. The variable data is provided in a 2-dimensional array var with maximum dimensions EX by EY. The variable name is provided as a string in the varname parameter.

Parameters
outA pointer to a FILE structure representing the output file.
metA pointer to a met_t structure containing meteorological data.
varAn array of floats representing the 2-dimensional variable data.
varnameA string containing the name of the variable being written.

The function performs the following steps:

  • Allocates memory for a temporary buffer to hold the variable data.
  • Copies the variable data from the 2-dimensional array var to the temporary buffer help.
  • Writes the uncompressed variable data to the binary file specified by out.
  • Logs a message indicating the successful writing of the variable data.
  • Frees the allocated memory.
Note
This function is typically used to write surface data or other 2-dimensional meteorological variables to a binary file.
Author
Lars Hoffmann

Definition at line 15806 of file mptrac.c.

15810 {
15811
15812 float *help;
15813
15814 /* Allocate... */
15815 ALLOC(help, float,
15816 EX * EY);
15817
15818 /* Copy data... */
15819 for (int ix = 0; ix < met->nx; ix++)
15820 for (int iy = 0; iy < met->ny; iy++)
15821 help[ARRAY_2D(ix, iy, met->ny)] = var[ix][iy];
15822
15823 /* Write uncompressed data... */
15824 LOG(2, "Write 2-D variable: %s (uncompressed)", varname);
15825 FWRITE(help, float,
15826 (size_t) (met->nx * met->ny),
15827 out);
15828
15829 /* Free... */
15830 free(help);
15831}

◆ write_met_bin_3d()

void write_met_bin_3d ( FILE * out,
const ctl_t * ctl,
met_t * met,
float var[EX][EY][EP],
const char * varname,
const int metvar,
FILE * level_log )

Writes a 3-dimensional meteorological variable to a binary file.

The write_met_bin_3d function writes a 3-dimensional meteorological variable to a binary file specified by the out parameter. The variable data is provided in a 3-dimensional array var with maximum dimensions EX by EY by EP. The variable name is provided as a string in the varname parameter. Additionally, the function takes parameters for specifying the compression precision and tolerance.

Parameters
outA pointer to a FILE structure representing the output file.
ctlA pointer to a ctl_t structure containing control parameters.
metA pointer to a met_t structure containing meteorological data.
varAn array of floats representing the 3-dimensional variable data.
varnameA string containing the name of the variable being written.
metvarIndex of the meteorological variable, used to select codec-specific compression settings.
level_logOptional file stream for per-level compression diagnostics, or NULL to disable logging.

The function performs the following steps:

  • Allocates memory for a temporary buffer to hold the variable data.
  • Copies the variable data from the 3-dimensional array var to the temporary buffer help.
  • Writes the variable data to the binary file specified by out using the specified compression method (uncompressed, packed, ZFP, ZSTD, cmultiscale).
  • Logs a message indicating the successful writing of the variable data.
  • Frees the allocated memory.
Note
This function is typically used to write level data or other 3-dimensional meteorological variables to a binary file.
Depending on the value of ctl->met_type, the function writes the variable data using different compression methods. If ctl->met_type is not supported, an error message is logged.
Author
Lars Hoffmann

Definition at line 15835 of file mptrac.c.

15842 {
15843
15844 float *help;
15845
15846 /* Allocate... */
15847 ALLOC(help, float,
15848 EX * EY * EP);
15849
15850 /* Copy data... */
15851#pragma omp parallel for default(shared) collapse(2)
15852 for (int ix = 0; ix < met->nx; ix++)
15853 for (int iy = 0; iy < met->ny; iy++)
15854 for (int ip = 0; ip < met->np; ip++)
15855 help[ARRAY_3D(ix, iy, met->ny, ip, met->np)] = var[ix][iy][ip];
15856
15857 /* Write uncompressed data... */
15858 if (ctl->met_type == 1) {
15859 LOG(2, "Write 3-D variable: %s (uncompressed)", varname);
15860 FWRITE(help, float,
15861 (size_t) (met->nx * met->ny * met->np),
15862 out);
15863 }
15864
15865 /* Write packed data... */
15866 else if (ctl->met_type == 2)
15867 compress_pck(ctl, met, varname, help, 0, level_log, out);
15868
15869 /* Write ZFP data... */
15870#ifdef ZFP
15871 else if (ctl->met_type == 3) {
15872 FWRITE(&ctl->met_zfp_prec[metvar], int,
15873 1,
15874 out);
15875 FWRITE(&ctl->met_zfp_tol[metvar], double,
15876 1,
15877 out);
15878 compress_zfp(ctl, met, varname, help, 0, level_log, out);
15879 }
15880#endif
15881
15882 /* Write zstd data... */
15883#ifdef ZSTD
15884 else if (ctl->met_type == 4)
15885 compress_zstd(ctl, met, varname, help, 0, level_log, out);
15886#endif
15887
15888 /* Write LZ4 data... */
15889#ifdef LZ4
15890 else if (ctl->met_type == 8)
15891 compress_lz4(ctl, met, varname, help, 0, level_log, out);
15892#endif
15893
15894 /* Write cmultiscale data... */
15895#ifdef CMS
15896 else if (ctl->met_type == 5) {
15897 compress_cms(ctl, met, varname, help, 0, level_log, out);
15898 }
15899#endif
15900
15901 /* Write SZ3 data... */
15902#ifdef SZ3
15903 else if (ctl->met_type == 7) {
15904 FWRITE(&ctl->met_sz3_prec[metvar], int,
15905 1,
15906 out);
15907 FWRITE(&ctl->met_sz3_tol[metvar], double,
15908 1,
15909 out);
15910 compress_sz3(ctl, met, varname, help, 0, level_log, out);
15911 }
15912#endif
15913
15914 /* Unknown method... */
15915 else {
15916 ERRMSG("MET_TYPE not supported!");
15917
15918 /* This will never execute, hack to avoid compilation error... */
15919 LOG(3, "%d", metvar);
15920 }
15921
15922 /* Free... */
15923 free(help);
15924}
Here is the call graph for this function:

◆ write_met_nc()

void write_met_nc ( const char * filename,
const ctl_t * ctl,
met_t * met )

Writes meteorological data to a NetCDF file.

This function creates and writes meteorological data to a NetCDF file in the NetCDF-4 format. It defines the required dimensions, grid, surface variables, and level data within the NetCDF structure and writes the corresponding values from the met_t structure. The function uses helper functions to write 2D surface and 3D level data.

Parameters
filenameA constant character pointer representing the name of the NetCDF file to create and write the data to.
ctlA pointer to a ctl_t structure that contains control parameters, such as the NetCDF level and quantization settings.
metA pointer to a met_t structure that contains the meteorological data to be written to the NetCDF file.
Note
  • The function uses the NetCDF-4 format for efficient data storage.
  • It defines the grid dimensions (time, longitude, latitude, pressure levels) and adds global attributes like units and descriptions for each variable.
  • The surface variables include surface pressure, geopotential, 2-meter temperature, and wind components, which are defined on a 2D grid (latitude × longitude).
  • The level variables, such as temperature, wind velocities, and cloud properties, are defined on a 3D grid (pressure level × latitude × longitude).
Author
Lars Hoffmann

Definition at line 15928 of file mptrac.c.

15931 {
15932
15933 /* Create file... */
15934 int ncid, varid;
15935 size_t start[4], count[4];
15936 NC(nc_create(filename, NC_NETCDF4, &ncid));
15937
15938 /* Define dimensions... */
15939 int tid, lonid, latid, levid;
15940 NC(nc_def_dim(ncid, "time", 1, &tid));
15941
15942 if (met->coord_type == 0) {
15943 NC(nc_def_dim(ncid, "lon", (size_t) met->nx, &lonid));
15944 NC(nc_def_dim(ncid, "lat", (size_t) met->ny, &latid));
15945 NC_DEF_VAR("lon", NC_DOUBLE, 1, &lonid, "longitude", "degrees_east", 0,
15946 0);
15947 NC_DEF_VAR("lat", NC_DOUBLE, 1, &latid, "latitude", "degrees_north", 0,
15948 0);
15949 } else {
15950 NC(nc_def_dim(ncid, "x", (size_t) met->nx, &lonid));
15951 NC(nc_def_dim(ncid, "y", (size_t) met->ny, &latid));
15952 NC_DEF_VAR("x", NC_DOUBLE, 1, &lonid, "x", "easting", 0, 0);
15953 NC_DEF_VAR("y", NC_DOUBLE, 1, &latid, "y", "northing", 0, 0);
15954 }
15955
15956 NC(nc_def_dim(ncid, "lev", (size_t) met->np, &levid));
15957
15958 /* Define grid... */
15959 NC_DEF_VAR("time", NC_DOUBLE, 1, &tid, "time",
15960 "seconds since 2000-01-01 00:00:00 UTC", 0, 0);
15961 NC_DEF_VAR("lev", NC_DOUBLE, 1, &levid, "pressure", "Pa", 0, 0);
15962
15963 /* Define surface variables... */
15964 int dimid2[3] = { tid, latid, lonid };
15965 NC_DEF_VAR("sp", NC_FLOAT, 3, dimid2, "Surface pressure", "Pa",
15966 ctl->met_nc_level, 0);
15967 NC_DEF_VAR("z", NC_FLOAT, 3, dimid2, "Geopotential", "m**2 s**-2",
15968 ctl->met_nc_level, 0);
15969 NC_DEF_VAR("t2m", NC_FLOAT, 3, dimid2, "2 metre temperature", "K",
15970 ctl->met_nc_level, 0);
15971 NC_DEF_VAR("u10m", NC_FLOAT, 3, dimid2, "10 metre U wind component",
15972 "m s**-1", ctl->met_nc_level, 0);
15973 NC_DEF_VAR("v10m", NC_FLOAT, 3, dimid2, "10 metre V wind component",
15974 "m s**-1", ctl->met_nc_level, 0);
15975 NC_DEF_VAR("iews", NC_FLOAT, 3, dimid2,
15976 "Instantaneous eastward turbulent surface stress", "N m**-2",
15977 ctl->met_nc_level, 0);
15978 NC_DEF_VAR("inss", NC_FLOAT, 3, dimid2,
15979 "Instantaneous northward turbulent surface stress", "N m**-2",
15980 ctl->met_nc_level, 0);
15981 NC_DEF_VAR("ishf", NC_FLOAT, 3, dimid2,
15982 "Instantaneous surface sensible heat flux", "W m**-2",
15983 ctl->met_nc_level, 0);
15984 NC_DEF_VAR("lsm", NC_FLOAT, 3, dimid2, "Land/sea mask", "-",
15985 ctl->met_nc_level, 0);
15986 NC_DEF_VAR("sstk", NC_FLOAT, 3, dimid2, "Sea surface temperature", "K",
15987 ctl->met_nc_level, 0);
15988 NC_DEF_VAR("blp", NC_FLOAT, 3, dimid2, "Boundary layer pressure", "Pa",
15989 ctl->met_nc_level, 0);
15990 NC_DEF_VAR("pt", NC_FLOAT, 3, dimid2, "Tropopause pressure", "Pa",
15991 ctl->met_nc_level, 0);
15992 NC_DEF_VAR("tt", NC_FLOAT, 3, dimid2, "Tropopause temperature", "K",
15993 ctl->met_nc_level, 0);
15994 NC_DEF_VAR("zt", NC_FLOAT, 3, dimid2, "Tropopause height", "m",
15995 ctl->met_nc_level, 0);
15996 NC_DEF_VAR("h2ot", NC_FLOAT, 3, dimid2, "Tropopause water vapor", "ppv",
15997 ctl->met_nc_level, 0);
15998 NC_DEF_VAR("pct", NC_FLOAT, 3, dimid2, "Cloud top pressure", "Pa",
15999 ctl->met_nc_level, 0);
16000 NC_DEF_VAR("pcb", NC_FLOAT, 3, dimid2, "Cloud bottom pressure", "Pa",
16001 ctl->met_nc_level, 0);
16002 NC_DEF_VAR("cl", NC_FLOAT, 3, dimid2, "Total column cloud water",
16003 "kg m**2", ctl->met_nc_level, 0);
16004 NC_DEF_VAR("plcl", NC_FLOAT, 3, dimid2,
16005 "Pressure at lifted condensation level (LCL)", "Pa",
16006 ctl->met_nc_level, 0);
16007 NC_DEF_VAR("plfc", NC_FLOAT, 3, dimid2,
16008 "Pressure at level of free convection (LFC)", "Pa",
16009 ctl->met_nc_level, 0);
16010 NC_DEF_VAR("pel", NC_FLOAT, 3, dimid2,
16011 "Pressure at equilibrium level (EL)", "Pa", ctl->met_nc_level,
16012 0);
16013 NC_DEF_VAR("cape", NC_FLOAT, 3, dimid2,
16014 "Convective available potential energy", "J kg**-1",
16015 ctl->met_nc_level, 0);
16016 NC_DEF_VAR("cin", NC_FLOAT, 3, dimid2, "Convective inhibition",
16017 "J kg**-1", ctl->met_nc_level, 0);
16018 NC_DEF_VAR("o3c", NC_FLOAT, 3, dimid2, "Total column ozone", "DU",
16019 ctl->met_nc_level, 0);
16020
16021 /* Define level data... */
16022 int dimid3[4] = { tid, levid, latid, lonid };
16023 NC_DEF_VAR("t", NC_FLOAT, 4, dimid3, "Temperature", "K",
16024 ctl->met_nc_level, ctl->met_nc_quant);
16025 NC_DEF_VAR("u", NC_FLOAT, 4, dimid3, "U velocity", "m s**-1",
16026 ctl->met_nc_level, ctl->met_nc_quant);
16027 NC_DEF_VAR("v", NC_FLOAT, 4, dimid3, "V velocity", "m s**-1",
16028 ctl->met_nc_level, ctl->met_nc_quant);
16029 NC_DEF_VAR("w", NC_FLOAT, 4, dimid3, "Vertical velocity", "Pa s**-1",
16030 ctl->met_nc_level, ctl->met_nc_quant);
16031 NC_DEF_VAR("q", NC_FLOAT, 4, dimid3, "Specific humidity", "kg kg**-1",
16032 ctl->met_nc_level, ctl->met_nc_quant);
16033 NC_DEF_VAR("o3", NC_FLOAT, 4, dimid3, "Ozone mass mixing ratio",
16034 "kg kg**-1", ctl->met_nc_level, ctl->met_nc_quant);
16035 NC_DEF_VAR("clwc", NC_FLOAT, 4, dimid3, "Cloud liquid water content",
16036 "kg kg**-1", ctl->met_nc_level, ctl->met_nc_quant);
16037 NC_DEF_VAR("crwc", NC_FLOAT, 4, dimid3, "Cloud rain water content",
16038 "kg kg**-1", ctl->met_nc_level, ctl->met_nc_quant);
16039 NC_DEF_VAR("ciwc", NC_FLOAT, 4, dimid3, "Cloud ice water content",
16040 "kg kg**-1", ctl->met_nc_level, ctl->met_nc_quant);
16041 NC_DEF_VAR("cswc", NC_FLOAT, 4, dimid3, "Cloud snow water content",
16042 "kg kg**-1", ctl->met_nc_level, ctl->met_nc_quant);
16043 NC_DEF_VAR("cc", NC_FLOAT, 4, dimid3, "Cloud cover", "-",
16044 ctl->met_nc_level, ctl->met_nc_quant);
16045
16046 /* End definitions... */
16047 NC(nc_enddef(ncid));
16048
16049 /* Write grid data... */
16050 NC_PUT_DOUBLE("time", &met->time, 0);
16051
16052 if (met->coord_type == 0) {
16053 NC_PUT_DOUBLE("lon", met->lon, 0);
16054 NC_PUT_DOUBLE("lat", met->lat, 0);
16055 } else {
16056 NC_PUT_DOUBLE("x", met->lon, 0);
16057 NC_PUT_DOUBLE("y", met->lat, 0);
16058 }
16059
16060 double phelp[EP];
16061 for (int ip = 0; ip < met->np; ip++)
16062 phelp[ip] = 100. * met->p[ip];
16063 NC_PUT_DOUBLE("lev", phelp, 0);
16064
16065 /* Write surface data... */
16066 write_met_nc_2d(ncid, "sp", met, met->ps, 100.0f);
16067 write_met_nc_2d(ncid, "z", met, met->zs, (float) (1000. * G0));
16068 write_met_nc_2d(ncid, "t2m", met, met->ts, 1.0f);
16069 write_met_nc_2d(ncid, "u10m", met, met->us, 1.0f);
16070 write_met_nc_2d(ncid, "v10m", met, met->vs, 1.0f);
16071 write_met_nc_2d(ncid, "iews", met, met->ess, 1.0f);
16072 write_met_nc_2d(ncid, "inss", met, met->nss, 1.0f);
16073 write_met_nc_2d(ncid, "ishf", met, met->shf, 1.0f);
16074 write_met_nc_2d(ncid, "lsm", met, met->lsm, 1.0f);
16075 write_met_nc_2d(ncid, "sstk", met, met->sst, 1.0f);
16076 write_met_nc_2d(ncid, "blp", met, met->pbl, 100.0f);
16077 write_met_nc_2d(ncid, "pt", met, met->pt, 100.0f);
16078 write_met_nc_2d(ncid, "tt", met, met->tt, 1.0f);
16079 write_met_nc_2d(ncid, "zt", met, met->zt, 1000.0f);
16080 write_met_nc_2d(ncid, "h2ot", met, met->h2ot, 1.0f);
16081 write_met_nc_2d(ncid, "pct", met, met->pct, 100.0f);
16082 write_met_nc_2d(ncid, "pcb", met, met->pcb, 100.0f);
16083 write_met_nc_2d(ncid, "cl", met, met->cl, 1.0f);
16084 write_met_nc_2d(ncid, "plcl", met, met->plcl, 100.0f);
16085 write_met_nc_2d(ncid, "plfc", met, met->plfc, 100.0f);
16086 write_met_nc_2d(ncid, "pel", met, met->pel, 100.0f);
16087 write_met_nc_2d(ncid, "cape", met, met->cape, 1.0f);
16088 write_met_nc_2d(ncid, "cin", met, met->cin, 1.0f);
16089 write_met_nc_2d(ncid, "o3c", met, met->o3c, 1.0f);
16090
16091 /* Write level data... */
16092 write_met_nc_3d(ncid, "t", met, met->t, 1.0f);
16093 write_met_nc_3d(ncid, "u", met, met->u, 1.0f);
16094 write_met_nc_3d(ncid, "v", met, met->v, 1.0f);
16095 write_met_nc_3d(ncid, "w", met, met->w, 100.0f);
16096 write_met_nc_3d(ncid, "q", met, met->h2o, (float) (MH2O / MA));
16097 write_met_nc_3d(ncid, "o3", met, met->o3, (float) (MO3 / MA));
16098 write_met_nc_3d(ncid, "clwc", met, met->lwc, 1.0f);
16099 write_met_nc_3d(ncid, "crwc", met, met->rwc, 1.0f);
16100 write_met_nc_3d(ncid, "ciwc", met, met->iwc, 1.0f);
16101 write_met_nc_3d(ncid, "cswc", met, met->swc, 1.0f);
16102 write_met_nc_3d(ncid, "cc", met, met->cc, 1.0f);
16103
16104 /* Close file... */
16105 NC(nc_close(ncid));
16106}
void write_met_nc_2d(const int ncid, const char *varname, met_t *met, float var[EX][EY], const float scl)
Writes a 2D meteorological variable to a NetCDF file.
Definition mptrac.c:16110
void write_met_nc_3d(const int ncid, const char *varname, met_t *met, float var[EX][EY][EP], const float scl)
Writes a 3D meteorological variable to a NetCDF file.
Definition mptrac.c:16140
Here is the call graph for this function:

◆ write_met_nc_2d()

void write_met_nc_2d ( const int ncid,
const char * varname,
met_t * met,
float var[EX][EY],
const float scl )

Writes a 2D meteorological variable to a NetCDF file.

This function writes a 2D meteorological variable, stored in the array var, to a NetCDF file with the specified variable name. The data is scaled by a factor scl before being written. The function handles memory allocation for the data copy, scaling, and freeing the allocated memory after writing the data to the NetCDF file.

Parameters
ncidThe NetCDF file ID. This is an integer that identifies the NetCDF file where the data will be written. It is assumed that this file has already been opened for writing.
varnameA pointer to a string containing the name of the variable in the NetCDF file where the data will be stored.
metA pointer to a structure of type met_t that contains metadata about the meteorological field, including the dimensions nx (number of points in x-direction) and ny (number of points in y-direction).
varA 2D array of dimensions EX x EY containing the meteorological data to be written. The data is provided in the format var[ix][iy], where ix is the index in the x-direction and iy is the index in the y-direction.
sclA scaling factor applied to each element in the var array before writing to the NetCDF file.
Author
Lars Hoffmann

Definition at line 16110 of file mptrac.c.

16115 {
16116
16117 int varid;
16118 size_t start[4], count[4];
16119
16120 /* Allocate... */
16121 float *help;
16122 ALLOC(help, float,
16123 EX * EY);
16124
16125 /* Copy data... */
16126 for (int ix = 0; ix < met->nx; ix++)
16127 for (int iy = 0; iy < met->ny; iy++)
16128 help[ARRAY_2D(iy, ix, met->nx)] = scl * var[ix][iy];
16129
16130 /* Write data... */
16131 LOG(2, "Write 2-D variable: %s (netCDF)", varname);
16132 NC_PUT_FLOAT(varname, help, 0);
16133
16134 /* Free... */
16135 free(help);
16136}
#define NC_PUT_FLOAT(varname, ptr, hyperslab)
Write a float array to a NetCDF file.
Definition mptrac.h:1703

◆ write_met_nc_3d()

void write_met_nc_3d ( const int ncid,
const char * varname,
met_t * met,
float var[EX][EY][EP],
const float scl )

Writes a 3D meteorological variable to a NetCDF file.

This function writes a 3D meteorological variable, stored in the array var, to a NetCDF file with the specified variable name. The data is scaled by a factor scl before being written. The function handles memory allocation for the data copy, scaling, and freeing the allocated memory after writing the data to the NetCDF file.

Parameters
ncidThe NetCDF file ID. This is an integer that identifies the NetCDF file where the data will be written. It is assumed that this file has already been opened for writing.
varnameA pointer to a string containing the name of the variable in the NetCDF file where the data will be stored.
metA pointer to a structure of type met_t that contains metadata about the meteorological field, including the dimensions nx (number of points in the x-direction), ny (number of points in the y-direction), and np (number of points in the third dimension, e.g., pressure levels).
varA 3D array of dimensions EX x EY x EP containing the meteorological data to be written. The data is provided in the format var[ix][iy][ip], where ix is the index in the x-direction, iy is the index in the y-direction, and ip is the index in the third dimension (e.g., vertical levels).
sclA scaling factor applied to each element in the var array before writing to the NetCDF file.
Author
Lars Hoffmann

Definition at line 16140 of file mptrac.c.

16145 {
16146
16147 int varid;
16148 size_t start[4], count[4];
16149
16150 /* Allocate... */
16151 float *help;
16152 ALLOC(help, float,
16153 EX * EY * EP);
16154
16155 /* Copy data... */
16156 for (int ix = 0; ix < met->nx; ix++)
16157 for (int iy = 0; iy < met->ny; iy++)
16158 for (int ip = 0; ip < met->np; ip++)
16159 help[ARRAY_3D(ip, iy, met->ny, ix, met->nx)] = scl * var[ix][iy][ip];
16160
16161 /* Write data... */
16162 LOG(2, "Write 3-D variable: %s (netCDF)", varname);
16163 NC_PUT_FLOAT(varname, help, 0);
16164
16165 /* Free... */
16166 free(help);
16167}

◆ write_prof()

void write_prof ( const char * filename,
const ctl_t * ctl,
met_t * met0,
met_t * met1,
const atm_t * atm,
const double t )

Writes profile data to a specified file.

The write_prof function writes profile data to a file specified by the filename parameter. It takes control parameters (ctl), two meteorological data structures (met0 and met1), an atmospheric data structure (atm), and a time value (t) as input.

Parameters
filenameA string representing the filename where the profile data will be written.
ctlA pointer to a ctl_t structure containing control parameters.
met0A pointer to a met_t structure representing the first set of meteorological data.
met1A pointer to a met_t structure representing the second set of meteorological data.
atmA pointer to an atm_t structure representing atmospheric data.
tA double value representing the time at which the profile data is being written.

The function performs the following steps:

  • Initializes variables and allocates memory if it's the start of the simulation.
  • Reads observation data and creates a new output file if necessary.
  • Writes header information to the output file.
  • Sets grid box size and vertical coordinates.
  • Processes observations and model data within the specified time interval.
  • Calculates and writes output data for each grid cell.
  • Finalizes by closing the output file and freeing allocated memory if it's the end of the simulation.
Note
This function writes profile data to a file, including time, altitude, coordinates, atmospheric properties, observed data, and the number of observations.
Author
Lars Hoffmann

Definition at line 16171 of file mptrac.c.

16177 {
16178
16179 if (ctl->met_coord_type != 0)
16180 ERRMSG("Only lat/lon grid supported");
16181
16182 static FILE *out;
16183
16184 static double *mass, *obsmean, *rt, *rz, *rlon, *rlat, *robs, *area,
16185 dz, dlon, dlat, *lon, *lat, *z, *press, temp, vmr, h2o, o3;
16186
16187 static int nobs, *obscount, ip;
16188
16189 /* Set timer... */
16190 SELECT_TIMER("WRITE_PROF", "OUTPUT");
16191
16192 /* Init... */
16193 if (t == ctl->t_start) {
16194
16195 nobs = 0;
16196
16197 /* Check quantity index for mass... */
16198 if (ctl->qnt_m < 0)
16199 ERRMSG("Need quantity mass!");
16200
16201 /* Check molar mass... */
16202 if (ctl->molmass <= 0)
16203 ERRMSG("Specify molar mass!");
16204
16205 /* Allocate... */
16206 ALLOC(lon, double,
16207 ctl->prof_nx);
16208 ALLOC(lat, double,
16209 ctl->prof_ny);
16210 ALLOC(area, double,
16211 ctl->prof_ny);
16212 ALLOC(z, double,
16213 ctl->prof_nz);
16214 ALLOC(press, double,
16215 ctl->prof_nz);
16216 ALLOC(rt, double,
16217 NOBS);
16218 ALLOC(rz, double,
16219 NOBS);
16220 ALLOC(rlon, double,
16221 NOBS);
16222 ALLOC(rlat, double,
16223 NOBS);
16224 ALLOC(robs, double,
16225 NOBS);
16226
16227 /* Read observation data... */
16228 read_obs(ctl->prof_obsfile, ctl, rt, rz, rlon, rlat, robs, &nobs);
16229
16230 /* Create new output file... */
16231 LOG(1, "Write profile data: %s", filename);
16232 if (!(out = fopen(filename, "w")))
16233 ERRMSG("Cannot create file!");
16234
16235 /* Write header... */
16236 fprintf(out,
16237 "# $1 = time [s]\n"
16238 "# $2 = altitude [km]\n"
16239 "# $3 = longitude [deg]\n"
16240 "# $4 = latitude [deg]\n"
16241 "# $5 = pressure [hPa]\n"
16242 "# $6 = temperature [K]\n"
16243 "# $7 = volume mixing ratio [ppv]\n"
16244 "# $8 = H2O volume mixing ratio [ppv]\n"
16245 "# $9 = O3 volume mixing ratio [ppv]\n"
16246 "# $10 = observed BT index [K]\n"
16247 "# $11 = number of observations\n");
16248
16249 /* Set grid box size... */
16250 dz = (ctl->prof_z1 - ctl->prof_z0) / ctl->prof_nz;
16251 dlon = (ctl->prof_lon1 - ctl->prof_lon0) / ctl->prof_nx;
16252 dlat = (ctl->prof_lat1 - ctl->prof_lat0) / ctl->prof_ny;
16253
16254 /* Set vertical coordinates... */
16255 for (int iz = 0; iz < ctl->prof_nz; iz++) {
16256 z[iz] = ctl->prof_z0 + dz * (iz + 0.5);
16257 press[iz] = P(z[iz]);
16258 }
16259
16260 /* Set horizontal coordinates... */
16261 for (int ix = 0; ix < ctl->prof_nx; ix++)
16262 lon[ix] = ctl->prof_lon0 + dlon * (ix + 0.5);
16263 for (int iy = 0; iy < ctl->prof_ny; iy++) {
16264 lat[iy] = ctl->prof_lat0 + dlat * (iy + 0.5);
16265 area[iy] = dlat * dlon * SQR(RE * M_PI / 180.) * cos(DEG2RAD(lat[iy]));
16266 }
16267 }
16268
16269 /* Set time interval... */
16270 double t0, t1;
16271 OBS_TIME_WINDOW(ctl, t, t0, t1);
16272
16273 /* Allocate... */
16274 ALLOC(mass, double,
16275 ctl->prof_nx * ctl->prof_ny * ctl->prof_nz);
16276 ALLOC(obsmean, double,
16277 ctl->prof_nx * ctl->prof_ny);
16278 ALLOC(obscount, int,
16279 ctl->prof_nx * ctl->prof_ny);
16280
16281 /* Loop over observations... */
16282 for (int i = 0; i < nobs; i++) {
16283
16284 /* Check time... */
16285 if (rt[i] < t0)
16286 continue;
16287 else if (rt[i] >= t1)
16288 break;
16289
16290 /* Check observation data... */
16291 if (!isfinite(robs[i]))
16292 continue;
16293
16294 /* Check grid boundaries and calculate indices... */
16295 if (rlon[i] < ctl->prof_lon0 || rlon[i] >= ctl->prof_lon1
16296 || rlat[i] < ctl->prof_lat0 || rlat[i] >= ctl->prof_lat1)
16297 continue;
16298 const int ix = (int) ((rlon[i] - ctl->prof_lon0) / dlon);
16299 const int iy = (int) ((rlat[i] - ctl->prof_lat0) / dlat);
16300 if (ix >= ctl->prof_nx || iy >= ctl->prof_ny)
16301 continue;
16302
16303 /* Get mean observation index... */
16304 const int idx = ARRAY_2D(ix, iy, ctl->prof_ny);
16305 obsmean[idx] += robs[i];
16306 obscount[idx]++;
16307 }
16308
16309 /* Analyze model data... */
16310 for (ip = 0; ip < atm->np; ip++) {
16311
16312 /* Check time... */
16313 if (atm->time[ip] < t0 || atm->time[ip] >= t1)
16314 continue;
16315
16316 /* Check grid boundaries and get indices... */
16317 const double zpart = Z(atm->p[ip]);
16318 if (atm->lon[ip] < ctl->prof_lon0
16319 || atm->lon[ip] >= ctl->prof_lon1
16320 || atm->lat[ip] < ctl->prof_lat0
16321 || atm->lat[ip] >= ctl->prof_lat1
16322 || zpart < ctl->prof_z0 || zpart >= ctl->prof_z1)
16323 continue;
16324 const int ix = (int) ((atm->lon[ip] - ctl->prof_lon0) / dlon);
16325 const int iy = (int) ((atm->lat[ip] - ctl->prof_lat0) / dlat);
16326 const int iz = (int) ((zpart - ctl->prof_z0) / dz);
16327 if (ix >= ctl->prof_nx || iy >= ctl->prof_ny || iz >= ctl->prof_nz)
16328 continue;
16329
16330 /* Get total mass in grid cell... */
16331 const int idx = ARRAY_3D(ix, iy, ctl->prof_ny, iz, ctl->prof_nz);
16332 mass[idx] += atm->q[ctl->qnt_m][ip];
16333 }
16334
16335 /* Extract profiles... */
16336 for (int ix = 0; ix < ctl->prof_nx; ix++)
16337 for (int iy = 0; iy < ctl->prof_ny; iy++) {
16338 int idx2 = ARRAY_2D(ix, iy, ctl->prof_ny);
16339 if (obscount[idx2] > 0) {
16340
16341 /* Write output... */
16342 fprintf(out, "\n");
16343
16344 /* Loop over altitudes... */
16345 for (int iz = 0; iz < ctl->prof_nz; iz++) {
16346
16347 /* Get temperature, water vapor, and ozone... */
16349 intpol_met_time_3d(met0, met0->t, met1, met1->t, t, press[iz],
16350 lon[ix], lat[iy], &temp, ci, cw, 1);
16351 intpol_met_time_3d(met0, met0->h2o, met1, met1->h2o, t, press[iz],
16352 lon[ix], lat[iy], &h2o, ci, cw, 0);
16353 intpol_met_time_3d(met0, met0->o3, met1, met1->o3, t, press[iz],
16354 lon[ix], lat[iy], &o3, ci, cw, 0);
16355
16356 /* Calculate volume mixing ratio... */
16357 const int idx3 = ARRAY_3D(ix, iy, ctl->prof_ny, iz, ctl->prof_nz);
16358 vmr = MA / ctl->molmass * mass[idx3]
16359 / (RHO(press[iz], temp) * area[iy] * dz * 1e9);
16360
16361 /* Write output... */
16362 fprintf(out, "%.2f %g %g %g %g %g %g %g %g %g %d\n",
16363 t, z[iz], lon[ix], lat[iy], press[iz], temp, vmr, h2o, o3,
16364 obsmean[idx2] / obscount[idx2], obscount[idx2]);
16365 }
16366 }
16367 }
16368
16369 /* Free... */
16370 free(mass);
16371 free(obsmean);
16372 free(obscount);
16373
16374 /* Finalize... */
16375 if (t == ctl->t_stop) {
16376
16377 /* Close output file... */
16378 fclose(out);
16379
16380 /* Free... */
16381 free(lon);
16382 free(lat);
16383 free(area);
16384 free(z);
16385 free(press);
16386 free(rt);
16387 free(rz);
16388 free(rlon);
16389 free(rlat);
16390 free(robs);
16391 }
16392}
Here is the call graph for this function:

◆ write_sample()

void write_sample ( const char * filename,
const ctl_t * ctl,
met_t * met0,
met_t * met1,
const atm_t * atm,
const double t )

Writes sample data to a specified file.

The write_sample function writes sample data to a file specified by the filename parameter. It takes control parameters (ctl), two meteorological data structures (met0 and met1), an atmospheric data structure (atm), and a time value (t) as input.

Parameters
filenameA string representing the filename where the sample data will be written.
ctlA pointer to a ctl_t structure containing control parameters.
met0A pointer to a met_t structure representing the first set of meteorological data.
met1A pointer to a met_t structure representing the second set of meteorological data.
atmA pointer to an atm_t structure representing atmospheric data.
tA double value representing the time at which the sample data is being written.

The function performs the following steps:

  • Initializes variables and allocates memory if it's the start of the simulation.
  • Reads observation data and kernel data if necessary.
  • Creates a new output file and writes header information to it.
  • Sets latitude range, squared radius, and area.
  • Processes observations and calculates sample data within the specified time interval.
  • Writes output data for each observation.
  • Finalizes by closing the output file and freeing allocated memory if it's the end of the simulation.
Note
This function writes sample data to a file, including time, altitude, coordinates, surface area, layer depth, number of particles, column density, volume mixing ratio, and observed data.
Author
Lars Hoffmann

Definition at line 16396 of file mptrac.c.

16402 {
16403
16404 if (ctl->met_coord_type != 0)
16405 ERRMSG("Only lat/lon grid supported");
16406
16407 static FILE *out;
16408
16409 static double area, dlat, rmax2, *rt, *rz, *rlon, *rlat, *robs, kz[EP],
16410 kw[EP];
16411
16412 static int nobs, nk;
16413
16414 /* Set timer... */
16415 SELECT_TIMER("WRITE_SAMPLE", "OUTPUT");
16416
16417 /* Init... */
16418 if (t == ctl->t_start) {
16419
16420 nobs = 0;
16421 nk = 0;
16422
16423 /* Allocate... */
16424 ALLOC(rt, double,
16425 NOBS);
16426 ALLOC(rz, double,
16427 NOBS);
16428 ALLOC(rlon, double,
16429 NOBS);
16430 ALLOC(rlat, double,
16431 NOBS);
16432 ALLOC(robs, double,
16433 NOBS);
16434
16435 /* Read observation data... */
16436 read_obs(ctl->sample_obsfile, ctl, rt, rz, rlon, rlat, robs, &nobs);
16437
16438 /* Read kernel data... */
16439 if (ctl->sample_kernel[0] != '-')
16440 read_kernel(ctl->sample_kernel, kz, kw, &nk);
16441
16442 /* Create output file... */
16443 LOG(1, "Write sample data: %s", filename);
16444 if (!(out = fopen(filename, "w")))
16445 ERRMSG("Cannot create file!");
16446
16447 /* Write header... */
16448 fprintf(out,
16449 "# $1 = time [s]\n"
16450 "# $2 = altitude [km]\n"
16451 "# $3 = longitude [deg]\n"
16452 "# $4 = latitude [deg]\n"
16453 "# $5 = surface area [km^2]\n"
16454 "# $6 = vertical half-width [km]\n"
16455 "# $7 = number of particles [1]\n"
16456 "# $8 = column density [kg/m^2]\n"
16457 "# $9 = volume mixing ratio [ppv]\n"
16458 "# $10 = observed BT index [K]\n\n");
16459
16460 /* Set latitude range, squared radius, and area... */
16461 dlat = DY2DEG(ctl->sample_dx);
16462 rmax2 = SQR(ctl->sample_dx);
16463 area = M_PI * rmax2;
16464 }
16465
16466 /* Set time interval for output... */
16467 double t0, t1;
16468 OBS_TIME_WINDOW(ctl, t, t0, t1);
16469
16470 /* Loop over observations... */
16471 for (int i = 0; i < nobs; i++) {
16472
16473 /* Check time... */
16474 if (rt[i] < t0)
16475 continue;
16476 else if (rt[i] >= t1)
16477 break;
16478
16479 /* Calculate Cartesian coordinates... */
16480 double x0[3];
16481 geo2cart(0, rlon[i], rlat[i], x0);
16482
16483 /* Set pressure range... */
16484 const double ptop = P(rz[i] + ctl->sample_dz);
16485 const double pbot = P(rz[i] - ctl->sample_dz);
16486
16487 /* Init... */
16488 double mass = 0;
16489 int np = 0;
16490
16491 /* Loop over air parcels... */
16492 //#pragma omp parallel for default(shared) reduction(+:mass,np)
16493 for (int ip = 0; ip < atm->np; ip++) {
16494
16495 /* Check time... */
16496 if (atm->time[ip] < t0 || atm->time[ip] >= t1)
16497 continue;
16498
16499 /* Check latitude... */
16500 if (fabs(rlat[i] - atm->lat[ip]) > dlat)
16501 continue;
16502
16503 /* Check horizontal distance... */
16504 double x1[3];
16505 geo2cart(0, atm->lon[ip], atm->lat[ip], x1);
16506 if (DIST2(x0, x1) > rmax2)
16507 continue;
16508
16509 /* Check pressure... */
16510 if (ctl->sample_dz > 0)
16511 if (atm->p[ip] > pbot || atm->p[ip] < ptop)
16512 continue;
16513
16514 /* Add mass... */
16515 if (ctl->qnt_m >= 0)
16516 mass +=
16517 kernel_weight(kz, kw, nk, atm->p[ip]) * atm->q[ctl->qnt_m][ip];
16518 np++;
16519 }
16520
16521 /* Calculate column density... */
16522 const double cd = mass / (1e6 * area);
16523
16524 /* Normalize by the sampled atmospheric pressure column. */
16525 double vmr = 0;
16526 if (ctl->molmass > 0 && ctl->sample_dz > 0) {
16527 if (mass > 0) {
16528
16529 /* Clip the nominal layer to the surface and meteorological model top. */
16530 double ps;
16532 intpol_met_time_2d(met0, met0->ps, met1, met1->ps, rt[i],
16533 rlon[i], rlat[i], &ps, ci, cw, 0);
16534
16535 const double p_lower = MIN(pbot, ps);
16536 const double p_upper =
16537 MAX(ptop, MAX(met0->p[met0->np - 1], met1->p[met1->np - 1]));
16538 vmr = isfinite(ps) && ps > 0 && p_lower > p_upper
16539 ? MA / ctl->molmass * cd * G0 / (100. * (p_lower - p_upper))
16540 : NAN;
16541 }
16542 } else
16543 vmr = NAN;
16544
16545 /* Write output... */
16546 fprintf(out, "%.2f %g %g %g %g %g %d %g %g %g\n", rt[i], rz[i],
16547 rlon[i], rlat[i], area, ctl->sample_dz, np, cd, vmr, robs[i]);
16548 }
16549
16550 /* Finalize...... */
16551 if (t == ctl->t_stop) {
16552
16553 /* Close output file... */
16554 fclose(out);
16555
16556 /* Free... */
16557 free(rt);
16558 free(rz);
16559 free(rlon);
16560 free(rlat);
16561 free(robs);
16562 }
16563}
void intpol_met_time_2d(const met_t *met0, float array0[EX][EY], const met_t *met1, float array1[EX][EY], const double ts, const double lon, const double lat, double *var, int *ci, double *cw, const int init)
Interpolates meteorological data in 2D space and time.
Definition mptrac.c:3472
Here is the call graph for this function:

◆ write_station()

void write_station ( const char * filename,
const ctl_t * ctl,
atm_t * atm,
const double t )

Writes station data to a specified file.

The write_station function writes station data to a file specified by the filename parameter. It takes control parameters (ctl), an atmospheric data structure (atm), and a time value (t) as input.

Parameters
filenameA string representing the filename where the station data will be written.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure representing atmospheric data.
tA double value representing the time at which the station data is being written.

The function performs the following steps:

  • Initializes variables and opens a new file if it's the start of the simulation.
  • Writes header information to the output file.
  • Sets geolocation and search radius for station data.
  • Processes air parcels and writes station data within the specified time interval and search radius.
  • Writes station data for each air parcel satisfying the criteria.
  • Closes the output file if it's the end of the simulation.
Note
This function writes station data to a file, including time, altitude, longitude, latitude, and additional quantities specified in the control parameters.
Author
Lars Hoffmann

Definition at line 16567 of file mptrac.c.

16571 {
16572
16573 if (ctl->met_coord_type != 0)
16574 ERRMSG("Only lat/lon grid supported");
16575
16576 static FILE *out;
16577
16578 static double rmax2, x0[3], x1[3];
16579
16580 /* Set timer... */
16581 SELECT_TIMER("WRITE_STATION", "OUTPUT");
16582
16583 /* Init... */
16584 if (t == ctl->t_start) {
16585
16586 /* Write info... */
16587 LOG(1, "Write station data: %s", filename);
16588
16589 /* Create new file... */
16590 if (!(out = fopen(filename, "w")))
16591 ERRMSG("Cannot create file!");
16592
16593 /* Write header... */
16594 fprintf(out,
16595 "# $1 = time [s]\n"
16596 "# $2 = altitude [km]\n"
16597 "# $3 = longitude [deg]\n" "# $4 = latitude [deg]\n");
16598 for (int iq = 0; iq < ctl->nq; iq++)
16599 fprintf(out, "# $%i = %s [%s]\n", (iq + 5),
16600 ctl->qnt_name[iq], ctl->qnt_unit[iq]);
16601 fprintf(out, "\n");
16602
16603 /* Set geolocation and search radius... */
16604 geo2cart(0, ctl->stat_lon, ctl->stat_lat, x0);
16605 rmax2 = SQR(ctl->stat_r);
16606 }
16607
16608 /* Set time interval for output... */
16609 double t0, t1;
16610 OBS_TIME_WINDOW(ctl, t, t0, t1);
16611
16612 /* Count number of newly set station flags... */
16613 int nflag = 0;
16614
16615 /* Loop over air parcels... */
16616 for (int ip = 0; ip < atm->np; ip++) {
16617
16618 /* Check time... */
16619 if (atm->time[ip] < t0 || atm->time[ip] >= t1)
16620 continue;
16621
16622 /* Check time range for station output... */
16623 if (atm->time[ip] < ctl->stat_t0 || atm->time[ip] > ctl->stat_t1)
16624 continue;
16625
16626 /* Check station flag... */
16627 if (ctl->qnt_stat >= 0)
16628 if ((int) atm->q[ctl->qnt_stat][ip])
16629 continue;
16630
16631 /* Get Cartesian coordinates... */
16632 geo2cart(0, atm->lon[ip], atm->lat[ip], x1);
16633
16634 /* Check horizontal distance... */
16635 if (DIST2(x0, x1) > rmax2)
16636 continue;
16637
16638 /* Set station flag... */
16639 if (ctl->qnt_stat >= 0) {
16640 atm->q[ctl->qnt_stat][ip] = 1;
16641 nflag += 1;
16642 }
16643
16644 /* Write data... */
16645 fprintf(out, "%.2f %g %g %g",
16646 atm->time[ip], Z(atm->p[ip]), atm->lon[ip], atm->lat[ip]);
16647 for (int iq = 0; iq < ctl->nq; iq++) {
16648 fprintf(out, " ");
16649 fprintf(out, ctl->qnt_format[iq], atm->q[iq][ip]);
16650 }
16651 fprintf(out, "\n");
16652 }
16653
16654 /* During the run, the parcel state lives on the GPU, see mptrac_init().
16655 Therefore, push the station flags written above back to the device;
16656 otherwise, they are invisible to the next timesteps and get discarded
16657 by the next mptrac_update_host() within mptrac_write_output(). */
16658#ifdef _OPENACC
16659 if (nflag > 0) {
16660#pragma acc update device(atm->q[ctl->qnt_stat][0:atm->np])
16661 }
16662#else
16663 (void) nflag;
16664#endif
16665
16666 /* Close file... */
16667 if (t == ctl->t_stop)
16668 fclose(out);
16669}
Here is the call graph for this function:

◆ write_vtk()

void write_vtk ( const char * filename,
const ctl_t * ctl,
const atm_t * atm,
const double t )

Writes VTK (Visualization Toolkit) data to a specified file.

The write_vtk function writes VTK data to a file specified by the filename parameter. It takes control parameters (ctl), an atmospheric data structure (atm), and a time value (t) as input.

Parameters
filenameA string representing the filename where the VTK data will be written.
ctlA pointer to a ctl_t structure containing control parameters.
atmA pointer to an atm_t structure representing atmospheric data.
tA double value representing the time at which the VTK data is being written.

The function performs the following steps:

  • Sets a timer and logs information about writing VTK data.
  • Sets a time interval for output based on the specified time and control parameters.
  • Creates a new file and checks if the file creation was successful.
  • Counts the number of data points to be written.
  • Writes the VTK header, including metadata.
  • Writes point coordinates based on the sphere or Cartesian coordinate system.
  • Writes point data for each quantity specified in the control parameters.
  • Closes the output file.
Note
This function writes VTK data in ASCII format, including point coordinates and associated scalar data for visualization purposes.
Author
Lars Hoffmann

Definition at line 16673 of file mptrac.c.

16677 {
16678
16679 if (ctl->met_coord_type != 0)
16680 ERRMSG("Only lat/lon grid supported");
16681
16682 FILE *out;
16683
16684 /* Set timer... */
16685 SELECT_TIMER("WRITE_VTK", "OUTPUT");
16686
16687 /* Write info... */
16688 LOG(1, "Write VTK data: %s", filename);
16689
16690 /* Set time interval for output... */
16691 const double t0 = t - 0.5 * ctl->dt_mod;
16692 const double t1 = t + 0.5 * ctl->dt_mod;
16693
16694 /* Create file... */
16695 if (!(out = fopen(filename, "w")))
16696 ERRMSG("Cannot create file!");
16697
16698 /* Count data points... */
16699 int np = 0;
16700 for (int ip = 0; ip < atm->np; ip += ctl->vtk_stride) {
16701 if (atm->time[ip] < t0 || atm->time[ip] > t1)
16702 continue;
16703 np++;
16704 }
16705
16706 /* Write header... */
16707 fprintf(out,
16708 "# vtk DataFile Version 3.0\n"
16709 "vtk output\n" "ASCII\n" "DATASET POLYDATA\n");
16710
16711 /* Write point coordinates... */
16712 fprintf(out, "POINTS %d float\n", np);
16713 if (ctl->vtk_sphere) {
16714 for (int ip = 0; ip < atm->np; ip += ctl->vtk_stride) {
16715 if (atm->time[ip] < t0 || atm->time[ip] > t1)
16716 continue;
16717 const double radius = (RE + Z(atm->p[ip]) * ctl->vtk_scale
16718 + ctl->vtk_offset) / RE;
16719 const double coslat = cos(DEG2RAD(atm->lat[ip]));
16720 const double x = radius * coslat * cos(DEG2RAD(atm->lon[ip]));
16721 const double y = radius * coslat * sin(DEG2RAD(atm->lon[ip]));
16722 const double z = radius * sin(DEG2RAD(atm->lat[ip]));
16723 fprintf(out, "%g %g %g\n", x, y, z);
16724 }
16725 } else
16726 for (int ip = 0; ip < atm->np; ip += ctl->vtk_stride) {
16727 if (atm->time[ip] < t0 || atm->time[ip] > t1)
16728 continue;
16729 fprintf(out, "%g %g %g\n", atm->lon[ip], atm->lat[ip],
16730 Z(atm->p[ip]) * ctl->vtk_scale + ctl->vtk_offset);
16731 }
16732
16733 /* Write point data... */
16734 fprintf(out, "POINT_DATA %d\n", np);
16735 for (int iq = 0; iq < ctl->nq; iq++) {
16736 fprintf(out, "SCALARS %s float 1\n" "LOOKUP_TABLE default\n",
16737 ctl->qnt_name[iq]);
16738 for (int ip = 0; ip < atm->np; ip += ctl->vtk_stride) {
16739 if (atm->time[ip] < t0 || atm->time[ip] > t1)
16740 continue;
16741 fprintf(out, "%g\n", atm->q[iq][ip]);
16742 }
16743 }
16744
16745 /* Close file... */
16746 fclose(out);
16747}