pio_write.c 13.3 KB
Newer Older
1
2
3
4
5
#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

#include <errno.h>
6
#include <inttypes.h>
7
8
#include <limits.h>
#include <math.h>
9
#include <stdbool.h>
Thomas Jahns's avatar
Thomas Jahns committed
10
#include <stdio.h>
11
#include <string.h>
12
#include <time.h>
13
14
15
16
17
#include <unistd.h>

#ifdef USE_MPI
#include <mpi.h>
#include "pio_c_temp.h"
18
19
#else
typedef int MPI_Comm;
20
21
22
23
#endif

#include "cdi.h"
#include "pio_util.h"
24
#include "cksum.h"
25
26
27
28
29

struct model_config
{
  int nlon, nlat, nts;
  int filetype, datatype;
30
  bool compute_checksum;
31
32
33
34
35
36
  const char *suffix;
};

struct model_config default_setup
  = { .nlon = 12, .nts = 3, .nlat = 6,
      .filetype = FILETYPE_GRB, .datatype = DATATYPE_PACK24,
37
      .compute_checksum = 1,
38
39
40
41
42
43
44
45
46
47
48
49
50
51
      .suffix = "grb"
};

static void
var_scale(int datatype, double *mscale, double *mrscale);

static inline double
sign_flat(double v)
{
  if (v == 0.0)
    return 0.0;
  return v;
}

52
53
54
55
56
57
enum {
  ntfiles     = 2,
  nVars       = 5,
  maxlev      = 5
};

58
59
60
61
62
63
static time_t
cditime2time_t(int date, int timeofday);
static void
time_t2cditime(time_t t, int *date, int *timeofday);


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
static void
modelRegionCompute(double region[], size_t offset, size_t len,
                   int nlev, int nlat, int nlon,
                   int tsID, const double lons[], const double lats[],
                   double mscale, double mrscale)
{
  size_t local_pos;
  for (local_pos = 0; local_pos < len; ++local_pos)
    {
      size_t global_pos = offset + local_pos;
      int k = global_pos / (nlon * nlat);
      int j = (global_pos % (nlon * nlat))/ nlon;
      int i = global_pos % nlon;
      region[local_pos]
        = sign_flat(round(
                          (cos(2.0 * M_PI * (lons[(i + tsID)%nlon] - lons[0])
                               / (lons[nlon-1] - lons[0]))
                           * sin(2.0 * M_PI * (lats[j] - lats[0])
                                 / (lats[nlat-1] - lats[0]))
                           ) * mscale)) * mrscale;
    }
}
86
87


