コード例 #1
0
ファイル: genlib.c プロジェクト: Unidata/netcdf-c
static void
cl_netcdf(void)
{
    int stat = nc_close(ncid);
    check_err(stat);
}
コード例 #2
0
ファイル: read_netcdf.c プロジェクト: RHESSys/RHESSys
int get_netcdf_var(char *netcdf_filename, char *varname, 
				   char *nlat_name, char *nlon_name,
				   float rlat, float rlon, float sd, float *data){
	/***Read netcdf format metdata by using lat,lon as index
	 NO TIME DIMENSION
	 varname: variable name
	 rlat,rlon: y and x of site location
	 sd: the minimum distance for searching nearby grid in netcdf
	 ************************************************************/
	
	int ncid, temp_varid,nlatid,nlontid;
	int latid,lontid;
	size_t nlat,nlont;
	int ndims_in, nvars_in, ngatts_in, unlimdimid_in;
	float *lat,*lont;
	size_t start[2],count[2];
	int i,j,k,l;
	int retval;
	int idlat,idlont;	//offset
	/*printf("\n   Opening netcdf file...\n");*/
	/***open netcdf***/
	if((retval = nc_open(netcdf_filename, NC_NOWRITE, &ncid)))
		ERR(retval);
	if((retval = nc_inq(ncid, &ndims_in, &nvars_in, &ngatts_in,
                        &unlimdimid_in)))
		ERR(retval);
	/*printf("\n   ncid=%d ndims_in=%d nvars_in=%d ngatts_in=%d unlimdimid_in=%d\n",ncid, ndims_in, nvars_in, ngatts_in, unlimdimid_in);*/
	/***Get the dimension and var id***/
	if((retval = nc_inq_dimid(ncid, nlat_name, &nlatid)))
		ERR(retval);
	if((retval = nc_inq_dimid(ncid, nlon_name, &nlontid)))
		ERR(retval);
	if((retval = nc_inq_dimlen(ncid, nlatid, &nlat)))
		ERR(retval);
	if((retval = nc_inq_dimlen(ncid, nlontid, &nlont)))
		ERR(retval);
  	/* Get the varids of variables. */
	if ((retval = nc_inq_varid(ncid, nlat_name, &latid)))
		ERR(retval);
	if ((retval = nc_inq_varid(ncid, nlon_name, &lontid)))
		ERR(retval);
	if ((retval = nc_inq_varid(ncid, varname, &temp_varid)))
		ERR(retval);

	lat = (float *) alloc(nlat * sizeof(float),"lat","get_netcdf_var");
	lont = (float *) alloc(nlont * sizeof(float),"lont","get_netcdf_var");
	/* get dimention var */
	if ((retval = nc_get_var_float(ncid, latid, &lat[0]))){
		free(lat);
		free(lont);	
		ERR(retval);
	}
	if ((retval = nc_get_var_float(ncid, lontid, &lont[0]))){
		free(lat);
		free(lont);	
		ERR(retval);
	}
	/*locate the record */
	idlat = locate(lat,nlat,rlat,sd);
	idlont = locate(lont,nlont,rlon,sd);
	if(idlat == -1 || idlont == -1){
		fprintf(stderr,"can't locate the station\n");
		free(lat);
		free(lont);	
		return -1;
	}
	
	start[0] = idlat;           //lat
	start[1] = idlont;
	count[0] = 1;
	count[1] = 1;
	/***Read netcdf data***/ 
	if ((retval = nc_get_vara_float(ncid,temp_varid,start,count,&data[0]))){
		free(lat);
		free(lont);
		ERR(retval);
	}
	
	if ((retval = nc_close(ncid))){
		free(lat);
		free(lont);
		ERR(retval);
	}
	
	free(lat);
	free(lont);
	return 0;
}
コード例 #3
0
ファイル: read_netcdf.c プロジェクト: RHESSys/RHESSys
int get_netcdf_var_timeserias(char *netcdf_filename, char *varname, 
							  char *nlat_name, char *nlon_name, 
							  float rlat, float rlon, float sd, 
							  int startday, int day_offset, int duration, float *data){
	/***Read netcdf format metdata by using lat,lon as index
	varname: variable name
	rlat,rlon: latitue and longitude of site location
	sd: the minimum distance for searching nearby grid in netcdf
	startday: startday of metdata (since STARTYEAR-01-01)
	duration: days of required metdata

	Mingliang Liu
	Nov. 17, 2011
	************************************************************/

	int ncid, temp_varid,ndaysid,nlatid,nlontid;
        int dayid,latid,lontid;
        size_t nday,nlat,nlont;
        int ndims_in, nvars_in, ngatts_in, unlimdimid_in;
        int *days;
        float *lat,*lont;
        size_t start[3],count[3];
        int i,j,k,l;
        int retval;
	int idlat,idlont,idday;	//offset
	/*printf("\n   Opening netcdf file...\n");*/
        /***open netcdf***/
	if((retval = nc_open(netcdf_filename, NC_NOWRITE, &ncid)))
                ERR(retval);
        if((retval = nc_inq(ncid, &ndims_in, &nvars_in, &ngatts_in,
                        &unlimdimid_in)))
                ERR(retval);
		/*printf("\n   ncid=%d ndims_in=%d nvars_in=%d ngatts_in=%d unlimdimid_in=%d\n",ncid, ndims_in, nvars_in, ngatts_in, unlimdimid_in);*/
        /*printf("\n   Getting dimensions and var id... %d %s %d\n",ncid,NDAYS_NAME,ndaysid);*/
        /***Get the dimension and var id***/
        if((retval = nc_inq_dimid(ncid,NDAYS_NAME, &ndaysid)))
                ERR(retval);
        if((retval = nc_inq_dimid(ncid, nlat_name, &nlatid)))
                ERR(retval);
        if((retval = nc_inq_dimid(ncid, nlon_name, &nlontid)))
                ERR(retval);
        if((retval = nc_inq_dimlen(ncid, ndaysid, &nday)))
                ERR(retval);
        if((retval = nc_inq_dimlen(ncid, nlatid, &nlat)))
                ERR(retval);
        if((retval = nc_inq_dimlen(ncid, nlontid, &nlont)))
                ERR(retval);
  	/* Get the varids of variables. */
        if ((retval = nc_inq_varid(ncid, NDAYS_NAME, &dayid)))
                ERR(retval);
        if ((retval = nc_inq_varid(ncid, nlat_name, &latid)))
                ERR(retval);
        if ((retval = nc_inq_varid(ncid, nlon_name, &lontid)))
                ERR(retval);
        if ((retval = nc_inq_varid(ncid, varname, &temp_varid)))
                ERR(retval);

		days = (int *) alloc(nday * sizeof(int),"days","get_netcdf_var_timeserias");
        lat = (float *) alloc(nlat * sizeof(float),"lat","get_netcdf_var_timeserias");
        lont = (float *) alloc(nlont * sizeof(float),"lont","get_netcdf_var_timeserias");
	/* get dimention var */
        if ((retval = nc_get_var_int(ncid, dayid, &days[0]))){
                free(days);
		free(lat);
		free(lont);	
		ERR(retval);
	}
        if ((retval = nc_get_var_float(ncid, latid, &lat[0]))){
		free(days);
		free(lat);
		free(lont);	
                ERR(retval);
	}
        if ((retval = nc_get_var_float(ncid, lontid, &lont[0]))){
 		free(days);
		free(lat);
		free(lont);	
                ERR(retval);
	}
	/*locate the record */
	idlat = locate(lat,nlat,rlat,sd);
	idlont = locate(lont,nlont,rlon,sd);
	if(idlat == -1 || idlont == -1){
		fprintf(stderr,"can't locate the station\n");
 		free(days);
		free(lat);
		free(lont);	
		return -1;
	}
	/*printf("\nstartday=%d duration=%d nday=%d day1=%d dayfin=%d\n",startday,duration,nday,days[0],days[nday-1]);*/
	if((startday<days[0] || (duration+startday) > days[nday-1])){
		fprintf(stderr,"time period is out of the range of metdata\n");
  		free(days);
		free(lat);
		free(lont);	
		return -1;
	}
	start[0] = startday-days[0]+day_offset;		//netcdf 4.1.3 problem: there is 1 day offset
        start[1] = idlat;           //lat
	start[2] = idlont;
        count[0] = duration;
        count[1] = 1;
        count[2] = 1;
       	/***Read netcdf data***/ 
        if ((retval = nc_get_vara_float(ncid,temp_varid,start,count,&data[0]))){
		free(days);
		free(lat);
		free(lont);
		ERR(retval);
	}

	if ((retval = nc_close(ncid))){
		free(days);
		free(lat);
		free(lont);
		ERR(retval);
	}
	
	free(days);
	free(lat);
	free(lont);
	return 0;
}
コード例 #4
0
ファイル: Resample_on_Z.c プロジェクト: BreakawayLabs/MOM4p1
void write_output(char out_file[], char in_file[][FILE_NAME_SZ], char depth_file[],
     size_t nz, char var_names[MAX_VARS][NC_MAX_NAME], char time_names[2][NC_MAX_NAME], 
     char depth_names[2][NC_MAX_NAME], int *num_var,
     char arglist[]) {
  int i, j, v;
  int ncid, nc_den_id, status, ndims, ndim, nvariables, ngatt, recdim;
  int use_dim[NC_MAX_DIMS];
  int dv_id[NC_MAX_DIMS], dim2id[NC_MAX_DIMS], dim2vid[NC_MAX_DIMS];
  int dimids[NC_MAX_VAR_DIMS], dd2id[2];
  int ddvid[2], dd2vid[2];
  int num_att;
  int use_file[MAX_FILES], max_file;
  char dim_name[10][NC_MAX_NAME];
  char att_name[NC_MAX_NAME];
  nc_type xtype;

  size_t dim_len[NC_MAX_DIMS], ddim_len[2], max_dim_len = 0;
    
  status = nc_open(in_file[0],NC_NOWRITE, &ncid);
  if (status != NC_NOERR) handle_error(status,in_file[0],status);
  ncInid[0] = ncid; use_file[0] = 1;

  status = nc_inq(ncid,&ndims,&nvariables,&ngatt,&recdim);
  if (status != NC_NOERR) handle_error(status,in_file[0],status);
  strcpy(master_in_file,in_file[0]);

  for (i=1;i<MAX_FILES;i++) { ncInid[i] = -1; use_file[i] = 0;}
  for (i=0;i<MAX_FILES;i++) if (strlen(in_file[i]) == 0) break;
  max_file = i;

/* Determine which dimensions need to be created. */
  for (i=0;i<ndims;i++) use_dim[i] = 0.0;
  for (v=0;v<*num_var;v++) {
    int vin_id, fn = 0, id;
    for (fn=0;fn<max_file;fn++) {
      if (ncInid[fn] < 0) {
        status = nc_open(in_file[fn],NC_NOWRITE, &ncInid[fn]);
        if (status != NC_NOERR) handle_error(status,in_file[fn],status);
      }
      status = nc_inq_varid(ncInid[fn], var_names[v], &vin_id);
      if (status == NC_NOERR) break;
    }
    if (fn==max_file) {
      printf("ERROR: Unable to find variable %s in any of %d files.\n",var_names[v],max_file);
      handle_error(status, var_names[v], v);
    }
    id = ncInid[fn];
    status = nc_inq_var(id, vin_id, att_name, &xtype, &ndim, dimids, &num_att);
    if (status != NC_NOERR) handle_error(status, var_names[v], v);

    if (ndim < 2) printf("Variable %s has only 2 dimensions and will be excluded.\n", var_names[v]);
    else {
      use_dim[find_dimid(id,dimids[ndim-1],ncid)] = 1;
      use_dim[find_dimid(id,dimids[ndim-2],ncid)] = 1;
      if (ndim > 4) {
        printf("ERROR: Variable %s has %d dimensions. This program only works with up to 4 dimensions.\n",
                var_names[v],ndim);
        exit(-1);
      }
      if (ndim == 4) {
        int frecdim; status = nc_inq_unlimdim(id,&frecdim);
        if (status != NC_NOERR) handle_error(status,"Finding record dimid",status);
        if (dimids[0] = frecdim) use_dim[recdim] = 1;
        else {
          printf("ERROR: Variable %s has 4 non-record dimensions. This program only works with 3 such dimensions.\n",
                  var_names[v]);
          exit(-1);
        }
      }
      
      var_file[v] = fn;
      use_file[fn] = 1;
    }
  }

  // Close any unneeded files.
  for (i=1;i<max_file;i++) if ((use_file[i] == 0) && (ncInid[i] >= 0)) {
    nc_close(ncInid[i]); ncInid[i] = -1;
  }
  
  status = nc_create(out_file, 0, &ncOutid);
  if (status != NC_NOERR) handle_error(status,out_file,status);
  status = nc_set_fill(ncOutid,NC_NOFILL,&j);
  if (status != NC_NOERR) handle_error(status,out_file,status);

  // printf("Created file %s with id %d.\n",out_file,ncOutid);
    
  // Copy all of the global attributes over.
  for (j=0;j<ngatt;j++) {
    status = nc_inq_attname (ncid, NC_GLOBAL, j, att_name);
    if (status != NC_NOERR) handle_error(status,"Global",j);    
    status = nc_copy_att(ncid, NC_GLOBAL, att_name, ncOutid, NC_GLOBAL);
    if (status != NC_NOERR) handle_error(status,att_name,j);
  }
  {
    char hist[1000];
    status = nc_get_att_text(ncid, NC_GLOBAL,"history",hist);
    if (status == NC_NOERR) {strcat(hist,"\n"); strcat(hist,arglist);}
    else strcpy(hist,arglist);
    status = nc_put_att_text(ncOutid, NC_GLOBAL,"history",strlen(hist),hist);
  }
  
  // Copy all appropriate dimensions over.
  for (i=0;i<ndims;i++) if (use_dim[i]) {
    status = nc_inq_dim(ncid, i, dim_name[i], &dim_len[i]);
    if (status != NC_NOERR) handle_error(status, "", i);
    if (dim_len[i] > max_dim_len) max_dim_len = dim_len[i];

    if (i==recdim)
      status = nc_def_dim(ncOutid, dim_name[i], NC_UNLIMITED, &dim2id[i]);
    else
      status = nc_def_dim(ncOutid, dim_name[i], dim_len[i], &dim2id[i]);
    if (status != NC_NOERR) handle_error(status,dim_name[i],i);

    // Get information about the coordinate variable.
    status = nc_inq_varid (ncid, dim_name[i], &dv_id[i]);
    if (status != NC_NOERR) handle_error(status, dim_name[i], i);
    status = nc_inq_vartype(ncid, dv_id[i], &xtype);
    if (status != NC_NOERR) handle_error(status, dim_name[i], i);
    status = nc_inq_varnatts(ncid, dv_id[i], &num_att);
    if (status != NC_NOERR) handle_error(status,dim_name[i],i);

    // Create the coordinate variables.
    status = nc_def_var (ncOutid, dim_name[i], xtype, 1, &dim2id[i], &dim2vid[i]);
    if (status != NC_NOERR) handle_error(status, dim_name[i],i);    
    // Copy all of the attributes over.
    for (j=0;j<num_att;j++) {
      status = nc_inq_attname (ncid, dv_id[i], j, att_name);
      if (status != NC_NOERR) handle_error(status,att_name,j);
      status = nc_copy_att(ncid, dv_id[i], att_name, ncOutid, dim2vid[i]);
      if (status != NC_NOERR) handle_error(status,att_name,j);
    }
  }
  
  // Copy the vertical dimensions over from depth_file.
  //    if (strlen(depth_file) > 1)
  status = nc_open(depth_file,NC_NOWRITE, &nc_den_id);
  if (status != NC_NOERR) handle_error(status,depth_file,status);

  for (i=0;i<2;i++) {
    int ddid;
    status = nc_inq_dimid (nc_den_id, depth_names[i], &ddid);
    if (status != NC_NOERR) handle_error(status,depth_names[i],0);
    status = nc_inq_dimlen(nc_den_id, ddid, &ddim_len[i]);
    if (status != NC_NOERR) handle_error(status,depth_names[i], i);

    status = nc_def_dim(ncOutid, depth_names[i], ddim_len[i], &dd2id[i]);
    if (status != NC_NOERR) handle_error(status,depth_names[i],i);

    // Get information about the coordinate variable.
    status = nc_inq_varid (nc_den_id, depth_names[i], &ddvid[i]);
    if (status != NC_NOERR) handle_error(status, depth_names[i], i);
    status = nc_inq_vartype(nc_den_id, ddvid[i], &xtype);
    if (status != NC_NOERR) handle_error(status, depth_names[i], i);
    status = nc_inq_varnatts(nc_den_id, ddvid[i], &num_att);
    if (status != NC_NOERR) handle_error(status,depth_names[i],i);

    // Create the coordinate variables.
    status = nc_def_var (ncOutid, depth_names[i], xtype, 1, &dd2id[i], &dd2vid[i]);
    if (status != NC_NOERR) handle_error(status, depth_names[i],i);    
    // Copy all of the attributes over.
    for (j=0;j<num_att;j++) {
      status = nc_inq_attname (nc_den_id, ddvid[i], j, att_name);
      if (status != NC_NOERR) handle_error(status,att_name,j);
      status = nc_copy_att(nc_den_id, ddvid[i], att_name, ncOutid, dd2vid[i]);
      if (status != NC_NOERR) handle_error(status,att_name,j);
    }
  }


  // Create the auxiliary time variable (if it exists) and store the time indices.
  if (recdim != -1) {
    // If there is a record dimension, it must be one of the two named
    // time dimensions.  If none are named, the name of the record
    // dimension is copied into it.
    if ((strcmp(dim_name[recdim],time_names[0]) != 0) &&
        (strcmp(dim_name[recdim],time_names[1]) != 0)) {
      if (strlen(time_names[0]) == 0) strcpy(time_names[0],dim_name[recdim]);
      else if (strlen(time_names[1]) == 0) strcpy(time_names[1],dim_name[recdim]);
      else {
        printf("ERROR: The specified time variables %s and %s do not agree\n"
               "\twith the record variable, %s.\n",time_names[0],time_names[1],
               dim_name[recdim]);
        exit(-1);
      }
    }
  }
  for (v=0;v<2;v++) {
    status = nc_inq_varid(ncOutid, time_names[v], &time_out_id[v]);
    if (status != NC_NOERR) {
      if (strlen(time_names[v]) > 0)  {
        int out_dim;
        status = nc_inq_varid(ncid, time_names[v], &time_in_id[v]);
        if (status != NC_NOERR) handle_error(status, time_names[v], v);
        status = nc_inq_var(ncid, time_in_id[v], att_name, &xtype, &ndim,
                            dimids, &num_att);
        if (status != NC_NOERR) handle_error(status, time_names[v], v);
        if (ndim > 1) {
          printf("ERROR: Time variable %s has %d dimensions in %s.\n",time_names[v],ndim,in_file[0]);
          exit(-1);
        }
        out_dim = dim2id[dimids[0]];

        status = nc_def_var(ncOutid, time_names[v], xtype, ndim, &out_dim, &time_out_id[v]);
        if (status != NC_NOERR) handle_error(status, time_names[v],v);
        // Copy all of the attributes over.
        for (j=0;j<num_att;j++) {
          status = nc_inq_attname(ncid, time_in_id[v], j, att_name);
          if (status != NC_NOERR) handle_error(status,att_name,j);
          status = nc_copy_att(ncid, time_in_id[v], att_name, ncOutid, time_out_id[v]);
          if (status != NC_NOERR) handle_error(status,att_name,j);
        }
      }
    } else {
      status = nc_inq_varid(ncid, time_names[v], &time_in_id[v]);
      if (status != NC_NOERR) handle_error(status, time_names[v], v);
    }
  }

  // Create the output variables, while checking the validity of the list.
  for (v=0;v<*num_var;v++) {
    int id, vin_id, frecdim, valid = 1;
    for (i=0;i<2;i++) if (strcmp(var_names[v],time_names[i])==0) valid = 0;
    for (i=0;i<ndims;i++) if (strcmp(var_names[v],dim_name[i])==0) valid = 0;
    for (i=0;i<2;i++) if (strcmp(var_names[v],depth_names[i])==0) valid = 0;
    
    if (valid) {
      id = ncInid[var_file[v]];
      
      if (var_file[v] == 0) frecdim = recdim;
      else {
        status = nc_inq_unlimdim(id,&frecdim);
        if (status != NC_NOERR) handle_error(status,"Finding record dimid",status);
      }

      status = nc_inq_varid(id, var_names[v], &vin_id);
      if (status != NC_NOERR) handle_error(status, var_names[v], v);
      status = nc_inq_var(id, vin_id, att_name, &xtype, &ndim,
                          dimids, &num_att);
      if (status != NC_NOERR) handle_error(status, var_names[v], v);

      if (ndim <= 2) {
        printf("Variable %s has only 2 dimensions and will be excluded.\n", var_names[v]);
        valid = 0;
      } else if ((ndim == 3) && (dimids[0] == frecdim)) {
        printf("Variable %s uses the record dimension as 3rd dimension and will be excluded.\n", var_names[v]);
        valid = 0;
      }
    }

    if (valid) {
      // Get information about the variable.
      int out_dimids[4];
      if (dimids[0] != frecdim) {
        out_dimids[0] = dd2id[0]; var_count[v][0] = ddim_len[0];
        static_var[v] = 1; i = 1;
      } else {
        out_dimids[0] = dim2id[recdim]; out_dimids[1] = dd2id[0];
        var_count[v][0] = 1; var_count[v][1] = ddim_len[0];
        static_var[v] = 0; i = 2;
      }
      var_size[v] = ddim_len[0];
      for (;i<ndim;i++) {
        int did;
        did = find_dimid(id,dimids[i],ncid);
        out_dimids[i] = dim2id[did];
        var_count[v][i] = dim_len[did];
        var_size[v] *= var_count[v][i];
      }

      status = nc_def_var(ncOutid, var_names[v], xtype, ndim, out_dimids, &var_id[v]);
      if (status != NC_NOERR) handle_error(status, var_names[v],v);
      // Copy all of the attributes over.
      for (j=0;j<num_att;j++) {
        status = nc_inq_attname(id, vin_id, j, att_name);
        if (status != NC_NOERR) handle_error(status,att_name,j);
        status = nc_copy_att(id, vin_id, att_name, ncOutid, var_id[v]);
        if (status != NC_NOERR) handle_error(status,att_name,j);
      }
      status = nc_get_att_double(id, vin_id,"missing_value",&missing_val[v]);
      if (status != NC_NOERR) {
        missing_val[v] = -1.0e34;
        status = nc_put_att_double(ncOutid,var_id[v],"missing_value",xtype,1,&missing_val[v]);
        if (status != NC_NOERR) handle_error(status,"missing_value",v);
      }
    } else {
      for (i=v;i<*num_var-1;i++) strcpy(var_names[i],var_names[i+1]);
      (*num_var)--; v--;
    }
  }

  status = nc_enddef(ncOutid);
  if (status != NC_NOERR) handle_error(status,out_file,status);
  // printf("Finished define mode for %s.\n",out_file);
    
    
    
    
/*
    // Create the vertical coordinates. //
    status = nc_def_dim(ncOutid, zc_name, nz, &layerid);
    if (status != NC_NOERR) handle_error(status,zc_name,0);
    status = nc_def_var (ncOutid, zc_name, NC_DOUBLE, 1, &layerid, &layervid);
    if (status != NC_NOERR) handle_error(status,zc_name,0);

    status = nc_def_dim(ncOutid, ze_name, (size_t) (nz+1), &intid);
    if (status != NC_NOERR) handle_error(status,ze_name,0);
    status = nc_def_var (ncOutid, ze_name, NC_DOUBLE, 1, &intid, &intvid);
    if (status != NC_NOERR) handle_error(status,ze_name,0);
    status = nc_put_att_text(ncOutid, intvid, "units", 2, "m");
    if (status != NC_NOERR) handle_error(status,"Units Interface",0);

    dims[0] = layervid;
    {
      strcpy(att[0][0],"long_name"); strcpy(att[0][1],"Depth of Layer Center");
//      strcpy(att[1][0],"units"); strcpy(att[1][1],"m");
      strcpy(att[1][0],"units"); strcpy(att[1][1],"cm");
      strcpy(att[2][0],"positive"); strcpy(att[2][1],"down");
      strcpy(att[3][0],"edges"); strcpy(att[2][1],ze_name);
      for (j=0;j<=2;j++) {
        status = nc_put_att_text(ncOutid, layervid, att[j][0],
            strlen(att[j][1]), att[j][1]);
        if (status != NC_NOERR) handle_error(status,att[j][0],j);
      }
    
      strcpy(att[0][0],"long_name"); strcpy(att[0][1],"Depth of edges");
//      strcpy(att[1][0],"units"); strcpy(att[1][1],"m");
      strcpy(att[1][0],"units"); strcpy(att[1][1],"cm");
      strcpy(att[2][0],"positive"); strcpy(att[2][1],"down");
      for (j=0;j<=2;j++) {
        status = nc_put_att_text(ncOutid, intvid, att[j][0],
            strlen(att[j][1]), att[j][1]);
        if (status != NC_NOERR) handle_error(status,att[j][0],j);    
      }
    }
*/
     
    // Copy the axis values from the first file.
  {
    double *coord_array;
    coord_array = malloc(sizeof(double)*(max_dim_len));
    for (i=0;i<ndims;i++) if (use_dim[i] && (i!=recdim)) {
      status = nc_get_var_double(ncid,dv_id[i],coord_array);
      if (status != NC_NOERR) handle_error(status,"Read Coordinate Variable",i);
      
      status = nc_put_var_double(ncOutid,dim2vid[i],coord_array);
      if (status != NC_NOERR) handle_error(status,"Write Coordinate Variable",i);
    }
    
    // Copy the vertical axis values from the depth file.
    for (i=0;i<2;i++) {
      status = nc_get_var_double(nc_den_id,ddvid[i],coord_array);
      if (status != NC_NOERR) handle_error(status,"Read Coordinate Variable",i);
      
      status = nc_put_var_double(ncOutid,dd2vid[i],coord_array);
      if (status != NC_NOERR) handle_error(status,"Write Coordinate Variable",i);
    }

    free(coord_array);
  }

    /*
    {
      double *z;
      z = (double *) calloc((size_t) (nz+1), sizeof(double));
      for (i=0;i<=nz;i++) z[i] = (-100.0)*int_depth[i];
      status = nc_put_var_double(ncOutid,intid,z);
      if (status != NC_NOERR) handle_error(status,"Interface Coordinate",0);

      for (i=0;i<nz;i++) z[i] = (-100.0)*lay_depth[i];
      status = nc_put_var_double(ncOutid,layerid,z);
      if (status != NC_NOERR) handle_error(status,"Layer Coordinate",0);
    }
    */

  nc_close(nc_den_id);
}
コード例 #5
0
OSErr NetCDFWindMoverCurv::TextRead(char *path, TMap **newMap, char *topFilePath) // don't want a map  
{
	// this code is for curvilinear grids
	OSErr err = 0;
	long i,j, numScanned, indexOfStart = 0;
	int status, ncid, latIndexid, lonIndexid, latid, lonid, recid, timeid, numdims;
	size_t latLength, lonLength, recs, t_len, t_len2;
	float timeVal;
	char recname[NC_MAX_NAME], *timeUnits=0, month[10];	
	char dimname[NC_MAX_NAME], s[256], topPath[256];
	WORLDPOINTFH vertexPtsH=0;
	float *lat_vals=0,*lon_vals=0,yearShift=0.;
	static size_t timeIndex,ptIndex[2]={0,0};
	static size_t pt_count[2];
	Seconds startTime, startTime2;
	double timeConversion = 1.;
	char errmsg[256] = "",className[256]="";
	char fileName[64],*modelTypeStr=0;
	Point where;
	OSType typeList[] = { 'NULL', 'NULL', 'NULL', 'NULL' };
	MySFReply reply;
	Boolean bTopFile = false, fIsNavy = false;	// for now keep code around but probably don't need Navy curvilinear wind
	//VelocityFH velocityH = 0;
	char outPath[256];
	
	if (!path || !path[0]) return 0;
	strcpy(fPathName,path);
	
	strcpy(s,path);
	SplitPathFile (s, fileName);
	strcpy(fFileName, fileName); // maybe use a name from the file
	status = nc_open(path, NC_NOWRITE, &ncid);
	//if (status != NC_NOERR) {err = -1; goto done;}
	if (status != NC_NOERR) 
	{
#if TARGET_API_MAC_CARBON
		err = ConvertTraditionalPathToUnixPath((const char *) path, outPath, kMaxNameLen) ;
		status = nc_open(outPath, NC_NOWRITE, &ncid);
#endif
		if (status != NC_NOERR) {err = -1; goto done;}
	}
	// check number of dimensions - 2D or 3D
	status = nc_inq_ndims(ncid, &numdims);
	if (status != NC_NOERR) {err = -1; goto done;}
	
	status = nc_inq_attlen(ncid,NC_GLOBAL,"generating_model",&t_len2);
	if (status != NC_NOERR) {fIsNavy = false; /*goto done;*/}	
	else 
	{
		fIsNavy = true;
		// may only need to see keyword is there, since already checked grid type
		modelTypeStr = new char[t_len2+1];
		status = nc_get_att_text(ncid, NC_GLOBAL, "generating_model", modelTypeStr);
		if (status != NC_NOERR) {fIsNavy = false; goto done;}	
		modelTypeStr[t_len2] = '\0';
		
		strcpy(fFileName, modelTypeStr); 
	}
	GetClassName(className);
	if (!strcmp("NetCDF Wind",className))
		SetClassName(fFileName); //first check that name is now the default and not set by command file ("NetCDF Wind")
	
	//if (fIsNavy)
	{
		status = nc_inq_dimid(ncid, "time", &recid); //Navy
		//if (status != NC_NOERR) {err = -1; goto done;}
		if (status != NC_NOERR) 
		{	status = nc_inq_unlimdim(ncid, &recid);	// issue of time not being unlimited dimension
			if (status != NC_NOERR) {err = -1; goto done;}
		}			
	}
	/*else
	 {
	 status = nc_inq_unlimdim(ncid, &recid);	// issue of time not being unlimited dimension
	 if (status != NC_NOERR) {err = -1; goto done;}
	 }*/
	
	//if (fIsNavy)
	status = nc_inq_varid(ncid, "time", &timeid); 
	if (status != NC_NOERR) 
	{	
		status = nc_inq_varid(ncid, "ProjectionHr", &timeid); 
		if (status != NC_NOERR) {err = -1; goto done;}
	}			
	//	if (status != NC_NOERR) {/*err = -1; goto done;*/timeid=recid;} 
	
	//if (!fIsNavy)
	//status = nc_inq_attlen(ncid, recid, "units", &t_len);	// recid is the dimension id not the variable id
	//else	// LAS has them in order, and time is unlimited, but variable/dimension names keep changing so leave this way for now
	status = nc_inq_attlen(ncid, timeid, "units", &t_len);
	if (status != NC_NOERR) 
	{
		timeUnits = 0;	// files should always have this info
		timeConversion = 3600.;		// default is hours
		startTime2 = model->GetStartTime();	// default to model start time
		//err = -1; goto done;
	}
	else
	{
		DateTimeRec time;
		char unitStr[24], junk[10];
		
		timeUnits = new char[t_len+1];
		//if (!fIsNavy)
		//status = nc_get_att_text(ncid, recid, "units", timeUnits);	// recid is the dimension id not the variable id
		//else
		status = nc_get_att_text(ncid, timeid, "units", timeUnits);
		if (status != NC_NOERR) {err = -1; goto done;} 
		timeUnits[t_len] = '\0'; // moved this statement before StringSubstitute, JLM 5/2/10
		StringSubstitute(timeUnits, ':', ' ');
		StringSubstitute(timeUnits, '-', ' ');
		StringSubstitute(timeUnits, 'T', ' ');
		StringSubstitute(timeUnits, 'Z', ' ');
		
		numScanned=sscanf(timeUnits, "%s %s %hd %hd %hd %hd %hd %hd",
						  unitStr, junk, &time.year, &time.month, &time.day,
						  &time.hour, &time.minute, &time.second) ;
		if (numScanned==5)	
		{time.hour = 0; time.minute = 0; time.second = 0; }
		else if (numScanned==7) // has two extra time entries ??	
			time.second = 0;
		else if (numScanned<8)	
		//else if (numScanned!=8)	
		{ 
			//timeUnits = 0;	// files should always have this info
			//timeConversion = 3600.;		// default is hours
			//startTime2 = model->GetStartTime();	// default to model start time
			err = -1; TechError("NetCDFWindMoverCurv::TextRead()", "sscanf() == 8", 0); goto done;
		}
		else
		{
			// code goes here, trouble with the DAYS since 1900 format, since converts to seconds since 1904
			if (time.year ==1900) {time.year += 40; time.day += 1; /*for the 1900 non-leap yr issue*/ yearShift = 40.;}
			DateToSeconds (&time, &startTime2);	// code goes here, which start Time to use ??
			if (!strcmpnocase(unitStr,"HOURS") || !strcmpnocase(unitStr,"HOUR"))
				timeConversion = 3600.;
			else if (!strcmpnocase(unitStr,"MINUTES") || !strcmpnocase(unitStr,"MINUTE"))
				timeConversion = 60.;
			else if (!strcmpnocase(unitStr,"SECONDS") || !strcmpnocase(unitStr,"SECOND"))
				timeConversion = 1.;
			else if (!strcmpnocase(unitStr,"DAYS") || !strcmpnocase(unitStr,"DAY"))
				timeConversion = 24.*3600.;
		}
	} 
	
	status = nc_inq_dimid(ncid, "yc", &latIndexid); 
	if (status != NC_NOERR) 
	{	
		status = nc_inq_dimid(ncid, "y", &latIndexid); 
		if (status != NC_NOERR) 
		{
			err = -1; goto OLD;
		}
	}
	bIsCOOPSWaterMask = true;
	status = nc_inq_varid(ncid, "latc", &latid);
	if (status != NC_NOERR) 
	{
		status = nc_inq_varid(ncid, "lat", &latid);
		if (status != NC_NOERR) 
		{
			err = -1; goto done;
		}
	}
	status = nc_inq_dimlen(ncid, latIndexid, &latLength);
	if (status != NC_NOERR) {err = -1; goto done;}
	status = nc_inq_dimid(ncid, "xc", &lonIndexid);	
	if (status != NC_NOERR) 
	{
		status = nc_inq_dimid(ncid, "x", &lonIndexid); 
		if (status != NC_NOERR) 
		{
			err = -1; goto done;
		}
	}
	status = nc_inq_varid(ncid, "lonc", &lonid);	
	if (status != NC_NOERR) 
	{
		status = nc_inq_varid(ncid, "lon", &lonid);
		if (status != NC_NOERR) 
		{
			err = -1; goto done;
		}
	}
	status = nc_inq_dimlen(ncid, lonIndexid, &lonLength);
	if (status != NC_NOERR) {err = -1; goto done;}
	
OLD:
	if (!bIsCOOPSWaterMask)	
	{
	if (fIsNavy)
	{
		status = nc_inq_dimid(ncid, "gridy", &latIndexid); //Navy
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimlen(ncid, latIndexid, &latLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimid(ncid, "gridx", &lonIndexid);	//Navy
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimlen(ncid, lonIndexid, &lonLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		// option to use index values?
		status = nc_inq_varid(ncid, "grid_lat", &latid);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_varid(ncid, "grid_lon", &lonid);
		if (status != NC_NOERR) {err = -1; goto done;}
	}
	else
	{
		for (i=0;i<numdims;i++)
		{
			if (i == recid) continue;
			status = nc_inq_dimname(ncid,i,dimname);
			if (status != NC_NOERR) {err = -1; goto done;}
			if (!strncmpnocase(dimname,"X",1) || !strncmpnocase(dimname,"LON",3) || !strncmpnocase(dimname,"nx",2))
			{
				lonIndexid = i;
			}
			if (!strncmpnocase(dimname,"Y",1) || !strncmpnocase(dimname,"LAT",3) || !strncmpnocase(dimname,"ny",2))
			{
				latIndexid = i;
			}
		}
		
		status = nc_inq_dimlen(ncid, latIndexid, &latLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_dimlen(ncid, lonIndexid, &lonLength);
		if (status != NC_NOERR) {err = -1; goto done;}
		
		status = nc_inq_varid(ncid, "LATITUDE", &latid);
		if (status != NC_NOERR) 
		{
			status = nc_inq_varid(ncid, "lat", &latid);
			if (status != NC_NOERR) 
			{
				status = nc_inq_varid(ncid, "latitude", &latid);
				if (status != NC_NOERR) {err = -1; goto done;}
			}
		}
		status = nc_inq_varid(ncid, "LONGITUDE", &lonid);
		if (status != NC_NOERR) 
		{
			status = nc_inq_varid(ncid, "lon", &lonid);
			if (status != NC_NOERR) 
			{
				status = nc_inq_varid(ncid, "longitude", &lonid);
				if (status != NC_NOERR) {err = -1; goto done;}
			}
		}
	}
	}
	pt_count[0] = latLength;
	pt_count[1] = lonLength;
	vertexPtsH = (WorldPointF**)_NewHandleClear(latLength*lonLength*sizeof(WorldPointF));
	if (!vertexPtsH) {err = memFullErr; goto done;}
	lat_vals = new float[latLength*lonLength]; 
	lon_vals = new float[latLength*lonLength]; 
	if (!lat_vals || !lon_vals) {err = memFullErr; goto done;}
	status = nc_get_vara_float(ncid, latid, ptIndex, pt_count, lat_vals);
	if (status != NC_NOERR) {err = -1; goto done;}
	status = nc_get_vara_float(ncid, lonid, ptIndex, pt_count, lon_vals);
	if (status != NC_NOERR) {err = -1; goto done;}
	for (i=0;i<latLength;i++)
	{
		for (j=0;j<lonLength;j++)
		{
			//if (lat_vals[(latLength-i-1)*lonLength+j]==fill_value)	// this would be an error
			//lat_vals[(latLength-i-1)*lonLength+j]=0.;
			//if (lon_vals[(latLength-i-1)*lonLength+j]==fill_value)
			//lon_vals[(latLength-i-1)*lonLength+j]=0.;
			INDEXH(vertexPtsH,i*lonLength+j).pLat = lat_vals[(latLength-i-1)*lonLength+j];	
			INDEXH(vertexPtsH,i*lonLength+j).pLong = lon_vals[(latLength-i-1)*lonLength+j];
		}
	}
	fVertexPtsH	 = vertexPtsH;
	
	status = nc_inq_dim(ncid, recid, recname, &recs);
	if (status != NC_NOERR) {err = -1; goto done;}
	if (recs<=0) {strcpy(errmsg,"No times in file. Error opening NetCDF wind file"); err =  -1; goto done;}
	
	fTimeHdl = (Seconds**)_NewHandleClear(recs*sizeof(Seconds));
	if (!fTimeHdl) {err = memFullErr; goto done;}
	for (i=0;i<recs;i++)
	{
		Seconds newTime;
		// possible units are, HOURS, MINUTES, SECONDS,...
		timeIndex = i;
		//if (!fIsNavy)
		//status = nc_get_var1_float(ncid, recid, &timeIndex, &timeVal);	// recid is the dimension id not the variable id
		//else
		status = nc_get_var1_float(ncid, timeid, &timeIndex, &timeVal);
		if (status != NC_NOERR) {err = -1; goto done;}
		newTime = RoundDateSeconds(round(startTime2+timeVal*timeConversion));
		//INDEXH(fTimeHdl,i) = startTime2+(long)(timeVal*timeConversion -yearShift*3600.*24.*365.25);	// which start time where?
		//if (i==0) startTime = startTime2+(long)(timeVal*timeConversion -yearShift*3600.*24.*365.25);
		INDEXH(fTimeHdl,i) = newTime-yearShift*3600.*24.*365.25;	// which start time where?
		if (i==0) startTime = newTime-yearShift*3600.*24.*365.25;
	}
	if (model->GetStartTime() != startTime || model->GetModelTime()!=model->GetStartTime())
	{
		if (true)	// maybe use NOAA.ver here?
		{
			short buttonSelected;
			//buttonSelected  = MULTICHOICEALERT(1688,"Do you want to reset the model start time to the first time in the file?",FALSE);
			if(!gCommandFileRun)	// also may want to skip for location files...
				buttonSelected  = MULTICHOICEALERT(1688,"Do you want to reset the model start time to the first time in the file?",FALSE);
			else buttonSelected = 1;	// TAP user doesn't want to see any dialogs, always reset (or maybe never reset? or send message to errorlog?)
			switch(buttonSelected){
				case 1: // reset model start time
					//bTopFile = true;
					model->SetModelTime(startTime);
					model->SetStartTime(startTime);
					model->NewDirtNotification(DIRTY_RUNBAR); // must reset the runbar
					break;  
				case 3: // don't reset model start time
					//bTopFile = false;
					break;
				case 4: // cancel
					err=-1;// user cancel
					goto done;
			}
		}
		//model->SetModelTime(startTime);
		//model->SetStartTime(startTime);
		//model->NewDirtNotification(DIRTY_RUNBAR); // must reset the runbar
	}
	
	fNumRows = latLength;
	fNumCols = lonLength;
	
	status = nc_close(ncid);
	if (status != NC_NOERR) {err = -1; goto done;}
	
	//err = this -> SetInterval(errmsg);
	//if(err) goto done;
	
	// look for topology in the file
	// for now ask for an ascii file, output from Topology save option
	// need dialog to ask for file
	//if (fIsNavy)	// for now don't allow for wind files
	{if (topFilePath[0]) {err = ReadTopology(topFilePath,newMap); goto done;}}
	if (!gCommandFileRun)
	{
		short buttonSelected;
		buttonSelected  = MULTICHOICEALERT(1688,"Do you have an extended topology file to load?",FALSE);
		switch(buttonSelected){
			case 1: // there is an extended top file
				bTopFile = true;
				break;  
			case 3: // no extended top file
				bTopFile = false;
				break;
			case 4: // cancel
				err=-1;// stay at this dialog
				goto done;
		}
	}
	if(bTopFile)
	{
#if TARGET_API_MAC_CARBON
		mysfpgetfile(&where, "", -1, typeList,
					 (MyDlgHookUPP)0, &reply, M38c, MakeModalFilterUPP(STDFilter));
		if (!reply.good)/* return USERCANCEL;*/
		{
			/*if (recs>0)
				err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg);
			else {strcpy(errmsg,"No times in file. Error opening NetCDF file"); err =  -1;}
			if(err) goto done;*/
			if (bIsCOOPSWaterMask) err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPointsCOOPSNoMask(newMap,errmsg);	
			else err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg);	
			//err = ReorderPoints(fStartData.dataHdl,newMap,errmsg);	// if u, v input separately only do this once?
	 		goto done;
		}
		else
			strcpy(topPath, reply.fullPath);
		
#else
		where = CenteredDialogUpLeft(M38c);
		sfpgetfile(&where, "",
				   (FileFilterUPP)0,
				   -1, typeList,
				   (DlgHookUPP)0,
				   &reply, M38c,
				   (ModalFilterUPP)MakeUPP((ProcPtr)STDFilter, uppModalFilterProcInfo));
		if (!reply.good) 
		{
			/*if (recs>0)
				err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg);
			else {strcpy(errmsg,"No times in file. Error opening NetCDF file"); err =  -1;}
			if(err) goto done;*/
			if (bIsCOOPSWaterMask) err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPointsCOOPSNoMask(newMap,errmsg);	
			else err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg);	
			//err = ReorderPoints(fStartData.dataHdl,newMap,errmsg);	
	 		/*if (err)*/ goto done;
		}
		
		my_p2cstr(reply.fName);
		
#ifdef MAC
		GetFullPath(reply.vRefNum, 0, (char *)reply.fName, topPath);
#else
		strcpy(topPath, reply.fName);
#endif
#endif		
		strcpy (s, topPath);
		err = ReadTopology(topPath,newMap);	
		goto done;
	}
	
	/*if (recs>0)
		err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg);
	else {strcpy(errmsg,"No times in file. Error opening NetCDF wind file"); err =  -1;}
	if(err) goto done;*/
	if (bIsCOOPSWaterMask) err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPointsCOOPSNoMask(newMap,errmsg);	
	else err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg);	
	//err = ReorderPoints(fStartData.dataHdl,newMap,errmsg);	
	
done:
	if (err)
	{
		printNote("Error opening NetCDF wind file");
		if(fGrid)
		{
			fGrid ->Dispose();
			delete fGrid;
			fGrid = 0;
		}
		if(vertexPtsH) {DisposeHandle((Handle)vertexPtsH); vertexPtsH = 0;	fVertexPtsH	 = 0;}
	}
	
	if (timeUnits) delete [] timeUnits;
	if (lat_vals) delete [] lat_vals;
	if (lon_vals) delete [] lon_vals;
	if (modelTypeStr) delete [] modelTypeStr;
	//if (velocityH) {DisposeHandle((Handle)velocityH); velocityH = 0;}
	return err;
}
コード例 #6
0
ファイル: vol2NetCDF.c プロジェクト: MRKspace/imgRecSrc
int main(int argc, char* argv[])
{
    char* filename=argv[1];
    FILE* f;

    if(argc<3){
        printf("error:   ");
        printf("Call this program by \"%s volfile.vol out.nc\"\n",argv[0]);
        return -1;
    }

    char line[MAXLINE];
    long int nx,ny,nz;
    //char Shortline[100];
    int i,j,max=0,temp;
    int ncid, x_dimid, y_dimid, z_dimid, varid;
    int dimids[3],retval;
    size_t start[3],count[3];
    long int filesize;
    int x, y,z;
    DATATYPE* data,p;

    printf("input filename: %s \n",filename);
    if((f=fopen(filename,"rb"))){
        fseek(f,0,SEEK_END);
        filesize=ftell(f);
        printf("filesize=%ld\n",filesize);
        rewind(f);
        temp=0;
        while(temp!=3){
            i=0;
            while((line[i]=fgetc(f))!=0 && line[i]!=13 && line[i]!=10) i++;
            //printf("%s\n",line);
            temp=sscanf(line,"Volume Size: %ldx%ldx%ld",&ny,&nx,&nz);
        }
        printf("Volume Size: %ldx%ldx%ld\n",nx,ny,nz);
        fseek(f,filesize%(nx*ny*nz),SEEK_SET);

        data = (DATATYPE*)calloc(nx*ny, sizeof(DATATYPE));
        if(data==NULL){ perror("failed calloc call\n"); return -1; }

        if ((retval = nc_create(argv[2], NC_NETCDF4|NC_CLOBBER, &ncid))) ERR(retval);
        if ((retval = nc_def_dim(ncid, "x", nx, &x_dimid))) ERR(retval);
        if ((retval = nc_def_dim(ncid, "y", ny, &y_dimid))) ERR(retval);
        if ((retval = nc_def_dim(ncid, "z", nz, &z_dimid))) ERR(retval);

        dimids[0] = z_dimid;
        dimids[1] = x_dimid;
        dimids[2] = y_dimid;

        printf("Start to convert sin to NetCDF format ...\n");
#if FLOAT
        if ((retval = nc_def_var(ncid, "density", NC_FLOAT, 3, dimids, &varid))) ERR(retval);
#endif
        if ((retval = nc_enddef(ncid))) ERR(retval);

        count[0] = 1;
        count[1] = nx;
        count[2] = ny;
        start[0] = 0;
        start[1] = 0;
        start[2] = 0;

        memset(line,0,MAXLINE);
        for(z=0; z<nz; z++){
            temp=fread(data,sizeof(DATATYPE),nx*ny,f);
            if(temp!=(nx*ny)){
                printf("readed %d bytes intead of %ld\n",temp,nx*ny*sizeof(DATATYPE));
                return -1;
            }
            //printf("data: %f %f %f %f\n", data[0], data[1], data[2], data[3]);
            start[0]=z;
#if FLOAT
            if ((retval = nc_put_vara_float(ncid, varid, start, count, data))) ERR(retval);
#endif
            for(i=0; i<strlen(line); i++) printf("\b");
            sprintf(line,"z=%d/%ld",z,nz);
            printf("%s",line);
            fflush(stdout);
        }
        fclose(f);
        if ((retval = nc_close(ncid))) ERR(retval);
        printf("\n");
    }

    return 0;
}
コード例 #7
0
ファイル: imrcdf.c プロジェクト: ArielleBassanelli/gempak
void im_rcdf ( char imgfil[], int *kx, int *ky, int *isorc, int *itype, 
		int *idate, int *itime, int *iproj, float *clat, 
		float *clon, float *xmin, float *xmax, float *ymin, 
		float *ymax, int *iret )
