gribapi_utilities.c 30.8 KB
Newer Older
Uwe Schulzweida's avatar
Uwe Schulzweida committed
1
#ifdef HAVE_CONFIG_H
2
#include "config.h"
Uwe Schulzweida's avatar
Uwe Schulzweida committed
3
4
#endif

5
6
#ifdef HAVE_LIBGRIB_API

7
8
9
10
11
12
#include "gribapi_utilities.h"

#include "cdi.h"
#include "dmemory.h"
#include "error.h"
#include "gribapi.h"
13
#include "grid.h"
14
15
16
17
18
19

#include <assert.h>
#include <time.h>

#define FAIL_ON_GRIB_ERROR(function, gribHandle, key, ...) do\
{\
20
  const int errorCode = (int)function(gribHandle, key, __VA_ARGS__);  \
21
22
23
24
25
26
27
28
29
30
31
  if(errorCode)\
    {\
      fprintf(stderr, "%s:%d: Error in function `%s`: `%s` returned error code %d for key \"%s\"", __FILE__, __LINE__, __func__, #function, errorCode, key);\
      exit(errorCode);\
    }\
} while(0)

//A simple wrapper for grib_get_string() that returns a newly allocated string.
char* gribCopyString(grib_handle* gribHandle, const char* key)
{
  size_t length;
32
#ifdef HAVE_GRIB_GET_LENGTH
Thomas Jahns's avatar
Thomas Jahns committed
33
  if (!grib_get_length(gribHandle, key, &length))
34
    {
35
      char *result = (char *)Malloc(length);
Thomas Jahns's avatar
Thomas Jahns committed
36
37
38
39
      if (!grib_get_string(gribHandle, key, result, &length))
        result = (char *) Realloc(result, length);
      else
        {
40
          Free(result);
Thomas Jahns's avatar
Thomas Jahns committed
41
          result = NULL;
Thomas Jahns's avatar
Thomas Jahns committed
42
        }
Thomas Jahns's avatar
Thomas Jahns committed
43
      return result;
44
    }
Thomas Jahns's avatar
Thomas Jahns committed
45
46
  else
    return NULL;
47
48
49
50
51
52
#else
  length = 1024;         /* there's an implementation limit
                          * that makes strings longer than
                          * this unlikely in grib_api versions
                          * not providing grib_get_length */
  int rc;
53
  char *result = (char *) Malloc(length);
54
55
56
  while ((rc = grib_get_string(gribHandle, key, result, &length))
         == GRIB_BUFFER_TOO_SMALL || rc == GRIB_ARRAY_TOO_SMALL)
    {
Thomas Jahns's avatar
Thomas Jahns committed
57
58
59
      if (length <= 1024UL * 1024UL)
        {
          length *= 2;
60
          result = Realloc(result, length);
Thomas Jahns's avatar
Thomas Jahns committed
61
62
63
        }
      else
        break;
64
65
    }
  if (!rc)
66
    result = Realloc(result, length);
Thomas Jahns's avatar
Thomas Jahns committed
67
68
  else
    {
69
      Free(result);
Thomas Jahns's avatar
Thomas Jahns committed
70
71
72
      result = NULL;
    }
  return result;
Thomas Jahns's avatar
Thomas Jahns committed
73
#endif
74
75
76
77
78
79
}

//A simple wrapper for grib_get_string() for the usecase that the result is only compared to a given constant string.
//Returns true if the key exists and the value is equal to the given string.
bool gribCheckString(grib_handle* gribHandle, const char* key, const char* expectedValue)
{
80
81
82
  size_t expectedLength = strlen(expectedValue) + 1;
#ifdef HAVE_GRIB_GET_LENGTH
  size_t length;
83
84
  if(grib_get_length(gribHandle, key, &length)) return false;
  if(length != expectedLength) return false;
85
  char *value = (char *) Malloc(length);
86
  if(grib_get_string(gribHandle, key, value, &length)) return false;
87
  int rc = !strcmp(value, expectedValue);
88
  Free(value);
89
90
#else
  char *value = gribCopyString(gribHandle, key);
91
  int rc = value ? (strlen(value) + 1 == expectedLength ? !strcmp(value, expectedValue) : false) : false;
92
  Free(value);
93
94
#endif
  return rc;
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
}

//A simple wrapper for grib_get_long() for the usecase that the result is only compared to a given constant value.
//Returns true if the key exists and the value is equal to the given one.
bool gribCheckLong(grib_handle* gribHandle, const char* key, long expectedValue)
{
  long value;
  if(grib_get_long(gribHandle, key, &value)) return false;
  return value == expectedValue;
}

//A simple wrapper for grib_get_long() for the usecase that failure to fetch the value is fatal.
long gribGetLong(grib_handle* gh, const char* key)
{
  long result;
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, key, &result);
  return result;
}

//A simple wrapper for grib_get_long() for the usecase that a default value is used in the case that the operation fails.
long gribGetLongDefault(grib_handle* gribHandle, const char* key, long defaultValue)
{
  long result;
118
119
  if ( grib_get_long(gribHandle, key, &result) || result == GRIB_MISSING_LONG )
    result = defaultValue;
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
  return result;
}

//A simple wrapper for grib_get_double() for the usecase that failure to fetch the value is fatal.
double gribGetDouble(grib_handle* gh, const char* key)
{
  double result;
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, key, &result);
  return result;
}

