Ejemplo n.º 1
0
/**
 * Create a netCdf-file
 * Any existing file will be replaced.
 *
 * @param i_baseName base name of the netCDF-file to which the data will be written to.
 * @param i_nX number of cells in the horizontal direction.
 * @param i_nY number of cells in the vertical direction.
 * @param i_dX cell size in x-direction.
 * @param i_dY cell size in y-direction.
 * @param i_originX
 * @param i_originY
 */
io::NetCdfWriter::NetCdfWriter( const std::string &i_baseName,
		const Float2D &i_b,
		int i_nX, int i_nY,
		float i_dX, float i_dY,
		float i_originX, float i_originY) : 
	io::Writer(i_baseName + ".nc", i_b,{{1, 1, 1, 1}}, i_nX, i_nY),
	flush(0) {
		int status;
		status = nc_create(fileName.c_str(), NC_NETCDF4, &dataFile);
	
		//check if the netCDF-file open command succeeded.
		if (status != NC_NOERR) {
			assert(false);
			return;
		}

		//dimensions
		int l_timeDim, l_xDim, l_yDim;
		nc_def_dim(dataFile, "time", NC_UNLIMITED, &l_timeDim);
		nc_def_dim(dataFile, "x", nX, &l_xDim);
		nc_def_dim(dataFile, "y", nY, &l_yDim);
	
		//variables (TODO: add rest of CF-1.5)
		int l_xVar, l_yVar;
	
		nc_def_var(dataFile, "time", NC_FLOAT, 1, &l_timeDim, &timeVar);
		ncPutAttText(timeVar, "long_name", "Time");
		ncPutAttText(timeVar, "units", "seconds since simulation start"); // the word "since" is important for the paraview reader
	
		nc_def_var(dataFile, "x", NC_FLOAT, 1, &l_xDim, &l_xVar);
		nc_def_var(dataFile, "y", NC_FLOAT, 1, &l_yDim, &l_yVar);
	
		//variables, fastest changing index is on the right (C syntax), will be mirrored by the library
		int dims[] = {l_timeDim, l_yDim, l_xDim};
		nc_def_var(dataFile, "b",  NC_FLOAT, 3, dims, &bVar);
	
		//set attributes to match CF-1.5 convention
		ncPutAttText(NC_GLOBAL, "Conventions", "CF-1.5");
		ncPutAttText(NC_GLOBAL, "title", "Computed tsunami solution");
		ncPutAttText(NC_GLOBAL, "history", "SWE");
		ncPutAttText(NC_GLOBAL, "institution", "Technische Universitaet Muenchen, Department of Informatics, Chair of Scientific Computing");
		ncPutAttText(NC_GLOBAL, "source", "Bathymetry and displacement data.");
		ncPutAttText(NC_GLOBAL, "references", "http://www5.in.tum.de/SWE");
		ncPutAttText(NC_GLOBAL, "comment", "SWE is free software and licensed under the GNU General Public License. Remark: In general this does not hold for the used input data.");
	
		//setup grid size
		
		float gridPosition = i_originX + (float).5 * i_dX;
		for(size_t i = 0; i < nX; i++) {
			nc_put_var1_float(dataFile, l_xVar, &i, &gridPosition);
			gridPosition += i_dX;
		}
	
		gridPosition = i_originY + (float).5 * i_dY;
		for(size_t j = 0; j < nY; j++) {
			nc_put_var1_float(dataFile, l_yVar, &j, &gridPosition);
   		gridPosition += i_dY;
		}
		nc_sync(dataFile);
}
Ejemplo n.º 2
0
//*****************************************************************************************
//Writes the data of the traceur.
int cdf_write( bloc_t data, s_all_parameters *t, s_nc_result *c, index_t time){
//*****************************************************************************************
	int status;
	float value;
	size_t ip[NVDIM];
	index_t *i, *j;
#ifdef BLOC_DIM_3D
	index_t *k;
	k=&(ip[O_DEPTH]);
#endif
	i=&(ip[O_LON]);
	j=&(ip[O_LAT]);
	ip[O_TIME]=time;
#ifdef BLOC_DIM_2D
	for(*i=0;*i<t->x.P;(*i)++){
		for(*j=0;*j<t->y.P;(*j)++){
			value=data[*i][*j];
			if(value<EPS) value=MYFILL;
			H(nc_put_var1_float(c->file.ncid, c->c.id, ip, &(value)))
		}
	}
#endif
#ifdef BLOC_DIM_3D
	for(*k=0;*k<t->z.P;(*k)++){
		for(*i=0;*i<t->x.P;(*i)++){
			for(*j=0;*j<t->y.P;(*j)++){
				value=data[*k][*i][*j];
				if(value<EPS) value=MYFILL;
				H(nc_put_var1_float(c->file.ncid, c->c.id, ip, &(value)))
			}
		}
	}
#endif
	return 0;
}
Ejemplo n.º 3
0
/**
 * Writes the unknwons to a netCDF-file (-> constructor) with respect to the boundary sizes.
 *
 * boundarySize[0] == left
 * boundarySize[1] == right
 * boundarySize[2] == bottom
 * boundarySize[3] == top
 *
 * @param i_h water heights at a given time step.
 * @param i_hu momentums in x-direction at a given time step.
 * @param i_hv momentums in y-direction at a given time step.
 * @param i_boundarySize size of the boundaries.
 * @param i_time simulation time of the time step.
 */