/************************************************************************
 * im_rcdf								*
 *									*
 * This subroutine opens a NetCDF file and reads the header information *
 * and returns it to the calling function.                              *
 *                                                                      *
 * im_rcdf ( imgfil, kx, ky, isorc, itype, idate, itime, iproj,         *
 *	  clat, clon, xmin, xmax, ymin, ymax, iret )                    *
 *                                                                      *
 * Input parameters:                                                    *
 *	imgfil[]	char		Name of image file              *
 *                                                                      *
 * Output parameters:                                                   *
 *	*kx		int		x dimension of image		*
 *     	*ky		int		y dimension of image		*
 *	*isorc		int						*
 *	*itype		int		type of channel			*
 * 	*idate		int		date				*
 *	*itime		int		time				*
 *	*iproj		int		projection type			*
 *	*clat		float		central latitude		*
 * 	*clon		float		central longitude		*
 *	*xmin		float		x - minimum for image		*
 * 	*xmax	 	float		x - maximum for image		*
 *	*ymin 		float		y - minimum for image		*
 *	*ymax		float		y - maximum for image		*
 *	*iret 		int		return value			*
 *                                                                      *
 *                                                                      *
 **									*
 * Log:									*
 * S. Jacobs/NCEP	 6/99	Created					*
 * R. Curtis/EAI  	 8/00   Updated and implemented in GEMPAK       *
 * T. Piper/GSC		 9/00	Modified for Lambert Conformal		*
 * A. Hardy/GSC		 7/01   Modified to use the channel table       *
 ***********************************************************************/
{
	int		ncid, iy, im, id, ih, in, is;
	size_t		lenp, jx, jy;
	double		dsec;
	time_t		isec;
	struct tm	*tarr;
	char		chanl[81];
/*---------------------------------------------------------------------*/
	*iret = 0;
/*
 *	Open the NetCDF file.
 */
	nc_open ( imgfil, NC_NOWRITE, &ncid );
/*
 *	Get the x and y dimensions of the image.
 */
	nc_inq_dimlen ( ncid, 0, &jy );
	nc_inq_dimlen ( ncid, 1, &jx );
	*kx = (int) jx;
	*ky = (int) jy;
/*
 *	Get the date/time. It is stored as the number of seconds
 *	since 00:00:00 UTC, January 1, 1970.
 */
	nc_get_var1_double ( ncid, 1, 0, &dsec );
	isec = (time_t) dsec;
	tarr = gmtime ( &isec );
	iy = (*tarr).tm_year + 1900;
	im = (*tarr).tm_mon + 1;
	id = (*tarr).tm_mday;
	ih = (*tarr).tm_hour;
	in = (*tarr).tm_min;
	is = (*tarr).tm_sec;
	*idate = iy * 10000 + im * 100 + id;
	*itime = ih * 10000 + in * 100 + is;
/*
 *	Get the channel information.
 */
	nc_inq_attlen ( ncid, NC_GLOBAL, "channel", &lenp );
	nc_get_att_text ( ncid, NC_GLOBAL, "channel", chanl );
	chanl[lenp] = CHNULL;
/*
 *       ITYPE  Channel String(s)
 *      -----------------------------
 *          1   VIS
 *          2   3.9 micron (IR2)
 *          4   6.7 micron (WV)
 *          8   11  micron (IR)
 *         16   12  micron (IR5)
 */
	im_chtb ( chanl, itype, iret, strlen(chanl) );
/*
 *	Get the projection and central lat/lon.
 */
	nc_get_att_int ( ncid, NC_GLOBAL, "projIndex", iproj );
	nc_get_att_float ( ncid, NC_GLOBAL, "centralLat", clat );
	nc_get_att_float ( ncid, NC_GLOBAL, "centralLon", clon );
/*
 *	If the center longitude is east of -100, assume that the image
 *	is from GOES-8. Otherwise, assume that it is from GOES-9.
 */
	if  ( *clon > -100.0 )  {
	    *isorc = 70;
	}
	else {
	    *isorc = 72;
	}
/*
 *	Get the corner lat/lons. The values are for the upper left
 *	and lower right corners.
 */
	nc_get_att_float ( ncid, NC_GLOBAL, "xMin",   xmin );
	nc_get_att_float ( ncid, NC_GLOBAL, "xMax",   xmax );
	nc_get_att_float ( ncid, NC_GLOBAL, "yMin",   ymin );
	nc_get_att_float ( ncid, NC_GLOBAL, "yMax",   ymax );
/*
 *	Close the NetCDF file.
 */
 	nc_close ( ncid );
}
コード例 #8
0
int
main()
{

    int ncid;
    int varid;
    int i;
    int ncstatus;
    size_t start[5], count[5];
    ptrdiff_t stride[5], tmp_ptrdiff_t;
    int pass = 1;
    int nelems = XSIZE*YSIZE;

    int idim, ndim;
    float *dat = (float*)malloc(sizeof(float)*nelems);
    float sdat[10];

    for (idim=0; idim<5; idim++) {
        start[idim] = 0;
        count[idim] = 1;
        stride[idim] = 1;
    }

    ndim=2;

    printf(" \n");
    printf("********************\n");
    printf("open URL %s\n",URL);
    printf(" \n");

    ncstatus = nc_open(URL, NC_NOWRITE, &ncid);

    if(ncstatus != NC_NOERR) {
	fprintf(stderr,"Could not open: %s; server may be down; test ignored\n",URL);
	exit(0);
    }

    ncstatus = nc_inq_varid(ncid, VAR1, &varid);

    ndim=2;


#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Read %s data w/o strides\n",VAR1);
    printf(" \n");
#endif

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;
    start[3] = 0;

    count[0] =  XSIZE;
    count[1] =  YSIZE;

    stride[0] = 1;
    stride[1] = 1;

#ifdef VERBOSE
    for (idim=0; idim<ndim; idim++)
	printf("start[%1d]=%3lu count[%1d]=%3lu stride[%1d]=%3lu\n",
		idim,start[idim],idim,count[idim],idim,stride[idim]);
#endif

    ncstatus = nc_get_vars_float (ncid, varid, start, count, stride, (float*) dat);

#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Print some of %s\n",VAR1);
    printf(" \n");

    for (i=0; i<10; i++)
        printf("%s[%d] = %f\n",VAR1,i,dat[i]);
    printf(" \n");


    for (i=(nelems-11); i<(nelems-1); i++)
        printf("%s[%d] = %f\n",VAR1,i,dat[i]);
    printf(" \n");
#endif

    memset((void*)dat,0,sizeof(dat));

    /* Read a second variable */

    ncstatus = nc_inq_varid(ncid, VAR2, &varid);

    ndim=2;

#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Read %s data w/o strides\n",VAR2);
    printf(" \n");
#endif

    start[0] = 0;
    start[1] = 0;
    start[2] = 0;
    start[3] = 0;

    count[0] =  XSIZE;
    count[1] =  YSIZE;

    stride[0] = 1;
    stride[1] = 1;

#ifdef VERBOSE
    for (idim=0; idim<ndim; idim++)
        printf("start[%d]=%3lu count[%d]=%3lu stride[%d]=%3lu\n",
		idim, start[idim], idim, count[idim], idim, stride[idim]);
#endif

    ncstatus = nc_get_vars_float (ncid, varid, start, count, stride, (float*) dat);

#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Print some of %s\n",VAR2);
    printf(" \n");
    for (i=0; i<10; i++)
        printf("%s[%d] = %f\n",VAR2,i,dat[i]);
    printf(" \n");

    printf(" \n");
    for (i=(nelems-11); i<(nelems-1); i++)
        printf("%s[%d] = %f\n",VAR2,i,dat[i]);
    printf(" \n");
#endif

    memset((void*)dat,0,sizeof(dat));

    /* close and reopen the dataset, then the below read is correct */

#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Close and reopen the dataset\n");
#endif

    ncstatus = nc_close (ncid);
    ncstatus = nc_open(URL, NC_NOWRITE, &ncid);

    /*  ----------------------------------------------------- */
    /* Read a subset of the data with strides */

    ncstatus = nc_inq_varid(ncid, VAR1, &varid);

#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Read a subset of %s data with strides\n",VAR1);
    printf(" \n");
#endif

    start[0] = 250;
    start[1] = 704;

    count[0] =  5;
    count[1] =  2;

    stride[0] = 2;
    stride[1] = 4;

#ifdef VERBOSE
    for (idim=0; idim<ndim; idim++)
	printf("start[%1d]=%3lu count[%1d]=%3lu stride[%1d]=%3lu\n",
		idim,start[idim],idim,count[idim],idim,stride[idim]);
#endif

    memset((void*)sdat,0,sizeof(sdat));
    ncstatus = nc_get_vars_float (ncid, varid, start, count, stride,  (float*) sdat);

    printf("status = %d\n", ncstatus);

    /* Verify that all read values are 50 <= n < 51 */
    for (i=0; i<10; i++) {
	if(sdat[i] <= 50.0 || sdat[i] > 51.0) {
	    printf("Out of range: %s[%d] = %f\n",VAR1, i,sdat[i]);
	    pass = 0;
	}
    }

#ifdef VERBOSE
    printf(" \n");
    printf("********************\n");
    printf("Print  values read. They should all be 50.xxxx \n");
    printf(" \n");

    for (i=0; i<10; i++)
        printf("%s[%d] = %f\n",VAR1,i,sdat[i]);
#endif

    ncstatus = nc_close (ncid);

    if(!pass) {
	printf("*** FAIL: %s value out of range.\n",VAR1);
	exit(1);
    }

    printf("*** PASS\n");
    free(dat);
    exit(0);

}
コード例 #9
0
int
main(int argc, char **argv)
{
   printf("\n*** Testing HDF4/NetCDF-4 interoperability...\n");
   printf("*** testing that netCDF can read a HDF4 file with some ints...");
   {
#define PRES_NAME "pres"
#define LAT_LEN 3
#define LON_LEN 2
#define DIMS_2 2

      int32 sd_id, sds_id;
      int32 dim_size[DIMS_2] = {LAT_LEN, LON_LEN};
      int32 start[DIMS_2] = {0, 0}, edge[DIMS_2] = {LAT_LEN, LON_LEN};
      int ncid, nvars_in, ndims_in, natts_in, unlimdim_in;
      size_t len_in;
      int data_out[LAT_LEN][LON_LEN], data_in[LAT_LEN][LON_LEN];
      size_t nstart[DIMS_2] = {0, 0}, ncount[DIMS_2] = {LAT_LEN, LON_LEN};
      size_t nindex[DIMS_2] = {0, 0};
      int scalar_data_in = 0;
      int i, j;

      /* Create some data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    data_out[i][j] = j;

      /* Create a file with one SDS, containing our phony data. */
      sd_id = SDstart(FILE_NAME, DFACC_CREATE);
      sds_id = SDcreate(sd_id, PRES_NAME, DFNT_INT32, DIMS_2, dim_size);
      if (SDwritedata(sds_id, start, NULL, edge, (void *)data_out)) ERR;
      if (SDendaccess(sds_id)) ERR;
      if (SDend(sd_id)) ERR;

      /* Now open with netCDF and check the contents. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; 
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdim_in)) ERR; 
      if (ndims_in != 2 || nvars_in != 1 || natts_in != 0 || unlimdim_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, NULL, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_inq_dim(ncid, 1, NULL, &len_in)) ERR;
      if (len_in != LON_LEN) ERR;
      
      /* Read the data through a vara function from the netCDF API. */
      if (nc_get_vara(ncid, 0, nstart, ncount, data_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (data_in[i][j] != data_out[i][j]) ERR;

      /* Reset for next test. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    data_in[i][j] = -88;

      /* Read the data through a vara_int function from the netCDF API. */
      if (nc_get_vara_int(ncid, 0, nstart, ncount, data_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (data_in[i][j] != data_out[i][j]) ERR;

      /* Reset for next test. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    data_in[i][j] = -88;

      /* Read the data through a var_int function from the netCDF API. */
      if (nc_get_var_int(ncid, 0, data_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (data_in[i][j] != data_out[i][j]) ERR;

      /* Read the data through a var1 function from the netCDF API. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	 {
	    nindex[0] = i;
	    nindex[1] = j;
	    if (nc_get_var1(ncid, 0, nindex, &scalar_data_in)) ERR;
	    if (scalar_data_in != data_out[i][j]) ERR;
	    scalar_data_in = -88; /* reset */
	    if (nc_get_var1_int(ncid, 0, nindex, &scalar_data_in)) ERR;
	    if (scalar_data_in != data_out[i][j]) ERR;
	 }

      if (nc_close(ncid)) ERR; 
   }
   SUMMARIZE_ERR;
   printf("*** testing with a more complex HDF4 file...");
   {
#define Z_LEN 3
#define Y_LEN 2
#define X_LEN 5
#define DIMS_3 3
#define NUM_TYPES 8

      int32 sd_id, sds_id;
      int32 dim_size[DIMS_3] = {Z_LEN, Y_LEN, X_LEN};
      int dimids_in[DIMS_3];
      int ncid, nvars_in, ndims_in, natts_in, unlimdim_in;
      size_t len_in;
      nc_type type_in;
      int hdf4_type[NUM_TYPES] = {DFNT_FLOAT32, DFNT_FLOAT64, 
				  DFNT_INT8, DFNT_UINT8, DFNT_INT16, 
				  DFNT_UINT16, DFNT_INT32, DFNT_UINT32};
      int netcdf_type[NUM_TYPES] = {NC_FLOAT, NC_DOUBLE, 
				  NC_BYTE, NC_UBYTE, NC_SHORT, 
				  NC_USHORT, NC_INT, NC_UINT};
      char tmp_name[NC_MAX_NAME + 1], name_in[NC_MAX_NAME + 1];
      char dim_name[NC_MAX_NAME + 1][DIMS_3] = {"z", "y", "x"};
      int d, t;

      /* Create a HDF4 SD file. */
      sd_id = SDstart (FILE_NAME, DFACC_CREATE);

      /* Create some HDF4 datasets. */
      for (t = 0; t < NUM_TYPES; t++)
      {
	 sprintf(tmp_name, "hdf4_dataset_type_%d", t);
	 if ((sds_id = SDcreate(sd_id, tmp_name, hdf4_type[t], 
				DIMS_3, dim_size)) == FAIL) ERR;	    
	 /* Set up dimensions. By giving them the same names for each
	  * dataset, I am specifying that they are shared
	  * dimensions. */
	 for (d = 0; d < DIMS_3; d++)
	 {
	    int32 dimid;
	    if ((dimid = SDgetdimid(sds_id, d)) == FAIL) ERR;
	    if (SDsetdimname(dimid, dim_name[d])) ERR;
	 }
	 if (SDendaccess(sds_id)) ERR;
      }
      if (SDend(sd_id)) ERR;

      /* Open the file with netCDF and check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdim_in)) ERR;
      if (ndims_in != DIMS_3 || nvars_in != NUM_TYPES || natts_in != 0 || unlimdim_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, NULL, &len_in)) ERR;
      if (len_in != Z_LEN) ERR;
      if (nc_inq_dim(ncid, 1, NULL, &len_in)) ERR;
      if (len_in != Y_LEN) ERR;
      if (nc_inq_dim(ncid, 2, NULL, &len_in)) ERR;
      if (len_in != X_LEN) ERR;
      for (t = 0; t < NUM_TYPES; t++)
      {
	 if (nc_inq_var(ncid, t, name_in, &type_in, &ndims_in, 
			dimids_in, &natts_in)) ERR;
	 if (type_in != netcdf_type[t] || ndims_in != DIMS_3 ||
	     dimids_in[0] != 0 || dimids_in[2] != 2 || dimids_in[2] != 2 || 
	     natts_in != 0) ERR;
      }
      
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #10
0
ファイル: tst_nans.c プロジェクト: ArielleBassanelli/gempak
int
main(int argc, char **argv)
{
    int ncid, dimid, fvarid, dvarid;
    float fvals[NVALS], fvals_in[NVALS];
    double dvals[NVALS], dvals_in[NVALS];

    float fnan = 0.f/0.f;
    double dnan = 0.0/0.0;
    float fpinf = 1.0f/0.0f;
    float fninf = -fpinf;
    double dpinf = 1.0/0.0;
    double dninf = -dpinf;
    nc_type att_type;
    size_t att_len;
    float att_fvals[NVALS];
    double att_dvals[NVALS];

    printf("\n*** Testing NaN\n");
    printf("*** creating NaN test file %s...", FILE8_NAME);
    if (nc_create(FILE8_NAME, NC_CLOBBER, &ncid)) ERR;
    
    if (nc_def_dim(ncid, DIM_NAME, NVALS, &dimid)) ERR;
    
    if (nc_def_var(ncid, F_NAME, NC_FLOAT, NDIMS, &dimid, &fvarid)) ERR;
    if (nc_def_var(ncid, D_NAME, NC_DOUBLE, NDIMS, &dimid, &dvarid)) ERR;

    fvals[0] = fninf;
    fvals[1] = fnan;
    fvals[2] = fpinf;
    dvals[0] = dninf;
    dvals[1] = dnan;
    dvals[2] = dpinf;
    
    /* Create float and double attributes */
    if (nc_put_att_float(ncid, fvarid, FV_NAME, NC_FLOAT, FV_NVALS, &fnan)) ERR;
    if (nc_put_att_float(ncid, fvarid, ATT_NAME, NC_FLOAT, NVALS, fvals)) ERR;
    if (nc_put_att_double(ncid, dvarid, FV_NAME, NC_DOUBLE, FV_NVALS, &dnan)) ERR;
    if (nc_put_att_double(ncid, dvarid, ATT_NAME, NC_DOUBLE, NVALS, dvals)) ERR;
    
    if (nc_enddef(ncid)) ERR;
   
    /* Write float and double data */
   if (nc_put_var_float(ncid, fvarid, fvals)) ERR;
   if (nc_put_var_double(ncid, dvarid, dvals)) ERR;
   
   if (nc_close(ncid)) ERR;
   
   /* Check it out. */
   
   /* Reopen the file. */
   if (nc_open(FILE8_NAME, NC_NOWRITE, &ncid)) ERR;
   if (nc_inq_varid(ncid, F_NAME, &fvarid)) ERR;
   if (nc_inq_varid(ncid, D_NAME, &dvarid)) ERR;
   /* Check the values of the float attributes */
   if (nc_inq_att(ncid, fvarid, FV_NAME, &att_type, &att_len)) ERR;
   if (att_type != NC_FLOAT || att_len != FV_NVALS) ERR;
   if (nc_get_att_float(ncid, fvarid, FV_NAME, att_fvals)) ERR;
   if (!isnan(att_fvals[0])) ERR;
   if (nc_get_att_float(ncid, fvarid, ATT_NAME, att_fvals)) ERR;
   if (!(isinf(att_fvals[0]) && att_fvals[0] < 0)) ERR;
   if (!isnan(att_fvals[1])) ERR;
   if (!(isinf(att_fvals[2]) && att_fvals[2] > 0)) ERR;
   /* Check the values of double attributes */
   if (nc_inq_att(ncid, dvarid, FV_NAME, &att_type, &att_len)) ERR;
   if (att_type != NC_DOUBLE || att_len != FV_NVALS) ERR;
   if (nc_get_att_double(ncid, dvarid, FV_NAME, att_dvals)) ERR;
   if (!isnan(att_dvals[0])) ERR;
   if (nc_get_att_double(ncid, dvarid, ATT_NAME, att_dvals)) ERR;
   if (!(isinf(att_dvals[0]) && att_dvals[0] < 0)) ERR;
   if (!isnan(att_dvals[1])) ERR;
   if (!(isinf(att_dvals[2]) && att_dvals[2] > 0)) ERR;
   /* Check values of float data */
   if (nc_get_var_float(ncid, fvarid, fvals_in)) ERR;
   if (!(isinf(fvals_in[0]) && fvals_in[0] < 0)) ERR;
   if (!isnan(fvals_in[1])) ERR;
   if (!(isinf(fvals_in[2]) && fvals_in[2] > 0)) ERR;
   /* Check values of double data */
   if (nc_get_var_double(ncid, dvarid, dvals_in)) ERR;
   if (!(isinf(dvals_in[0]) && dvals_in[0] < 0)) ERR;
   if (!isnan(dvals_in[1])) ERR;
   if (!(isinf(dvals_in[2]) && dvals_in[2] > 0)) ERR;

   if (nc_close(ncid)) ERR;
   
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #11
0
ファイル: tst_pnetcdf.c プロジェクト: brandontheis/netcdf-1
int main(int argc, char* argv[])
{
    int i, j, rank, nprocs, ncid, cmode, varid[NVARS], dimid[2], *buf;
    int err = 0;
    char str[32];
    size_t start[2], count[2];
    MPI_Comm comm=MPI_COMM_SELF;
    MPI_Info info=MPI_INFO_NULL;

    printf("\n*** Testing bug fix with changing pnetcdf variable offsets...");

    MPI_Init(&argc,&argv);
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    if (nprocs > 1 && rank == 0)
        printf("This test program is intended to run on ONE process\n");
    if (rank > 0) goto fn_exit;

    /* first, use PnetCDF to create a file with default header/variable alignment */
#ifdef DISABLE_PNETCDF_ALIGNMENT
    MPI_Info_create(&info);
    MPI_Info_set(info, "nc_header_align_size", "1");
    MPI_Info_set(info, "nc_var_align_size",    "1");
#endif

    cmode = NC_PNETCDF | NC_CLOBBER;
    if (nc_create_par(FILENAME, cmode, comm, info, &ncid)) ERR_RET;

    /* define dimension */
    if (nc_def_dim(ncid, "Y", NC_UNLIMITED, &dimid[0])) ERR;
    if (nc_def_dim(ncid, "X", NX,           &dimid[1])) ERR;

    /* Odd numbers are fixed variables, even numbers are record variables */
    for (i=0; i<NVARS; i++) {
        if (i%2) {
            sprintf(str,"fixed_var_%d",i);
            if (nc_def_var(ncid, str, NC_INT, 1, dimid+1, &varid[i])) ERR;
        }
        else {
            sprintf(str,"record_var_%d",i);
            if (nc_def_var(ncid, str, NC_INT, 2, dimid, &varid[i])) ERR;
        }
    }
    if (nc_enddef(ncid)) ERR;

    for (i=0; i<NVARS; i++) {
        /* Note NC_INDEPENDENT is the default */
        if (nc_var_par_access(ncid, varid[i], NC_INDEPENDENT)) ERR;
    }

    /* write all variables */
    buf = (int*) malloc(NX * sizeof(int));
    for (i=0; i<NVARS; i++) {
        for (j=0; j<NX; j++) buf[j] = i*10 + j;
        if (i%2) {
            start[0] = 0; count[0] = NX;
            if (nc_put_vara_int(ncid, varid[i], start, count, buf)) ERR;
        }
        else {
            start[0] = 0; start[1] = 0;
            count[0] = 1; count[1] = NX;
            if (nc_put_vara_int(ncid, varid[i], start, count, buf)) ERR;
        }
    }
    if (nc_close(ncid)) ERR;
    if (info != MPI_INFO_NULL) MPI_Info_free(&info);

    /* re-open the file with netCDF (parallel) and enter define mode */
    if (nc_open_par(FILENAME, NC_WRITE|NC_PNETCDF, comm, info, &ncid)) ERR_RET;
    if (nc_redef(ncid)) ERR;

    /* add attributes to make header grow */
    for (i=0; i<NVARS; i++) {
        sprintf(str, "annotation_for_var_%d",i);
        if (nc_put_att_text(ncid, varid[i], "text_attr", strlen(str), str)) ERR;
    }
    if (nc_enddef(ncid)) ERR;

    /* read variables and check their contents */
    for (i=0; i<NVARS; i++) {
        for (j=0; j<NX; j++) buf[j] = -1;
        if (i%2) {
            start[0] = 0; count[0] = NX;
            if (nc_get_var_int(ncid, varid[i], buf)) ERR;
            for (j=0; j<NX; j++)
                if (buf[j] != i*10 + j)
                    printf("unexpected read value var i=%d buf[j=%d]=%d should be %d\n",i,j,buf[j],i*10+j);
        }
        else {
            start[0] = 0; start[1] = 0;
            count[0] = 1; count[1] = NX;
            if (nc_get_vara_int(ncid, varid[i], start, count, buf)) ERR;
            for (j=0; j<NX; j++)
                if (buf[j] != i*10+j)
                    printf("unexpected read value var i=%d buf[j=%d]=%d should be %d\n",i,j,buf[j],i*10+j);
        }
    }
    if (nc_close(ncid)) ERR;

fn_exit:
    MPI_Finalize();
    SUMMARIZE_ERR;
    FINAL_RESULTS;
    return 0;
}
コード例 #12
0
ファイル: ephemeris.c プロジェクト: arnaud85/DataProcessing
//FUNCTION : createNc
int createNc(char* ncfile, SpiceDouble n_iter, SpiceDouble t[], SpiceDouble *pos_hci[3], SpiceDouble *pos_iau_sun[3], SpiceDouble *pos_hee[3], SpiceDouble lon_hci[], SpiceDouble lat_hci[], SpiceDouble lon_iau_sun[], SpiceDouble lat_iau_sun[], SpiceDouble dist[])
{
	
	/**************** LOCAL VARIABLES ***********************/
	//NC file ID
	int ncid;

	//Dimensions IDs
	int time_dimid;
	int timelength_dimid;
	int dataId;
	int time_tab_dimid[2];
	int data_tab_dimid[2];

	////Variables IDs
	int time_varid;
	int position1_varid;
	int position2_varid;
	int position3_varid;
	int longitude_hci_varid;
	int latitude_hci_varid;
	int longitude_iau_varid;
	int latitude_iau_varid;
	int distance_varid;
	int startTime_varid;
	int stopTime_varid;

	//Stocking time reference
	time_t p;
	char *s;

	//Buffers
	size_t start[2];
	size_t timeCount[2];
	size_t dataCount[2];

	//Dates
    dd_time_t *DDdates = NULL;

	//Other
	int step;
	int retval;
	size_t i;
	size_t j;


	/**************** END OF LOCAL VARIABLES ***********************/


	/**************** OPEN NC FILE ***********************/
	//Create nc file (NC_CLOBBER to overwrite)
	retval = nc_create(ncfile, NC_CLOBBER, &ncid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Create nc file");
	} 
	/**************** END OF OPEN NC FILE ***********************/



	/*************************** DEFINE MODE ****************************/

	//Define dimensions
	retval = nc_def_dim(ncid, TIME_DIM, NC_UNLIMITED, &time_dimid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Time dimension definition");
	} 
	retval = nc_def_dim(ncid, TIMELEN_DIM, TIME_STR_LEN, &timelength_dimid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "TimeLength dimension definition");
	} 
	retval = nc_def_dim(ncid, POS_DIM, 3L, &dataId);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Position dimension definition");
	} 
	

	//Define the netCDF variables
	time_tab_dimid[0] = time_dimid;
	time_tab_dimid[1] = timelength_dimid;
  	data_tab_dimid[0] = time_dimid;
  	data_tab_dimid[1] = dataId;

  	retval = nc_def_var(ncid, TIME_VAR, NC_CHAR, 2, time_tab_dimid, &time_varid);
  	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Time variable");
	}
	retval = nc_def_var(ncid, POS_VAR_HCI, NC_DOUBLE, 2, data_tab_dimid, &position1_varid);
  	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "HCI Position variable");
	} 
	retval = nc_def_var(ncid, POS_VAR_IAU, NC_DOUBLE, 2, data_tab_dimid, &position2_varid);
  	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "IAU_SUN Position variable");
	}
	retval = nc_def_var(ncid, POS_VAR_HEE, NC_DOUBLE, 2, data_tab_dimid, &position3_varid);
  	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "HEE Position variable");
	}
	retval = nc_def_var(ncid, LON_VAR_HCI, NC_DOUBLE, 1, &time_dimid, &longitude_hci_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "LON HCI variable");
	}
	retval = nc_def_var(ncid, LAT_VAR_HCI, NC_DOUBLE, 1, &time_dimid, &latitude_hci_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "LAT HCI variable");
	} 
	retval = nc_def_var(ncid, LON_VAR_IAU_SUN, NC_DOUBLE, 1, &time_dimid, &longitude_iau_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "LON IAU_SUN variable");
	}
	retval = nc_def_var(ncid, LAT_VAR_IAU_SUN, NC_DOUBLE, 1, &time_dimid, &latitude_iau_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "LAT IAU_SUN variable");
	}
	retval = nc_def_var(ncid, DIST_VAR, NC_DOUBLE, 1, &time_dimid, &distance_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Distance variable");
	}
	retval = nc_def_var(ncid, START_VAR, NC_CHAR, 1, &timelength_dimid, &startTime_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "StartTime variable");
	}
	retval = nc_def_var(ncid, STOP_VAR, NC_CHAR, 1, &timelength_dimid, &stopTime_varid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "StopTime variable");
	}

	//Units attributes for netCDF variables
	retval = nc_put_att_text(ncid, position1_varid, "units", strlen(POS_UNIT), POS_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Position unit");
	}
	retval = nc_put_att_text(ncid, position2_varid, "units", strlen(POS_UNIT), POS_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Position unit");
	}
	retval = nc_put_att_text(ncid, position3_varid, "units", strlen(POS_UNIT), POS_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Position unit");
	}
	retval = nc_put_att_text(ncid, distance_varid, "units", strlen(DIST_UNIT), DIST_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Distance unit");
	}
	retval = nc_put_att_text(ncid, longitude_hci_varid, "units", strlen(LON_UNIT), LON_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Longitude unit");
	}
	retval = nc_put_att_text(ncid, latitude_hci_varid, "units", strlen(LAT_UNIT), LAT_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Latitude unit");
	}
	retval = nc_put_att_text(ncid, longitude_iau_varid, "units", strlen(LON_UNIT), LON_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Longitude unit");
	}
	retval = nc_put_att_text(ncid, latitude_iau_varid, "units", strlen(LAT_UNIT), LAT_UNIT);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Latitude unit");
	}
	retval = nc_put_att_text(ncid, NC_GLOBAL, "Source", strlen(SOURCE), SOURCE);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Source");
	}

	time(&p);
	s = ctime(&p);
	retval = nc_put_att_text(ncid, NC_GLOBAL, "Created", 24, s);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Created argument");
	}
	

	//End of define mode
	retval = nc_enddef(ncid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "End define mode");
	}

	/*********************** END OF DEFINE MODE ****************************/





	/************************ WRITING MODE ********************************/
  	//Configure buffers
	timeCount[0] = 1L;
	timeCount[1] = TIME_STR_LEN;
	dataCount[0] = 1;
	dataCount[1] = 3L;
	start[1] = 0L;

	//Build DDdate
	DDdates = (dd_time_t*)malloc((int)n_iter*sizeof(dd_time_t));
	if(DDdates == NULL)
	{
		printf("[ERROR] Unable to build DD dates\n");

		exit(EXIT_FAILURE);
	}
	
	for (i = 0; i < n_iter; i++)
	{
		time2DDtime(t[i], &DDdates[i]);
	}

	//Write datas
    for (i = 0; i < n_iter; i++)
    {
    	start[0] = i;
	    retval = nc_put_vara_text(ncid, time_varid, start, timeCount, DDdates[i]);
		if (retval != NC_NOERR)
		{
			nc_handle_error(retval, "Write time variable");
		}
    }

	for (i = 0; i < n_iter; i++)
	{
		start[0] = i;
		retval = nc_put_vara_double(ncid, position1_varid, start, dataCount, pos_hci[i]);
	 	if (retval != NC_NOERR)
		{
			nc_handle_error(retval, "Write HCI position variable");
		}
	}

	for (i = 0; i < n_iter; i++)
	{
		start[0] = i;
		retval = nc_put_vara_double(ncid, position2_varid, start, dataCount, pos_iau_sun[i]);
	 	if (retval != NC_NOERR)
		{
			nc_handle_error(retval, "Write IAU_SUN position variable");
		}
	}

	for (i = 0; i < n_iter; i++)
	{
		start[0] = i;
		retval = nc_put_vara_double(ncid, position3_varid, start, dataCount, pos_hee[i]);
	 	if (retval != NC_NOERR)
		{
			nc_handle_error(retval, "Write HEE position variable");
		}
	}

	retval = nc_put_var_double(ncid, longitude_hci_varid, lon_hci);
 	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write LON HCI variable");
	}

	retval = nc_put_var_double(ncid, latitude_hci_varid, lat_hci);
 	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write LAT HCI variable");
	}

	retval = nc_put_var_double(ncid, longitude_iau_varid, lon_iau_sun);
 	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write LON IAU_SUN variable");
	}

	retval = nc_put_var_double(ncid, latitude_iau_varid, lat_iau_sun);
 	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write LAT IAU_SUN variable");
	}

	retval = nc_put_var_double(ncid, distance_varid, dist);
 	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write distance variable");
	}

	retval = nc_put_var_text(ncid, startTime_varid, DDdates[0]);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write start time variable");
	}

	retval = nc_put_var_text(ncid, stopTime_varid, DDdates[(int)n_iter-1]);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Write stop time variable");
	}

	//Free memory
	free(DDdates);

	/************************ END OF WRITING MODE ********************************/



	/**************** CLOSE NC FILE ***********************/
	//Close the file
	retval = nc_close(ncid);
	if (retval != NC_NOERR)
	{
		nc_handle_error(retval, "Close nc file");
	}

	printf("[INFO] %s has been created\n", ncfile);
	/**************** END OF CLOSE NC FILE ***********************/

	return 0;
}
コード例 #13
0
int
main()
{
   /* IDs for the netCDF file, dimensions, and variables. */
   int ncid, lon_dimid, lat_dimid, lvl_dimid, rec_dimid;
   int lat_varid, lon_varid, pres_varid, temp_varid;
   int dimids[NDIMS];

   /* The start and count arrays will tell the netCDF library where to
      write our data. */
   size_t start[NDIMS], count[NDIMS];

   /* Program variables to hold the data we will write out. We will only
      need enough space to hold one timestep of data; one record. */
   float pres_out[NLVL][NLAT][NLON];
   float temp_out[NLVL][NLAT][NLON];

   /* These program variables hold the latitudes and longitudes. */
   float lats[NLAT], lons[NLON];

   /* Loop indexes. */
   int lvl, lat, lon, rec, i = 0;
   
   /* Error handling. */
   int retval;

   /* Create some pretend data. If this wasn't an example program, we
    * would have some real data to write, for example, model
    * output. */
   for (lat = 0; lat < NLAT; lat++)
      lats[lat] = START_LAT + 5.*lat;
   for (lon = 0; lon < NLON; lon++)
      lons[lon] = START_LON + 5.*lon;
   
   for (lvl = 0; lvl < NLVL; lvl++)
      for (lat = 0; lat < NLAT; lat++)
	 for (lon = 0; lon < NLON; lon++)
	 {
	    pres_out[lvl][lat][lon] = SAMPLE_PRESSURE + i;
	    temp_out[lvl][lat][lon] = SAMPLE_TEMP + i++;
	 }

   /* Create the file. */
   if ((retval = nc_create(FILE_NAME, NC_CLOBBER, &ncid)))
      ERR(retval);

   /* Define the dimensions. The record dimension is defined to have
    * unlimited length - it can grow as needed. In this example it is
    * the time dimension.*/
   if ((retval = nc_def_dim(ncid, LVL_NAME, NLVL, &lvl_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, LAT_NAME, NLAT, &lat_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, LON_NAME, NLON, &lon_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, REC_NAME, NC_UNLIMITED, &rec_dimid)))
      ERR(retval);

   /* Define the coordinate variables. We will only define coordinate
      variables for lat and lon.  Ordinarily we would need to provide
      an array of dimension IDs for each variable's dimensions, but
      since coordinate variables only have one dimension, we can
      simply provide the address of that dimension ID (&lat_dimid) and
      similarly for (&lon_dimid). */
   if ((retval = nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, &lat_dimid, 
			    &lat_varid)))
      ERR(retval);
   if ((retval = nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, &lon_dimid, 
			    &lon_varid)))
      ERR(retval);

   /* Assign units attributes to coordinate variables. */
   if ((retval = nc_put_att_text(ncid, lat_varid, UNITS, 
				 strlen(DEGREES_NORTH), DEGREES_NORTH)))
      ERR(retval);
   if ((retval = nc_put_att_text(ncid, lon_varid, UNITS, 
				 strlen(DEGREES_EAST), DEGREES_EAST)))
      ERR(retval);

   /* The dimids array is used to pass the dimids of the dimensions of
      the netCDF variables. Both of the netCDF variables we are
      creating share the same four dimensions. In C, the
      unlimited dimension must come first on the list of dimids. */
   dimids[0] = rec_dimid;
   dimids[1] = lvl_dimid;
   dimids[2] = lat_dimid;
   dimids[3] = lon_dimid;

   /* Define the netCDF variables for the pressure and temperature
    * data. */
   if ((retval = nc_def_var(ncid, PRES_NAME, NC_FLOAT, NDIMS, 
			    dimids, &pres_varid)))
      ERR(retval);
   if ((retval = nc_def_var(ncid, TEMP_NAME, NC_FLOAT, NDIMS, 
			    dimids, &temp_varid)))
      ERR(retval);

   /* Assign units attributes to the netCDF variables. */
   if ((retval = nc_put_att_text(ncid, pres_varid, UNITS, 
				 strlen(PRES_UNITS), PRES_UNITS)))
      ERR(retval);
   if ((retval = nc_put_att_text(ncid, temp_varid, UNITS, 
				 strlen(TEMP_UNITS), TEMP_UNITS)))
      ERR(retval);

   /* End define mode. */
   if ((retval = nc_enddef(ncid)))
      ERR(retval);

   /* Write the coordinate variable data. This will put the latitudes
      and longitudes of our data grid into the netCDF file. */
   if ((retval = nc_put_var_float(ncid, lat_varid, &lats[0])))
      ERR(retval);
   if ((retval = nc_put_var_float(ncid, lon_varid, &lons[0])))
      ERR(retval);

   /* These settings tell netcdf to write one timestep of data. (The
     setting of start[0] inside the loop below tells netCDF which
     timestep to write.) */
   count[0] = 1;
   count[1] = NLVL;
   count[2] = NLAT;
   count[3] = NLON;
   start[1] = 0;
   start[2] = 0;
   start[3] = 0;

   /* Write the pretend data. This will write our surface pressure and
      surface temperature data. The arrays only hold one timestep worth
      of data. We will just rewrite the same data for each timestep. In
      a real application, the data would change between timesteps. */
   for (rec = 0; rec < NREC; rec++)
   {
      start[0] = rec;
      if ((retval = nc_put_vara_float(ncid, pres_varid, start, count, 
				      &pres_out[0][0][0])))
	 ERR(retval);
      if ((retval = nc_put_vara_float(ncid, temp_varid, start, count, 
				      &temp_out[0][0][0])))
	 ERR(retval);
   }

   /* Close the file. */
   if ((retval = nc_close(ncid)))
      ERR(retval);
   
   printf("*** SUCCESS writing example file %s!\n", FILE_NAME);
   return 0;
}
コード例 #14
0
ファイル: ex_create.c プロジェクト: bartlettroscoe/seacas
int ex_create_int(const char *path, int cmode, int *comp_ws, int *io_ws, int run_version)
{
  int   exoid;
  int   status;
  int   dimid;
  int   old_fill;
  int   lio_ws;
  int   filesiz;
  float vers;
  char  errmsg[MAX_ERR_LENGTH];
  char *mode_name;
  int   nc_mode = 0;
#if NC_HAS_HDF5
  static int netcdf4_mode = -1;
  char *     option;
#endif /* NC_NETCDF4 */
  const char * routine = "ex_create";
  int          int64_status;
  unsigned int my_mode = cmode;

  /* Contains a 1 in all bits corresponding to file modes */
  static unsigned int all_modes = EX_NORMAL_MODEL | EX_64BIT_OFFSET | EX_64BIT_DATA | EX_NETCDF4;

  exerrval = 0; /* clear error code */

  if (run_version != EX_API_VERS_NODOT && warning_output == 0) {
    int run_version_major = run_version / 100;
    int run_version_minor = run_version % 100;
    int lib_version_major = EX_API_VERS_NODOT / 100;
    int lib_version_minor = EX_API_VERS_NODOT % 100;
    fprintf(stderr, "EXODUS: Warning: This code was compiled with exodusII "
                    "version %d.%02d,\n          but was linked with exodusII "
                    "library version %d.%02d\n          This is probably an "
                    "error in the build process of this code.\n",
            run_version_major, run_version_minor, lib_version_major, lib_version_minor);
    warning_output = 1;
  }

/*
 * See if specified mode is supported in the version of netcdf we
 * are using
 */
#if !NC_HAS_HDF5
  if (my_mode & EX_NETCDF4) {
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "EXODUS: ERROR: File format specified as netcdf-4, but the "
                                     "NetCDF library being used was not configured to enable "
                                     "this format\n");
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }
#endif

