stream_gribapi.c 82.4 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
2
3
4
#if defined (HAVE_CONFIG_H)
#  include "config.h"
#endif

5
#include <limits.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
6
7
#include <stdio.h>

Uwe Schulzweida's avatar
Uwe Schulzweida committed
8
#include "dmemory.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
9
#include "cdi.h"
10
#include "cdi_int.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
11
#include "file.h"
12
13
#include "gribapi_utilities.h"
#include "stream_grb.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
14
15
16
#include "varscan.h"
#include "datetime.h"
#include "vlist.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
17
#include "stream_grb.h"
18
#include "calendar.h"
19
#include "subtype.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
20
21
22


#if  defined  (HAVE_LIBGRIB_API)
23
#  include "cgribex.h"      /* gribGetSize, gribRead, gribGetZip, GRIB1_LTYPE_99 */
Uwe Schulzweida's avatar
Uwe Schulzweida committed
24
#  include "gribapi.h"
25
26

#  include <grib_api.h>
Uwe Schulzweida's avatar
Uwe Schulzweida committed
27
28
29
30
#endif

extern int cdiInventoryMode;

Thomas Jahns's avatar
Thomas Jahns committed
31
#if  defined  (HAVE_LIBGRIB_API)
32
static const var_tile_t dummy_tiles = { -1, -1, -1, -1, -1, -1 };
Thomas Jahns's avatar
Thomas Jahns committed
33
#endif
34

Uwe Schulzweida's avatar
Uwe Schulzweida committed
35
typedef struct {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
36
  int param;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
37
38
39
  int level1;
  int level2;
  int ltype;
40
  int tsteptype;
41
  char name[32];
42
43
44

  var_tile_t tiles;

45
} compvar2_t;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
46
47
48
49