void io::NetCdfWriter::writeTimeStep( const Float2D &i_h,
                                      const Float2D &i_hu,
                                      const Float2D &i_hv, 
                                      float i_time) {
	if (timeStep == 0)
		// Write bathymetry
		writeVarTimeIndependent(b, bVar);
		
	//write i_time
	nc_put_var1_float(dataFile, timeVar, &timeStep, &i_time);

	//write water height
	writeVarTimeDependent(i_h, hVar);

	//write momentum in x-direction
	writeVarTimeDependent(i_hu, huVar);

	//write momentum in y-direction
	writeVarTimeDependent(i_hv, hvVar);

	//Write everything to the file
	nc_sync(dataFile);

	// Increment timeStep for next call
	timeStep++;
}
Ejemplo n.º 4
0
int main(void)
{
   int ncid, sfc_tempid;
   float data;
   int dimid;
   size_t l_index[NDIMS] = {10000};
   int mem_used, mem_used1;
   int i;

   printf("\n*** Testing netcdf-4 memory use with unlimited dimensions.\n");
   printf("*** testing with user-contributed code...");

   if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
   if (nc_def_dim(ncid, TIME_NAME, NC_UNLIMITED, &dimid)) ERR;
   if (nc_def_var(ncid, SFC_TEMP_NAME, NC_FLOAT, NDIMS, &dimid, &sfc_tempid)) ERR;

   /* Write data each 100ms*/
   get_mem_used2(&mem_used);
   for (i = 0; i < NUM_TRIES; i++)
   {
      data = 25.5 + l_index[0];
      if (nc_put_var1_float(ncid, sfc_tempid, l_index, (const float*) &data)) ERR;
      l_index[0]++;
      get_mem_used2(&mem_used1);
      if (!(i%100) && mem_used1 - mem_used)
	 printf("delta %d bytes of memory for try %d\n", mem_used1 - mem_used, i);
   }

   if (nc_close(ncid)) ERR;
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
Ejemplo n.º 5
0
//*****************************************************************************************
//Remplit les valeurs de la variable a partir du bloc_t.
//Attention, ca n'a pas besoin du temps pour rien!
void cdf_fill_var(int ncid, bloc_t v, s_nc_variable_xyz *ncv, s_nc_result* c){
//*****************************************************************************************
	int status;
	float value;
	size_t ind_p[NUDIM];
	size_t *i,*j;
#ifdef BLOC_DIM_3D
	size_t *k;
	k=&(ind_p[U_DEPTH]);
#endif
	i=&(ind_p[U_LON]);
	j=&(ind_p[U_LAT]);
#ifdef BLOC_DIM_3D
	for(*k=0;*k<c->z.length;(*k)++){
#endif
		for(*i=0;*i<c->x.length;(*i)++){
			for(*j=0;*j<c->y.length;(*j)++){
				value=CDF_BLC;
				H(nc_put_var1_float(ncid, ncv->id, ind_p, &(value)));
			}
		}
#ifdef BLOC_DIM_3D
	}
#endif
	return;
}
Ejemplo n.º 6
0
void io::NetCdfWriter::writeBathymetry(const Float2D &i_b, float i_time){
	nc_put_var1_float(dataFile, timeVar, &timeStep, &i_time);
	//writeVarTimeDependent(i_b,bVar);
	size_t start[] = {timeStep, 0, 0};
	size_t count[] = {1, nY, 1};
	for(int col = 0; col < nX; col++) {
		start[2] = col; //select col (dim "x")
		nc_put_vara_float(dataFile,bVar, start, count,
				&i_b[col][0]); //write col
	}
	timeStep++;
}
Ejemplo n.º 7
0
//*****************************************************************************************
//Remplit les valeurs de la variable dimension.
void cdf_fill_dim( int ncfrid, int nctoid, s_nc_dimension* to, s_nc_dimension* from, size_t start){
//*****************************************************************************************
	int status;
	float value1, value2;
	size_t i,q;
	q=start;
	value2=-100.0;
	for(i=0;i<to->length;i++){
		H(nc_get_var1_float(ncfrid, from->varid, &q, &value1))
		if(value1<value2) value2=value1+MODULO_DEG;
		else value2=value1;
		H(nc_put_var1_float(nctoid, to->varid, &i, &value2))
		q=(q+1)%(from->length);
	}
	return;
}
Ejemplo n.º 8
0
/**
 * Writes the unknwons to a netCDF-file (-> constructor) with respect to the boundary sizes.
 *
 * boundarySize[0] == left
 * boundarySize[1] == right
 * boundarySize[2] == bottom
 * boundarySize[3] == top
 *
 * @param i_h water heights at a given time step.
 * @param i_hu momentums in x-direction at a given time step.
 * @param i_hv momentums in y-direction at a given time step.
 * @param i_boundarySize size of the boundaries.
 * @param i_time simulation time of the time step.
 */
void io::NetCdfWriter::writeTimeStep( const Float2D &i_h,
                                      const Float2D &i_hu,
                                      const Float2D &i_hv,
                                      float i_time, bool i_writeBathymetry) {
	/*
	 * Prints the arrays
	for(int row = 0; row < i_h.getRows(); row++)
		for(int col = 0; col < i_h.getCols(); col++)
			{
				std::cout << "Row " << row << ", Column " << col << std::endl;
				std::cout << i_h[row][col] << " " << i_hu[row][col] << " " << i_hv[row][col] << std::endl;
			}
	*/

	if (timeStep == 0 && i_writeBathymetry)
		// Write bathymetry
		writeVarTimeIndependent(b, bVar);

	//write i_time
	nc_put_var1_float(dataFile, timeVar, &timeStep, &i_time);

	//write water height
	writeVarTimeDependent(i_h, hVar);

	//write momentum in x-direction
	writeVarTimeDependent(i_hu, huVar);

	//write momentum in y-direction
	writeVarTimeDependent(i_hv, hvVar);

	// Increment timeStep for next call
	timeStep++;

	if (flush > 0 && timeStep % flush == 0)
		nc_sync(dataFile);

	nc_sync(dataFile);
#ifndef NDEBUG
	std:string text = "Wrote to file ";
	
	std::ostringstream buff;
   		buff << dataFile;
	tools::Logger::logger.printString(text + buff.str());
#endif
}
Ejemplo n.º 9
0
int ex_put_time (int   exoid,
                 int   time_step,
                 const void *time_value)
{
  int status;
  int varid; 
  size_t start[1];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* inquire previously defined variable */
  if ((status = nc_inq_varid(exoid, VAR_WHOLE_TIME, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to locate time variable in file id %d", exoid);
    ex_err("ex_put_time",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* store time value */
  start[0] = --time_step;

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_var1_float(exoid, varid, start, time_value);
  } else {
    status = nc_put_var1_double(exoid, varid, start, time_value);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to store time value in file id %d", exoid);
    ex_err("ex_put_time",errmsg,exerrval);
    return (EX_FATAL);
  }


  return (EX_NOERR);
}
Ejemplo n.º 10
0
    /**
     * Write float data to corresponding variable name
     */
    void store(Property<float> *v)
    {
        int retval;
        int varid;
        float value = v->get();
        std::string sname = composeName(v->getName());

        /**
         * Get netcdf variable ID from name
         */
        retval = nc_inq_varid(ncid, sname.c_str(), &varid);
        if (retval)
            log(Error) << "Could not get variable id of " << sname << ", error " << retval <<endlog();

        /**
         * Write a single data value
         */
        retval = nc_put_var1_float(ncid, varid, &index, &value);
        if(retval)
            log(Error) << "Could not write variable " << sname << ", error " << retval <<endlog();

    }
Ejemplo n.º 11
0
void io::NetCdfWriter::writeTimeStep( const Float2D &i_h,
                                      const Float2D &i_hu,
                                      const Float2D &i_hv,
                                      const Float2D &i_b,
                                      float i_time) {
	//write i_time
	nc_put_var1_float(dataFile, timeVar, &timeStep, &i_time);

	//write water height
	writeVarTimeDependent(i_h, hVar);

	//write momentum in x-direction
	writeVarTimeDependent(i_hu, huVar);

	//write momentum in y-direction
	writeVarTimeDependent(i_hv, hvVar);

	//write bathymetry
	writeVarTimeDependent(i_b, bVar);

	// Increment timeStep for next call
	timeStep++;

	if (flush > 0 && timeStep % flush == 0)
		nc_sync(dataFile);

	nc_sync(dataFile);
#ifndef NDEBUG
	std:string text = "Wrote to file ";
	
	std::ostringstream buff;
   		buff << dataFile;
	tools::Logger::logger.printString(text + buff.str());
#endif

}
Ejemplo n.º 12
0
int main(int argc,char *argv[]) {
  struct DataMap *ptr;
  struct DataMapScalar *sx,*sy;
  struct DataMapArray *ax,*ay;
  size_t index[256];
  size_t start[256];
  size_t count[256];

  int s;
  unsigned char vbflg=0;
  unsigned char help=0;
  unsigned char option=0;
  unsigned char zflg=0;

  FILE *fp=NULL;
  gzFile zfp=0;

  FILE *mapfp;
  int n,c,x;
  int ncid;
  int block=0;
 
  int varid;
  
  int strsze;
  char **strptr;
  char *tmpbuf=NULL;

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);
  OptionAdd(&opt,"vb",'x',&vbflg);
  OptionAdd(&opt,"z",'x',&zflg);


  if (argc>1) {
    arg=OptionProcess(1,argc,argv,&opt,NULL); 
    if (help==1) {
      OptionPrintInfo(stdout,hlpstr);
      exit(0);
    }
    if (option==1) {
      OptionDump(stdout,&opt);
      exit(0);
    }

    if (zflg) {
      zfp=gzopen(argv[arg],"r");
      if (zfp==0) {
        fprintf(stderr,"File not found.\n");
        exit(-1);
      }
    } else {
      fp=fopen(argv[arg],"r");
      if (fp==NULL) {
        fprintf(stderr,"File not found.\n");
        exit(-1);
      }
    }  

  } else {
    OptionPrintInfo(stdout,errstr);
    exit(-1);
  }


  /* load the map */

  mapfp=fopen(argv[arg+1],"r");
  loadmap(mapfp);
  fclose(mapfp);

 

  s=nc_open(argv[arg+2],NC_WRITE,&ncid);
  if (s !=NC_NOERR) {
    fprintf(stderr,"Error opening CDF file.\n");
    exit(-1);
  }


   


  block=0;
  while (1) {

    if (zflg) ptr=DataMapReadZ(zfp);
    else ptr=DataMapFread(fp);

    if (ptr==NULL) break;

    for (c=0;c<ptr->snum;c++) {
      sx=ptr->scl[c];
      for (n=0;n<snum;n++) {
        sy=sptr[n];
        if (strcmp(sx->name,sy->name) !=0) continue;
        if (sx->type !=sy->type) continue;
        break;
      }
      if (n !=snum) { /* mapped variable */
        s=nc_inq_varid(ncid,cdfsname[n],&varid);
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error accessing CDF file.\n");
          exit(-1);
        }
        index[0]=block;
        switch (sx->type) {
        case DATACHAR:
          s=nc_put_var1_text(ncid,varid,index,sx->data.cptr);
          break;
        case DATASHORT:
          s=nc_put_var1_short(ncid,varid,index,sx->data.sptr);
          break;
        case DATAINT:
          s=nc_put_var1_int(ncid,varid,index,sx->data.iptr);
          break;
        case DATAFLOAT:
          s=nc_put_var1_float(ncid,varid,index,sx->data.fptr);
          break;
        case DATADOUBLE:
          s=nc_put_var1_double(ncid,varid,index,sx->data.dptr);
          break;
        case DATASTRING:
          start[0]=block;
          start[1]=0;
          count[0]=1;
          count[1]=strlen(*((char **) sx->data.vptr))+1;
          s=nc_put_vara_text(ncid,varid,start,count,
                             *((char **) sx->data.vptr));
          break;
	}
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error writing CDF file (%d).\n",s);
          exit(-1);
        }
       
      }
    }

    for (c=0;c<ptr->anum;c++) {
      ax=ptr->arr[c];
      for (n=0;n<anum;n++) {
        ay=aptr[n];
      
        if (strcmp(ax->name,ay->name) !=0) continue;
        if (ax->type !=ay->type) continue;
        if (ax->dim !=ay->dim) continue;
        break;
      }
      if (n !=anum) { /* mapped variable */
      
        s=nc_inq_varid(ncid,cdfaname[n],&varid);
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error accessing CDF file.\n");
          exit(-1);
        }
        start[0]=block;
        count[0]=1;
        n=1;
        for (x=0;x<ax->dim;x++) {
          start[1+x]=0;
          count[1+x]=ax->rng[x];
          n=n*ax->rng[x];
	}

        if (ax->type==DATASTRING) {
          int ndims;
          int dimids[NC_MAX_VAR_DIMS];
          size_t dimlen;
          s=nc_inq_varndims(ncid,varid,&ndims);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          s=nc_inq_vardimid(ncid,varid,dimids);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          if (ndims-2!=ax->dim) {
            fprintf(stderr,"Error matching dimensions.\n");
            exit(-1);
	  }
          
          s=nc_inq_dimlen(ncid,dimids[ndims-1],&dimlen);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          strsze=dimlen;
          tmpbuf=malloc(n*strsze);
          if (tmpbuf==NULL) {
            fprintf(stderr,"Failed to allocate buffer.\n");
            exit(-1);
	  }
          memset(tmpbuf,0,n*strsze);
          start[1+ax->dim]=0;
          count[1+ax->dim]=strsze;
          strptr=(char **) ax->data.vptr;
          for (x=0;x<n;x++) strncpy(tmpbuf+x*strsze,strptr[x],strsze);
	}               

        switch (ax->type) { 
        case DATACHAR:
           s=nc_put_vara_text(ncid,varid,start,count,ax->data.cptr);
           break;
        case DATASHORT:
           s=nc_put_vara_short(ncid,varid,start,count,ax->data.sptr);
           break;
        case DATAINT:
           s=nc_put_vara_int(ncid,varid,start,count,ax->data.iptr);
           break;
        case DATAFLOAT:
           s=nc_put_vara_float(ncid,varid,start,count,ax->data.fptr);
           break;
        case DATADOUBLE:
           s=nc_put_vara_double(ncid,varid,start,count,ax->data.dptr);
           break;
        case DATASTRING:
           s=nc_put_vara_text(ncid,varid,start,count,tmpbuf);
	   break;
	}
        if (tmpbuf !=NULL) {
	  free(tmpbuf);
          tmpbuf=NULL;
	}

        if (s !=NC_NOERR) {
          fprintf(stderr,"Error writing CDF file (%d).\n",s);
          exit(-1);
        }
 
      }
    }
  

    DataMapFree(ptr);
    block++;
  }
  nc_close(ncid);
  if (zflg) gzclose(zfp);
  else fclose(fp);
  return 0;
}
Ejemplo n.º 13
0
int extract_unary_single(int mpi_rank,int mpi_size, int ncid,int vlid,int ncidout,int vlidout,int ndims,nc_type vtype,size_t *shape,size_t *begins,size_t *ends, ptrdiff_t *strides,size_t preLen,size_t *outLen){
	
	int i,j,res;
	size_t *divider=(size_t *)malloc(sizeof(size_t)*ndims);    //input divider 
	size_t *dividerOut=(size_t *)malloc(sizeof(size_t)*ndims); // output divider
	size_t *start=(size_t*)malloc(sizeof(size_t)*ndims);     //start position for reading element from input file
	size_t *startOut=(size_t*)malloc(sizeof(size_t)*ndims);  //start position for writing element to output file
	size_t *shapeOut=(size_t*)malloc(sizeof(size_t)*ndims);  //output dimension shape

	int lenOut=1;
	for(i=0;i<ndims;++i){
		shapeOut[i]=(ends[i]-begins[i])/strides[i]+1;	
		lenOut*=shapeOut[i];
	}
	if(outLen!=NULL)
		*outLen=lenOut;
	getDivider(ndims,shape,divider);
	getDivider(ndims,shapeOut,dividerOut);

	/* decide element boundary for each mpi process */
	size_t beginOut;
	size_t endOut;
	if(lenOut>=mpi_size){                              
		beginOut=mpi_rank*(lenOut/mpi_size);
		if(mpi_rank!=mpi_size-1)
			endOut=(mpi_rank+1)*(lenOut/mpi_size);
		else
			endOut=lenOut;
	}else{ //mpi_size is bigger than lenOut
		if(mpi_rank<lenOut){
			beginOut=mpi_rank;
			endOut=mpi_rank+1;
		}else{
			beginOut=0;
			endOut=0;
		}
	}

	printf("mpi_rank %d, beginOut %d, endOut %d\n",mpi_rank,beginOut,endOut);
	void *data=malloc(sizeof(double));
	size_t rem,remIn;
	for(i=beginOut;i<endOut;++i){
		rem=i+preLen;
		remIn=i;
		for(j=0;j<ndims;++j){
			startOut[j]=rem/dividerOut[j];
			start[j]=begins[j]+(remIn/dividerOut[j])*strides[j];
			rem=rem%dividerOut[j];
			remIn=remIn%dividerOut[j];
		}

	switch(vtype){
		case NC_BYTE:
			if((res=nc_get_var1_uchar(ncid,vlid,start,data)))
				BAIL(res);
			if((res=nc_put_var1_uchar(ncidout,vlidout,startOut,(unsigned char *)data)))
				BAIL(res);
			break;
		case NC_CHAR:
			if((res=nc_get_var1_schar(ncid,vlid,start,(signed char *)data)))
				BAIL(res);
			if((res=nc_put_var1_schar(ncidout,vlidout,startOut,(signed char *)data)))
				BAIL(res);
			break;
		case NC_SHORT:
			if((res=nc_get_var1_short(ncid,vlid,start,data)))
				BAIL(res);
			if((res=nc_put_var1_short(ncidout,vlidout,startOut,(short *)data)))
				BAIL(res);
			break;
		case NC_INT:
			if((res=nc_get_var1_int(ncid,vlid,start,(int *)data)))
				BAIL(res);
			if((res=nc_put_var1_int(ncidout,vlidout,startOut,(int *)data)))
				BAIL(res);
			break;
		case NC_FLOAT:
			if((res=nc_get_var1_float(ncid,vlid,start,data)))
				BAIL(res);
			if((res=nc_put_var1_float(ncidout,vlidout,startOut,(float *)data)))
				BAIL(res);
			break;
		case NC_DOUBLE:
			if((res=nc_get_var1_double(ncid,vlid,start,data)))
				BAIL(res);
			if((res=nc_put_var1_double(ncidout,vlidout,startOut,(double *)data)))
				BAIL(res);
			break;
		default:
			printf("Unknown data type\n");
			}
		}

	/*free resourses*/
	free(divider);
	free(dividerOut);
	free(start);
	free(startOut);
	free(shapeOut);
	free(data);
	return 0;
}
Ejemplo n.º 14
0
/*
 * Put a single numeric data value into a variable of an open netCDF.
 */