//A sample wrapper for grib_get_double() for the usecase that a default value is used in the case that the operation fails.
double gribGetDoubleDefault(grib_handle* gribHandle, const char* key, double defaultValue)
{
  double result;
135
136
137
  if ( grib_get_double(gribHandle, key, &result)
       || IS_EQUAL(result, GRIB_MISSING_DOUBLE) )
    result = defaultValue;
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
  return result;
}

//A simple wrapper for grib_get_size() for the usecase that failure to fetch the value is fatal.
size_t gribGetArraySize(grib_handle* gribHandle, const char* key)
{
  size_t result;
  FAIL_ON_GRIB_ERROR(grib_get_size, gribHandle, key, &result);
  return result;
}

//A simple wrapper for grib_get_double_array() for the usecase that failure to fetch the data is fatal.
void gribGetDoubleArray(grib_handle* gribHandle, const char* key, double* array)
{
  size_t valueCount = gribGetArraySize(gribHandle, key);
  FAIL_ON_GRIB_ERROR(grib_get_double_array, gribHandle, key, array, &valueCount);
}

//A simple wrapper for grib_get_long_array() for the usecase that failure to fetch the data is fatal.
void gribGetLongArray(grib_handle* gribHandle, const char* key, long* array)
{
  size_t valueCount = gribGetArraySize(gribHandle, key);
  FAIL_ON_GRIB_ERROR(grib_get_long_array, gribHandle, key, array, &valueCount);
}


//We need the edition number so frequently, that it's convenient to give it its own function.
long gribEditionNumber(grib_handle* gh)
{
  return gribGetLong(gh, "editionNumber");
}

//This return value of this should be passed to a call to resetTz(), it is a malloc'ed string with the content of the TZ environment variable before the call (or NULL if that was not set).
static char* setUtc()
{
  char* temp = getenv("TZ"), *result = NULL;
174
  if(temp) result = strdup(temp);
175
176
177
178
179
180
181
182
183
184
  setenv("TZ", "UTC", 1);
  return result;
}

//Undoes the effect of setUtc(), pass to it the return value of the corresponding setUtc() call, it will free the string.
static void resetTz(char* savedTz)
{
  if(savedTz)
    {
      setenv("TZ", savedTz, 1);
185
      Free(savedTz);
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    }
  else
    {
      unsetenv("TZ");
    }
}

//This function uses the system functions to normalize the date representation according to the gregorian calendar.
//Returns zero on success.
static int normalizeDays(struct tm* me)
{
  char* savedTz = setUtc();     //Ensure that mktime() does not interprete the date according to our local time zone.

  int result = mktime(me) == (time_t)-1;        //This does all the heavy lifting.

  resetTz(savedTz);
  return result;
}

//Returns zero on success.
static int addSecondsToDate(struct tm* me, long long amount)
{
  //It is irrelevant here whether days are zero or one based, the correction would have be undone again so that it is effectless.
  long long seconds = ((me->tm_mday*24ll + me->tm_hour)*60 + me->tm_min)*60 + me->tm_sec;    //The portion of the date that uses fixed increments.
  seconds += amount;
Thomas Jahns's avatar
Thomas Jahns committed
211
212
213
214
215
216
217
  me->tm_mday = (int)(seconds / 24 / 60 / 60);
  seconds -= (long long)me->tm_mday * 24 * 60 * 60;
  me->tm_hour = (int)(seconds / 60 / 60);
  seconds -= (long long)me->tm_hour * 60 * 60;
  me->tm_min = (int)(seconds / 60);
  seconds -= (long long)(me->tm_min * 60);
  me->tm_sec = (int)seconds;
218
219
220
221
222
223
224
  return normalizeDays(me);
}

static void addMonthsToDate(struct tm* me, long long amount)
{
  long long months = me->tm_year*12ll + me->tm_mon;
  months += amount;
Thomas Jahns's avatar
Thomas Jahns committed
225
226
227
  me->tm_year = (int)(months/12);
  months -= (long long)me->tm_year*12;
  me->tm_mon = (int)months;
228
229
230
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
}

//unit is a value according to code table 4.4 of the GRIB2 specification, returns non-zero on error
static int addToDate(struct tm* me, long long amount, long unit)
{
  switch(unit)
    {
      case 0: return addSecondsToDate(me,       60*amount);   // minute
      case 1: return addSecondsToDate(me,    60*60*amount);   // hour
      case 2: return addSecondsToDate(me, 24*60*60*amount);   // day

      case 3: addMonthsToDate(me,        amount); return 0;   // month
      case 4: addMonthsToDate(me,     12*amount); return 0;   // year
      case 5: addMonthsToDate(me,  10*12*amount); return 0;   // decade
      case 6: addMonthsToDate(me,  30*12*amount); return 0;   // normal
      case 7: addMonthsToDate(me, 100*12*amount); return 0;   // century

      case 10: return addSecondsToDate(me,  3*60*60*amount);  // eighth of a day
      case 11: return addSecondsToDate(me,  6*60*60*amount);  // quarter day
      case 12: return addSecondsToDate(me, 12*60*60*amount);  // half day
      case 13: return addSecondsToDate(me,          amount);  // second

      default: return 1;        //reserved, unknown, or missing
    }
}