#if  defined  (HAVE_LIBGRIB_API)
static
50
int gribapiGetZaxisType(long editionNumber, int grib_ltype)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
51
{
Uwe Schulzweida's avatar
Uwe Schulzweida committed
52
53
54
  int zaxistype = ZAXIS_GENERIC;

  if ( editionNumber <= 1 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
55
    {
56
      zaxistype = grib1ltypeToZaxisType(grib_ltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
57
58
59
    }
  else
    {
60
      zaxistype = grib2ltypeToZaxisType(grib_ltype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
61
62
63
64
65
    }

  return (zaxistype);
}

66
static
67
int getTimeunits(long unitsOfTime)
68
69
{
  int timeunits = -1;
70
71
72
73
74
75
76
77
78
79
80
81
82

  switch (unitsOfTime)
    {
    case 13:  timeunits = TUNIT_SECOND;  break;
    case  0:  timeunits = TUNIT_MINUTE;  break;
    case  1:  timeunits = TUNIT_HOUR;    break;
    case 10:  timeunits = TUNIT_3HOURS;  break;
    case 11:  timeunits = TUNIT_6HOURS;  break;
    case 12:  timeunits = TUNIT_12HOURS; break;
    case  2:  timeunits = TUNIT_DAY;     break;
    default:  timeunits = TUNIT_HOUR;    break;
    }

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
  return (timeunits);
}

static
double timeunit_factor(int tu1, int tu2)
{
  double factor = 1;

  if ( tu2 == TUNIT_HOUR )
    {
      switch (tu1)
        {
        case TUNIT_SECOND:  factor = 3600;   break;
        case TUNIT_MINUTE:  factor = 60;     break;
        case TUNIT_HOUR:    factor = 1;      break;
        case TUNIT_3HOURS:  factor = 1./3;   break;
        case TUNIT_6HOURS:  factor = 1./6;   break;
        case TUNIT_12HOURS: factor = 1./12;  break;
        case TUNIT_DAY:     factor = 1./24;  break;
        }
    }

  return (factor);
}

static
int gribapiGetTimeUnits(grib_handle *gh)
{
  int timeunits = -1;
112
  long unitsOfTime = -1;
113

114
  grib_get_long(gh, "indicatorOfUnitOfTimeRange", &unitsOfTime);
115

116
  GRIB_CHECK(my_grib_set_long(gh, "stepUnits", unitsOfTime), 0);
117

118
  timeunits = getTimeunits(unitsOfTime);
119
120
121
122

  return (timeunits);
}

123
static
124
void gribapiGetSteps(grib_handle *gh, int timeunits, int *startStep, int *endStep)
125
{
126
  int timeunits2 = timeunits;
127
128
  long unitsOfTime;
  int status = grib_get_long(gh, "stepUnits", &unitsOfTime);
129
130
  if ( status == 0 ) timeunits2 = getTimeunits(unitsOfTime);
  //timeunits2 = gribapiGetTimeUnits(gh);
131

132
  long lpar;
133
134
135
136
137
138
139
140
  status = grib_get_long(gh, "forecastTime", &lpar);
  if ( status == 0 ) *startStep = (int) lpar;
  else
    {
      status = grib_get_long(gh, "startStep", &lpar);
      if ( status == 0 )
        *startStep = (int) (((double)lpar * timeunit_factor(timeunits, timeunits2)) + 0.5);
    }
141

142
143
  *endStep = *startStep;
  status = grib_get_long(gh, "endStep", &lpar);
144
  if ( status == 0 )
145
146
    *endStep = (int) (((double)lpar * timeunit_factor(timeunits, timeunits2)) + 0.5);
  // printf("%d %d %d %d %d %g\n", *startStep, *endStep, lpar, timeunits, timeunits2, timeunit_factor(timeunits, timeunits2));
147
148
}

149
150
151
152
153
154
155
static
void gribapiGetDataDateTime(grib_handle *gh, int *datadate, int *datatime)
{
  long lpar;

  GRIB_CHECK(grib_get_long(gh, "dataDate", &lpar), 0);
  *datadate = (int) lpar;
156
  GRIB_CHECK(grib_get_long(gh, "dataTime", &lpar), 0);  //FIXME: This looses the seconds in GRIB2 files.
157
158
159
  *datatime = (int) lpar*100;
}

160
161
162
static
void gribapiSetDataDateTime(grib_handle *gh, int datadate, int datatime)
{
163
164
  GRIB_CHECK(my_grib_set_long(gh, "dataDate", datadate), 0);
  GRIB_CHECK(my_grib_set_long(gh, "dataTime", datatime/100), 0);
165
166
}

167
static
168
int gribapiGetValidityDateTime(grib_handle *gh, int *vdate, int *vtime)
169
{
170
  int rdate, rtime;
171
  int timeUnits, startStep = 0, endStep;
172
173
  int tstepRange = 0;
  int range;
174
175
  long sigofrtime = 3;

176
  if ( gribEditionNumber(gh) > 1 )
177
178
179
    {
      GRIB_CHECK(grib_get_long(gh, "significanceOfReferenceTime", &sigofrtime), 0);
    }
180
181
182
183
  else
    {
      GRIB_CHECK(grib_get_long(gh, "timeRangeIndicator", &sigofrtime), 0);
    }
184

185
  if ( sigofrtime == 3 )        //XXX: This looks like a bug to me, because timeRangeIndicator == 3 does not seem to have the same meaning as significanceOfReferenceTime == 3. I would recommend replacing this condition with `if(!gribapiTimeIsFC())`.
186
    {
187
      gribapiGetDataDateTime(gh, vdate, vtime);
188
189
190
    }
  else
    {
191
192
      gribapiGetDataDateTime(gh, &rdate, &rtime);

193
      timeUnits = gribapiGetTimeUnits(gh);
194
      gribapiGetSteps(gh, timeUnits, &startStep, &endStep);
195
196
197
198
199
200
201
202
203

      range = endStep - startStep;

      if ( range > 0 )
	{
	  if ( startStep == 0 ) tstepRange = -1;
	  else                  tstepRange =  1;
	}

204
205
206
207
      {
	static int lprint = TRUE;
	extern int grib_calendar;
	int ryear, rmonth, rday, rhour, rminute, rsecond;
208
209
210
	int julday, secofday;
	int64_t time_period = endStep;
        int64_t addsec;
211
212
213
214

	cdiDecodeDate(rdate, &ryear, &rmonth, &rday);
	cdiDecodeTime(rtime, &rhour, &rminute, &rsecond);

215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
        if ( rday > 0 )
          {
            encode_caldaysec(grib_calendar, ryear, rmonth, rday, rhour, rminute, rsecond, &julday, &secofday);

            addsec = 0;
            switch ( timeUnits )
              {
              case TUNIT_SECOND:  addsec =         time_period; break;
              case TUNIT_MINUTE:  addsec =    60 * time_period; break;
              case TUNIT_HOUR:    addsec =  3600 * time_period; break;
              case TUNIT_3HOURS:  addsec = 10800 * time_period; break;
              case TUNIT_6HOURS:  addsec = 21600 * time_period; break;
              case TUNIT_12HOURS: addsec = 43200 * time_period; break;
              case TUNIT_DAY:     addsec = 86400 * time_period; break;
              default:
                if ( lprint )
                  {
                    Warning("Time unit %d unsupported", timeUnits);
                    lprint = FALSE;
                  }
                break;
              }

            julday_add_seconds(addsec, &julday, &secofday);

            decode_caldaysec(grib_calendar, julday, secofday, &ryear, &rmonth, &rday, &rhour, &rminute, &rsecond);
          }
242

243
244
245
	*vdate = cdiEncodeDate(ryear, rmonth, rday);
	*vtime = cdiEncodeTime(rhour, rminute, rsecond);
      }
246
    }
247
248

  return (tstepRange);
249
250
}

251
static
252
void grib1GetLevel(grib_handle *gh, int *leveltype, int *lbounds, int *level1, int *level2)
253
{
254
  *leveltype = 0;
255
256
257
  *lbounds   = 0;
  *level1    = 0;
  *level2    = 0;
258

259
  long lpar;
260
  if(!grib_get_long(gh, "indicatorOfTypeOfLevel", &lpar))       //1 byte
261
    {
262
      *leveltype = (int) lpar;
263

264
      switch (*leveltype)
265
266
267
268
	{
	case GRIB1_LTYPE_SIGMA_LAYER:
	case GRIB1_LTYPE_HYBRID_LAYER:
	case GRIB1_LTYPE_LANDDEPTH_LAYER:
269
	  { *lbounds = 1; break; }
270
	}
271

272
273
274
275
276
277
278
279
      if ( *lbounds )
	{
	  GRIB_CHECK(grib_get_long(gh, "topLevel", &lpar), 0);  //1 byte
	  *level1 = (int)lpar;
	  GRIB_CHECK(grib_get_long(gh, "bottomLevel", &lpar), 0);       //1 byte
	  *level2 = (int)lpar;
	}
      else
280
	{
281
          double dlevel;
282
	  GRIB_CHECK(grib_get_double(gh, "level", &dlevel), 0); //2 byte
283
284
	  if ( *leveltype == 100 ) dlevel *= 100;
	  if ( dlevel < -2.e9 || dlevel > 2.e9 ) dlevel = 0;
285
	  if ( *leveltype == GRIB1_LTYPE_99 ) *leveltype = 100;
286

287
288
289
	  *level1 = (int) dlevel;
	  *level2 = 0;
	}
290
    }
291
292
}

293
294
295
static
double grib2ScaleFactor(long factor)
{
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
  switch(factor)
    {
      case GRIB_MISSING_LONG: return 1;
      case 0: return 1;
      case 1: return 0.1;
      case 2: return 0.01;
      case 3: return 0.001;
      case 4: return 0.0001;
      case 5: return 0.00001;
      case 6: return 0.000001;
      case 7: return 0.0000001;
      case 8: return 0.00000001;
      case 9: return 0.000000001;
      default: return 0;
    }
}

static
int calcLevel(int level_sf, long factor, long level)
{
  double result = 0;
Thomas Jahns's avatar
Thomas Jahns committed
317
  if(level != GRIB_MISSING_LONG) result = (double)level*grib2ScaleFactor(factor);
318
319
  if(level_sf) result *= level_sf;
  return (int)result;
320
321
}

322
static
323
324
void grib2GetLevel(grib_handle *gh, int *leveltype1, int *leveltype2, int *lbounds, int *level1, 
                   int *level2, int *level_sf, int *level_unit)
325
{
326
327
328
  int status;
  long lpar;
  long factor;
329

330
331
  *leveltype1 = 0;
  *leveltype2 = -1;
332
333
334
335
336
  *lbounds    = 0;
  *level1     = 0;
  *level2     = 0;
  *level_sf   = 0;
  *level_unit = 0;
337

338
  status = grib_get_long(gh, "typeOfFirstFixedSurface", &lpar); //1 byte
339
  if ( status == 0 )
340
    {
341
      long llevel;
342

343
      *leveltype1 = (int) lpar;
344

345
      status = grib_get_long(gh, "typeOfSecondFixedSurface", &lpar); //1 byte
346
      /* FIXME: assert(lpar >= INT_MIN && lpar <= INT_MAX) */
347
      if ( status == 0 ) *leveltype2 = (int)lpar;
348

349
      if ( *leveltype1 != 255 && *leveltype2 != 255 && *leveltype2 > 0 ) *lbounds = 1;
350
      switch(*leveltype1)
351
        {
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
          case GRIB2_LTYPE_REFERENCE:
            if(*leveltype2 == 1) *lbounds = 0;
            break;

          case GRIB2_LTYPE_LANDDEPTH:
            *level_sf = 1000;
            *level_unit = CDI_UNIT_M;
            break;

          case GRIB2_LTYPE_ISOBARIC:
            *level_sf = 1000;
            *level_unit = CDI_UNIT_PA;
            break;

          case GRIB2_LTYPE_SIGMA:
            *level_sf = 1000;
            *level_unit = 0;
            break;
370
        }
371

372
373
374
      GRIB_CHECK(grib_get_long(gh, "scaleFactorOfFirstFixedSurface", &factor), 0);      //1 byte
      GRIB_CHECK(grib_get_long(gh, "scaledValueOfFirstFixedSurface", &llevel), 0);      //4 byte
      *level1 = calcLevel(*level_sf, factor, llevel);
375

376
377
378
379
380
      if ( *lbounds )
        {
          GRIB_CHECK(grib_get_long(gh, "scaleFactorOfSecondFixedSurface", &factor), 0); //1 byte
          GRIB_CHECK(grib_get_long(gh, "scaledValueOfSecondFixedSurface", &llevel), 0); //4 byte
          *level2 = calcLevel(*level_sf, factor, llevel);
381
        }
382
383
    }
}
384

385
static
386
void gribGetLevel(grib_handle *gh, int* leveltype1, int* leveltype2, int* lbounds, int* level1, int* level2, int* level_sf, int* level_unit, var_tile_t* tiles)
387
388
389
390
391
392
393
394
395
396
397
{
  if ( gribEditionNumber(gh) <= 1 )
    {
      grib1GetLevel(gh, leveltype1, lbounds, level1, level2);
      *leveltype2 = -1;
      *level_sf = 0;
      *level_unit = 0;
    }
  else
    {
      grib2GetLevel(gh, leveltype1, leveltype2, lbounds, level1, level2, level_sf, level_unit);
398
399

      /* read in tiles attributes (if there are any) */
Thomas Jahns's avatar
Thomas Jahns committed
400
401
402
403
404
405
      tiles->tileindex = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TILEINDEX], -1);
      tiles->totalno_of_tileattr_pairs = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TOTALNO_OF_TILEATTR_PAIRS], -1);
      tiles->tileClassification = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TILE_CLASSIFICATION], -1);
      tiles->numberOfTiles = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_NUMBER_OF_TILES], -1);
      tiles->numberOfAttributes = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_NUMBER_OF_ATTR], -1);
      tiles->attribute = (int)gribGetLongDefault(gh, cdiSubtypeAttributeName[SUBTYPE_ATT_TILEATTRIBUTE], -1);