static void
c_ncvpt1 (
    int			ncid,	/* netCDF ID */
    int	 		varid,	/* variable ID */
    const size_t*	indices,/* multidim index of data to be written */
    const void*		value,	/* pointer to data value to be written */
    int*		rcode	/* returned error code */
)
{
    int		status;
    nc_type	datatype;

    if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0)
    {
	switch (datatype)
	{
	case NC_CHAR:
	    status = NC_ECHAR;
	    break;
	case NC_BYTE:
#	    if NF_INT1_IS_C_SIGNED_CHAR
		status = nc_put_var1_schar(ncid, varid, indices,
					   (const signed char*)value);
#	    elif NF_INT1_IS_C_SHORT
		status = nc_put_var1_short(ncid, varid, indices,
					   (const short*)value);
#	    elif NF_INT1_IS_C_INT
		status = nc_put_var1_int(ncid, varid, indices,
					   (const int*)value);
#	    elif NF_INT1_IS_C_LONG
		status = nc_put_var1_long(ncid, varid, indices,
					   (const long*)value);
#	    endif
	    break;
	case NC_SHORT:
#	    if NF_INT2_IS_C_SHORT
		status = nc_put_var1_short(ncid, varid, indices,
					   (const short*)value);
#	    elif NF_INT2_IS_C_INT
		status = nc_put_var1_int(ncid, varid, indices,
					   (const int*)value);
#	    elif NF_INT2_IS_C_LONG
		status = nc_put_var1_long(ncid, varid, indices,
					   (const long*)value);
#	    endif
	    break;
	case NC_INT:
#	    if NF_INT_IS_C_INT
		status = nc_put_var1_int(ncid, varid, indices,
					   (const int*)value);
#	    elif NF_INT_IS_C_LONG
		status = nc_put_var1_long(ncid, varid, indices,
					   (const long*)value);
#	    endif
	    break;
	case NC_FLOAT:
#	    if NF_REAL_IS_C_FLOAT
		status = nc_put_var1_float(ncid, varid, indices,
					   (const float*)value);
#	    elif NF_REAL_IS_C_DOUBLE
		status = nc_put_var1_double(ncid, varid, indices,
					   (const double*)value);
#	    endif
	    break;
	case NC_DOUBLE:
#	    if NF_DOUBLEPRECISION_IS_C_FLOAT
		status = nc_put_var1_float(ncid, varid, indices,
					   (const float*)value);
#	    elif NF_DOUBLEPRECISION_IS_C_DOUBLE
		status = nc_put_var1_double(ncid, varid, indices,
					   (const double*)value);
#	    endif
	    break;
	}
    }

    if (status == 0)
	*rcode = 0;
    else
    {
	nc_advise("NCVPT1", status, "");
	*rcode = ncerr;
    }
}
Ejemplo n.º 15
0
/*! \internal */
int
cpy_var_val(int in_id,int out_id,char *var_nm)
/*
   int in_id: input netCDF input-file ID
   int out_id: input netCDF output-file ID
   char *var_nm: input variable name
 */
{
  /* Routine to copy the variable data from an input netCDF file
   * to an output netCDF file. 
   */

  int *dim_id;
  int idx;
  int nbr_dim;
  int var_in_id;
  int var_out_id;
  size_t *dim_cnt;
  size_t *dim_sz;
  size_t *dim_srt;
  size_t var_sz=1L;
  nc_type var_type_in, var_type_out;

  void *void_ptr = NULL;

  /* Get the var_id for the requested variable from both files. */
  (void)nc_inq_varid(in_id, var_nm, &var_in_id);
  (void)nc_inq_varid(out_id,var_nm, &var_out_id);
 
  /* Get the number of dimensions for the variable. */
  (void)nc_inq_vartype( out_id, var_out_id, &var_type_out);
  (void)nc_inq_varndims(out_id, var_out_id, &nbr_dim);

  (void)nc_inq_vartype( in_id,   var_in_id, &var_type_in);
  (void)nc_inq_varndims(in_id,   var_in_id, &nbr_dim);
 
  /* Allocate space to hold the dimension IDs */
  dim_cnt = malloc(nbr_dim*sizeof(size_t));

  dim_id=malloc(nbr_dim*sizeof(int));

  dim_sz=malloc(nbr_dim*sizeof(size_t));

  dim_srt=malloc(nbr_dim*sizeof(size_t));
 
  /* Get the dimension IDs from the input file */
  (void)nc_inq_vardimid(in_id, var_in_id, dim_id);
 
  /* Get the dimension sizes and names from the input file */
  for(idx=0;idx<nbr_dim;idx++){
  /* NB: For the unlimited dimension, ncdiminq() returns the maximum
     value used so far in writing data for that dimension.
     Thus if you read the dimension sizes from the output file, then
     the ncdiminq() returns dim_sz=0 for the unlimited dimension
     until a variable has been written with that dimension. This is
     the reason for always reading the input file for the dimension
     sizes. */

    (void)nc_inq_dimlen(in_id,dim_id[idx],dim_cnt+idx);

    /* Initialize the indicial offset and stride arrays */
    dim_srt[idx]=0L;
    var_sz*=dim_cnt[idx];
  } /* end loop over dim */

  /* Allocate enough space to hold the variable */
  if (var_sz > 0)
      void_ptr=malloc(var_sz * type_size(var_type_in));

  /* Get the variable */

  /* if variable is float or double, convert if necessary */

  if(nbr_dim==0){  /* variable is a scalar */

    if (var_type_in == NC_INT && var_type_out == NC_INT) {
      nc_get_var1_int(in_id,  var_in_id,  0L, void_ptr);
      nc_put_var1_int(out_id, var_out_id, 0L, void_ptr);
    }

    else if (var_type_in == NC_INT64 && var_type_out == NC_INT64) {
      nc_get_var1_longlong(in_id,  var_in_id,  0L, void_ptr);
      nc_put_var1_longlong(out_id, var_out_id, 0L, void_ptr);
    }

    else if (var_type_in == NC_FLOAT) {
      nc_get_var1_float(in_id,  var_in_id,  0L, void_ptr);
      nc_put_var1_float(out_id, var_out_id, 0L, void_ptr);
    }

    else if (var_type_in == NC_DOUBLE) {
      nc_get_var1_double(in_id,  var_in_id,  0L, void_ptr);
      nc_put_var1_double(out_id, var_out_id, 0L, void_ptr);
    }

    else if (var_type_in == NC_CHAR) {
      nc_get_var1_text(in_id,  var_in_id,  0L, void_ptr);
      nc_put_var1_text(out_id, var_out_id, 0L, void_ptr);
    }

    else {
      assert(1==0);
    }
  } else { /* variable is a vector */

    if (var_type_in == NC_INT && var_type_out == NC_INT) {
      (void)nc_get_var_int(in_id,  var_in_id,  void_ptr);
      (void)nc_put_var_int(out_id, var_out_id, void_ptr);
    }

    else if (var_type_in == NC_INT64 && var_type_out == NC_INT64) {
      (void)nc_get_var_longlong(in_id,  var_in_id,  void_ptr);
      (void)nc_put_var_longlong(out_id, var_out_id, void_ptr);
    }

    else if (var_type_in == NC_FLOAT) {
      (void)nc_get_var_float(in_id,  var_in_id,  void_ptr);
      (void)nc_put_var_float(out_id, var_out_id, void_ptr);
    }

    else if (var_type_in == NC_DOUBLE) {
      (void)nc_get_var_double(in_id,  var_in_id,  void_ptr);
      (void)nc_put_var_double(out_id, var_out_id, void_ptr);
    }

    else if (var_type_in == NC_CHAR) {
      (void)nc_get_var_text(in_id,  var_in_id,  void_ptr);
      (void)nc_put_var_text(out_id, var_out_id, void_ptr);
    }

    else {
      assert(1==0);
    }
  } /* end if variable is an array */

  /* Free the space that held the dimension IDs */
  (void)free(dim_cnt);
  (void)free(dim_id);
  (void)free(dim_sz);
  (void)free(dim_srt);

  /* Free the space that held the variable */
  (void)free(void_ptr);

  return(EX_NOERR);

} /* end cpy_var_val() */
Ejemplo n.º 16
0
/*ARGSUSED*/
int
main(int argc, char *argv[])
{
	int cmode=NC_CLOBBER, omode, ret;
	int	 id;
	char buf[256];
#ifdef SYNCDEBUG
	char *str = "one";
#endif
	int ii;
	size_t ui;
	const struct tcdfvar *tvp = testvars;
	union getret got;
	const size_t initialsz = 8192;
	size_t chunksz = 8192;
	size_t align = 8192/32;

	MPI_Init(&argc, &argv);

        /* cmode |= NC_PNETCDF |NC_64BIT_OFFSET; */
        cmode != NC_PNETCDF |NC_64BIT_DATA;
	ret = nc_create_par(fname,cmode, MPI_COMM_WORLD, MPI_INFO_NULL, &id);
	if(ret != NC_NOERR)  {
		fprintf(stderr,"Error %s in file %s at line %d\n",nc_strerror(ret),__FILE__,__LINE__);
		exit(ret);
        }
	
	assert( nc_put_att_text(id, NC_GLOBAL,
		"TITLE", 12, "another name") == NC_NOERR);
	assert( nc_get_att_text(id, NC_GLOBAL,
		"TITLE", buf) == NC_NOERR);
/*	(void) printf("title 1 \"%s\"\n", buf); */
	assert( nc_put_att_text(id, NC_GLOBAL,
		"TITLE", strlen(fname), fname) == NC_NOERR);
	assert( nc_get_att_text(id, NC_GLOBAL,
		"TITLE", buf) == NC_NOERR);
	buf[strlen(fname)] = 0;
/*	(void) printf("title 2 \"%s\"\n", buf); */
	assert( strcmp(fname, buf) == 0);

	createtestdims(id, NUM_DIMS, sizes, dim_names);
	testdims(id, NUM_DIMS, sizes, dim_names);

	createtestvars(id, testvars, NUM_TESTVARS); 

 	{
 	int ifill = -1; double dfill = -9999;
 	assert( nc_put_att_int(id, Long_id,
 		_FillValue, NC_INT, 1, &ifill) == NC_NOERR);
 	assert( nc_put_att_double(id, Double_id,
 		_FillValue, NC_DOUBLE, 1, &dfill) == NC_NOERR);
 	}

#ifdef REDEF
	assert( nc__enddef(id, 0, align, 0, 2*align) == NC_NOERR );
	assert( nc_put_var1_int(id, Long_id, indices[3], &birthday) 
		== NC_NOERR );
	fill_seq(id);
	assert( nc_redef(id) == NC_NOERR );
/*	assert( nc_rename_dim(id,2, "a long dim name") == NC_NOERR); */
#endif

	assert( nc_rename_dim(id,1, "IXX") == NC_NOERR);
	assert( nc_inq_dim(id, 1, buf, &ui) == NC_NOERR);
	/* (void) printf("dimrename: %s\n", buf); */
	assert( nc_rename_dim(id,1, dim_names[1]) == NC_NOERR);

#ifdef ATTRX
	assert( nc_rename_att(id, 1, "UNITS", "units") == NC_NOERR);
	assert( nc_del_att(id, 4, "FIELDNAM")== NC_NOERR);
	assert( nc_del_att(id, 2, "SCALEMIN")== NC_NOERR);
	assert( nc_del_att(id, 2, "SCALEMAX")== NC_NOERR);
#endif /* ATTRX */

	assert( nc__enddef(id, 0, align, 0, 2*align) == NC_NOERR );

#ifndef REDEF
	fill_seq(id);
	assert( nc_put_var1_int(id, Long_id, indices[3], &birthday)== NC_NOERR );
#endif

	assert( nc_put_vara_schar(id, Byte_id, s_start, s_edges,
		(signed char *)sentence)
		== NC_NOERR);
	assert( nc_put_var1_schar(id, Byte_id, indices[6], (signed char *)(chs+1))
		== NC_NOERR);
	assert( nc_put_var1_schar(id, Byte_id, indices[5], (signed char *)chs)
		== NC_NOERR);

	assert( nc_put_vara_text(id, Char_id, s_start, s_edges, sentence)
		== NC_NOERR);
	assert( nc_put_var1_text(id, Char_id, indices[6], (chs+1))
		== NC_NOERR) ;
	assert( nc_put_var1_text(id, Char_id, indices[5], chs)
		== NC_NOERR);

	assert( nc_put_var1_short(id, Short_id, indices[4], shs)
		== NC_NOERR);

	assert( nc_put_var1_float(id, Float_id, indices[2], &e)
		== NC_NOERR);

	assert( nc_put_var1_double(id, Double_id, indices[1], &zed)
		== NC_NOERR);
	assert( nc_put_var1_double(id, Double_id, indices[0], &pinot)
		== NC_NOERR);


#ifdef SYNCDEBUG
	(void) printf("Hit Return to sync\n");
	gets(str);
	nc_sync(id,0);
	(void) printf("Sync done. Hit Return to continue\n");
	gets(str);
#endif /* SYNCDEBUG */

	ret = nc_close(id);
	/* (void) printf("nc_close ret = %d\n\n", ret); */


/*
 *	read it
 */
        omode = NC_NOWRITE;
        omode = NC_NOWRITE | NC_PNETCDF;
	if(ret != NC_NOERR)
	{
   	    (void) printf("Could not open %s: %s\n", fname,
			nc_strerror(ret));
   	    exit(1);
	}
	/* (void) printf("reopen id = %d for filename %s\n", */
	/* 	id, fname); */

	/*	NC	*/ 
	/* (void) printf("NC "); */
	assert( nc_inq(id, &(cdesc->num_dims), &(cdesc->num_vars),
		&(cdesc->num_attrs), &(cdesc->xtendim) ) == NC_NOERR);
	assert((size_t) cdesc->num_dims == num_dims);
	assert(cdesc->num_attrs == 1);
	assert(cdesc->num_vars == NUM_TESTVARS);
	/* (void) printf("done\n"); */
	
	/*	GATTR	*/
	/* (void) printf("GATTR "); */

	assert( nc_inq_attname(id, NC_GLOBAL, 0, adesc->mnem) == 0);
	assert(strcmp("TITLE",adesc->mnem) == 0);
	assert( nc_inq_att(id, NC_GLOBAL, adesc->mnem, &(adesc->type), &(adesc->len))== NC_NOERR);
	assert( adesc->type == NC_CHAR );
	assert( adesc->len == strlen(fname) );
	assert( nc_get_att_text(id, NC_GLOBAL, "TITLE", buf)== NC_NOERR);
	buf[adesc->len] = 0;
	assert( strcmp(fname, buf) == 0);

	/*	VAR	*/
	/* (void) printf("VAR "); */
	assert( cdesc->num_vars == NUM_TESTVARS );

	for(ii = 0; ii < cdesc->num_vars; ii++, tvp++ ) 
	{
		int jj;
		assert( nc_inq_var(id, ii,
			vdesc->mnem,
			&(vdesc->type),
			&(vdesc->ndims),
			vdesc->dims,
			&(vdesc->num_attrs)) == NC_NOERR);
		if(strcmp(tvp->mnem , vdesc->mnem) != 0)
		{
			(void) printf("attr %d mnem mismatch %s, %s\n",
				ii, tvp->mnem, vdesc->mnem);
			continue;
		}
		if(tvp->type != vdesc->type)
		{
			(void) printf("attr %d type mismatch %d, %d\n",
				ii, (int)tvp->type, (int)vdesc->type);
			continue;
		}
		for(jj = 0; jj < vdesc->ndims; jj++ )
		{
			if(tvp->dims[jj] != vdesc->dims[jj] )
			{
		(void) printf(
		"inconsistent dim[%d] for variable %d: %d != %d\n",
		jj, ii, tvp->dims[jj], vdesc->dims[jj] );
			continue;
			}
		}

		/* VATTR */
		/* (void) printf("VATTR\n"); */
		for(jj=0; jj<vdesc->num_attrs; jj++ ) 
		{
			assert( nc_inq_attname(id, ii, jj, adesc->mnem) == NC_NOERR);
			if( strcmp(adesc->mnem, reqattr[jj]) != 0 )
			{
				(void) printf("var %d attr %d mismatch %s != %s\n",
					ii, jj, adesc->mnem, reqattr[jj] );
				break;
			}
		}

		if( nc_inq_att(id, ii, reqattr[0], &(adesc->type), &(adesc->len))
			!= -1) {
		assert( adesc->type == NC_CHAR );
		assert( adesc->len == strlen(tvp->units) );
	 	assert( nc_get_att_text(id,ii,reqattr[0],buf)== NC_NOERR); 
		buf[adesc->len] = 0;
		assert( strcmp(tvp->units, buf) == 0);
		}

		if(
			nc_inq_att(id, ii, reqattr[1], &(adesc->type), &(adesc->len))
			!= -1)
		{
		assert( adesc->type == NC_DOUBLE );
		assert( adesc->len == 1 );
	 	assert( nc_get_att_double(id, ii, reqattr[1], &got.dbl)== NC_NOERR);
		chkgot(adesc->type, got, tvp->validmin);
		}

		if(
			nc_inq_att(id, ii, reqattr[2], &(adesc->type), &(adesc->len))
			!= -1)
		{
		assert( adesc->type == NC_DOUBLE );
		assert( adesc->len == 1 );
	 	assert( nc_get_att_double(id, ii, reqattr[2], &got.dbl)== NC_NOERR);
		chkgot(adesc->type, got, tvp->validmax);
		}

		if(
			nc_inq_att(id, ii, reqattr[3], &(adesc->type), &(adesc->len))
			!= -1)
		{
		assert( adesc->type == NC_DOUBLE );
		assert( adesc->len ==1 );
	 	assert( nc_get_att_double(id, ii, reqattr[3], &got.dbl)== NC_NOERR);
		chkgot(adesc->type, got, tvp->scalemin);
		}

		if(
			nc_inq_att(id, ii, reqattr[4], &(adesc->type), &(adesc->len))
			!= -1)
		{
		assert( adesc->type == NC_DOUBLE );
		assert( adesc->len == 1 );
	 	assert( nc_get_att_double(id, ii, reqattr[4], &got.dbl)== NC_NOERR);
		chkgot(adesc->type, got, tvp->scalemax);
		}

		if( nc_inq_att(id, ii, reqattr[5], &(adesc->type), &(adesc->len))== NC_NOERR)
		{
		assert( adesc->type == NC_CHAR );
		assert( adesc->len == strlen(tvp->fieldnam) );
	 	assert( nc_get_att_text(id,ii,reqattr[5],buf)== NC_NOERR); 
		buf[adesc->len] = 0;
		assert( strcmp(tvp->fieldnam, buf) == 0);
		}
	}

	/* (void) printf("fill_seq "); */
	check_fill_seq(id);
	/* (void) printf("Done\n"); */

	assert( nc_get_var1_double(id, Double_id, indices[0], &got.dbl)== NC_NOERR);
	/* (void) printf("got val = %f\n", got.dbl ); */

	assert( nc_get_var1_double(id, Double_id, indices[1], &got.dbl)== NC_NOERR);
	/* (void) printf("got val = %f\n", got.dbl ); */

	assert( nc_get_var1_float(id, Float_id, indices[2], &got.fl[0])== NC_NOERR);
	/* (void) printf("got val = %f\n", got.fl[0] ); */

	assert( nc_get_var1_int(id, Long_id, indices[3], &got.in[0])== NC_NOERR);
	/* (void) printf("got val = %d\n", got.in[0] ); */

	assert( nc_get_var1_short(id, Short_id, indices[4], &got.sh[0])== NC_NOERR);
	/* (void) printf("got val = %d\n", got.sh[0] ); */

	assert( nc_get_var1_text(id, Char_id, indices[5], &got.by[0]) == NC_NOERR);
	/* (void) printf("got NC_CHAR val = %c (0x%02x) \n", */
		 /* got.by[0] , got.by[0]); */

	assert( nc_get_var1_text(id, Char_id, indices[6], &got.by[0]) == NC_NOERR);
	/* (void) printf("got NC_CHAR val = %c (0x%02x) \n", */
	/* 	 got.by[0], got.by[0] ); */

	(void) memset(buf,0,sizeof(buf));
	assert( nc_get_vara_text(id, Char_id, s_start, s_edges, buf) == NC_NOERR);
	/* (void) printf("got NC_CHAR val = \"%s\"\n", buf); */

	assert( nc_get_var1_schar(id, Byte_id, indices[5],
			(signed char *)&got.by[0])== NC_NOERR);
	/* (void) printf("got val = %c (0x%02x) \n", got.by[0] , got.by[0]); */

	assert( nc_get_var1_schar(id, Byte_id, indices[6],
			(signed char *)&got.by[0])== NC_NOERR);
	/* (void) printf("got val = %c (0x%02x) \n", got.by[0], got.by[0] ); */

	(void) memset(buf,0,sizeof(buf));
	assert( nc_get_vara_schar(id, Byte_id, s_start, s_edges,
			(signed char *)buf)== NC_NOERR );
	/* (void) printf("got val = \"%s\"\n", buf); */

	{
		double dbuf[NUM_RECS * SIZE_1 * SIZE_2];
		assert(nc_get_var_double(id, Float_id, dbuf) == NC_NOERR);
		/* (void) printf("got vals = %f ... %f\n", dbuf[0], */
		/* 	 dbuf[NUM_RECS * SIZE_1 * SIZE_2 -1] ); */
	}

	ret = nc_close(id);
	/* (void) printf("re nc_close ret = %d\n", ret); */

	MPI_Finalize();
	return 0;
}
Ejemplo n.º 17
0
/**
 * Create a netCdf-file
 * Any existing file will be replaced.
 *
 * @param i_baseName base name of the netCDF-file to which the data will be written to.
 * @param i_nX number of cells in the horizontal direction.
 * @param i_nY number of cells in the vertical direction.
 * @param i_dX cell size in x-direction.
 * @param i_dY cell size in y-direction.
 * @param i_originX
 * @param i_originY
 * @param i_flush If > 0, flush data to disk every i_flush write operation
 * @param i_dynamicBathymetry
 */