static char* makeDateString(struct tm* me)
{
256
  char *result= (char *) Malloc(4+1+ 2+1+ 2+1+ 2+1+ 2+1+ 2+ 4+ 1);
257
258
  sprintf(result, "%04d-%02d-%02dT%02d:%02d:%02d.000", me->tm_year + 1900, me->tm_mon + 1, me->tm_mday, me->tm_hour, me->tm_min, me->tm_sec);
  return result;
259
260
261
262
263
264
265
266
267
268
269
270
}

//FIXME: This ignores any calendar definition that might be present.
//XXX: Identification templates are not implemented in grib_api-1.12.3, so even if I implemented the other calendars now, it wouldn't be possible to use them.
static int getAvailabilityOfRelativeTimes(grib_handle* gh, bool* outHaveForecastTime, bool* outHaveTimeRange)
{
  switch(gribGetLong(gh, "productDefinitionTemplateNumber"))
    {
      case 20: case 30: case 31: case 254: case 311: case 2000:
        *outHaveForecastTime = false, *outHaveTimeRange = false;
        return 0;

271
      //case 55 and case 40455 are the same: 55 is the proposed standard value, 40455 is the value in the local use range that is used by the dwd until the standard is updated.
272
273
274
275
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
      case 15: case 32: case 33: case 40: case 41: case 44: case 45: case 48:
      case 51: case 53: case 54: case 55: case 56: case 60:
      case 1000: case 1002: case 1100: case 40033: case 40455: case 40456:
276
277
278
        *outHaveForecastTime = true, *outHaveTimeRange = false;
        return 0;

279
280
281
      case 8: case 9: case 10: case 11: case 12: case 13: case 14:
      case 34: case 42: case 43: case 46: case 47: case 61: case 67: case 68: case 91:
      case 1001: case 1101: case 40034:
282
283
284
285
286
287
288
289
        *outHaveForecastTime = true, *outHaveTimeRange = true;
        return 0;

      default:
        return 1;
    }
}

290

291
char* gribMakeTimeString(grib_handle* gh, CdiTimeType timeType)
292
293
{
  //Get the parts of the reference date.
294
295
296
297
298
  struct tm date;
  date.tm_mon = (int)gribGetLong(gh, "month") - 1;   //months are zero based in struct tm and one based in GRIB
  date.tm_mday = (int)gribGetLong(gh, "day");
  date.tm_hour = (int)gribGetLong(gh, "hour");
  date.tm_min = (int)gribGetLong(gh, "minute");
299

300
301
  if(gribEditionNumber(gh) == 1)
    {
Thomas Jahns's avatar
Thomas Jahns committed
302
      date.tm_year = (int)gribGetLong(gh, "yearOfCentury");  //years are -1900 based both in struct tm and GRIB1
303
304
305
    }
  else
    {
Thomas Jahns's avatar
Thomas Jahns committed
306
307
      date.tm_year = (int)gribGetLong(gh, "year") - 1900;   //years are -1900 based in struct tm and zero based in GRIB2
      date.tm_sec = (int)gribGetLong(gh, "second");
308

309
310
      //If the start or end time are requested, we need to take the relative times into account.
      if(timeType != kCdiTimeType_referenceTime)
311
        {
312
313
314
315
316
317
318
          //Determine whether we have a forecast time and a time range.
          bool haveForecastTime, haveTimeRange;
          if(getAvailabilityOfRelativeTimes(gh, &haveForecastTime, &haveTimeRange)) return NULL;
          if(timeType == kCdiTimeType_endTime && !haveTimeRange) return NULL;     //tell the caller that the requested time does not exist

          //If we have relative times, apply the relative times to the date
          if(haveForecastTime)
319
            {
320
321
322
323
324
325
326
327
328
329
              long offset = gribGetLongDefault(gh, "forecastTime", 0);  //if(stepUnits == indicatorOfUnitOfTimeRange) assert(startStep == forecastTime)
              long offsetUnit = gribGetLongDefault(gh, "indicatorOfUnitOfTimeRange", 255);
              if(addToDate(&date, offset, offsetUnit)) return NULL;
              if(timeType == kCdiTimeType_endTime)
                {
                  assert(haveTimeRange);
                  long range = gribGetLongDefault(gh, "lengthOfTimeRange", 0);       //if(stepUnits == indicatorOfUnitForTimeRange) assert(endStep == startStep + lengthOfTimeRange)
                  long rangeUnit = gribGetLongDefault(gh, "indicatorOfUnitForTimeRange", 255);
                  if(addToDate(&date, range, rangeUnit)) return NULL;
                }
330
331
332
333
334
335
336
337
            }
        }
    }

  //Bake the date into a string.
  return makeDateString(&date);
}

338

339
340
int gribapiTimeIsFC(grib_handle *gh)
{
341
  if (gribEditionNumber(gh) <= 1) return true;
342
343
344
345
346
347

  long sigofrtime;
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "significanceOfReferenceTime", &sigofrtime);
  return sigofrtime != 3;
}

348