#if !defined(NC_64BIT_DATA)
  if (my_mode & EX_64BIT_DATA) {
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "EXODUS: ERROR: File format specified as 64bit_data, but "
                                     "the NetCDF library being used does not support this "
                                     "format\n");
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }
#endif

  /* Check that one and only one format mode is specified... */
  {
    unsigned int set_modes = all_modes & my_mode;

    if (set_modes == 0) {
      my_mode |= EX_64BIT_OFFSET; /* Default if nothing specified */
    }
    else {
      /* Checks that only a single bit is set */
      set_modes = set_modes && !(set_modes & (set_modes - 1));
      if (!set_modes) {
        exerrval = EX_BADPARAM;
        snprintf(errmsg, MAX_ERR_LENGTH, "EXODUS: ERROR: More than 1 file format "
                                         "(EX_NORMAL_MODEL, EX_LARGE_MODEL, EX_64BIT_OFFSET, "
                                         "EX_64BIT_DATA, or EX_NETCDF4)\nwas specified in the "
                                         "mode argument of the ex_create call. Only a single "
                                         "format can be specified.\n");
        ex_err(routine, errmsg, exerrval);
        return (EX_FATAL);
      }
    }
  }

  /*
   * See if any integer data is to be stored as int64 (long long). If
   * so, then need to set NC_NETCDF4 and unset NC_CLASSIC_MODEL (or
   * set EX_NOCLASSIC.  Output meaningful error message if the library
   * is not NetCDF-4 enabled...
   *
   * As of netcdf-4.4.0, can also use NC_64BIT_DATA (CDF5) mode for this...
   */
  int64_status = my_mode & (EX_ALL_INT64_DB | EX_ALL_INT64_API);

  if ((int64_status & EX_ALL_INT64_DB) != 0) {
#if NC_HAS_HDF5 || defined(NC_64BIT_DATA)
    /* Library DOES support netcdf4 and/or cdf5 ... See if user
     * specified either of these and use that one; if not, pick
     * netcdf4, non-classic as default.
     */
    if (my_mode & EX_NETCDF4) {
      my_mode |= EX_NOCLASSIC;
    }
#if defined(NC_64BIT_DATA)
    else if (my_mode & EX_64BIT_DATA) {
      ; /* Do nothing, already set */
    }
#endif
    else {
      /* Unset the current mode so we don't have multiples specified */
      /* ~all_modes sets to 1 all bits not associated with file format */
      my_mode &= ~all_modes;
#if NC_HAS_HDF5
      /* Pick netcdf4 as default mode for 64-bit integers */
      my_mode |= EX_NOCLASSIC;
      my_mode |= EX_NETCDF4;
#else
      /* Pick 64bit_data as default mode for 64-bit integers */
      my_mode |= EX_64BIT_DATA;
#endif
    }
#else
    /* Library does NOT support netcdf4 or cdf5 */
    exerrval = EX_BADPARAM;
    snprintf(errmsg, MAX_ERR_LENGTH, "EXODUS: ERROR: 64-bit integer storage requested, but the "
                                     "netcdf library does not support the required netcdf-4 or "
                                     "64BIT_DATA extensions.\n");
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
#endif
  }