88
void modelRun (struct model_config setup, MPI_Comm comm)
89
90
91
{

  static int nlev[nVars]    = {1,1,5,5,2};
92
  static int varCodes[nVars] = {129, 130, 131, 132, 133};
93
94
95
96
  static char * name        = "example";

  int gridID, zaxisID[nVars], taxisID;
  int vlistID, varIDs[nVars], streamID, tsID, tfID = 0;
97
  int i, varID, nmiss = 0;
98
99
  double *lons, *lats;
  double levs[maxlev] = {101300, 92500, 85000, 50000, 20000};
100
  double *var = NULL, *varslice;
101
  double mscale, mrscale;
102
  time_t current_time;
103
  int vdate = 19850101, vtime = 120000;
104
  int start = CDI_UNDEFID, chunk = CDI_UNDEFID, rank = 0, comm_size = 1;
105
106
  char filename[1024];
  int nlon = setup.nlon, nlat = setup.nlat;
107
  uint32_t checksum_state[nVars];
108
109
  size_t varSize[nVars], varslice_size;
#if USE_MPI
110
  int *chunks = NULL, *displs = NULL;
111
#endif
112
113
114

#if USE_MPI
  xmpi ( MPI_Comm_rank ( comm, &rank ));
115
  xmpi ( MPI_Comm_size ( comm, &comm_size ));
116
  if (rank == 0 && setup.compute_checksum)
117
118
119
    {
      chunks = xmalloc(comm_size * sizeof (chunks[0]));
      displs = xmalloc(comm_size * sizeof (displs[0]));
120
      var = xmalloc(nlon * nlat * maxlev * sizeof(var[0]));
121
    }
122
#endif
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

  var_scale(setup.datatype, &mscale, &mrscale);

  gridID = gridCreate ( GRID_LONLAT, nlon*nlat );
  gridDefXsize ( gridID, nlon );
  gridDefYsize ( gridID, nlat );
  lons = malloc(nlon * sizeof (lons[0]));
  for (i = 0; i < nlon; ++i)
    lons[i] = ((double)(i * 360))/nlon;
  lats = malloc(nlat * sizeof (lats[0]));
  for (i = 0; i < nlat; ++i)
    lats[i] = ((double)(i * 180))/nlat - 90.0;
  gridDefXvals ( gridID, lons );
  gridDefYvals ( gridID, lats );

  for ( i = 0; i < nVars; i++ )
    {
      zaxisID[i] = zaxisCreate ( ZAXIS_PRESSURE, nlev[i] );
      zaxisDefLevels ( zaxisID[i], levs );
    }

  varslice = NULL;
145
  varslice_size = 0;
146
147
148
149

  vlistID = vlistCreate ();

  for ( i = 0; i < nVars; i++ )
150
151
152
153
154
155
    {
      varIDs[i] = vlistDefVar ( vlistID, gridID, zaxisID[i], TIME_VARIABLE );
      varSize[i] = nlon * nlat * nlev[i];
      vlistDefVarCode(vlistID, varIDs[i], varCodes[i]);
      vlistDefVarDatatype(vlistID, varIDs[i], setup.datatype);
    }
156
157
158
159
160
161
162
163
164
165
166
167
168

  taxisID = taxisCreate ( TAXIS_ABSOLUTE );
  vlistDefTaxis ( vlistID, taxisID );

  sprintf ( &filename[0], "%s_%d.%s", name, tfID, setup.suffix );
  streamID = streamOpenWrite ( filename, setup.filetype );
  xassert ( streamID >= 0 );
  streamDefVlist ( streamID, vlistID);

  pioEndDef ();

  for ( tfID = 0; tfID < ntfiles; tfID++ )
    {
169
      memset(checksum_state, 0, sizeof(checksum_state));
170
171
172
173
174
175
176
177
      if ( tfID > 0 )
	{
	  streamClose ( streamID );
	  sprintf ( &filename[0], "%s_%d.%s", name, tfID, setup.suffix );
	  streamID = streamOpenWrite ( filename, setup.filetype );
	  xassert ( streamID >= 0 );
	  streamDefVlist ( streamID, vlistID );
	}
178
179
180
      vdate = 19850101;
      vtime = 120000;
      current_time = cditime2time_t(vdate, vtime);
181
182
      for ( tsID = 0; tsID < setup.nts; tsID++ )
	{
183
          time_t2cditime(current_time, &vdate, &vtime);
184
185
186
187
188
	  taxisDefVdate ( taxisID, vdate );
	  taxisDefVtime ( taxisID, vtime );
	  streamDefTimestep ( streamID, tsID );
	  for ( varID = 0; varID < nVars; varID++ )
	    {
189
190
              start = pioInqVarDecoOff(vlistID, varIDs[varID]);
              chunk = pioInqVarDecoChunk(vlistID, varIDs[varID]);
191
              if (varslice_size < chunk)
192
                {
193
194
                  varslice = xrealloc(varslice, chunk * sizeof (var[0]));
                  varslice_size = chunk;
195
                }
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
              modelRegionCompute(varslice, start, chunk,
                                 nlev[varID], nlat, nlon,
                                 tsID, lons, lats,
                                 mscale, mrscale);
              if (setup.compute_checksum)
                {
#if USE_MPI
                  xmpi(MPI_Gather(&chunk, 1, MPI_INT,
                                  chunks, 1, MPI_INT, 0, comm));
                  if (rank == 0)
                    {
                      displs[0] = 0;
                      for (i = 1; i < comm_size; ++i)
                        displs[i] = displs[i - 1] + chunks[i - 1];
                    }
                  xmpi(MPI_Gatherv(varslice, chunk, MPI_DOUBLE,
                                   var, chunks, displs, MPI_DOUBLE, 0, comm));
213
#else
214
                  var = varslice;
215
#endif
216
217
                }
              if (rank == 0 && setup.compute_checksum)
218
219
220
221
                {
                  memcrc_r(&checksum_state[varID], (const unsigned char *)var,
                           varSize[varID] * sizeof (var[0]));
                }
222

223
224
225
226
	      streamWriteVar ( streamID, varIDs[varID], varslice, nmiss );
	      start = CDI_UNDEFID;
	      chunk = CDI_UNDEFID;
	    }
227
          current_time += 86400;
228
229
	  pioWriteTimestep ( tsID, vdate, vtime );
	}
230
      if (rank == 0 && setup.compute_checksum)
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
        {
          FILE *tablefp;
          {
            sprintf(filename, "%s_%d.cksum", name, tfID);
            if (!(tablefp = fopen(filename, "w")))
              {
                perror("failed to open table file");
                exit(EXIT_FAILURE);
              }
            for (i = 0; i < nVars; ++i)
              {
                uint32_t cksum;
                int code;
                cksum = memcrc_finish(&checksum_state[i],
                                      (off_t)varSize[i]
                                      * sizeof (var[0]) * setup.nts);
                code = vlistInqVarCode(vlistID, varIDs[i]);
                if (fprintf(tablefp, "%08lx %d\n", (unsigned long)cksum,
                            code) < 0)
                  {
                    perror("failed to write table file");
                    exit(EXIT_FAILURE);
                  }
              }
            fclose(tablefp);
          }
        }
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    }
  pioEndTimestepping ();
  streamClose ( streamID );
  vlistDestroy ( vlistID );
  taxisDestroy ( taxisID );
  for ( i = 0; i < nVars; i++ )
    zaxisDestroy ( zaxisID[i] );
  gridDestroy ( gridID );
  free(lats);
  free(lons);
}