349
struct cdiGribAPI_ts_str_map_elem cdiGribAPI_ts_str_map[] = {
350
  // clang-format off
351
  [TSTEP_INSTANT] = {  0, "instant" },
352
353
354
355
356
357
358
359
360
361
  [TSTEP_AVG]     = {  8, "avg" },
  [TSTEP_ACCUM]   = {  8, "accum" },
  [TSTEP_MAX]     = {  8, "max" },
  [TSTEP_MIN]     = {  8, "min" },
  [TSTEP_DIFF]    = {  8, "diff" },
  [TSTEP_RMS]     = {  8, "rms" },
  [TSTEP_SD]      = {  8, "sd" },
  [TSTEP_COV]     = {  8, "cov" },
  [TSTEP_RATIO]   = {  8, "ratio" },
  [TSTEP_SUM]     = {  8, "sum" },
362
                    {  0, "" }
363
  // clang-format on
364
365
366
};


367
368
369
//Fetches the value of the "stepType" key and converts it into a constant in the TSTEP_* range.
int gribapiGetTsteptype(grib_handle *gh)
{
370
371
  size_t len = 256;
  char stepType[256];
372
373
374
375
376
  int tsteptype = TSTEP_INSTANT;
  static bool lprint = true;

  if ( gribapiTimeIsFC(gh) )
    {
377
      const int status = grib_get_string(gh, "stepType", stepType, &len);
378
379
      if ( status == 0 && len > 1 && len < 256 )
        {
380
381
382
383
384
385
386
387
          for (int i = TSTEP_INSTANT; cdiGribAPI_ts_str_map[i].sname[0]; ++i)
            if ( strncmp(cdiGribAPI_ts_str_map[i].sname, stepType, len) == 0 )
              {
                tsteptype = i;
                goto tsteptypeFound;
              }

          if ( lprint )
388
389
390
391
392
393
            {
              Message("Time stepType %s unsupported, set to instant!", stepType);
              lprint = false;
            }
          // printf("stepType: %s %ld %d\n", stepType, len, tsteptype);
        }
394

395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#ifdef HIRLAM_EXTENSIONS
      {
      // Normaly cdo looks in grib for attribute called "stepType", see above.
      // BUT NWP models such as Hirlam and Harmonie 37h1.2, use "timeRangeIndicator" instead!
      // Where for example:       0: for instanteneous fields; 4: for accumulated fields
      //  0:   Forecast product valid at reference time + P1
      //  2:   Product with a valid time ranging between reference time + P1 and reference time + P2
      //  4:   Accumulation (reference time + P1 to reference time + P2)
      //  5:   Difference(reference time + P2 minus reference time + P1) product considered valid at reference time + P2
      // More details on WMO standards:
      //               http://www.wmo.int/pages/prog/www/WDM/Guides/Guide-binary-2.html
      //tsteptype = TSTEP_INSTANT;  // default value for any case
      long timeRangeIND = 0; // typically 0: for instanteneous fields; 4: for accumulated fields
      int rc = grib_get_long(gh, "timeRangeIndicator", &timeRangeIND);
      if (rc != 0) {
            //if ( lprint )
411
412
            Warning("Could not get 'stepType' either 'timeRangeIndicator'. Using default!");
            return tsteptype;
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
      }
      extern int cdiGribUseTimeRangeIndicator;
      cdiGribUseTimeRangeIndicator = 1;
      switch ( timeRangeIND )
          {
              case 0:  tsteptype = TSTEP_INSTANT; break;
              case 2:  tsteptype = TSTEP_INSTANT2;
                       strcpy(stepType, "instant2");  // was incorrectly set before into accum
                       break;
              case 4:  tsteptype = TSTEP_ACCUM; break;
              case 5:  tsteptype = TSTEP_DIFF; break;
              default:
                if ( lprint )
                {
                  if (CDI_Debug)
                      Warning("timeRangeIND = %d;  stepType= %s; tsteptype=%d unsupported timeRangeIND at the moment, set to instant!", timeRangeIND, stepType, tsteptype);
429
                  lprint = false;
430
431
432
433
434
435
436
                }
                break;
          }
      if (CDI_Debug)
          Warning("timeRangeIND = %d;  stepType= %s; tsteptype=%d", timeRangeIND, stepType, tsteptype);
      }
#endif // HIRLAM_EXTENSIONS
437
    }
438

439
  tsteptypeFound:
440
  return tsteptype;
441
442
}

443

444
445
446
447
448
int gribGetDatatype(grib_handle* gribHandle)
{
  int datatype;
  if(gribEditionNumber(gribHandle) > 1 && gribCheckString(gribHandle, "packingType", "grid_ieee"))
    {
449
      datatype = gribCheckLong(gribHandle, "precision", 1) ? CDI_DATATYPE_FLT32 : CDI_DATATYPE_FLT64;
450
451
452
453
    }
  else
    {
      long bitsPerValue;
454
      datatype = (!grib_get_long(gribHandle, "bitsPerValue", &bitsPerValue) && bitsPerValue > 0 && bitsPerValue <= 32) ? (int)bitsPerValue : CDI_DATATYPE_PACK;
455
456
457
458
    }
  return datatype;
}

459