io::NetCdfWriter::NetCdfWriter( const std::string &i_baseName,
		const Float2D &i_b,
		const BoundarySize &i_boundarySize,
		int i_nX, int i_nY,
		float i_dX, float i_dY,
		float i_originX, float i_originY,
		unsigned int i_flush,
		size_t contTimestep,
		unsigned int compression) :
		//const bool  &i_dynamicBathymetry) : //!TODO
  io::Writer(i_baseName + ".nc", i_b, i_boundarySize, i_nX, i_nY, contTimestep),
  flush(i_flush), compress(compression) {
	int status;
	if(contTimestep)
	{
		status = nc_open(fileName.c_str(), NC_WRITE, &dataFile);

		
		//check if the netCDF-file open command succeeded.
		if (status != NC_NOERR) {
			assert(false);
			return;
		}

		size_t l_length;
		if(status = nc_inq_varid(dataFile, "time", &timeVar)) ERR(status);
		if(status = nc_inq_varid(dataFile, "h", &hVar)) ERR(status);
		if(status = nc_inq_varid(dataFile, "hu", &huVar)) ERR(status);
		if(status = nc_inq_varid(dataFile, "hv", &hvVar)) ERR(status);
		if(status = nc_inq_varid(dataFile, "b", &bVar)) ERR(status);
		//if(status = nc_inq_dimlen(dataFile, timeVar, &timeStep)) ERR(status);
	}
	else {
		//create a netCDF-file, an existing file will be replaced
		status = nc_create(fileName.c_str(), NC_NETCDF4, &dataFile);
	
		//check if the netCDF-file creation constructor succeeded.
		if (status != NC_NOERR) {
			assert(false);
			return;
		}

//		std::cout << "i_nX, i_nY, i_dX, i_dY: " << nX << ", " << nY << ", " << i_dX << ", " << i_dY << std::endl;
		adjust(nX, nY, i_dX, i_dY, compress);
//		std::cout << "i_nX, i_nY, i_dX, i_dY: " << nX << ", " << nY << ", " << i_dX << ", " << i_dY << std::endl;

#ifdef PRINT_NETCDFWRITER_INFORMATION
		std::cout << "   *** io::NetCdfWriter::createNetCdfFile" << std::endl;
		std::cout << "     created/replaced: " << fileName << std::endl;
		std::cout << "     dimensions(nx, ny): " << nX << ", " << nY << std::endl;
		std::cout << "     cell width(dx,dy): " << i_dX << ", " << i_dY << std::endl;
		std::cout << "     origin(x,y): " << i_originX << ", " << i_originY << std::endl;
#endif

		//dimensions
		int l_timeDim, l_xDim, l_yDim;
		nc_def_dim(dataFile, "time", NC_UNLIMITED, &l_timeDim);
		nc_def_dim(dataFile, "x", nX, &l_xDim);
		nc_def_dim(dataFile, "y", nY, &l_yDim);
	
		//variables (TODO: add rest of CF-1.5)
		int l_xVar, l_yVar;
	
		nc_def_var(dataFile, "time", NC_FLOAT, 1, &l_timeDim, &timeVar);
		ncPutAttText(timeVar, "long_name", "Time");
		ncPutAttText(timeVar, "units", "seconds since simulation start"); // the word "since" is important for the paraview reader
	
		nc_def_var(dataFile, "x", NC_FLOAT, 1, &l_xDim, &l_xVar);
		nc_def_var(dataFile, "y", NC_FLOAT, 1, &l_yDim, &l_yVar);
	
		//variables, fastest changing index is on the right (C syntax), will be mirrored by the library
		int dims[] = {l_timeDim, l_yDim, l_xDim};
		nc_def_var(dataFile, "h",  NC_FLOAT, 3, dims, &hVar);
		nc_def_var(dataFile, "hu", NC_FLOAT, 3, dims, &huVar);
		nc_def_var(dataFile, "hv", NC_FLOAT, 3, dims, &hvVar);
		nc_def_var(dataFile, "b",  NC_FLOAT, 3, dims, &bVar);
	
		//set attributes to match CF-1.5 convention
		ncPutAttText(NC_GLOBAL, "Conventions", "CF-1.5");
		ncPutAttText(NC_GLOBAL, "title", "Computed tsunami solution");
		ncPutAttText(NC_GLOBAL, "history", "SWE");
		ncPutAttText(NC_GLOBAL, "institution", "Technische Universitaet Muenchen, Department of Informatics, Chair of Scientific Computing");
		ncPutAttText(NC_GLOBAL, "source", "Bathymetry and displacement data.");
		ncPutAttText(NC_GLOBAL, "references", "http://www5.in.tum.de/SWE");
		ncPutAttText(NC_GLOBAL, "comment", "SWE is free software and licensed under the GNU General Public License. Remark: In general this does not hold for the used input data.");
	
		//setup grid size
		
		float gridPosition = i_originX + (float).5 * i_dX;
		for(size_t i = 0; i < nX; i++) {
			nc_put_var1_float(dataFile, l_xVar, &i, &gridPosition);

			gridPosition += i_dX;
		}
	
		gridPosition = i_originY + (float).5 * i_dY;
		for(size_t j = 0; j < nY; j++) {
			nc_put_var1_float(dataFile, l_yVar, &j, &gridPosition);
	
	    		gridPosition += i_dY;
		}
		nc_sync(dataFile);
	}
}
Ejemplo n.º 18
0
/**
 * Create or open an existing netCdf-file
 * 
 * If i_baseName appended with the ".nc" extension represents an existing
 * NetCDF file, the file is opened and it is tried to append to the 
 * file (e.g. open a checkpoint-file of a previously crashed run)
 *
 * @param i_baseName base name of the netCDF-file to which the data will be written to.
 * @param i_nX number of cells in the horizontal direction.
 * @param i_nY number of cells in the vertical direction.
 * @param i_dX cell size in x-direction.
 * @param i_dY cell size in y-direction.
 * @param i_originX
 * @param i_originY
 * @param i_coarseness The coarseness factor
 * @param i_flush If > 0, flush data to disk every i_flush write operation
 * @param i_dynamicBathymetry
 */
