Example #1
0
int main(int argc, char* argv[]) {
  grib_handle *h=NULL;
  grib_context* c=NULL;
  FILE* fin=NULL;
  FILE* fout=NULL;
  char* finname;
  char* ofilename;
  char defofilename[]="ccsds_perf.out";
  double *values=NULL;
  int append=0;
  size_t nvalues=0;
  int count,e=0;
  int repeatccsds=1;
  int repeatsimple=1;
  grib_timer *tes,*tds,*tej,*tdj;
  char grid_ccsds[]="grid_ccsds";
  size_t grid_ccsds_l=strlen(grid_ccsds);
  char grid_simple[]="grid_simple";
  size_t grid_simple_l=strlen(grid_simple);
  char packingType[50]={0,};
  size_t len=50;
  char param[50]={0,};
  char gridType[50]={0,};
  char outfilename[255]={0,};
  size_t filesize_ccsds=0;
  size_t filesize_simple=0;
  double perc=0;
  long bitsPerValue=0;
  int iarg=1;
  char grid[20]={0,};
  char shortName[20]={0,};
  long level;
  char levelType[20]={0,};

  tes=grib_get_timer(0,"encoding simple", 0, 0);
  tds=grib_get_timer(0,"decoding simple", 0, 0);
  tej=grib_get_timer(0,"encoding ccsds", 0, 0);
  tdj=grib_get_timer(0,"decoding ccsds", 0, 0);

  if (argc != 4 && argc != 6 ) usage(argv[0]);
  if (!strcmp(argv[iarg],"-w")) {
    append=0;
    iarg++;
    ofilename=argv[iarg];
    iarg++;
  } else if (!strcmp(argv[iarg],"-a")) {
    append=1;
    iarg++;
    ofilename=argv[iarg];
    iarg++;
  } else {
    append=0;
    ofilename=defofilename;
  }
  finname=argv[iarg++];
  repeatsimple=atoi(argv[iarg++]);
  bitsPerValue=atoi(argv[iarg++]);

  fin = fopen(finname,"r");
  if(!fin) {perror(finname);exit(1);}

  if (append)
      fout = fopen(ofilename,"a");
  else
      fout = fopen(ofilename,"w");

  if(!fout) {perror(ofilename);exit(1);}

  c=grib_context_get_default();
  e=0;
  h=grib_handle_new_from_file(c,fin,&e);
  fclose(fin);

  GRIB_CHECK(e,0);

  len=50;
  grib_get_string(h,"shortName",param,&len);

  len=20;
  grib_get_string(h,"levelType",levelType,&len);

  if (!strcmp(levelType,"pl")) {
    GRIB_CHECK(grib_get_long(h,"level",&level),0);
    sprintf(shortName,"%s%ld",param,level);
  } else {
    sprintf(shortName,"%s",param);
  }


  grib_set_long(h,"editionNumber",2);
  GRIB_CHECK(grib_get_size(h,"values",&nvalues),0);
  values=(double*)grib_context_malloc(c,sizeof(double)*nvalues);
  if (!values) { printf("%s: memory allocation error\n",argv[0]); exit(1); }

  len=50;
  grib_get_string(h,"gridType",gridType,&len);

  len=50;
  grib_get_string(h,"packingType",packingType,&len);

  GRIB_CHECK(grib_get_double_array(h,"values",values,&nvalues),0);
  grib_set_long(h,"bitsPerValue",bitsPerValue);
  GRIB_CHECK(grib_set_double_array(h,"values",values,nvalues),0);

  printf("--------------------------------\n");
  printf("- %s - gridType=%s packingType=%s numberOfValues=%ld bitsPerValue=%ld\n",
    param,gridType,packingType,(long)nvalues,bitsPerValue);

  if (!strcmp(packingType,"spectral_complex") || !strcmp(packingType,"spectral_simple")) {
     printf("unable to process spectral data\n");
     exit(1);
  }

  if (!strcmp(gridType,"reduced_gg") || !strcmp(gridType,"regular_gg")) {
     long N;
     grib_get_long(h,"N",&N);
     printf("    N=%ld\n",N);
     sprintf(grid,"%ld",N);
  }
  if (!strcmp(gridType,"regular_ll")) {
     double Di,Dj;
     grib_get_double(h,"DiInDegrees",&Di);
     grib_get_double(h,"DjInDegrees",&Dj);
     printf("    Di=%g Dj=%g\n",Di,Dj);
     sprintf(grid,"%g/%g",Di,Dj);
  }


  if (!append)
    fprintf(fout,
    "shortName gridType numberOfValues bitsPerValue grid sizeSimple sizeccsds encodeccsds encodeSimple decodeccsds decodeSimple\n");

  /* decode values grid_simple */
  if (strcmp(packingType,grid_simple))
    grib_set_string(h,"packingType",grid_simple,&grid_simple_l);
  /* printf("decoding simple\n"); */
  grib_timer_start(tds);
  for (count=0;count<repeatsimple;count++)
    GRIB_CHECK(grib_get_double_array(h,"values",values,&nvalues),0);
  grib_timer_stop(tds,0);
  /* printf("%d messages decoded\n\n",count); */

  *outfilename='\0';
  sprintf(outfilename,"%s_%s_%ld_simple.grib2",param,gridType,bitsPerValue);
  filesize_simple=grib_handle_write(h,outfilename);
  printf("file size simple = %ld\n",(long)filesize_simple);

  /* encode values grid_simple*/
  /* printf("encoding simple\n"); */
  grib_timer_start(tes);
  for (count=0;count<repeatsimple;count++)
    GRIB_CHECK(grib_set_double_array(h,"values",values,nvalues),0);
  grib_timer_stop(tes,0);
  /* printf("%d messages encoded \n\n",count); */

  /* decode values grid_ccsds */
  grib_set_string(h,"packingType",grid_ccsds,&grid_ccsds_l);
  /* printf("decoding ccsds\n"); */
  grib_timer_start(tdj);
  for (count=0;count<repeatccsds;count++)
    GRIB_CHECK(grib_get_double_array(h,"values",values,&nvalues),0);
  grib_timer_stop(tdj,0);
  /* printf("%d messages decoded\n\n",count); */

  *outfilename='\0';
  sprintf(outfilename,"%s_%s_%ld_ccsds.grib2",param,gridType,bitsPerValue);
  filesize_ccsds=grib_handle_write(h,outfilename);
  printf("file size ccsds   = %ld\n",(long)filesize_ccsds);

  perc=(double)filesize_simple/(double)filesize_ccsds;

  printf("compression ratio = %g \n",perc);
  printf("space savings = %g \n",(1.0-1.0/perc)*100);

  /* encode values grid_ccsds*/
  /* printf("encoding ccsds\n"); */
  grib_timer_start(tej);
  for (count=0;count<repeatccsds;count++)
    GRIB_CHECK(grib_set_double_array(h,"values",values,nvalues),0);
  grib_timer_stop(tej,0);
  /* printf("%d messages encoded \n\n",count); */

  grib_handle_delete(h);
  grib_context_free(c,values);

  print_timer(tej,repeatccsds);
  print_timer(tdj,repeatccsds);
  print_timer(tes,repeatsimple);
  print_timer(tds,repeatsimple);
  printf("--------------------------------\n\n");
  fprintf(fout,"%s %s %ld %ld %s %ld %ld %g %g %g %g\n",
    shortName,gridType,(long)nvalues,bitsPerValue,
    grid,(long)filesize_simple,(long)filesize_ccsds,tej->timer_/repeatccsds,tes->timer_/repeatsimple,tdj->timer_/repeatccsds,tds->timer_/repeatsimple);

  return 0;
}
Example #2
0
int main(int argc, char** argv)
{
    FILE* fin=0;
    int ret=0;
    char* fname=0;
    float lat,lon;
    double *vlat,*vlon;
    int npoints=0,i=0,n=0;
    grib_handle* h;
    double *outlats,*outlons,*values,*lsm_values,*distances;
    int* indexes;
    long step=0;
    char time[10]={0,};
    char date[10]={0,};
    long parameter=0;
    size_t len=0;
    long iid=0;
    long *id=NULL;

    if (argc < 2) usage(argv[0]);

    fname=argv[1];
    fin=fopen(fname,"r");
    if(!fin) { perror(fname); exit(1); }
    npoints=0;
    while (fscanf(fin,"%ld %g %g",&iid,&lat,&lon) != EOF) npoints++;
    fclose(fin);

    id=(long*)malloc(npoints*sizeof(long));
    if (!id) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(long)));exit(1);}
    vlat=(double*)malloc(npoints*sizeof(double));
    if (!vlat) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    vlon=(double*)malloc(npoints*sizeof(double));
    if (!vlon) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    outlats=(double*)malloc(npoints*sizeof(double));
    if (!outlats) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    outlons=(double*)malloc(npoints*sizeof(double));
    if (!outlons) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    values=(double*)malloc(npoints*sizeof(double));
    if (!values) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    lsm_values=(double*)malloc(npoints*sizeof(double));
    if (!lsm_values) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    distances=(double*)malloc(npoints*sizeof(double));
    if (!distances) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}
    indexes=(int*)malloc(npoints*sizeof(int));
    if (!indexes) {printf("unable to allocate %ld bytes\n",(long)(npoints*sizeof(double)));exit(1);}

    fname=argv[1];
    fin=fopen(fname,"r");
    if(!fin) { perror(fname); exit(1); }
    i=0;
    while (fscanf(fin,"%ld %g %g",&iid,&lat,&lon) != EOF) {
        id[i]=iid;vlat[i]=lat;
        while(lon < 0) lon+=360;
        vlon[i]=lon;
        i++;
    }
    fclose(fin);

    fname=argv[2];
    fin=fopen(fname,"r");
    if(!fin) { perror(fname); exit(1); }
    h=grib_handle_new_from_file(0,fin,&ret);
    if (!h || ret!=GRIB_SUCCESS) {printf(" unable to create handle\n");exit(1);}

    grib_nearest_find_multiple(h,1,vlat,vlon,npoints,
            outlats,outlons,lsm_values,distances,indexes);

    grib_handle_delete(h);

    fclose(fin);

    for (n=3;n<=argc-1;n++) {
        fname=argv[n];
        fin=fopen(fname,"r");
        if(!fin) { perror(fname); exit(1); }
        while ((h=grib_handle_new_from_file(0,fin,&ret))!=NULL) {
            grib_get_double_elements(h,"values",indexes,npoints,values);

            GRIB_CHECK(grib_get_length(h, "date", &len),0);
            grib_get_string(h,"date",date,&len);
            GRIB_CHECK(grib_get_length(h, "time", &len),0);
            grib_get_string(h,"time",time,&len);
            grib_get_long(h,"step",&step);
            grib_get_long(h,"parameter",&parameter);

            printf("# %s %s %ld %ld\n",date,time,step,parameter);
            grib_handle_delete(h);
            for (i=0;i<npoints;i++)
                printf("%ld %g %g %g %g\n",
                        id[i],outlats[i],outlons[i],
                        lsm_values[i],values[i]);
        }

        fclose(fin);
    }

    return ret;
}
Example #3
0
int main(int argc, char** argv) {
  int err = 0;
  double *values = NULL;
  size_t values_len= 0;

  size_t i = 0;

  double latitudeOfFirstGridPointInDegrees;
  double longitudeOfFirstGridPointInDegrees;
  double latitudeOfLastGridPointInDegrees;
  double longitudeOfLastGridPointInDegrees;

  double jDirectionIncrementInDegrees;
  double iDirectionIncrementInDegrees;

  long numberOfPointsAlongAParallel;
  long numberOfPointsAlongAMeridian;

  double average = 0;

  FILE* in = NULL;
  char* filename = "../data/regular_latlon_surface.grib1";
  grib_handle *h = NULL;

  in = fopen(filename,"r");
  if(!in) {
    printf("ERROR: unable to open file %s\n",filename);
    return 1;
  }

  /* create new handle from a message in a file*/
  h = grib_handle_new_from_file(0,in,&err);
  if (h == NULL) {
    printf("Error: unable to create handle from file %s\n",filename);
  }

  /* get as a long*/
  GRIB_CHECK(grib_get_long(h,"numberOfPointsAlongAParallel",&numberOfPointsAlongAParallel),0);
  printf("numberOfPointsAlongAParallel=%ld\n",numberOfPointsAlongAParallel);

  /* get as a long*/
  GRIB_CHECK(grib_get_long(h,"numberOfPointsAlongAMeridian",&numberOfPointsAlongAMeridian),0);
  printf("numberOfPointsAlongAMeridian=%ld\n",numberOfPointsAlongAMeridian);

  /* get as a double*/
  GRIB_CHECK(grib_get_double(h,"latitudeOfFirstGridPointInDegrees",&latitudeOfFirstGridPointInDegrees),0);
  printf("latitudeOfFirstGridPointInDegrees=%g\n",latitudeOfFirstGridPointInDegrees);

  /* get as a double*/
  GRIB_CHECK(grib_get_double(h,"longitudeOfFirstGridPointInDegrees",&longitudeOfFirstGridPointInDegrees),0);
  printf("longitudeOfFirstGridPointInDegrees=%g\n",longitudeOfFirstGridPointInDegrees);

  /* get as a double*/
  GRIB_CHECK(grib_get_double(h,"latitudeOfLastGridPointInDegrees",&latitudeOfLastGridPointInDegrees),0);
  printf("latitudeOfLastGridPointInDegrees=%g\n",latitudeOfLastGridPointInDegrees);

  /* get as a double*/
  GRIB_CHECK(grib_get_double(h,"longitudeOfLastGridPointInDegrees",&longitudeOfLastGridPointInDegrees),0);
  printf("longitudeOfLastGridPointInDegrees=%g\n",longitudeOfLastGridPointInDegrees);

  /* get as a double*/
  GRIB_CHECK(grib_get_double(h,"jDirectionIncrementInDegrees",&jDirectionIncrementInDegrees),0);
  printf("jDirectionIncrementInDegrees=%g\n",jDirectionIncrementInDegrees);

  /* get as a double*/
  GRIB_CHECK(grib_get_double(h,"iDirectionIncrementInDegrees",&iDirectionIncrementInDegrees),0);
  printf("iDirectionIncrementInDegrees=%g\n",iDirectionIncrementInDegrees);

  /* get the size of the values array*/
  GRIB_CHECK(grib_get_size(h,"values",&values_len),0);

  values = malloc(values_len*sizeof(double));

  /* get data values*/
  GRIB_CHECK(grib_get_double_array(h,"values",values,&values_len),0);

  average = 0;
  for(i = 0; i < values_len; i++)
    average += values[i];

  average /=(double)values_len;

  free(values);

  printf("There are %d values, average is %g\n",(int)values_len,average);

  grib_handle_delete(h);

  fclose(in);
  return 0;
}
Example #4
0
File: Grib.cpp Project: WFRT/Comps
float InputGrib::getValueCore(const Key::Input& iKey) const {
#ifdef WITH_GRIB
   // Check that date hasn't been checked before
   std::map<int,std::map<float, bool> >::const_iterator it0 = mMissingFiles.find(iKey.date);
   if(it0 != mMissingFiles.end()) {
      // Date has missing files
      std::map<float, bool>::const_iterator it1 = it0->second.find(iKey.offset);
      if(it1 != it0->second.end()) {
         writeMissingToCache(iKey);
         return Global::MV;
      }
   }

   std::string localVariable;
   bool found = getLocalVariableName(iKey.variable, localVariable);
   assert(found);

   int numLocations = Input::getNumLocations();

   std::string filename = getFilename(iKey);
   std::stringstream ss;
   ss << "InputGrib: Loading " << filename << " " << iKey.date << " " << iKey.offset << " " << iKey.location << " " << localVariable;
   Global::logger->write(ss.str(), Logger::message);
   bool foundVariable = false;
   FILE* fid = fopen(filename.c_str(),"r");
   float value = Global::MV;
   if(fid) {
      // GRIB File found
      int err = 0;
      grib_handle* h = NULL;

      // double s = Global::clock();

      // Try to use an index to read file as this is much faster. Fall back on just reading the 
      // GRIB file.
      grib_index* gribIndex = getIndex(iKey, localVariable);
      bool validIndex = (gribIndex != NULL);
      if(!validIndex) {
         std::stringstream ss;
         ss << "InputGrib: No index file available for " << filename;
         Global::logger->write(ss.str(), Logger::message);
      }

      int counter = 1;
      // Loop over available variables (in index or in file)
      while(1) {
         // Read message from file or index
         if(!validIndex) {
            h = grib_handle_new_from_file(0,fid,&err);
         }
         else {
            h = grib_handle_new_from_index(gribIndex,&err);
         }
         if(h == NULL)
            break; // No more messages to process

         std::string currVariable = getVariableName(h);
         std::stringstream ss;
         ss << "InputGrib: Reading message #" << counter << ": " << currVariable;
         Global::logger->write(ss.str(), Logger::message);

         // Check if the current variable is defined in the variable list
         int variableId;
         found = getVariableIdFromLocalVariable(currVariable, variableId);
         if(!found) {
            std::stringstream ss;
            ss << "InputGrib: Found variable " << currVariable << " in " << filename << " but this is not mapped to any variable in namelist" << std::endl;
            Global::logger->write(ss.str(), Logger::message);
         }
         else {
            // Only read the current variable if necessary
            if(mCacheOtherVariables || currVariable == localVariable) {
               std::vector<float> currValues;
               currValues.resize(numLocations, Global::MV);
               int numValid = 0;

               // Check that the message has the right number of locations
               size_t N;
               GRIB_CHECK(grib_get_size(h,"values",&N),0);
               if(N == numLocations) {
                  foundVariable = foundVariable || (currVariable == localVariable);
                  double* arr = new double[N];

                  GRIB_CHECK(grib_get_double_array(h,"values",arr,&N),0);
                  currValues.assign(arr, arr + numLocations);
                  for(int i = 0; i < (int) currValues.size(); i++) {
                     if(currValues[i] == mMV)
                        currValues[i] = Global::MV;
                     else
                        numValid++;
                  }
                  std::stringstream ss;
                  ss << "InputGrib: Number of valid values: " << numValid;
                  Global::logger->write(ss.str(), Logger::message);
                  delete arr;
               }
               else {
                  std::stringstream ss;
                  ss << "GribInput: Discarding variable " << currVariable << " in " << filename
                     << " because it has incorrect number of locations";
                  Global::logger->write(ss.str(), Logger::debug);
               }

               Key::Input key = iKey;
               key.offset = getOffset(h);
               // Cache values
               for(int i = 0; i < numLocations; i++) {
                  key.location = i;
                  key.variable = variableId;
                  if(key.location == iKey.location && currVariable == localVariable) {
                     // Found the value
                     value = currValues[i];
                  }
                  if(mCacheOtherLocations || key.location == iKey.location) {
                     //if(currVariable == localVariable)
                     //   std::cout << currValues[i] << std::endl;
                     Input::addToCache(key, currValues[i]);
                  }
               }
            }
         }
         if(h) {
            grib_handle_delete(h);
         }

         // Quit reading file if we have found the variable we need
         if(!mCacheOtherVariables && (currVariable == localVariable)) {
            break;
         }
         counter++;
      }
      if(!foundVariable) {
         // File was there, but couldn't find variable
         std::stringstream ss;
         ss << "InputGrib: Could not find variable " << localVariable << " in " << filename;
         Global::logger->write(ss.str(), Logger::warning);
         writeMissingToCache(iKey);
      }
      if(validIndex) {
         grib_index_delete(gribIndex);
      }

      // double e = Global::clock();
      //std::cout << "Grib read time: " << e - s << " seconds" << std::endl;

      fclose(fid);
      return value;
   }
   else {
      // GRIB file not found
      std::stringstream ss;
      ss << "GribInput: File not found: " << filename;
      Global::logger->write(ss.str(), Logger::message);

      std::vector<float> currValues;
      currValues.resize(numLocations, Global::MV);
      for(int i = 0; i < numLocations; i++) {
         Key::Input key = iKey;
         key.location = i;
         if(mCacheOtherLocations || key.location == iKey.location)
            Input::addToCache(key, currValues[i]);
      }
      return Global::MV;
   }
#else
   return Global::MV;
#endif
}
Example #5
0
int main(int argc, char** argv)
{
  int err = 0;
  size_t size=0;

  FILE* in = NULL;
  char* infile = "../../data/regular_latlon_surface.grib1";
  FILE* out = NULL;
  char* outfile = "out.grib1";
  grib_handle *h = NULL;
  const void* buffer = NULL;
  size_t values_len;
  double* values;
  double missing=9999;
  int i=0;

  in = fopen(infile,"r");
  if(!in) {
    printf("ERROR: unable to open input file %s\n",infile);
    return 1;
  }

  out = fopen(outfile,"w");
  if(!out) {
    printf("ERROR: unable to open output file %s\n",outfile);
        fclose(in);
    return 1;
  }

  h = grib_handle_new_from_file(0,in,&err);
  if (h == NULL) {
    printf("Error: unable to create handle from file %s\n",infile);
  }

  GRIB_CHECK(grib_set_double(h,"missingValue",missing),0);

  /* get the size of the values array*/
  GRIB_CHECK(grib_get_size(h,"values",&values_len),0);

  values = (double*)malloc(values_len*sizeof(double));

  /* get data values*/
  GRIB_CHECK(grib_get_double_array(h,"values",values,&values_len),0);

  GRIB_CHECK(grib_set_long(h,"bitmapPresent",1),0);

  for(i = 0; i < 10; i++)
    values[i]=missing;

  GRIB_CHECK(grib_set_double_array(h,"values",values,values_len),0);

  /* get the coded message in a buffer */
  GRIB_CHECK(grib_get_message(h,&buffer,&size),0);

  /* write the buffer in a file*/
  if(fwrite(buffer,1,size,out) != size)
  {
     perror(outfile);
     exit(1);
  }

  /* delete handle */
  grib_handle_delete(h);

  fclose(in);
  fclose(out);

  return 0;
}
Example #6
0
int main(int argc,const char** argv)
{
    grib_handle *h     = NULL;
    size_t size        = 0;
    double* vdouble    = NULL;
    FILE* f            = NULL;
    const void* buffer = NULL;

    if(argc != 2) {
       fprintf(stderr,"usage: %s out\n",argv[0]);
        exit(1);
    }

    h = grib_handle_new_from_samples(NULL,"GRIB2");
    if(!h) {
        fprintf(stderr,"Cannot create grib handle\n");
        exit(1);
    }

    GRIB_CHECK(grib_set_long(h,"parametersVersion",1),0);
    GRIB_CHECK(grib_set_long(h,"truncateLaplacian",0),0);
    GRIB_CHECK(grib_set_long(h,"truncateDegrees",0),0);
    GRIB_CHECK(grib_set_long(h,"dummy",1),0);
    GRIB_CHECK(grib_set_long(h,"changingPrecision",0),0);
    GRIB_CHECK(grib_set_long(h,"unitsFactor",1),0);
    GRIB_CHECK(grib_set_long(h,"unitsBias",0),0);
    GRIB_CHECK(grib_set_long(h,"timeRangeIndicatorFromStepRange",-1),0);
    GRIB_CHECK(grib_set_long(h,"missingValue",9999),0);

    /* 0 = Meteorological products (grib2/tables/4/0.0.table)  */
    GRIB_CHECK(grib_set_long(h,"discipline",0),0);

    GRIB_CHECK(grib_set_long(h,"editionNumber",2),0);

    /* 98 = European Center for Medium-Range Weather Forecasts (grib1/0.table)  */
    GRIB_CHECK(grib_set_long(h,"centre",98),0);

    GRIB_CHECK(grib_set_long(h,"subCentre",0),0);

    /* 4 = Version implemented on 7 November 2007 (grib2/tables/1.0.table)  */
    GRIB_CHECK(grib_set_long(h,"tablesVersion",4),0);


    /* 0 = Local tables not used  (grib2/tables/4/1.1.table)  */
    GRIB_CHECK(grib_set_long(h,"localTablesVersion",0),0);


    /* 1 = Start of forecast (grib2/tables/4/1.2.table)  */
    GRIB_CHECK(grib_set_long(h,"significanceOfReferenceTime",1),0);

    GRIB_CHECK(grib_set_long(h,"year",2007),0);
    GRIB_CHECK(grib_set_long(h,"month",3),0);
    GRIB_CHECK(grib_set_long(h,"day",23),0);
    GRIB_CHECK(grib_set_long(h,"hour",12),0);
    GRIB_CHECK(grib_set_long(h,"minute",0),0);
    GRIB_CHECK(grib_set_long(h,"second",0),0);
    GRIB_CHECK(grib_set_long(h,"dataDate",20070323),0);
    GRIB_CHECK(grib_set_long(h,"dataTime",1200),0);

    /* 0 = Operational products (grib2/tables/4/1.3.table)  */
    GRIB_CHECK(grib_set_long(h,"productionStatusOfProcessedData",0),0);


    /* 2 = Analysis and forecast products (grib2/tables/4/1.4.table)  */
    GRIB_CHECK(grib_set_long(h,"typeOfProcessedData",2),0);

    GRIB_CHECK(grib_set_long(h,"selectStepTemplateInterval",1),0);
    GRIB_CHECK(grib_set_long(h,"selectStepTemplateInstant",1),0);
    GRIB_CHECK(grib_set_long(h,"grib2LocalSectionPresent",0),0);

    /* 0 = Specified in Code table 3.1 (grib2/tables/4/3.0.table)  */
    GRIB_CHECK(grib_set_long(h,"sourceOfGridDefinition",0),0);

    GRIB_CHECK(grib_set_long(h,"numberOfDataPoints",496),0);
    GRIB_CHECK(grib_set_long(h,"numberOfOctectsForNumberOfPoints",0),0);

    /* 0 = There is no appended list (grib2/tables/4/3.11.table)  */
    GRIB_CHECK(grib_set_long(h,"interpretationOfNumberOfPoints",0),0);

    GRIB_CHECK(grib_set_long(h,"PLPresent",0),0);

    /* 0 = Latitude/longitude. Also called equidistant cylindrical, or Plate Carree (grib2/tables/4/3.1.table)  */
    GRIB_CHECK(grib_set_long(h,"gridDefinitionTemplateNumber",0),0);


    /* 0 = Earth assumed spherical with radius = 6,367,470.0 m (grib2/tables/4/3.2.table)  */
    GRIB_CHECK(grib_set_long(h,"shapeOfTheEarth",0),0);

    GRIB_CHECK(grib_set_missing(h,"scaleFactorOfRadiusOfSphericalEarth"),0);
    GRIB_CHECK(grib_set_missing(h,"scaledValueOfRadiusOfSphericalEarth"),0);
    GRIB_CHECK(grib_set_missing(h,"scaleFactorOfEarthMajorAxis"),0);
    GRIB_CHECK(grib_set_missing(h,"scaledValueOfEarthMajorAxis"),0);
    GRIB_CHECK(grib_set_missing(h,"scaleFactorOfEarthMinorAxis"),0);
    GRIB_CHECK(grib_set_missing(h,"scaledValueOfEarthMinorAxis"),0);
    GRIB_CHECK(grib_set_long(h,"radius",6367470),0);
    GRIB_CHECK(grib_set_long(h,"Ni",16),0);
    GRIB_CHECK(grib_set_long(h,"Nj",31),0);
    GRIB_CHECK(grib_set_long(h,"basicAngleOfTheInitialProductionDomain",0),0);
    GRIB_CHECK(grib_set_long(h,"mBasicAngle",0),0);
    GRIB_CHECK(grib_set_long(h,"angleMultiplier",1),0);
    GRIB_CHECK(grib_set_long(h,"mAngleMultiplier",1000000),0);
    GRIB_CHECK(grib_set_missing(h,"subdivisionsOfBasicAngle"),0);
    GRIB_CHECK(grib_set_long(h,"angleDivisor",1000000),0);
    GRIB_CHECK(grib_set_long(h,"latitudeOfFirstGridPoint",60000000),0);
    GRIB_CHECK(grib_set_long(h,"longitudeOfFirstGridPoint",0),0);

    /* 48 = 00110000
    (3=1)  i direction increments given
    (4=1)  j direction increments given
    (5=0)  Resolved u- and v- components of vector quantities relative to easterly and northerly directions
    See grib2/tables/[tablesVersion]/3.3.table */
    GRIB_CHECK(grib_set_long(h,"resolutionAndComponentFlags",48),0);

    GRIB_CHECK(grib_set_long(h,"iDirectionIncrementGiven",1),0);
    GRIB_CHECK(grib_set_long(h,"jDirectionIncrementGiven",1),0);
    GRIB_CHECK(grib_set_long(h,"uvRelativeToGrid",0),0);
    GRIB_CHECK(grib_set_long(h,"latitudeOfLastGridPoint",0),0);
    GRIB_CHECK(grib_set_long(h,"longitudeOfLastGridPoint",30000000),0);
    GRIB_CHECK(grib_set_long(h,"iDirectionIncrement",2000000),0);
    GRIB_CHECK(grib_set_long(h,"jDirectionIncrement",2000000),0);

    /* 0 = 00000000
    (1=0)  Points of first row or column scan in the +i (+x) direction
    (2=0)  Points of first row or column scan in the -j (-y) direction
    (3=0)  Adjacent points in i (x) direction are consecutive
    (4=0)  All rows scan in the same direction
    See grib2/tables/[tablesVersion]/3.4.table */
    GRIB_CHECK(grib_set_long(h,"scanningMode",0),0);

    GRIB_CHECK(grib_set_long(h,"iScansNegatively",0),0);
    GRIB_CHECK(grib_set_long(h,"jScansPositively",0),0);
    GRIB_CHECK(grib_set_long(h,"jPointsAreConsecutive",0),0);
    GRIB_CHECK(grib_set_long(h,"alternativeRowScanning",0),0);
    GRIB_CHECK(grib_set_long(h,"iScansPositively",1),0);

    /* ITERATOR */


    /* NEAREST */

    GRIB_CHECK(grib_set_long(h,"timeRangeIndicator",0),0);
    GRIB_CHECK(grib_set_long(h,"NV",0),0);
    GRIB_CHECK(grib_set_long(h,"neitherPresent",0),0);

    /* 0 = Analysis or forecast at a horizontal level or in a horizontal layer at a point in time (grib2/tables/4/4.0.table)  */
    GRIB_CHECK(grib_set_long(h,"productDefinitionTemplateNumber",0),0);


    /* Parameter information */


    /* 0 = Temperature (grib2/tables/4/4.1.0.table)  */
    GRIB_CHECK(grib_set_long(h,"parameterCategory",0),0);


    /* 0 = Temperature  (K)  (grib2/tables/4/4.2.0.0.table)  */
    GRIB_CHECK(grib_set_long(h,"parameterNumber",0),0);


    /* 0 = Analysis (grib2/tables/4/4.3.table)  */
    GRIB_CHECK(grib_set_long(h,"typeOfGeneratingProcess",0),0);

    GRIB_CHECK(grib_set_long(h,"backgroundProcess",255),0);
    GRIB_CHECK(grib_set_long(h,"generatingProcessIdentifier",128),0);
    GRIB_CHECK(grib_set_long(h,"hoursAfterDataCutoff",0),0);
    GRIB_CHECK(grib_set_long(h,"minutesAfterDataCutoff",0),0);

    /* 1 = Hour (grib2/tables/4/4.4.table)  */
    GRIB_CHECK(grib_set_long(h,"indicatorOfUnitOfTimeRange",1),0);


    /* 1 = Hour (stepUnits.table)  */
    GRIB_CHECK(grib_set_long(h,"stepUnits",1),0);

    GRIB_CHECK(grib_set_long(h,"forecastTime",0),0);

    /* 1 = Ground or water surface  (grib2/tables/4/4.5.table)  */
    GRIB_CHECK(grib_set_long(h,"typeOfFirstFixedSurface",1),0);

    GRIB_CHECK(grib_set_missing(h,"scaleFactorOfFirstFixedSurface"),0);
    GRIB_CHECK(grib_set_missing(h,"scaledValueOfFirstFixedSurface"),0);

    /* 255 = Missing (grib2/tables/4/4.5.table)  */
    GRIB_CHECK(grib_set_long(h,"typeOfSecondFixedSurface",255),0);

    GRIB_CHECK(grib_set_missing(h,"scaleFactorOfSecondFixedSurface"),0);
    GRIB_CHECK(grib_set_missing(h,"scaledValueOfSecondFixedSurface"),0);
    GRIB_CHECK(grib_set_long(h,"level",0),0);
    GRIB_CHECK(grib_set_long(h,"bottomLevel",0),0);
    GRIB_CHECK(grib_set_long(h,"topLevel",0),0);
    GRIB_CHECK(grib_set_long(h,"dummyc",0),0);
    GRIB_CHECK(grib_set_long(h,"PVPresent",0),0);

    /* grib 2 Section 5 DATA REPRESENTATION SECTION */

    GRIB_CHECK(grib_set_long(h,"numberOfValues",496),0);

    /* 0 = Grid point data - simple packing (grib2/tables/4/5.0.table)  */
    GRIB_CHECK(grib_set_long(h,"dataRepresentationTemplateNumber",0),0);

    GRIB_CHECK(grib_set_long(h,"decimalScaleFactor",0),0);
    GRIB_CHECK(grib_set_long(h,"bitsPerValue",0),0);

    /* 0 = Floating point (grib2/tables/4/5.1.table)  */
    GRIB_CHECK(grib_set_long(h,"typeOfOriginalFieldValues",0),0);

    GRIB_CHECK(grib_set_long(h,"representationMode",0),0);

    /* grib 2 Section 6 BIT-MAP SECTION */


    /* 255 = A bit map does not apply to this product (grib2/tables/4/6.0.table)  */
    GRIB_CHECK(grib_set_long(h,"bitMapIndicator",255),0);

    GRIB_CHECK(grib_set_long(h,"bitmapPresent",0),0);

    /* grib 2 Section 7 data */

    size = 496;
    vdouble    = (double*)calloc(size,sizeof(double));
    if(!vdouble) {
        fprintf(stderr,"failed to allocate %lu bytes\n",size*sizeof(double));
        exit(1);
    }

    vdouble[   0] =       1; vdouble[   1] =       1; vdouble[   2] =       1; vdouble[   3] =       1;
    vdouble[   4] =       1; vdouble[   5] =       1; vdouble[   6] =       1; vdouble[   7] =       1;
    vdouble[   8] =       1; vdouble[   9] =       1; vdouble[  10] =       1; vdouble[  11] =       1;
    vdouble[  12] =       1; vdouble[  13] =       1; vdouble[  14] =       1; vdouble[  15] =       1;
    vdouble[  16] =       1; vdouble[  17] =       1; vdouble[  18] =       1; vdouble[  19] =       1;
    vdouble[  20] =       1; vdouble[  21] =       1; vdouble[  22] =       1; vdouble[  23] =       1;
    vdouble[  24] =       1; vdouble[  25] =       1; vdouble[  26] =       1; vdouble[  27] =       1;
    vdouble[  28] =       1; vdouble[  29] =       1; vdouble[  30] =       1; vdouble[  31] =       1;
    vdouble[  32] =       1; vdouble[  33] =       1; vdouble[  34] =       1; vdouble[  35] =       1;
    vdouble[  36] =       1; vdouble[  37] =       1; vdouble[  38] =       1; vdouble[  39] =       1;
    vdouble[  40] =       1; vdouble[  41] =       1; vdouble[  42] =       1; vdouble[  43] =       1;
    vdouble[  44] =       1; vdouble[  45] =       1; vdouble[  46] =       1; vdouble[  47] =       1;
    vdouble[  48] =       1; vdouble[  49] =       1; vdouble[  50] =       1; vdouble[  51] =       1;
    vdouble[  52] =       1; vdouble[  53] =       1; vdouble[  54] =       1; vdouble[  55] =       1;
    vdouble[  56] =       1; vdouble[  57] =       1; vdouble[  58] =       1; vdouble[  59] =       1;
    vdouble[  60] =       1; vdouble[  61] =       1; vdouble[  62] =       1; vdouble[  63] =       1;
    vdouble[  64] =       1; vdouble[  65] =       1; vdouble[  66] =       1; vdouble[  67] =       1;
    vdouble[  68] =       1; vdouble[  69] =       1; vdouble[  70] =       1; vdouble[  71] =       1;
    vdouble[  72] =       1; vdouble[  73] =       1; vdouble[  74] =       1; vdouble[  75] =       1;
    vdouble[  76] =       1; vdouble[  77] =       1; vdouble[  78] =       1; vdouble[  79] =       1;
    vdouble[  80] =       1; vdouble[  81] =       1; vdouble[  82] =       1; vdouble[  83] =       1;
    vdouble[  84] =       1; vdouble[  85] =       1; vdouble[  86] =       1; vdouble[  87] =       1;
    vdouble[  88] =       1; vdouble[  89] =       1; vdouble[  90] =       1; vdouble[  91] =       1;
    vdouble[  92] =       1; vdouble[  93] =       1; vdouble[  94] =       1; vdouble[  95] =       1;
    vdouble[  96] =       1; vdouble[  97] =       1; vdouble[  98] =       1; vdouble[  99] =       1;
    vdouble[ 100] =       1; vdouble[ 101] =       1; vdouble[ 102] =       1; vdouble[ 103] =       1;
    vdouble[ 104] =       1; vdouble[ 105] =       1; vdouble[ 106] =       1; vdouble[ 107] =       1;
    vdouble[ 108] =       1; vdouble[ 109] =       1; vdouble[ 110] =       1; vdouble[ 111] =       1;
    vdouble[ 112] =       1; vdouble[ 113] =       1; vdouble[ 114] =       1; vdouble[ 115] =       1;
    vdouble[ 116] =       1; vdouble[ 117] =       1; vdouble[ 118] =       1; vdouble[ 119] =       1;
    vdouble[ 120] =       1; vdouble[ 121] =       1; vdouble[ 122] =       1; vdouble[ 123] =       1;
    vdouble[ 124] =       1; vdouble[ 125] =       1; vdouble[ 126] =       1; vdouble[ 127] =       1;
    vdouble[ 128] =       1; vdouble[ 129] =       1; vdouble[ 130] =       1; vdouble[ 131] =       1;
    vdouble[ 132] =       1; vdouble[ 133] =       1; vdouble[ 134] =       1; vdouble[ 135] =       1;
    vdouble[ 136] =       1; vdouble[ 137] =       1; vdouble[ 138] =       1; vdouble[ 139] =       1;
    vdouble[ 140] =       1; vdouble[ 141] =       1; vdouble[ 142] =       1; vdouble[ 143] =       1;
    vdouble[ 144] =       1; vdouble[ 145] =       1; vdouble[ 146] =       1; vdouble[ 147] =       1;
    vdouble[ 148] =       1; vdouble[ 149] =       1; vdouble[ 150] =       1; vdouble[ 151] =       1;
    vdouble[ 152] =       1; vdouble[ 153] =       1; vdouble[ 154] =       1; vdouble[ 155] =       1;
    vdouble[ 156] =       1; vdouble[ 157] =       1; vdouble[ 158] =       1; vdouble[ 159] =       1;
    vdouble[ 160] =       1; vdouble[ 161] =       1; vdouble[ 162] =       1; vdouble[ 163] =       1;
    vdouble[ 164] =       1; vdouble[ 165] =       1; vdouble[ 166] =       1; vdouble[ 167] =       1;
    vdouble[ 168] =       1; vdouble[ 169] =       1; vdouble[ 170] =       1; vdouble[ 171] =       1;
    vdouble[ 172] =       1; vdouble[ 173] =       1; vdouble[ 174] =       1; vdouble[ 175] =       1;
    vdouble[ 176] =       1; vdouble[ 177] =       1; vdouble[ 178] =       1; vdouble[ 179] =       1;
    vdouble[ 180] =       1; vdouble[ 181] =       1; vdouble[ 182] =       1; vdouble[ 183] =       1;
    vdouble[ 184] =       1; vdouble[ 185] =       1; vdouble[ 186] =       1; vdouble[ 187] =       1;
    vdouble[ 188] =       1; vdouble[ 189] =       1; vdouble[ 190] =       1; vdouble[ 191] =       1;
    vdouble[ 192] =       1; vdouble[ 193] =       1; vdouble[ 194] =       1; vdouble[ 195] =       1;
    vdouble[ 196] =       1; vdouble[ 197] =       1; vdouble[ 198] =       1; vdouble[ 199] =       1;
    vdouble[ 200] =       1; vdouble[ 201] =       1; vdouble[ 202] =       1; vdouble[ 203] =       1;
    vdouble[ 204] =       1; vdouble[ 205] =       1; vdouble[ 206] =       1; vdouble[ 207] =       1;
    vdouble[ 208] =       1; vdouble[ 209] =       1; vdouble[ 210] =       1; vdouble[ 211] =       1;
    vdouble[ 212] =       1; vdouble[ 213] =       1; vdouble[ 214] =       1; vdouble[ 215] =       1;
    vdouble[ 216] =       1; vdouble[ 217] =       1; vdouble[ 218] =       1; vdouble[ 219] =       1;
    vdouble[ 220] =       1; vdouble[ 221] =       1; vdouble[ 222] =       1; vdouble[ 223] =       1;
    vdouble[ 224] =       1; vdouble[ 225] =       1; vdouble[ 226] =       1; vdouble[ 227] =       1;
    vdouble[ 228] =       1; vdouble[ 229] =       1; vdouble[ 230] =       1; vdouble[ 231] =       1;
    vdouble[ 232] =       1; vdouble[ 233] =       1; vdouble[ 234] =       1; vdouble[ 235] =       1;
    vdouble[ 236] =       1; vdouble[ 237] =       1; vdouble[ 238] =       1; vdouble[ 239] =       1;
    vdouble[ 240] =       1; vdouble[ 241] =       1; vdouble[ 242] =       1; vdouble[ 243] =       1;
    vdouble[ 244] =       1; vdouble[ 245] =       1; vdouble[ 246] =       1; vdouble[ 247] =       1;
    vdouble[ 248] =       1; vdouble[ 249] =       1; vdouble[ 250] =       1; vdouble[ 251] =       1;
    vdouble[ 252] =       1; vdouble[ 253] =       1; vdouble[ 254] =       1; vdouble[ 255] =       1;
    vdouble[ 256] =       1; vdouble[ 257] =       1; vdouble[ 258] =       1; vdouble[ 259] =       1;
    vdouble[ 260] =       1; vdouble[ 261] =       1; vdouble[ 262] =       1; vdouble[ 263] =       1;
    vdouble[ 264] =       1; vdouble[ 265] =       1; vdouble[ 266] =       1; vdouble[ 267] =       1;
    vdouble[ 268] =       1; vdouble[ 269] =       1; vdouble[ 270] =       1; vdouble[ 271] =       1;
    vdouble[ 272] =       1; vdouble[ 273] =       1; vdouble[ 274] =       1; vdouble[ 275] =       1;
    vdouble[ 276] =       1; vdouble[ 277] =       1; vdouble[ 278] =       1; vdouble[ 279] =       1;
    vdouble[ 280] =       1; vdouble[ 281] =       1; vdouble[ 282] =       1; vdouble[ 283] =       1;
    vdouble[ 284] =       1; vdouble[ 285] =       1; vdouble[ 286] =       1; vdouble[ 287] =       1;
    vdouble[ 288] =       1; vdouble[ 289] =       1; vdouble[ 290] =       1; vdouble[ 291] =       1;
    vdouble[ 292] =       1; vdouble[ 293] =       1; vdouble[ 294] =       1; vdouble[ 295] =       1;
    vdouble[ 296] =       1; vdouble[ 297] =       1; vdouble[ 298] =       1; vdouble[ 299] =       1;
    vdouble[ 300] =       1; vdouble[ 301] =       1; vdouble[ 302] =       1; vdouble[ 303] =       1;
    vdouble[ 304] =       1; vdouble[ 305] =       1; vdouble[ 306] =       1; vdouble[ 307] =       1;
    vdouble[ 308] =       1; vdouble[ 309] =       1; vdouble[ 310] =       1; vdouble[ 311] =       1;
    vdouble[ 312] =       1; vdouble[ 313] =       1; vdouble[ 314] =       1; vdouble[ 315] =       1;
    vdouble[ 316] =       1; vdouble[ 317] =       1; vdouble[ 318] =       1; vdouble[ 319] =       1;
    vdouble[ 320] =       1; vdouble[ 321] =       1; vdouble[ 322] =       1; vdouble[ 323] =       1;
    vdouble[ 324] =       1; vdouble[ 325] =       1; vdouble[ 326] =       1; vdouble[ 327] =       1;
    vdouble[ 328] =       1; vdouble[ 329] =       1; vdouble[ 330] =       1; vdouble[ 331] =       1;
    vdouble[ 332] =       1; vdouble[ 333] =       1; vdouble[ 334] =       1; vdouble[ 335] =       1;
    vdouble[ 336] =       1; vdouble[ 337] =       1; vdouble[ 338] =       1; vdouble[ 339] =       1;
    vdouble[ 340] =       1; vdouble[ 341] =       1; vdouble[ 342] =       1; vdouble[ 343] =       1;
    vdouble[ 344] =       1; vdouble[ 345] =       1; vdouble[ 346] =       1; vdouble[ 347] =       1;
    vdouble[ 348] =       1; vdouble[ 349] =       1; vdouble[ 350] =       1; vdouble[ 351] =       1;
    vdouble[ 352] =       1; vdouble[ 353] =       1; vdouble[ 354] =       1; vdouble[ 355] =       1;
    vdouble[ 356] =       1; vdouble[ 357] =       1; vdouble[ 358] =       1; vdouble[ 359] =       1;
    vdouble[ 360] =       1; vdouble[ 361] =       1; vdouble[ 362] =       1; vdouble[ 363] =       1;
    vdouble[ 364] =       1; vdouble[ 365] =       1; vdouble[ 366] =       1; vdouble[ 367] =       1;
    vdouble[ 368] =       1; vdouble[ 369] =       1; vdouble[ 370] =       1; vdouble[ 371] =       1;
    vdouble[ 372] =       1; vdouble[ 373] =       1; vdouble[ 374] =       1; vdouble[ 375] =       1;
    vdouble[ 376] =       1; vdouble[ 377] =       1; vdouble[ 378] =       1; vdouble[ 379] =       1;
    vdouble[ 380] =       1; vdouble[ 381] =       1; vdouble[ 382] =       1; vdouble[ 383] =       1;
    vdouble[ 384] =       1; vdouble[ 385] =       1; vdouble[ 386] =       1; vdouble[ 387] =       1;
    vdouble[ 388] =       1; vdouble[ 389] =       1; vdouble[ 390] =       1; vdouble[ 391] =       1;
    vdouble[ 392] =       1; vdouble[ 393] =       1; vdouble[ 394] =       1; vdouble[ 395] =       1;
    vdouble[ 396] =       1; vdouble[ 397] =       1; vdouble[ 398] =       1; vdouble[ 399] =       1;
    vdouble[ 400] =       1; vdouble[ 401] =       1; vdouble[ 402] =       1; vdouble[ 403] =       1;
    vdouble[ 404] =       1; vdouble[ 405] =       1; vdouble[ 406] =       1; vdouble[ 407] =       1;
    vdouble[ 408] =       1; vdouble[ 409] =       1; vdouble[ 410] =       1; vdouble[ 411] =       1;
    vdouble[ 412] =       1; vdouble[ 413] =       1; vdouble[ 414] =       1; vdouble[ 415] =       1;
    vdouble[ 416] =       1; vdouble[ 417] =       1; vdouble[ 418] =       1; vdouble[ 419] =       1;
    vdouble[ 420] =       1; vdouble[ 421] =       1; vdouble[ 422] =       1; vdouble[ 423] =       1;
    vdouble[ 424] =       1; vdouble[ 425] =       1; vdouble[ 426] =       1; vdouble[ 427] =       1;
    vdouble[ 428] =       1; vdouble[ 429] =       1; vdouble[ 430] =       1; vdouble[ 431] =       1;
    vdouble[ 432] =       1; vdouble[ 433] =       1; vdouble[ 434] =       1; vdouble[ 435] =       1;
    vdouble[ 436] =       1; vdouble[ 437] =       1; vdouble[ 438] =       1; vdouble[ 439] =       1;
    vdouble[ 440] =       1; vdouble[ 441] =       1; vdouble[ 442] =       1; vdouble[ 443] =       1;
    vdouble[ 444] =       1; vdouble[ 445] =       1; vdouble[ 446] =       1; vdouble[ 447] =       1;
    vdouble[ 448] =       1; vdouble[ 449] =       1; vdouble[ 450] =       1; vdouble[ 451] =       1;
    vdouble[ 452] =       1; vdouble[ 453] =       1; vdouble[ 454] =       1; vdouble[ 455] =       1;
    vdouble[ 456] =       1; vdouble[ 457] =       1; vdouble[ 458] =       1; vdouble[ 459] =       1;
    vdouble[ 460] =       1; vdouble[ 461] =       1; vdouble[ 462] =       1; vdouble[ 463] =       1;
    vdouble[ 464] =       1; vdouble[ 465] =       1; vdouble[ 466] =       1; vdouble[ 467] =       1;
    vdouble[ 468] =       1; vdouble[ 469] =       1; vdouble[ 470] =       1; vdouble[ 471] =       1;
    vdouble[ 472] =       1; vdouble[ 473] =       1; vdouble[ 474] =       1; vdouble[ 475] =       1;
    vdouble[ 476] =       1; vdouble[ 477] =       1; vdouble[ 478] =       1; vdouble[ 479] =       1;
    vdouble[ 480] =       1; vdouble[ 481] =       1; vdouble[ 482] =       1; vdouble[ 483] =       1;
    vdouble[ 484] =       1; vdouble[ 485] =       1; vdouble[ 486] =       1; vdouble[ 487] =       1;
    vdouble[ 488] =       1; vdouble[ 489] =       1; vdouble[ 490] =       1; vdouble[ 491] =       1;
    vdouble[ 492] =       1; vdouble[ 493] =       1; vdouble[ 494] =       1; vdouble[ 495] =       1;
   
    GRIB_CHECK(grib_set_double_array(h,"values",vdouble,size),0);
    free(vdouble);
    GRIB_CHECK(grib_set_long(h,"dirty_statistics",1),0);
    GRIB_CHECK(grib_set_long(h,"changeDecimalPrecision",0),0);
    GRIB_CHECK(grib_set_long(h,"decimalPrecision",0),0);
    GRIB_CHECK(grib_set_long(h,"setBitsPerValue",0),0);
/* Save the message */

    f = fopen(argv[1],"w");
    if(!f) {
        perror(argv[1]);
        exit(1);
    }

    GRIB_CHECK(grib_get_message(h,&buffer,&size),0);

    if(fwrite(buffer,1,size,f) != size) {
        perror(argv[1]);
        exit(1);
    }

    if(fclose(f)) {
        perror(argv[1]);
        exit(1);
    }

    grib_handle_delete(h);
    return 0;
}
Example #7
0
/*
 The options have been parsed and the structure
 grib_runtime_options* options has been loaded.
 Initialisation and startup can be done here
*/
int grib_tool_init(grib_runtime_options* options)
{
    char  *theEnd = NULL, *end1=NULL;
    size_t size=4;
    int ret=0;
    double min=0,max=0;
    int i=0;
    char* p=NULL;
    if (options->latlon && grib_options_on("j")) {
        options->verbose=0;
        json_latlon=1;
    }

    if (options->latlon) {

        lat = strtod(options->latlon,&theEnd);
        if (*theEnd != ',') {
            printf("ERROR: wrong latitude value\n");
            exit(1);
        }
        lon= strtod(++theEnd,&end1);

        mode=GRIB_NEAREST_SAME_POINT | GRIB_NEAREST_SAME_GRID;

        if (end1 && *end1 == ',') {
            end1++;
            if (*end1 != '0') {
                p=end1;
                while (*p != ',' && *p !='\0') p++;
                if (*end1 == '4') {
                    options->latlon_mode=4;
                } else if (*end1 == '1') {
                    options->latlon_mode=1;
                } else {
                    printf("ERROR %s: wrong mode given in option -l\n",grib_tool_name);
                    exit(1);
                }
            }
            if (*p == ',') {
                p++;
                options->latlon_mask=strdup(p);
            }
        }
    }

    if (options->latlon && options->latlon_mask) {
        FILE* f=NULL;
        grib_handle* hh;
        int idx=0, land_found=0;
        double min_overall = 0.0;
        int idx_overall = -1;
        f=fopen(options->latlon_mask,"r");
        if(!f) {
            perror(options->latlon_mask);
            exit(1);
        }
        hh=grib_handle_new_from_file(0,f,&ret);
        fclose(f);
        GRIB_CHECK_NOLINE(ret,0);
        n=grib_nearest_new(hh,&ret);
        GRIB_CHECK_NOLINE(ret,0);
        GRIB_CHECK_NOLINE(grib_nearest_find(n,hh,lat,lon,mode,
                options->lats,options->lons,options->mask_values,options->distances,options->indexes,&size),0);
        grib_nearest_delete(n);
        n=NULL;
        grib_handle_delete(hh);

        options->latlon_idx=-1;
        max=options->distances[0];
        for (i=0;i<4;i++)
            if (max<options->distances[i]) {max=options->distances[i];}
        min=max;
        min_overall=max;
        /* See GRIB-213 */
        for (i=0;i<4;i++) {
            if (min_overall >= options->distances[i]) { /* find overall min and index ignoring mask */
                min_overall = options->distances[i];
                idx_overall = i;
            }
            if ((min >= options->distances[i]) && (options->mask_values[i] >= 0.5)) {
                land_found=1; /* found at least one point which is land */
                min = options->distances[i];
                idx = i;
            }
        }
        if (land_found) {
            options->latlon_idx=idx;
        } else {
            options->latlon_idx=idx_overall; /* all points were sea, so pick the min overall */
        }

        if (options->latlon_idx<0){
            min=0;
            options->latlon_idx=0;
            for (i=1;i<4;i++)
                if (min>options->distances[i]) {
                    min = options->distances[i];
                    options->latlon_idx=i;
                }
        }
    }
    if (json_latlon) printf("[\n");

    return 0;
}
Example #8
0
int main(int argc, char** argv) {
	int err = 0;

	size_t i = 0;
	size_t count;
	size_t size;

	long numberOfContributingSpectralBands;
	long values[1024];

	FILE* in = NULL;
	char* filename = "../../data/satellite.grib";
	grib_handle *h = NULL;

	in = fopen(filename,"r");
	if(!in) {
		printf("ERROR: unable to open file %s\n",filename);
		return 1;
	}

	/* create new handle from a message in a file*/
	h = grib_handle_new_from_file(0,in,&err);
	if (h == NULL) {
		printf("Error: unable to create handle from file %s\n",filename);
	}

	numberOfContributingSpectralBands = 2;
	GRIB_CHECK(grib_set_long(h,"numberOfContributingSpectralBands",numberOfContributingSpectralBands),0);

	numberOfContributingSpectralBands = 9;
	GRIB_CHECK(grib_set_long(h,"numberOfContributingSpectralBands",numberOfContributingSpectralBands),0);

	/* get as a long*/
	GRIB_CHECK(grib_get_long(h,"numberOfContributingSpectralBands",&numberOfContributingSpectralBands),0);
	printf("numberOfContributingSpectralBands=%ld\n",numberOfContributingSpectralBands);

	/* get as a long*/
	GRIB_CHECK(grib_get_size(h,"scaledValueOfCentralWaveNumber",&count),0);
	printf("count=%ld\n",(long)count);

	assert(count < sizeof(values)/sizeof(values[0]));

	size = count;
	GRIB_CHECK(grib_get_long_array(h,"scaledValueOfCentralWaveNumber",values,&size),0);
	assert(size == count);

	for(i=0;i<count;i++)
		printf("scaledValueOfCentralWaveNumber %lu = %ld\n",(unsigned long)i,values[i]);

	for(i=0;i<count;i++)
		values[i] = -values[i]; 

	size = count;
	/* size--; */
	GRIB_CHECK(grib_set_long_array(h,"scaledValueOfCentralWaveNumber",values,size),0);
	assert(size == count);

	grib_handle_delete(h);

	fclose(in);
	return 0;
}
Example #9
0
int main(int argc,char* argv[])
{
  grib_index* index=NULL;
  grib_handle* h=NULL;
  long *step,*level,*number;
  char** shortName=NULL;
  int i,j,k,l;
  size_t stepSize,levelSize,shortNameSize,numberSize;
  long ostep,olevel,onumber;
  char oshortName[200];
  size_t lenshortName=200;
  int ret=0,count=0;

  if (argc != 2) usage(argv[0]);

  printf("indexing...\n");

  index=grib_index_read(0,"out.gribidx",&ret);
  GRIB_CHECK(ret,0);

  printf("end indexing...\n");

  /* get the number of distinct values of "step" in the index */
  GRIB_CHECK(grib_index_get_size(index,"step",&stepSize),0);
  step=(long*)malloc(sizeof(long)*stepSize);
  if (!step) exit(1);
  /* get the list of distinct steps from the index */
  /* the list is in ascending order */
  GRIB_CHECK(grib_index_get_long(index,"step",step,&stepSize),0);
  printf("stepSize=%ld\n",(long)stepSize);
  for (i=0;i<stepSize;i++) printf("%ld ",step[i]);
  printf("\n");

  /*same as for "step"*/
  GRIB_CHECK(grib_index_get_size(index,"level",&levelSize),0);
  level=(long*)malloc(sizeof(long)*levelSize);
  if (!level) exit(1);
  /*same as for "step"*/
  GRIB_CHECK(grib_index_get_long(index,"level",level,&levelSize),0);
  printf("levelSize=%ld\n",(long)levelSize);
  for (i=0;i<levelSize;i++) printf("%ld ",level[i]);
  printf("\n");

  /*same as for "step"*/
  GRIB_CHECK(grib_index_get_size(index,"number",&numberSize),0);
  number=(long*)malloc(sizeof(long)*numberSize);
  if (!number) exit(1);
  /*same as for "step"*/
  GRIB_CHECK(grib_index_get_long(index,"number",number,&numberSize),0);
  printf("numberSize=%ld\n",(long)numberSize);
  for (i=0;i<numberSize;i++) printf("%ld ",number[i]);
  printf("\n");

  /*same as for "step"*/
  GRIB_CHECK(grib_index_get_size(index,"shortName",&shortNameSize),0);
  shortName=(char**)malloc(sizeof(char*)*shortNameSize);
  if (!shortName) exit(1);
  /*same as for "step"*/
  GRIB_CHECK(grib_index_get_string(index,"shortName",shortName,&shortNameSize),0);
  printf("shortNameSize=%ld\n",(long)shortNameSize);
  for (i=0;i<shortNameSize;i++) printf("%s ",shortName[i]);
  printf("\n");

  count=0;
  /* nested loops on the keys values of the index */
  /* different order of the nested loops doesn't affect performance*/
  for (i=0;i<shortNameSize;i++) {
    /* select the grib with shortName=shortName[i] */
    grib_index_select_string(index,"shortName",shortName[i]);

    for (l=0;l<levelSize;l++) {
      /* select the grib with level=level[i] */
      grib_index_select_long(index,"level",level[l]);

      for (j=0;j<numberSize;j++) {
        /* select the grib with number=number[i] */
        grib_index_select_long(index,"number",number[j]);

        for (k=0;k<stepSize;k++) {
          /* select the grib with step=step[i] */
          grib_index_select_long(index,"step",step[k]);

		 /* create a new grib_handle from the index with the constraints 
		    imposed by the select statements. It is a loop because
			in the index there could be more than one grib with those
			constrants */
         while ((h=grib_handle_new_from_index(index,&ret))!=NULL){
		   count++;
           if (ret) {printf("error: %d\n",ret); exit(ret);}
           lenshortName=200;
		   grib_get_string(h,"shortName",oshortName,&lenshortName);
		   grib_get_long(h,"level",&olevel);
		   grib_get_long(h,"number",&onumber);
		   grib_get_long(h,"step",&ostep);
		   printf("shortName=%s ",oshortName);
		   printf("level=%ld ",olevel);
		   printf("number=%ld ",onumber);
		   printf("step=%ld \n",ostep);
		   grib_handle_delete(h);
		 }
         if (ret!=GRIB_END_OF_INDEX) {printf("error: %s\n",grib_get_error_message(ret)); exit(ret);}
	    } 
	  }
	}
  }
  printf("  %d messages selected\n",count);


  return 0;
}
Example #10
0
int main(int argc, char** argv)
{
  int err = 0;
  FILE* in = NULL;
  FILE* of = NULL;
  long edition, step;
  char* filename=NULL;
  char* ofilename=NULL;
  grib_handle *h = NULL;
  grib_multi_handle *mh=NULL;
  const int start_section = 4; /* Grib2 Product Definition Section */

  if (argc < 3) usage(argv[0]);
  filename=argv[1];
  ofilename=argv[2];

  /* open input file */
  in = fopen(filename,"r");
  if(!in) {
    fprintf(stderr, "ERROR: unable to open input file %s\n",filename);
    return 1;
  }

  /* new grib handle from input file */
  h = grib_handle_new_from_file(0,in,&err);  
  GRIB_CHECK(err,0);
  GRIB_CHECK(grib_get_long(h,"edition",&edition),0);
  if (edition != 2) {
     fprintf(stderr, "ERROR: Input grib must be edition 2 for multi fields\n");
     exit(1);
  }
  
  /* create a new empty multi field handle */
  mh=grib_multi_handle_new(0);
  if (!mh) {
    fprintf(stderr,"ERROR: Unable to create multi field handle\n");
    exit(1);
  }

  for (step=12;step<=120;step+=12) {
    /* set step */
    grib_set_long(h,"step",step);
	 /* append h to mh repeating from section 4 */
	 /* i.e. starting from section 4 all the sections to the end of the message will be copied */
	 grib_multi_handle_append(h, start_section, mh);
  }

  /* open output file */
  of=fopen(ofilename,"w");
  if(!of) {
	 fprintf(stderr, "ERROR: unable to open output file %s\n",ofilename);
    exit(1);
  }

  /* write multi fields handle to output file */
  grib_multi_handle_write(mh,of);
  fclose(of);

  /* release memory */
  grib_handle_delete(h);
  grib_multi_handle_delete(mh);

  fclose(in);
  return 0;
}
Example #11
0
int main(int argc, const char *argv[])
{
	int i,j;
	FILE *in,*out;
	int e;
	grib_handle *result = NULL,*h;
	double* values = NULL;
	double *tmp = NULL;
	size_t size,count;

    fprintf(stderr, "\nWARNING: The tool %s is deprecated.\n\n", argv[0]);

	if(argc < 3) usage(argv[0]);

	out = fopen(argv[argc-1],"w");
	if(!out) {
		perror(argv[argc-1]);
		exit(1);
	}

	for(i = 1; i < argc-1; i++)
	{
		in = fopen(argv[i],"r");
		if(!in) {
			perror(argv[i]);
			exit(1);
		}

		while( (h = grib_handle_new_from_file(NULL,in,&e)) != NULL )
		{
			if(result == NULL)
			{
				GRIB_CHECK(grib_get_size(h,"values",&size),argv[i]);

				values = (double*)calloc(size,sizeof(double));
				assert(values);

				tmp    = (double*)calloc(size,sizeof(double));
				assert(tmp);

				result = h;
			}

			GRIB_CHECK(grib_get_size(h,"values",&count),argv[i]);
			assert(count == size);

			GRIB_CHECK(grib_get_double_array(h,"values",tmp,&count),argv[i]);
			assert(count == size);

			for(j = 0; j < count; j++)
				values[j] += tmp[j];

			if(h != result)
				grib_handle_delete(h);
		}

		GRIB_CHECK(e,argv[argc-2]);
	}

	if(result)
	{
		const void *buffer; 
		GRIB_CHECK(grib_set_double_array(result,"values",values,size),argv[i]);
		GRIB_CHECK(grib_get_message(result,&buffer,&size),argv[0]);

		if(fwrite(buffer,1,size,out) != size)
		{
			perror(argv[argc-1]);
			exit(1);
		}
		grib_handle_delete(result);
	}

	if(fclose(out))
	{
		perror(argv[argc-1]);
		exit(1);
	}

	return 0;
}
Example #12
0
int main(int argc, char* argv[]) {
	int order,count,i,j,k,l;
	FILE *f1,*f2;
	double *m1,*m2,*dm;
	int ret=0;
	long numberOfValues;
	double geast,gwest,gnorth,gsouth;
	double *east,*west,*north,*south;
	grib_handle *h1,*h2;
	grib_context *c=grib_context_get_default();
	int split=1;

    fprintf(stderr, "\nWARNING: The tool %s is deprecated.\n\n", argv[0]);
	if (argc!=5) usage(argv[0]);

	split=atoi(argv[1]);
	order=atoi(argv[2]);

	f1=fopen(argv[3],"r");
	if (!f1) {
		perror(argv[3]);
		exit(1);
	}

	f2=fopen(argv[4],"r");
	if (!f2) {
		perror(argv[4]);
		exit(1);
	}

	m1=(double*)grib_context_malloc_clear(c,sizeof(double)*order*order);
	m2=(double*)grib_context_malloc_clear(c,sizeof(double)*order*order);
	dm=(double*)grib_context_malloc_clear(c,sizeof(double)*order*order);
	east=(double*)grib_context_malloc_clear(c,sizeof(double)*split);
	south=(double*)grib_context_malloc_clear(c,sizeof(double)*split);
	north=(double*)grib_context_malloc_clear(c,sizeof(double)*split);
	west=(double*)grib_context_malloc_clear(c,sizeof(double)*split);

	count=0;
	while ((h1=grib_handle_new_from_file(0,f1,&ret))!=NULL && (h2=grib_handle_new_from_file(0,f2,&ret))!=NULL) {
		get_box(h1,&geast,&gnorth,&gwest,&gsouth);
		if (split>1) {
			double inc=0;
			double d=(gwest-geast)/split;
			
			inc=0;
			for (i=0;i<split;i++) {
				east[i]=geast+inc;
				inc+=d;
				west[i]=geast+inc;
			}
			d=(gnorth-gsouth)/split;
			inc=0;
			for (i=0;i<split;i++) {
				south[i]=gsouth+inc;
				inc+=d;
				north[i]=gsouth+inc;
			}
		} else {
			east[0]=geast;
			north[0]=gnorth;
			south[0]=gsouth;
			west[0]=gwest;
		}

		for (k=0;k<split;k++) {
			for (l=0;l<split;l++) {
				printf("- %d - east=%.3f \twest=%.3f \tsouth=%.3f \tnorth=%.3f\n",count+1,east[k],west[k],south[l],north[l]);
				grib_moments(h1,east[k],north[l],west[k],south[l],order,m1,&numberOfValues);
				grib_moments(h2,east[k],north[l],west[k],south[l],order,m2,&numberOfValues);

				printf("numberOfValues=%ld\n",numberOfValues);
				for (i=0;i<order;i++) {
					for (j=0;j<order;j++) {
						printf("  (%d,%d)   ",i,j);
					}
				}
				printf("\n");
				for (i=0;i<order*order;i++) printf("% .2e ",m1[i]);
				printf("\n");
				for (i=0;i<order*order;i++) printf("% .2e ",m2[i]);
				printf("\n");
				for (i=0;i<order*order;i++) printf("% .2e ",fabs((m1[i]-m2[i])/m2[i]));
				printf("\n\n");
			}
		}
		grib_handle_delete(h2);
		grib_handle_delete(h1);

		count++;
	}

	grib_context_free(c,m1);
	grib_context_free(c,m2);
	grib_context_free(c,dm);
	grib_context_free(c,east);
	grib_context_free(c,south);
	grib_context_free(c,north);
	grib_context_free(c,west);

	fclose(f1);
	fclose(f2);

	return 0;
}
Example #13
0
int grib_tool_init(grib_runtime_options* options)
{
    char  *end = NULL, *end1=NULL;
    size_t size=4;
    int ret=0;
    double min=0,max=0;
    int i=0;
    char* p=NULL;

    options->print_header=0;
    options->print_statistics=0;
    options->default_print_width=-1;

    if (options->latlon) {

        lat = strtod(options->latlon,&end);
        if (*end != ',') {
            printf("ERROR: wrong latitude value\n");
            exit(1);
        }
        lon= strtod(++end,&end1);

        mode=GRIB_NEAREST_SAME_POINT | GRIB_NEAREST_SAME_GRID;

        if (end1 && *end1 == ',') {
            end1++;
            if (*end1 != '0') {
                p=end1;
                while (*p != ',' && *p !='\0') p++;
                if (*end1 == '4') {
                    options->latlon_mode=4;
                } else if (*end1 == '1') {
                    options->latlon_mode=1;
                } else {
                    printf("ERROR %s: wrong mode given in option -l\n",grib_tool_name);
                    exit(1);
                }
            }
            if (*p == ',') {
                p++;
                options->latlon_mask=strdup(p);
            }
        }


    }

    if (options->latlon && options->latlon_mask) {
        FILE* f=NULL;
        grib_handle* hh;
        f=fopen(options->latlon_mask,"r");
        if(!f) {
            perror(options->latlon_mask);
            exit(1);
        }
        hh=grib_handle_new_from_file(0,f,&ret);
        fclose(f);
        GRIB_CHECK_NOLINE(ret,0);
        n=grib_nearest_new(hh,&ret);
        GRIB_CHECK_NOLINE(ret,0);
        GRIB_CHECK_NOLINE(grib_nearest_find(n,hh,lat,lon,mode,
                options->lats,options->lons,options->mask_values,options->distances,options->indexes,&size),0);
        grib_nearest_delete(n);
        n=NULL;
        grib_handle_delete( hh);

        options->latlon_idx=-1;
        max=options->distances[0];
        for (i=0;i<4;i++)
            if (max<options->distances[i]) {max=options->distances[i];}
        min=max;
        for (i=0;i<4;i++) {
            if ((min >= options->distances[i]) && (options->mask_values[i] >= 0.5)) {
                options->latlon_idx=i;
                min = options->distances[i];
            }
        }

        if (options->latlon_idx<0){
            min=0;
            options->latlon_idx=0;
            for (i=1;i<4;i++)
                if (min>options->distances[i]) {
                    min = options->distances[i];
                    options->latlon_idx=i;
                }
        }
    }

    return 0;
}
Example #14
0
int main(int argc, char** argv) {
  FILE* fin=0;
  int ret=0;
  char* fname=0;
  float lat,lon;
  double *vlat,*vlon;
  int npoints=0,i=0,n=0;
  grib_handle* h;
  double *outlats,*outlons,*values,*lsm_values,*distances;
  size_t* indexes;

  if (argc < 2) usage(argv[0]);

  fname=argv[1];
  fin=fopen(fname,"r");
  if(!fin) { perror(fname); exit(1); }
  npoints=0;
  while (fscanf(fin,"%g %g",&lat,&lon) != EOF) npoints++;
  fclose(fin);

  vlat=(double*)malloc(npoints*sizeof(double));
  if (!vlat) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  vlon=(double*)malloc(npoints*sizeof(double));
  if (!vlon) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  outlats=(double*)malloc(npoints*sizeof(double));
  if (!outlats) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  outlons=(double*)malloc(npoints*sizeof(double));
  if (!outlons) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  values=(double*)malloc(npoints*sizeof(double));
  if (!values) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  lsm_values=(double*)malloc(npoints*sizeof(double));
  if (!lsm_values) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  distances=(double*)malloc(npoints*sizeof(double));
  if (!distances) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}
  indexes=(size_t*)malloc(npoints*sizeof(double));
  if (!indexes) {printf("unable to allocate %d bytes\n",npoints*sizeof(double));exit(1);}

  fname=argv[1];
  fin=fopen(fname,"r");
  if(!fin) { perror(fname); exit(1); }
  i=0;
  while (fscanf(fin,"%g %g",&lat,&lon) != EOF) {vlat[i]=lat; vlon[i]=lon>0 ? lon : lon+360; i++;}
  fclose(fin);

  fname=argv[2];
  fin=fopen(fname,"r");
  if(!fin) { perror(fname); exit(1); }
  h=grib_handle_new_from_file(0,fin,&ret);
  if (!h || ret!=GRIB_SUCCESS) {printf(" unable to create handle\n");exit(1);}

  grib_nearest_find_multiple(h,1,vlat,vlon,npoints,
        outlats,outlons,lsm_values,distances,indexes);

  grib_handle_delete(h);

  fclose(fin);

  for (n=3;n<=argc-1;n++) {
    fname=argv[n];
    fin=fopen(fname,"r");
    if(!fin) { perror(fname); exit(1); }
    while ((h=grib_handle_new_from_file(0,fin,&ret))!=NULL) {
       grib_get_double_elements(h,"values",indexes,npoints,values);

       grib_handle_delete(h);
       for (i=0;i<npoints;i++)
          printf("%g %g %g %g %g %g\n",
            vlat[i],vlon[i],
            outlats[i],outlons[i],
            lsm_values[i],values[i]);
    }


    fclose(fin);
  }



  return ret;
}
Example #15
0
int main(int argc, char** argv)
{
    int err = 0;
    size_t size=0;

    FILE* in = NULL;
    char* infile = "../../data/regular_latlon_surface.grib1";
    FILE* out = NULL;
    char* outfile = "out.precision.grib1";
    grib_handle *h = NULL;
    const void* buffer = NULL;
    double* values1=NULL;
    double* values2=NULL;
    double maxa=0;
    double maxv=0,minv=0;
    double maxr=0,r=0;
    long decimalPrecision;
    long bitsPerValue1=0, bitsPerValue2=0;
    int i=0;

    in = fopen(infile,"r");
    if(!in) {
        printf("ERROR: unable to open input file %s\n",infile);
        return 1;
    }

    out = fopen(outfile,"w");
    if(!out) {
        printf("ERROR: unable to open output file %s\n",outfile);
        fclose(in);
        return 1;
    }

    /* create a new handle from a message in a file */
    h = grib_handle_new_from_file(0,in,&err);
    if (h == NULL) {
        printf("Error: unable to create handle from file %s\n",infile);
    }

    /* bitsPerValue before changing the packing parameters */
    GRIB_CHECK(grib_get_long(h,"bitsPerValue",&bitsPerValue1),0);
    assert(bitsPerValue1 == 16);

    /* get the size of the values array*/
    GRIB_CHECK(grib_get_size(h,"values",&size),0);
    assert(size == 496);

    values1 = (double*)malloc(size*sizeof(double));
    /* get data values before changing the packing parameters*/
    GRIB_CHECK(grib_get_double_array(h,"values",values1,&size),0);

    /* changing decimal precision to 2 means that 2 decimal digits
     are preserved when packing.  */
    decimalPrecision=2;
    GRIB_CHECK(grib_set_long(h,"changeDecimalPrecision",decimalPrecision),0);

    /* bitsPerValue after changing the packing parameters */
    GRIB_CHECK(grib_get_long(h,"bitsPerValue",&bitsPerValue2),0);
    assert(bitsPerValue2 == 12);

    values2 = (double*)malloc(size*sizeof(double));
    /* get data values after changing the packing parameters*/
    GRIB_CHECK(grib_get_double_array(h,"values",values2,&size),0);

    /* computing error */
    maxa=0;
    maxr=0;
    maxv=values2[0];
    minv=maxv;
    for (i=0;i<size;i++) {
        double a=fabs(values2[i]-values1[i]);
        if ( values2[i] > maxv ) maxv=values2[i];
        if ( values2[i] < minv ) minv=values2[i];
        if ( values2[i] !=0 ) r=fabs((values2[i]-values1[i])/values2[i]);
        if ( a > maxa ) maxa=a;
        if ( r > maxr ) maxr=r;
    }
    printf("max absolute error = %g\n",maxa);
    printf("max relative error = %g\n",maxr);
    printf("min value = %g\n",minv);
    printf("max value = %g\n",maxv);
    assert(fabs(minv - EXPECTED_MIN) < EPSILON);
    assert(fabs(maxv - EXPECTED_MAX) < EPSILON);

    /* get the coded message in a buffer */
    GRIB_CHECK(grib_get_message(h,&buffer,&size),0);

    /* write the buffer in a file*/
    if(fwrite(buffer,1,size,out) != size)
    {
        perror(argv[1]);
        exit(1);
    }

    grib_handle_delete(h);

    fclose(in);
    fclose(out);

    return 0;
}
Example #16
0
/*
 A new handle to skip is available. At this point something can be done
 with the message to be skipped before deleting the handle
*/
int grib_tool_skip_handle(grib_runtime_options* options, grib_handle* h)
{
    grib_handle_delete(h);
    return 0;
}
Example #17
0
int main(int argc, char* argv[]) {
  int i;
  grib_handle *h=NULL;
  grib_handle *hso=NULL;
  grib_context* c=NULL;
  FILE* fin=NULL;
  FILE* fout=NULL;
  char* finname;
  char* ofilename;
  char defofilename[]="so_perf.out";
  double *values=NULL;
  double gvalues[1000000]={0,};
  double sovalues[1000000]={0,};
  int append=0;
  size_t nvalues=0;
  int count,e=0;
  int repeatso=1;
  int repeatsimple=1;
  grib_timer *tes,*tds,*teso,*tdso;
  char grid_simple[]="grid_simple";
  size_t grid_simple_l=strlen(grid_simple);
  char packingType[50]={0,};
  size_t len=50;
  char param[50]={0,};
  char gridType[50]={0,};
  char outfilename[255]={0,};
  size_t filesize_so=0;
  size_t filesize_simple=0;
  double perc=0;
  long bitsPerValue=0;
  int iarg=1;
  char grid[20]={0,};
  char shortName[20]={0,};
  long level;
  char levelType[20]={0,};
  char buffer[BUFF_SIZE]={0,};
  char buf[BUFF_SIZE]={0,};
  size_t length;
  int sec4len;
  flong ksec0[ISECTION_0];
  flong ksec1[ISECTION_1];
  flong ksec2[ISECTION_2];
  flong ksec3[ISECTION_3];
  flong ksec4[ISECTION_4];
  flong miss=0;
  const void *msg;
  flong gribex_msg_len=0;
  double packingError=0;


  double rsec2[RSECTION_2];
  double rsec3[RSECTION_3];

  tes=grib_get_timer(0,"encoding simple", 0, 0);
  tds=grib_get_timer(0,"decoding simple", 0, 0);
  teso=grib_get_timer(0,"encoding so", 0, 0);
  tdso=grib_get_timer(0,"decoding so", 0, 0);

  if (argc != 4 && argc != 6 ) usage(argv[0]);
  if (!strcmp(argv[iarg],"-w")) {
	append=0;
	iarg++;
	ofilename=argv[iarg];
	iarg++;
  } else if (!strcmp(argv[iarg],"-a")) {
	append=1;
	iarg++;
	ofilename=argv[iarg];
	iarg++;
  } else {
	append=0;
  	ofilename=defofilename;
  }
  finname=argv[iarg++];
  repeatsimple=atoi(argv[iarg++]);
  bitsPerValue=atoi(argv[iarg++]);

  fin = fopen(finname,"r");
  if(!fin) {perror(finname);exit(1);}

  c=grib_context_get_default();
  length=BUFF_SIZE;
  GRIB_CHECK(grib_read_any_from_file(c,fin,buffer,&length),0);
  fclose(fin);


  if (append) 
	  fout = fopen(ofilename,"a");
  else
	  fout = fopen(ofilename,"w");

  if(!fout) {perror(ofilename);exit(1);}

  c=grib_context_get_default();
  e=0;
  h=grib_handle_new_from_message_copy(c,buffer,length);

  GRIB_CHECK(e,0);

  len=50;
  grib_get_string(h,"shortName",param,&len);

  len=20;
  grib_get_string(h,"levelType",levelType,&len);

  if (!strcmp(levelType,"pl")) {
  	GRIB_CHECK(grib_get_long(h,"level",&level),0);
	sprintf(shortName,"%s%ld",param,level);
  } else {
	sprintf(shortName,"%s",param);
  }

  /* grib_set_long(h,"editionNumber",2); */
  GRIB_CHECK(grib_get_size(h,"values",&nvalues),0);
  values=(double*)grib_context_malloc_clear(c,sizeof(double)*nvalues);
  if (!values) { printf("%s: memory allocation error\n",argv[0]); exit(1); }

  len=50;
  grib_get_string(h,"gridType",gridType,&len);

  len=50;
  grib_get_string(h,"packingType",packingType,&len);

  GRIB_CHECK(grib_get_double_array(h,"values",values,&nvalues),0);
  grib_set_long(h,"bitsPerValue",bitsPerValue);
  GRIB_CHECK(grib_set_double_array(h,"values",values,nvalues),0);
  GRIB_CHECK(grib_get_double(h,"packingError",&packingError),0);

  printf("--------------------------------\n");
  printf("- %s - gridType=%s packingType=%s numberOfValues=%ld bitsPerValue=%ld\n",
	param,gridType,packingType,(long)nvalues,bitsPerValue);

  if (!strcmp(packingType,"spectral_complex") || !strcmp(packingType,"spectral_simple")) {
	 printf("unable to process spectral data\n");
	 exit(1);
  }

  if (!strcmp(gridType,"reduced_gg") || !strcmp(gridType,"regular_gg")) {
	 long N;
	 grib_get_long(h,"N",&N);
	 printf("    N=%ld\n",N);
	 sprintf(grid,"%ld",N);
  }
  if (!strcmp(gridType,"regular_ll")) {
	 double Di,Dj;
	 grib_get_double(h,"DiInDegrees",&Di);
	 grib_get_double(h,"DjInDegrees",&Dj);
	 printf("    Di=%g Dj=%g\n",Di,Dj);
	 sprintf(grid,"%g/%g",Di,Dj);
  }


  if (!append) 
    fprintf(fout,
	"shortName gridType numberOfValues bitsPerValue grid sizeSimple sizeso encodeso encodeSimple decodeso decodeSimple\n");

  sec4len=nvalues+100000;

  /* decode values grid_simple */
  if (strcmp(packingType,grid_simple))
    grib_set_string(h,"packingType",grid_simple,&grid_simple_l);
  grib_timer_start(tds);
  for (count=0;count<repeatsimple;count++) 
    GRIB_CHECK(grib_get_double_array(h,"values",values,&nvalues),0);
  grib_timer_stop(tds,0);

  *outfilename='\0';
  sprintf(outfilename,"%s_%s_%ld_%ld_simple.grib1",param,gridType,bitsPerValue,(long)nvalues);
  filesize_simple=grib_handle_write(h,outfilename);
  printf("file size simple = %ld\n",(long)filesize_simple);

  /* encode values grid_simple*/
  grib_timer_start(tes);
  for (count=0;count<repeatsimple;count++) 
    GRIB_CHECK(grib_set_double_array(h,"values",values,nvalues),0);
  grib_timer_stop(tes,0);

  /* decode with gribex*/
  msg=(char*)buffer;
  gribex_msg_len=BUFF_SIZE;
  sec4len=nvalues+100000;
  gribex_check(cgribex(  miss, ksec0,ksec1,ksec2,rsec2,ksec3,rsec3,
                      ksec4,gvalues,sec4len, (char*)msg,&gribex_msg_len,"D")); 

  /* encode values second order with gribex*/
  ksec4[1] = bitsPerValue;
  /* to indicate complex packing. */
  ksec4[3] = 64;

  /* to indicate extended flags are present. */
  ksec4[5] = 16;

  ksec4[9] = 16; 
  ksec4[11] = 8; 
  ksec4[12] = 4; 
  ksec4[13] = 0; 
  ksec4[14] = -1; 

  gribex_msg_len=BUFF_SIZE;
  grib_timer_start(teso);
  gribex_check(cgribex(  miss, ksec0,ksec1,ksec2,rsec2,ksec3,rsec3,
                      ksec4,gvalues,nvalues, buf,&gribex_msg_len,"K"));
  grib_timer_stop(teso,0);

  hso=grib_handle_new_from_message_copy(c,buf,gribex_msg_len);

  GRIB_CHECK(grib_get_double_array(h,"values",sovalues,&nvalues),0);

  *outfilename='\0';
  sprintf(outfilename,"%s_%s_%ld_%ld_so.grib1",param,gridType,bitsPerValue,(long)nvalues);
  filesize_so=grib_handle_write(hso,outfilename);
  printf("file size so   = %ld\n",(long)filesize_so);

  perc=(double)filesize_simple/(double)filesize_so; 

  printf("compression ratio = %g \n",perc);
  printf("space savings = %g \n",(1.0-1.0/perc)*100);

  grib_handle_delete(h);
  /* decode values second order */
  /* decode with gribex*/
  msg=(char*)buf;
  gribex_msg_len=BUFF_SIZE;
  sec4len=nvalues+100000;
  grib_timer_start(tdso);
  gribex_check(cgribex(  miss, ksec0,ksec1,ksec2,rsec2,ksec3,rsec3,
                      ksec4,gvalues,sec4len, (char*)msg,&gribex_msg_len,"D")); 
  grib_timer_stop(tdso,0);

  for (i=0;i<nvalues;i++) {
	if (fabs(gvalues[i]-values[i])>packingError) {
	  printf("++++++++ Wrong coding\n");
	  printf("packingError=%g gvalues[%d]=%.20e values[%d]=%.20e abs. err=%g \n",packingError,i,
	  gvalues[i],i,values[i],gvalues[i]-values[i]);
	}
  }

  for (i=0;i<nvalues;i++) {
	if (fabs(gvalues[i]-sovalues[i])>packingError) {
	  printf("++++++++ Wrong coding\n");
	  printf("packingError=%g gvalues[%d]=%.20e sovalues[%d]=%.20e abs. err=%g \n",packingError,i,
	  gvalues[i],i,sovalues[i],gvalues[i]-sovalues[i]);
	}
  }

  grib_handle_delete(hso);
  grib_context_free(c,values);

  print_timer(teso,repeatso);
  print_timer(tdso,repeatso);
  print_timer(tes,repeatsimple);
  print_timer(tds,repeatsimple);

  fprintf(fout,"%s %s %ld %ld %s %ld %ld %g %g %g %g\n",
	shortName,gridType,(long)nvalues,bitsPerValue,
  	grid,(long)filesize_simple,(long)filesize_so,teso->timer_/repeatso,tes->timer_/repeatsimple,tdso->timer_/repeatso,tds->timer_/repeatsimple);

  fclose(fout);
  return 0;
}
Example #18
0
static int notify_change(grib_action* act, grib_accessor * notified,
                         grib_accessor* changed)
{

  grib_loader loader = { 0,};

  grib_section *old_section = NULL;
  grib_handle *h = notified->parent->h;
  size_t len = 0;
  size_t size = 0;
  int err=0;
  grib_handle* tmp_handle;
  int doit = 0;

  grib_action* la        = NULL;

  grib_context_log(h->context,
      GRIB_LOG_DEBUG,"------------- SECTION action %s (%s) is triggerred by [%s]",
      act->name, notified->name, changed->name);

  la = grib_action_reparse(act,notified,&doit);
  old_section = notified->sub_section;
  Assert(old_section);

  Assert(old_section->h == h);

  /* printf("old = %p\n",(void*)old_section->branch); */
  /* printf("new = %p\n",(void*)la); */

  grib_context_log(h->context,
      GRIB_LOG_DEBUG,"------------- DOIT %ld OLD %p NEW %p",
      doit,old_section->branch,la);


  if(!doit) {
    if(la != NULL || old_section->branch != NULL)
      if(la == old_section->branch)
      {
        grib_context_log(h->context,GRIB_LOG_DEBUG,"IGNORING TRIGGER action %s (%s) is triggerred %p", act->name, notified->name
            ,(void*)la);
        return GRIB_SUCCESS;
      }
  }

  loader.list_is_resized = (la == old_section->branch);

  if (!strcmp(changed->name,"GRIBEditionNumber")) loader.changing_edition=1;
  else loader.changing_edition=0;

  old_section->branch = la;

  tmp_handle = grib_new_handle(h->context);
  if(!tmp_handle)
    return GRIB_OUT_OF_MEMORY;

  tmp_handle->buffer = grib_create_growable_buffer(h->context);
  Assert(tmp_handle->buffer); /* FIXME */

  loader.data          = h;
  loader.lookup_long   = grib_lookup_long_from_handle;
  loader.init_accessor = grib_init_accessor_from_handle;


  Assert(h->kid == NULL);
  tmp_handle->loader = &loader;
  tmp_handle->main  = h;
  h->kid = tmp_handle;
  /* printf("tmp_handle- main %p %p\n",(void*)tmp_handle,(void*)h); */

  grib_context_log(h->context,GRIB_LOG_DEBUG,"------------- CREATE TMP BLOCK ", act->name, notified->name);
  tmp_handle->root  = grib_section_create(tmp_handle,NULL);

  tmp_handle->use_trie=1;

  err=grib_create_accessor(tmp_handle->root, act, &loader);

  grib_section_adjust_sizes(tmp_handle->root,1,0);

  grib_section_post_init(tmp_handle->root);

  /* grib_recompute_sections_lengths(tmp_handle->root); */
  grib_get_block_length(tmp_handle->root,&len);
  grib_context_log(h->context,GRIB_LOG_DEBUG,"-------------  TMP BLOCK IS sectlen=%d buffer=%d", len,  tmp_handle->buffer->ulength);

#if 0
  if(h->context->debug > 10)
    grib_dump_content(tmp_handle,stdout,NULL,0,NULL);
#endif

  /* Assert(tmp_handle->buffer->ulength == len); */
  /* grib_empty_section(h->context,old_section); */

  grib_buffer_replace(notified, tmp_handle->buffer->data, tmp_handle->buffer->ulength,0,1);

  grib_swap_sections(old_section,
      tmp_handle->root->block->first->sub_section);

  Assert(tmp_handle->dependencies == NULL);
  /* printf("grib_handle_delete %p\n",(void*)tmp_handle); */


  grib_handle_delete(tmp_handle);

  h->use_trie = 1;
  h->trie_invalid=1;
  h->kid = NULL;

  grib_section_adjust_sizes(h->root,1,0);

  grib_section_post_init(h->root);

  grib_get_block_length(old_section,&size);

  grib_context_log(h->context,GRIB_LOG_DEBUG,"-------------   BLOCK SIZE %ld, buffer len=%ld", size,len);
  if(h->context->debug > 10)
    grib_dump_content(h,stdout,"debug",~0,NULL);

  Assert(size == len);

  grib_update_paddings(old_section);


  return err;
}