460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
int gribapiGetParam(grib_handle *gh)
{
  long pdis, pcat, pnum;
  if ( gribEditionNumber(gh) <= 1 )
    {
      pdis = 255;
      FAIL_ON_GRIB_ERROR(grib_get_long, gh, "table2Version", &pcat);
      FAIL_ON_GRIB_ERROR(grib_get_long, gh, "indicatorOfParameter", &pnum);
    }
  else
    {
      FAIL_ON_GRIB_ERROR(grib_get_long, gh, "discipline", &pdis);
      if(grib_get_long(gh, "parameterCategory", &pcat)) pcat = 0;
      if(grib_get_long(gh, "parameterNumber", &pnum)) pnum = 0;
    }
  return cdiEncodeParam((int)pnum, (int)pcat, (int)pdis);
}

478

479
480
481
int gribapiGetGridType(grib_handle *gh)
{
  int gridtype = GRID_GENERIC;
482
  const long gridDefinitionTemplateNumber = gribGetLongDefault(gh, "gridDefinitionTemplateNumber", -1);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
483
  switch (gridDefinitionTemplateNumber)
484
485
486
487
488
489
490
    {
      case  GRIB2_GTYPE_LATLON:
        gridtype = ( gribGetLong(gh, "Ni") == (long) GRIB_MISSING_LONG ) ? GRID_GENERIC : GRID_LONLAT;
        break;
      case  GRIB2_GTYPE_GAUSSIAN:
        gridtype = ( gribGetLong(gh, "Ni") == (long) GRIB_MISSING_LONG ) ? GRID_GAUSSIAN_REDUCED : GRID_GAUSSIAN;
        break;
491
      case GRIB2_GTYPE_LATLON_ROT:   gridtype = GRID_PROJECTION; break;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
492
493
      case GRIB2_GTYPE_LCC:          gridtype = CDI_PROJ_LCC; break;
      case GRIB2_GTYPE_STERE:        gridtype = CDI_PROJ_STERE; break;
494
495
496
      case GRIB2_GTYPE_SPECTRAL:     gridtype = GRID_SPECTRAL; break;
      case GRIB2_GTYPE_GME:          gridtype = GRID_GME; break;
      case GRIB2_GTYPE_UNSTRUCTURED: gridtype = GRID_UNSTRUCTURED; break;
497
498
499
500
501
502
503
      default:
        {
          char mesg[256];
          size_t len = sizeof(mesg);
          if (grib_get_string(gh, "gridType", mesg, &len) != 0) mesg[0] = 0;
          Warning("gridDefinitionTemplateNumber %d unsupported (gridType=%s)!", gridDefinitionTemplateNumber, mesg);
        }
504
505
506
507
508
509
510
511
512
513
514
    }

  return gridtype;
}

static
int gribapiGetIsRotated(grib_handle *gh)
{
  return gribGetLongDefault(gh, "gridDefinitionTemplateNumber", -1) == GRIB2_GTYPE_LATLON_ROT;
}

515
516
517
518
519
520
521
522

size_t gribapiGetGridsize(grib_handle *gh)
{
  size_t gridsize;
  FAIL_ON_GRIB_ERROR(grib_get_size, gh, "values", &gridsize);
  return gridsize;
}

Uwe Schulzweida's avatar
Uwe Schulzweida committed
523
524
static
void gribapiGetGridGaussianReduced(grib_handle *gh, grid_t *grid, int editionNumber, size_t numberOfPoints)
525
{
526
  long lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
527
528
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "numberOfParallelsBetweenAPoleAndTheEquator", &lpar);
  grid->np = (int)lpar;
529

Uwe Schulzweida's avatar
Uwe Schulzweida committed
530
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "Nj", &lpar);
531
  size_t nlat = (size_t)lpar;
532

Uwe Schulzweida's avatar
Uwe Schulzweida committed
533
  grid->size = numberOfPoints;
534

535
  grid->reducedPointsSize = (int)nlat;
536
537
538
  grid->rowlon = (int *) Malloc(nlat * sizeof(int));
  long *pl     = (long *) Malloc(nlat * sizeof(long));
  size_t dummy = nlat;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
539
  FAIL_ON_GRIB_ERROR(grib_get_long_array, gh, "pl", pl, &dummy);
540
  for ( size_t i = 0; i < nlat; ++i ) grid->rowlon[i] = (int)pl[i];
Uwe Schulzweida's avatar
Uwe Schulzweida committed
541
  Free(pl);
542

543
  grid->y.size  = nlat;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
  grid->x.inc   = 0;
  grid->y.inc   = 0;
  grid->x.flag  = 0;
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "longitudeOfFirstGridPointInDegrees", &grid->x.first);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "longitudeOfLastGridPointInDegrees",  &grid->x.last);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "latitudeOfFirstGridPointInDegrees",  &grid->y.first);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "latitudeOfLastGridPointInDegrees",   &grid->y.last);

  // FAIL_ON_GRIB_ERROR(grib_get_double, gh, "iDirectionIncrementInDegrees", &grid->x.inc);
  // if ( IS_EQUAL(grid->x.inc, GRIB_MISSING_DOUBLE) ) grid->x.inc = 0;

  /* if ( IS_NOT_EQUAL(grid->x.first, 0) || IS_NOT_EQUAL(grid->x.last, 0) ) */
  {
    if ( grid->x.size > 1 )
558
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
559
560
561
        if ( (grid->x.first > grid->x.last) && (grid->x.first >= 180) ) grid->x.first -= 360;

        if ( editionNumber <= 1 )
562
          {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
563
564
            /* correct xinc if necessary */
            if ( IS_EQUAL(grid->x.first, 0) && grid->x.last > 354 )
565
              {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
566
567
                double xinc = 360. / grid->x.size;
                if ( fabs(grid->x.inc-xinc) > 0.0 )
568
                  {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
569
570
                    grid->x.inc = xinc;
                    if ( CDI_Debug ) Message("set xinc to %g", grid->x.inc);
571
572
573
                  }
              }
          }
574
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
575
576
577
578
579
580
    grid->x.flag = 2;
  }
  grid->y.flag = 0;
  /* if ( IS_NOT_EQUAL(grid->y.first, 0) || IS_NOT_EQUAL(grid->y.last, 0) ) */
  {
    if ( grid->y.size > 1 )
581
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
582
        if ( editionNumber <= 1 )
583
584
585
          {
          }
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
586
587
588
589
590
591
592
593
594
    grid->y.flag = 2;
  }
}