struct {
  char *text;
  int mode;
} mode_map[] = {
  { "PIO_MPI", PIO_MPI },
  { "PIO_FPGUARD", PIO_FPGUARD },
  { "PIO_ASYNCH", PIO_ASYNCH },
  { "PIO_WRITER", PIO_WRITER }
};

static const struct {
  char suffix[4];
  int type, defaultDT, defaultGrid;
} suffix2type[] = {
  { "nc", FILETYPE_NC, DATATYPE_FLT64, GRID_LONLAT },
  { "grb",  FILETYPE_GRB, DATATYPE_PACK24, GRID_LONLAT },
  { "nc2", FILETYPE_NC2, DATATYPE_FLT64, GRID_LONLAT },
  { "nc4", FILETYPE_NC4, DATATYPE_FLT64, GRID_LONLAT },
  { "ext", FILETYPE_EXT, DATATYPE_FLT64, GRID_GENERIC, },
  { "svc", FILETYPE_SRV, DATATYPE_FLT64, GRID_GENERIC, },
  { "ieg", FILETYPE_IEG, DATATYPE_FLT64, GRID_LONLAT },
};

static int
parse_intarg(const char msg[])
{
  char *end;
  long temp = strtol(optarg, &end, 0);
  if ((errno == ERANGE && (temp == LONG_MAX || temp == LONG_MIN))
      || (errno != 0 && temp == 0)) {
    perror(msg);
    exit(EXIT_FAILURE);
  }
  if (temp > INT_MAX || temp < INT_MIN)
  {
    fprintf(stderr, "range error: %ld\n", temp);
    exit(EXIT_FAILURE);
  }
  return (int)temp;
}

static void
var_scale(int datatype, double *mscale, double *mrscale)
{
  int mant_bits;
  switch (datatype)
    {
    case DATATYPE_PACK8:
      mant_bits = 7;
      break;
    case DATATYPE_PACK16:
      mant_bits = 15;
      break;
    case DATATYPE_PACK24:
      mant_bits = 23;
      break;
    case DATATYPE_FLT32:
      mant_bits = 24;
      break;
    case DATATYPE_FLT64:
      mant_bits = 53;
      break;
    case DATATYPE_INT8:
    case DATATYPE_INT16:
    case DATATYPE_INT32:
    default:
      fprintf(stderr, "Unexpected or unusable content format: %d\n",
              datatype);
      exit(EXIT_FAILURE);
    }
340
  *mscale = INT64_C(1) << mant_bits;
341
342
343
  *mrscale = 1.0 / *mscale;
}

344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
static inline int
search_iomode_str(const char *modestr)
{
  int i, retval = -1;
  for (i = 0;
       i < sizeof (mode_map) / sizeof (mode_map[0]);
       ++i)
    if (!strcmp(modestr, mode_map[i].text))
      {
        retval = i;
        break;
      }
  return retval;
}