406
    }
407
408
}

409
410
411
412
413
static
void gribapiGetString(grib_handle *gh, const char *key, char *string, size_t length)
{
  string[0] = 0;

414
415
416
417
418
419
  int ret = grib_get_string(gh, key, string, &length);
  if (ret != 0)
    {
      fprintf(stderr, "grib_get_string(gh, \"%s\", ...) failed!\n", key);
      GRIB_CHECK(ret, 0);
    }
420
421
422
423
  if      ( length == 8 && memcmp(string, "unknown", length) == 0 ) string[0] = 0;
  else if ( length == 2 && memcmp(string, "~", length)       == 0 ) string[0] = 0;
}

424
#if  defined  (HAVE_LIBGRIB_API)
425
static
426
void gribapiAddRecord(stream_t * streamptr, int param, grib_handle *gh,
427
                      size_t recsize, off_t position, int datatype, int comptype, const char *varname,
428
                      int leveltype1, int leveltype2, int lbounds, int level1, int level2, int level_sf, int level_unit,
429
                      const var_tile_t *tiles, int lread_additional_keys)
430
{
431
  int varID;
432
433
434
435
  int levelID = 0;
  grid_t grid;
  long lpar;
  int status;
436
  char stdname[CDI_MAX_NAME], longname[CDI_MAX_NAME], units[CDI_MAX_NAME];
437
  size_t vlen;
438
  long ens_index = 0, ens_count = 0, ens_forecast_type = 0;
439

440
441
442
443
  int vlistID = streamptr->vlistID;
  int tsID    = streamptr->curTsID;
  int recID   = recordNewEntry(streamptr, tsID);
  record_t *record  = &streamptr->tsteps[tsID].records[recID];
444

445
  int tsteptype = gribapiGetTsteptype(gh);
446
  // numavg  = ISEC1_AvgNum;
447
  int numavg  = 0;
448

449
  // fprintf(stderr, "param %d %d %d %d\n", param, level1, level2, leveltype1);
450

Thomas Jahns's avatar
Thomas Jahns committed
451
452
453
454
455
456
457
458
  record->size      = recsize;
  record->position  = position;
  record->param     = param;
  record->ilevel    = level1;
  record->ilevel2   = level2;
  record->ltype     = leveltype1;
  record->tsteptype = tsteptype;
  record->tiles = tiles ? *tiles : dummy_tiles;
459
460
461
462
463
464
465
466
467
468
469
470

  //FIXME: This may leave the variable name unterminated (which is the behavior that I found in the code).
  //       I don't know precisely how this field is used, so I did not change this behavior to avoid regressions,
  //       but I think that it would be better to at least add a line
  //
  //           record->varname[sizeof(record->varname) - 1] = 0;`
  //
  //       after the `strncpy()` call.
  //
  //       I would consider using strdup() (that requires POSIX-2008 compliance, though), or a similar homebrew approach.
  //       I. e. kick the fixed size array and allocate enough space, whatever that may be.
  strncpy(record->varname, varname, sizeof(record->varname));
471
472

  gribapiGetGrid(gh, &grid);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
473

474
  int gridID = varDefGrid(vlistID, &grid, 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
475

476
  int zaxistype = gribapiGetZaxisType(gribEditionNumber(gh), leveltype1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
477

478
  switch (zaxistype)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
479
    {
480
481
482
    case ZAXIS_HYBRID:
    case ZAXIS_HYBRID_HALF:
      {
Thomas Jahns's avatar
Thomas Jahns committed
483
        size_t vctsize;
484
485
        size_t dummy;
        double *vctptr;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
486

487
        GRIB_CHECK(grib_get_long(gh, "NV", &lpar), 0);
Thomas Jahns's avatar
Thomas Jahns committed
488
489
        /* FIXME: assert(lpar >= 0) */
        vctsize = (size_t)lpar;
490
491
        if ( vctsize > 0 )
          {
492
            vctptr = (double *) Malloc(vctsize*sizeof(double));
Thomas Jahns's avatar
Thomas Jahns committed
493
            dummy = vctsize;
494
            GRIB_CHECK(grib_get_double_array(gh, "pv", vctptr, &dummy), 0);
Thomas Jahns's avatar
Thomas Jahns committed
495
            varDefVCT(vctsize, vctptr);
496
            Free(vctptr);
497
498
499
500
501
          }
        break;
      }
    case ZAXIS_REFERENCE:
      {
502
        unsigned char uuid[CDI_UUID_SIZE];
503
        long ltmp;
504
        long nhlev, nvgrid;
505
506

        GRIB_CHECK(grib_get_long(gh, "NV", &lpar), 0);
507
        if ( lpar != 6 )
508
509
510
          {
            fprintf(stderr, "Warning ...\n");
          }
511
        GRIB_CHECK(grib_get_long(gh, "nlev", &ltmp), 0);
512
        nhlev = ltmp;
513
514
        GRIB_CHECK(grib_get_long(gh, "numberOfVGridUsed", &ltmp), 0);
        nvgrid = ltmp;
515
        size_t len = (size_t)CDI_UUID_SIZE;
516
517
        memset(uuid, 0, CDI_UUID_SIZE);
        GRIB_CHECK(grib_get_bytes(gh, "uuidOfVGrid", uuid, &len), 0);
518
        varDefZAxisReference((int) nhlev, (int) nvgrid, uuid);
519
520
        break;
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
521
    }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
522

523
  // if ( datatype > 32 ) datatype = DATATYPE_PACK32;
524
  if ( datatype <  0 ) datatype = DATATYPE_PACK;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
525

526
  stdname[0] = 0;
527
528
529
  longname[0] = 0;
  units[0] = 0;

530
  if ( varname[0] != 0 )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
531
    {
532
      vlen = CDI_MAX_NAME;
533
      gribapiGetString(gh, "name", longname, vlen);
534
      vlen = CDI_MAX_NAME;
535
      gribapiGetString(gh, "units", units, vlen);
536
537
538
539
540

      {
        vlen = CDI_MAX_NAME;
        status = grib_get_string(gh, "cfName", stdname, &vlen);
        if ( status != 0 || vlen <= 1 ) stdname[0] = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
541
        else if ( strncmp(stdname, "unknown", 7) == 0 ) stdname[0] = 0;
542
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
543
    }
544
  // fprintf(stderr, "param %d name %s %s %s\n", param, name, longname, units);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
545

546
547
  /* add the previously read record data to the (intermediate) list of records */
  int tile_index = -1;
548
  varAddRecord(recID, param, gridID, zaxistype, lbounds, level1, level2, level_sf, level_unit,
549
	       datatype, &varID, &levelID, tsteptype, numavg, leveltype1, leveltype2,
550
	       varname, stdname, longname, units, tiles, &tile_index);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
551

Thomas Jahns's avatar
Thomas Jahns committed
552
553
  record->varID   = (short)varID;
  record->levelID = (short)levelID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
554

555
  varDefCompType(varID, comptype);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
556

557
558
  /*
    Get the ensemble Info from the grib-2 Tables and update the intermediate datastructure.
559
    Further update to the "vlist" is handled in the same way as for GRIB-1 by "cdi_generate_vars"
560
  */
561
562
563
564
565
566
567
  status = grib_get_long(gh, "typeOfEnsembleForecast", &ens_forecast_type );
  if ( status == 0 )
    {
      GRIB_CHECK(grib_get_long(gh, "numberOfForecastsInEnsemble", &ens_count ), 0);
      GRIB_CHECK(grib_get_long(gh, "perturbationNumber", &ens_index ), 0);
    }

568
569
570
  if ( ens_index > 0 )
    varDefEnsembleInfo(varID, (int)ens_index, (int)ens_count, (int)ens_forecast_type);

571
572
573
574
575
  long typeOfGeneratingProcess = 0;
  status = grib_get_long(gh, "typeOfGeneratingProcess", &typeOfGeneratingProcess);
  if ( status == 0 )
    varDefTypeOfGeneratingProcess(varID, (int) typeOfGeneratingProcess);

576
577
578
579
580
  long productDefinitionTemplate = 0;
  status = grib_get_long(gh, "productDefinitionTemplateNumber", &productDefinitionTemplate);
  if ( status == 0 )
    varDefProductDefinitionTemplate(varID, (int) productDefinitionTemplate);

581
582
583
584
  int    i;
  long   lval;
  double dval;

585
586
587
588
589
590
591
592
593
  if (lread_additional_keys)
    for ( i = 0; i < cdiNAdditionalGRIBKeys; i++ )
      {
        /* note: if the key is not defined, we do not throw an error! */
        if ( grib_get_long(gh, cdiAdditionalGRIBKeys[i], &lval) == 0 )
          varDefOptGribInt(varID, tile_index, lval, cdiAdditionalGRIBKeys[i]);
        if ( grib_get_double(gh, cdiAdditionalGRIBKeys[i], &dval) == 0 )
          varDefOptGribDbl(varID, tile_index, dval, cdiAdditionalGRIBKeys[i]);
      }
594

Uwe Schulzweida's avatar
Uwe Schulzweida committed
595
596
  if ( varInqInst(varID) == CDI_UNDEFID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
597
598
599
600
601
      long center, subcenter;
      int instID;
      GRIB_CHECK(grib_get_long(gh, "centre", &center), 0);
      GRIB_CHECK(grib_get_long(gh, "subCentre", &subcenter), 0);
      instID    = institutInq((int)center, (int)subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
602
      if ( instID == CDI_UNDEFID )
Uwe Schulzweida's avatar
Uwe Schulzweida committed
603
	instID = institutDef((int)center, (int)subcenter, NULL, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
604
605
606
607
608
609
      varDefInst(varID, instID);
    }

  if ( varInqModel(varID) == CDI_UNDEFID )
    {
      int modelID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
610
      long processID;
611
612
613
      status = grib_get_long(gh, "generatingProcessIdentifier", &processID);
      if ( status == 0 )
	{
614
615
          /* FIXME: assert(processID >= INT_MIN && processID <= INT_MAX) */
	  modelID = modelInq(varInqInst(varID), (int)processID, NULL);
616
	  if ( modelID == CDI_UNDEFID )
617
	    modelID = modelDef(varInqInst(varID), (int)processID, NULL);
618
619
	  varDefModel(varID, modelID);
	}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
620
621
622
623
    }

  if ( varInqTable(varID) == CDI_UNDEFID )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
624
      int pdis, pcat, pnum;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
625

Uwe Schulzweida's avatar
Uwe Schulzweida committed
626
      cdiDecodeParam(param, &pnum, &pcat, &pdis);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
627

Uwe Schulzweida's avatar
Uwe Schulzweida committed
628
629
630
631
      if ( pdis == 255 )
	{
	  int tableID;
	  int tabnum = pcat;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
632

Uwe Schulzweida's avatar
Uwe Schulzweida committed
633
	  tableID = tableInq(varInqModel(varID), tabnum, NULL);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
634

Uwe Schulzweida's avatar
Uwe Schulzweida committed
635
636
637
	  if ( tableID == CDI_UNDEFID )
	    tableID = tableDef(varInqModel(varID), tabnum, NULL);
	  varDefTable(varID, tableID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
638
639
640
641
642
643
644
	}
    }

  streamptr->tsteps[tsID].nallrecs++;
  streamptr->nrecs++;

  if ( CDI_Debug )
645
    Message("varID = %d  param = %d  zaxistype = %d  gridID = %d  levelID = %d",
Uwe Schulzweida's avatar
Uwe Schulzweida committed
646
	    varID, param, zaxistype, gridID, levelID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
647
}
648
#endif
649

650
651
static compvar2_t gribapiVarSet(int param, int level1, int level2, int leveltype, 
                                int tsteptype, char *name, var_tile_t tiles_data)
652
653
{
  compvar2_t compVar;
654
655
656
  size_t maxlen = sizeof(compVar.name);
  size_t len = strlen(name);
  if ( len > maxlen ) len = maxlen;
657

658
659
660
661
662
  compVar.param     = param;
  compVar.level1    = level1;
  compVar.level2    = level2;
  compVar.ltype     = leveltype;
  compVar.tsteptype = tsteptype;
663
664
  memset(compVar.name, 0, maxlen);
  memcpy(compVar.name, name, len);
665
  compVar.tiles = tiles_data;
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
666

667
668
  return (compVar);
}
669
#endif
670

671
#ifdef HAVE_LIBGRIB_API
672
static
673
int gribapiVarCompare(compvar2_t compVar, record_t record, int flag)
674
675
{
  compvar2_t compVar0;
676
677
678
679
680
  compVar0.param     = record.param;
  compVar0.level1    = record.ilevel;
  compVar0.level2    = record.ilevel2;
  compVar0.ltype     = record.ltype;
  compVar0.tsteptype = record.tsteptype;
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
681
  memcpy(compVar0.name, record.varname, sizeof(compVar.name));
682

683
684
685
686
687
688
  if ( flag == 0 )
    {
      if ( compVar0.tsteptype == TSTEP_INSTANT  && compVar.tsteptype == TSTEP_INSTANT3 ) compVar0.tsteptype = TSTEP_INSTANT3;
      if ( compVar0.tsteptype == TSTEP_INSTANT3 && compVar.tsteptype == TSTEP_INSTANT  ) compVar0.tsteptype = TSTEP_INSTANT;
    }

689
690
  compVar0.tiles = record.tiles;

691
  int rstatus = memcmp(&compVar0, &compVar, sizeof(compvar2_t));
692
693
694

  return (rstatus);
}
Uwe Schulzweida's avatar
Uwe Schulzweida committed
695

696
697
698
static
void ensureBufferSize(size_t requiredSize, size_t *curSize, void **buffer)
{
699
700
701
  if ( *curSize < requiredSize )
    {
      *curSize = requiredSize;
702
      *buffer = Realloc(*buffer, *curSize);
703
704
705
    }
}

706
static
707
grib_handle *gribapiGetDiskRepresentation(size_t recsize, size_t *buffersize, void **gribbuffer, int *outDatatype, int *outCompressionType, long *outUnzipsize)
708
709
710
{
  int lieee = FALSE;

711
  grib_handle *gh = grib_handle_new_from_message(NULL, *gribbuffer, recsize);
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
  if(gribEditionNumber(gh) > 1)
    {
      size_t len = 256;
      char typeOfPacking[256];

      if ( grib_get_string(gh, "packingType", typeOfPacking, &len) == 0 )
        {
          // fprintf(stderr, "packingType %d %s\n", len, typeOfPacking);
          if      ( strncmp(typeOfPacking, "grid_jpeg", len) == 0 ) *outCompressionType = COMPRESS_JPEG;
          else if ( strncmp(typeOfPacking, "grid_ccsds", len) == 0 ) *outCompressionType = COMPRESS_SZIP;
          else if ( strncmp(typeOfPacking, "grid_ieee", len) == 0 ) lieee = TRUE;
        }
    }
  else
    {
Thomas Jahns's avatar
Thomas Jahns committed
727
      if( gribGetZip((long)recsize, *gribbuffer, outUnzipsize) > 0 )
728
729
        {
          *outCompressionType = COMPRESS_SZIP;
Thomas Jahns's avatar
Thomas Jahns committed
730
          ensureBufferSize((size_t)*outUnzipsize + 100, buffersize, gribbuffer);
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
        }
      else
        {
          *outCompressionType = COMPRESS_NONE;
        }
    }

  if ( lieee )
    {
      *outDatatype = DATATYPE_FLT64;
      long precision;
      int status = grib_get_long(gh, "precision", &precision);
      if ( status == 0 && precision == 1 ) *outDatatype = DATATYPE_FLT32;
    }
  else
    {
      *outDatatype = DATATYPE_PACK;
      long bitsPerValue;
      if ( grib_get_long(gh, "bitsPerValue", &bitsPerValue) == 0 )
        {
          if ( bitsPerValue > 0 && bitsPerValue <= 32 ) *outDatatype = (int)bitsPerValue;
        }
    }
  return gh;
}
756
#endif
757

758
#if  defined  (HAVE_LIBGRIB_API)
759
760
typedef enum { CHECKTIME_OK, CHECKTIME_SKIP, CHECKTIME_STOP, CHECKTIME_INCONSISTENT } checkTimeResult;
static checkTimeResult checkTime(stream_t* streamptr, compvar2_t compVar, const DateTime* verificationTime, const DateTime* expectedVTime) {
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
761
  // First determine whether the current record exists already.
762
763
764
765
766
767
768
  int recID = 0;
  for ( ; recID < streamptr->nrecs; recID++ )
    {
      if ( gribapiVarCompare(compVar, streamptr->tsteps[0].records[recID], 1) == 0 ) break;
    }
  int recordExists = recID < streamptr->nrecs;

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
769
  // Then we need to know whether the verification time is consistent.
770
771
  int consistentTime = !memcmp(verificationTime, expectedVTime, sizeof(*verificationTime));

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
772
  // Finally, we make a decision.
773
774
775
776
777
778
779
780
781
782
  if ( cdiInventoryMode == 1 )
    {
      if ( recordExists ) return CHECKTIME_STOP;
      if ( !consistentTime ) return CHECKTIME_INCONSISTENT;
    }
  else
    {
      if ( !consistentTime ) return CHECKTIME_STOP;
      if ( recordExists ) return CHECKTIME_SKIP;
    }
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
783

784
785
  return CHECKTIME_OK;
}
786
#endif
787
788
789
790
791
792
793
794

#define gribWarning(text, nrecs, timestep, varname, param, level1, level2) do \
  { \
    char paramstr[32]; \
    cdiParamToString(param, paramstr, sizeof(paramstr)); \
    Warning("Record %2d (name=%s id=%s lev1=%d lev2=%d) timestep %d: %s", nrecs, varname, paramstr, level1, level2, timestep, text); \
  } \
while(0)
795

796
#if  defined  (HAVE_LIBGRIB_API)
797
int gribapiScanTimestep1(stream_t * streamptr)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
798
799
{
  off_t recpos = 0;
800
  void *gribbuffer = NULL;
801
  size_t buffersize = 0;
802
803
  DateTime datetime0 = { .date = 10101, .time = 0 };
  int nrecs_scanned = 0;        //Only used for debug output.
Uwe Schulzweida's avatar
Uwe Schulzweida committed
804
  int warn_time = TRUE;
805
  // int warn_numavg = TRUE;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
806
807
808
809
810
  int rdate = 0, rtime = 0, tunit = 0, fcast = 0;
  grib_handle *gh = NULL;

  streamptr->curTsID = 0;

811
812
  int tsID  = tstepsNewEntry(streamptr);
  taxis_t *taxis = &streamptr->tsteps[tsID].taxis;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
813
814

  if ( tsID != 0 )
815
    Error("Internal problem! tstepsNewEntry returns %d", tsID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
816

817
  int fileID = streamptr->fileID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
818

Thomas Jahns's avatar
Thomas Jahns committed
819
  unsigned nrecs = 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
820
821
  while ( TRUE )
    {
822
823
      int level1 = 0, level2 = 0;
      size_t recsize = (size_t)gribGetSize(fileID);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
824
825
826
      recpos  = fileGetPos(fileID);

      if ( recsize == 0 )
827
828
829
830
831
        {
          streamptr->ntsteps = 1;
          break;
        }
      ensureBufferSize(recsize, &buffersize, &gribbuffer);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
832

833
      size_t readsize = recsize;
834
      int rstatus = gribRead(fileID, gribbuffer, &readsize); //Search for next 'GRIB', read the following record, and position file offset after it.
Uwe Schulzweida's avatar
Uwe Schulzweida committed
835
      if ( rstatus ) break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
836

837
      int datatype, comptype = 0;
838
839
      long unzipsize;
      gh = gribapiGetDiskRepresentation(recsize, &buffersize, &gribbuffer, &datatype, &comptype, &unzipsize);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
840

841
      nrecs_scanned++;
842
      GRIB_CHECK(my_grib_set_double(gh, "missingValue", cdiDefaultMissval), 0);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
843

844
845
      int param = gribapiGetParam(gh);
      int leveltype1 = -1, leveltype2 = -1, lbounds, level_sf, level_unit;
846
      var_tile_t tiles = dummy_tiles;
847
      gribGetLevel(gh, &leveltype1, &leveltype2, &lbounds, &level1, &level2, &level_sf, &level_unit, &tiles);
848

849
      char varname[256];
850
851
      varname[0] = 0;
      gribapiGetString(gh, "shortName", varname, sizeof(varname));
852

853
      int tsteptype = gribapiGetTsteptype(gh);
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
854

855
      int vdate = 0, vtime = 0;
856
      gribapiGetValidityDateTime(gh, &vdate, &vtime);
857
      DateTime datetime = { .date = vdate, .time = vtime };
858
      /*
859
      printf("%d %d %d\n", vdate, vtime, leveltype1);
860
      */
861

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
862
      if ( datetime0.date == 10101 && datetime0.time == 0 )
863
        {
864
          if( datetimeCmp(datetime, datetime0) || !nrecs )       //Do we really need this condition? I have included it in order not to change the number of times gribapiGetDataDateTime() etc. get called. But if those are sideeffect-free, this condition should be removed.
865
866
867
868
869
870
871
872
            {
              datetime0 = datetime;

              gribapiGetDataDateTime(gh, &rdate, &rtime);

              fcast = gribapiTimeIsFC(gh);
              if ( fcast ) tunit = gribapiGetTimeUnits(gh);
            }
873
        }
874

Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
875
      if ( nrecs )
876
        {
877
          checkTimeResult result = checkTime(streamptr, gribapiVarSet(param, level1, level2, leveltype1, tsteptype, varname, tiles), &datetime, &datetime0);
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
878
          if ( result == CHECKTIME_STOP )
879
            {
880
              break;
881
            }
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
882
          else if ( result == CHECKTIME_SKIP )
883
            {
884
885
              gribWarning("Parameter already exist, skipped!", nrecs_scanned, tsID+1, varname, param, level1, level2);
              continue;
886
            }
Uwe Schulzweida's avatar
cleanup    
Uwe Schulzweida committed
887
          else if ( result == CHECKTIME_INCONSISTENT && warn_time )
888
889
890
891
892
            {
              gribWarning("Inconsistent verification time!", nrecs_scanned, tsID+1, varname, param, level1, level2);
              warn_time = FALSE;
            }
          assert(result == CHECKTIME_OK || result == CHECKTIME_INCONSISTENT);
893
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
894
895
      /*
      if ( ISEC1_AvgNum )
896
897
898
899
900
901
902
903
904
905
906
907
        {
          if (  taxis->numavg && warn_numavg && (taxis->numavg != ISEC1_AvgNum) )
            {
              Message("Change numavg from %d to %d not allowed!",
                      taxis->numavg, ISEC1_AvgNum);
              warn_numavg = FALSE;
            }
          else
            {
              taxis->numavg = ISEC1_AvgNum;
            }
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
908
909
910
911
      */
      nrecs++;

      if ( CDI_Debug )
912
913
914
        {
          char paramstr[32];
          cdiParamToString(param, paramstr, sizeof(paramstr));
Thomas Jahns's avatar
Thomas Jahns committed
915
          Message("%4u %8d name=%s id=%s ltype=%d lev1=%d lev2=%d vdate=%d vtime=%d",
916
                nrecs, (int)recpos, varname, paramstr, leveltype1, level1, level2, vdate, vtime);
917
        }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
918

919
920
      var_tile_t *ptiles = NULL;
      if ( memcmp(&tiles, &dummy_tiles, sizeof(var_tile_t)) != 0 ) ptiles = &tiles;
921
      gribapiAddRecord(streamptr, param, gh, recsize, recpos, datatype, comptype, varname,
922
                       leveltype1, leveltype2, lbounds, level1, level2, level_sf, level_unit, ptiles, 1);
923
924
925

      grib_handle_delete(gh);
      gh = NULL;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
926
927
    }

928
929
  if ( gh ) grib_handle_delete(gh);

Uwe Schulzweida's avatar
Uwe Schulzweida committed
930
931
  streamptr->rtsteps = 1;

932
933
  if ( nrecs == 0 ) return (CDI_EUFSTRUCT);

934
  cdi_generate_vars(streamptr);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
935

936
  int taxisID = -1;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
937
938
939
940
941
942
943
944
945
946
947
948
949
950
  if ( fcast )
    {
      taxisID = taxisCreate(TAXIS_RELATIVE);
      taxis->type  = TAXIS_RELATIVE;
      taxis->rdate = rdate;
      taxis->rtime = rtime;
      taxis->unit  = tunit;
    }
  else
    {
      taxisID = taxisCreate(TAXIS_ABSOLUTE);
      taxis->type  = TAXIS_ABSOLUTE;
    }