static
void gribapiGetGridRegular(grib_handle *gh, grid_t *grid, int editionNumber, int gridtype, size_t numberOfPoints)
{
  long lpar;
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "Ni", &lpar);
595
  const size_t nlon = (size_t) lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
596
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "Nj", &lpar);
597
  const size_t nlat = (size_t) lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
598
599

  if ( gridtype == GRID_GAUSSIAN )
600
601
602
    {
      FAIL_ON_GRIB_ERROR(grib_get_long, gh, "numberOfParallelsBetweenAPoleAndTheEquator", &lpar);
      grid->np = (int)lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
603
    }
604

Uwe Schulzweida's avatar
Uwe Schulzweida committed
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
  if ( numberOfPoints != nlon*nlat )
    Error("numberOfPoints (%zu) and gridSize (%zu) differ!", numberOfPoints, nlon*nlat);

  grid->size   = numberOfPoints;
  grid->x.size = nlon;
  grid->y.size = nlat;
  grid->x.inc  = 0;
  grid->y.inc  = 0;
  grid->x.flag = 0;
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "longitudeOfFirstGridPointInDegrees", &grid->x.first);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "longitudeOfLastGridPointInDegrees",  &grid->x.last);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "latitudeOfFirstGridPointInDegrees",  &grid->y.first);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "latitudeOfLastGridPointInDegrees",   &grid->y.last);
  if ( nlon > 1 )
    FAIL_ON_GRIB_ERROR(grib_get_double, gh, "iDirectionIncrementInDegrees", &grid->x.inc);
  if ( gridtype == GRID_LONLAT && nlat > 1 )
    FAIL_ON_GRIB_ERROR(grib_get_double, gh, "jDirectionIncrementInDegrees", &grid->y.inc);

  long iscan = 0, jscan = 0;
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "iScansNegatively", &iscan);
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "jScansPositively", &jscan);
  if (  iscan ) grid->x.inc = - grid->x.inc;
  if ( !jscan ) grid->y.inc = - grid->y.inc;

  if ( grid->x.inc < -999 || grid->x.inc > 999 ) grid->x.inc = 0;
  if ( grid->y.inc < -999 || grid->y.inc > 999 ) grid->y.inc = 0;

  /* if ( IS_NOT_EQUAL(grid->x.first, 0) || IS_NOT_EQUAL(grid->x.last, 0) ) */
  {
    if ( grid->x.size > 1 )
635
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
636
637
638
639
640
641
642
643
644
        //if ( editionNumber <= 1 )
        {
          if ( grid->x.last < grid->x.first )
            {
              if ( grid->x.first >= 180 )
                grid->x.first -= 360;
              else
                grid->x.last += 360;
            }
645

Uwe Schulzweida's avatar
Uwe Schulzweida committed
646
647
648
649
650
651
652
653
654
655
656
          // correct xinc if necessary
          if ( IS_EQUAL(grid->x.first, 0) && grid->x.last > 354 && grid->x.last < 360 )
            {
              double xinc = 360. / grid->x.size;
              if ( fabs(grid->x.inc-xinc) > 0.0 )
                {
                  grid->x.inc = xinc;
                  if ( CDI_Debug ) Message("set xinc to %g", grid->x.inc);
                }
            }
        }
657
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
658
659
660
661
662
663
664
    grid->x.flag = 2;
  }

  grid->y.flag = 0;
  /* if ( IS_NOT_EQUAL(grid->y.first, 0) || IS_NOT_EQUAL(grid->y.last, 0) ) */
  {
    if ( grid->y.size > 1 )
665
      {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
666
        if ( editionNumber <= 1 )
667
668
669
          {
          }
      }
Uwe Schulzweida's avatar
Uwe Schulzweida committed
670
671
672
673
674
675
676
677
678
    grid->y.flag = 2;
  }
}

static
void gribapiGetGridProj(grib_handle *gh, grid_t *grid, size_t numberOfPoints)
{
  long lpar;
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "Nx", &lpar);
679
  const size_t nlon = (size_t)lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