359
360
int main (int argc, char *argv[])
{
361
#ifdef USE_MPI
362
  enum {
363
364
    nNamespaces = 2 };
  static int hasLocalFile[nNamespaces] = { 0, 1 };
365
#endif
366
367
368

  struct model_config setup = default_setup;

369
  MPI_Comm commModel;
370
#ifdef USE_MPI
371
  MPI_Comm commGlob;
372
373
374
375
376
377
378
379
380
381
382
383
384
385
  int sizeGlob;
  int rankGlob;
  int IOMode = PIO_MPI;
  int nProcsIO = 2;

  xmpi ( MPI_Init ( &argc, &argv));
  xmpi ( MPI_Comm_dup ( MPI_COMM_WORLD, &commGlob ));
  xmpi ( MPI_Comm_set_errhandler ( commGlob, MPI_ERRORS_RETURN ));
  xmpi ( MPI_Comm_size ( commGlob, &sizeGlob ));
  xmpi ( MPI_Comm_rank ( commGlob, &rankGlob ));
#endif

  {
    int opt;
386
    while ((opt = getopt(argc, argv, "f:m:n:t:c"
387
388
389
390
391
392
393
394
#ifdef USE_MPI
                         "p:w:"
#endif
                         )) != -1)
      switch (opt) {
#ifdef USE_MPI
      case 'p':
        {
395
396
          int entry = search_iomode_str(optarg);
          if (entry < 0)
397
398
399
400
            {
              fprintf(stderr, "Unsupported PIO mode requested: %s\n", optarg);
              exit(EXIT_FAILURE);
            }
401
          IOMode = mode_map[entry].mode;
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
        }
        break;
      case 'w':
        nProcsIO = strtol(optarg, NULL, 0);
        break;
#endif
      case 'f':
        {
          int i, found = 0;
          for (i = 0;
               i < sizeof (suffix2type) / sizeof (suffix2type[0]);
               ++i)
            if (!strcmp(optarg, suffix2type[i].suffix))
              {
                found = 1;
                setup.filetype = suffix2type[i].type;
                setup.suffix = suffix2type[i].suffix;
                setup.datatype = suffix2type[i].defaultDT;
                break;
              }
          if (!found)
            {
              fprintf(stderr, "Unsupported format requested: %s\n", optarg);
              exit(EXIT_FAILURE);
            }
        }
        break;
      case 'm':
        setup.nlon = parse_intarg("error parsing number of longitudes");
        break;
      case 'n':
        setup.nlat = parse_intarg("error parsing number of latitudes");
        break;
      case 't':
        setup.nts = parse_intarg("error parsing number of timesteps");
        break;
438
439
440
      case 'c':
        setup.compute_checksum = 0;
        break;
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
      default: /* '?' */
        fprintf(stderr, "Usage: %s "
                "[-m nlon] [-n nlat] [-o nlev] [-t nts]"
#ifdef USE_MPI
                " [-p PIO_MODE] [-w NIOSERVERS]"
#endif
                "\n", argv[0]);
        exit(EXIT_FAILURE);
      }

  }

#ifdef USE_MPI
  commModel = pioInit_c(commGlob, nProcsIO, IOMode,
                        nNamespaces, hasLocalFile);
456
457
#else
  commModel = -1;
458
459
#endif

460
  modelRun (setup, commModel);
461
462
463
464
465
466
467
468

#ifdef USE_MPI
  pioFinalize ();
  MPI_Finalize ();
#endif
  return 0;
}

469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
static time_t
cditime2time_t(int date, int timeofday)
{
  struct tm t_s;
  time_t t;
  t_s.tm_year = date / 10000;
  t_s.tm_mon = (date - t_s.tm_year * 10000)/100;
  t_s.tm_mday = date % 100;
  t_s.tm_year -= 1900;
  t_s.tm_hour = timeofday/10000;
  t_s.tm_min = (timeofday%10000)/100;
  t_s.tm_sec = timeofday%100;
  t_s.tm_isdst = 0;
  t = mktime(&t_s);
  /* 
   * fprintf(stderr, "converted %d,%d to %s to %lld.\n", date, timeofday,
   *         asctime(&t_s), (long long)t);
   */
  return t;
}

static void
time_t2cditime(time_t t, int *date, int *timeofday)
{
  struct tm *t_s;
  t_s = localtime(&t);
  /* fprintf(stderr, "converted %lld to %s.\n", (long long)t, asctime(t_s)); */
  *date = (t_s->tm_year + 1900) * 10000 + t_s->tm_mon * 100 + t_s->tm_mday;
  *timeofday = t_s->tm_hour * 10000 + t_s->tm_min * 100 + t_s->tm_sec;
}

500
501
502
503
504
505
506
507
508
/*
 * Local Variables:
 * c-file-style: "Java"
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * show-trailing-whitespace: t
 * require-trailing-newline: t
 * End:
 */