#if NC_HAS_HDF5
  if (my_mode & EX_NETCDF4) {
    nc_mode |= (NC_NETCDF4);
  }
  else {
    if (netcdf4_mode == -1) {
      option = getenv("EXODUS_NETCDF4");
      if (option != NULL) {
        netcdf4_mode = NC_NETCDF4;
	if (option[0] != 'q') {
	  fprintf(stderr, "EXODUS: Using netcdf version 4 selected via "
		  "EXODUS_NETCDF4 environment variable\n");
	}
      }
      else {
        netcdf4_mode = 0;
      }
    }
    nc_mode |= netcdf4_mode;
  }
  if (!(my_mode & EX_NOCLASSIC)) {
    nc_mode |= NC_CLASSIC_MODEL;
  }
#endif

#if defined(NC_64BIT_DATA)
  if (my_mode & EX_64BIT_DATA) {
    nc_mode |= (NC_64BIT_DATA);
  }
  if (!(my_mode & EX_NOCLASSIC)) {
    nc_mode |= NC_CLASSIC_MODEL;
  }
#endif

  /*
   * See if "large file" mode was specified in a ex_create my_mode. If
   * so, then pass the NC_64BIT_OFFSET flag down to netcdf.
   * If netcdf4 mode specified, don't use NC_64BIT_OFFSET mode.
   */
  if (my_mode & EX_NORMAL_MODEL) {
    filesiz = 0;
#if NC_HAS_HDF5
  }
  else if (nc_mode & NC_NETCDF4) {
    filesiz = 1;
#endif
#if defined(NC_64BIT_DATA)
  }
  else if (nc_mode & NC_64BIT_DATA) {
    filesiz = 1;
#endif
  }
  else {
    filesiz = (int)((my_mode & EX_64BIT_OFFSET) || (ex_large_model(-1) == 1));
  }

  if (
#if NC_HAS_HDF5
      !(nc_mode & NC_NETCDF4) &&
#endif
#if defined(NC_64BIT_DATA)
      !(nc_mode & NC_64BIT_DATA) &&
#endif
      filesiz == 1) {
    nc_mode |= NC_64BIT_OFFSET;
  }

  if (my_mode & EX_SHARE) {
    nc_mode |= NC_SHARE;
  }

  /*
   * set error handling mode to no messages, non-fatal errors
   */
  ex_opts(exoptval); /* call required to set ncopts first time through */

  if (my_mode & EX_CLOBBER) {
    nc_mode |= NC_CLOBBER;
    mode_name = "CLOBBER";
  }
  else {
    nc_mode |= NC_NOCLOBBER;
    mode_name = "NOCLOBBER";
  }

#if defined NC_IGNORE_MAX_DIMS
  nc_mode |= NC_IGNORE_MAX_DIMS;
#endif

#if defined NC_IGNORE_MAX_VARS
  nc_mode |= NC_IGNORE_MAX_VARS;
#endif

#if NC_HAS_DISKLESS
  if (my_mode & EX_DISKLESS) {
    nc_mode |= NC_DISKLESS;
  }
#endif

  if ((status = nc_create(path, nc_mode, &exoid)) != NC_NOERR) {
    exerrval = status;
#if NC_HAS_HDF5
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: file create failed for %s, mode: %s", path, mode_name);
#else
    if (my_mode & EX_NETCDF4) {
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: file create failed for %s in NETCDF4 and %s "
                                       "mode.\n\tThis library does not support netcdf-4 files.",
               path, mode_name);
    }
    else {
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: file create failed for %s, mode: %s", path,
               mode_name);
    }
