MPTRAC
Loading...
Searching...
No Matches
mptrac.c
Go to the documentation of this file.
1/*
2 This file is part of MPTRAC.
3
4 MPTRAC is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 MPTRAC is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with MPTRAC. If not, see <http://www.gnu.org/licenses/>.
16
17 Copyright (C) 2013-2026 Forschungszentrum Juelich GmbH
18*/
19
25#include "mptrac.h"
26
27#include <limits.h>
28
29#ifdef KPP
30#include "kpp_chem.h"
31#endif
32
34static gsl_rng *rng[NTHREADS];
35
37static uint64_t rng_ctr;
38
40#ifdef CURAND
41static curandGenerator_t rng_curand;
42#endif
43
44/*****************************************************************************/
45
46#ifdef MPI
48 void *data,
49 size_t N) {
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}
72#endif
73
74/*****************************************************************************/
75
77 const double *x,
78 double *z,
79 double *lon,
80 double *lat) {
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}
88
89/*****************************************************************************/
90
91double clim_oh(
92 const ctl_t *ctl,
93 const clim_t *clim,
94 const double t,
95 const double lon,
96 const double lat,
97 const double p) {
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}
123
124/*****************************************************************************/
125
127 const ctl_t *ctl,
128 clim_t *clim) {
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}
157
158/*****************************************************************************/
159
161 const double rate[CP][CSZA][CO3],
162 const clim_photo_t *photo,
163 const double p,
164 const double sza,
165 const double o3c) {
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}
214
215/*****************************************************************************/
216
218 const clim_t *clim,
219 const double t,
220 const double lat) {
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}
242
243/*****************************************************************************/
244
246 clim_t *clim) {
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}
397
398/*****************************************************************************/
399
400double clim_ts(
401 const clim_ts_t *ts,
402 const double t) {
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}
415
416/*****************************************************************************/
417
418double clim_zm(
419 const clim_zm_t *zm,
420 const double t,
421 const double lat,
422 const double p) {
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}
468
469/*****************************************************************************/
470
471#ifdef CMS
472void compress_cms(
473 const ctl_t *ctl,
474 const met_t *met,
475 const char *varname,
476 float *array,
477 const int decompress,
478 FILE *level_log,
479 FILE *inout) {
480
481 const size_t nx = (size_t) met->nx;
482 const size_t ny = (size_t) met->ny;
483 const size_t np = (size_t) met->np;
484 const size_t nxy = nx * ny;
485
486 /* Get meteo variable... */
487 const int metvar = compress_metvar_index(varname);
488
489 /* Set lon-lat grid... */
490 double lon[EX], lat[EY];
491 for (size_t ix = 0; ix < nx; ix++)
492 lon[ix] = 360. * (double) ix / ((double) nx - 1.);
493 for (size_t iy = 0; iy < ny; iy++)
494 lat[iy] = 90. - 180. * (double) iy / ((double) ny - 1.);
495
496 /* Set multiscale parameters... */
497 const char domain[] = "[0.0, 360.0]x[-90.0, 90.0]";
498 const int Nd0_x = ctl->met_cms_nd0x;
499 const int Nd0_y = ctl->met_cms_nd0y;
500 const int max_level_grid = ctl->met_cms_maxlev;
501 cms_param_t *cms_param
502 = cms_set_parameters(nx, ny, max_level_grid, Nd0_x, Nd0_y, domain);
503
504 /* Init... */
505 double cr = 0, t_coars = 0, t_eval = 0;
506
507 /* Read compressed stream and decompress array... */
508 if (decompress) {
509 t_eval = 0;
510
511 /* Loop over levels... */
512 for (size_t ip = 0; ip < np; ip++) {
513
514 /* Initialize multiscale module... */
515 cms_module_t *cms_ptr = cms_init(cms_param);
516
517 /* Read binary data... */
518 cms_sol_t *cms_sol;
519 if (ctl->met_cms_zstd == 1)
520 cms_sol = cms_read_zstd_sol(cms_ptr, inout);
521 else
522 cms_sol = cms_read_sol(cms_ptr, inout);
523
524 /* Evaluate current level... */
525 const double t0 = omp_get_wtime();
526#pragma omp parallel for collapse(2) default(shared)
527 for (size_t ix = 0; ix < nx; ix++)
528 for (size_t iy = 0; iy < ny; iy++) {
529 double val;
530 const double x[] = { lon[ix], lat[iy] };
531 cms_eval(cms_ptr, cms_sol, x, &val);
532 array[ARRAY_3D(ix, iy, ny, ip, np)] = (float) val;
533 }
534 t_eval += omp_get_wtime() - t0;
535
536 /* Calculate harmonic mean of compression rates... */
537 cr += 1.0 / cms_compression_rate(cms_ptr, cms_sol);
538
539 /* Free... */
540 cms_delete_sol(cms_sol);
541 cms_delete_module(cms_ptr);
542 }
543
544 /* Write info... */
545 LOG(2, "Read 3-D variable: %s"
546 " (CMS, RATIO=%g, BPV=%g, T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
547 varname, (double) np / cr, 32. * cr / (double) np, t_eval,
548 COMPRESS_SPEED(nx * ny * np * sizeof(float), t_eval));
549 }
550
551 /* Compress array and output compressed stream... */
552 else {
553
554 /* Init... */
555 cms_module_t *cms_ptr[EP];
556 cms_sol_t *cms_sol[EP];
557 double ratio[EP], t_coars_level[EP], t_eval_level[EP];
558
559 /* Loop over batches... */
560 const size_t dip = (ctl->met_cms_batch <= 0
561 ? (size_t) omp_get_max_threads()
562 : (size_t) ctl->met_cms_batch);
563 for (size_t ip0 = 0; ip0 < np; ip0 += dip) {
564
565 /* Measure time... */
566 double t0 = omp_get_wtime();
567
568 /* Loop over levels... */
569#pragma omp parallel for default(shared)
570 for (size_t ip = ip0; ip < MIN(ip0 + dip, np); ip++) {
571 const double t1 = omp_get_wtime();
572
573 /* Allocate... */
574 float *tmp_arr;
575 ALLOC(tmp_arr, float,
576 nxy);
577
578 /* Copy level data... */
579 for (size_t ix = 0; ix < nx; ++ix)
580 for (size_t iy = 0; iy < ny; ++iy)
581 tmp_arr[ARRAY_2D(ix, iy, ny)] =
582 array[ARRAY_3D(ix, iy, ny, ip, np)];
583
584 /* Initialize current level... */
585 cms_ptr[ip] = cms_init(cms_param);
586
587 /* Coarsening... */
588 cms_sol[ip] =
589 cms_read_arr_new(cms_ptr[ip], tmp_arr, lon, lat,
590 nx, ny, ctl->met_cms_eps[metvar]);
591 t_coars_level[ip] = omp_get_wtime() - t1;
592
593 /* Free... */
594 free(tmp_arr);
595 }
596
597 /* Measure time... */
598 t_coars += (omp_get_wtime() - t0);
599
600 /* Loop over levels... */
601 for (size_t ip = ip0; ip < MIN(ip0 + dip, np); ip++) {
602
603 /* Allocate... */
604 float *tmp_cms, *tmp_org;
605 ALLOC(tmp_cms, float,
606 nxy);
607 ALLOC(tmp_org, float,
608 nxy);
609
610 /* Measure time... */
611 t0 = omp_get_wtime();
612
613 /* Evaluate... */
614#pragma omp parallel for collapse(2) default(shared)
615 for (size_t ix = 0; ix < nx; ix++)
616 for (size_t iy = 0; iy < ny; iy++) {
617 const size_t idx = ARRAY_2D(ix, iy, ny);
618 const double x[] = { lon[ix], lat[iy] };
619 double val;
620 cms_eval(cms_ptr[ip], cms_sol[ip], x, &val);
621 tmp_cms[idx] = (float) val;
622 tmp_org[idx] = array[ARRAY_3D(ix, iy, ny, ip, np)];
623 }
624
625 /* Measure time... */
626 t_eval_level[ip] = omp_get_wtime() - t0;
627 t_eval += t_eval_level[ip];
628
629 /* Calculate harmonic mean of compression rates... */
630 ratio[ip] = cms_compression_rate(cms_ptr[ip], cms_sol[ip]);
631 cr += 1.0 / ratio[ip];
632
633 /* Write per-level diagnostics... */
634 if (level_log)
635 compress_log_level(level_log, "CMS", varname, ip, met->p[ip],
636 ratio[ip], 32. / ratio[ip],
637 t_coars_level[ip], t_eval_level[ip], nxy,
638 nxy * sizeof(float), tmp_org, tmp_cms);
639
640 /* Save binary data... */
641 if (ctl->met_cms_zstd == 1)
642 cms_save_zstd_sol(cms_sol[ip], inout, 3);
643 else
644 cms_save_sol(cms_sol[ip], inout);
645
646 /* Free... */
647 cms_delete_sol(cms_sol[ip]);
648 cms_delete_module(cms_ptr[ip]);
649 free(tmp_cms);
650 free(tmp_org);
651 }
652 }
653
654 /* Write info... */
655 LOG(2, "Write 3-D variable: %s"
656 " (CMS, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s,"
657 " T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
658 varname, (double) np / cr, 32. * cr / (double) np, t_coars,
659 COMPRESS_SPEED(nx * ny * np * sizeof(float), t_coars), t_eval,
660 COMPRESS_SPEED(nx * ny * np * sizeof(float), t_eval));
661 }
662
663 /* Free... */
664 cms_delete_param(cms_param);
665}
666#endif
667
668/*****************************************************************************/
669
671 FILE *out,
672 const char *codec,
673 const char *varname,
674 const size_t lev,
675 const double plev,
676 const double ratio,
677 const double bpv,
678 const double t_comp,
679 const double t_decomp,
680 const size_t n,
681 const size_t nbytes,
682 const float *org,
683 const float *cmp) {
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}
766
767/*****************************************************************************/
768
770 FILE *out,
771 const char *codec,
772 const char *varname,
773 const met_t *met,
774 const float *org_all,
775 const float *cmp_all,
776 const size_t nxy,
777 const size_t nz,
778 const double ratio,
779 const double bpv,
780 const double t_comp,
781 const double t_decomp,
782 const size_t nbytes) {
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}
812
813/*****************************************************************************/
814
816 float *array,
817 const size_t nxy,
818 const size_t nz,
819 double *off,
820 double *scl) {
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}
855
856/*****************************************************************************/
857
859 float *array,
860 const size_t nxy,
861 const size_t nz,
862 const double *off,
863 const double *scl) {
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}
875
876/*****************************************************************************/
877
879 FILE *in,
880 const size_t nz,
881 double **off,
882 double **scl) {
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}
910
911/*****************************************************************************/
912
914 FILE *out,
915 const int enabled,
916 float *array,
917 const size_t nxy,
918 const size_t nz,
919 double **off,
920 double **scl) {
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}
947
948/*****************************************************************************/
949
950#ifdef ZSTD
951ZSTD_CCtx *compress_zstd_create_cctx(
952 const int level,
953 const int nworkers) {
954
955 /* Create and configure the ZSTD context... */
956 ZSTD_CCtx *cctx = ZSTD_createCCtx();
957 if (!cctx)
958 ERRMSG("Cannot create ZSTD context!");
959
960 if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_compressionLevel,
961 level)))
962 ERRMSG("Cannot set ZSTD compression level!");
963
964 if (ZSTD_isError(ZSTD_CCtx_setParameter(cctx, ZSTD_c_nbWorkers, nworkers)))
965 ERRMSG("Cannot set ZSTD worker count!");
966
967 return cctx;
968}
969#endif
970
971/*****************************************************************************/
972
974 const char *varname) {
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}
987
988/*****************************************************************************/
989
991 const ctl_t *ctl,
992 const met_t *met,
993 const char *varname,
994 float *array,
995 const int decompress,
996 FILE *level_log,
997 FILE *inout) {
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}
1261
1262/*****************************************************************************/
1263
1264#ifdef SZ3
1265void compress_sz3(
1266 const ctl_t *ctl,
1267 const met_t *met,
1268 const char *varname,
1269 float *array,
1270 const int decompress,
1271 FILE *level_log,
1272 FILE *inout) {
1273
1274 /* Get meteo variable... */
1275 const int metvar = compress_metvar_index(varname);
1276
1277 /* Check compression settings... */
1278 if ((ctl->met_sz3_prec[metvar] > 0) == (ctl->met_sz3_tol[metvar] > 0.0))
1279 ERRMSG("Exactly one of precision or tolerance must be set for SZ3!");
1280
1281 size_t r1 = (size_t) met->np, r2 = (size_t) met->ny, r3 = (size_t) met->nx,
1282 outSize = 0, total_elems = r1 * r2 * r3;
1283
1284 unsigned char *bytes = NULL;
1285 double *scale_off = NULL, *scale_scl = NULL;
1286 float *orig_all = NULL;
1287 char codec_info[LEN];
1288
1289 /* Read compressed stream and decompress array... */
1290 if (decompress) {
1291
1292 /* Read optional scaling metadata before the SZ3 byte stream... */
1293 const int stored_lossy_scale =
1294 compress_read_lossy_scale(inout, r1, &scale_off, &scale_scl);
1295
1296 size_t sz3size;
1297
1298 /* Read input... */
1299 FREAD(&sz3size, size_t,
1300 1,
1301 inout);
1302 ALLOC(bytes, char,
1303 sz3size);
1304 FREAD(bytes, unsigned char,
1305 sz3size,
1306 inout);
1307
1308 /* Let SZ3 rebuild the scaled field in its native 3-D layout... */
1309 const double t0 = omp_get_wtime();
1310 void *outData = SZ_decompress(SZ_FLOAT, bytes, sz3size, 0, 0, r3, r2, r1);
1311 if (!outData)
1312 ERRMSG("Decompression failed!");
1313
1314 memcpy(array, outData, total_elems * sizeof(float));
1315
1316 /* Restore the original value range after lossy unit scaling... */
1317 if (stored_lossy_scale > 0)
1318 compress_unscale_from_unit(array, r2 * r3, r1, scale_off, scale_scl);
1319 const double t_decomp = omp_get_wtime() - t0;
1320
1321 /* Free... */
1322 free(outData);
1323 free(bytes);
1324
1325 const double ratio = COMPRESS_RATIO(total_elems * sizeof(float), sz3size);
1326 const double bpv = COMPRESS_BPV(total_elems, sz3size);
1327 snprintf(codec_info, LEN, "SZ3, PREC=%d, TOL=%g, SCALE=%d",
1328 ctl->met_sz3_prec[metvar], ctl->met_sz3_tol[metvar],
1329 stored_lossy_scale);
1330
1331 /* Logging... */
1332 LOG(2, "Read 3-D variable: %s"
1333 " (%s, RATIO=%g, BPV=%g, T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1334 varname, codec_info, ratio, bpv, t_decomp,
1335 COMPRESS_SPEED(total_elems * sizeof(float), t_decomp));
1336 }
1337
1338 /* Compress array and output compressed stream... */
1339 else {
1340
1341 /* Translate MPTRAC settings into the SZ3 absolute/relative error mode... */
1342 const int errBoundMode = (ctl->met_sz3_prec[metvar] > 0) ? REL : ABS;
1343 const double absBound =
1344 (errBoundMode == ABS) ? ctl->met_sz3_tol[metvar] : 0.0;
1345 const double relBound =
1346 (errBoundMode == REL) ? pow(2.0, -(double) ctl->met_sz3_prec[metvar])
1347 : 0.0;
1348 const size_t raw_size = total_elems * sizeof(float);
1349
1350 /* Preserve the unscaled input only if diagnostics need it later... */
1351 if (ctl->met_lossy_scale[metvar] > 0 && level_log) {
1352 ALLOC(orig_all, float,
1353 total_elems);
1354 memcpy(orig_all, array, total_elems * sizeof(float));
1355 }
1356
1357 /* Optionally scale each vertical level to unit space before SZ3... */
1358 compress_write_lossy_scale(inout, ctl->met_lossy_scale[metvar], array,
1359 r2 * r3, r1, &scale_off, &scale_scl);
1360
1361 /* Compress the possibly scaled field with the selected SZ3 error mode... */
1362 const double t0 = omp_get_wtime();
1363 bytes = SZ_compress_args(SZ_FLOAT, array, &outSize,
1364 errBoundMode, absBound, relBound, 0.0,
1365 0, 0, r3, r2, r1);
1366 const double t_comp = omp_get_wtime() - t0;
1367 if (!bytes || outSize == 0)
1368 ERRMSG("Compression failed!");
1369
1370 /* Write output... */
1371 FWRITE(&outSize, size_t,
1372 1,
1373 inout);
1374 FWRITE(bytes, unsigned char,
1375 outSize,
1376 inout);
1377
1378 snprintf(codec_info, LEN, "SZ3, PREC=%d, TOL=%g, SCALE=%d",
1379 ctl->met_sz3_prec[metvar], ctl->met_sz3_tol[metvar],
1380 ctl->met_lossy_scale[metvar]);
1381
1382 /* Reconstruct once more only when per-level diagnostics are requested... */
1383 double t_decomp = NAN;
1384 if (level_log) {
1385 unsigned char *bytes_copy;
1386 float *tmp_all;
1387 const size_t nxy = r2 * r3;
1388
1389 /* Reconstruct data for per-level diagnostics... */
1390 ALLOC(bytes_copy, unsigned char,
1391 outSize);
1392 memcpy(bytes_copy, bytes, outSize);
1393
1394 const double t1 = omp_get_wtime();
1395 void *decData = SZ_decompress(SZ_FLOAT, bytes_copy, outSize, 0, 0, r3,
1396 r2, r1);
1397 t_decomp = omp_get_wtime() - t1;
1398 if (!decData)
1399 ERRMSG("Decompression failed!");
1400
1401 /* Rebuild the decoded field so diagnostics compare like with like... */
1402 ALLOC(tmp_all, float,
1403 total_elems);
1404 memcpy(tmp_all, decData, total_elems * sizeof(float));
1405 if (ctl->met_lossy_scale[metvar] > 0)
1406 compress_unscale_from_unit(tmp_all, r2 * r3, r1, scale_off,
1407 scale_scl);
1408
1409 const double ratio = COMPRESS_RATIO(raw_size, outSize);
1410 const double bpv = COMPRESS_BPV(total_elems, outSize);
1411 compress_log_levels_3d(level_log, "SZ3", varname, met,
1412 (orig_all ? orig_all : array), tmp_all, nxy, r1,
1413 ratio, bpv, t_comp, t_decomp, raw_size);
1414
1415 /* Free... */
1416 free(tmp_all);
1417 free(decData);
1418 free(bytes_copy);
1419
1420 /* Logging... */
1421 LOG(2, "Write 3-D variable: %s"
1422 " (%s, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s,"
1423 " T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1424 varname, codec_info, ratio, bpv, t_comp,
1425 COMPRESS_SPEED(raw_size, t_comp), t_decomp,
1426 COMPRESS_SPEED(raw_size, t_decomp));
1427 } else {
1428 const double ratio = COMPRESS_RATIO(raw_size, outSize);
1429 const double bpv = COMPRESS_BPV(total_elems, outSize);
1430
1431 /* Logging... */
1432 LOG(2, "Write 3-D variable: %s"
1433 " (%s, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s)",
1434 varname, codec_info, ratio, bpv, t_comp,
1435 COMPRESS_SPEED(raw_size, t_comp));
1436 }
1437 /* Free... */
1438 free(bytes);
1439 free(orig_all);
1440 }
1441
1442 /* Free... */
1443 free(scale_off);
1444 free(scale_scl);
1445}
1446#endif
1447
1448/*****************************************************************************/
1449
1450#ifdef ZFP
1451void compress_zfp(
1452 const ctl_t *ctl,
1453 const met_t *met,
1454 const char *varname,
1455 float *array,
1456 const int decompress,
1457 FILE *level_log,
1458 FILE *inout) {
1459
1460 /* Get meteo variable... */
1461 const int metvar = compress_metvar_index(varname);
1462
1463 /* Allocate meta data for the 3D array a[nz][ny][nx]... */
1464 const size_t snx = (size_t) met->np;
1465 const size_t sny = (size_t) met->ny;
1466 const size_t snz = (size_t) met->nx;
1467 const size_t n = snx * sny * snz;
1468 const size_t raw_size = n * sizeof(float);
1469 const zfp_type type = zfp_type_float;
1470 zfp_field *field = zfp_field_3d(array, type, snx, sny, snz);
1471
1472 /* Allocate meta data for a compressed stream... */
1473 zfp_stream *zfp = zfp_stream_open(NULL);
1474 if (!field || !zfp)
1475 ERRMSG("Failed to allocate zfp structures!");
1476
1477 /* Set compression mode... */
1478 int actual_prec = 0;
1479 double actual_tol = 0;
1480 if ((ctl->met_zfp_prec[metvar] > 0 && ctl->met_zfp_tol[metvar] > 0)
1481 || (ctl->met_zfp_prec[metvar] <= 0 && ctl->met_zfp_tol[metvar] <= 0)) {
1482 ERRMSG("Exactly one of precision or tolerance must be set for zfp!");
1483 } else if (ctl->met_zfp_prec[metvar] > 0)
1484 actual_prec = (int) zfp_stream_set_precision(zfp, (unsigned int)
1485 ctl->met_zfp_prec[metvar]);
1486 else if (ctl->met_zfp_tol[metvar] > 0)
1487 actual_tol = zfp_stream_set_accuracy(zfp, ctl->met_zfp_tol[metvar]);
1488
1489 /* Allocate buffer for compressed data... */
1490 const size_t bufsize = zfp_stream_maximum_size(zfp, field);
1491 void *buffer;
1492 ALLOC(buffer, char,
1493 bufsize);
1494
1495 /* Associate bit stream with allocated buffer... */
1496 bitstream *stream = stream_open(buffer, bufsize);
1497 zfp_stream_set_bit_stream(zfp, stream);
1498 zfp_stream_rewind(zfp);
1499
1500 /* Read compressed stream and decompress array... */
1501 size_t zfpsize;
1502 double *scale_off = NULL, *scale_scl = NULL;
1503 char codec_info[LEN];
1504 if (decompress) {
1505
1506 /* Read optional scaling metadata before the ZFP bit stream... */
1507 const int stored_lossy_scale =
1508 compress_read_lossy_scale(inout, snx, &scale_off, &scale_scl);
1509 /* Read input... */
1510 FREAD(&zfpsize, size_t,
1511 1,
1512 inout);
1513 if (zfpsize > bufsize)
1514 ERRMSG("Compressed data size exceeds allocated buffer!");
1515 FREAD(buffer, unsigned char,
1516 zfpsize,
1517 inout);
1518
1519 /* Decode the bit stream directly into the caller-provided field... */
1520 const double t0 = omp_get_wtime();
1521 if (!zfp_decompress(zfp, field))
1522 ERRMSG("Decompression failed!");
1523
1524 /* Restore the original value range after lossy unit scaling... */
1525 if (stored_lossy_scale > 0)
1526 compress_unscale_from_unit(array, sny * snz, snx, scale_off, scale_scl);
1527 const double t_decomp = omp_get_wtime() - t0;
1528 const double ratio = COMPRESS_RATIO(raw_size, zfpsize);
1529 const double bpv = COMPRESS_BPV(n, zfpsize);
1530 snprintf(codec_info, LEN, "ZFP, PREC=%d, TOL=%g, SCALE=%d",
1531 actual_prec, actual_tol, stored_lossy_scale);
1532
1533 /* Logging... */
1534 LOG(2, "Read 3-D variable: %s"
1535 " (%s, RATIO=%g, BPV=%g, T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1536 varname, codec_info, ratio, bpv, t_decomp, COMPRESS_SPEED(raw_size,
1537 t_decomp));
1538 }
1539
1540 /* Compress array and output compressed stream... */
1541 else {
1542 float *tmp_all, *orig_all = NULL;
1543 const size_t nxy = sny * snz;
1544
1545 /* Preserve the unscaled input only if diagnostics need it later... */
1546 if (ctl->met_lossy_scale[metvar] > 0 && level_log) {
1547 ALLOC(orig_all, float,
1548 n);
1549 memcpy(orig_all, array, raw_size);
1550 }
1551
1552 /* Optionally scale each vertical level to unit space before ZFP... */
1553 compress_write_lossy_scale(inout, ctl->met_lossy_scale[metvar], array,
1554 nxy, snx, &scale_off, &scale_scl);
1555
1556 /* Keep a temporary decode buffer for the shared diagnostics path... */
1557 ALLOC(tmp_all, float,
1558 n);
1559
1560 /* Compress the field into the configured ZFP bit stream... */
1561 const double t0 = omp_get_wtime();
1562 zfpsize = zfp_compress(zfp, field);
1563 const double t_comp = omp_get_wtime() - t0;
1564 if (!zfpsize) {
1565 ERRMSG("Compression failed!");
1566 } else {
1567 /* Write output... */
1568 FWRITE(&zfpsize, size_t,
1569 1,
1570 inout);
1571 FWRITE(buffer, unsigned char,
1572 zfpsize,
1573 inout);
1574 }
1575
1576 /* Decode once into a temporary field for the shared diagnostics... */
1577 zfp_field *dec_field = zfp_field_3d(tmp_all, type, snx, sny, snz);
1578 if (!dec_field)
1579 ERRMSG("Failed to allocate zfp structures!");
1580
1581 /* Rewind the bit stream and decode once for diagnostics and timing... */
1582 const double t1 = omp_get_wtime();
1583 zfp_stream_rewind(zfp);
1584 if (!zfp_decompress(zfp, dec_field))
1585 ERRMSG("Decompression failed!");
1586 if (ctl->met_lossy_scale[metvar] > 0)
1587 compress_unscale_from_unit(tmp_all, nxy, snx, scale_off, scale_scl);
1588 const double t_decomp = omp_get_wtime() - t1;
1589
1590 const double ratio = COMPRESS_RATIO(raw_size, zfpsize);
1591 const double bpv = COMPRESS_BPV(n, zfpsize);
1592 compress_log_levels_3d(level_log, "ZFP", varname, met,
1593 (orig_all ? orig_all : array), tmp_all, nxy, snx,
1594 ratio, bpv, t_comp, t_decomp, raw_size);
1595
1596 snprintf(codec_info, LEN, "ZFP, PREC=%d, TOL=%g, SCALE=%d",
1597 actual_prec, actual_tol, ctl->met_lossy_scale[metvar]);
1598
1599 /* Logging... */
1600 LOG(2, "Write 3-D variable: %s"
1601 " (%s, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s,"
1602 " T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1603 varname, codec_info, ratio, bpv, t_comp, COMPRESS_SPEED(raw_size,
1604 t_comp),
1605 t_decomp, COMPRESS_SPEED(raw_size, t_decomp));
1606
1607 /* Free... */
1608 free(tmp_all);
1609 free(orig_all);
1610 zfp_field_free(dec_field);
1611 }
1612
1613 /* Free... */
1614 free(scale_off);
1615 free(scale_scl);
1616
1617 /* Free... */
1618 zfp_field_free(field);
1619 stream_close(stream);
1620 zfp_stream_close(zfp);
1621 free(buffer);
1622}
1623#endif
1624
1625/*****************************************************************************/
1626
1627#ifdef ZSTD
1628void compress_zstd(
1629 const ctl_t *ctl,
1630 const met_t *met,
1631 const char *varname,
1632 float *array,
1633 const int decompress,
1634 FILE *level_log,
1635 FILE *inout) {
1636
1637 /* Get buffer sizes... */
1638 const size_t nxy = (size_t) met->nx * (size_t) met->ny;
1639 const size_t nz = (size_t) met->np;
1640 const size_t n = nxy * nz, uncomprLen = n * sizeof(float);
1641 size_t compsize, comprLen = ZSTD_compressBound(uncomprLen);
1642
1643 /* Allocate... */
1644 char *compr, *uncompr = (char *) array;
1645 char codec_info[LEN];
1646 ALLOC(compr, char,
1647 comprLen);
1648
1649 /* Read compressed stream and decompress array... */
1650 if (decompress) {
1651
1652 /* Read input... */
1653 FREAD(&comprLen, size_t,
1654 1,
1655 inout);
1656 FREAD(compr, unsigned char,
1657 comprLen,
1658 inout);
1659
1660 /* Decode one full frame and validate the restored byte count... */
1661 const double t0 = omp_get_wtime();
1662 compsize = ZSTD_decompress(uncompr, uncomprLen, compr, comprLen);
1663 const double t_decomp = omp_get_wtime() - t0;
1664 if (ZSTD_isError(compsize) || compsize != uncomprLen)
1665 ERRMSG("Decompression failed or size mismatch!");
1666 const double ratio = COMPRESS_RATIO(uncomprLen, comprLen);
1667 const double bpv = COMPRESS_BPV(n, comprLen);
1668 snprintf(codec_info, LEN, "ZSTD, LEVEL=%d", ctl->met_zstd_level);
1669
1670 /* Logging... */
1671 LOG(2, "Read 3-D variable: %s"
1672 " (%s, RATIO=%g, BPV=%g, T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1673 varname, codec_info, ratio, bpv, t_decomp, COMPRESS_SPEED(uncomprLen,
1674 t_decomp));
1675 }
1676
1677 /* Compress array and output compressed stream... */
1678 else {
1679 ZSTD_CCtx *cctx;
1680 float *tmp_all;
1681
1682 /* Keep one temporary decode buffer for the shared diagnostics path... */
1683 ALLOC(tmp_all, float,
1684 n);
1685
1686 cctx = compress_zstd_create_cctx(ctl->met_zstd_level,
1687 ctl->met_zstd_nworkers);
1688
1689 /* Compress one full field with the preconfigured ZSTD context... */
1690 const double t0 = omp_get_wtime();
1691 compsize = ZSTD_compress2(cctx, compr, comprLen, uncompr, uncomprLen);
1692 const double t_comp = omp_get_wtime() - t0;
1693 if (ZSTD_isError(compsize)) {
1694 ZSTD_freeCCtx(cctx);
1695 ERRMSG("Compression failed!");
1696 } else {
1697
1698 /* Write output... */
1699 FWRITE(&compsize, size_t,
1700 1,
1701 inout);
1702 FWRITE(compr, unsigned char,
1703 compsize,
1704 inout);
1705 }
1706
1707 /* Decode once more so the common diagnostics see the reconstructed field... */
1708 const double t1 = omp_get_wtime();
1709 const size_t decomp_size = ZSTD_decompress(tmp_all, uncomprLen, compr,
1710 compsize);
1711 const double t_decomp = omp_get_wtime() - t1;
1712 if (ZSTD_isError(decomp_size) || decomp_size != uncomprLen)
1713 ERRMSG("Decompression failed or size mismatch!");
1714
1715 const double ratio = COMPRESS_RATIO(uncomprLen, compsize);
1716 const double bpv = COMPRESS_BPV(n, compsize);
1717 compress_log_levels_3d(level_log, "ZSTD", varname, met, array, tmp_all,
1718 nxy, nz, ratio, bpv, t_comp, t_decomp, uncomprLen);
1719
1720 snprintf(codec_info, LEN, "ZSTD, LEVEL=%d, NWORKERS=%d",
1722
1723 /* Logging... */
1724 LOG(2, "Write 3-D variable: %s"
1725 " (%s, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s,"
1726 " T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1727 varname, codec_info, ratio, bpv, t_comp, COMPRESS_SPEED(uncomprLen,
1728 t_comp),
1729 t_decomp, COMPRESS_SPEED(uncomprLen, t_decomp));
1730
1731 /* Free... */
1732 ZSTD_freeCCtx(cctx);
1733 free(tmp_all);
1734 }
1735
1736 /* Free... */
1737 free(compr);
1738}
1739#endif
1740
1741/*****************************************************************************/
1742
1743#ifdef LZ4
1744void compress_lz4(
1745 const ctl_t *ctl,
1746 const met_t *met,
1747 const char *varname,
1748 float *array,
1749 const int decompress,
1750 FILE *level_log,
1751 FILE *inout) {
1752
1753 /* Get buffer sizes... */
1754 const size_t nxy = (size_t) met->nx * (size_t) met->ny;
1755 const size_t nz = (size_t) met->np;
1756 const size_t n = nxy * nz;
1757 const size_t uncomprLen = n * sizeof(float);
1758 if (uncomprLen > (size_t) INT_MAX)
1759 ERRMSG("LZ4 input buffer exceeds INT_MAX!");
1760 const int uncomprLenInt = (int) uncomprLen;
1761 const int accel = ctl->met_lz4_accel > 0 ? ctl->met_lz4_accel : 1;
1762 const int comprCapInt = LZ4_compressBound(uncomprLenInt);
1763 if (comprCapInt <= 0)
1764 ERRMSG("Cannot determine LZ4 compression bound!");
1765 size_t comprLen = (size_t) comprCapInt;
1766
1767 /* Allocate... */
1768 char *compr, *uncompr = (char *) array;
1769 char codec_info[LEN];
1770 ALLOC(compr, char,
1771 comprLen);
1772 snprintf(codec_info, LEN, "LZ4, ACCEL=%d", accel);
1773
1774 /* Read compressed stream and decompress array... */
1775 if (decompress) {
1776
1777 /* Read input... */
1778 FREAD(&comprLen, size_t,
1779 1,
1780 inout);
1781 if (comprLen > (size_t) INT_MAX)
1782 ERRMSG("LZ4 compressed buffer exceeds INT_MAX!");
1783 FREAD(compr, unsigned char,
1784 comprLen,
1785 inout);
1786
1787 /* Decode one full frame and validate the restored byte count... */
1788 const double t0 = omp_get_wtime();
1789 const int decomp_size =
1790 LZ4_decompress_safe(compr, uncompr, (int) comprLen, uncomprLenInt);
1791 const double t_decomp = omp_get_wtime() - t0;
1792 if (decomp_size != uncomprLenInt)
1793 ERRMSG("Decompression failed or size mismatch!");
1794 const double ratio = COMPRESS_RATIO(uncomprLen, comprLen);
1795 const double bpv = COMPRESS_BPV(n, comprLen);
1796
1797 /* Logging... */
1798 LOG(2, "Read 3-D variable: %s"
1799 " (%s, RATIO=%g, BPV=%g, T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1800 varname, codec_info, ratio, bpv, t_decomp, COMPRESS_SPEED(uncomprLen,
1801 t_decomp));
1802 }
1803
1804 /* Compress array and output compressed stream... */
1805 else {
1806 float *tmp_all;
1807
1808 /* Keep one temporary decode buffer for the shared diagnostics path... */
1809 ALLOC(tmp_all, float,
1810 n);
1811
1812 /* Compress one full field with the configured LZ4 acceleration... */
1813 const double t0 = omp_get_wtime();
1814 const int compsizeInt =
1815 LZ4_compress_fast(uncompr, compr, uncomprLenInt, comprCapInt, accel);
1816 const double t_comp = omp_get_wtime() - t0;
1817 if (compsizeInt <= 0)
1818 ERRMSG("Compression failed!");
1819 const size_t compsize = (size_t) compsizeInt;
1820
1821 /* Write output... */
1822 FWRITE(&compsize, size_t,
1823 1,
1824 inout);
1825 FWRITE(compr, unsigned char,
1826 compsize,
1827 inout);
1828
1829 /* Decode once more so the common diagnostics see the reconstructed field... */
1830 const double t1 = omp_get_wtime();
1831 const int decomp_size =
1832 LZ4_decompress_safe(compr, (char *) tmp_all, compsizeInt,
1833 uncomprLenInt);
1834 const double t_decomp = omp_get_wtime() - t1;
1835 if (decomp_size != uncomprLenInt)
1836 ERRMSG("Decompression failed or size mismatch!");
1837
1838 const double ratio = COMPRESS_RATIO(uncomprLen, compsize);
1839 const double bpv = COMPRESS_BPV(n, compsize);
1840 compress_log_levels_3d(level_log, "LZ4", varname, met, array, tmp_all,
1841 nxy, nz, ratio, bpv, t_comp, t_decomp, uncomprLen);
1842
1843 /* Logging... */
1844 LOG(2, "Write 3-D variable: %s"
1845 " (%s, RATIO=%g, BPV=%g, T_COMP=%g s, V_COMP=%g MiB/s,"
1846 " T_DECOMP=%g s, V_DECOMP=%g MiB/s)",
1847 varname, codec_info, ratio, bpv, t_comp, COMPRESS_SPEED(uncomprLen,
1848 t_comp),
1849 t_decomp, COMPRESS_SPEED(uncomprLen, t_decomp));
1850
1851 free(tmp_all);
1852 }
1853
1854 /* Free... */
1855 free(compr);
1856}
1857#endif
1858
1859/*****************************************************************************/
1860
1861double cos_sza(
1862 const double sec,
1863 const double lon,
1864 const double lat) {
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}
1899
1900/*****************************************************************************/
1901
1903 const int year,
1904 const int mon,
1905 const int day,
1906 int *doy) {
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}
1918
1919/*****************************************************************************/
1920
1921#ifdef DD
1922/* Per-rank communication statistics use the existing MPI send counts. */
1923#if LOGLEV >= 2
1924static int *dd_node;
1925static int dd_particle_bytes;
1926static unsigned long long dd_sent, dd_intra, dd_inter;
1927#endif
1928
1930 const ctl_t *ctl,
1931 const dd_t *dd,
1932 atm_t *atm,
1933 const int init) {
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}
1997#endif
1998
1999/*****************************************************************************/
2000
2001#ifdef DD
2003 const ctl_t *ctl,
2004 cache_t *cache,
2005 atm_t *atm,
2006 particle_t *particles,
2007 const int npart) {
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}
2049#endif
2050
2051/*****************************************************************************/
2052
2053#ifdef DD
2055 const ctl_t *ctl,
2056 cache_t *cache,
2057 atm_t *atm,
2058 dd_t *dd,
2059 particle_t *particles,
2060 const int nkeep,
2061 const int npart) {
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}
2168#endif
2169
2170/*****************************************************************************/
2171
2172#ifdef DD
2174 const ctl_t *ctl,
2175 const dd_t *dd,
2176 double lon,
2177 double lat) {
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}
2201#endif
2202
2203/*****************************************************************************/
2204
2205#ifdef DD
2207 const ctl_t *ctl,
2208 const dd_t *dd,
2209 particle_t **particles,
2210 int *npart,
2211 int *capacity) {
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}
2338#endif
2339
2340/*****************************************************************************/
2341
2342#ifdef DD
2344 const ctl_t *ctl,
2345 dd_t *dd,
2346 atm_t *atm) {
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}
2418#endif
2419
2420/*****************************************************************************/
2421
2422#ifdef DD
2424 const dd_t *dd,
2425 double *lon,
2426 double *lat) {
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}
2451#endif
2452
2453/*****************************************************************************/
2454
2455#ifdef DD
2457 const ctl_t *ctl,
2458 cache_t *cache,
2459 const particle_t *particles,
2460 const int npart,
2461 atm_t *atm) {
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}
2502#endif
2503
2504/*****************************************************************************/
2505
2507 double *array,
2508 const int *perm,
2509 double *tmp,
2510 const int np) {
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}
2541
2542/*****************************************************************************/
2543
2545 cache_t *cache,
2546 const int *perm,
2547 double *tmp,
2548 const int np) {
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}
2598
2599/*****************************************************************************/
2600
2601#ifdef DD
2603 const ctl_t *ctl,
2604 atm_t *atm,
2605 cache_t *cache,
2606 int *npart) {
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}
2676#endif
2677
2678/*****************************************************************************/
2679
2680#ifdef DD
2682 const ctl_t *ctl,
2683 const met_t *met0,
2684 cache_t *cache,
2685 atm_t *atm,
2686 dd_t *dd,
2687 int *npart) {
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}
2791#endif
2792
2793/*****************************************************************************/
2794
2795#ifdef DD
2797 const ctl_t *ctl,
2798 const atm_t *atm,
2799 dd_t *dd,
2800 int *nkeep,
2801 int *npart) {
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}
2858#endif
2859
2860/*****************************************************************************/
2861
2863 const int year,
2864 const int doy,
2865 int *mon,
2866 int *day) {
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}
2889
2890/*****************************************************************************/
2891
2893 double *fcReal,
2894 double *fcImag,
2895 const int n) {
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}
2928
2929/*****************************************************************************/
2930
2932 const double z,
2933 const double lon,
2934 const double lat,
2935 double *x) {
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}
2946
2947/*****************************************************************************/
2948
2950 const ctl_t *ctl,
2951 const double t,
2952 const int direct,
2953 const char *metbase,
2954 const double dt_met,
2955 char *filename) {
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}
3015
3016/*****************************************************************************/
3017
3019 char *orig,
3020 const char *search,
3021 const char *repl) {
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}
3039
3040/*****************************************************************************/
3041
3043 const int met_tropo,
3044 ctl_t *ctl,
3045 const clim_t *clim,
3046 met_t *met,
3047 const double *lons,
3048 const int nx,
3049 const double *lats,
3050 const int ny,
3051 double *pt,
3052 double *zt,
3053 double *tt,
3054 double *qt,
3055 double *o3t,
3056 double *ps,
3057 double *zs) {
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}
3082
3083/*****************************************************************************/
3084
3086 const double *lons,
3087 const int nlon,
3088 const double *lats,
3089 const int nlat,
3090 const double lon,
3091 const double lat,
3092 double *lon2,
3093 double *lat2) {
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}
3109
3110/*****************************************************************************/
3111
3113 const double *lons,
3114 const int nlon,
3115 const double *lats,
3116 const int nlat,
3117 const double lon,
3118 const double lat,
3119 double *lon2,
3120 double *lat2) {
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}
3134
3135
3136/*****************************************************************************/
3137
3139 const met_t *met0,
3140 float heights0[EX][EY][EP],
3141 float array0[EX][EY][EP],
3142 const met_t *met1,
3143 float heights1[EX][EY][EP],
3144 float array1[EX][EY][EP],
3145 const double ts,
3146 const double height,
3147 const double lon,
3148 const double lat,
3149 double *var,
3150 int *ci,
3151 double *cw,
3152 const int init) {
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}
3313
3314/*****************************************************************************/
3315
3317 const met_t *met,
3318 float array[EX][EY][EP],
3319 const double p,
3320 const double lon,
3321 const double lat,
3322 double *var,
3323 int *ci,
3324 double *cw,
3325 const int init) {
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}
3376
3377/*****************************************************************************/
3378
3380 const met_t *met,
3381 float array[EX][EY],
3382 const double lon,
3383 const double lat,
3384 double *var,
3385 int *ci,
3386 double *cw,
3387 const int init) {
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}
3440
3441/*****************************************************************************/
3442
3444 const met_t *met0,
3445 float array0[EX][EY][EP],
3446 const met_t *met1,
3447 float array1[EX][EY][EP],
3448 const double ts,
3449 const double p,
3450 const double lon,
3451 const double lat,
3452 double *var,
3453 int *ci,
3454 double *cw,
3455 const int init) {
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}
3469
3470/*****************************************************************************/
3471
3473 const met_t *met0,
3474 float array0[EX][EY],
3475 const met_t *met1,
3476 float array1[EX][EY],
3477 const double ts,
3478 const double lon,
3479 const double lat,
3480 double *var,
3481 int *ci,
3482 double *cw,
3483 const int init) {
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}
3502
3503/*****************************************************************************/
3504
3506 const double time0,
3507 float array0[EX][EY],
3508 const double time1,
3509 float array1[EX][EY],
3510 const double lons[EX],
3511 const double lats[EY],
3512 const int nlon,
3513 const int nlat,
3514 const double time,
3515 const double lon,
3516 const double lat,
3517 const int method,
3518 double *var,
3519 double *sigma) {
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}
3606
3607/*****************************************************************************/
3608
3610 const double jsec,
3611 int *year,
3612 int *mon,
3613 int *day,
3614 int *hour,
3615 int *min,
3616 int *sec,
3617 double *remain) {
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}
3639
3640/*****************************************************************************/
3641
3643 const double kz[EP],
3644 const double kw[EP],
3645 const int nk,
3646 const double p) {
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}
3665
3666/*****************************************************************************/
3667
3669 const double t,
3670 const double h2o) {
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}
3683
3684/*****************************************************************************/
3685
3687 ctl_t *ctl) {
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}
3836
3837/*****************************************************************************/
3838
3840 const double *xx,
3841 const int n,
3842 const double x) {
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}
3866
3867/*****************************************************************************/
3868
3870 const float *xx,
3871 const int n,
3872 const double x,
3873 const int ig) {
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}
3900
3901/*****************************************************************************/
3902
3904 const double *xx,
3905 const int n,
3906 const double x) {
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}
3919
3920/*****************************************************************************/
3921
3923 float profiles[EX][EY][EP],
3924 const int np,
3925 const int lon_ap_ind,
3926 const int lat_ap_ind,
3927 const double height_ap,
3928 int *ind) {
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}
3939
3940/*****************************************************************************/
3941
3943 const ctl_t *ctl,
3944 const cache_t *cache,
3945 met_t *met0,
3946 met_t *met1,
3947 atm_t *atm) {
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}
4095
4096/*****************************************************************************/
4097
4099 const ctl_t *ctl,
4100 const cache_t *cache,
4101 met_t *met0,
4102 met_t *met1,
4103 atm_t *atm) {
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}
4122
4123/*****************************************************************************/
4124
4126 const ctl_t *ctl,
4127 const cache_t *cache,
4128 const clim_t *clim,
4129 met_t *met0,
4130 met_t *met1,
4131 atm_t *atm) {
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}
4218
4219/*****************************************************************************/
4220
4222 const ctl_t *ctl,
4223 const cache_t *cache,
4224 met_t *met0,
4225 met_t *met1,
4226 atm_t *atm,
4227 const double tt) {
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}
4410
4411/*****************************************************************************/
4412
4414 const ctl_t *ctl,
4415 const cache_t *cache,
4416 const clim_t *clim,
4417 met_t *met0,
4418 met_t *met1,
4419 atm_t *atm) {
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}
4454
4455/*****************************************************************************/
4456
4458 const ctl_t *ctl,
4459 cache_t *cache,
4460 met_t *met0,
4461 met_t *met1,
4462 atm_t *atm) {
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}
4528
4529/*****************************************************************************/
4530
4531#ifdef DD
4533 double t,
4534 const ctl_t *ctl,
4535 cache_t *cache,
4536 dd_t *dd,
4537 atm_t *atm,
4538 met_t **met) {
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}
4587#endif
4588
4589/*****************************************************************************/
4590
4592 const ctl_t *ctl,
4593 const cache_t *cache,
4594 const clim_t *clim,
4595 atm_t *atm) {
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}
4627
4628/*****************************************************************************/
4629
4631 const ctl_t *ctl,
4632 cache_t *cache,
4633 const met_t *met0,
4634 const met_t *met1,
4635 atm_t *atm) {
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}
4704
4705/*****************************************************************************/
4706
4708 const ctl_t *ctl,
4709 cache_t *cache,
4710 met_t *met0,
4711 met_t *met1,
4712 atm_t *atm) {
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}
4987
4988/*****************************************************************************/
4989
4991 const ctl_t *ctl,
4992 cache_t *cache,
4993 const clim_t *clim,
4994 met_t *met0,
4995 met_t *met1,
4996 atm_t *atm) {
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}
5159
5160/*****************************************************************************/
5161
5163 const ctl_t *ctl,
5164 const cache_t *cache,
5165 met_t *met0,
5166 met_t *met1,
5167 atm_t *atm) {
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}
5225
5226/*****************************************************************************/
5227
5229 const ctl_t *ctl,
5230 const cache_t *cache,
5231 const clim_t *clim,
5232 met_t *met0,
5233 met_t *met1,
5234 atm_t *atm) {
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}
5329
5330/*****************************************************************************/
5331
5333 const ctl_t *ctl,
5334 cache_t *cache,
5335 met_t *met0,
5336 met_t *met1,
5337 atm_t *atm,
5338 const int initial,
5339 const double model_t) {
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}
5441
5442/*****************************************************************************/
5443
5445 const ctl_t *ctl,
5446 const cache_t *cache,
5447 met_t *met0,
5448 met_t *met1,
5449 atm_t *atm) {
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}
5497
5498/*****************************************************************************/
5499
5500#ifdef KPP
5501void module_kpp_chem(
5502 ctl_t *ctl,
5503 cache_t *cache,
5504 clim_t *clim,
5505 met_t *met0,
5506 met_t *met1,
5507 atm_t *atm) {
5508
5509 /* Set timer... */
5510 SELECT_TIMER("MODULE_KPP_CHEM", "PHYSICS");
5511
5512 const int nvar = NVAR, nfix = NFIX, nreact = NREACT;
5513 double rtol[1] = { 1.0e-3 };
5514 double atol[1] = { 1.0 };
5515
5516 /* Loop over particles... */
5517#ifdef _OPENACC
5518#pragma acc data copy(rtol,atol,nvar,nfix,nreact)
5519#endif
5520 PARTICLE_LOOP(0, atm->np, 1,
5521 "acc data present(ctl,cache,clim,met0,met1,atm) ") {
5522
5523 /* Initialize... */
5524 double var[nvar], fix[nfix], rconst[nreact];
5525 for (int i = 0; i < nvar; i++)
5526 var[i] = 0.0;
5527 for (int i = 0; i < nfix; i++)
5528 fix[i] = 0.0;
5529 for (int i = 0; i < nreact; i++)
5530 rconst[i] = 0.0;
5531 kpp_chem_initialize(ctl, clim, met0, met1, atm, var, fix, rconst, ip);
5532
5533 /* Integrate... */
5534 double rpar[20];
5535 int ipar[20];
5536 for (int i = 0; i < 20; i++) {
5537 ipar[i] = 0;
5538 rpar[i] = 0.0;
5539 }
5540 ipar[0] = 0; /* 0: F=F(y), i.e. independent of t (autonomous); 0:F=F(t,y), i.e. depends on t (non-autonomous) */
5541 ipar[1] = 1; /* 0: NVAR-dimentional vector of tolerances; 1:scalar tolerances */
5542 ipar[3] = 4; /* choice of the method:Rodas3 */
5543 const int status = Rosenbrock(var, fix, rconst, 0, ctl->dt_kpp,
5544 atol, rtol, &FunTemplate, &JacTemplate, rpar, ipar);
5545 int valid = status == 1;
5546 for (int i = 0; i < nvar && valid; i++)
5547 valid = isfinite(var[i]);
5548 if (!valid || var[ind_so2] < 0)
5549 continue;
5550
5551 /* Save results.. */
5552 kpp_chem_output2atm(atm, ctl, met0, met1, var, ip);
5553 }
5554}
5555#endif
5556
5557/*****************************************************************************/
5558
5560 const ctl_t *ctl,
5561 const cache_t *cache,
5562 const clim_t *clim,
5563 met_t *met0,
5564 met_t *met1,
5565 atm_t *atm) {
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}
5686
5687/*****************************************************************************/
5688
5690 const ctl_t *ctl,
5691 const cache_t *cache,
5692 const clim_t *clim,
5693 atm_t *atm,
5694 const double t) {
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}
5786
5787/*****************************************************************************/
5788
5790 const ctl_t *ctl,
5791 atm_t *atm,
5792 const int *ixs,
5793 const int *iys,
5794 const int *izs,
5795 const double *mixparam,
5796 const int qnt_idx,
5797 const int use_ensemble) {
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}
5889
5890/*****************************************************************************/
5891
5893 const ctl_t *ctl,
5894 const cache_t *cache,
5895 const clim_t *clim,
5896 met_t *met0,
5897 met_t *met1,
5898 atm_t *atm) {
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}
5989
5990/*****************************************************************************/
5991
5993 const cache_t *cache,
5994 met_t *met0,
5995 met_t *met1,
5996 atm_t *atm,
5997 const int reflect) {
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}
6048
6049/*****************************************************************************/
6050
6052 const ctl_t *ctl,
6053 const cache_t *cache,
6054 atm_t *atm) {
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}
6106
6107/*****************************************************************************/
6108
6110 const ctl_t *ctl,
6111 const cache_t *cache,
6112 met_t *met0,
6113 met_t *met1,
6114 atm_t *atm,
6115 depo_t *depo) {
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}
6297
6298/*****************************************************************************/
6299
6301 const int ntask) {
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}
6331
6332/*****************************************************************************/
6333
6335 const ctl_t *ctl,
6336 double *rs,
6337 const size_t n,
6338 const int method) {
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}
6439
6440/*****************************************************************************/
6441
6443 const ctl_t *ctl,
6444 const cache_t *cache,
6445 met_t *met0,
6446 met_t *met1,
6447 atm_t *atm) {
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}
6467
6468/*****************************************************************************/
6469
6471 const ctl_t *ctl,
6472 const met_t *met0,
6473 cache_t *cache,
6474 atm_t *atm) {
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}
6544
6545/*****************************************************************************/
6546
6548 const ctl_t *ctl,
6549 cache_t *cache,
6550 const met_t *met0,
6551 atm_t *atm,
6552 const double t) {
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}
6593
6594/*****************************************************************************/
6595
6597 ctl_t *ctl,
6598 const atm_t *atm) {
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}
6624
6625/*****************************************************************************/
6626
6628 const ctl_t *ctl,
6629 const cache_t *cache,
6630 const clim_t *clim,
6631 met_t *met0,
6632 met_t *met1,
6633 atm_t *atm) {
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}
6716
6717/*****************************************************************************/
6718
6720 const ctl_t *ctl,
6721 const cache_t *cache,
6722 met_t *met0,
6723 met_t *met1,
6724 atm_t *atm) {
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}
6863
6864/*****************************************************************************/
6865
6867 ctl_t **ctl,
6868 cache_t **cache,
6869 clim_t **clim,
6870 met_t **met0,
6871 met_t **met1,
6872 atm_t **atm,
6873 depo_t **depo,
6874 dd_t **dd) {
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}
6953
6954/*****************************************************************************/
6955
6957 ctl_t *ctl,
6958 cache_t *cache,
6959 clim_t *clim,
6960 met_t *met0,
6961 met_t *met1,
6962 atm_t *atm,
6963 depo_t *depo,
6964 dd_t *dd) {
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}
7031
7032/*****************************************************************************/
7033
7035 ctl_t *ctl,
7036 clim_t *clim,
7037 const double t,
7038 met_t **met0,
7039 met_t **met1,
7040 dd_t *dd) {
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}
7165
7166/*****************************************************************************/
7167
7169 ctl_t *ctl,
7170 cache_t *cache,
7171 clim_t *clim,
7172 atm_t *atm,
7173 depo_t *depo,
7174 const int ntask) {
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}
7199
7200/*****************************************************************************/
7201
7203 const char *filename,
7204 const ctl_t *ctl,
7205 atm_t *atm) {
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}
7274
7275/*****************************************************************************/
7276
7278 const ctl_t *ctl,
7279 clim_t *clim) {
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}
7348
7349/*****************************************************************************/
7350
7352 const char *filename,
7353 int argc,
7354 char *argv[],
7355 ctl_t *ctl) {
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}
8670
8671/*****************************************************************************/
8672
8674 const char *filename,
8675 const ctl_t *ctl,
8676 const clim_t *clim,
8677 met_t *met,
8678 dd_t *dd) {
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}
8829
8830/*****************************************************************************/
8831
8833 ctl_t *ctl,
8834 cache_t *cache,
8835 clim_t *clim,
8836 met_t **met0,
8837 met_t **met1,
8838 atm_t *atm,
8839 depo_t *depo,
8840 double t,
8841 dd_t *dd) {
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}
8988
8989/*****************************************************************************/
8990
8992 const ctl_t *ctl,
8993 const cache_t *cache,
8994 const clim_t *clim,
8995 met_t **met0,
8996 met_t **met1,
8997 const atm_t *atm) {
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}
9044
9045/*****************************************************************************/
9046
9048 const ctl_t *ctl,
9049 const cache_t *cache,
9050 const clim_t *clim,
9051 met_t **met0,
9052 met_t **met1,
9053 const atm_t *atm) {
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}
9100
9101/*****************************************************************************/
9102
9104 const char *filename,
9105 const ctl_t *ctl,
9106 const atm_t *atm,
9107 const double t) {
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}
9164
9165/*****************************************************************************/
9166
9168 const char *filename,
9169 const ctl_t *ctl,
9170 met_t *met) {
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}
9213
9214/*****************************************************************************/
9215
9217 const char *dirname,
9218 const ctl_t *ctl,
9219 met_t *met0,
9220 met_t *met1,
9221 atm_t *atm,
9222 depo_t *depo,
9223 const double t) {
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}
9338
9339/*****************************************************************************/
9340
9342 const double p,
9343 const double h2o,
9344 const double hno3) {
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}
9362
9363/*****************************************************************************/
9364
9366 const ctl_t *ctl,
9367 const atm_t *atm,
9368 const int ip,
9369 const double pbl,
9370 const double ps) {
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}
9384
9385/*****************************************************************************/
9386
9388 const char *filename,
9389 const ctl_t *ctl,
9390 atm_t *atm) {
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}
9428
9429/*****************************************************************************/
9430
9432 const char *filename,
9433 const ctl_t *ctl,
9434 atm_t *atm) {
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}
9486
9487/*****************************************************************************/
9488
9490 const char *filename,
9491 const ctl_t *ctl,
9492 atm_t *atm) {
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}
9549
9550/*****************************************************************************/
9551
9553 const char *filename,
9554 const ctl_t *ctl,
9555 atm_t *atm) {
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}
9582
9583/*****************************************************************************/
9584
9586 const char *filename,
9587 clim_photo_t *photo) {
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}
9673
9674/*****************************************************************************/
9675
9677 const int ncid,
9678 const char *varname,
9679 const clim_photo_t *photo,
9680 double var[CP][CSZA][CO3]) {
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}
9701
9702/*****************************************************************************/
9703
9705 const char *filename,
9706 clim_ts_t *ts) {
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}
9755
9756/*****************************************************************************/
9757
9759 const char *filename,
9760 const char *varname,
9761 clim_zm_t *zm) {
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}
9854
9855/*****************************************************************************/
9856
9858 const char *filename,
9859 double kz[EP],
9860 double kw[EP],
9861 int *nk) {
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}
9901
9902/*****************************************************************************/
9903
9905 const char *filename,
9906 const ctl_t *ctl,
9907 met_t *met) {
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}
10061
10062/*****************************************************************************/
10063
10065 FILE *in,
10066 const met_t *met,
10067 float var[EX][EY],
10068 const char *varname) {
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}
10090
10091/*****************************************************************************/
10092
10094 FILE *in,
10095 const ctl_t *ctl,
10096 const met_t *met,
10097 float var[EX][EY][EP],
10098 const char *varname,
10099 const float bound_min,
10100 const float bound_max) {
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}
10200
10201/*****************************************************************************/
10202
10204 const ctl_t *ctl,
10205 const clim_t *clim,
10206 met_t *met) {
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}
10320
10321/*****************************************************************************/
10322
10324 met_t *met) {
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}
10377
10378/*****************************************************************************/
10379
10381 const ctl_t *ctl,
10382 met_t *met) {
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}
10484
10485/*****************************************************************************/
10486
10488 met_t *met) {
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}
10524
10525/*****************************************************************************/
10526
10528 const ctl_t *ctl,
10529 met_t *met) {
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}
10653
10654/*****************************************************************************/
10655
10657 const char *filename,
10658 const int ncid,
10659 const ctl_t *ctl,
10660 met_t *met,
10661 dd_t *dd) {
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}
10840
10841/*****************************************************************************/
10842
10844 const int ncid,
10845 const ctl_t *ctl,
10846 met_t *met,
10847 dd_t *dd) {
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}
10997
10998/*****************************************************************************/
10999
11001 const int ncid,
11002 const ctl_t *ctl,
11003 met_t *met,
11004 dd_t *dd) {
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}
11224
11225/*****************************************************************************/
11226
11227#ifdef DD
11228/* One file-local redistribution workspace. The eight entries per rank are
11229 * y/x starts, y/x counts, periodic x start/count, and the two x offsets. */
11230static struct {
11231 unsigned long long *geometry;
11232 float *global, *packed, *local;
11235} met_global_2d;
11236
11238static void met_global_2d_init(const dd_t *dd, const met_t *met) {
11239
11240 MPI_Comm_rank(MPI_COMM_WORLD, &met_global_2d.rank);
11241 MPI_Comm_size(MPI_COMM_WORLD, &met_global_2d.size);
11242 const unsigned long long own[8] = {
11243 dd->subdomain_start[2], dd->subdomain_start[3],
11244 dd->subdomain_count[2], dd->subdomain_count[3],
11245 dd->halo_bnd_start[3], dd->halo_bnd_count[3],
11246 (unsigned long long) dd->halo_offset_start,
11247 (unsigned long long) dd->halo_offset_end
11248 };
11249 ALLOC(met_global_2d.geometry, unsigned long long,
11250 8 * (size_t) met_global_2d.size);
11251 MPI_Allgather(own, 8, MPI_UNSIGNED_LONG_LONG, met_global_2d.geometry,
11252 8, MPI_UNSIGNED_LONG_LONG, MPI_COMM_WORLD);
11253
11254 const size_t nx = (size_t) dd->nx_glob, ny = (size_t) dd->ny_glob;
11255 if (nx > SIZE_MAX / ny || nx * ny > SIZE_MAX / sizeof(float))
11256 ERRMSG("Global 2-D meteorological field exceeds addressable memory!");
11257 met_global_2d.global_elements = nx * ny;
11258 met_global_2d.local_elements = (size_t) met->nx * (size_t) met->ny;
11259 if (met_global_2d.local_elements > SIZE_MAX / sizeof(float))
11260 ERRMSG("Local 2-D meteorological field exceeds addressable memory!");
11261 ALLOC(met_global_2d.local, float, met_global_2d.local_elements);
11262
11263 for (int rank = 0; rank < met_global_2d.size; rank++) {
11264 const unsigned long long *g = met_global_2d.geometry + 8 * rank;
11265 if (g[3] > SIZE_MAX - g[5])
11266 ERRMSG("Invalid DD window width for global 2-D redistribution!");
11267 const size_t width = (size_t) g[3] + (size_t) g[5];
11268 if (width == 0 || g[2] > SIZE_MAX / width)
11269 ERRMSG("Invalid DD window size for global 2-D redistribution!");
11270 const size_t count = (size_t) g[2] * width;
11271 if (g[6] > width || g[3] > width - g[6]
11272 || g[7] > width || g[5] > width - g[7]
11273 || count > SIZE_MAX / sizeof(float)
11274 || g[0] + g[2] > ny || g[1] + g[3] > nx
11275 || g[4] + g[5] > nx)
11276 ERRMSG("Invalid DD window for global 2-D redistribution!");
11277 if (count > met_global_2d.packed_elements)
11278 met_global_2d.packed_elements = count;
11279 }
11280 ALLOC(met_global_2d.packed, float, met_global_2d.packed_elements);
11281}
11282
11284static void met_global_2d_free(void) {
11285
11286 free(met_global_2d.geometry);
11287 free(met_global_2d.global);
11288 free(met_global_2d.packed);
11289 free(met_global_2d.local);
11290 memset(&met_global_2d, 0, sizeof(met_global_2d));
11291}
11292
11294static void met_global_2d_pack(
11295 const float *global,
11296 float *packed,
11297 const unsigned long long *g,
11298 const size_t nx) {
11299
11300 const size_t width = (size_t) g[3] + (size_t) g[5];
11301 for (size_t y = 0; y < (size_t) g[2]; y++) {
11302 float *row = packed + y * width;
11303 const float *source = global + ((size_t) g[0] + y) * nx;
11304 memcpy(row + (size_t) g[6], source + (size_t) g[1],
11305 (size_t) g[3] * sizeof(float));
11306 if (g[5])
11307 memcpy(row + (size_t) g[7], source + (size_t) g[4],
11308 (size_t) g[5] * sizeof(float));
11309 }
11310}
11311
11313static const float *met_global_2d_read(
11314 const int ncid,
11315 const int varid,
11316 const int ndims,
11317 const int level,
11318 const dd_t *dd) {
11319
11320 const int reader = level % met_global_2d.size;
11321 if (met_global_2d.rank == reader) {
11322 SELECT_TIMER("MET_READ", "INPUT");
11323 if (met_global_2d.global == NULL)
11324 ALLOC(met_global_2d.global, float, met_global_2d.global_elements);
11325 if (ndims == 4) {
11326 const size_t start[4] = { 0, (size_t) level, 0, 0 };
11327 const size_t count[4] = { 1, 1, (size_t) dd->ny_glob,
11328 (size_t) dd->nx_glob };
11329 NC(nc_get_vara_float(ncid, varid, start, count,
11330 met_global_2d.global));
11331 } else {
11332 const size_t start[3] = { 0, 0, 0 };
11333 const size_t count[3] = { 1, (size_t) dd->ny_glob,
11334 (size_t) dd->nx_glob };
11335 NC(nc_get_vara_float(ncid, varid, start, count,
11336 met_global_2d.global));
11337 }
11338 }
11339
11340 for (int rank = 0; rank < met_global_2d.size; rank++) {
11341 const unsigned long long *g = met_global_2d.geometry + 8 * rank;
11342 const size_t elements = (size_t) g[2] * ((size_t) g[3] + (size_t) g[5]);
11343 if (met_global_2d.rank == reader) {
11344 SELECT_TIMER("MET_PACK", "INPUT");
11345 float *target = rank == reader ? met_global_2d.local :
11346 met_global_2d.packed;
11347 met_global_2d_pack(met_global_2d.global, target, g,
11348 (size_t) dd->nx_glob);
11349 if (rank != reader) {
11350 SELECT_TIMER("MET_MPI", "INPUT");
11351 for (size_t offset = 0; offset < elements;) {
11352 const int count = (int) MIN(elements - offset, (size_t) INT_MAX);
11353 if (MPI_Send(target + offset, count, MPI_FLOAT, rank, 0,
11354 MPI_COMM_WORLD) != MPI_SUCCESS)
11355 ERRMSG("Failed to distribute meteorological field!");
11356 offset += (size_t) count;
11357 }
11358 }
11359 } else if (met_global_2d.rank == rank) {
11360 SELECT_TIMER("MET_MPI", "INPUT");
11361 for (size_t offset = 0; offset < elements;) {
11362 const int count = (int) MIN(elements - offset, (size_t) INT_MAX);
11363 if (MPI_Recv(met_global_2d.local + offset, count, MPI_FLOAT, reader,
11364 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE) != MPI_SUCCESS)
11365 ERRMSG("Failed to receive meteorological field!");
11366 offset += (size_t) count;
11367 }
11368 }
11369 }
11370 return met_global_2d.local;
11371}
11372
11374static void met_global_2d_check_var(
11375 const int ncid,
11376 const int varid,
11377 const int ndims,
11378 const dd_t *dd,
11379 const int levels) {
11380
11381 int actual, ids[NC_MAX_VAR_DIMS];
11382 char name[NC_MAX_NAME + 1];
11383 size_t length;
11384 NC(nc_inq_varndims(ncid, varid, &actual));
11385 if (actual != ndims)
11386 ERRMSG("MET_NC_READ_MODE=1 requires time-first NetCDF variables!");
11387 NC(nc_inq_vardimid(ncid, varid, ids));
11388 NC(nc_inq_dimname(ncid, ids[0], name));
11389 if (strcmp(name, "time") != 0)
11390 ERRMSG("MET_NC_READ_MODE=1 requires time as first dimension!");
11391 NC(nc_inq_dimlen(ncid, ids[0], &length));
11392 if (length < 1)
11393 ERRMSG("MET_NC_READ_MODE=1 requires a nonempty time dimension!");
11394 NC(nc_inq_dimname(ncid, ids[ndims - 1], name));
11395 if (strcmp(name, "lon") != 0)
11396 ERRMSG("MET_NC_READ_MODE=1 requires longitude as last dimension!");
11397 NC(nc_inq_dimlen(ncid, ids[ndims - 1], &length));
11398 if (length != (size_t) dd->nx_glob)
11399 ERRMSG("MET_NC_READ_MODE=1 requires longitude as fastest dimension!");
11400 NC(nc_inq_dimname(ncid, ids[ndims - 2], name));
11401 if (strcmp(name, "lat") != 0)
11402 ERRMSG("MET_NC_READ_MODE=1 requires latitude before longitude!");
11403 NC(nc_inq_dimlen(ncid, ids[ndims - 2], &length));
11404 if (length != (size_t) dd->ny_glob)
11405 ERRMSG("MET_NC_READ_MODE=1 requires latitude before longitude!");
11406 if (ndims == 4) {
11407 NC(nc_inq_dimlen(ncid, ids[1], &length));
11408 if (length != (size_t) levels)
11409 ERRMSG("MET_NC_READ_MODE=1 requires all vertical levels!");
11410 }
11411}
11412#endif
11413
11414/*****************************************************************************/
11415
11417 const int ncid,
11418 const char *const varnames[],
11419 const size_t nvarnames,
11420 const ctl_t *ctl,
11421 const met_t *met,
11422 dd_t *dd,
11423 float dest[EX][EY],
11424 const float scl,
11425 const int init) {
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}
11751
11752/*****************************************************************************/
11753
11755 const int ncid,
11756 const char *const varnames[],
11757 const size_t nvarnames,
11758 const ctl_t *ctl,
11759 const met_t *met,
11760 dd_t *dd,
11761 float dest[EX][EY][EP],
11762 const float scl) {
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}
12084
12085/*****************************************************************************/
12086
12087#ifdef ECCODES
12088int read_met_grib(
12089 const char *filename,
12090 const ctl_t *ctl,
12091 met_t *met) {
12092
12093 /* Set filenames... */
12094 size_t filename_len = strlen(filename) + 1;
12095 char sf_filename[filename_len];
12096 char ml_filename[filename_len];
12097 strcpy(sf_filename, filename);
12098 strcpy(ml_filename, filename);
12099 get_met_replace(ml_filename, "XX", "ml");
12100 get_met_replace(sf_filename, "XX", "sf");
12101
12102 /* Open files... */
12103 FILE *ml_file = fopen(ml_filename, "rb");
12104 FILE *sf_file = fopen(sf_filename, "rb");
12105 if (ml_file == NULL || sf_file == NULL) {
12106 if (ml_file != NULL) {
12107 fclose(ml_file);
12108 WARN("Cannot open file: %s", sf_filename);
12109 }
12110 if (sf_file != NULL) {
12111 fclose(sf_file);
12112 WARN("Cannot open file: %s", ml_filename);
12113 }
12114 return 0;
12115 }
12116
12117 /* Get handles for model level data... */
12118 int ml_num_messages = 0, err = 0;
12119 ECC(codes_count_in_file(0, ml_file, &ml_num_messages));
12120 codes_handle **ml_handles =
12121 (codes_handle **) malloc(sizeof(codes_handle *) *
12122 (size_t) ml_num_messages);
12123 for (int i = 0; i < ml_num_messages; i++) {
12124 codes_handle *h = NULL;
12125 if ((h = codes_grib_handle_new_from_file(0, ml_file, &err)) != NULL)
12126 ml_handles[i] = h;
12127 }
12128
12129 /* Get handles for surface data... */
12130 int sf_num_messages = 0;
12131 ECC(codes_count_in_file(0, sf_file, &sf_num_messages));
12132 codes_handle **sf_handles =
12133 (codes_handle **) malloc(sizeof(codes_handle *) *
12134 (size_t) sf_num_messages);
12135 for (int i = 0; i < sf_num_messages; i++) {
12136 codes_handle *h = NULL;
12137 if ((h = codes_grib_handle_new_from_file(0, sf_file, &err)) != NULL)
12138 sf_handles[i] = h;
12139 }
12140
12141 /* Close files... */
12142 fclose(ml_file);
12143 fclose(sf_file);
12144
12145 /* Read grid data... */
12146 read_met_grib_grid(ml_handles, ml_num_messages, met);
12147
12148 /* Read surface data... */
12149 read_met_grib_surface(sf_handles, sf_num_messages, ctl, met);
12150 for (int i = 0; i < sf_num_messages; i++)
12151 codes_handle_delete(sf_handles[i]);
12152 free(sf_handles);
12153
12154 /* Compute 3D pressure field... */
12155 size_t value_count = 0;
12156 ECC(codes_get_size(ml_handles[0], "pv", &value_count));
12157 if (value_count % 2 != 0)
12158 ERRMSG("Unexpected pv array length!");
12159 size_t nlevels = value_count / 2 - 1; /* number of full model levels */
12160 double *values;
12161 ALLOC(values, double,
12162 value_count);
12163 ECC(codes_get_double_array(ml_handles[0], "pv", values, &value_count));
12164 double *a_vals = values;
12165 double *b_vals = values + nlevels;
12166 if (met->npl > (int) nlevels)
12167 ERRMSG("met->npl exceeds number of pressure levels in GRIB!");
12168 for (int nx = 0; nx < met->nx; nx++)
12169 for (int ny = 0; ny < met->ny; ny++)
12170 for (int level = 0; level <= met->npl; level++) {
12171 const float p1 = (float) (a_vals[level] * 0.01f +
12172 met->ps[nx][ny] * b_vals[level]);
12173 const float p2 = (float) (a_vals[level + 1] * 0.01f +
12174 met->ps[nx][ny] * b_vals[level + 1]);
12175 met->pl[nx][ny][level] = 0.5f * (p1 + p2);
12176 }
12177 free(values);
12178
12179 /* Read model level data... */
12180 read_met_grib_levels(ml_handles, ml_num_messages, ctl, met);
12181 for (int i = 0; i < ml_num_messages; i++)
12182 codes_handle_delete(ml_handles[i]);
12183 free(ml_handles);
12184
12185 /* Return success... */
12186 return 1;
12187}
12188#endif
12189
12190/*****************************************************************************/
12191
12192#ifdef ECCODES
12194 codes_handle **handles,
12195 int count_handles,
12196 met_t *met) {
12197
12198 /* Set timer... */
12199 SELECT_TIMER("READ_MET_GRIB_GRID", "INPUT");
12200 LOG(2, "Read meteo grid information...");
12201
12202 /* Read date and time... */
12203 char datestr[LEN], timestr[LEN];
12204 size_t s_date = sizeof(datestr);
12205 ECC(codes_get_string(handles[0], "dataDate", datestr, &s_date));
12206 size_t s_time = sizeof(timestr);
12207 ECC(codes_get_string(handles[0], "dataTime", timestr, &s_time));
12208 int year, month, day, hour;
12209 if (sscanf(datestr, "%4d%2d%2d", &year, &month, &day) != 3)
12210 ERRMSG("Failed to parse dataDate: %s", datestr);
12211 if (sscanf(timestr, "%2d", &hour) != 1)
12212 ERRMSG("Failed to parse dataTime: %s", timestr);
12213 time2jsec(year, month, day, hour, 0, 0, 0, &(met->time));
12214 LOG(2, "Time: %.2f (%d-%02d-%02d, %02d:%02d UTC)", met->time, year, month,
12215 day, hour, 0);
12216
12217 /* Read grid information... */
12218 long count_lat = 0, count_lon = 0;
12219 ECC(codes_get_long(handles[0], "Nj", &count_lat));
12220 ECC(codes_get_long(handles[0], "Ni", &count_lon));
12221 met->ny = (int) count_lat;
12222 met->nx = (int) count_lon;
12223
12224 /* Check grid dimensions... */
12225 LOG(2, "Number of longitudes: %d", met->nx);
12226 if (met->nx < 2 || met->nx > EX)
12227 ERRMSG("Number of longitudes out of range!");
12228 LOG(2, "Number of latitudes: %d", met->ny);
12229 if (met->ny < 2 || met->ny > EY)
12230 ERRMSG("Number of latitudes out of range!");
12231
12232 double first_lon, last_lon, first_lat, last_lat, inc_lon, inc_lat;
12233 ECC(codes_get_double
12234 (handles[0], "longitudeOfFirstGridPointInDegrees", &first_lon));
12235 ECC(codes_get_double
12236 (handles[0], "latitudeOfFirstGridPointInDegrees", &first_lat));
12237 ECC(codes_get_double
12238 (handles[0], "longitudeOfLastGridPointInDegrees", &last_lon));
12239 ECC(codes_get_double
12240 (handles[0], "latitudeOfLastGridPointInDegrees", &last_lat));
12241 ECC(codes_get_double(handles[0], "iDirectionIncrementInDegrees", &inc_lon));
12242 ECC(codes_get_double(handles[0], "jDirectionIncrementInDegrees", &inc_lat));
12243
12244 long jscanpos, iscanneg;
12245 ECC(codes_get_long(handles[0], "iScansNegatively", &iscanneg));
12246 ECC(codes_get_long(handles[0], "jScansPositively", &jscanpos));
12247
12248 /* Compute longitude-latitude grid... */
12249 int counter = 0;
12250 if (iscanneg == 0)
12251 for (double i = first_lon; i <= last_lon + 1e-6; i += inc_lon) {
12252 met->lon[counter] = i;
12253 counter++;
12254 } else
12255 for (double i = first_lon; i > last_lon - 1e-6; i -= inc_lon) {
12256 met->lon[counter] = i;
12257 counter++;
12258 }
12259
12260 counter = 0;
12261 if (jscanpos == 0)
12262 for (double i = first_lat; i > last_lat - 1e-6; i -= inc_lat) {
12263 met->lat[counter] = i;
12264 counter++;
12265 } else
12266 for (double i = first_lat; i <= last_lat + 1e-6; i += inc_lat) {
12267 met->lat[counter] = i;
12268 counter++;
12269 }
12270
12271 /* Write info... */
12272 LOG(2, "Longitudes: %g, %g ... %g deg",
12273 met->lon[0], met->lon[1], met->lon[met->nx - 1]);
12274 LOG(2, "Latitudes: %g, %g ... %g deg",
12275 met->lat[0], met->lat[1], met->lat[met->ny - 1]);
12276
12277 /* Read vertical levels... */
12278 int max_level = 0;
12279 for (int i = 0; i < count_handles; i++) {
12280 long level;
12281 ECC(codes_get_long(handles[i], "level", &level));
12282 if (level > max_level)
12283 max_level = (int) level;
12284 }
12285 met->npl = max_level;
12286
12287 /* Check number of levels... */
12288 LOG(2, "Number of levels: %d", met->npl);
12289 if (met->npl < 2 || met->npl > EP)
12290 ERRMSG("Number of levels out of range!");
12291}
12292#endif
12293
12294/*****************************************************************************/
12295
12296#ifdef ECCODES
12298 codes_handle **handles,
12299 const int num_messages,
12300 const ctl_t *ctl,
12301 met_t *met) {
12302
12303 /* Set timer... */
12304 SELECT_TIMER("READ_MET_GRIB_LEVELS", "INPUT");
12305 LOG(2, "Read level data...");
12306
12307 /* Init... */
12308 int t_flag = 0, u_flag = 0, v_flag = 0, w_flag = 0, o3_flag = 0, h2o_flag =
12309 0, lwc_flag = 0, rwc_flag = 0, iwc_flag = 0, swc_flag = 0, cc_flag = 0;
12310
12311 /* Iterate over all messages... */
12312 for (int i = 0; i < num_messages; i++) {
12313
12314 size_t max_size = LEN;
12315 char short_name[max_size];
12316 size_t value_count;
12317 double *values;
12318
12319 /* Get the current level */
12320 long current_level;
12321 ECC(codes_get_long(handles[i], "level", &current_level));
12322 current_level -= 1;
12323
12324 /* Retrieve data from current message */
12325 ECC(codes_get_string(handles[i], "shortName", short_name, &max_size));
12326 ECC(codes_get_size(handles[i], "values", &value_count));
12327 ALLOC(values, double,
12328 value_count);
12329 ECC(codes_get_double_array(handles[i], "values", values, &value_count));
12330
12331 /* Read temperature... */
12332 ECC_READ_3D("t", current_level, met->t, 1.0, t_flag);
12333
12334 /* Read horizontal wind and vertical velocity... */
12335 ECC_READ_3D("u", current_level, met->u, 1.0, u_flag);
12336 ECC_READ_3D("v", current_level, met->v, 1.0, v_flag);
12337 ECC_READ_3D("w", current_level, met->w, 0.01f, w_flag);
12338
12339 /* Read water vapor and ozone... */
12340 ECC_READ_3D("q", current_level, met->h2o, (float) (MA / MH2O), h2o_flag);
12341 ECC_READ_3D("o3", current_level, met->o3, (float) (MA / MO3), o3_flag);
12342
12343 /* Read cloud data... */
12344 ECC_READ_3D("clwc", current_level, met->lwc, 1.0, lwc_flag);
12345 ECC_READ_3D("crwc", current_level, met->rwc, 1.0, rwc_flag);
12346 ECC_READ_3D("ciwc", current_level, met->iwc, 1.0, iwc_flag);
12347 ECC_READ_3D("cswc", current_level, met->swc, 1.0, swc_flag);
12348 ECC_READ_3D("cc", current_level, met->cc, 1.0, cc_flag);
12349
12350 /*Free allocated array */
12351 free(values);
12352 }
12353
12354 /* Check whether data were found... */
12355 if (t_flag != met->npl)
12356 ERRMSG("Cannot read temperature!");
12357 if (u_flag != met->npl)
12358 ERRMSG("Cannot read zonal wind!");
12359 if (v_flag != met->npl)
12360 ERRMSG("Cannot read meridional wind!");
12361 if (w_flag != met->npl)
12362 WARN("Cannot read vertical velocity!");
12363 if (h2o_flag != met->npl)
12364 WARN("Cannot read specific humidity!");
12365 if (o3_flag != met->npl)
12366 WARN("Cannot read ozone data!");
12367 if (lwc_flag != met->npl)
12368 WARN("Cannot read cloud liquid water content!");
12369 if (rwc_flag != met->npl)
12370 WARN("Cannot read cloud rain water content!");
12371 if (iwc_flag != met->npl)
12372 WARN("Cannot read cloud ice water content!");
12373 if (swc_flag != met->npl)
12374 WARN("Cannot read cloud snow water content!");
12375 if (cc_flag != met->npl)
12376 WARN("Cannot read cloud cover!");
12377
12378 /* Check ordering of pressure levels... */
12379 for (int ix = 0; ix < met->nx; ix++)
12380 for (int iy = 0; iy < met->ny; iy++)
12381 for (int ip = 1; ip < met->np; ip++)
12382 if ((met->pl[ix][iy][0] > met->pl[ix][iy][1]
12383 && met->pl[ix][iy][ip - 1] <= met->pl[ix][iy][ip])
12384 || (met->pl[ix][iy][0] < met->pl[ix][iy][1]
12385 && met->pl[ix][iy][ip - 1] >= met->pl[ix][iy][ip])) {
12386 LOG(1, "%f %f %f %f", met->pl[ix][iy][0], met->pl[ix][iy][1],
12387 met->pl[ix][iy][ip - 1], met->pl[ix][iy][ip]);
12388 ERRMSG("Pressure profiles are not monotonic!");
12389 }
12390
12391 /* Interpolate from model levels to pressure levels... */
12392 if (ctl->met_np > 0) {
12393 met->np = ctl->met_np;
12394
12395 /* Interpolate variables... */
12396 read_met_ml2pl(ctl, met, met->t, "T");
12397 read_met_ml2pl(ctl, met, met->u, "U");
12398 read_met_ml2pl(ctl, met, met->v, "V");
12399 read_met_ml2pl(ctl, met, met->w, "W");
12400 read_met_ml2pl(ctl, met, met->h2o, "H2O");
12401 read_met_ml2pl(ctl, met, met->o3, "O3");
12402 read_met_ml2pl(ctl, met, met->lwc, "LWC");
12403 read_met_ml2pl(ctl, met, met->rwc, "RWC");
12404 read_met_ml2pl(ctl, met, met->iwc, "IWC");
12405 read_met_ml2pl(ctl, met, met->swc, "SWC");
12406 read_met_ml2pl(ctl, met, met->cc, "CC");
12407
12408 /* Set new pressure levels... */
12409 for (int ip = 0; ip < met->np; ip++)
12410 met->p[ip] = ctl->met_p[ip];
12411 }
12412
12413 /* Check ordering of pressure levels... */
12414 for (int ip = 1; ip < met->np; ip++)
12415 if (met->p[ip - 1] < met->p[ip])
12416 ERRMSG("Pressure levels must be descending!");
12417}
12418#endif
12419
12420/*****************************************************************************/
12421
12422#ifdef ECCODES
12424 codes_handle **handles,
12425 const int num_messages,
12426 const ctl_t *ctl,
12427 met_t *met) {
12428
12429 /* Set timer... */
12430 SELECT_TIMER("READ_MET_GRIB_SURFACE", "INPUT");
12431 LOG(2, "Read surface data...");
12432
12433 /* Init... */
12434 int sp_flag = 0, z_flag = 0, t_flag = 0, u_flag = 0, v_flag = 0, ess_flag =
12435 0, nss_flag = 0, shf_flag = 0, lsm_flag = 0, sst_flag = 0, cape_flag = 0,
12436 cin_flag = 0, pbl_flag = 0;
12437
12438 /* Iterate over all messages... */
12439 for (int i = 0; i < num_messages; i++) {
12440
12441 size_t max_size = LEN, value_count;
12442
12443 char short_name[max_size];
12444
12445 /* Store values with shortname... */
12446 ECC(codes_get_string(handles[i], "shortName", short_name, &max_size));
12447 ECC(codes_get_size(handles[i], "values", &value_count));
12448 double *values = (double *) malloc(value_count * sizeof(double));
12449 ECC(codes_get_double_array(handles[i], "values", values, &value_count));
12450
12451 /*Read surface pressure... */
12452 ECC_READ_2D("sp", met->ps, 0.01f, sp_flag);
12453
12454 /*Read geopotential height at the surface... */
12455 ECC_READ_2D("z", met->zs, (float) (1. / (1000. * G0)), z_flag);
12456
12457 /* Read temperature at the surface... */
12458 ECC_READ_2D("2t", met->ts, 1.0f, t_flag);
12459
12460 /* Read zonal wind at the surface... */
12461 ECC_READ_2D("10u", met->us, 1.0f, u_flag);
12462
12463 /* Read meridional wind at the surface... */
12464 ECC_READ_2D("10v", met->vs, 1.0f, v_flag);
12465
12466 /* Read eastward turbulent surface stress... */
12467 ECC_READ_2D("iews", met->ess, 1.0f, ess_flag);
12468
12469 /* Read northward turbulent surface stress... */
12470 ECC_READ_2D("inss", met->nss, 1.0f, nss_flag);
12471
12472 /* Read surface sensible heat flux... */
12473 ECC_READ_2D("ishf", met->shf, 1.0f, shf_flag);
12474
12475 /* Read land-sea mask... */
12476 ECC_READ_2D("lsm", met->lsm, 1.0f, lsm_flag);
12477
12478 /* Read sea surface temperature... */
12479 ECC_READ_2D("sst", met->sst, 1.0f, sst_flag);
12480 if (ctl->met_cape == 0) {
12481
12482 /* Read CAPE... */
12483 ECC_READ_2D("cape", met->cape, 1.0f, cape_flag);
12484
12485 /* Read CIN... */
12486 ECC_READ_2D("cin", met->cin, 1.0f, cin_flag);
12487 }
12488
12489 /* Read PBL... */
12490 if (ctl->met_pbl == 1)
12491 ECC_READ_2D("blh", met->pbl, 0.001f, pbl_flag);
12492 }
12493
12494 /* Check whether data have been read... */
12495 if (sp_flag == 0)
12496 WARN("Cannot read surface pressure data!");
12497 if (z_flag == 0)
12498 WARN("Cannot read surface geopotential height!");
12499 if (t_flag == 0)
12500 WARN("Cannot read surface temperature!");
12501 if (u_flag == 0)
12502 WARN("Cannot read surface zonal wind!");
12503 if (v_flag == 0)
12504 WARN("Cannot read surface meridional wind!");
12505 if (ess_flag == 0)
12506 WARN("Cannot read eastward turbulent surface stress!");
12507 if (nss_flag == 0)
12508 WARN("Cannot read northward turbulent surface stress!");
12509 if (shf_flag == 0)
12510 WARN("Cannot read surface sensible heat flux!");
12511 if (lsm_flag == 0)
12512 WARN("Cannot read land-sea mask!");
12513 if (sst_flag == 0)
12514 WARN("Cannot read sea surface temperature!");
12515 if (ctl->met_cape == 0) {
12516 if (cape_flag == 0)
12517 WARN("Cannot read CAPE!");
12518 if (cin_flag == 0)
12519 WARN("Cannot read convective inhibition!");
12520 }
12521 if (ctl->met_pbl == 1 && pbl_flag == 0)
12522 WARN("Cannot read planetary boundary layer height!");
12523}
12524#endif
12525
12526/*****************************************************************************/
12527
12529 const ctl_t *ctl,
12530 const met_t *met,
12531 float var[EX][EY][EP],
12532 const char *varname) {
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}
12567
12568/*****************************************************************************/
12569
12571 const ctl_t *ctl,
12572 met_t *met) {
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}
12652
12653/*****************************************************************************/
12654
12656 const char *filename,
12657 const ctl_t *ctl,
12658 met_t *met,
12659 dd_t *dd,
12660 int *pv_supplied) {
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}
12715
12716/*****************************************************************************/
12717
12719 dd_t *dd,
12720 const ctl_t *ctl,
12721 met_t *met,
12722 const int ncid) {
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}
12905
12906/*****************************************************************************/
12907
12909 const ctl_t *ctl,
12910 met_t *met) {
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}
13042
13043/*****************************************************************************/
13044
13046 met_t *met) {
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}
13104
13105/*****************************************************************************/
13106
13108 met_t *met) {
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}
13166
13167/*****************************************************************************/
13168
13170 met_t *met) {
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}
13285
13286/*****************************************************************************/
13287
13289 met_t *met) {
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}
13314
13315/*****************************************************************************/
13316
13318 const ctl_t *ctl,
13319 met_t *met) {
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}
13493
13494/*****************************************************************************/
13495
13497 const ctl_t *ctl,
13498 const clim_t *clim,
13499 met_t *met) {
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}
13667
13668/*****************************************************************************/
13669
13671 const char *filename,
13672 const ctl_t *ctl,
13673 double *rt,
13674 double *rz,
13675 double *rlon,
13676 double *rlat,
13677 double *robs,
13678 int *nobs) {
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}
13711
13712/*****************************************************************************/
13713
13715 const char *filename,
13716 double *rt,
13717 double *rz,
13718 double *rlon,
13719 double *rlat,
13720 double *robs,
13721 int *nobs) {
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}
13739
13740/*****************************************************************************/
13741
13743 const char *filename,
13744 double *rt,
13745 double *rz,
13746 double *rlon,
13747 double *rlat,
13748 double *robs,
13749 int *nobs) {
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}
13768
13769/*****************************************************************************/
13770
13772 const char *filename,
13773 int argc,
13774 char *argv[],
13775 const char *varname,
13776 const int arridx,
13777 const char *defvalue,
13778 char *value) {
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}
13840
13841/*****************************************************************************/
13842
13843double sedi(
13844 const double p,
13845 const double T,
13846 const double rp,
13847 const double rhop) {
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}
13876
13877/*****************************************************************************/
13878
13880 const double *x,
13881 const double *y,
13882 const int n,
13883 const double *x2,
13884 double *y2,
13885 const int n2,
13886 const int method) {
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}
13923
13924/*****************************************************************************/
13925
13927 const double x,
13928 const double w,
13929 const double weight_old,
13930 double *mean,
13931 double *m2) {
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}
13946
13947/*****************************************************************************/
13948
13950 const float *data,
13951 const int n) {
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}
13969
13970/*****************************************************************************/
13971
13973 const int year,
13974 const int mon,
13975 const int day,
13976 const int hour,
13977 const int min,
13978 const int sec,
13979 const double remain,
13980 double *jsec) {
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}
14000
14001/*****************************************************************************/
14002
14004 const char *name,
14005 const char *group,
14006 const int output) {
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}
14068
14069/*****************************************************************************/
14070
14072 const char *filename,
14073 const int offset,
14074 const int with_seconds) {
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}
14110
14111/*****************************************************************************/
14112
14114 const ctl_t *ctl,
14115 const clim_t *clim,
14116 const atm_t *atm,
14117 const int ip) {
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}
14136
14137/*****************************************************************************/
14138
14140 const char *filename,
14141 const ctl_t *ctl,
14142 const atm_t *atm,
14143 const double t) {
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}
14234
14235/*****************************************************************************/
14236
14238 const char *filename,
14239 const ctl_t *ctl,
14240 const atm_t *atm) {
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}
14284
14285/*****************************************************************************/
14286
14288 const char *filename,
14289 const ctl_t *ctl,
14290 const atm_t *atm) {
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}
14342
14343/*****************************************************************************/
14344
14346 const char *dirname,
14347 const ctl_t *ctl,
14348 const atm_t *atm,
14349 const double t) {
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}
14510
14511/*****************************************************************************/
14512
14514 const char *filename,
14515 const ctl_t *ctl,
14516 const atm_t *atm) {
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}
14559
14560/*****************************************************************************/
14561
14563 const char *filename,
14564 const ctl_t *ctl,
14565 const atm_t *atm,
14566 const double t) {
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}
14655
14656/*****************************************************************************/
14657
14659 const char *filename,
14660 const ctl_t *ctl,
14661 const atm_t *atm,
14662 const double t) {
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}
14949
14950/*****************************************************************************/
14951
14953 const char *filename,
14954 const ctl_t *ctl,
14955 const atm_t *atm,
14956 const double t) {
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}
15054
15055/*****************************************************************************/
15056
15058 const char *filename,
15059 const ctl_t *ctl,
15060 const depo_t *depo,
15061 const double t) {
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}
15125
15126/*****************************************************************************/
15127
15129 const char *filename,
15130 const ctl_t *ctl,
15131 const double *data,
15132 const double t,
15133 const double *lon,
15134 const double *lat,
15135 const double *area) {
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}
15165
15166/*****************************************************************************/
15167
15169 const char *filename,
15170 const ctl_t *ctl,
15171 const double *data,
15172 const double t,
15173 const double *lon,
15174 const double *lat,
15175 const double *area) {
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}
15231
15232/*****************************************************************************/
15233
15235 const char *filename,
15236 const ctl_t *ctl,
15237 met_t *met0,
15238 met_t *met1,
15239 const atm_t *atm,
15240 const double t) {
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}
15438
15439/*****************************************************************************/
15440
15442 const char *filename,
15443 const ctl_t *ctl,
15444 const double *cd,
15445 double *mean[NQ],
15446 double *sigma[NQ],
15447 const double *vmr_impl,
15448 const double t,
15449 const double *z,
15450 const double *lon,
15451 const double *lat,
15452 const double *area,
15453 const double dz,
15454 const int *np) {
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}
15542
15543/*****************************************************************************/
15544
15546 const char *filename,
15547 const ctl_t *ctl,
15548 const double *cd,
15549 double *mean[NQ],
15550 double *sigma[NQ],
15551 const double *vmr_impl,
15552 const double t,
15553 const double *z,
15554 const double *lon,
15555 const double *lat,
15556 const double *area,
15557 const double dz,
15558 const int *np) {
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}
15673
15674/*****************************************************************************/
15675
15677 const char *filename,
15678 const ctl_t *ctl,
15679 met_t *met) {
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}
15803
15804/*****************************************************************************/
15805
15807 FILE *out,
15808 met_t *met,
15809 float var[EX][EY],
15810 const char *varname) {
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}
15832
15833/*****************************************************************************/
15834
15836 FILE *out,
15837 const ctl_t *ctl,
15838 met_t *met,
15839 float var[EX][EY][EP],
15840 const char *varname,
15841 const int metvar,
15842 FILE *level_log) {
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}
15925
15926/*****************************************************************************/
15927
15929 const char *filename,
15930 const ctl_t *ctl,
15931 met_t *met) {
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}
16107
16108/*****************************************************************************/
16109
16111 const int ncid,
16112 const char *varname,
16113 met_t *met,
16114 float var[EX][EY],
16115 const float scl) {
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}
16137
16138/*****************************************************************************/
16139
16141 const int ncid,
16142 const char *varname,
16143 met_t *met,
16144 float var[EX][EY][EP],
16145 const float scl) {
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}
16168
16169/*****************************************************************************/
16170
16172 const char *filename,
16173 const ctl_t *ctl,
16174 met_t *met0,
16175 met_t *met1,
16176 const atm_t *atm,
16177 const double t) {
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}
16393
16394/*****************************************************************************/
16395
16397 const char *filename,
16398 const ctl_t *ctl,
16399 met_t *met0,
16400 met_t *met1,
16401 const atm_t *atm,
16402 const double t) {
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}
16564
16565/*****************************************************************************/
16566
16568 const char *filename,
16569 const ctl_t *ctl,
16570 atm_t *atm,
16571 const double t) {
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}
16670
16671/*****************************************************************************/
16672
16674 const char *filename,
16675 const ctl_t *ctl,
16676 const atm_t *atm,
16677 const double t) {
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}
void read_met_geopot(const ctl_t *ctl, met_t *met)
Calculates geopotential heights from meteorological data.
Definition mptrac.c:10527
void dd_init(const ctl_t *ctl, dd_t *dd, atm_t *atm)
Initialize the domain decomposition infrastructure.
Definition mptrac.c:2343
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 day2doy(const int year, const int mon, const int day, int *doy)
Get day of year from date.
Definition mptrac.c:1902
void read_met_extrapolate(met_t *met)
Extrapolates meteorological data.
Definition mptrac.c:10487
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_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 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 read_met_sample(const ctl_t *ctl, met_t *met)
Downsamples meteorological data based on specified parameters.
Definition mptrac.c:13317
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
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 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 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
void read_met_cloud(met_t *met)
Calculates cloud-related variables for each grid point.
Definition mptrac.c:10323
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
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 cos_sza(const double sec, const double lon, const double lat)
Calculates the cosine of the solar zenith angle.
Definition mptrac.c:1861
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
float * global
Definition mptrac.c:11232
size_t local_elements
Definition mptrac.c:11233
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.
Definition mptrac.c:769
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
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_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 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 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 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
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
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 read_met_monotonize(const ctl_t *ctl, met_t *met)
Makes zeta and pressure profiles monotone.
Definition mptrac.c:12570
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 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 read_met_periodic(met_t *met)
Applies periodic boundary conditions to meteorological data along longitudinal axis.
Definition mptrac.c:13045
int compress_metvar_index(const char *varname)
Maps a meteorological variable name to its internal MPTRAC variable index.
Definition mptrac.c:973
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 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 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
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
int size
Definition mptrac.c:11234
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
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
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
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
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
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
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.
Definition mptrac.c:6956
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 level_definitions(ctl_t *ctl)
Defines pressure levels for meteorological data.
Definition mptrac.c:3686
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 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 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
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.
Definition mptrac.c:9216
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
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 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
void fft_help(double *fcReal, double *fcImag, const int n)
Computes the Fast Fourier Transform (FFT) of a complex sequence.
Definition mptrac.c:2892
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
float * packed
Definition mptrac.c:11232
int compress_read_lossy_scale(FILE *in, const size_t nz, double **off, double **scl)
Read optional lossyscaling metadata for a 3-D field.
Definition mptrac.c:878
double nat_temperature(const double p, const double h2o, const double hno3)
Calculates the nitric acid trihydrate (NAT) temperature.
Definition mptrac.c:9341
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
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
float * local
Definition mptrac.c:11232
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
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
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 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
int rank
Definition mptrac.c:11234
void timer(const char *name, const char *group, const int output)
Measures and reports elapsed time for named and grouped timers.
Definition mptrac.c:14003
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 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
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 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 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 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
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
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
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
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
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 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.
Definition mptrac.c:7034
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
float stddev(const float *data, const int n)
Calculates the standard deviation of a set of data.
Definition mptrac.c:13949
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).
Definition mptrac.c:3505
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
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
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
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 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_read_clim(const ctl_t *ctl, clim_t *clim)
Reads various climatological data and populates the given climatology structure.
Definition mptrac.c:7277
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 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 module_rng_init(const int ntask)
Initialize random number generators for parallel tasks.
Definition mptrac.c:6300
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.
Definition mptrac.c:7168
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.
Definition mptrac.c:7202
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
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
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 read_met_ozone(met_t *met)
Calculates the total column ozone from meteorological ozone data.
Definition mptrac.c:13288
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 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.
Definition mptrac.c:6866
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 broadcast_large_data(void *data, size_t N)
State variables of cuRAND random number generator.
Definition mptrac.c:47
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.
Definition mptrac.c:913
size_t packed_elements
Definition mptrac.c:11233
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 clim_tropo_init(clim_t *clim)
Initializes the tropopause data in the climatology structure.
Definition mptrac.c:245
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
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 cart2geo(const double *x, double *z, double *lon, double *lat)
Converts Cartesian coordinates to geographic coordinates.
Definition mptrac.c:76
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
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 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 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 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).
Definition mptrac.c:2862
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
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
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
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
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 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
void read_met_pv(met_t *met)
Calculates potential vorticity (PV) from meteorological data.
Definition mptrac.c:13169
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
size_t global_elements
Definition mptrac.c:11233
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
double clim_ts(const clim_ts_t *ts, const double t)
Interpolates a time series of climatological variables.
Definition mptrac.c:400
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
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 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 sort_uvwp(cache_t *cache, const int *perm, double *tmp, const int np)
Reorder particle-specific wind perturbations.
Definition mptrac.c:2544
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
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
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
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
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
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
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.
Definition mptrac.c:8832
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 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 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.
Definition mptrac.c:7351
unsigned long long * geometry
Definition mptrac.c:11231
void read_met_polar_winds(met_t *met)
Applies a fix for polar winds in meteorological data.
Definition mptrac.c:13107
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 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
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
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 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
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 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
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
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.
Definition mptrac.c:3042
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
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 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 CHUNK_SIZE
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.
Definition mptrac.c:858
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
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
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
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 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 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
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 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
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.
Definition mptrac.c:9167
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
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 lapse_rate(const double t, const double h2o)
Calculates the moist adiabatic lapse rate in Kelvin per kilometer.
Definition mptrac.c:3668
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 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
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
MPTRAC library declarations.
#define NN(x0, y0, x1, y1, x)
Perform nearest-neighbor interpolation.
Definition mptrac.h:1786
#define LEN
Maximum length of ASCII data lines.
Definition mptrac.h:559
#define RE
Mean radius of Earth [km].
Definition mptrac.h:315
#define TVIRT(t, h2o)
Compute virtual temperature.
Definition mptrac.h:2259
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...
#define ARRAY_3D(ix, iy, ny, iz, nz)
Compute the linear index of a 3D array element.
Definition mptrac.h:711
#define SO2_DISS_K2_TEMP
Temperature dependence of the second SO2 dissociation constant [K].
Definition mptrac.h:445
#define PARTICLE_LOOP(ip0, ip1, check_dt,...)
Loop over particle indices with OpenACC acceleration.
Definition mptrac.h:1813
#define MA
Molar mass of dry air [g/mol].
Definition mptrac.h:290
#define RADIO_HALF_LIFE_CS137
Half-life of Cs-137 [s].
Definition mptrac.h:480
#define P0
Standard pressure [hPa].
Definition mptrac.h:305
#define AVO
Avogadro constant [1/mol].
Definition mptrac.h:250
#define KB
Boltzmann constant [kg m^2/(K s^2)].
Definition mptrac.h:285
#define SO2_CORR_B
Exponent of the high-SO2 correction [1].
Definition mptrac.h:385
#define COMPRESS_BPV(n, stored_size)
Calculate bits per value from stored size and element count.
Definition mptrac.h:797
#define MH2O
Molar mass of water vapor [g/mol].
Definition mptrac.h:295
#define METVAR
Number of 3-D meteorological variables.
Definition mptrac.h:564
#define NENS
Maximum number of data points for ensemble analysis.
Definition mptrac.h:584
#define FWRITE(ptr, type, size, out)
Write data from memory to a file stream.
Definition mptrac.h:1204
#define PW(p, h2o)
Calculate partial water vapor pressure.
Definition mptrac.h:1918
#define H0
Scale height [km].
Definition mptrac.h:270
#define NC_PUT_ATT_GLOBAL(attname, text)
Add a global text attribute to a NetCDF file.
Definition mptrac.h:1765
#define MOLEC_DENS(p, t)
Calculate the molecular number density of air.
Definition mptrac.h:1541
#define LAPSE(p1, t1, p2, t2)
Calculate lapse rate.
Definition mptrac.h:1379
#define NC(cmd)
Execute a NetCDF command and check for errors.
Definition mptrac.h:1555
#define RADIO_DRY_VDEP_I131
Dry deposition velocity of aerosol-bound I-131 [m/s].
Definition mptrac.h:510
#define SELECT_TIMER(id, group)
Select and start a timer with specific attributes.
Definition mptrac.h:2542
#define RADIO_DRY_VDEP_CS137
Dry deposition velocity of Cs-137 [m/s].
Definition mptrac.h:505
#define SO2_DISS_K1_REF
First SO2 dissociation constant at CHEM_REF_TEMP [mol/L].
Definition mptrac.h:430
#define ECC_READ_3D(variable, level, target, scaling_factor, found_flag)
Writes 3D data from a grib message into the meteo struct.
Definition mptrac.h:1096
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.
#define SO2_DISS_K1_TEMP
Temperature dependence of the first SO2 dissociation constant [K].
Definition mptrac.h:435
#define DOTP(a, b)
Calculate the dot product of two vectors.
Definition mptrac.h:1038
#define RA
Specific gas constant of dry air [J/(kg K)].
Definition mptrac.h:310
#define DD_EY_GLOB
Maximum number of latitudes of global meteo data.
Definition mptrac.h:634
#define KARMAN
Karman's constant.
Definition mptrac.h:280
#define INTPOL_INIT
Initialize arrays for interpolation.
Definition mptrac.h:1219
#define MIN(a, b)
Macro to determine the minimum of two values.
Definition mptrac.h:1527
#define O1D_RATE_CFC12_B
O(1D) reaction temperature parameter for CFC-12 [K].
Definition mptrac.h:415
#define ERRMSG(...)
Print an error message with contextual information and terminate the program.
Definition mptrac.h:2466
#define NC_PUT_INT(varname, ptr, hyperslab)
Write integer data to a NetCDF variable.
Definition mptrac.h:1726
#define O1D_RATE_N2O_A
O(1D) parent-destruction pre-factor for N2O [cm^3 molecule^-1 s^-1].
Definition mptrac.h:420
#define EY
Maximum number of latitudes for meteo data.
Definition mptrac.h:554
#define RADIO_DRY_VDEP_PB210
Dry deposition velocity of Pb-210 [m/s].
Definition mptrac.h:495
#define SH(h2o)
Compute specific humidity from water vapor volume mixing ratio.
Definition mptrac.h:2084
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.
#define H2O2_HENRY_TEMP
Temperature dependence of the H2O2 Henry constant [K].
Definition mptrac.h:375
#define INTPOL_3D(var, init)
Perform 3D interpolation for a meteorological variable.
Definition mptrac.h:1251
#define CLAMP(v, lo, hi)
Clamp a value to a specified range.
Definition mptrac.h:758
#define M_AIR_MOLECULE
Mean mass of an air molecule [kg].
Definition mptrac.h:340
#define NOBS
Maximum number of observation data points.
Definition mptrac.h:589
#define NTHREADS
Maximum number of OpenMP threads.
Definition mptrac.h:594
#define ARRAY_2D(ix, iy, ny)
Macro for computing the linear index of a 2D array element.
Definition mptrac.h:692
#define Z(p)
Convert pressure to altitude.
Definition mptrac.h:2303
#define codes_handle
Placeholder when ECCODES is not available.
Definition mptrac.h:241
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.
#define SO2_CORR_A
Scale factor of the high-SO2 correction for fractional SO2 mole fraction.
Definition mptrac.h:380
#define P(z)
Compute pressure at given altitude.
Definition mptrac.h:1843
#define LV
Latent heat of vaporization of water [J/kg].
Definition mptrac.h:275
#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 G0
Standard gravity [m/s^2].
Definition mptrac.h:265
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.
#define CP
Maximum number of pressure levels for climatological data.
Definition mptrac.h:609
#define NQ
Maximum number of quantities per data point.
Definition mptrac.h:574
#define FREAD(ptr, type, size, in)
Read data from a file stream and store it in memory.
Definition mptrac.h:1184
#define H2O2_SO2_RATE_REF
Reference rate for aqueous H2O2-SO2 chemistry [L^2/(mol^2 s)].
Definition mptrac.h:350
#define DX2DEG(dx, lat)
Convert a distance in kilometers to degrees longitude at a given latitude.
Definition mptrac.h:906
#define DEG2DY(dlat)
Convert a latitude difference to a distance in the y-direction (north-south).
Definition mptrac.h:842
#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 EX
Maximum number of longitudes for meteo data.
Definition mptrac.h:549
#define EPS
Ratio of the specific gas constant of dry air and water vapor [1].
Definition mptrac.h:260
#define PSICE(t)
Compute saturation pressure over ice (WMO, 2018).
Definition mptrac.h:1891
#define O1D_RATE_N2O_B
O(1D) reaction temperature parameter for N2O [K].
Definition mptrac.h:425
#define DX2COORD(met, dx, lat)
Convert a distance in meters to a coordinate value based on grid type.
Definition mptrac.h:968
#define O1D_RATE_CCL4_B
O(1D) reaction temperature parameter for CCl4 [K].
Definition mptrac.h:395
#define COMPRESS_RATIO(raw_size, stored_size)
Calculate the compression ratio from raw and stored byte counts.
Definition mptrac.h:785
#define WET_DEPO_T_ICE
Lower temperature of the ice-cloud retention transition [K].
Definition mptrac.h:455
#define THETA(p, t)
Compute potential temperature.
Definition mptrac.h:2184
#define RI
Ideal gas constant [J/(mol K)].
Definition mptrac.h:320
int read_met_grib(const char *filename, const ctl_t *ctl, met_t *met)
Reads meteorological data from a grib file and processes it.
#define RADIO_WET_COEFF_BE7
Wet deposition coefficient of Be-7 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:520
#define SET_QNT(qnt, name, longname, unit)
Set atmospheric quantity index.
Definition mptrac.h:2063
#define TICE(p, h2o)
Calculate frost point temperature (WMO, 2018).
Definition mptrac.h:2160
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.
#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 RADIO_WET_COEFF_CS137
Wet deposition coefficient of Cs-137 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:525
#define TOK(line, tok, format, var)
Get string tokens.
Definition mptrac.h:2234
#define ZDIFF(lnp0, t0, h2o0, lnp1, t1, h2o1)
Calculate geopotential height difference.
Definition mptrac.h:2334
#define THETAVIRT(p, t, h2o)
Compute virtual potential temperature.
Definition mptrac.h:2213
#define DZ2DP(dz, p)
Convert a change in altitude to a change in pressure.
Definition mptrac.h:943
#define WARN(...)
Print a warning message with contextual information.
Definition mptrac.h:2433
#define H2O2_SO2_RATE_TEMP
Temperature parameter for the aqueous H2O2-SO2 rate [K].
Definition mptrac.h:355
#define ZETA(ps, p, t)
Computes the value of the zeta vertical coordinate.
Definition mptrac.h:2353
#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 OBS_TIME_WINDOW(ctl, t, t0, t1)
Set the half-open observation window for a model output time.
Definition mptrac.h:1150
#define ALLOC(ptr, type, n)
Allocate memory for a pointer with error handling.
Definition mptrac.h:668
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.
#define SET_ATM(qnt, val)
Set atmospheric quantity value.
Definition mptrac.h:2039
#define O1D_RATE_CCL4_A
O(1D) parent-destruction pre-factor for CCl4 [cm^3 molecule^-1 s^-1].
Definition mptrac.h:390
#define CTS
Maximum number of data points of climatological time series.
Definition mptrac.h:624
#define ECC_READ_2D(variable, target, scaling_factor, found_flag)
Writes 2-D data from a grib message into the meteo struct.
Definition mptrac.h:1071
#define OMEGA_EARTH
Angular velocity of Earth [s^-1].
Definition mptrac.h:330
#define DEG2RAD(deg)
Converts degrees to radians.
Definition mptrac.h:859
#define MO3
Molar mass of ozone [g/mol].
Definition mptrac.h:300
#define SQR(x)
Compute the square of a value.
Definition mptrac.h:2097
#define RADIO_WET_COEFF_I131
Wet deposition coefficient of aerosol-bound I-131 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:530
#define RAD2DEG(rad)
Converts radians to degrees.
Definition mptrac.h:1935
#define RADIO_DRY_VDEP_BE7
Dry deposition velocity of Be-7 [m/s].
Definition mptrac.h:500
#define NP
Maximum number of atmospheric data points.
Definition mptrac.h:569
#define NTIMER
Maximum number of timers.
Definition mptrac.h:2511
#define COMPRESS_SPEED(nbytes, dt)
Calculate compression throughput in MiB/s.
Definition mptrac.h:773
#define INTPOL_2D(var, init)
Perform 2D interpolation for a meteorological variable.
Definition mptrac.h:1233
#define RH(p, t, h2o)
Compute relative humidity over water.
Definition mptrac.h:1965
#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 NC_PUT_FLOAT(varname, ptr, hyperslab)
Write a float array to a NetCDF file.
Definition mptrac.h:1703
#define DD_EX_GLOB
Maximum number of longitudes of global meteo data.
Definition mptrac.h:629
#define CY
Maximum number of latitudes for climatological data.
Definition mptrac.h:599
#define DT_ALIGNED(dt, dt_mod)
Definition mptrac.h:1127
#define LOG(level,...)
Print a log message with a specified logging level.
Definition mptrac.h:2396
#define RADIO_HALF_LIFE_RN222
Half-life of Rn-222 [s].
Definition mptrac.h:465
#define NC_DEF_VAR(varname, type, ndims, dims, long_name, units, level, quant)
Define a NetCDF variable with attributes.
Definition mptrac.h:1584
#define TDEW(p, h2o)
Calculate dew point temperature.
Definition mptrac.h:2135
#define KAPPA
Exponent used for potential-temperature calculations [1].
Definition mptrac.h:325
#define ARRHENIUS(a, b, t)
Calculate the Arrhenius rate constant.
Definition mptrac.h:736
#define NCSI
Maximum number of data points for CSI calculation.
Definition mptrac.h:579
#define NC_GET_DOUBLE(varname, ptr, force)
Retrieve a double-precision variable from a NetCDF file.
Definition mptrac.h:1625
#define EP
Maximum number of pressure levels for meteo data.
Definition mptrac.h:544
#define PSAT(t)
Compute saturation pressure over water.
Definition mptrac.h:1867
#define SO2_DISS_K2_REF
Second SO2 dissociation constant at CHEM_REF_TEMP [mol/L].
Definition mptrac.h:440
#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
#define RHO(p, t)
Compute density of air.
Definition mptrac.h:2020
#define RADIO_HALF_LIFE_PB210
Half-life of Pb-210 [s].
Definition mptrac.h:470
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.
#define CO3
Maximum number of total column ozone data for climatological data.
Definition mptrac.h:604
void read_met_grib_grid(codes_handle **handles, int count_handles, met_t *met)
Reads global meteorological information from a grib file.
#define NC_PUT_DOUBLE(varname, ptr, hyperslab)
Write double precision data to a NetCDF variable.
Definition mptrac.h:1679
#define ECC(cmd)
Execute an ECCODES command and check for errors.
Definition mptrac.h:1052
#define LIN(x0, y0, x1, y1, x)
Linear interpolation.
Definition mptrac.h:1398
#define WET_DEPO_T_LIQUID
Upper temperature of the ice-cloud retention transition [K].
Definition mptrac.h:450
#define DIST2(a, b)
Calculate the squared Euclidean distance between two points in Cartesian coordinates.
Definition mptrac.h:1022
#define NC_INQ_DIM(dimname, ptr, min, max, check)
Inquire the length of a dimension in a NetCDF file.
Definition mptrac.h:1655
#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
#define DY2COORD(met, dy)
Convert a distance to coordinate value based on grid type.
Definition mptrac.h:991
#define CPD
Specific heat of dry air at constant pressure [J/(kg K)].
Definition mptrac.h:255
#define CSZA
Maximum number of solar zenith angles for climatological data.
Definition mptrac.h:614
#define DY2DEG(dy)
Convert a distance in kilometers to degrees latitude.
Definition mptrac.h:924
#define O1D_RATE_CFC11_B
O(1D) reaction temperature parameter for CFC-11 [K].
Definition mptrac.h:405
#define MAX(a, b)
Macro to determine the maximum of two values.
Definition mptrac.h:1425
#define WET_DEPO_T_LIQUID_BC
Temperature threshold for below-cloud retention [K].
Definition mptrac.h:460
#define RADIO_HALF_LIFE_XE133
Half-life of Xe-133 [s].
Definition mptrac.h:490
#define RADIO_WET_COEFF_PB210
Wet deposition coefficient of Pb-210 [s^-1 (mm h^-1)^-1].
Definition mptrac.h:515
#define FMOD(x, y)
Calculate the floating-point remainder of dividing x by y.
Definition mptrac.h:1123
#define DOBSON_UNIT
Ozone column mass corresponding to one Dobson unit [kg/m^2].
Definition mptrac.h:335
Air parcel data.
Definition mptrac.h:3662
double time[NP]
Time [s].
Definition mptrac.h:3668
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
double p[NP]
Pressure [hPa].
Definition mptrac.h:3671
Cache data structure.
Definition mptrac.h:3726
double dt[NP]
Timesteps [s].
Definition mptrac.h:3747
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
double rs[3 *NP+1]
Random numbers.
Definition mptrac.h:3744
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
Climatological data in the form of photolysis rates.
Definition mptrac.h:3785
int nsza
Number of solar zenith angles.
Definition mptrac.h:3791
double sza[CSZA]
Solar zenith angle [rad].
Definition mptrac.h:3800
double o3_1[CP][CSZA][CO3]
O3 photolysis rate (O3 + hv = O1d + O2) [1/s].
Definition mptrac.h:3821
double p[CP]
Pressure [hPa].
Definition mptrac.h:3797
double ccl2f2[CP][CSZA][CO3]
CCl2F2 photolysis rate [1/s].
Definition mptrac.h:3815
double o2[CP][CSZA][CO3]
O2 photolysis rate [1/s].
Definition mptrac.h:3818
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 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 ccl4[CP][CSZA][CO3]
CCl4 photolysis rate [1/s].
Definition mptrac.h:3809
double o3_2[CP][CSZA][CO3]
O3 photolysis rate (O3 + hv = O3p + O2) [1/s].
Definition mptrac.h:3824
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
Climatological data.
Definition mptrac.h:3893
clim_ts_t ccl2f2
CFC-12 time series.
Definition mptrac.h:3935
clim_photo_t photo
Photolysis rates.
Definition mptrac.h:3911
clim_zm_t ho2
HO2 zonal means.
Definition mptrac.h:3923
clim_zm_t hno3
HNO3 zonal means.
Definition mptrac.h:3914
int tropo_ntime
Number of tropopause timesteps.
Definition mptrac.h:3896
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_zm_t o1d
O(1D) zonal means.
Definition mptrac.h:3926
double tropo_lat[73]
Tropopause latitudes [deg].
Definition mptrac.h:3905
clim_zm_t h2o2
H2O2 zonal means.
Definition mptrac.h:3920
int tropo_nlat
Number of tropopause latitudes.
Definition mptrac.h:3899
clim_zm_t oh
OH zonal means.
Definition mptrac.h:3917
double tropo[12][73]
Tropopause pressure values [hPa].
Definition mptrac.h:3908
double tropo_time[12]
Tropopause time steps [s].
Definition mptrac.h:3902
clim_ts_t n2o
N2O time series.
Definition mptrac.h:3938
Climatological data in the form of time series.
Definition mptrac.h:3841
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
Climatological data in the form of zonal means.
Definition mptrac.h:3861
double time[CT]
Time [s].
Definition mptrac.h:3873
int np
Number of pressure levels.
Definition mptrac.h:3870
double p[CP]
Pressure [hPa].
Definition mptrac.h:3879
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
Control parameters.
Definition mptrac.h:2557
double met_utm_ref_lon
Reference longitude [deg] for UTM grid.
Definition mptrac.h:2923
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 qnt_Coh
Quantity array index for OH volume mixing ratio (chemistry code).
Definition mptrac.h:2831
double wet_depo_ic_a
Coefficient A for wet deposition in cloud (exponential form).
Definition mptrac.h:3340
int qnt_eta_d
Quantity array index for diagnosed eta vertical coordinate.
Definition mptrac.h:2786
int qnt_target_subdomain
Quantity array index for destination subdomain in domain decomposition.
Definition mptrac.h:2889
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
double molmass
Molar mass [g/mol].
Definition mptrac.h:3196
int qnt_p
Quantity array index for pressure.
Definition mptrac.h:2648
double dry_depo_dz
Geometric dry-deposition layer thickness above the surface [m].
Definition mptrac.h:3364
int qnt_Cccl2f2
Quantity array index for CFC-12 volume mixing ratio (chemistry code).
Definition mptrac.h:2855
int dd_halos_size
Domain decomposition halo size in grid points.
Definition mptrac.h:3639
char atm_gpfile[LEN]
Gnuplot file for atmospheric data.
Definition mptrac.h:3392
int mixing_nx
Number of longitudes of mixing grid.
Definition mptrac.h:3259
int met_zstd_nworkers
ZSTD number of worker threads (0=single-threaded, default=4).
Definition mptrac.h:2955
double chemgrid_z1
Upper altitude of chemistry grid [km].
Definition mptrac.h:3283
char qnt_format[NQ][LEN]
Quantity output format.
Definition mptrac.h:2576
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
int qnt_rhop
Quantity array index for particle density.
Definition mptrac.h:2597
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
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
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 mixing_z1
Upper altitude of mixing grid [km].
Definition mptrac.h:3256
double stat_r
Search radius around station [km].
Definition mptrac.h:3593
double wet_depo_bc_a
Coefficient A for wet deposition below cloud (exponential form).
Definition mptrac.h:3334
int met_zstd_level
ZSTD compression level (from -5 to 22, default=-3).
Definition mptrac.h:2952
double met_utm_ref_lat
Reference latitude [deg] for UTM grid.
Definition mptrac.h:2920
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 chemgrid_z0
Lower altitude of chemistry grid [km].
Definition mptrac.h:3280
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
double chemgrid_lat0
Lower latitude of chemistry grid [deg].
Definition mptrac.h:3298
double conv_cape
CAPE threshold for convection module [J/kg].
Definition mptrac.h:3148
int qnt_Co1d
Quantity array index for O(1D) volume mixing ratio (chemistry code).
Definition mptrac.h:2843
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 direction
Direction flag (1=forward calculation, -1=backward calculation).
Definition mptrac.h:2892
char balloon[LEN]
Balloon position filename.
Definition mptrac.h:3093
int qnt_Cccl4
Quantity array index for CFC-10 volume mixing ratio (chemistry code).
Definition mptrac.h:2849
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
char species[LEN]
Species.
Definition mptrac.h:3193
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
double turb_dz_trop
Vertical turbulent diffusion coefficient (troposphere) [m^2/s].
Definition mptrac.h:3127
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
double turb_mesoz
Vertical scaling factor for mesoscale wind fluctuations.
Definition mptrac.h:3136
int grid_nc_level
zlib compression level of netCDF grid data files (0=off).
Definition mptrac.h:3497
int grid_nx
Number of longitudes of gridded data.
Definition mptrac.h:3515
int atm_type
Type of atmospheric data files (0=ASCII, 1=binary, 2=netCDF, 3=CLaMS_traj, 4=CLaMS_pos).
Definition mptrac.h:3405
double bound_mass
Boundary conditions mass per particle [kg].
Definition mptrac.h:3157
double grid_lat0
Lower latitude of gridded data [deg].
Definition mptrac.h:3527
int qnt_ts
Quantity array index for surface temperature.
Definition mptrac.h:2603
int qnt_loss_rate
Quantity array index for total loss rate.
Definition mptrac.h:2747
int qnt_plfc
Quantity array index for pressure at level of free convection (LCF).
Definition mptrac.h:2699
int qnt_Acs137
Quantity array index for radioactive activity of Cs-137.
Definition mptrac.h:2877
double grid_lon0
Lower longitude of gridded data [deg].
Definition mptrac.h:3518
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
double dt_met
Time step of meteo data [s].
Definition mptrac.h:2911
char clim_ho2_filename[LEN]
Filename of HO2 climatology.
Definition mptrac.h:3217
double chemgrid_lat1
Upper latitude of chemistry grid [deg].
Definition mptrac.h:3301
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
double turb_dx_strat
Horizontal turbulent diffusion coefficient (stratosphere) [m^2/s].
Definition mptrac.h:3121
int qnt_vmr
Quantity array index for volume mixing ratio.
Definition mptrac.h:2591
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 bound_lat1
Boundary conditions maximum longitude [deg].
Definition mptrac.h:3172
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
double turb_dx_trop
Horizontal turbulent diffusion coefficient (troposphere) [m^2/s].
Definition mptrac.h:3118
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
double oh_chem[4]
Coefficients for OH reaction rate (A, E/R or k0, n, kinf, m).
Definition mptrac.h:3307
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
double chemgrid_lon0
Lower longitude of chemistry grid [deg].
Definition mptrac.h:3289
int bound_pbl
Boundary conditions planetary boundary layer (0=no, 1=yes).
Definition mptrac.h:3190
double dt_pbl
Maximum internal Hanna-PBL timestep [s] (default: 2 s).
Definition mptrac.h:3112
int qnt_mloss_wet
Quantity array index for total mass loss due to wet deposition.
Definition mptrac.h:2738
int radio_decay
RADIO_DECAY switch for airborne and deposited activity (0=off, 1=on, default: 0).
Definition mptrac.h:3325
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
int rng_type
Random number generator (0=GSL, 1=Squares, 2=cuRAND).
Definition mptrac.h:3103
char prof_obsfile[LEN]
Observation data file for profile output.
Definition mptrac.h:3539
int met_pck_zstd
Apply an additional ZSTD compression step to PCK payloads (0=off, 1=on).
Definition mptrac.h:2961
int isosurf
Isosurface parameter (0=none, 1=pressure, 2=density, 3=theta, 4=balloon).
Definition mptrac.h:3090
double bound_p1
Boundary conditions top pressure [hPa].
Definition mptrac.h:3178
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 chemgrid_lon1
Upper longitude of chemistry grid [deg].
Definition mptrac.h:3292
double depo_dt_out
DEPO_DT_OUT time interval for radioactive deposition output [s] (default: 86400).
Definition mptrac.h:3383
double turb_mesox
Horizontal scaling factor for mesoscale wind fluctuations.
Definition mptrac.h:3133
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 bound_vmr
Boundary conditions volume mixing ratio [ppv].
Definition mptrac.h:3163
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
double dd_sort_dt
Sorting time interval for the compactification (DD_EXCHANGE_MODE=0).
Definition mptrac.h:3642
int met_tropo
Tropopause definition (0=none, 1=clim, 2=cold point, 3=WMO_1st, 4=WMO_2nd, 5=dynamical).
Definition mptrac.h:3061
int qnt_rp
Quantity array index for particle radius.
Definition mptrac.h:2594
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
double oh_chem_beta
Beta parameter for diurnal variability of OH.
Definition mptrac.h:3310
int dd
Domain decomposition (0=no, 1=yes).
Definition mptrac.h:3627
char clim_o1d_filename[LEN]
Filename of O(1D) climatology.
Definition mptrac.h:3220
int qnt_eta
Quantity array index for eta vertical coordinate.
Definition mptrac.h:2783
char clim_photo[LEN]
Filename of photolysis rates climatology.
Definition mptrac.h:3205
double wet_depo_so2_ph
pH value used to calculate effective Henry constant of SO2.
Definition mptrac.h:3352
double mixing_z0
Lower altitude of mixing grid [km].
Definition mptrac.h:3253
int qnt_mloss_decay
Quantity array index for total mass loss due to exponential decay.
Definition mptrac.h:2744
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
int qnt_Cco
Quantity array index for CO volume mixing ratio (chemistry code).
Definition mptrac.h:2828
double vtk_dt_out
Time step for VTK data output [s].
Definition mptrac.h:3605
double t_stop
Stop time of simulation [s].
Definition mptrac.h:2898
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
int met_clams
Read MPTRAC or CLaMS meteo data (0=MPTRAC, 1=CLaMS).
Definition mptrac.h:2937
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 bound_lat0
Boundary conditions minimum longitude [deg].
Definition mptrac.h:3169
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 mixing_ny
Number of latitudes of mixing grid.
Definition mptrac.h:3268
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
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
double dt_mod
Time step of simulation [s].
Definition mptrac.h:2901
int diffusion
Diffusion switch (0=off, 1=on).
Definition mptrac.h:3106
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 turb_pbl_scheme
PBL turbulence scheme (0=none, 1=closure).
Definition mptrac.h:3109
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
int qnt_mloss_dry
Quantity array index for total mass loss due to dry deposition.
Definition mptrac.h:2741
double bound_vmr_trend
Boundary conditions volume mixing ratio trend [ppv/s].
Definition mptrac.h:3166
double met_zfp_tol[METVAR]
ZFP compression tolerance.
Definition mptrac.h:2967
int met_cache
Preload meteo data into disk cache (0=no, 1=yes).
Definition mptrac.h:3076
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
char qnt_unit[NQ][LEN]
Quantity units.
Definition mptrac.h:2573
int qnt_Ch
Quantity array index for H volume mixing ratio (chemistry code).
Definition mptrac.h:2834
int met_press_level_def
Use predefined pressure levels or not.
Definition mptrac.h:3027
int oh_chem_reaction
OH reaction type (0=off, 1=constant, 2=bimolecular, 3=termolecular).
Definition mptrac.h:3304
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
double tdec_strat
Life time of particles in the stratosphere [s].
Definition mptrac.h:3202
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
double grid_lon1
Upper longitude of gridded data [deg].
Definition mptrac.h:3521
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
char qnt_name[NQ][LEN]
Quantity names.
Definition mptrac.h:2567
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
double mixing_lat0
Lower latitude of mixing grid [deg].
Definition mptrac.h:3271
int nens
Number of ensembles.
Definition mptrac.h:3473
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
int advect
Advection scheme (1=Euler, 2=midpoint).
Definition mptrac.h:3096
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 qnt_zeta
Quantity array index for zeta vertical coordinate.
Definition mptrac.h:2774
double conv_pbl_trans
Depth of PBL transition layer (fraction of PBL pressure thickness).
Definition mptrac.h:3145
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 qnt_Ai131
Quantity array index for radioactive activity of I-131.
Definition mptrac.h:2880
double wet_depo_pre[2]
Positive coefficients for the column-condensate precipitation proxy.
Definition mptrac.h:3331
double mixing_tau_trop
E-folding time for interparcel mixing in the troposphere [s].
Definition mptrac.h:3244
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
int qnt_Apb210
Quantity array index for radioactive activity of Pb-210.
Definition mptrac.h:2871
double stat_lat
Latitude of station [deg].
Definition mptrac.h:3590
int qnt_Cho2
Quantity array index for HO2 volume mixing ratio (chemistry code).
Definition mptrac.h:2837
double wet_depo_bc_h[2]
Below-cloud Henry coefficients (reference solubility, temperature coefficient).
Definition mptrac.h:3349
int grid_ny
Number of latitudes of gridded data.
Definition mptrac.h:3524
int qnt_Csf6
Quantity array index for SF6 volume mixing ratio (chemistry code).
Definition mptrac.h:2861
int qnt_Ch2o
Quantity array index for H2O volume mixing ratio (chemistry code).
Definition mptrac.h:2822
double met_detrend
FWHM of horizontal Gaussian used for detrending [km].
Definition mptrac.h:3018
int conv_mix_pbl
Vertical mixing in the PBL (0=off, 1=on).
Definition mptrac.h:3142
char metbase[LEN]
Basename for meteo data.
Definition mptrac.h:2908
double bound_dps
Boundary conditions surface layer depth [hPa].
Definition mptrac.h:3181
double met_cms_eps[METVAR]
cmultiscale compression epsilon.
Definition mptrac.h:2997
int chemgrid_nz
Number of altitudes of chemistry grid.
Definition mptrac.h:3277
int qnt_cape
Quantity array index for convective available potential energy (CAPE).
Definition mptrac.h:2705
int qnt_zeta_dot
Quantity array index for velocity of zeta vertical coordinate.
Definition mptrac.h:2780
double bound_mass_trend
Boundary conditions mass per particle trend [kg/s].
Definition mptrac.h:3160
int met_cms_nd0y
cmultiscale number of cells of coarsest grid in y-direction.
Definition mptrac.h:2991
int mixing_nz
Number of altitudes of mixing grid.
Definition mptrac.h:3250
int qnt_o3c
Quantity array index for total column ozone.
Definition mptrac.h:2711
double bound_p0
Boundary conditions bottom pressure [hPa].
Definition mptrac.h:3175
double mixing_lon0
Lower longitude of mixing grid [deg].
Definition mptrac.h:3262
char clim_ccl4_timeseries[LEN]
Filename of CFC-10 time series.
Definition mptrac.h:3226
int qnt_Co3
Quantity array index for O3 volume mixing ratio (chemistry code).
Definition mptrac.h:2825
int qnt_tsts
Quantity array index for T_STS.
Definition mptrac.h:2813
int grid_nz
Number of altitudes of gridded data.
Definition mptrac.h:3506
char clim_oh_filename[LEN]
Filename of OH climatology.
Definition mptrac.h:3211
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 mixing_lat1
Upper latitude of mixing grid [deg].
Definition mptrac.h:3274
double atm_dt_out
Time step for atmospheric data output [s].
Definition mptrac.h:3395
char clim_sf6_timeseries[LEN]
Filename of SF6 time series.
Definition mptrac.h:3238
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 qnt_current_subdomain
Quantity array index for current subdomain in domain decomposition.
Definition mptrac.h:2886
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_Axe133
Quantity array index for radioactive activity of Xe-133.
Definition mptrac.h:2883
int chemgrid_nx
Number of longitudes of chemistry grid.
Definition mptrac.h:3286
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 h2o2_chem_reaction
Reaction type for H2O2 chemistry (0=none, 1=SO2).
Definition mptrac.h:3313
int qnt_Co3p
Quantity array index for O(3P) volume mixing ratio (chemistry code).
Definition mptrac.h:2846
int atm_nc_quant[NQ]
Number of digits for quantization of netCDF atmospheric data files (0=off).
Definition mptrac.h:3416
double wet_depo_bc_ret_ratio
Coefficients for wet deposition below cloud: retention ratio.
Definition mptrac.h:3358
int chemgrid_ny
Number of latitudes of chemistry grid.
Definition mptrac.h:3295
int qnt_Abe7
Quantity array index for radioactive activity of Be-7.
Definition mptrac.h:2874
char clim_ccl3f_timeseries[LEN]
Filename of CFC-11 time series.
Definition mptrac.h:3229
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
double dry_depo_vdep
Prescribed dry deposition velocity for mode 1 [m/s].
Definition mptrac.h:3367
int qnt_tt
Quantity array index for tropopause temperature.
Definition mptrac.h:2636
int met_np
Number of target pressure levels.
Definition mptrac.h:3021
int qnt_ens
Quantity array index for ensemble IDs.
Definition mptrac.h:2582
int met_nc_level
zlib compression level of netCDF meteo files (0=off).
Definition mptrac.h:2946
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_mloss_h2o2
Quantity array index for total mass loss due to H2O2 chemistry.
Definition mptrac.h:2732
double vtk_scale
Vertical scaling factor for VTK data.
Definition mptrac.h:3611
char clim_ccl2f2_timeseries[LEN]
Filename of CFC-12 time series.
Definition mptrac.h:3232
double wet_depo_ic_h[2]
In-cloud Henry coefficients (reference solubility, temperature coefficient).
Definition mptrac.h:3346
double turb_dx_pbl
Horizontal turbulent diffusion coefficient (PBL) [m^2/s].
Definition mptrac.h:3115
int dd_exchange_mode
Particle exchange: 0=sort/push (default), 1=direct pack/compact.
Definition mptrac.h:3645
double conv_cin
CIN threshold for convection module [J/kg].
Definition mptrac.h:3151
int qnt_pv
Quantity array index for potential vorticity.
Definition mptrac.h:2804
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
int qnt_mloss_oh
Quantity array index for total mass loss due to OH chemistry.
Definition mptrac.h:2729
int qnt_Ch2o2
Quantity array index for H2O2 volume mixing ratio (chemistry code).
Definition mptrac.h:2840
int qnt_sst
Quantity array index for sea surface temperature.
Definition mptrac.h:2627
double mixing_lon1
Upper longitude of mixing grid [deg].
Definition mptrac.h:3265
int atm_nc_level
zlib compression level of netCDF atmospheric data files (0=off).
Definition mptrac.h:3413
char clim_hno3_filename[LEN]
Filename of HNO3 climatology.
Definition mptrac.h:3208
double wet_depo_ic_ret_ratio
Coefficients for wet deposition in cloud: retention ratio.
Definition mptrac.h:3355
int qnt_sh
Quantity array index for specific humidity.
Definition mptrac.h:2759
int met_coord_type
Type of coordinates for meteo data (-1=detect, 0=lat/lon [deg], 1=UTM [m]).
Definition mptrac.h:2917
int qnt_ess
Quantity array index for eastward turbulent surface stress.
Definition mptrac.h:2615
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
int met_dy
Stride for latitudes.
Definition mptrac.h:3003
int qnt_Cx
Quantity array index for trace species x volume mixing ratio (chemistry code).
Definition mptrac.h:2819
double turb_dz_strat
Vertical turbulent diffusion coefficient (stratosphere) [m^2/s].
Definition mptrac.h:3130
double bound_zetas
Boundary conditions surface layer zeta [K].
Definition mptrac.h:3187
int radio_depo
RADIO_DEPO switch for radionuclide deposition (0=off, 1=on, default: 0).
Definition mptrac.h:3328
int dd_subdomains_zonal
Domain decomposition zonal subdomain number (defaults to 2 if domain decomposition is used,...
Definition mptrac.h:3631
int dry_depo_mode
Dry deposition mode: 0=off, 1=prescribed velocity, 2=aerosol velocity.
Definition mptrac.h:3361
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
double t_start
Start time of simulation [s].
Definition mptrac.h:2895
char qnt_longname[NQ][LEN]
Quantity long names.
Definition mptrac.h:2570
double met_p[EP]
Target pressure levels [hPa].
Definition mptrac.h:3024
int nq
Number of quantities.
Definition mptrac.h:2564
double tdec_trop
Life time of particles in the troposphere [s].
Definition mptrac.h:3199
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
double turb_dz_pbl
Vertical turbulent diffusion coefficient (PBL) [m^2/s].
Definition mptrac.h:3124
double grid_lat1
Upper latitude of gridded data [deg].
Definition mptrac.h:3530
int dd_subdomains_meridional
Domain decomposition meridional subdomain number (defaults to 2 if domain decomposition is used,...
Definition mptrac.h:3635
int qnt_zt
Quantity array index for tropopause geopotential height.
Definition mptrac.h:2639
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
int qnt_iso_var
Quantity array index for isosurface reference (units depend on ISOSURF).
Definition mptrac.h:2771
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
Domain decomposition data structure.
Definition mptrac.h:4129
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
int nx_glob
Number of global longitudes.
Definition mptrac.h:4136
double sort_key[NP]
Auxiliary array for sorting.
Definition mptrac.h:4179
size_t halo_bnd_start[4]
Start indices of the periodic boundary halo hyperslab.
Definition mptrac.h:4158
double lon_glob[DD_EX_GLOB]
Longitudes of the global grid [deg].
Definition mptrac.h:4142
double tmp[NP]
Auxiliary temporary array for sorting.
Definition mptrac.h:4185
double lat_glob[DD_EY_GLOB]
Latitudes of the global grid [deg].
Definition mptrac.h:4145
int halo_offset_start
Offset of the periodic halo block at the beginning of the local x-array.
Definition mptrac.h:4164
MPI_Datatype MPI_Particle
MPI datatype for particle exchange.
Definition mptrac.h:4176
size_t subdomain_count[4]
Extent of the local subdomain hyperslab (including inner halos).
Definition mptrac.h:4155
int ny_glob
Number of global latitudes.
Definition mptrac.h:4139
size_t subdomain_start[4]
Start indices of the local subdomain hyperslab (including inner halos).
Definition mptrac.h:4152
int perm[NP]
Auxiliary permutation array for sorting.
Definition mptrac.h:4182
Ground inventories of deposited radionuclides.
Definition mptrac.h:3762
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
Meteo data structure.
Definition mptrac.h:3952
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 zeta_dotl[EX][EY][EP]
Vertical velocity on model levels [K/s].
Definition mptrac.h:4120
float h2o[EX][EY][EP]
Water vapor volume mixing ratio [1].
Definition mptrac.h:4084
float cape[EX][EY]
Convective available potential energy [J/kg].
Definition mptrac.h:4057
int coord_type
Definition mptrac.h:3958
float w[EX][EY][EP]
Vertical velocity [hPa/s].
Definition mptrac.h:4078
float pct[EX][EY]
Cloud top pressure [hPa].
Definition mptrac.h:4039
double hybrid[EP]
Model hybrid levels.
Definition mptrac.h:3982
int nx
Number of longitudes.
Definition mptrac.h:3961
int ny
Number of latitudes.
Definition mptrac.h:3964
float shf[EX][EY]
Surface sensible heat flux [W/m^2].
Definition mptrac.h:4015
float ps[EX][EY]
Surface pressure [hPa].
Definition mptrac.h:3994
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 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 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 cc[EX][EY][EP]
Cloud cover [1].
Definition mptrac.h:4102
int np
Number of pressure levels.
Definition mptrac.h:3967
float t[EX][EY][EP]
Temperature [K].
Definition mptrac.h:4069
float ts[EX][EY]
Surface temperature [K].
Definition mptrac.h:3997
float u[EX][EY][EP]
Zonal wind [m/s].
Definition mptrac.h:4072
float ess[EX][EY]
Eastward turbulent surface stress [N/m^2].
Definition mptrac.h:4009
float ul[EX][EY][EP]
Zonal wind on model levels [m/s].
Definition mptrac.h:4108
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
double lon[EX]
Longitudes [deg].
Definition mptrac.h:3973
float pt[EX][EY]
Tropopause pressure [hPa].
Definition mptrac.h:4027
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 z[EX][EY][EP]
Geopotential height [km].
Definition mptrac.h:4066
float v[EX][EY][EP]
Meridional wind [m/s].
Definition mptrac.h:4075
int npl
Number of model levels.
Definition mptrac.h:3970
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
double eta[EP]
Model level eta values.
Definition mptrac.h:3991
double time
Time [s].
Definition mptrac.h:3955
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 pl[EX][EY][EP]
Pressure on model levels [hPa].
Definition mptrac.h:4105
float plfc[EX][EY]
Pressure at level of free convection (LFC) [hPa].
Definition mptrac.h:4051
double hyam[EP]
Model level a coefficients [Pa].
Definition mptrac.h:3985
double lat[EY]
Latitudes [deg].
Definition mptrac.h:3976
float swc[EX][EY][EP]
Cloud snow water content [kg/kg].
Definition mptrac.h:4099
double hybm[EP]
Model level b coefficients.
Definition mptrac.h:3988
float zetal[EX][EY][EP]
Zeta on model levels [K].
Definition mptrac.h:4117
double p[EP]
Pressure levels [hPa].
Definition mptrac.h:3979
Particle data.
Definition mptrac.h:3692
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
float uvwp[3]
Correlated velocity perturbations: horizontal [m/s], mesoscale vertical [hPa/s].
Definition mptrac.h:3713
double lon
Longitude [deg].
Definition mptrac.h:3701
double q[NQ]
Quantity data (for various, user-defined attributes).
Definition mptrac.h:3710
double dt
Individual time step [s].
Definition mptrac.h:3707