io::NetCdfWriter::NetCdfWriter( const std::string &i_baseName,
		const Float2D &i_b,
		const BoundarySize &i_boundarySize,
		int i_nX, int i_nY,
		float i_dX, float i_dY,
		float i_originX, float i_originY,
		float i_coarseness,
        unsigned int i_flush) :
		//const bool  &i_dynamicBathymetry) : //!TODO
  io::Writer(i_baseName + ".nc", i_b, i_boundarySize, i_nX, i_nY, i_coarseness),
  flush(i_flush)
{
	int status;
    
	// variables (TODO: add rest of CF-1.5)
	int l_xVar, l_yVar;
    
	// dimensions
	int l_timeDim, l_xDim, l_yDim;
    
    // Try to open the file (to see if it is an existing checkpoint file)
    status = nc_open(fileName.c_str(), NC_WRITE, &dataFile);
    
    if(status == NC_NOERR) {
        // File exists and is a NetCDF file we can write to
        // Read ID for time, x, y, h, hu, hv and b dimensions and variables
        status = nc_inq_unlimdim(dataFile, &l_timeDim);
        status = nc_inq_dimid(dataFile, "x", &l_xDim);
        status = nc_inq_dimid(dataFile, "y", &l_yDim);
        status = nc_inq_varid(dataFile, "time", &timeVar);
        status = nc_inq_varid(dataFile, "x", &l_xVar);
        status = nc_inq_varid(dataFile, "y", &l_yVar);
        status = nc_inq_varid(dataFile, "h", &hVar);
        status = nc_inq_varid(dataFile, "hu", &huVar);
        status = nc_inq_varid(dataFile, "hv", &hvVar);
        status = nc_inq_varid(dataFile, "b", &bVar);
        
        // Read Dimensions for x and y variable
        size_t l_xLen, l_yLen;
        status = nc_inq_dimlen(dataFile, l_xDim, &l_xLen);
        status = nc_inq_dimlen(dataFile, l_yDim, &l_yLen);
        
        // Set next timeStep
        status = nc_inq_dimlen(dataFile, l_timeDim, &timeStep);
        
        // Check actual dimensions in file against supplied dimensions
        assert(l_xLen == coarseX); assert(l_yLen == coarseY);
    } else {
        // File does not exist or is not a valid NetCDF file
    	//create a netCDF-file, an existing file will be replaced
    	status = nc_create(fileName.c_str(), NC_NETCDF4, &dataFile);

        //check if the netCDF-file creation constructor succeeded.
    	if (status != NC_NOERR) {
    		assert(false);
    		return;
    	}

#ifdef PRINT_NETCDFWRITER_INFORMATION
    	std::cout << "   *** io::NetCdfWriter::createNetCdfFile" << std::endl;
    	std::cout << "     created/replaced: " << fileName << std::endl;
    	std::cout << "     internal dimensions(nx, ny): " << nX << ", " << nY << std::endl;
        std::cout << "     dimensions(nx, ny): " << coarseX << ", " << coarseY << std::endl;
        std::cout << "     coarseness: " << coarseness << std::endl;
    	std::cout << "     cell width(dx,dy): " << i_dX << ", " << i_dY << std::endl;
    	std::cout << "     origin(x,y): " << i_originX << ", " << i_originY << std::endl;
#endif

    	nc_def_dim(dataFile, "time", NC_UNLIMITED, &l_timeDim);
    	nc_def_dim(dataFile, "x", coarseX, &l_xDim);
    	nc_def_dim(dataFile, "y", coarseY, &l_yDim);

    	nc_def_var(dataFile, "time", NC_FLOAT, 1, &l_timeDim, &timeVar);
    	ncPutAttText(timeVar, "long_name", "Time");
    	ncPutAttText(timeVar, "units", "seconds since simulation start"); // the word "since" is important for the paraview reader
    	nc_def_var(dataFile, "x", NC_FLOAT, 1, &l_xDim, &l_xVar);
    	nc_def_var(dataFile, "y", NC_FLOAT, 1, &l_yDim, &l_yVar);

    	//variables, fastest changing index is on the right (C syntax), will be mirrored by the library
    	int dims[] = {l_timeDim, l_yDim, l_xDim};
    	nc_def_var(dataFile, "h",  NC_FLOAT, 3, dims, &hVar);
    	nc_def_var(dataFile, "hu", NC_FLOAT, 3, dims, &huVar);
    	nc_def_var(dataFile, "hv", NC_FLOAT, 3, dims, &hvVar);
    	nc_def_var(dataFile, "b",  NC_FLOAT, 2, &dims[1], &bVar);

    	//set attributes to match CF-1.5 convention
    	ncPutAttText(NC_GLOBAL, "Conventions", "CF-1.5");
    	ncPutAttText(NC_GLOBAL, "title", "Computed tsunami solution");
    	ncPutAttText(NC_GLOBAL, "history", "SWE");
    	ncPutAttText(NC_GLOBAL, "institution", "Technische Universitaet Muenchen, Department of Informatics, Chair of Scientific Computing");
    	ncPutAttText(NC_GLOBAL, "source", "Bathymetry and displacement data.");
    	ncPutAttText(NC_GLOBAL, "references", "http://www5.in.tum.de/SWE");
    	ncPutAttText(NC_GLOBAL, "comment", "SWE is free software and licensed under the GNU General Public License. Remark: In general this does not hold for the used input data.");

    	//setup grid size
    	float gridPosition = i_originX + (float).5 * i_dX;
    	for(size_t i = 0; i < coarseX; i++) {
    		nc_put_var1_float(dataFile, l_xVar, &i, &gridPosition);

    		gridPosition += i_dX;
    	}

    	gridPosition = i_originY + (float).5 * i_dY;
    	for(size_t j = 0; j < coarseY; j++) {
    		nc_put_var1_float(dataFile, l_yVar, &j, &gridPosition);

        	gridPosition += i_dY;
    	}
    }
}