#endif
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* turn off automatic filling of netCDF variables */

  if ((status = nc_set_fill(exoid, NC_NOFILL, &old_fill)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to set nofill mode in file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* Verify that there is not an existing file_item struct for this
     exoid This could happen (and has) when application calls
     ex_open(), but then closes file using nc_close() and then reopens
     file.  NetCDF will possibly reuse the exoid which results in
     internal corruption in exodus data structures since exodus does
     not know that file was closed and possibly new file opened for
     this exoid
  */
  if (ex_find_file_item(exoid) != NULL) {
    exerrval = EX_BADFILEID;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: There is an existing file already using the file "
                                     "id %d which was also assigned to file %s.\n\tWas "
                                     "nc_close() called instead of ex_close() on an open Exodus "
                                     "file?\n",
             exoid, path);
    ex_err(routine, errmsg, exerrval);
    nc_close(exoid);
    return (EX_FATAL);
  }

  /* initialize floating point size conversion.  since creating new file,
   * i/o wordsize attribute from file is zero.
   */
  if (ex_conv_ini(exoid, comp_ws, io_ws, 0, int64_status, 0, 0, 0) != EX_NOERR) {
    exerrval = EX_FATAL;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to init conversion routines in file id %d",
             exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* put the EXODUS version number, and i/o floating point word size as
   * netcdf global attributes
   */

  /* store Exodus API version # as an attribute */
  vers = EX_API_VERS;
  if ((status = nc_put_att_float(exoid, NC_GLOBAL, ATT_API_VERSION, NC_FLOAT, 1, &vers)) !=
      NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to store Exodus II API version attribute in file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* store Exodus file version # as an attribute */
  vers = EX_VERS;
  if ((status = nc_put_att_float(exoid, NC_GLOBAL, ATT_VERSION, NC_FLOAT, 1, &vers)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to store Exodus II file version attribute in file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* store Exodus file float word size  as an attribute */
  lio_ws = (int)(*io_ws);
  if ((status = nc_put_att_int(exoid, NC_GLOBAL, ATT_FLT_WORDSIZE, NC_INT, 1, &lio_ws)) !=
      NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to store Exodus II file float word size "
                                     "attribute in file id %d",
             exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* store Exodus file size (1=large, 0=normal) as an attribute */
  if ((status = nc_put_att_int(exoid, NC_GLOBAL, ATT_FILESIZE, NC_INT, 1, &filesiz)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to store Exodus II file size attribute in file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  {
    int max_so_far = 32;
    if ((status = nc_put_att_int(exoid, NC_GLOBAL, ATT_MAX_NAME_LENGTH, NC_INT, 1, &max_so_far)) !=
        NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH,
               "ERROR: failed to add maximum_name_length attribute in file id %d", exoid);
      ex_err(routine, errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  /* define some dimensions and variables */

  /* create string length dimension */
  if ((status = nc_def_dim(exoid, DIM_STR, (MAX_STR_LENGTH + 1), &dimid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define string length in file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* The name string length dimension is delayed until the ex_put_init function
   */

  /* create line length dimension */
  if ((status = nc_def_dim(exoid, DIM_LIN, (MAX_LINE_LENGTH + 1), &dimid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define line length in file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  /* create number "4" dimension; must be of type long */
  if ((status = nc_def_dim(exoid, DIM_N4, 4L, &dimid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to define number \"4\" dimension in file id %d",
             exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  {
    int int64_db_status = int64_status & EX_ALL_INT64_DB;
    if ((status = nc_put_att_int(exoid, NC_GLOBAL, ATT_INT64_STATUS, NC_INT, 1,
                                 &int64_db_status)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to add int64_status attribute in file id %d",
               exoid);
      ex_err(routine, errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  if ((status = nc_enddef(exoid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to complete definition for file id %d", exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  return (exoid);
}
コード例 #15
0
//=========================================================================
//
// WriteNetCDF(DICE *dice, BORG_Archive result, string ncfile)
//
// Writes the full model output for a set of solutions and (if applicable)
// climate sentitivities.
//
//=========================================================================
void WriteNetCDF(DICE *dice, BORG_Archive result, const char *ncfile)
{
  // Loop control variables
  int iInd, jInd, tInd;
  
  // Was doeclim used?
  int use_doeclim = dice->ctrl.use_doeclim;  
  
  // Define the dimensions for the vectors
  int nPeriods = dice->config.nPeriods;
  int nSamples = dice->ctrl.csSamples;
  int nDoeclimts = dice->clim.ns;
  int nSolutions = BORG_Archive_get_size(result);
  
  int ndims = 3;

  // Dimension ids
  int nPeriodsid, nSamplesid, nSolutionsid, nDoeclimtsid;
  int fulldimids[ndims];
  int extfulldimids[ndims];
  int per_sol_dimids[2];
  int sol_sam_dimids[2];
  int sam_dimids[1];
  int per_dimids[1];
  
  // netcdf file id
  int ncid;
  
  // Variable ids
  int tatmid, matid, miuid, sid, utilityid, csid, oceandiffid, alphaid;
  int yearid, forcid, toceanid, muid, mlid, ccaid, kid, cid;
  int cpcid, iid, riid, yid, ygrossid, ynetid, damagesid, damfracid;
  int abatecostid, perioduid, sccid, lid, gaid, alid, gsigid;
  int sigmaid, cost1id, etreeid, eindid, rrid, forcothid, partfractid;
  int pv_abatecostid, pv_damagesid, totalcostid, pv_totalcostid;
  int pbacktimeid, eid, mcabateid, cemutotperid;
  
  int tempid, doeclim_forcid, heat_mixedid;
  
  // Initialize the variable vectors
  float tatm[nPeriods][nSolutions][nSamples]; 
  float mat[nPeriods][nSolutions][nSamples];
  float forc[nPeriods][nSolutions][nSamples];  
  float tocean[nPeriods][nSolutions][nSamples]; 
  float mu[nPeriods][nSolutions][nSamples];
  float ml[nPeriods][nSolutions][nSamples];
  float cca[nPeriods][nSolutions][nSamples];
  float k[nPeriods][nSolutions][nSamples];
  float c[nPeriods][nSolutions][nSamples];
	float cpc[nPeriods][nSolutions][nSamples];
  float i[nPeriods][nSolutions][nSamples];
  float ri[nPeriods][nSolutions][nSamples];
  float y[nPeriods][nSolutions][nSamples];
  float ygross[nPeriods][nSolutions][nSamples];
	float ynet[nPeriods][nSolutions][nSamples];
  float damages[nPeriods][nSolutions][nSamples];
  float damfrac[nPeriods][nSolutions][nSamples];
  float abatecost[nPeriods][nSolutions][nSamples];
  float periodu[nPeriods][nSolutions][nSamples];
  float scc[nPeriods][nSolutions][nSamples];
  float eind[nPeriods][nSolutions][nSamples];
  float pv_abatecost[nPeriods][nSolutions][nSamples];
  float pv_damages[nPeriods][nSolutions][nSamples];
  float totalcost[nPeriods][nSolutions][nSamples];
  float pv_totalcost[nPeriods][nSolutions][nSamples];
  float pbacktime[nPeriods][nSolutions][nSamples];
  float e[nPeriods][nSolutions][nSamples];
  float mcabate[nPeriods][nSolutions][nSamples]; 
  float cemutotper[nPeriods][nSolutions][nSamples];
  
  float temp[nDoeclimts][nSolutions][nSamples];
	float doeclim_forc[nDoeclimts][nSolutions][nSamples];
  float heat_mixed[nDoeclimts][nSolutions][nSamples];

  float miu[nPeriods][nSolutions];
	float utility[nSolutions][nSamples];
     
  float cs[nSamples];
  float oceandiff[nSamples];
  float alpha[nSamples];

  short year[nPeriods];
  float l[nPeriods];
  float ga[nPeriods];
  float al[nPeriods];
  float gsig[nPeriods];
  float sigma[nPeriods];
  float cost1[nPeriods];
  float etree[nPeriods];
  float rr[nPeriods];
  float forcoth[nPeriods];
  float partfract[nPeriods];
  
  // If the savings rate is set from the control file,
  // we will only need to provide a single dimension
  // for the savings rate output
  float s1[nPeriods];				// Savings rate if set in control file
  float s2[nPeriods][nSolutions];	// Savings rate if used as decision variable
  
  // Setup the netcdf file
  int retval;
  if((retval = nc_create(ncfile, NC_64BIT_OFFSET, &ncid))) { ncError(retval); }
  
  // Define the dimensions in the netcdf file
  if((retval = nc_def_dim(ncid, "nPeriods", nPeriods, &nPeriodsid))) { ncError(retval); }
  if((retval = nc_def_dim(ncid, "nSolutions", nSolutions, &nSolutionsid))) { ncError(retval); }
  if((retval = nc_def_dim(ncid, "nSamples", nSamples, &nSamplesid))) { ncError(retval); }
  
  if(use_doeclim == 1) {
    if((retval = nc_def_dim(ncid, "nDoeclimts", nDoeclimts, &nDoeclimtsid))) { ncError(retval); }
  }

  // Gather the dimension IDs into a vector
  fulldimids[0] = nPeriodsid;
  fulldimids[1] = nSolutionsid;
  fulldimids[2] = nSamplesid;
  
  extfulldimids[0] = nDoeclimtsid;
  extfulldimids[1] = nSolutionsid;
  extfulldimids[2] = nSamplesid;
  
  per_sol_dimids[0] = nPeriodsid;
  per_sol_dimids[1] = nSolutionsid;
  
  sol_sam_dimids[0] = nSolutionsid;
  sol_sam_dimids[1] = nSamplesid;
  
  sam_dimids[0] = nSamplesid;
  
  per_dimids[0] = nPeriodsid;
  
  // Create the netcdf variables
  if((retval = nc_def_var(ncid, "mat", NC_FLOAT, 3, fulldimids, &matid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "forc", NC_FLOAT, 3, fulldimids, &forcid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "mu", NC_FLOAT, 3, fulldimids, &muid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "ml", NC_FLOAT, 3, fulldimids, &mlid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "cca", NC_FLOAT, 3, fulldimids, &ccaid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "k", NC_FLOAT, 3, fulldimids, &kid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "c", NC_FLOAT, 3, fulldimids, &cid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "cpc", NC_FLOAT, 3, fulldimids, &cpcid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "i", NC_FLOAT, 3, fulldimids, &iid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "ri", NC_FLOAT, 3, fulldimids, &riid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "y", NC_FLOAT, 3, fulldimids, &yid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "ygross", NC_FLOAT, 3, fulldimids, &ygrossid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "ynet", NC_FLOAT, 3, fulldimids, &ynetid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "damages", NC_FLOAT, 3, fulldimids, &damagesid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "damfrac", NC_FLOAT, 3, fulldimids, &damfracid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "abatecost", NC_FLOAT, 3, fulldimids, &abatecostid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "periodu", NC_FLOAT, 3, fulldimids, &perioduid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "eind", NC_FLOAT, 3, fulldimids, &eindid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "pv_abatecost", NC_FLOAT, 3, fulldimids, &pv_abatecostid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "pv_damages", NC_FLOAT, 3, fulldimids, &pv_damagesid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "totalcost", NC_FLOAT, 3, fulldimids, &totalcostid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "pv_totalcost", NC_FLOAT, 3, fulldimids, &pv_totalcostid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "e", NC_FLOAT, 3, fulldimids, &eid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "mcabate", NC_FLOAT, 3, fulldimids, &mcabateid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "cemutotper", NC_FLOAT, 3, fulldimids, &cemutotperid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "scc", NC_FLOAT, 3, fulldimids, &sccid))) { ncError(retval); }

  if(use_doeclim == 1) {
    if((retval = nc_def_var(ncid, "temp", NC_FLOAT, 3, extfulldimids, &tempid))) { ncError(retval); }
    if((retval = nc_def_var(ncid, "doeclim_forc", NC_FLOAT, 3, extfulldimids, &doeclim_forcid))) { ncError(retval); }
    if((retval = nc_def_var(ncid, "heat_mixed", NC_FLOAT, 3, extfulldimids, &heat_mixedid))) { ncError(retval); }
  }
  else {
    if((retval = nc_def_var(ncid, "tatm", NC_FLOAT, 3, fulldimids, &tatmid))) { ncError(retval); }
    if((retval = nc_def_var(ncid, "tocean", NC_FLOAT, 3, fulldimids, &toceanid))) { ncError(retval); }
  }
  
  
  if((retval = nc_def_var(ncid, "miu", NC_FLOAT, 2, per_sol_dimids, &miuid))) { ncError(retval); }
  
  if((retval = nc_def_var(ncid, "utility", NC_FLOAT, 2, sol_sam_dimids, &utilityid))) { ncError(retval); }
  
  if((retval = nc_def_var(ncid, "cs", NC_FLOAT, 1, sam_dimids, &csid))) { ncError(retval); }  
  if(use_doeclim == 1) {
  	if((retval = nc_def_var(ncid, "oceandiff", NC_FLOAT, 1, sam_dimids, &oceandiffid))) { ncError(retval); }
  	if((retval = nc_def_var(ncid, "alpha", NC_FLOAT, 1, sam_dimids, &alphaid))) { ncError(retval); }
  }
  
  if((retval = nc_def_var(ncid, "Year", NC_SHORT, 1, per_dimids, &yearid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "l", NC_FLOAT, 1, per_dimids, &lid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "ga", NC_FLOAT, 1, per_dimids, &gaid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "al", NC_FLOAT, 1, per_dimids, &alid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "gsig", NC_FLOAT, 1, per_dimids, &gsigid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "sigma", NC_FLOAT, 1, per_dimids, &sigmaid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "cost1", NC_FLOAT, 1, per_dimids, &cost1id))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "etree", NC_FLOAT, 1, per_dimids, &etreeid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "rr", NC_FLOAT, 1, per_dimids, &rrid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "forcoth", NC_FLOAT, 1, per_dimids, &forcothid))) { ncError(retval); }
  if((retval = nc_def_var(ncid, "partfract", NC_FLOAT, 1, per_dimids, &partfractid))) { ncError(retval); }
  
  // If the savings rate is set in the control file,
  // the savings rate will only need one dimension
  if (dice->ctrl.setSavings < 0) {
    if((retval = nc_def_var(ncid, "s", NC_FLOAT, 2, per_sol_dimids, &sid))) { ncError(retval); }
  }
  else {
    if((retval = nc_def_var(ncid, "s", NC_FLOAT, 1, per_dimids, &sid))) { ncError(retval); }
  }
  
  // End "Metadata" mode
  if((retval = nc_enddef(ncid))) { ncError(retval); }
  
  // Populate the variable vectors with the appropriate data
  // First, loop over the BORG solutions
  for(iInd=0; iInd<nSolutions; iInd++) {

    // Get this BORG solution
    BORG_Solution this_solution = BORG_Archive_get(result, iInd);
    
    // Apply the decision vector to the dice object
    for(tInd=0; tInd<dice->ctrl.nvars; tInd++) {
      if(tInd < 59) {
      	if(dice->ctrl.policy_inertia <= 0.0) {
					dice->dvars.miu[tInd+1] = BORG_Solution_get_variable(this_solution, tInd);
				}
				else {
					dice->dvars.miu[tInd+1] = dice->dvars.miu[tInd] + (BORG_Solution_get_variable(this_solution, tInd) * dice->ctrl.policy_inertia);
				}
      }
      else {
	dice->dvars.s[tInd-59] = BORG_Solution_get_variable(this_solution, tInd);
      }
    }
    
    // Store the decision variables from this solution
    for(tInd=0; tInd<nPeriods; tInd++) {
      miu[tInd][iInd] = (float) dice->dvars.miu[tInd];
      if (dice->ctrl.setSavings < 0) {
	s2[tInd][iInd] = (float) dice->dvars.s[tInd];
      }
    }			
    
    // Loop over the climate sensitivity samples
    for(jInd=0; jInd<nSamples; jInd++) {
      
      // If this is the first BORG solution, put
      // the climate sensitivity in its vector
      if(iInd==0) {
				cs[jInd] = (float) dice->clim.cs_sample_vec[jInd];
				if(use_doeclim == 1) {
					oceandiff[jInd] = (float) dice->clim.ocean_diff_vec[jInd];
					alpha[jInd] = (float) dice->clim.alpha_vec[jInd];
				}
      }
      
      // Apply this climate sensitivity to the dice object
      if(use_doeclim == 1) {
	dice->clim.t2co = dice->clim.cs_sample_vec[jInd];
	dice->clim.kappa = dice->clim.ocean_diff_vec[jInd];
	dice->clim.alpha = dice->clim.alpha_vec[jInd];
	doeclim_DICE_init(dice);
      }
      else {
	dice->clim.t2xco2 = dice->clim.cs_sample_vec[jInd];
      }
            
      // Run CDICE with the SCC calculation
      calcSCC(dice, this_solution);
      //calc_CDICE(dice);
      
      // Capture the full time series of the model variables
      // in the appropriate vector
      utility[iInd][jInd] = (float) dice->econ.utility;
      for(tInd=0; tInd<nPeriods; tInd++) {
	
	if(use_doeclim == 0) {
	  tatm[tInd][iInd][jInd] = (float) dice->clim.tatm[tInd];
	  tocean[tInd][iInd][jInd] = (float) dice->clim.tocean[tInd];
	}
	mat[tInd][iInd][jInd] = (float) dice->carb.mat[tInd];
	forc[tInd][iInd][jInd] = (float) dice->carb.forc[tInd];
	mu[tInd][iInd][jInd] = (float) dice->carb.mu[tInd];
	ml[tInd][iInd][jInd] = (float) dice->carb.ml[tInd];
	cca[tInd][iInd][jInd] = (float) dice->econ.cca[tInd];
	k[tInd][iInd][jInd] = (float) dice->econ.k[tInd];
	c[tInd][iInd][jInd] = (float) dice->econ.c[tInd];
	cpc[tInd][iInd][jInd] = (float) dice->econ.cpc[tInd];
	i[tInd][iInd][jInd] = (float) dice->econ.i[tInd];
	ri[tInd][iInd][jInd] = (float) dice->econ.ri[tInd];
	y[tInd][iInd][jInd] = (float) dice->econ.y[tInd];
	ygross[tInd][iInd][jInd] = (float) dice->econ.ygross[tInd];
	ynet[tInd][iInd][jInd] = (float) dice->econ.ynet[tInd];
	damages[tInd][iInd][jInd] = (float) dice->econ.damages[tInd];
	damfrac[tInd][iInd][jInd] = (float) dice->econ.damfrac[tInd];
	abatecost[tInd][iInd][jInd] = (float) dice->econ.abatecost[tInd];
	periodu[tInd][iInd][jInd] = (float) dice->econ.periodu[tInd];
	eind[tInd][iInd][jInd] = (float) dice->econ.eind[tInd];
	pv_abatecost[tInd][iInd][jInd] = (float) dice->econ.pv_abatecost[tInd];
	pv_damages[tInd][iInd][jInd] = (float) dice->econ.pv_damages[tInd];
	totalcost[tInd][iInd][jInd] = (float) dice->econ.totalcost[tInd];
	pv_totalcost[tInd][iInd][jInd] = (float) dice->econ.pv_totalcost[tInd];
	e[tInd][iInd][jInd] = (float) dice->econ.e[tInd];
	mcabate[tInd][iInd][jInd] = (float) dice->econ.mcabate[tInd];
	cemutotper[tInd][iInd][jInd] = (float) dice->econ.cemutotper[tInd];
	scc[tInd][iInd][jInd] = (float) dice->econ.scc[tInd];
	
	
	if((iInd == 0) && (jInd == 0)) {
	  year[tInd] = (short) dice->config.dateSeries[tInd];
	  l[tInd] = (float) dice->econ.l[tInd];
	  ga[tInd] = (float) dice->econ.ga[tInd];
	  al[tInd] = (float) dice->econ.al[tInd];
	  gsig[tInd] = (float) dice->econ.gsig[tInd];
	  sigma[tInd] = (float) dice->econ.sigma[tInd];
	  cost1[tInd] = (float) dice->econ.cost1[tInd];
	  etree[tInd] = (float) dice->econ.etree[tInd];
	  rr[tInd] = (float) dice->econ.rr[tInd];
	  forcoth[tInd] = (float) dice->carb.forcoth[tInd];
	  partfract[tInd] = (float) dice->econ.partfract[tInd];
	  if (dice->ctrl.setSavings >= 0) {
	    s1[tInd] = (float) dice->dvars.s[tInd];
	  }
	}
	
	
      } // end loop over nPeriods
      
      // If DOEclim was used, store the variables with appropriate
      // dimensions.
      if(use_doeclim == 1) {
	for(tInd=0; tInd<nDoeclimts; tInd++) {
	  temp[tInd][iInd][jInd] = (float) dice->clim.temp[tInd];
	  doeclim_forc[tInd][iInd][jInd] = (float) dice->clim.forc[tInd];
	  heat_mixed[tInd][iInd][jInd] = (float) dice->clim.heat_mixed[tInd];
	}
      }
      
    } // end loop over nSamples
    
  } // end loop over nSolutions

  // Write these variable vectors to the netcdf file
  if(use_doeclim == 0) {
    if((retval = nc_put_var(ncid, tatmid, &tatm[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, toceanid, &tocean[0][0][0]))) { ncError(retval); }
  }
  if((retval = nc_put_var(ncid, matid, &mat[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, forcid, &forc[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, muid, &mu[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, mlid, &ml[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, ccaid, &cca[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, kid, &k[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, cid, &c[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, cpcid, &cpc[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, iid, &i[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, riid, &ri[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, yid, &y[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, ygrossid, &ygross[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, ynetid, &ynet[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, damagesid, &damages[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, damfracid, &damfrac[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, abatecostid, &abatecost[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, perioduid, &periodu[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, eindid, &eind[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, pv_abatecostid, &pv_abatecost[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, pv_damagesid, &pv_damages[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, totalcostid, &totalcost[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, pv_totalcostid, &pv_totalcost[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, eid, &e[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, mcabateid, &mcabate[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, cemutotperid, &cemutotper[0][0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, sccid, &scc[0][0][0]))) { ncError(retval); }

  if(use_doeclim == 1) {
    if((retval = nc_put_var(ncid, tempid, &temp[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, doeclim_forcid, &doeclim_forc[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, heat_mixedid, &heat_mixed[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, oceandiffid, &oceandiff[0]))) { ncError(retval); }
	  if((retval = nc_put_var(ncid, alphaid, &alpha[0]))) { ncError(retval); }
  }
  
  
  if((retval = nc_put_var(ncid, miuid, &miu[0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, utilityid, &utility[0][0]))) { ncError(retval); }
  
  if((retval = nc_put_var(ncid, csid, &cs[0]))) { ncError(retval); }
  
  if((retval = nc_put_var(ncid, yearid, &year[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, lid, &l[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, gaid, &ga[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, alid, &al[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, gsigid, &gsig[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, sigmaid, &sigma[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, cost1id, &cost1[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, etreeid, &etree[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, rrid, &rr[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, forcothid, &forcoth[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, partfractid, &partfract[0]))) { ncError(retval); }
  
  if (dice->ctrl.setSavings < 0) {
    if((retval = nc_put_var(ncid, sid, &s2[0][0]))) { ncError(retval); }
  }
  else {
    if((retval = nc_put_var(ncid, sid, &s1[0]))) { ncError(retval); }
  }
  
  
  // Close the netcdf file
  if((retval = nc_close(ncid))) { ncError(retval); }
  
  return;
}
コード例 #16
0
ファイル: meshid.C プロジェクト: computingtek/libmesh
int main(int argc, char ** argv)
{
  GetPot cl(argc, argv);

  // Command line parsing
  if(!cl.search("--input"))
    {
      std::cerr << "No --input argument found!" << std::endl;
      usage_error(argv[0]);
    }
  const char * meshname = cl.next("");

  if(!cl.search("--oldid"))
    {
      std::cerr << "No --oldid argument found!" << std::endl;
      usage_error(argv[0]);
    }
  long oldid = cl.next(0);

  if(!cl.search("--newid"))
    {
      std::cerr << "No --newid argument found!" << std::endl;
      usage_error(argv[0]);
    }
  long newid = cl.next(0);

  unsigned char flags = 0;
  if (cl.search("--nodesetonly"))
    flags |= NODES;
  if (cl.search("--sidesetonly"))
    flags |= SIDES;
  if (cl.search("--blockonly"))
    flags |= BLOCKS;
  if (cl.search("--dim"))
    flags |= EXODUS_DIM;

  // No command line flags were set, turn on NODES, SIDES, and BLOCKS
  if (!flags)
    flags = NODES | SIDES | BLOCKS; // ALL except EXODUS_DIM on

  // flags are exclusive
  if (flags != NODES &&
      flags != SIDES &&
      flags != BLOCKS &&
      flags != EXODUS_DIM &&
      flags != (NODES | SIDES | BLOCKS))
    {
      std::cerr << "Only one of the following options may be active [--nodesetonly | --sidesetonly | --blockonly | --dim]!" << std::endl;
      usage_error(argv[0]);
    }

  // Processing
  std::string var_name, dim_name;
  int status;
  int nc_id, var_id, dim_id;
  size_t dim_len;

  status = nc_open (meshname, NC_WRITE, &nc_id);
  if (status != NC_NOERR) handle_error(status, "Error while opening file.");

  for (unsigned char mask = 8; mask; mask/=2)
    {
      // These are char *'s #defined in exodsuII_int.h
      switch (flags & mask)
        {
        case BLOCKS:
          dim_name = DIM_NUM_EL_BLK;
          var_name = VAR_ID_EL_BLK;
          break;
        case SIDES:
          dim_name = DIM_NUM_SS;
          var_name = VAR_SS_IDS;
          break;
        case NODES:
          dim_name = DIM_NUM_NS;
          var_name = VAR_NS_IDS;
          break;
        case EXODUS_DIM:
          dim_name = DIM_NUM_DIM;
          // var_name not used for setting dimension
          break;
        default:
          // We don't match this flag, so go to the next mask
          continue;
        }

      // Get the ID and length of the variable in question - stored in a dimension field
      status = nc_inq_dimid (nc_id, dim_name.c_str(), &dim_id);
      if (status != NC_NOERR) handle_error(status, "Error while inquiring about a dimension's ID.");

      status = nc_inq_dimlen (nc_id, dim_id, &dim_len);
      if (status != NC_NOERR) handle_error(status, "Error while inquiring about a dimension's length.");

      if ( (flags & mask) != EXODUS_DIM)
        {
          // Now get the variable values themselves
          std::vector<long> var_vals(dim_len);

          status = nc_inq_varid (nc_id, var_name.c_str(), &var_id);
          if (status != NC_NOERR) handle_error(status, "Error while inquiring about a variable's ID.");

          status = nc_get_var_long (nc_id, var_id, &var_vals[0]);
          if (status != NC_NOERR) handle_error(status, "Error while retrieving a variable's values.");

          // Update the variable value specified on the command line
          for (unsigned int i=0; i<dim_len; ++i)
            if (var_vals[i] == oldid)
              var_vals[i] = newid;

          // Save that value back to the NetCDF database
          status = nc_put_var_long (nc_id, var_id, &var_vals[0]);
          if (status != NC_NOERR) handle_error(status, "Error while writing a variable's values.");
        }

      // Redefine the dimension
      else
        {
          // The value stored in dim_len is actually the dimension?
          if (dim_len == (size_t)oldid)
            {
              // Trying to change def's always raises
              // Error -38: /* Operation not allowed in data mode */
              // unless you are in "define" mode.  So let's go there now.

              // Try to put the file into define mode
              status = nc_redef(nc_id);
              if (status != NC_NOERR) handle_error(status, "Error while putting file into define mode.");

              // Rename the "num_dim" dimension.  Note: this will fail if there is already a dimension
              // which has the name you are trying to use.  This can happen, for example if you have already
              // changed the dimension of this exodus file once using this very script.  There appears
              // to be no way to delete a dimension using basic NetCDF interfaces, so to workaround this
              // we just rename it to an arbitrary unique string that Exodus will ignore.

              // Construct a string with 6 random alpha-numeric characters at the end.
              std::string random_dim_name;
              gen_random_string(random_dim_name, 6);
              random_dim_name = std::string("ignored_num_dim_") + random_dim_name;

              // Rename the old dimension variable to our randomly-chosen name
              status = nc_rename_dim(nc_id, dim_id, random_dim_name.c_str());
              if (status != NC_NOERR) handle_error(status, "Error while trying to rename num_dim.");

              // Now define a new "num_dim" value of newid
              int dummy=0;
              status = nc_def_dim (nc_id, dim_name.c_str(), newid, &dummy);
              if (status != NC_NOERR) handle_error(status, "Error while trying to define num_dim.");

              // Leave define mode
              status = nc_enddef(nc_id);
              if (status != NC_NOERR) handle_error(status, "Error while leaving define mode.");
            }
        }
    } // end for

  // Write out the dataset
  status = nc_close(nc_id);

  return (status != NC_NOERR);
}
コード例 #17
0
ファイル: sfc_pres_temp_rd.c プロジェクト: Unidata/netcdf-c
int
main()
{
   int ncid, pres_varid, temp_varid;
   int lat_varid, lon_varid;

   /* We will read surface temperature and pressure fields. */
   float pres_in[NLAT][NLON];
   float temp_in[NLAT][NLON];

   /* For the lat lon coordinate variables. */
   float lats_in[NLAT], lons_in[NLON];

   /* To check the units attributes. */
   char pres_units_in[MAX_ATT_LEN], temp_units_in[MAX_ATT_LEN];
   char lat_units_in[MAX_ATT_LEN], lon_units_in[MAX_ATT_LEN];

   /* We will learn about the data file and store results in these
      program variables. */
   int ndims_in, nvars_in, ngatts_in, unlimdimid_in;

   /* Loop indexes. */
   int lat, lon;

   /* Error handling. */
   int retval;

   /* Open the file. */
   if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid)))
      ERR(retval);

   /* There are a number of inquiry functions in netCDF which can be
      used to learn about an unknown netCDF file. NC_INQ tells how
      many netCDF variables, dimensions, and global attributes are in
      the file; also the dimension id of the unlimited dimension, if
      there is one. */
   if ((retval = nc_inq(ncid, &ndims_in, &nvars_in, &ngatts_in,
			&unlimdimid_in)))
      ERR(retval);

   /* In this case we know that there are 2 netCDF dimensions, 4
      netCDF variables, no global attributes, and no unlimited
      dimension. */
   if (ndims_in != 2 || nvars_in != 4 || ngatts_in != 0 ||
       unlimdimid_in != -1) return 2;

   /* Get the varids of the latitude and longitude coordinate
    * variables. */
   if ((retval = nc_inq_varid(ncid, LAT_NAME, &lat_varid)))
      ERR(retval);
   if ((retval = nc_inq_varid(ncid, LON_NAME, &lon_varid)))
      ERR(retval);

   /* Read the coordinate variable data. */
   if ((retval = nc_get_var_float(ncid, lat_varid, &lats_in[0])))
      ERR(retval);
   if ((retval = nc_get_var_float(ncid, lon_varid, &lons_in[0])))
      ERR(retval);

   /* Check the coordinate variable data. */
   for (lat = 0; lat < NLAT; lat++)
      if (lats_in[lat] != START_LAT + 5.*lat)
	 return 2;
   for (lon = 0; lon < NLON; lon++)
      if (lons_in[lon] != START_LON + 5.*lon)
	 return 2;

   /* Get the varids of the pressure and temperature netCDF
    * variables. */
   if ((retval = nc_inq_varid(ncid, PRES_NAME, &pres_varid)))
      ERR(retval);
   if ((retval = nc_inq_varid(ncid, TEMP_NAME, &temp_varid)))
      ERR(retval);

   /* Read the data. Since we know the contents of the file we know
    * that the data arrays in this program are the correct size to
    * hold all the data. */
   if ((retval = nc_get_var_float(ncid, pres_varid, &pres_in[0][0])))
      ERR(retval);
   if ((retval = nc_get_var_float(ncid, temp_varid, &temp_in[0][0])))
      ERR(retval);

   /* Check the data. */
   for (lat = 0; lat < NLAT; lat++)
      for (lon = 0; lon < NLON; lon++)
	 if (pres_in[lat][lon] != SAMPLE_PRESSURE + (lon * NLAT + lat) ||
	     temp_in[lat][lon] != SAMPLE_TEMP + .25 * (lon * NLAT + lat))
	    return 2;

   /* Each of the netCDF variables has a "units" attribute. Let's read
      them and check them. */
   if ((retval = nc_get_att_text(ncid, lat_varid, UNITS, lat_units_in)))
      ERR(retval);
   if (strncmp(lat_units_in, LAT_UNITS, strlen(LAT_UNITS)))
      return 2;

   if ((retval = nc_get_att_text(ncid, lon_varid, UNITS, lon_units_in)))
      ERR(retval);
   if (strncmp(lon_units_in, LON_UNITS, strlen(LON_UNITS)))
      return 2;

   if ((retval = nc_get_att_text(ncid, pres_varid, UNITS, pres_units_in)))
      ERR(retval);
   if (strncmp(pres_units_in, PRES_UNITS, strlen(PRES_UNITS)))
      return 2;

   if ((retval = nc_get_att_text(ncid, temp_varid, UNITS, temp_units_in)))
      ERR(retval);
   if (strncmp(temp_units_in, TEMP_UNITS, strlen(TEMP_UNITS))) return 2;

   /* Close the file. */
   if ((retval = nc_close(ncid)))
      ERR(retval);

   printf("*** SUCCESS reading example file sfc_pres_temp.nc!\n");
   return 0;
}
コード例 #18
0
ファイル: surface3d.c プロジェクト: c-abird/H2Lib
void
write_nc_surface3d(pcsurface3d gr, const char *filename)
{
#ifdef USE_NETCDF
  const     real(*x)[3] = (const real(*)[3]) gr->x;
  const     uint(*e)[2] = (const uint(*)[2]) gr->e;
  const     uint(*t)[3] = (const uint(*)[3]) gr->t;
  const     uint(*s)[3] = (const uint(*)[3]) gr->s;
  uint      vertices = gr->vertices;
  uint      edges = gr->edges;
  uint      triangles = gr->triangles;
  int       res, nc_out;
  int       x_id, e_id, t_id, s_id;
  int       vertices_id, edges_id, triangles_id;
  int       n2_id, n3_id;
  int       dimid[2];

  /* Create CDF file */
  res = nc_create(filename, NC_NETCDF4, &nc_out);
  nc_handle_error(res);

  /* Define dimensions */
  res = nc_def_dim(nc_out, "vertices", vertices, &vertices_id);
  nc_handle_error(res);
  res = nc_def_dim(nc_out, "edges", edges, &edges_id);
  nc_handle_error(res);
  res = nc_def_dim(nc_out, "triangles", triangles, &triangles_id);
  nc_handle_error(res);
  res = nc_def_dim(nc_out, "two", 2, &n2_id);
  nc_handle_error(res);
  res = nc_def_dim(nc_out, "three", 3, &n3_id);
  nc_handle_error(res);

  /* Define x variable */
  dimid[0] = vertices_id;
  dimid[1] = n3_id;
  res = nc_def_var(nc_out, "x", NC_DOUBLE, 2, dimid, &x_id);
  nc_handle_error(res);
  res = nc_def_var_deflate(nc_out, x_id, 0, 1, NC_DEFLATE_LEVEL);
  nc_handle_error(res);

  /* Define e variable */
  dimid[0] = edges_id;
  dimid[1] = n2_id;
  res = nc_def_var(nc_out, "e", NC_UINT, 2, dimid, &e_id);
  nc_handle_error(res);
  res = nc_def_var_deflate(nc_out, e_id, 0, 1, NC_DEFLATE_LEVEL);
  nc_handle_error(res);

  /* Define t variable */
  dimid[0] = triangles_id;
  dimid[1] = n3_id;
  res = nc_def_var(nc_out, "t", NC_UINT, 2, dimid, &t_id);
  nc_handle_error(res);
  res = nc_def_var_deflate(nc_out, t_id, 0, 1, NC_DEFLATE_LEVEL);
  nc_handle_error(res);

  /* Define s variable */
  dimid[0] = triangles_id;
  dimid[1] = n3_id;
  res = nc_def_var(nc_out, "s", NC_UINT, 2, dimid, &s_id);
  nc_handle_error(res);
  res = nc_def_var_deflate(nc_out, s_id, 0, 1, NC_DEFLATE_LEVEL);
  nc_handle_error(res);

  /* Leave define mode */
  res = nc_enddef(nc_out);
  nc_handle_error(res);

  /* Write variables */
  res = nc_put_var(nc_out, x_id, x);
  nc_handle_error(res);
  res = nc_put_var(nc_out, e_id, e);
  nc_handle_error(res);
  res = nc_put_var(nc_out, t_id, t);
  nc_handle_error(res);
  res = nc_put_var(nc_out, s_id, s);
  nc_handle_error(res);

  /* Close file */
  res = nc_close(nc_out);
  nc_handle_error(res);

#else
  (void) gr;
  (void) filename;

  (void) printf("Sorry, no NetCDF support.\n");
#endif
}
コード例 #19
0
/*! Main function for tst_fill_attr_vanish.c
 *
 */
int main()
{
  int ncid, dimids[RANK_P], time_id, p_id, test_id;
  int ndims, dimids_in[RANK_P];

  int test_data[1] = {1};
  size_t test_start[1] = {0}, test_count[1] = {1};
  int test_fill_val[] = {5};


  double data[1] = {3.14159};
  size_t start[1] = {0}, count[1] = {1};
  float ddata[1][4][3];
  static float P_data[LEN];
  size_t cor[RANK_P] = {0, 1, 0};
  size_t edg[RANK_P] = {1, 1, LEN};
  float pfills[] = {3};

  printf("\n*** Testing for a netCDF-4 fill-value bug.\n");
  printf("*** Creating a file with no _FillValue defined. ***\n");

  /* Create a 3D test file. */
  if (nc_create(FILENAME, NC_CLOBBER|NC_NETCDF4, &ncid)) ERR;
  if (nc_set_fill(ncid, NC_NOFILL, NULL)) ERR;

  /* define dimensions */
  if (nc_def_dim(ncid, "Time", NC_UNLIMITED, &dimids[0])) ERR;
  if (nc_def_dim(ncid, "X", 4, &dimids[2])) ERR;
  if (nc_def_dim(ncid, "Y", 3, &dimids[1])) ERR;

  /* define variables */
  if (nc_def_var(ncid, "Time", NC_DOUBLE, 1, dimids, &time_id)) ERR;
  if (nc_def_var(ncid, "P", NC_FLOAT, RANK_P, dimids, &p_id)) ERR;
  if (nc_def_var(ncid, "Test", NC_INT, 1, &dimids[1], &test_id)) ERR;

  /* Add a _FillValue attribute */

  if (nc_put_att_text(ncid, test_id, ATTNAME, strlen(ATTVAL), ATTVAL)) ERR;
  /* Add a value to the test variable */
  if (nc_put_vara(ncid, test_id, test_start, test_count, test_data)) ERR;

  /* Add one record in coordinate variable. */
  if (nc_put_vara(ncid, time_id, start, count, data)) ERR;

  /* That's it! */
  if (nc_close(ncid)) ERR;

  /********************************************/

  /* Reopen the file, add a fillvalue attribute. */
  if (nc_open(FILENAME, NC_NOCLOBBER|NC_WRITE, &ncid)) ERR;
  if (nc_redef(ncid)) ERR;
  if (nc_inq_varid(ncid, "Test", &test_id)) ERR;

  /* Query existing attribute. */
  {
    printf("**** Checking that attribute still exists:\t");
    char *attval = malloc(sizeof(char) * strlen(ATTVAL));
    if(nc_get_att_text(ncid,test_id,ATTNAME,attval)) {printf("Fail\n"); ERR;}
    else {printf("%s\n",attval);}
    free(attval);

  }

  printf("**** Adding _FillValue attribute.\n");
  if (nc_put_att_int(ncid, test_id, "_FillValue", NC_INT, 1, test_fill_val)) ERR;

  /* Query existing attribute. */
  {
    printf("**** Checking that attribute still exists, pre-write:\t");
    char *attval = malloc(sizeof(char) * strlen(ATTVAL));
    if(nc_get_att_text(ncid,test_id,ATTNAME,attval)) {printf("Fail\n"); ERR;}
    else {printf("%s\n",attval);}
    free(attval);

  }

  /* Close file again. */
  printf( "**** Saving, closing file.\n");
  if (nc_close(ncid)) ERR;
  /********************************************/
  printf( "*** Reopening file.\n");
  /* Reopen the file, checking that all attributes are preserved. */
  if (nc_open(FILENAME, NC_NOCLOBBER|NC_WRITE, &ncid)) ERR;
  if (nc_redef(ncid)) ERR;
  if (nc_inq_varid(ncid, "Test", &test_id)) ERR;

  /* Query existing attribute. */
  {
    printf("**** Checking that attribute still exists:\t");
    char *attval = malloc(sizeof(char) * strlen(ATTVAL));
    if(nc_get_att_text(ncid,test_id,ATTNAME,attval)) {printf("Fail\n"); ERR;}
    else {printf("%s\n",attval);}
    free(attval);

  }

  if (nc_close(ncid)) ERR;
  /********************************************/

  SUMMARIZE_ERR;

  FINAL_RESULTS;
  return 0;
}
コード例 #20
0
ファイル: surface3d.c プロジェクト: c-abird/H2Lib
psurface3d
read_nc_surface3d(const char *filename)
{
#ifdef USE_NETCDF
  psurface3d gr;
  real(*x)[3];
  uint(*e)[2];
  uint(*t)[3];
  uint(*s)[3];
  uint      vertices;
  uint      edges;
  uint      triangles;
  int       res, nc_in;
  int       x_id, e_id, t_id, s_id;
  int       vertices_id, edges_id, triangles_id;
  size_t    dim;

  /* Open CDF file */
  res = nc_open(filename, NC_NOWRITE, &nc_in);
  nc_handle_error(res);

  /* Obtain dimensions */
  res = nc_inq_dimid(nc_in, "vertices", &vertices_id);
  nc_handle_error(res);
  res = nc_inq_dimid(nc_in, "edges", &edges_id);
  nc_handle_error(res);
  res = nc_inq_dimid(nc_in, "triangles", &triangles_id);
  nc_handle_error(res);

  /* Get values of dimensions */
  res = nc_inq_dimlen(nc_in, vertices_id, &dim);
  nc_handle_error(res);
  vertices = dim;
  res = nc_inq_dimlen(nc_in, edges_id, &dim);
  nc_handle_error(res);
  edges = dim;
  res = nc_inq_dimlen(nc_in, triangles_id, &dim);
  nc_handle_error(res);
  triangles = dim;

  /* Create surface3d object */
  gr = new_surface3d(vertices, edges, triangles);
  x = gr->x;
  e = gr->e;
  t = gr->t;
  s = gr->s;

  /* Obtain variables */
  res = nc_inq_varid(nc_in, "x", &x_id);
  nc_handle_error(res);
  res = nc_inq_varid(nc_in, "e", &e_id);
  nc_handle_error(res);
  res = nc_inq_varid(nc_in, "t", &t_id);
  nc_handle_error(res);
  res = nc_inq_varid(nc_in, "s", &s_id);
  nc_handle_error(res);

  /* Read variables */
  res = nc_get_var(nc_in, x_id, x);
  res = nc_get_var(nc_in, e_id, e);
  res = nc_get_var(nc_in, t_id, t);
  res = nc_get_var(nc_in, s_id, s);

  /* Close file */
  res = nc_close(nc_in);
  nc_handle_error(res);

  return gr;

#else
  (void) filename;

  (void) printf("Sorry, no NetCDF support.\n");
  return 0;
#endif
}
コード例 #21
0
ファイル: sfc_pres_temp_more.c プロジェクト: Unidata/netcdf-c
int
main()
{
   int ncid, lon_dimid, lat_dimid, pres_varid, temp_varid;
   int dimids[NDIMS];
   float pres_out[LAT_LEN][LON_LEN], pres_in[LAT_LEN][LON_LEN];
   float temp_out[LAT_LEN][LON_LEN], temp_in[LAT_LEN][LON_LEN];
   char *att_in;
   size_t len_in;
   int error = 0;
   int lat, lon, retval;

   /* Create phoney data. If this wasn't an example program, we would
    * have some real data to write, for example, model output. */
   for (lat = 0; lat < LAT_LEN; lat++)
      for (lon = 0; lon < LON_LEN; lon++)
      {
	 pres_out[lat][lon] = 1013.1;
	 temp_out[lat][lon] = 12.5;
      }

   /* These are the latitudes and longitudes which correspond with
    * ticks on the dimension axes. */
   for (lat = 0; lat < LAT_LEN; lat++)
      latitude[lat] = 40. + lat * 2.5;
   for (lon = 0; lon < LON_LEN; lon++)
      longitude[lon] = -90. - lon * 5;

   /* Create the file. */
   if ((retval = nc_create(FILE_NAME, NC_CLOBBER, &ncid)))
      return retval;

   /* Add data sonnet. By using NC_GLOBAL we mean that this attribute
    * applies to the entire file, not just to one variable. Don't
    * forget that sizeof does not include the null terminator, so if
    * you want it, you need to add one more byte. */
   if ((retval = nc_put_att_text(ncid, NC_GLOBAL, SONNET_NAME,
				 sizeof(poem) + 1, poem)))
      return retval;

   /* Define the dimensions. */
   if ((retval = nc_def_dim(ncid, LAT_NAME, LAT_LEN, &lat_dimid)))
      return retval;
   if ((retval = nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)))
      return retval;

   /* Save the dimension information, in variables of the same
    * name. First we need to define these variables. */
   dimids[0] = lat_dimid;
   if ((retval = nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, dimids, &lat_varid)))
      return retval;
   dimids[0] = lon_dimid;
   if ((retval = nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, dimids, &lon_varid)))
      return retval;

   /* Define the variables. */
   dimids[0] = lat_dimid;
   dimids[1] = lon_dimid;
   if ((retval = nc_def_var(ncid, PRES_NAME, NC_FLOAT, NDIMS, dimids, &pres_varid)))
      return retval;
   if ((retval = nc_def_var(ncid, TEMP_NAME, NC_FLOAT, NDIMS, dimids, &temp_varid)))
      return retval;

   /* End define mode. */
   if ((retval = nc_enddef(ncid)))
      return retval;

   /* Write the dimension metadata. */
   if ((retval = nc_put_var_float(ncid, lat_varid, latitude_out)))
      return retval;
   if ((retval = nc_put_var_float(ncid, lon_varid, longitude_out)))
      return retval;

   /* Write the phoney data. */
   if ((retval = nc_put_var_float(ncid, pres_varid, pres_out)))
      return retval;
   if ((retval = nc_put_var_float(ncid, temp_varid, temp_out)))
      return retval;

   /* Close the file. */
   if ((retval = nc_close(ncid)))
      return retval;

   /* Open the file and check that everything's OK. */
   if ((retval = nc_open(FILE_NAME, 0, &ncid)))
      return retval;

   /* Read the attribute. First find it's length to allocate storage
    * for it. */
   if ((retval = nc_inq_attlen(ncid, NC_GLOBAL, SONNET_NAME, &len_in)))
      return retval;
   if (!(att_in = malloc(len_in)))
      return NC_ENOMEM;
   if (strcmp(att_in, data_poem))
      error++;
   free(att_in);
   if (error)
      return -2;

   /* Read the data. */
   if ((retval = nc_get_var_float(ncid, pres_varid, pres_in)))
      return retval;
   if ((retval = nc_get_var_float(ncid, temp_varid, temp_in)))
      return retval;

   /* Check the data. */
   for (lat = 0; lat < LAT_LEN; lat++)
      for (lon = 0; lon < LON_LEN; lon++)
	 if (pres_in[lat][lon] != pres_out[lat][lon] ||
	     temp_in[lat][lon] != temp_out[lat][lon])
	    return -2;

   /* Close the file. */
   if ((retval = nc_close(ncid)))
      return retval;

   return 0;
}
コード例 #22
0
ファイル: tst_utf8.c プロジェクト: mmase/wgrib2
int
main(int argc, char **argv)
{
   int ncid, dimid, varid;
   int dimids[NDIMS];

   /* (unnormalized) UTF-8 encoding for Unicode 8-character "Hello" in Greek */
   unsigned char name_utf8[] = {
       0xCE, 0x9A,	  /* GREEK CAPITAL LETTER KAPPA  : 2-bytes utf8 */
       0xCE, 0xB1,	  /* GREEK SMALL LETTER LAMBDA   : 2-bytes utf8 */
       0xCE, 0xBB,	  /* GREEK SMALL LETTER ALPHA    : 2-bytes utf8 */
       0xCE, 0xB7,	  /* GREEK SMALL LETTER ETA      : 2-bytes utf8 */
       0xCE, 0xBC,	  /* GREEK SMALL LETTER MU       : 2-bytes utf8 */
       0xE1, 0xBD, 0xB3,  /* GREEK SMALL LETTER EPSILON
                             WITH TONOS                  : 3-bytes utf8 */
       0xCF, 0x81,	  /* GREEK SMALL LETTER RHO      : 2-bytes utf8 */
       0xCE, 0xB1,	  /* GREEK SMALL LETTER ALPHA    : 2-bytes utf8 */
       0x00
   };

/* Name used for dimension, variable, and attribute value */
#define UNAME ((char *) name_utf8)
#define UNAMELEN (sizeof name_utf8)

   char name_in[UNAMELEN + 1], strings_in[UNAMELEN + 1];
   nc_type att_type;
   size_t att_len;
   int res;
   
#ifdef USE_PARALLEL
   MPI_Init(&argc, &argv);
#endif

   printf("*** creating UTF-8 test file %s...", FILE7_NAME);
   if ((res = nc_create(FILE7_NAME, NC_CLOBBER, &ncid)))
       ERR;

   /* Define dimension with Unicode UTF-8 encoded name */
   if ((res = nc_def_dim(ncid, UNAME, NX, &dimid)))
       ERR;
   dimids[0] = dimid;

   /* Define variable with same name */
   if ((res = nc_def_var(ncid, UNAME, NC_CHAR, NDIMS, dimids, &varid)))
       ERR;

   /* Create string attribute with same value */
   if ((res = nc_put_att_text(ncid, varid, UNITS, UNAMELEN, UNAME)))
       ERR;

   if ((res = nc_enddef(ncid)))
       ERR;

   /* Write string data, UTF-8 encoded, to the file */
   if ((res = nc_put_var_text(ncid, varid, UNAME)))
       ERR;

   if ((res = nc_close(ncid)))
       ERR;

   /* Check it out. */
   
   /* Reopen the file. */
   if ((res = nc_open(FILE7_NAME, NC_NOWRITE, &ncid)))
       ERR;
   if ((res = nc_inq_varid(ncid, UNAME, &varid)))
       ERR;
   if ((res = nc_inq_varname(ncid, varid, name_in)))
       ERR;
   {
       /* Note, name was normalized before storing, so retrieved name
	  won't match original unnormalized name.  Check that we get
	  normalized version, instead.  */
       
       /* NFC normalized UTF-8 for Unicode 8-character "Hello" in Greek */
       unsigned char norm_utf8[] = {
	   0xCE, 0x9A,	  /* GREEK CAPITAL LETTER KAPPA  : 2-bytes utf8 */
	   0xCE, 0xB1,	  /* GREEK SMALL LETTER LAMBDA   : 2-bytes utf8 */
	   0xCE, 0xBB,	  /* GREEK SMALL LETTER ALPHA    : 2-bytes utf8 */
	   0xCE, 0xB7,	  /* GREEK SMALL LETTER ETA      : 2-bytes utf8 */
	   0xCE, 0xBC,	  /* GREEK SMALL LETTER MU       : 2-bytes utf8 */
	   0xCE, 0xAD,    /* GREEK SMALL LETTER EPSILON WITH TONOS 
			                                 : 2-bytes utf8 */
	   0xCF, 0x81,	  /* GREEK SMALL LETTER RHO      : 2-bytes utf8 */
	   0xCE, 0xB1,	  /* GREEK SMALL LETTER ALPHA    : 2-bytes utf8 */
	   0x00
       };
#define NNAME ((char *) norm_utf8)
#define NNAMELEN (sizeof norm_utf8)
       if ((res = strncmp(NNAME, name_in, NNAMELEN)))
	   ERR;
   }
   if ((res = nc_inq_att(ncid, varid, UNITS, &att_type, &att_len)))
       ERR;
   if ((res = att_type != NC_CHAR || att_len != UNAMELEN))
       ERR;
   /* We don't normalize data or attribute values, so get exactly what was put */
   if ((res = nc_get_att_text(ncid, varid, UNITS, strings_in)))
       ERR;
   strings_in[att_len] = '\0';
   if ((res = strncmp(UNAME, strings_in, UNAMELEN)))
       ERR;
   if ((res = nc_close(ncid)))
       ERR;

   SUMMARIZE_ERR;
   FINAL_RESULTS;
#ifdef USE_PARALLEL
   MPI_Finalize();
#endif   
   return 0;
}
コード例 #23
0
ファイル: Resample_on_Z.c プロジェクト: BreakawayLabs/MOM4p1
int main(int argc, char *argv[]) {
  double *int_depth, *lay_depth;
  int nvar=0, n_tname = 0, n, m, i, j, k, lev, v, num_files = 0;
  size_t nx, ny, nxy, nz;
  int verbose = 0;
  int status;
  size_t nlay, nint;
  double st_eta[2], st_var[2];
  double *eta = NULL, *var_out = NULL, *var_in = NULL, *ev = NULL;
  double *elc = NULL;
//  double elc[100], depths[100];
  char var_names[MAX_VARS][NC_MAX_NAME], eta_name[NC_MAX_NAME];
  double EPSILON = 1.0e-10;
  double missing = -1.0e34;
  char time_names[2][NC_MAX_NAME], depth_names[2][NC_MAX_NAME];

  char depth_file[FILE_NAME_SZ], in_file[MAX_FILES][FILE_NAME_SZ], out_file[FILE_NAME_SZ];
  char arglist[2000];

  
  // The following block interprets the input fields.
  {
    if (argc < 6) {
      printf("%s requires at least 5 arguments (# = %d):\n\n"
          "useage:\n%s -d'Depth_file' -V:'variable_names'[,'vn2',...] -e'Eta_name' variables\n"
          "\t-T:'Time_varable_name1,Time_varable_name2' -o'Output_file' 'Input_file_name[s]'\n"
          "\nOptions:\n\t-v\t\t Verbose mode"
           "\n\t-z:'Z-center_name,Z-edge_name'"
         "\nvariables:\n\tVariable names from input file.\n",
          argv[0],argc-1,argv[0]);
      return -1;
    }
    
    strcpy(arglist,argv[0]);
    for (n=1;n<argc;n++) {strcat(arglist," "); strcat(arglist,argv[n]);}

    for (n=1;n<argc;n++) if (strcmp(argv[n],"-v")==0) {
      verbose = 1; printf("\nUsing verbose mode.\n\n");
    }

    strcpy(depth_file,""); strcpy(out_file,"");
    for (n=0;n<MAX_FILES;n++) strcpy(in_file[n],"");
    strcpy(zc_name,"zt"); strcpy(ze_name,"zw");
    strcpy(eta_name,""); strcpy(time_names[0],""); strcpy(time_names[1],"");

    for (n=1;n<argc;n++) {
      size_t sz;
      // if (verbose) printf("Arg %d: %s\n",n,argv[n]);
      if (strcmp(argv[n],"-v")==0) continue;
      else if (strncmp(argv[n],"-z:",3)==0) {
        // PARSE FOR depth names.
        m = 3; sz = strlen(argv[n]);
        for (i=m;i<sz;i++) if (argv[n][i] == ',') {break;}
        strncpy(zc_name,&argv[n][m],i-m); zc_name[i-m] = '\0';
        // if (verbose) printf("\tTime name %d is %s.\n",n_tname,time_names[n_tname]);
        m = i+1;
        if (i<sz) {
          strncpy(ze_name,&argv[n][m],sz-m); ze_name[sz-m] = '\0';
        }
      }
      else if (strncmp(argv[n],"-d",2)==0) strcpy(depth_file,&argv[n][2]);
      else if (strncmp(argv[n],"-o",2)==0) strcpy(out_file,&argv[n][2]);
      else if (strncmp(argv[n],"-e",2)==0) strcpy(eta_name,&argv[n][2]);
      else if (strncmp(argv[n],"-V:",3)==0) {
        // PARSE FOR variable names.
        m = 3; sz = strlen(argv[n]);
        for (;;) {
          for (i=m;i<sz;i++) if (argv[n][i] == ',') {break;}
          strncpy(var_names[nvar],&argv[n][m],i-m);
          var_names[nvar][i-m] = '\0';
          // if (verbose) printf("\tVariable %d is %s.\n",nvar,var_names[nvar]);
          nvar++;
          if (i==sz) break;
          m = i+1;
        }
      }
      else if (strncmp(argv[n],"-T:",3)==0) {
        // PARSE FOR time names.
        m = 3; sz = strlen(argv[n]);
        for (;;) {
          for (i=m;i<sz;i++) if (argv[n][i] == ',') {break;}
          strncpy(time_names[n_tname],&argv[n][m],i-m);
          time_names[n_tname][i-m] = '\0';
          // if (verbose) printf("\tTime name %d is %s.\n",n_tname,time_names[n_tname]);
          n_tname++;
          if (i==sz) break;
          m = i+1;
        }
      }
      else if (strncmp(argv[n],"-",1)==0)
        printf("Unrecognized argument %s.\n",argv[n]);
      else {
        // Add input file name.
        if (num_files >= MAX_FILES)
          printf("Unable to add input file %s, because %d files are already in use.\n"
                 "Increase MAX_FILES in %s.c.\n",argv[n],num_files,argv[0]);
        strcpy(in_file[num_files],argv[n]);
        // if (verbose) printf("Adding input file %d with name %s.\n",num_files,in_file[num_files]);
        num_files++;
      }
    }

    if (strlen(depth_file) == 0) {
      printf("Depth file name must be specified as -dDEPTH_FILE_NAME\n");
      exit(-1);
    }
    if (num_files == 0) {
      printf("At least one input file name must be specified.\n");
      exit(-1);
    }
    if (strlen(out_file) == 0) {
      printf("Output file name must be specified as -oOUTPUT_FILE_NAME\n");
      exit(-1);
    }
    if (strlen(eta_name) == 0) {
      printf("Interface height variable name must be specified as -eETA_NAME\n");
      exit(-1);
    }
    if (nvar < 1) {
      printf("At least 1 variable must be specified.\n");
      exit(-1);
    }
  }
      
  strcpy(depth_names[0],zc_name);
  strcpy(depth_names[1],ze_name);
  //  get_vertical_grid(...);
  if (verbose) printf("\tGet depths from %s.\n",depth_file);
  get_depths(depth_file, depth_names, &lay_depth, &int_depth, &nz);

  
//  if (verbose) printf("Read eta as %s from %s.\n",eta_name,in_file);
//  read_eta(in_file,eta_name,&eta,&nlay);
  
  // Create the new NetCDF file.
  {
    if (verbose) printf("\tPrepare %s.\n",out_file);
    write_output(out_file,in_file,depth_file,
                 nz,var_names,time_names,depth_names,&nvar,arglist);
  }

  // Allocate space for the depth space variables.
  // if (verbose) printf("Read eta.\n");
  status = read_field(0,0,eta_name,&eta,&nint,&nx,&ny, st_eta);
  if (status != 0) {
    printf("ERROR: Unsuccessful in reading %s from %s.\n",eta_name,in_file[0]);
    exit(-1);
  }
  if (verbose) printf("\tEta %s starts at %g %g.\n",eta_name,st_eta[0],st_eta[1]);
  nxy = nx*ny;
  nlay = nint-1;

  if (verbose) printf("\tAllocating space for output variables.\n");
  var_out = (double *) calloc((size_t) (nz*nxy), sizeof(double));
  ev = (double *) calloc((size_t) nint, sizeof(double));
  elc = (double *) calloc((size_t) nint, sizeof(double));
  if (verbose) printf("\tDone with allocations.\n");
  

  for (lev=0;;lev++) {
    size_t junk, nlv, nxv, nyv, nxyv;
  
    if (verbose) printf("\tWorking on time level %d.\n",lev);
    
    if (lev>0) {
      // if (verbose) printf("Read %s for time %d.\n",eta_name,lev);
      status = read_field(0, lev, eta_name, &eta, &junk, &junk, &junk, st_eta);
      // if (verbose) printf("Done reading %s for time %d.\n",eta_name,lev);
    }
    if (status != 0) break;
    for (k=nint-1;k>=0;k--) for (i=0;i<nxy;i++) eta[k*nxy+i] -= eta[i];

    for (v=0;v<nvar;v++) {
            // This assumes that the missing value is -1e34.
      double missing_value = -1.0e34;
      int I, grid = 0;
      if ((lev>0) && static_var[v]) break;
     // if (verbose) printf("Read %s for time %d.\n",var_names[v],lev);
      status = read_field(var_file[v], lev, var_names[v], &var_in, &nlv, &nxv, &nyv, st_var);
      nxyv = nxv*nyv;
      if (status != 0) break;
     // if (verbose) printf("Done reading %s for time %d - starts at %g %g.\n",
     //   var_names[v],lev,st_var[0],st_var[1]);
      if (nlv != nlay) printf("Mismatch of layers %d vs expected %d.\n",(int) nlv, (int) nlay);

      if ((st_var[0] == st_eta[0]) && (st_var[1] == st_eta[1])) { grid = 0;
        if (verbose && (lev==0)) printf("\t%s is on the h-grid.\n",var_names[v]);
        if ((nyv != ny) || (nxv != nx)) {
          printf("h-grid variable %s is not same size as %s (%d x %d) vs (%d x %d).\n",
              var_names[v],eta_name,(int)nyv,(int)ny,(int)nxv,(int)nx);
          exit(-1);
        }
      }
      else if ((st_var[0] == st_eta[0]) && (st_var[1] != st_eta[1])) { grid = 1;
        if (verbose && (lev==0)) printf("\t%s is on the u-grid.\n",var_names[v]);
        if ((nyv != ny) || (abs((nxv-nx))>1)) {
          printf("u-grid variable %s is not consistent size with %s (%d x %d) vs (%d x %d).\n",
              var_names[v],eta_name,(int)nyv,(int)nxv,(int)ny,(int)nx);
          exit(-1);
        }
   //     printf("%s is on the u-grid.  No accomodation has yet been made for this grid.\n"
      }
      else if ((st_var[1] == st_eta[1]) && (st_var[0] != st_eta[0])) { grid = 2;
        if (verbose && (lev==0)) printf("\t%s is on the v-grid.\n",var_names[v]);
        if ((nxv != nx) || (abs((nyv-ny))>1)) {
          printf("v-grid variable %s is not consistent size with %s (%d x %d) vs (%d x %d).\n",
              var_names[v],eta_name,(int)nyv,(int)nxv,(int)ny,(int)nx);
          exit(-1);
        }
   //     printf("%s is on the v-grid.  No accomodation has yet been made for this grid.\n"
      } else {
        printf("%s is on the q-grid.  No accomodation has yet been made for this grid.\n"
               "Start locations: %g, %g vs %g, %g. Delta %g, %g\n",var_names[v],st_var[1],st_var[0],
                st_eta[1],st_eta[0],st_var[1]-st_eta[1],st_var[0]-st_eta[0]);
        exit(-1);
      }

/*      { int K;
        for (K=0;K<nz;K++) depths[K] = lay_depth[K]; 
      } */
      
      for (j=0;j<nyv;j++) for (i=0;i<nxv;i++) {
        I = i + nxv*j;
        // Interpolate interface height onto the variable's grid.
        if (grid == 0) {
          for (k=0;k<nint;k++) ev[k] = eta[k*nxy+I];
        } if (grid == 1) {
          if (st_var[1] < st_eta[1]) {
            if (i==0) {
              if (nx!=nxv) for (k=0;k<nint;k++) ev[k] = eta[k*nxy+j*nx];
              else for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx]+eta[k*nxy+j*nx+nx-1]);
            }
            else if ((i==nxv-1)&&(nxv>nx)) {
              for (k=0;k<nint;k++) ev[k] = eta[k*nxy+j*nx+i-1];
            }
            else for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+j*nx+i-1]);
          } else {
            if (i==nx-1) for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+j*nx]);
            else for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+j*nx+i+1]);
          }
        } else if (grid == 2) {
          if (st_var[0] < st_eta[0]) {
            if (j==0) {
              if (ny!=nyv) for (k=0;k<nint;k++) ev[k] = eta[k*nxy+i];
              else for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+(ny-1)*nx+i]);
            }
            else if ((j==nyv-1)&&(nyv>ny)) {
              for (k=0;k<nint;k++) ev[k] = eta[k*nxy+(j-1)*nx+i];
            }
            else for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+(j-1)*nx+i]);
          } else {
            if (j==ny-1) for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+i]);
            else for (k=0;k<nint;k++) ev[k] = 0.5*(eta[k*nxy+j*nx+i]+eta[k*nxy+(j+1)*nx+i]);
          }
        }
        
        {
          int K, ktop=0, kbot=0;
          double z_sbl = 0.0, z_bbl = 0.0;
//          double e_bot;
          for (k=0;k<nlay;k++) elc[k] = 0.5*(ev[k]+ev[k+1]);
          for (k=0;k<nlay;k++) {
            if (((ev[0]-elc[k]) > 2.0*nlay*EPSILON) && (var_in[k*nxyv+I] != missing_value))
              {ktop = k; z_sbl = elc[k]; break;}
          }
          for (k=nlay-1;k>=0;k--) {
            if (((elc[k]-ev[nint-1]) > 2.0*nlay*EPSILON) && (var_in[k*nxyv+I] != missing_value))
              {kbot = k; z_bbl = elc[k]; break;}
          }

          // Fill in massless interior layers with values from above.
          for (k=ktop+1;k<kbot;k++) {
            if ((ev[k]-ev[k+1]) < 2.0*EPSILON) var_in[k*nxyv+I] = var_in[(k-1)*nxyv+I];
            if (var_in[k*nxyv+I] == missing_value) var_in[k*nxyv+I] = var_in[(k-1)*nxyv+I];
          }
          // Interpolate var into depth space.
          k=ktop;
//          if (z_bbl < 0.0)
//            e_bot = ev[nint-1];
          for (K=0;K<nz;K++) {
            if (lay_depth[K] > z_sbl)
              var_out[K*nxyv+I] = var_in[ktop*nxyv+I];
            else if (lay_depth[K] < ev[nint-1])
              var_out[K*nxyv+I] = missing;
            else if
              (lay_depth[K] < z_bbl) var_out[K*nxyv+I] = var_in[kbot*nxyv+I];
            else {
              while ((lay_depth[K] < elc[k]) && (k <= kbot)) k++;

              if ((lay_depth[K] >= elc[k]) && (lay_depth[K] <= elc[k-1])) {
                var_out[K*nxyv+I] = var_in[k*nxyv+I];
                /**/
                if (fabs(elc[k-1]-elc[k]) > EPSILON)
                  var_out[K*nxyv+I] += (var_in[(k-1)*nxyv+I] - var_in[k*nxyv+I]) *
                    ((lay_depth[K] - elc[k]) / (elc[k-1]-elc[k]));
                   /* */
              } else {
                printf("Unexpected error: k = %d, ktop = %d, kbot = %d, Depth %g is not between %g and %g.\n",
                        k,ktop,kbot,lay_depth[K],elc[k-1],elc[k]);
              }
            }

          }
        }
        
      }
      
      // if (verbose) printf("Done interpolating %s for time %d.\n",var_names[v],lev);
      write_field(lev,v,var_out);
      // if (verbose) printf("Done writing %s for time %d.\n",var_names[v],lev);
    }

    // if (verbose) printf("Start copying time at %d.\n",lev);
    copy_time_vals(lev);
    // if (verbose) printf("Done copying time at %d.\n",lev);
    
    // status = nc_sync(ncOutid);
    // if (status != NC_NOERR) handle_error(status,out_file,status);
  }

  nc_close(ncOutid);
  if (verbose) printf("Done: successfully created %s.\n",out_file);
  for (i=0;i<num_files;i++) if (ncInid[i] >= 0) nc_close(ncInid[i]);

}
コード例 #24
0
ファイル: mb_close.c プロジェクト: schwehr/mb-system
/*--------------------------------------------------------------------*/
int mb_close(int verbose, void **mbio_ptr, int *error) {
	char *function_name = "mb_close";
	int status = MB_SUCCESS;
	struct mb_io_struct *mb_io_ptr;

	/* print input debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> called\n", function_name);
		fprintf(stderr, "dbg2  Input arguments:\n");
		fprintf(stderr, "dbg2       verbose:    %d\n", verbose);
		fprintf(stderr, "dbg2       mbio_ptr:   %p\n", (void *)*mbio_ptr);
	}

	/* get pointer to mbio descriptor */
	mb_io_ptr = (struct mb_io_struct *)*mbio_ptr;

	/* deallocate format dependent structures */
	status = (*mb_io_ptr->mb_io_format_free)(verbose, *mbio_ptr, error);

	/* deallocate system dependent structures */
	/*status = (*mb_io_ptr->mb_io_store_free)
	        (verbose,*mbio_ptr,&(mb_io_ptr->store_data),error);*/

	/* deallocate memory for arrays within the mbio descriptor */
	if (mb_io_ptr->filetype == MB_FILETYPE_XDR && mb_io_ptr->xdrs != NULL)
		status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->xdrs, error);
	if (mb_io_ptr->filetype == MB_FILETYPE_XDR && mb_io_ptr->xdrs2 != NULL)
		status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->xdrs2, error);
	if (mb_io_ptr->filetype == MB_FILETYPE_XDR && mb_io_ptr->xdrs3 != NULL)
		status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->xdrs3, error);
	if (mb_io_ptr->hdr_comment != NULL)
		status = mb_freed(verbose, __FILE__, __LINE__, (void **)&mb_io_ptr->hdr_comment, error);
	status = mb_deall_ioarrays(verbose, *mbio_ptr, error);

	/* close the files if normal */
	if (mb_io_ptr->filetype == MB_FILETYPE_NORMAL || mb_io_ptr->filetype == MB_FILETYPE_XDR) {
		if (mb_io_ptr->mbfp != NULL)
			fclose(mb_io_ptr->mbfp);
		if (mb_io_ptr->mbfp2 != NULL)
			fclose(mb_io_ptr->mbfp2);
		if (mb_io_ptr->mbfp3 != NULL)
			fclose(mb_io_ptr->mbfp3);
	}

	/* else handle single normal files to be closed with mb_fileio_close() */
	else if (mb_io_ptr->filetype == MB_FILETYPE_SINGLE) {
		status = mb_fileio_close(verbose, *mbio_ptr, error);
	}

	/* else if gsf then use gsfClose */
	else if (mb_io_ptr->filetype == MB_FILETYPE_GSF) {
		gsfClose((int)mb_io_ptr->gsfid);
	}

	/* else if netcdf then use nc_close */
	else if (mb_io_ptr->filetype == MB_FILETYPE_NETCDF) {
		if (mb_io_ptr->filemode == MB_FILEMODE_WRITE)
			nc_enddef(mb_io_ptr->ncid);
		nc_close(mb_io_ptr->ncid);
	}

	/* else handle surf files to be opened with libsapi */
	else if (mb_io_ptr->filetype == MB_FILETYPE_SURF) {
		SAPI_close();
	}

	/* deallocate UTM projection if required */
	if (mb_io_ptr->projection_initialized == MB_YES) {
		mb_io_ptr->projection_initialized = MB_NO;
		mb_proj_free(verbose, &(mb_io_ptr->pjptr), error);
	}

	/* deallocate the mbio descriptor */
	status = mb_freed(verbose, __FILE__, __LINE__, (void **)mbio_ptr, error);

	/* print output debug statements */
	if (verbose >= 2) {
		fprintf(stderr, "\ndbg2  MBIO function <%s> completed\n", function_name);
		fprintf(stderr, "dbg2  Return value:\n");
		fprintf(stderr, "dbg2       error:      %d\n", *error);
		fprintf(stderr, "dbg2  Return status:\n");
		fprintf(stderr, "dbg2       status:  %d\n", status);
	}

	return (status);
}
コード例 #25
0
OSErr NetCDFWindMoverCurv::ReadTimeData(long index,VelocityFH *velocityH, char* errmsg) 
{
	OSErr err = 0;
	long i,j;
	char path[256], outPath[256]; 
	char *velUnits=0;
	int status, ncid, numdims;
	int wind_ucmp_id, wind_vcmp_id, angle_id, uv_ndims;
	static size_t wind_index[] = {0,0,0,0}, angle_index[] = {0,0};
	static size_t wind_count[4], angle_count[2];
	size_t velunit_len;
	float *wind_uvals = 0,*wind_vvals = 0, fill_value=-1e-72, velConversion=1.;
	short *wind_uvals_Navy = 0,*wind_vvals_Navy = 0, fill_value_Navy;
	float *angle_vals = 0;
	long totalNumberOfVels = fNumRows * fNumCols;
	VelocityFH velH = 0;
	long latlength = fNumRows;
	long lonlength = fNumCols;
	float scale_factor = 1.,angle = 0.,u_grid,v_grid;
	Boolean bRotated = true, fIsNavy = false, bIsNWSSpeedDirData = false;
	
	errmsg[0]=0;
	
	strcpy(path,fPathName);
	if (!path || !path[0]) return -1;
	
	status = nc_open(path, NC_NOWRITE, &ncid);
	//if (status != NC_NOERR) {err = -1; goto done;}
	if (status != NC_NOERR)
	{
#if TARGET_API_MAC_CARBON
		err = ConvertTraditionalPathToUnixPath((const char *) path, outPath, kMaxNameLen) ;
		status = nc_open(outPath, NC_NOWRITE, &ncid);
#endif
		if (status != NC_NOERR) {err = -1; goto done;}
	}
	status = nc_inq_ndims(ncid, &numdims);
	if (status != NC_NOERR) {err = -1; goto done;}
	
	wind_index[0] = index;	// time 
	wind_count[0] = 1;	// take one at a time
	if (numdims>=4)	// should check what the dimensions are, CO-OPS uses sigma
	{
		wind_count[1] = 1;	// depth
		wind_count[2] = latlength;
		wind_count[3] = lonlength;
	}
	else
	{
		wind_count[1] = latlength;	
		wind_count[2] = lonlength;
	}
	angle_count[0] = latlength;
	angle_count[1] = lonlength;
	
	//wind_count[0] = latlength;		// a fudge for the PWS format which has u(lat,lon) not u(time,lat,lon)
	//wind_count[1] = lonlength;
	
	if (fIsNavy)
	{
		// need to check if type is float or short, if float no scale factor?
		wind_uvals = new float[latlength*lonlength]; 
		if(!wind_uvals) {TechError("GridVel::ReadNetCDFFile()", "new[]", 0); err = memFullErr; goto done;}
		wind_vvals = new float[latlength*lonlength]; 
		if(!wind_vvals) {TechError("GridVel::ReadNetCDFFile()", "new[]", 0); err = memFullErr; goto done;}
		
		angle_vals = new float[latlength*lonlength]; 
		if(!angle_vals) {TechError("GridVel::ReadNetCDFFile()", "new[]", 0); err = memFullErr; goto done;}
		status = nc_inq_varid(ncid, "air_gridu", &wind_ucmp_id);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_varid(ncid, "air_gridv", &wind_vcmp_id);	
		if (status != NC_NOERR) {err = -1; goto done;}
		
		status = nc_get_vara_float(ncid, wind_ucmp_id, wind_index, wind_count, wind_uvals);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_get_vara_float(ncid, wind_vcmp_id, wind_index, wind_count, wind_vvals);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_get_att_float(ncid, wind_ucmp_id, "_FillValue", &fill_value);
		//if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_get_att_float(ncid, wind_ucmp_id, "scale_factor", &scale_factor);
		//if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_inq_varid(ncid, "grid_orient", &angle_id);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_get_vara_float(ncid, angle_id, angle_index, angle_count, angle_vals);
		if (status != NC_NOERR) {/*err = -1; goto done;*/bRotated = false;}
	}
	else
	{
		wind_uvals = new float[latlength*lonlength]; 
		if(!wind_uvals) {TechError("NetCDFWindMoverCurv::ReadTimeData()", "new[]", 0); err = memFullErr; goto done;}
		wind_vvals = new float[latlength*lonlength]; 
		if(!wind_vvals) {TechError("NetCDFWindMoverCurv::ReadTimeData()", "new[]", 0); err = memFullErr; goto done;}
		status = nc_inq_varid(ncid, "air_u", &wind_ucmp_id);
		if (status != NC_NOERR)
		{
			status = nc_inq_varid(ncid, "u", &wind_ucmp_id);
			if (status != NC_NOERR)
			{
				status = nc_inq_varid(ncid, "U", &wind_ucmp_id);
				if (status != NC_NOERR)
				{
					status = nc_inq_varid(ncid, "WindSpd_SFC", &wind_ucmp_id);
					if (status != NC_NOERR)
					{err = -1; goto done;}
					bIsNWSSpeedDirData = true;
				}
				//{err = -1; goto done;}
			}
			//{err = -1; goto done;}
		}
		if (bIsNWSSpeedDirData)
		{
			status = nc_inq_varid(ncid, "WindDir_SFC", &wind_vcmp_id);
			if (status != NC_NOERR)
			{err = -2; goto done;}
		}
		else
		{
			status = nc_inq_varid(ncid, "air_v", &wind_vcmp_id);
			if (status != NC_NOERR) 
			{
				status = nc_inq_varid(ncid, "v", &wind_vcmp_id);
				if (status != NC_NOERR) 
				{
					status = nc_inq_varid(ncid, "V", &wind_vcmp_id);
					if (status != NC_NOERR)
					{err = -1; goto done;}
				}
				//{err = -1; goto done;}
			}
		}
		
		status = nc_inq_varndims(ncid, wind_ucmp_id, &uv_ndims);
		if (status==NC_NOERR){if (uv_ndims < numdims && uv_ndims==3) {wind_count[1] = latlength; wind_count[2] = lonlength;}}	// could have more dimensions than are used in u,v
		
		status = nc_get_vara_float(ncid, wind_ucmp_id, wind_index, wind_count, wind_uvals);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_get_vara_float(ncid, wind_vcmp_id, wind_index, wind_count, wind_vvals);
		if (status != NC_NOERR) {err = -1; goto done;}
		status = nc_get_att_float(ncid, wind_ucmp_id, "_FillValue", &fill_value);
		if (status != NC_NOERR) 
		{
			status = nc_get_att_float(ncid, wind_ucmp_id, "Fill_Value", &fill_value);
			if (status != NC_NOERR)
			{
				status = nc_get_att_float(ncid, wind_ucmp_id, "fillValue", &fill_value);// nws 2.5km
				if (status != NC_NOERR)
				{
					status = nc_get_att_float(ncid, wind_ucmp_id, "missing_value", &fill_value);
				}
				/*if (status != NC_NOERR)*//*err = -1; goto done;*/}}	// don't require
		//if (status != NC_NOERR) {err = -1; goto done;}	// don't require
	}	
	
	status = nc_inq_attlen(ncid, wind_ucmp_id, "units", &velunit_len);
	if (status == NC_NOERR)
	{
		velUnits = new char[velunit_len+1];
		status = nc_get_att_text(ncid, wind_ucmp_id, "units", velUnits);
		if (status == NC_NOERR)
		{
			velUnits[velunit_len] = '\0'; 
			if (!strcmpnocase(velUnits,"knots"))
				velConversion = KNOTSTOMETERSPERSEC;
			else if (!strcmpnocase(velUnits,"m/s"))
				velConversion = 1.0;
		}
	}
	
	
	status = nc_close(ncid);
	if (status != NC_NOERR) {err = -1; goto done;}
	
	velH = (VelocityFH)_NewHandleClear(totalNumberOfVels * sizeof(VelocityFRec));
	if (!velH) {err = memFullErr; goto done;}
	//for (i=0;i<totalNumberOfVels;i++)
	for (i=0;i<latlength;i++)
	{
		for (j=0;j<lonlength;j++)
		{
			if (wind_uvals[(latlength-i-1)*lonlength+j]==fill_value)
				wind_uvals[(latlength-i-1)*lonlength+j]=0.;
			if (wind_vvals[(latlength-i-1)*lonlength+j]==fill_value)
				wind_vvals[(latlength-i-1)*lonlength+j]=0.;
			if (isnan(wind_uvals[(latlength-i-1)*lonlength+j])) 
				wind_uvals[(latlength-i-1)*lonlength+j]=0.;
			if (isnan(wind_vvals[(latlength-i-1)*lonlength+j])) 
				wind_vvals[(latlength-i-1)*lonlength+j]=0.;

			if (fIsNavy)
			{
				u_grid = (float)wind_uvals[(latlength-i-1)*lonlength+j];
				v_grid = (float)wind_vvals[(latlength-i-1)*lonlength+j];
				if (bRotated) angle = angle_vals[(latlength-i-1)*lonlength+j];
				INDEXH(velH,i*lonlength+j).u = u_grid*cos(angle*PI/180.)-v_grid*sin(angle*PI/180.);
				INDEXH(velH,i*lonlength+j).v = u_grid*sin(angle*PI/180.)+v_grid*cos(angle*PI/180.);
			}
			else if (bIsNWSSpeedDirData)
			{
				//INDEXH(velH,i*lonlength+j).u = KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * sin ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]);	// need units
				//INDEXH(velH,i*lonlength+j).v = KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * cos ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]);
				// since direction is from rather than to need to switch the sign
				//INDEXH(velH,i*lonlength+j).u = -1. * KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * sin ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]);	// need units
				//INDEXH(velH,i*lonlength+j).v = -1. * KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * cos ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]);
				INDEXH(velH,i*lonlength+j).u = -1. * velConversion * wind_uvals[(latlength-i-1)*lonlength+j] * sin ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]);	// need units
				INDEXH(velH,i*lonlength+j).v = -1. * velConversion * wind_uvals[(latlength-i-1)*lonlength+j] * cos ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]);
			}
			else
			{
				// Look for a land mask, but do this if don't find one - float mask(lat,lon) - 1,0 which is which?
				//if (wind_uvals[(latlength-i-1)*lonlength+j]==0. && wind_vvals[(latlength-i-1)*lonlength+j]==0.)
				//wind_uvals[(latlength-i-1)*lonlength+j] = wind_vvals[(latlength-i-1)*lonlength+j] = 1e-06;
				
				// just leave fillValue as velocity for new algorithm - comment following lines out
				// should eliminate the above problem, assuming fill_value is a land mask
				// leave for now since not using a map...use the entire grid
				/////////////////////////////////////////////////
				
				INDEXH(velH,i*lonlength+j).u = /*KNOTSTOMETERSPERSEC**/velConversion*wind_uvals[(latlength-i-1)*lonlength+j];	// need units
				INDEXH(velH,i*lonlength+j).v = /*KNOTSTOMETERSPERSEC**/velConversion*wind_vvals[(latlength-i-1)*lonlength+j];
			}
		}
	}
	*velocityH = velH;
	fFillValue = fill_value;
	
	fWindScale = scale_factor;	// hmm, this forces a reset of scale factor each time, overriding any set by hand
	
done:
	if (err)
	{
		if (err==-2)
			strcpy(errmsg,"Error reading wind data from NetCDF file");
		else
			strcpy(errmsg,"Error reading wind direction data from NetCDF file");
		// We don't want to put up an error message here because it can lead to an infinite loop of messages.
		//printNote("Error opening NetCDF file");
		if(velH) {DisposeHandle((Handle)velH); velH = 0;}
	}
	if (wind_uvals) {delete [] wind_uvals; wind_uvals = 0;}
	if (wind_vvals) {delete [] wind_vvals; wind_vvals = 0;}
	if (angle_vals) {delete [] angle_vals; angle_vals = 0;}
	return err;
}
コード例 #26
0
ファイル: tst_utf8.c プロジェクト: Federico2014/edg4x-rose
int
main(int argc, char **argv)
{
   printf("\n*** Testing UTF-8 names.\n");
   printf("*** creating UTF-8 names in classic model netcdf files...");
   {
      int ncid, varid, dimids[NDIMS];
      int f;

      for (f = NC_FORMAT_CLASSIC; f < NC_FORMAT_NETCDF4_CLASSIC; f++)
      {
	 if (nc_set_default_format(f, NULL)) ERR;
	 if (nc_create(FILE_NAME, NC_CLOBBER, &ncid)) ERR;
      
	 /* Define various netcdf objects with a Unicode UTF-8 encoded name
	  * that must be normalized. Where possible, also use the utf8
	  * string as the value. The name will be normalized, but not the
	  * value. */
	 if (nc_def_dim(ncid, name_utf8, NX, &dimids[0])) ERR;
	 if (nc_def_var(ncid, name_utf8, NC_CHAR, NDIMS, dimids, &varid)) ERR;
	 if (nc_put_att_text(ncid, varid, name_utf8, sizeof(name_utf8), name_utf8)) ERR;
      
	 if (nc_enddef(ncid)) ERR;
      
	 /* Write var data. */
	 if (nc_put_var_text(ncid, varid, name_utf8)) ERR;
      
	 /* Check the file. */
	 check_classic_file(ncid);
      
	 if (nc_close(ncid)) ERR;
      
	 /* Reopen the file and check again. */
	 if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
	 check_classic_file(ncid);
	 if (nc_close(ncid)) ERR;
      } /* next format */
   }
   SUMMARIZE_ERR;

#define DIM1_NAME "d1"
#define VAR1_NAME "v1"
#define ATT1_NAME "a1"

   printf("*** renaming to UTF-8 names in classic model netcdf files...");
   {
      int ncid, varid, dimids[NDIMS];
      int f;

      for (f = NC_FORMAT_CLASSIC; f < NC_FORMAT_NETCDF4_CLASSIC; f++)
      {
	 if (nc_set_default_format(f, NULL)) ERR;
	 if (nc_create(FILE_NAME, NC_CLOBBER, &ncid)) ERR;
      
	 /* Create objects. */
	 if (nc_def_dim(ncid, DIM1_NAME, NX, &dimids[0])) ERR;
	 if (nc_rename_dim(ncid, 0, name_utf8)) ERR;
 	 if (nc_def_var(ncid, name_utf8, NC_CHAR, NDIMS, dimids, &varid)) ERR; 
 	 if (nc_put_att_text(ncid, varid, ATT1_NAME, sizeof(name_utf8), name_utf8)) ERR; 
 	 if (nc_rename_att(ncid, 0, ATT1_NAME, name_utf8)) ERR; 
      
	 if (nc_enddef(ncid)) ERR;
      
	 /* Write var data. */
	 if (nc_put_var_text(ncid, varid, name_utf8)) ERR;
      
	 /* Check the file. */
	 check_classic_file(ncid);
      
	 if (nc_close(ncid)) ERR;
      
	 /* Reopen the file and check again. */
	 if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
	 check_classic_file(ncid);
	 if (nc_close(ncid)) ERR;
      } /* next format */
   }
   SUMMARIZE_ERR;

   printf("*** creating UTF-8 names in netcdf-4 file...");
   {
      int ncid, varid, grpid, comp_typeid, enum_typeid, grpid2, grpid3;
      int dimids[NDIMS];
      char my_int = ENUM_VALUE;
      
      if (nc_create(FILE_NAME, NC_NETCDF4 | NC_CLOBBER, &ncid)) ERR;
      
      /* Define various netcdf objects with a Unicode UTF-8 encoded name
       * that must be normalized. Where possible, also use the utf8
       * string as the value. The name will be normalized, but not the
       * value. */
      if (nc_def_grp(ncid, name_utf8, &grpid)) ERR;
      if (nc_def_dim(grpid, name_utf8, NX, &dimids[0])) ERR;
      if (nc_def_var(grpid, name_utf8, NC_CHAR, NDIMS, dimids, &varid)) ERR;
      if (nc_put_att_text(grpid, varid, name_utf8, sizeof(name_utf8), name_utf8)) ERR;
      
      if (nc_def_grp(grpid, "tmp", &grpid2)) ERR;
      if (nc_def_enum(grpid2, NC_BYTE, name_utf8, &enum_typeid)) ERR;
      if (nc_insert_enum(grpid2, enum_typeid, name_utf8, &my_int)) ERR;
      
      if (nc_def_grp(grpid2, "tmp", &grpid3)) ERR;
      if (nc_def_compound(grpid3, sizeof(struct comp), name_utf8, &comp_typeid)) ERR;
      if (nc_insert_compound(grpid3, comp_typeid, name_utf8, offsetof(struct comp, i), NC_INT)) ERR;
      
      /* Write var data. */
      if (nc_put_var_text(grpid, varid, name_utf8)) ERR;
      
      /* Check the file. */
      check_nc4_file(ncid);
      
      if (nc_close(ncid)) ERR;
      
      /* Reopen the file and check again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      check_nc4_file(ncid);
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #27
0
ファイル: read_netcdf.c プロジェクト: RHESSys/RHESSys
int get_netcdf_xy(char *netcdf_filename, char *nlat_name, char *nlon_name,
				  float rlat, float rlon, float sd, float *y, float *x){
	/***Read netcdf format metdata by using lat,lon as index and return x, y coords
	 rlat,rlon: latitue and longitude of site location
	 sd: the minimum distance for searching nearby grid in netcdf
	 ************************************************************/
	
	int ncid, nlatid,nlontid;
	int latid,lontid;
	size_t nlat,nlont;
	int ndims_in, nvars_in, ngatts_in, unlimdimid_in;
	float *lat,*lont;
	size_t start[3],count[3];
	int retval;
	int idlat,idlont;	//offset
	/*printf("\n   Opening netcdf file... %s lat=%lf lon=%lf sd=%lf",
		   netcdf_filename,
		   rlat,
		   rlon,
		   sd);*/
	/***open netcdf***/
	if((retval = nc_open(netcdf_filename, NC_NOWRITE, &ncid)))
		ERR(retval);
	if((retval = nc_inq(ncid, &ndims_in, &nvars_in, &ngatts_in,
                        &unlimdimid_in)))
		ERR(retval);
	//printf("\n   ncid=%d ndims_in=%d nvars_in=%d ngatts_in=%d unlimdimid_in=%d\n",ncid, ndims_in, nvars_in, ngatts_in, unlimdimid_in);
	/***Get the dimension and var id***/
	if((retval = nc_inq_dimid(ncid, nlat_name, &nlatid)))
		ERR(retval);
	if((retval = nc_inq_dimid(ncid, nlon_name, &nlontid)))
		ERR(retval);
	if((retval = nc_inq_dimlen(ncid,nlatid, &nlat)))
		ERR(retval);
	if((retval = nc_inq_dimlen(ncid,nlontid, &nlont)))
		ERR(retval);
  	/* Get the varids of variables. */
	if ((retval = nc_inq_varid(ncid, nlat_name, &latid)))
		ERR(retval);
	if ((retval = nc_inq_varid(ncid, nlon_name, &lontid)))
		ERR(retval);
	
	lat = (float *) alloc(nlat * sizeof(float),"lat","get_netcdf_xy");
	lont = (float *) alloc(nlont * sizeof(float),"lont","get_netcdf_xy");
	/* get dimention var */
	if ((retval = nc_get_var_float(ncid, latid, &lat[0]))){
		free(lat);
		free(lont);	
		ERR(retval);
	}
	if ((retval = nc_get_var_float(ncid, lontid, &lont[0]))){
		free(lat);
		free(lont);	
		ERR(retval);
	}

	/*locate the record */
	idlat = locate(lat,nlat,rlat,sd);
	idlont = locate(lont,nlont,rlon,sd);
	if(idlat == -1 || idlont == -1){
		fprintf(stderr,"can't locate the station\n");
		free(lat);
		free(lont);	
		return -1;
	}
	else {
		*x = lont[idlont];
		*y = lat[idlat];
	}
	
	if ((retval = nc_close(ncid))){
		free(lat);
		free(lont);
		ERR(retval);
	}
	
	free(lat);
	free(lont);
	return 0;
}
コード例 #28
0
/**
 * Destructor of a netCDF-writer.
 */
io::NetCdfWriter::~NetCdfWriter() {
	nc_close(dataFile);
}
コード例 #29
0
ファイル: server.c プロジェクト: JimBrv/of-config
int
main(int argc, char **argv)
{
    const char *optstring = "d:fhv:";

    const struct option longopts[] = {
        {"db", required_argument, 0, 'd'},
        {"foreground", no_argument, 0, 'f'},
        {"help", no_argument, 0, 'h'},
        {"verbose", required_argument, 0, 'v'},
        {0, 0, 0, 0}
    };
    int longindex, next_option;
    int verbose = 0;
    int retval = EXIT_SUCCESS, r;
    char *aux_string;
    struct sigaction action;
    sigset_t block_mask;

    struct {
        struct ncds_ds *server;
        ncds_id server_id;
        struct ncds_ds *ofc;
        ncds_id ofc_id;
    } ds = {NULL, -1, NULL, -1};

    /* connection channel to agents */
    comm_t *c = NULL;

    /* initialize message system and set verbose and debug variables */
    if ((aux_string = getenv(ENVIRONMENT_VERBOSE)) == NULL) {
        /* default verbose level */
        verbose = NC_VERB_ERROR;
    } else {
        verbose = atoi(aux_string);
    }

    /* parse given options */
    while ((next_option = getopt_long(argc, argv, optstring, longopts,
                                      &longindex)) != -1) {
        switch (next_option) {
        case 'd':
            ovsdb_path = strdup(optarg);
            break;
        case 'f':
            ofc_daemonize = 0;
            break;
        case 'h':
            print_usage(argv[0]);
            break;
        case 'v':
            verbose = atoi(optarg);
            break;
        default:
            print_usage(argv[0]);
            break;
        }
    }

    /* set signal handler */
    sigfillset(&block_mask);
    action.sa_handler = signal_handler;
    action.sa_mask = block_mask;
    action.sa_flags = 0;
    sigaction(SIGINT, &action, NULL);
    sigaction(SIGQUIT, &action, NULL);
    sigaction(SIGABRT, &action, NULL);
    sigaction(SIGTERM, &action, NULL);
    sigaction(SIGKILL, &action, NULL);

    /* set verbose message printer callback */
    nc_callback_print(clb_print);

    /* normalize value if not from the enum */
    if (verbose < NC_VERB_ERROR) {
        nc_verbosity(NC_VERB_ERROR);
    } else if (verbose > NC_VERB_DEBUG) {
        nc_verbosity(NC_VERB_DEBUG);
    } else {
        nc_verbosity(verbose);
    }

    /* go to the background as a daemon */
    if (ofc_daemonize == 1) {
        if (daemon(0, 0) != 0) {
            nc_verb_error("Going to background failed (%s)", strerror(errno));
            return (EXIT_FAILURE);
        }
        openlog("ofc-server", LOG_PID, LOG_DAEMON);
    } else {
        openlog("ofc-server", LOG_PID | LOG_PERROR, LOG_DAEMON);
    }

    /* make sure we have sufficient rights to communicate with OVSDB */
    /* TODO */

    /* init libnetconf for a multilayer server */
    r = nc_init((NC_INIT_ALL & ~NC_INIT_NACM) | NC_INIT_MULTILAYER);
    if (r < 0) {
        nc_verb_error("libnetconf initialization failed.");
        return (EXIT_FAILURE);
    }

    /* Initiate communication subsystem for communication with agents */
    if ((c = comm_init(r)) == NULL) {
        nc_verb_error("Communication subsystem not initiated.");
        return (EXIT_FAILURE);
    }

    /* prepare the ietf-netconf-server module */
    ncds_add_model(OFC_DATADIR
                   "/ietf-netconf-server/ietf-x509-cert-to-name.yin");
    ds.server =
        ncds_new_transapi_static(NCDS_TYPE_FILE,
                                 OFC_DATADIR
                                 "/ietf-netconf-server/ietf-netconf-server.yin",
                                 &server_transapi);
    if (ds.server == NULL) {
        retval = EXIT_FAILURE;
        nc_verb_error("Creating ietf-netconf-server datastore failed.");
        goto cleanup;
    }
    ncds_file_set_path(ds.server,
                       OFC_DATADIR "/ietf-netconf-server/datastore.xml");
    ncds_feature_enable("ietf-netconf-server", "ssh");
    ncds_feature_enable("ietf-netconf-server", "inbound-ssh");
    if ((ds.server_id = ncds_init(ds.server)) < 0) {
        retval = EXIT_FAILURE;
        nc_verb_error
            ("Initiating ietf-netconf-server datastore failed (error code %d).",
             ds.ofc_id);
        goto cleanup;
    }

    /* prepare the of-config module */
    ds.ofc = ncds_new_transapi_static(NCDS_TYPE_CUSTOM,
                                      OFC_DATADIR "/of-config/of-config.yin",
                                      &ofc_transapi);
    if (ds.ofc == NULL) {
        retval = EXIT_FAILURE;
        nc_verb_error("Creating of-config datastore failed.");
        goto cleanup;
    }
    ncds_custom_set_data(ds.ofc, NULL, &ofcds_funcs);
    if ((ds.ofc_id = ncds_init(ds.ofc)) < 0) {
        retval = EXIT_FAILURE;
        nc_verb_error("Initiating of-config datastore failed (error code %d).",
                      ds.ofc_id);
        goto cleanup;
    }

    if (ncds_consolidate() != 0) {
        retval = EXIT_FAILURE;
        nc_verb_error("Consolidating data models failed.");
        goto cleanup;
    }

    if (ncds_device_init(&(ds.server_id), NULL, 1) != 0) {
        retval = EXIT_FAILURE;
        nc_verb_error("Initiating ietf-netconf-server module failed.");
        goto cleanup;
    }

    if (ncds_device_init(&(ds.ofc_id), NULL, 1) != 0) {
        retval = EXIT_FAILURE;
        nc_verb_error("Initiating of-config module failed.");
        goto cleanup;
    }

    nc_verb_verbose("OF-CONFIG server successfully initialized.");

    while (!mainloop) {
        comm_loop(c, 500);
    }

cleanup:

    /* cleanup */
    nc_close();

    return (retval);
}
コード例 #30
0
ファイル: NCCncAttributes.c プロジェクト: amiara/RGIS
int main (int argc,char *argv [])
{
	int argPos, argNum = argc, ncid, varid;
	double range[2];
	char *title = NULL, *type = NULL, *domain = NULL, *subject = NULL, *ref = NULL, *inst = NULL, *source = NULL, *comments = NULL;
	VarNode_t *head, *last;
	if((last = head = malloc(sizeof(VarNode_t))) == (VarNode_t *) NULL)
		{ CMmsgPrint (CMmsgAppError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); }
	for (argPos = 1;argPos < argNum;)
	{
		if (CMargTest(argv[argPos],"-h","--help"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            {
                            doHelp(CMprgName(argv[0]),0);
                            break;
                            }
                        else
                            doHelp(CMprgName(argv[0]),(strcmp(argv[argPos],"extend") == 0) ||
                                                      (strcmp(argv[argPos],"e")      == 0));
			continue;
		}
		if (CMargTest(argv[argPos],"-l","--longname"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing variable Name!"); return (CMfailed); }
			last->text = true;
			last->var = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing Long Name!"); return (CMfailed); }
			last->dat = argv[argPos];
			last->attrib = NCnameVALongName;
			if((last = last->next = malloc(sizeof(VarNode_t))) == NULL)
				{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); }
			last->dat = last->dat2 = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-n","--standardname"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing variable Name!"); return (CMfailed); }
			last->text = true;
			last->var = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing Standard Name!"); return (CMfailed); }
			last->dat = argv[argPos];
			last->attrib = NCnameVAStandardName;
			if((last = last->next = malloc(sizeof(VarNode_t))) == NULL)
                            { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d"); return(CMfailed); }
			last->dat = last->dat2 = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-U","--units"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing variable!"); return (CMfailed); }
			last->text = true;
			last->var = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing Units!"); return (CMfailed); }
			last->dat = argv[argPos];
			last->attrib = NCnameVAUnits;
			if((last = last->next = malloc(sizeof(VarNode_t))) == NULL)
				{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); }
			last->dat = last->dat2 = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-v","--validrange"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing variable!"); return (CMfailed); }
// ********************        CHECK HERE!!! ************************
			last->text = false;
			last->var = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing upper range!"); return (CMfailed); }
			last->dat = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing lower range!"); return (CMfailed); }
			last->dat2 = argv[argPos];
			last->attrib = NCnameVAValidRange;
			if((last = last->next = malloc(sizeof(VarNode_t))) == NULL)
				{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); }
			last->dat = last->dat2 = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-o","--offset"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing variable!"); return (CMfailed); }
			last->text = false;
			last->var = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
                            { CMmsgPrint (CMmsgUsrError, "Missing offset!"); return (CMfailed); }
			last->dat = argv[argPos];
			last->attrib = NCnameVAAddOffset;
			if((last = last->next = malloc(sizeof(VarNode_t))) == NULL)
                            { CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(CMfailed); }
			last->dat = last->dat2 = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-s","--scalefactor"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing variable!"); return (CMfailed); }
			last->text = false;
			last->var = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError,"Missing scale factor!"); return (CMfailed); }
			last->dat = argv[argPos];
			last->attrib = NCnameVAScaleFactor;
			if((last = last->next = malloc(sizeof(VarNode_t))) == NULL)
				{ CMmsgPrint (CMmsgSysError, "Memory allocation error in: %s %d",__FILE__,__LINE__); return(NCfailed); }
			last->dat = last->dat2 = (char *) NULL;
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-t","--title"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Title!"); return (CMfailed); }
			title = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-y","--type"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Type!"); return (CMfailed); }
			type = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-d","--domain"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Domain!"); return (CMfailed); }
			domain = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-s","--subject"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Subject!"); return (CMfailed); }
			subject = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-r","--references"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing References!"); return (CMfailed); }
			ref = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-i","--institution"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Institution!"); return (CMfailed); }
			inst = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-s","--source"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Source!"); return (CMfailed); }
			source = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if (CMargTest(argv[argPos],"-c","--comments"))
		{
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos)
				{ CMmsgPrint (CMmsgUsrError, "Missing Comment!"); return (CMfailed); }
			comments = argv[argPos];
			if ((argNum = CMargShiftLeft(argPos,argv,argc)) <= argPos) break;
			continue;
		}
		if ((argv[argPos][0] == '-') && (strlen (argv[argPos]) > 1))
			{ CMmsgPrint (CMmsgUsrError, "Unknown option: %s!",argv[argPos]); return (NCfailed); }
	argPos++;
	}
	last->next = (VarNode_t *) NULL;
	if ((argNum > 1) && (strcmp(argv[1],"-") != 0)) {
		if(nc_open(argv[1],NC_WRITE,&ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error opening file: %s!",argv[1]); return (NCfailed); }
	} else doHelp(CMprgName(argv[0]),1);
	if(nc_redef(ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Cannot place into redef mode!"); return (NCfailed); }

	last = head;
	while(last->next != (VarNode_t *) NULL)
	{
		if(nc_inq_varid(ncid,last->var,&varid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error finding %s variable",last->var); return (NCfailed); }
		if(last->text)
		{
			if(nc_put_att_text(ncid, varid, last->attrib,strlen(last->dat), last->dat) != NC_NOERR)
				{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: %s!", last->attrib); return (NCfailed); }
		}
	  	else
		{
			if(last->dat2 != (char *) NULL)
				{
				range[0] = atof(last->dat);
				range[1] = atof(last->dat2);
				if(nc_put_att_double(ncid, varid, last->attrib,NC_DOUBLE, 2, range) != NC_NOERR)
					{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: %s!", last->attrib); return (NCfailed); }
				}
			else
				{
				range[0] = atof(last->dat);
				if(nc_put_att_double(ncid, varid, last->attrib,NC_DOUBLE, 1, range) != NC_NOERR)
					{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: %s!", last->attrib); return (NCfailed); }
				}
		}
		last = last->next;
	}
	
	if((title != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGATitle,strlen(title), title) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: title!"); return (NCfailed); }
	if(type != NULL) if(nc_put_att_text(ncid, NC_GLOBAL, NCnameGADataType,strlen(type), type) != NC_NOERR)
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute; type!"); return (NCfailed); }
	if((domain != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGADomain, strlen(domain), domain) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: domain!"); return (NCfailed); }
	if((subject != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGASubject, strlen(subject), subject) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: subject!"); return (NCfailed); }
	if((ref != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGAReferences, strlen(ref), ref) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: references!"); return (NCfailed); }
	if((inst != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGAInstitution, strlen(inst), inst) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: institution!"); return (NCfailed); }
	if((source != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGASource, strlen(source), source) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: source!"); return (NCfailed); }
	if((comments != NULL) && (nc_put_att_text(ncid, NC_GLOBAL, NCnameGAComments, strlen(comments), comments) != NC_NOERR))
		{ CMmsgPrint (CMmsgUsrError, "Error changing attribute: comments!"); return (NCfailed); }

	if(nc_close(ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error commiting changes to file!"); return (NCfailed); }
	return 0;
}