680
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "Ny", &lpar);
681
  const size_t nlat = (size_t)lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714

  if ( numberOfPoints != nlon*nlat )
    Error("numberOfPoints (%zu) and gridSize (%zu) differ!", numberOfPoints, nlon*nlat);

  grid->size  = numberOfPoints;
  grid->x.size = nlon;
  grid->y.size = nlat;

  double xinc, yinc;
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "DxInMetres", &xinc);
  FAIL_ON_GRIB_ERROR(grib_get_double, gh, "DyInMetres", &yinc);

  grid->x.first = 0;
  grid->x.last  = 0;
  grid->x.inc   = xinc;
  grid->y.first = 0;
  grid->y.last  = 0;
  grid->y.inc   = yinc;
  grid->x.flag  = 2;
  grid->y.flag  = 2;
}

static
void gribapiGetGridSpectral(grib_handle *gh, grid_t *grid, size_t datasize)
{
  size_t len = 256;
  char typeOfPacking[256];
  FAIL_ON_GRIB_ERROR(grib_get_string, gh, "packingType", typeOfPacking, &len);
  grid->lcomplex = 0;
  if ( strncmp(typeOfPacking, "spectral_complex", len) == 0 ) grid->lcomplex = 1;

  grid->size = datasize;

715
  long lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
716
717
718
719
720
721
722
723
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "J", &lpar);
  grid->trunc = (int)lpar;
}

static
void gribapiGetGridGME(grib_handle *gh, grid_t *grid, size_t numberOfPoints)
{
  grid->size = numberOfPoints;
724
725

  long lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
  if ( grib_get_long(gh, "nd", &lpar) == 0 ) grid->gme.nd  = (int)lpar;
  if ( grib_get_long(gh, "Ni", &lpar) == 0 ) grid->gme.ni  = (int)lpar;
  if ( grib_get_long(gh, "n2", &lpar) == 0 ) grid->gme.ni2 = (int)lpar;
  if ( grib_get_long(gh, "n3", &lpar) == 0 ) grid->gme.ni3 = (int)lpar;
}

static
void gribapiGetGridUnstructured(grib_handle *gh, grid_t *grid, size_t numberOfPoints)
{
  unsigned char uuid[CDI_UUID_SIZE];
  /*
    char reference_link[8192];
    size_t len = sizeof(reference_link);
    reference_link[0] = 0;
  */
  grid->size = numberOfPoints;

743
  long lpar;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
744
  if ( grib_get_long(gh, "numberOfGridUsed", &lpar) == 0 )
745
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
746
747
748
749
750
751
752
753
754
755
756
      grid->number   = (int)lpar;
      if ( grib_get_long(gh, "numberOfGridInReference", &lpar) == 0 )
        grid->position = (int)lpar;
      /*
        if ( grib_get_string(gh, "gridDescriptionFile", reference_link, &len) == 0 )
        {
        if ( strncmp(reference_link, "file://", 7) == 0 )
        grid->reference = strdupx(reference_link);
        }
      */
      size_t len = (size_t)CDI_UUID_SIZE;
757
      if ( grib_get_bytes(gh, "uuidOfHGrid", uuid, &len) == 0) memcpy(grid->uuid, uuid, CDI_UUID_SIZE);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
758
759
    }
}
760

Uwe Schulzweida's avatar
Uwe Schulzweida committed
761
762
763
764
static
void gribapiGetGridGeneric(grib_handle *gh, grid_t *grid, size_t numberOfPoints)
{
  long lpar;
765
766
  const size_t nlon = (grib_get_long(gh, "Ni", &lpar) == 0) ? (size_t)lpar : 0;
  const size_t nlat = (grib_get_long(gh, "Nj", &lpar) == 0) ? (size_t)lpar : 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
767
768
769

  grid->size = numberOfPoints;

770
771
772
  const bool lgeneric = (nlon > 0 && nlat > 0 && nlon*nlat == numberOfPoints);
  grid->x.size = lgeneric ? nlon : 0;
  grid->y.size = lgeneric ? nlat : 0;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
773
}
774

Uwe Schulzweida's avatar
Uwe Schulzweida committed
775
//TODO: Simplify by use of the convenience functions (gribGetLong(), gribGetLongDefault(), etc.).
776
bool gribapiGetGrid(grib_handle *gh, grid_t *grid)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
777
{
778
  bool uvRelativeToGrid = false;
779
  const long editionNumber = gribEditionNumber(gh);
Uwe Schulzweida's avatar
Uwe Schulzweida committed
780
781
  int gridtype = gribapiGetGridType(gh);
  int projtype = (gridtype == GRID_PROJECTION && gribapiGetIsRotated(gh)) ? CDI_PROJ_RLL : CDI_UNDEFID;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
782
  if (gridtype == CDI_PROJ_LCC || gridtype == CDI_PROJ_STERE)
Uwe Schulzweida's avatar
Uwe Schulzweida committed
783
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
784
      projtype = gridtype;
Uwe Schulzweida's avatar
Uwe Schulzweida committed
785
786
787
788
789
790
791
792
793
794
795
796
      gridtype = GRID_PROJECTION;
    }
  /*
  if ( streamptr->unreduced && gridtype == GRID_GAUSSIAN_REDUCED )
    {
      gridtype = GRID_GAUSSIAN;
      ISEC2_NumLon = 2*ISEC2_NumLat;
      ISEC4_NumValues = ISEC2_NumLon*ISEC2_NumLat;
    }
  */
  grid_init(grid);
  cdiGridTypeInit(grid, gridtype, 0);
797

Uwe Schulzweida's avatar
Uwe Schulzweida committed
798
799
800
801
802
  size_t datasize;
  FAIL_ON_GRIB_ERROR(grib_get_size, gh, "values", &datasize);
  long lpar;
  FAIL_ON_GRIB_ERROR(grib_get_long, gh, "numberOfPoints", &lpar);
  size_t numberOfPoints = (size_t) lpar;
803

Uwe Schulzweida's avatar
Uwe Schulzweida committed
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
  if ( gridtype == GRID_LONLAT || gridtype == GRID_GAUSSIAN || projtype == CDI_PROJ_RLL )
    {
      gribapiGetGridRegular(gh, grid, editionNumber, gridtype, numberOfPoints);
    }
  else if ( gridtype == GRID_GAUSSIAN_REDUCED )
    {
      gribapiGetGridGaussianReduced(gh, grid, editionNumber, numberOfPoints);
    }
  else if ( projtype == CDI_PROJ_LCC )
    {
      gribapiGetGridProj(gh, grid, numberOfPoints);
    }
  else if ( projtype == CDI_PROJ_STERE )
    {
      gribapiGetGridProj(gh, grid, numberOfPoints);
    }
  else if ( gridtype == GRID_SPECTRAL )
    {
      gribapiGetGridSpectral(gh, grid, datasize);
823
824
825
    }
  else if ( gridtype == GRID_GME )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
826
      gribapiGetGridGME(gh, grid, numberOfPoints);
827
828
829
    }
  else if ( gridtype == GRID_UNSTRUCTURED )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
830
      gribapiGetGridUnstructured(gh, grid, numberOfPoints);
831
832
833
    }
  else if ( gridtype == GRID_GENERIC )
    {
Uwe Schulzweida's avatar
Uwe Schulzweida committed
834
      gribapiGetGridGeneric(gh, grid, numberOfPoints);
835
836
837
838
    }
  else
    {
      Error("Unsupported grid type: %s", gridNamePtr(gridtype));
839
840
    }

Uwe Schulzweida's avatar
Uwe Schulzweida committed
841
  if ( gridtype == GRID_GAUSSIAN || gridtype == GRID_LONLAT || projtype == CDI_PROJ_RLL || projtype == CDI_PROJ_LCC )
842
843
844
845
    {
      long temp;
      GRIB_CHECK(grib_get_long(gh, "uvRelativeToGrid", &temp), 0);
      assert(temp == 0 || temp == 1);
846
      uvRelativeToGrid = (bool)temp;
847
    }
848

Uwe Schulzweida's avatar
Uwe Schulzweida committed
849
  if ( gridtype == GRID_GAUSSIAN || gridtype == GRID_LONLAT || gridtype == GRID_PROJECTION )
850
    {
Thomas Jahns's avatar
Thomas Jahns committed
851
852
853
854
855
856
857
      long temp;
      GRIB_CHECK(grib_get_long(gh, "iScansNegatively", &temp), 0);
      grid->iScansNegatively = (bool)temp;
      GRIB_CHECK(grib_get_long(gh, "jScansPositively", &temp), 0);
      grid->jScansPositively = (bool)temp;
      GRIB_CHECK(grib_get_long(gh, "jPointsAreConsecutive", &temp), 0);
      grid->jPointsAreConsecutive = (bool)temp;
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
      grid->scanningMode = 128*grid->iScansNegatively + 64*grid->jScansPositively + 32*grid->jPointsAreConsecutive;
      /* scanningMode  = 128 * iScansNegatively + 64 * jScansPositively + 32 * jPointsAreConsecutive;
                   64  = 128 * 0                + 64 *        1         + 32 * 0
                   00  = 128 * 0                + 64 *        0         + 32 * 0
                   96  = 128 * 0                + 64 *        1         + 32 * 1
         Default / implicit scanning mode is 64:
                            i and j scan positively, i points are consecutive (row-major)        */
#ifdef HIRLAM_EXTENSIONS
      if (cdiDebugExt>=30)
      {
        //  indicatorOfParameter=33,indicatorOfTypeOfLevel=105,level
        long paramId, levelTypeId, levelId;
        GRIB_CHECK(grib_get_long(gh, "indicatorOfParameter", &paramId), 0);
        GRIB_CHECK(grib_get_long(gh, "indicatorOfTypeOfLevel", &levelTypeId), 0);
        GRIB_CHECK(grib_get_long(gh, "level", &levelId), 0);
        Message("(param,ltype,level) = (%3d,%3d,%4d); Scanning mode = %02d -> bits:(%1d.%1d.%1d)*32;  uvRelativeToGrid = %02d",\
                (int)paramId, (int)levelTypeId, (int)levelId,
Thomas Jahns's avatar
Thomas Jahns committed
875
                grid->scanningMode,grid->jPointsAreConsecutive,
876
877
                grid->jScansPositively, grid->iScansNegatively,
                uvRelativeToGrid);
878
879
880
881
      }
#endif //HIRLAM_EXTENSIONS
    }

882
  grid->type  = gridtype;
883
  grid->projtype  = projtype;
884
885

  return uvRelativeToGrid;
886
}
887
#endif
888
889
890
891
892
893
894
895
896
/*
 * Local Variables:
 * c-file-style: "Java"
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * show-trailing-whitespace: t
 * require-trailing-newline: t
 * End:
 */