Example #1
0
int
main(int argc, char **argv)
{
   printf("\n*** Testing netcdf-4 group functions.\n");
   printf("*** testing use of unlimited dim in parent group...");
   {
#define NDIMS_IN_VAR 1
#define NDIMS_IN_FILE 2
#define BABE_LIMIT 3
#define DIM_NAME1 "Influence"
#define DIM_NAME2 "Babe_Factor"
#define VAR_NAME1 "Court_of_Star_Chamber"
#define VAR_NAME2 "Justice_of_the_Peace"
#define VAR_NAME3 "Bosworth_Field"
      int ncid, dimid1, dimid2, varid1, varid2, varid3, henry_vii_id;
      int grpid_in, varid_in1, varid_in2, varid_in3;
      nc_type xtype_in;
      int ndims_in, dimids_in[NDIMS_IN_FILE], dimid1_in, natts;
      char name_in[NC_MAX_NAME + 1];
      size_t len_in, index[NDIMS_IN_VAR] = {0};
      long long value = NC_FILL_INT64 + 1, value_in;

      /* Create a file with an unlimited dim and a limited, used by
       * variables in child groups. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME1, NC_UNLIMITED, &dimid1)) ERR;
      if (nc_def_dim(ncid, DIM_NAME2, BABE_LIMIT, &dimid2)) ERR;
      if (nc_def_grp(ncid, HENRY_VII, &henry_vii_id)) ERR;
      if (nc_def_var(henry_vii_id, VAR_NAME1, NC_INT64, NDIMS_IN_VAR, &dimid1, &varid1)) ERR;
      if (nc_def_var(henry_vii_id, VAR_NAME2, NC_INT64, NDIMS_IN_VAR, &dimid1, &varid2)) ERR;
      if (nc_def_var(henry_vii_id, VAR_NAME3, NC_INT64, NDIMS_IN_VAR, &dimid2, &varid3)) ERR;

      /* Check it out. Find the group by name. */
      if (nc_inq_ncid(ncid, HENRY_VII, &grpid_in)) ERR;

      /* Ensure that dimensions in parent are visible and correct. */
      if (nc_inq_dimids(grpid_in, &ndims_in, dimids_in, 1)) ERR;
      if (ndims_in != NDIMS_IN_FILE || dimids_in[0] != dimid1 || dimids_in[1] != dimid2) ERR;
      if (nc_inq_dim(grpid_in, dimids_in[0], name_in, &len_in)) ERR;
      if (strcmp(name_in, DIM_NAME1) || len_in != 0) ERR;
      if (nc_inq_dim(grpid_in, dimids_in[1], name_in, &len_in)) ERR;
      if (strcmp(name_in, DIM_NAME2) || len_in != BABE_LIMIT) ERR;

      /* Check the vars in the group. */
      if (nc_inq_varid(grpid_in, VAR_NAME1, &varid_in1)) ERR;
      if (nc_inq_varid(grpid_in, VAR_NAME2, &varid_in2)) ERR;
      if (nc_inq_varid(grpid_in, VAR_NAME3, &varid_in3)) ERR;
      if (varid_in1 != varid1 || varid_in2 != varid2 || varid_in3 != varid3) ERR;
      if (nc_inq_var(grpid_in, varid1, name_in, &xtype_in, &ndims_in, &dimid1_in, &natts)) ERR;
      if (strcmp(name_in, VAR_NAME1) || xtype_in != NC_INT64 || ndims_in != NDIMS_IN_VAR ||
          dimid1_in != dimid1 || natts != 0) ERR;
      if (nc_inq_var(grpid_in, varid2, name_in, &xtype_in, &ndims_in, &dimid1_in, &natts)) ERR;
      if (strcmp(name_in, VAR_NAME2) || xtype_in != NC_INT64 || ndims_in != NDIMS_IN_VAR ||
          dimid1_in != dimid1 || natts != 0) ERR;
      if (nc_inq_var(grpid_in, varid3, name_in, &xtype_in, &ndims_in, &dimid1_in, &natts)) ERR;
      if (strcmp(name_in, VAR_NAME3) || xtype_in != NC_INT64 || ndims_in != NDIMS_IN_VAR ||
          dimid1_in != dimid2 || natts != 0) ERR;

      /* Write one value to one variable. */
      if (nc_put_var1_longlong(grpid_in, varid_in1, index, &value)) ERR;

      /* Read one value from the second unlim dim variable. It should
       * be the fill value. */
      if (nc_get_var1_longlong(grpid_in, varid_in2, index, &value_in)) ERR;
      if (value_in != NC_FILL_INT64) ERR;

      /* Read one value from the variable with limited dim. It should
       * be the fill value. */
      if (nc_get_var1_longlong(grpid_in, varid_in3, index, &value_in)) ERR;
      if (value_in != NC_FILL_INT64) ERR;

      /* Attempt to read beyond end of dimensions to generate error. */
      index[0] = BABE_LIMIT;
      if (nc_get_var1_longlong(grpid_in, varid_in1, index, &value_in) != NC_EINVALCOORDS) ERR;
      if (nc_get_var1_longlong(grpid_in, varid_in2, index, &value_in) != NC_EINVALCOORDS) ERR;
      if (nc_get_var1_longlong(grpid_in, varid_in3, index, &value_in) != NC_EINVALCOORDS) ERR;

      if (nc_close(ncid)) ERR;

      /* Check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      /* Find the group by name. */
      if (nc_inq_ncid(ncid, HENRY_VII, &grpid_in)) ERR;

      /* Ensure that dimensions in parent are visible and correct. */
      if (nc_inq_dimids(grpid_in, &ndims_in, dimids_in, 1)) ERR;
      if (ndims_in != NDIMS_IN_FILE || dimids_in[0] != dimid1 || dimids_in[1] != dimid2) ERR;
      if (nc_inq_dim(grpid_in, dimids_in[0], name_in, &len_in)) ERR;
      if (strcmp(name_in, DIM_NAME1) || len_in != 1) ERR;
      if (nc_inq_dim(grpid_in, dimids_in[1], name_in, &len_in)) ERR;
      if (strcmp(name_in, DIM_NAME2) || len_in != BABE_LIMIT) ERR;

      /* Check the vars in the group. */
      if (nc_inq_varid(grpid_in, VAR_NAME1, &varid_in1)) ERR;
      if (nc_inq_varid(grpid_in, VAR_NAME2, &varid_in2)) ERR;
      if (nc_inq_varid(grpid_in, VAR_NAME3, &varid_in3)) ERR;
      if (varid_in1 != varid1 || varid_in2 != varid2 || varid_in3 != varid3) ERR;
      if (nc_inq_var(grpid_in, varid1, name_in, &xtype_in, &ndims_in, &dimid1_in, &natts)) ERR;
      if (strcmp(name_in, VAR_NAME1) || xtype_in != NC_INT64 || ndims_in != NDIMS_IN_VAR ||
          dimid1_in != dimid1 || natts != 0) ERR;
      if (nc_inq_var(grpid_in, varid2, name_in, &xtype_in, &ndims_in, &dimid1_in, &natts)) ERR;
      if (strcmp(name_in, VAR_NAME2) || xtype_in != NC_INT64 || ndims_in != NDIMS_IN_VAR ||
          dimid1_in != dimid1 || natts != 0) ERR;
      if (nc_inq_var(grpid_in, varid3, name_in, &xtype_in, &ndims_in, &dimid1_in, &natts)) ERR;
      if (strcmp(name_in, VAR_NAME3) || xtype_in != NC_INT64 || ndims_in != NDIMS_IN_VAR ||
          dimid1_in != dimid2 || natts != 0) ERR;

      /* Read one value from the second unlim dim variable. It should
       * be the fill value. */
      index[0] = 0;
      if (nc_get_var1_longlong(grpid_in, varid_in2, index, &value_in)) ERR;
      if (value_in != NC_FILL_INT64) ERR;

      /* Read one value from the variable with limited dim. It should
       * be the fill value. */
      if (nc_get_var1_longlong(grpid_in, varid_in3, index, &value_in)) ERR;
      if (value_in != NC_FILL_INT64) ERR;

      /* Attempt to read beyond end of dimensions to generate error. */
      index[0] = BABE_LIMIT;
      if (nc_get_var1_longlong(grpid_in, varid_in1, index, &value_in) != NC_EINVALCOORDS) ERR;
      if (nc_get_var1_longlong(grpid_in, varid_in2, index, &value_in) != NC_EINVALCOORDS) ERR;
      if (nc_get_var1_longlong(grpid_in, varid_in3, index, &value_in) != NC_EINVALCOORDS) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing groups and unlimited dimensions...");
   {
      int ncid;
      int henry_vii_id;
      int tudor_id;
      int dimids_in[MAX_SIBLING_GROUPS], ndims_in;
      int num_grps;
      int dimid, dynasty, varid;
      size_t len_in;
      int natts_in;
      int grpids_in[10];
      nc_type xtype_in;
      char name_in[NC_MAX_NAME + 1];
      int data_out[DIM1_LEN] = {0, 2, 6}, data_in[DIM1_LEN];
      size_t start[1] = {0}, count[1] = {3};
      int j;

      /* Create one group, with one var, which has one dimension, which is unlimited. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_grp(ncid, DYNASTY, &tudor_id)) ERR;
      if (nc_def_dim(tudor_id, DIM1_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_grp(tudor_id, HENRY_VII, &henry_vii_id)) ERR;
      if (nc_def_var(henry_vii_id, VAR1_NAME, NC_INT, 1, &dimid, &varid)) ERR;
      if (nc_put_vara_int(henry_vii_id, varid, start, count, data_out)) ERR;
      if (nc_close(ncid)) ERR;

      /* Now check the file to see if the dimension and variable are
       * there. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_grps(ncid, &num_grps, &dynasty)) ERR;
      if (num_grps != 1) ERR;
      if (nc_inq_grps(dynasty, &num_grps, grpids_in)) ERR;
      if (num_grps != 1) ERR;
      if (nc_inq_dim(grpids_in[0], 0, name_in, &len_in)) ERR;
      if (strcmp(name_in, DIM1_NAME) || len_in != DIM1_LEN) ERR;
      if (nc_inq_var(grpids_in[0], 0, name_in, &xtype_in, &ndims_in, dimids_in,
		     &natts_in)) ERR;
      if (strcmp(name_in, VAR1_NAME) || xtype_in != NC_INT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_get_vara_int(grpids_in[0], 0, start, count, data_in)) ERR;
      for (j=0; j<DIM1_LEN; j++)
	 if (data_in[j] != data_out[j]) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
int ex_get_partial_elem_attr(int exoid, ex_entity_id elem_blk_id, int64_t start_elem_num,
                             int64_t num_elems, void *attrib)

{
  int    numelbdim, numattrdim, attrid, elem_blk_id_ndx, status;
  size_t num_elem_this_blk, num_attr, start[2], count[2];
  char   errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */
  if ((elem_blk_id_ndx = ex_id_lkup(exoid, EX_ELEM_BLOCK, elem_blk_id)) < 0) {
    if (exerrval == EX_NULLENTITY) {
      snprintf(errmsg, MAX_ERR_LENGTH,
               "Warning: no attributes found for NULL block %" PRId64 " in file id %d", elem_blk_id,
               exoid);
      ex_err("ex_get_partial_elem_attr", errmsg, EX_NULLENTITY);
      return (EX_WARN); /* no attributes for this element block */
    }
    snprintf(errmsg, MAX_ERR_LENGTH,
             "Warning: failed to locate element block %" PRId64 " in %s array in file id %d",
             elem_blk_id, VAR_ID_EL_BLK, exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_WARN);
  }

  /* inquire id's of previously defined dimensions  */

  if ((status = nc_inq_dimid(exoid, DIM_NUM_EL_IN_BLK(elem_blk_id_ndx), &numelbdim)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate number of elements for block %" PRId64 " in file id %d",
             elem_blk_id, exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimlen(exoid, numelbdim, &num_elem_this_blk)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to get number of elements for block %" PRId64 " in file id %d",
             elem_blk_id, exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_BLK(elem_blk_id_ndx), &numattrdim)) !=
      NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "Warning: no attributes found for block %" PRId64 " in file id %d", elem_blk_id,
             exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, EX_MSG);
    return (EX_WARN); /* no attributes for this element block */
  }

  if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to get number of attributes for block %" PRId64 " in file id %d",
             elem_blk_id, exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_varid(exoid, VAR_ATTRIB(elem_blk_id_ndx), &attrid)) != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate attributes for block %" PRId64 " in file id %d", elem_blk_id,
             exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* do some error checking */
  if (num_elem_this_blk < (start_elem_num + num_elems - 1)) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: requested attributes from too many elements in "
                                     "this block, %" PRId64 "",
             elem_blk_id);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* read in the attributes */

  start[0] = --start_elem_num;
  start[1] = 0;

  count[0] = num_elems;
  count[1] = num_attr;

  if (ex_comp_ws(exoid) == 4) {
    status = nc_get_vara_float(exoid, attrid, start, count, attrib);
  }
  else {
    status = nc_get_vara_double(exoid, attrid, start, count, attrib);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to get attributes for block %" PRId64 " in file id %d", elem_blk_id,
             exoid);
    ex_err("ex_get_partial_elem_attr", errmsg, exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
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.;
		}
	} 
	
	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;*/
			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;*/
			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;*/
	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;
}
Example #4
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;
}
Example #5
0
/* Test the creation of a system, and it's assignment to a data
 * variable. THis matches example 2 from John's document (with some of
 * the other attributes left out.) */
static void
test_system_assign(const char *testfile)
{
   int ncid, axis_varids[NDIMS], system_varid, dimids[NDIMS];
   int nvars, ndims, natts, unlimdimid;
   int dimids_in[NDIMS], ndims_in;
   size_t len_in;
   char name_in[NC_MAX_NAME + 1];
   char systems_in[NC_MAX_NAME + 1];
   int naxes_in, axis_varids_in[NDIMS], natts_in;
   char *dim_name[] = {TIME, LEVEL, LAT, LON};
   size_t dim_len[NDIMS] = {NC_UNLIMITED, LEVEL_LEN, LAT_LEN, LON_LEN};
   int earth_varid, air_varid;
   int varid_in;
   nc_type type_in;
   int d;

   /* Create a file. */
   if (nc_create(testfile, NC_CLOBBER, &ncid)) ERR;

   /* Create 4 dimensions, and a coordinate var to go with each. */
   for (d = 0; d < NDIMS; d++)
   {
      if (nc_def_dim(ncid, dim_name[d], dim_len[d], &dimids[d])) ERR;
      if (nc_def_var(ncid, dim_name[d], NC_FLOAT, 1, &dimids[d], 
		     &axis_varids[d])) ERR;
   }

   /* Create two data vars, earth and air. (Don't know what happened
    * to fire and water Aristotle!) */
   if (nc_def_var(ncid, EARTH, NC_FLOAT, NDIMS, dimids, 
		  &earth_varid)) ERR;
   if (nc_def_var(ncid, AIR, NC_FLOAT, NDIMS, dimids, 
		  &air_varid)) ERR;
   
   /* Unite our 4 dims in a coordinate system. */
   if (nccf_def_coord_system(ncid, LAT_LON_COORDINATE_SYSTEM, NDIMS, 
			     axis_varids, &system_varid)) ERR;

   /* Check things out. */
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != 4 && nvars != 7 && natts != 0 && unlimdimid != dimids[3]) ERR;
   if (nc_inq_varid(ncid, LAT_LON_COORDINATE_SYSTEM, &varid_in)) ERR;
   if (varid_in != system_varid) ERR;
   if (nc_inq_var(ncid, system_varid, name_in, &type_in, &ndims_in, 
		  dimids_in, &natts_in)) ERR;
   if (strcmp(name_in, LAT_LON_COORDINATE_SYSTEM) || type_in != NC_CHAR || 
       ndims_in != 0 || natts_in != 1);
   if (nc_inq_att(ncid, system_varid, COORDINATE_AXES, &type_in, &len_in)) ERR;
   if (type_in != NC_CHAR) ERR;
   if (nccf_inq_coord_system(ncid, system_varid, name_in, &naxes_in, axis_varids_in)) ERR;
   if (strcmp(name_in, LAT_LON_COORDINATE_SYSTEM) || naxes_in != NDIMS) ERR;
   for (d = 0; d < NDIMS; d++)
      if (axis_varids_in[d] != axis_varids[d]) ERR;

   /* Assign the system to the earth and air data variables. */
   if (nccf_assign_coord_system(ncid, earth_varid, system_varid)) ERR;
   if (nccf_assign_coord_system(ncid, air_varid, system_varid)) ERR;

   /* Check to ensure that the assignments happened. */
   if (nc_inq_varnatts(ncid, earth_varid, &natts_in)) ERR;
   if (natts_in != 1) ERR;
   if (nc_inq_att(ncid, earth_varid, COORDINATE_SYSTEMS, &type_in, &len_in)) ERR;
   if (type_in != NC_CHAR) ERR;
   if (nc_inq_varnatts(ncid, air_varid, &natts_in)) ERR;
   if (natts_in != 1) ERR;
   if (nc_get_att_text(ncid, earth_varid, COORDINATE_SYSTEMS, systems_in)) ERR;
   if (strcmp(systems_in, LAT_LON_COORDINATE_SYSTEM)) ERR;
   if (nc_inq_att(ncid, air_varid, COORDINATE_SYSTEMS, &type_in, &len_in)) ERR;
   if (type_in != NC_CHAR) ERR;
   if (nc_get_att_text(ncid, air_varid, COORDINATE_SYSTEMS, systems_in)) ERR;
   if (strcmp(systems_in, LAT_LON_COORDINATE_SYSTEM)) ERR;

   /* Write the file. */
   if (nc_close(ncid)) ERR;

   /* Reopen the file and check it. */
   if (nc_open(testfile, NC_NOWRITE, &ncid)) ERR;
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != 4 && nvars != 7 && natts != 0 && unlimdimid != dimids[3]) ERR;
   if (nc_inq_var(ncid, system_varid, name_in, &type_in, &ndims_in, 
		  dimids_in, &natts_in)) ERR;
   if (strcmp(name_in, LAT_LON_COORDINATE_SYSTEM) || type_in != NC_CHAR || 
       ndims_in != 0 || natts_in != 1);
   if (nc_inq_att(ncid, system_varid, COORDINATE_AXES, &type_in, &len_in)) ERR;
   if (type_in != NC_CHAR) ERR;
   if (nccf_inq_coord_system(ncid, system_varid, name_in, &naxes_in, axis_varids_in)) ERR;
   if (strcmp(name_in, LAT_LON_COORDINATE_SYSTEM) || naxes_in != NDIMS) ERR;
   for (d = 0; d < NDIMS; d++)
      if (axis_varids_in[d] != axis_varids[d]) ERR;

   /* Check to ensure that the assignments happened. */
   if (nc_inq_varnatts(ncid, earth_varid, &natts_in)) ERR;
   if (natts_in != 1) ERR;
   if (nc_inq_att(ncid, earth_varid, COORDINATE_SYSTEMS, &type_in, &len_in)) ERR;
   if (type_in != NC_CHAR) ERR;
   if (nc_inq_varnatts(ncid, air_varid, &natts_in)) ERR;
   if (natts_in != 1) ERR;
   if (nc_get_att_text(ncid, earth_varid, COORDINATE_SYSTEMS, systems_in)) ERR;
   if (strcmp(systems_in, LAT_LON_COORDINATE_SYSTEM)) ERR;
   if (nc_inq_att(ncid, air_varid, COORDINATE_SYSTEMS, &type_in, &len_in)) ERR;
   if (type_in != NC_CHAR) ERR;
   if (nc_get_att_text(ncid, air_varid, COORDINATE_SYSTEMS, systems_in)) ERR;
   if (strcmp(systems_in, LAT_LON_COORDINATE_SYSTEM)) ERR;

   if (nc_close(ncid)) ERR; 
}
Example #6
0
int ex_put_n_nodal_var (int   exoid,
                        int   time_step,
                        int   nodal_var_index,
                        int   start_node,
                        int   num_nodes, 
                        const void *nodal_var_vals)

{
  int status;
  int varid;
  size_t start[3], count[3];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  if (ex_large_model(exoid) == 0) {
    /* write values of the nodal variable */
    if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Warning: could not find nodal variables in file id %d",
              exoid);
      ex_err("ex_put_n_nodal_var",errmsg,exerrval);
      return (EX_WARN);
    }
    start[0] = --time_step;
    start[1] = --nodal_var_index;
    start[2] = --start_node;

    count[0] = 1;
    count[1] = 1;
    count[2] = num_nodes;
  } else {
    /* nodal variables stored separately, find variable for this variable
       index */
    if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Warning: could not find nodal variable %d in file id %d",
              nodal_var_index, exoid);
      ex_err("ex_put_n_nodal_var",errmsg,exerrval);
      return (EX_WARN);
    }

    start[0] = --time_step;
    start[1] = --start_node;

    count[0] = 1;
    count[1] = num_nodes;
  }

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, varid, start, count, nodal_var_vals);
  } else {
    status = nc_put_vara_double(exoid, varid, start, count, nodal_var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to store nodal variables in file id %d",
            exoid);
    ex_err("ex_put_n_nodal_var",errmsg,exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
Example #7
0
static int ex_get_concat_set_len(int exoid, int64_t *set_length, const char *set_name,
				 ex_entity_type set_type, const char *set_num_dim,
				 const char *set_stat_var, const char *set_size_root,
				 int missing_ok)
{
  int i;
  int status;
  char  errmsg[MAX_ERR_LENGTH];
  size_t idum;
  int dimid, varid;
  size_t num_sets;
  int *stat_vals = NULL;

  *set_length = 0;     /* default return value */

  if ((status = nc_inq_dimid (exoid, set_num_dim, &dimid)) == NC_NOERR)
    {
      if ((status = nc_inq_dimlen (exoid, dimid, &num_sets)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get number of %s sets in file id %d",
		set_name, exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }

      /* Allocate space for stat array */
      if (!(stat_vals = malloc((int)num_sets*sizeof(int)))) {
	exerrval = EX_MEMFAIL;
	sprintf(errmsg,
		"Error: failed to allocate memory for %s set status array for file id %d",
		set_name, exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }

      /* get variable id of status array */
      if ((status = nc_inq_varid (exoid, set_stat_var, &varid)) == NC_NOERR) {
	/* if status array exists, use it, otherwise assume, object exists
	   to be backward compatible */
	if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) {
	  exerrval = status;
	  free(stat_vals);
	  sprintf(errmsg,
		  "Error: failed to get %s set status array from file id %d",
		  set_name, exoid);
	  ex_err("ex_inquire",errmsg,exerrval);
	  return (EX_FATAL);
	}
      } else /* default: status is true */
	for(i=0;i<num_sets;i++)
	  stat_vals[i]=1;

      for (i=0; i<num_sets; i++) {
	if (stat_vals[i] == 0) /* is this object null? */
	  continue;


	if ((status = nc_inq_dimid (exoid, ex_catstr(set_size_root,i+1), &dimid)) != NC_NOERR) {
	  if ( missing_ok ) {
	    idum = 0;
	  } else {
	    *set_length = 0;
	    free(stat_vals);
	    return (EX_FATAL);
	  }
	} else {
	  if ((status = nc_inq_dimlen (exoid, dimid, &idum)) != NC_NOERR) {
	    *set_length = 0;
	    free(stat_vals);
	    return (EX_FATAL);
	  }
	}

	*set_length += idum;
      }

      free(stat_vals);
    }
  return (EX_NOERR);
}
Example #8
0
static int open_mmtk_cdf_read(cdfdata *cdf, int conventionsknown) {
  int rc;
  size_t len; 
  mmtkdata *mmtk = &cdf->mmtk;

  /* If conventions specify MMTK then we're safe to continue */
  /* and we know what we're dealing with */
  if (conventionsknown) {
    cdf->type = CDF_TYPE_MMTK;
  }

  /* global attrib: "trajectory_type" (new format) */
  nc_get_att_int(cdf->ncid, NC_GLOBAL, "trajectory_type", &mmtk->trajectorytype);
  if (rc == NC_NOERR) {
    printf("netcdfplugin) MMTK trajectory type: %d\n", mmtk->trajectorytype);
  } else {
    printf("netcdfplugin) Assuming MMTK trajectory type: %d\n", mmtk->trajectorytype);
    mmtk->trajectorytype = 0;
  }

  /* read in spatial dimension */
  rc = nc_inq_dimid(cdf->ncid, "xyz", &mmtk->xyzdimid);
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->xyzdimid, &mmtk->xyzdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: xyz dimension: %ld\n", (long)mmtk->xyzdim);
    else 
      return CDF_ERR;
  } else {
    return CDF_ERR;
  }

  /* read in atom dimension */
  rc = nc_inq_dimid(cdf->ncid, "atom_number", &mmtk->atom_numberdimid); 
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->atom_numberdimid, &mmtk->atom_numberdim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) MMTK: atom_number dimension: %ld\n", (long)mmtk->atom_numberdim);
      cdf->natoms = mmtk->atom_numberdim; /* copy to format independent part */
    } else {
      return CDF_ERR;
    }
  } else {
    return CDF_ERR;
  }


  /* read in frame dimension */
  rc = nc_inq_dimid(cdf->ncid, "step_number", &mmtk->step_numberdimid);
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->step_numberdimid, &mmtk->step_numberdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: step_number dimension: %ld\n", (long)mmtk->step_numberdim);
    else 
      return CDF_ERR;
  } else {
    return CDF_ERR;
  }


  /* read in minor step number dimension */
  rc = nc_inq_dimid(cdf->ncid, "minor_step_number", &mmtk->minor_step_numberdimid);
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->minor_step_numberdimid, &mmtk->minor_step_numberdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: minor_step_number dimension: %ld\n", (long)mmtk->minor_step_numberdim);
    else 
      return CDF_ERR;
  } else if (rc == NC_EBADDIM) {
    printf("netcdfplugin) MMTK: no minor_step_number dimension\n");
    mmtk->minor_step_numberdim = 0;
  } else {
    return CDF_ERR;
  }


  /* read in description_length dimension */
  rc = nc_inq_dimid(cdf->ncid, "description_length", &mmtk->description_lengthdimid); 
  if (rc == NC_NOERR) {
    rc = nc_inq_dimlen(cdf->ncid, mmtk->description_lengthdimid, &mmtk->description_lengthdim);
    if (rc == NC_NOERR)
      printf("netcdfplugin) MMTK: description_length dimension: %ld\n", (long)mmtk->description_lengthdim);
    else
      return CDF_ERR;
  } else {
    return CDF_ERR;
  }


  /* get ID values for all of the variables we're interested in */
  rc = nc_inq_varid(cdf->ncid, "configuration", &mmtk->configuration_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  rc = nc_inq_varid(cdf->ncid, "description", &mmtk->description_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  /* check for PBC */
  rc = nc_inq_varid(cdf->ncid, "box_size", &mmtk->box_size_id);
  if (rc == NC_NOERR) {
    mmtk->has_box = 1;
    printf("netcdfplugin) MMTK: system has periodic boundary conditions\n");
  }
  else if (rc == NC_ENOTVAR)
    mmtk->has_box = 0;
  else
    return CDF_ERR;


  /* global attrib: "comment" -- optional */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "comment", &len);
  if (rc == NC_NOERR && len > 0) {
    mmtk->comment = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "comment", mmtk->comment);
    mmtk->comment[len] = '\0';
    printf("netcdfplugin) MMTK: comment '%s'\n", mmtk->comment);
  } 

  /* at this point we know that this is an MMTK trajectory */
  if (!conventionsknown) {
    printf("netcdfplugin) File is an old format MMTK trajectory without conventions\n");    
    cdf->type = CDF_TYPE_MMTK;
  }

  return CDF_SUCCESS;
}
int ex_get_prop_array (int   exoid,
                       ex_entity_type obj_type,
                       const char *prop_name,
                       void_int  *values)
{
   int num_props, i, propid, status;
   int found = FALSE;
   char name[MAX_VAR_NAME_LENGTH+1];
   char tmpstr[MAX_STR_LENGTH+1];

   char errmsg[MAX_ERR_LENGTH];

   exerrval  = 0; /* clear error code */

/* open appropriate variable, depending on obj_type and prop_name */

   num_props = ex_get_num_props(exoid, obj_type);

   for (i=1; i<=num_props; i++)
   {
     switch (obj_type){
       case EX_ELEM_BLOCK:
         strcpy (name, VAR_EB_PROP(i));
         break;
       case EX_EDGE_BLOCK:
         strcpy (name, VAR_ED_PROP(i));
         break;
       case EX_FACE_BLOCK:
         strcpy (name, VAR_FA_PROP(i));
         break;
       case EX_NODE_SET:
         strcpy (name, VAR_NS_PROP(i));
         break;
       case EX_EDGE_SET:
         strcpy (name, VAR_ES_PROP(i));
         break;
       case EX_FACE_SET:
         strcpy (name, VAR_FS_PROP(i));
         break;
       case EX_ELEM_SET:
         strcpy (name, VAR_ELS_PROP(i));
         break;
       case EX_SIDE_SET:
         strcpy (name, VAR_SS_PROP(i));
         break;
       case EX_ELEM_MAP:
         strcpy (name, VAR_EM_PROP(i));
         break;
       case EX_FACE_MAP:
         strcpy (name, VAR_FAM_PROP(i));
         break;
       case EX_EDGE_MAP:
         strcpy (name, VAR_EDM_PROP(i));
         break;
       case EX_NODE_MAP:
         strcpy (name, VAR_NM_PROP(i));
         break;
       default:
         exerrval = EX_BADPARAM;
         sprintf(errmsg, "Error: object type %d not supported; file id %d",
           obj_type, exoid);
         ex_err("ex_get_prop_array",errmsg,exerrval);
         return(EX_FATAL);
     }

     if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) {
       exerrval = status;
       sprintf(errmsg,
          "Error: failed to locate property array %s in file id %d",
               name, exoid);
       ex_err("ex_get_prop_array",errmsg,exerrval);
       return (EX_FATAL);
     }

     /*   compare stored attribute name with passed property name   */
     memset(tmpstr, 0, MAX_STR_LENGTH+1);
     if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) {
       exerrval = status;
       sprintf(errmsg,
              "Error: failed to get property name in file id %d", exoid);
       ex_err("ex_get_prop_array",errmsg,exerrval);
       return (EX_FATAL);
     }

     if (strcmp(tmpstr, prop_name) == 0) {
       found = TRUE;
       break;
     }
   }

   /* if property is not found, return warning */
   if (!found) {
     exerrval = EX_BADPARAM;
     sprintf(errmsg,
       "Warning: object type %d, property %s not defined in file id %d",
        obj_type, prop_name, exoid);
     ex_err("ex_get_prop_array",errmsg,exerrval);
     return (EX_WARN);
   }

   /* read num_obj values from property variable */
  if (ex_int64_status(exoid) & EX_IDS_INT64_API) {
    status = nc_get_var_longlong(exoid, propid, values);
  } else {
    status = nc_get_var_int(exoid, propid, values);
  }

   if (status != NC_NOERR) {
     exerrval = status;
     sprintf(errmsg,
            "Error: failed to read values in %s property array in file id %d",
             ex_name_of_object(obj_type), exoid);
     ex_err("ex_get_prop_array",errmsg,exerrval);
     return (EX_FATAL);
   }

   return (EX_NOERR);
}
Example #10
0
int main (int argc, char **argv)
{
    struct arguments arguments;

    /* Default values. */
    arguments.verbose = 0;
    arguments.grd = 0;
    arguments.region = NULL;
    arguments.type = NULL;
    static const int NUM_DAYS = 365;

    /* Parse our arguments; every option seen by parse_opt will
     be reflected in arguments. */
    argp_parse (&argp, argc, argv, 0, 0, &arguments);

    /* Set up variables */
    int num_columns;
    int num_rows;
    char* region = arguments.region;
    char* type = arguments.type;
    int grd = arguments.grd;
    int i,j,k;

    /* Initialize NETCDF Variables */
    int ncid, row_dimid, col_dimid;
    int varid, wet_varid, dry_varid, slope_varid;
    int retval;
    char FILE_NAME[100];
    int dimids[NDIMS];

    /* multithread args */
    thread_args t_args[NUM_THREADS];
    pthread_t thread_id[NUM_THREADS];
    int ind_per_thread;
    int start_index;
    int stop_index;

    printf ("GEN_C0\n---------------\nBeginning processing with options:\n");

    printf ("Region = %s\nVERBOSE = %s\nTYPE = %s\n---------------\n",
      arguments.region,
      arguments.verbose ? "yes" : "no",
      arguments.type);

    /* define image areas based on region */
    if (!grd) {
        if (strcmp(region,"Ama") == 0) {
            num_columns = 1128;
            num_rows = 744;
        } else if (strcmp(region,"Ber") == 0) {
            num_columns = 1350;
            num_rows = 750;
        } else if (strcmp(region,"CAm") == 0) {
              num_columns = 1440;
              num_rows = 700;
        } else if (strcmp(region,"ChJ") == 0) {
              num_columns = 1980;
              num_rows = 950;
        } else if (strcmp(region,"Eur") == 0) {
              num_columns = 1530;
              num_rows = 1040;
        } else if (strcmp(region,"Ind") == 0) {
              num_columns = 1800;
              num_rows = 680;
        } else if (strcmp(region,"NAf") == 0) {
              num_columns = 2120;
              num_rows = 1130;
        } else if (strcmp(region,"NAm") == 0) {
              num_columns = 1890;
              num_rows = 1150;
        } else if (strcmp(region,"SAf") == 0) {
              num_columns = 1220;
              num_rows = 1260;
        } else if (strcmp(region,"SAm") == 0) {
              num_columns = 1310;
              num_rows = 1850;
        }  else if (strcmp(region,"SAs") == 0) {
              num_columns = 1760;
              num_rows = 720;
        } else {
            printf("ERROR SETTING REGION SIZES!");
            exit(-1);
        }
    } else {
        if (strcmp(region,"NAm") == 0) {
            num_columns = 672;
            num_rows = 410;
        } else {
            printf("ERROR SETTING REGION SIZES!");
            exit(-1);
        }
    }

    /* allocate memory for 2d arrays */
    printf("Allocating Memory...");
    float **c0_dry = (float**)malloc(sizeof(float *)*num_rows);
    float **c0_wet = (float**)malloc(sizeof(float *)*num_rows);
    float **dry_slope = (float**)malloc(sizeof(float *)*num_rows);
    c0_dry[0] = (float*)malloc(sizeof(float)*num_rows*num_columns);
    c0_wet[0] = (float*)malloc(sizeof(float)*num_rows*num_columns);
    dry_slope[0] = (float*)malloc(sizeof(float)*num_rows*num_columns);
    for (i = 1; i < num_rows; i++) {
        c0_dry[i] = c0_dry[0] + i * num_columns;
        c0_wet[i] = c0_wet[0] + i * num_columns;
        dry_slope[i] = dry_slope[0] + i * num_columns;
    }
    memset(c0_dry[0],0,num_rows*num_columns*sizeof(float));
    memset(c0_wet[0],0,num_rows*num_columns*sizeof(float));
    memset(dry_slope[0],0,num_rows*num_columns*sizeof(float));

    /* allocate memory for NetCDF File */
    float ****row_ptr = (float****)malloc(sizeof(float ***)*num_rows);
    float ***column_ptr = (float***)malloc(sizeof(float **)*num_rows * num_columns);
    float **year_ptr = (float**)malloc(sizeof(float *)*num_rows * num_columns*NUM_YEARS);
    float *day_ptr = (float*)malloc(sizeof(float)*num_rows*num_columns*NUM_YEARS*NUM_DAYS);
    float ****tseries = row_ptr;

    for (i = 0; i < num_rows; i++, column_ptr += num_columns) {
        tseries[i] = column_ptr;
        for (j = 0; j < num_columns; j++, year_ptr += NUM_YEARS) {
            tseries[i][j] = year_ptr;
            for (k = 0; k < NUM_YEARS; k++, day_ptr += NUM_DAYS) {
                tseries[i][j][k] = day_ptr;
            }
        }
    }

    row_ptr = (float****)malloc(sizeof(float ***)*num_rows);
    column_ptr = (float***)malloc(sizeof(float **)*num_rows * num_columns);
    year_ptr = (float**)malloc(sizeof(float *)*num_rows * num_columns*NUM_YEARS);
    day_ptr = (float*)malloc(sizeof(float)*num_rows*num_columns*NUM_YEARS*NUM_DAYS);
    float ****tseriesb = row_ptr;

    for (i = 0; i < num_rows; i++, column_ptr += num_columns) {
        tseriesb[i] = column_ptr;
        for (j = 0; j < num_columns; j++, year_ptr += NUM_YEARS) {
            tseriesb[i][j] = year_ptr;
            for (k = 0; k < NUM_YEARS; k++, day_ptr += NUM_DAYS) {
                tseriesb[i][j][k] = day_ptr;
            }
        }
    }

    printf("done\n");

    setvbuf (stdout, NULL, _IONBF, 0);
    printf("Reading NetCDF Files...");
    /* Open the netCDF time series a file*/
    sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/ts/ts_%s_%s.nc",region,"a");
    if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid)))
        ERR(retval);

    /* Get the varid of the data variable, based on its name. */
    if ((retval = nc_inq_varid(ncid, "data", &varid)))
        ERR(retval);

    /* read values from netCDF variable */
    if ((retval = nc_get_var_float(ncid, varid, &tseries[0][0][0][0])))
       ERR(retval);

    /* Open the netCDF time series b file*/
    sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/ts/ts_%s_%s.nc",region,"b");
    if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid)))
        ERR(retval);

    /* Get the varid of the data variable, based on its name. */
    if ((retval = nc_inq_varid(ncid, "data", &varid)))
        ERR(retval);

    /* read values from netCDF variable */
    if ((retval = nc_get_var_float(ncid, varid, &tseriesb[0][0][0][0])))
       ERR(retval);

    printf("done\n");

    /* get threads ready */
    /* split up column processing based on number of threads/rows */
    ind_per_thread = num_rows / NUM_THREADS - 1;
    start_index = 0;
    stop_index = 0;
    for (i = 0; i < NUM_THREADS; i++) {
        if (i == NUM_THREADS - 1) {
            stop_index = num_rows-1;
        } else {
            stop_index = start_index + ind_per_thread;
        }
        t_args[i].tseries = tseries;
        t_args[i].tseriesb = tseriesb;
        t_args[i].c0_wet = c0_wet;
        t_args[i].c0_dry = c0_dry;
        t_args[i].dry_slope = dry_slope;
        t_args[i].start_i = start_index;
        t_args[i].stop_i = stop_index;
        t_args[i].num_columns = num_columns;
        t_args[i].region = region;
        t_args[i].type = type;
        start_index = stop_index + 1;
    }

    /* call multithreaded function */
    /* submit threads */
    printf("Starting Processing\n");
    for (i = 0; i < NUM_THREADS; i++) {
        pthread_create(&thread_id[i], NULL, mthreadGenC0, &t_args[i]);
    }

    /* join threads */
    for (i = 0; i < NUM_THREADS; i++) {
        pthread_join(thread_id[i], NULL);
    }

    /* save min/max 2d arrays to netcdf file */
    /* Create the file. */
    sprintf(FILE_NAME,"/auto/temp/lindell/soilmoisture/c0/c0_%s.nc",region);
    if ((retval = nc_create(FILE_NAME, NC_NETCDF4, &ncid)))
        ERR(retval);

    /* Define the dimensions. */
    if ((retval = nc_def_dim(ncid, "row", num_rows, &row_dimid)))
        ERR(retval);
    if ((retval = nc_def_dim(ncid, "column", num_columns, &col_dimid)))
        ERR(retval);

    /* Define the netCDF variables. The dimids array is used to pass
        the dimids of the dimensions of the variables.*/
    dimids[0] = row_dimid;
    dimids[1] = col_dimid;

    /* define the variable */
    if ((retval = nc_def_var(ncid, "dry", NC_FLOAT, NDIMS, dimids, &dry_varid)))
        ERR(retval);

    if ((retval = nc_def_var(ncid, "wet", NC_FLOAT, NDIMS, dimids, &wet_varid)))
        ERR(retval);

    if ((retval = nc_def_var(ncid, "dry_slope", NC_FLOAT, NDIMS, dimids, &slope_varid)))
        ERR(retval);

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

    /* Write the data. */
    if ((retval = nc_put_var_float(ncid, dry_varid, &c0_dry[0][0])))
        ERR(retval);
    if ((retval = nc_put_var_float(ncid, wet_varid, &c0_wet[0][0])))
        ERR(retval);
    if ((retval = nc_put_var_float(ncid, slope_varid, &dry_slope[0][0])))
        ERR(retval);

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

    /* Free memory for 3D image timeseries array */
    printf("Finishing up...");
    free(tseries[0][0][0]);
    free(tseries[0][0]);
    free(tseries[0]);
    free(tseries);

    free(c0_wet[0]);
    free(c0_dry[0]);
    free(dry_slope[0]);
    free(c0_wet);
    free(c0_dry);
    free(dry_slope);

    printf("done\n");

    exit (0);
}
Example #11
0
static int open_amber_cdf_read(cdfdata *cdf) {
  int rc;
  size_t len; 
  amberdata *amber = &cdf->amber;

  /* global attrib: "ConventionVersion" -- required */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "ConventionVersion", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->conventionversion = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "ConventionVersion", amber->conventionversion);
    amber->conventionversion[len] = '\0';
    printf("netcdfplugin) trajectory follows AMBER conventions version '%s'\n", amber->conventionversion);
  } else {
    return CDF_ERR;
  }

  /* at this point we know that this is an AMBER trajectory */
  cdf->type = CDF_TYPE_AMBER;

  /* initialize default scaling factors so they are always set to a sane */
  /* value even if problems occur later */
  amber->coordinates_scalefactor = 1.0;
  amber->cell_lengths_scalefactor = 1.0;
  amber->cell_angles_scalefactor = 1.0;


  /* global attrib: "program" -- required */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "program", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->program = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "program", amber->program);
    amber->program[len] = '\0';
    printf("netcdfplugin) AMBER: program '%s'\n", amber->program);
  } else {
    printf("netcdfplugin) AMBER: Missing required 'program' global attribute, corrupt file?\n");
  }


  /* global attrib: "programVersion" -- required */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "programVersion", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->programversion = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "programVersion", amber->programversion);
    amber->programversion[len] = '\0';
    printf("netcdfplugin) AMBER: program version '%s'\n", amber->programversion);
  } else {
    printf("netcdfplugin) AMBER: Missing required 'programVersion' global attribute, corrupt file?\n");
  }


  /* global attrib: "title" -- optional */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "title", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->title = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "title", amber->title);
    amber->title[len] = '\0';
    printf("netcdfplugin) AMBER: title '%s'\n", amber->title);
  } 


  /* global attrib: "application" -- optional */
  rc = nc_inq_attlen(cdf->ncid, NC_GLOBAL, "application", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->application = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, NC_GLOBAL, "application", amber->application);
    amber->application[len] = '\0';
    printf("netcdfplugin) AMBER: application '%s'\n", amber->application);
  } 


/* XXX lots of additional error checking is needed below... */

  /* read in spatial dimension */
  rc = nc_inq_dimid(cdf->ncid, "spatial", &amber->spatialdimid);
  if (rc == NC_NOERR) {    
    rc = nc_inq_dimlen(cdf->ncid, amber->spatialdimid, &amber->spatialdim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER: spatial dimension: %ld\n", (long)amber->spatialdim);
    } else {
      printf("netcdfplugin) AMBER: Missing spatial dimension, corrupt file?\n");
      printf("netcdfplugin) AMBER: Fixing by guessing spatialdim as '3'\n");
      amber->spatialdim = 3;
    }
  } else {
    printf("netcdfplugin) AMBER: Missing spatial dimension, corrupt file?\n");
    printf("netcdfplugin) AMBER: Fixing by guessing spatialdim as '3'\n");
    amber->spatialdim = 3;
  }
 
  /* read in atom dimension */
  rc = nc_inq_dimid(cdf->ncid, "atom", &amber->atomdimid);
  if (rc == NC_NOERR) {    
    rc = nc_inq_dimlen(cdf->ncid, amber->atomdimid, &amber->atomdim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER: atom dimension: %ld\n", (long)amber->atomdim);
      cdf->natoms = amber->atomdim; /* copy to format independent part */
    } else  {
      printf("netcdfplugin) AMBER: missing atom dimension, aborting\n");
      return CDF_ERR;
    }
  } else {
    printf("netcdfplugin) AMBER: missing atom dimension, aborting\n");
    return CDF_ERR;
  }
 

  /* read in frame dimension */
  rc = nc_inq_dimid(cdf->ncid, "frame", &amber->framedimid);
  if (rc == NC_NOERR) {    
    rc = nc_inq_dimlen(cdf->ncid, amber->framedimid, &amber->framedim);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER: frame dimension: %ld\n", (long)amber->framedim);
    } else {
      printf("netcdfplugin) AMBER: missing frame dimension, aborting\n");
      return CDF_ERR;
    }
  } else {
    printf("netcdfplugin) AMBER: missing frame dimension, aborting\n");
    return CDF_ERR;
  }

  /* 
   * get ID values for all of the variables we're interested in 
   */
#if 0
  /* VMD can live without the various human readable label variables. */
  rc = nc_inq_varid(cdf->ncid, "spatial", &amber->spatial_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  rc = nc_inq_varid(cdf->ncid, "cell_spatial", &amber->cell_spatial_id);
  if (rc != NC_NOERR)
    return CDF_ERR;

  rc = nc_inq_varid(cdf->ncid, "cell_angular", &amber->cell_angular_id);
  if (rc != NC_NOERR)
    return CDF_ERR;
#endif

  /* VMD requires coordinates at a minimum */
  rc = nc_inq_varid(cdf->ncid, "coordinates", &amber->coordinates_id);
  if (rc != NC_NOERR) {
    printf("netcdfplugin) AMBER: no coordinates variable, nothing to load\n");
    return CDF_ERR;
  }

  /* Coordinate units */
  rc = nc_inq_attlen(cdf->ncid, amber->coordinates_id, "units", &len);
  if (rc == NC_NOERR && len > 0) {
    amber->coordinates_units = (char *) malloc((len+1) * sizeof(char));
    nc_get_att_text(cdf->ncid, amber->coordinates_id, "units", amber->coordinates_units);
    amber->coordinates_units[len] = '\0';
    printf("netcdfplugin) AMBER: coordinates units: '%s'\n", amber->coordinates_units);
  } else {
    printf("netcdfplugin) AMBER: no coordinates units attribute, Angstroms assumed\n");
  }

  /* Coordinate scaling factor to get to Angstroms */
  rc = nc_get_att_float(cdf->ncid, amber->coordinates_id, "scale_factor", &amber->coordinates_scalefactor);
  if (rc == NC_NOERR) {
    printf("netcdfplugin) AMBER: coordinates scalefactor: %f\n", amber->coordinates_scalefactor);
  } else {
    amber->coordinates_scalefactor = 1.0;
  }

#if 0
  /* we don't need velocities at this time */
  rc = nc_inq_varid(cdf->ncid, "velocities", &amber->velocities_id);
  if (rc != NC_NOERR) {
    printf("netcdfplugin) AMBER: missing velocities variable, aborting\n");
    return CDF_ERR;
  }
#endif

  /* optional periodic cell info */
  rc = nc_inq_varid(cdf->ncid, "cell_lengths", &amber->cell_lengths_id);
  if (rc == NC_NOERR) {
    rc = nc_inq_varid(cdf->ncid, "cell_angles", &amber->cell_angles_id);
    if (rc == NC_NOERR) {
      printf("netcdfplugin) AMBER trajectory contains periodic cell information\n");
      amber->has_box = 1;

      /* Cell lengths units */
      rc = nc_inq_attlen(cdf->ncid, amber->cell_lengths_id, "units", &len);
      if (rc == NC_NOERR && len > 0) {
        amber->cell_lengths_units = (char *) malloc((len+1) * sizeof(char));
        nc_get_att_text(cdf->ncid, amber->cell_lengths_id, "units", amber->cell_lengths_units);
        amber->cell_lengths_units[len] = '\0';
        printf("netcdfplugin) AMBER: cell lengths units: '%s'\n", amber->cell_lengths_units);
      } else {
        printf("netcdfplugin) AMBER: no cell lengths units attribute, Angstroms assumed\n");
      }

      /* Cell lengths scaling factor to get to Angstroms */
      rc = nc_get_att_float(cdf->ncid, amber->cell_lengths_id, "scale_factor", &amber->cell_lengths_scalefactor);
      if (rc == NC_NOERR) {
        printf("netcdfplugin) AMBER: cell lengths scalefactor: %f\n", amber->cell_lengths_scalefactor);
      } else {
        amber->cell_lengths_scalefactor = 1.0;
      }

      /* Cell angles units */
      rc = nc_inq_attlen(cdf->ncid, amber->cell_angles_id, "units", &len);
      if (rc == NC_NOERR && len > 0) {
        amber->cell_angles_units = (char *) malloc((len+1) * sizeof(char));
        nc_get_att_text(cdf->ncid, amber->cell_angles_id, "units", amber->cell_angles_units);
        amber->cell_angles_units[len] = '\0';
        printf("netcdfplugin) AMBER: cell angles units: '%s'\n", amber->cell_angles_units);
      } else {
        printf("netcdfplugin) AMBER: no cell angles units attribute, Degrees assumed\n");
      }

      /* Cell angles scaling factor to get to degrees */
      rc = nc_get_att_float(cdf->ncid, amber->cell_angles_id, "scale_factor", &amber->cell_angles_scalefactor);
      if (rc == NC_NOERR) {
        printf("netcdfplugin) AMBER: cell angles scalefactor: %f\n", amber->cell_angles_scalefactor);
      } else {
        amber->cell_angles_scalefactor = 1.0;
      }
    }
  }

  return CDF_SUCCESS;
}
Example #12
0
int main()
{
    int ncid, varid;
    int ncstat = NC_NOERR;
    char* url;
    char* topsrcdir;
    size_t len;
#ifndef USE_NETCDF4
    int i,j;
#endif

    /* location of our target url: use file:// to avoid remote
	server downtime issues
     */

    /* Assume that TESTS_ENVIRONMENT was set */
    topsrcdir = getenv("TOPSRCDIR");
    if(topsrcdir == NULL) {
        fprintf(stderr,"*** FAIL: $abs_top_srcdir not defined: location= %s:%d\n",__FILE__,__LINE__);
        exit(1);
    }
    len = strlen("file://") + strlen(topsrcdir) + strlen("/ncdap_test/testdata3/test.02") + 1;
#ifdef DEBUG
    len += strlen("[log][show=fetch]");
#endif
    url = (char*)malloc(len);
    url[0] = '\0';

#ifdef DEBUG
    strcat(url,"[log][show=fetch]");
#endif

    strcat(url,"file://");
    strcat(url,topsrcdir);
    strcat(url,"/ncdap_test/testdata3/test.02");

    printf("*** Test: var conversions on URL: %s\n",url);

    /* open file, get varid */
    CHECK(nc_open(url, NC_NOWRITE, &ncid));
    /* extract the string case for netcdf-3*/
#ifndef USE_NETCDF4
    CHECK(nc_inq_varid(ncid, "s", &varid));
    CHECK(nc_get_var_text(ncid,varid,(char*)string3));
#ifdef GENERATE
    printf("static %s string3_data[DIMSIZE][STRLEN]={","char");
    for(i=0;i<DIMSIZE;i++) {
	int j;
	/* Do simple escape */
	for(j=0;j<STRLEN;j++) {
	    if(string3[i][j] > 0
	       && string3[i][j] != '\n'
	       && string3[i][j] != '\r'
	       && string3[i][j] != '\t'
	       &&(string3[i][j] < ' ' || string3[i][j] >= '\177'))
		string3[i][j] = '?';
	}
	printf("%s\"%s\"",COMMA,string3[i]);
    }
    printf("};\n");
#else
 	fprintf(stdout,"*** testing: %s\n","string3");
	for(i=0;i<DIMSIZE;i++) {
   	    for(j=0;j<STRLEN;j++) {
	        if(string3[i][j] != string3_data[i][j]) {report(i,"string3",__LINE__); break;}
	    }
	}
#endif
#endif

    CHECK(nc_inq_varid(ncid, "b", &varid));
    CHECK(nc_get_var_text(ncid,varid,ch));
#ifdef GENERATE
    printf("static %s ch_data[DIMSIZE]={","char");
    for(i=0;i<DIMSIZE;i++) printf("%s'\\%03hho'",COMMA,ch[i]);
    printf("};\n");
#else
    COMPARE(NC_CHAR,NC_CHAR,ch,ch_data);
#endif

    CHECK(nc_inq_varid(ncid, "b", &varid));
    CHECK(nc_get_var_schar(ncid,varid,int8v));
#ifdef GENERATE
    printf("static %s int8_data[DIMSIZE]={","signed char");
    for(i=0;i<DIMSIZE;i++) printf("%s%hhd",COMMA,int8v[i]);
    printf("};\n");
#else
    COMPARE(NC_BYTE,NC_BYTE,int8v,int8_data);
#endif

    CHECK(nc_inq_varid(ncid, "b", &varid));
    CHECK(nc_get_var_uchar(ncid,varid,uint8v));
#ifdef GENERATE
    printf("static %s uint8_data[DIMSIZE]={","unsigned char");
    for(i=0;i<DIMSIZE;i++) printf("%s%hhu",COMMA,uint8v[i]);
    printf("};\n");
#else
    COMPARE(NC_UBYTE,NC_UBYTE,uint8v,uint8_data);
#endif

    CHECK(nc_inq_varid(ncid, "b", &varid));
    CHECK(nc_get_var_int(ncid,varid,int32v));
#ifdef GENERATE
    printf("static %s int8toint32_data[DIMSIZE]={","int");
    for(i=0;i<DIMSIZE;i++) printf("%s%d",COMMA,int32v[i]);
    printf("};\n");
#else
    COMPARE(NC_BYTE,NC_INT,int32v,int8toint32_data);
#endif

    CHECK(nc_inq_varid(ncid, "b", &varid));
    CHECK(nc_get_var_float(ncid,varid,float32v));
#ifdef GENERATE
    printf("static %s int82float32_data[DIMSIZE]={","float");
    for(i=0;i<DIMSIZE;i++) printf("%s%1.3f",COMMA,float32v[i]);
    printf("};\n");
#else
    COMPARE(NC_FLOAT,NC_FLOAT,float32v,int82float32_data);
#endif

    CHECK(nc_inq_varid(ncid, "i16", &varid));
    CHECK(nc_get_var_short(ncid,varid,int16v));
#ifdef GENERATE
    printf("static %s int16_data[DIMSIZE]={","short");
    for(i=0;i<DIMSIZE;i++) printf("%s%hd",COMMA,int16v[i]);
    printf("};\n");
#else
    COMPARE(NC_SHORT,NC_SHORT,int16v,int16_data);
#endif

    CHECK(nc_inq_varid(ncid, "i16", &varid));
    CHECK(nc_get_var_int(ncid,varid,int32v));
#ifdef GENERATE
    printf("static %s int16toint32_data[DIMSIZE]={","int");
    for(i=0;i<DIMSIZE;i++) printf("%s%d",COMMA,int32v[i]);
    printf("};\n");
#else
    COMPARE(NC_SHORT,NC_INT,int32v,int16toint32_data);
#endif

    CHECK(nc_inq_varid(ncid, "i16", &varid));
    CHECK(nc_get_var_float(ncid,varid,float32v));
#ifdef GENERATE
    printf("static %s int162float32_data[DIMSIZE]={","float");
    for(i=0;i<DIMSIZE;i++) printf("%s%1.3f",COMMA,float32v[i]);
    printf("};\n");
#else
    COMPARE(NC_SHORT,NC_FLOAT,float32v,int162float32_data);
#endif

    CHECK(nc_inq_varid(ncid, "i32", &varid));
    CHECK(nc_get_var_int(ncid,varid,int32v));
#ifdef GENERATE
    printf("static %s int32_data[DIMSIZE]={","int");
    for(i=0;i<DIMSIZE;i++) printf("%s%d",COMMA,int32v[i]);
    printf("};\n");
#else
    COMPARE(NC_INT,NC_INT,int32v,int32_data);
#endif

    CHECK(nc_inq_varid(ncid, "i32", &varid));
    CHECK(nc_get_var_float(ncid,varid,float32v));
#ifdef GENERATE
    printf("static %s int32tofloat32_data[DIMSIZE]={","float");
    for(i=0;i<DIMSIZE;i++) printf("%s%1.3f",COMMA,float32v[i]);
    printf("};\n");
#else
    COMPARE(NC_INT,NC_FLOAT,float32v,int32tofloat32_data);
#endif

    CHECK(nc_inq_varid(ncid, "i32", &varid));
    CHECK(nc_get_var_long(ncid,varid,ilong));
#ifdef GENERATE
    printf("static %s int32toilong_data[DIMSIZE]={","long");
    for(i=0;i<DIMSIZE;i++) printf("%s%ld",COMMA,ilong[i]);
    printf("};\n");
#else
    COMPARE(NC_INT,NC_NAT,ilong,int32toilong_data);
#endif

    CHECK(nc_inq_varid(ncid, "f32", &varid));
    CHECK(nc_get_var_float(ncid,varid,float32v));
#ifdef GENERATE
    printf("static %s float32_data[DIMSIZE]={","float");
    for(i=0;i<DIMSIZE;i++) printf("%s%1.3f",COMMA,float32v[i]);
    printf("};\n");
#else
    COMPARE(NC_FLOAT,NC_FLOAT,float32v,float32_data);
#endif

    CHECK(nc_inq_varid(ncid, "f64", &varid));
    CHECK(nc_get_var_double(ncid,varid,float64v));
#ifdef GENERATE
    printf("static %s float64_data[DIMSIZE]={","double");
    for(i=0;i<DIMSIZE;i++) printf("%s%1.3f",COMMA,float64v[i]);
    printf("};\n");
#else
    COMPARE(NC_DOUBLE,NC_DOUBLE,float64v,float64_data);
#endif

    if(failure) {
        printf("ncstat=%d %s",ncstat,nc_strerror(ncstat));
        exit(1);
    }
    return 0;
}
Example #13
0
int ex_get_variable_names (int   exoid,
         ex_entity_type obj_type,
         int   num_vars,
         char *var_names[])
{
  int varid, status;
  char errmsg[MAX_ERR_LENGTH];
  const char* vvarname;

  exerrval = 0; /* clear error code */

  switch (obj_type) {
  case EX_NODAL:
    vvarname = VAR_NAME_NOD_VAR;
    break;
  case EX_EDGE_BLOCK:
    vvarname = VAR_NAME_EDG_VAR;
    break;
  case EX_FACE_BLOCK:
    vvarname = VAR_NAME_FAC_VAR;
    break;
  case EX_ELEM_BLOCK:
    vvarname = VAR_NAME_ELE_VAR;
    break;
  case EX_NODE_SET:
    vvarname = VAR_NAME_NSET_VAR;
    break;
  case EX_EDGE_SET:
    vvarname = VAR_NAME_ESET_VAR;
    break;
  case EX_FACE_SET:
    vvarname = VAR_NAME_FSET_VAR;
    break;
  case EX_SIDE_SET:
    vvarname = VAR_NAME_SSET_VAR;
    break;
  case EX_ELEM_SET:
    vvarname = VAR_NAME_ELSET_VAR;
    break;
  case EX_GLOBAL:
    vvarname = VAR_NAME_GLO_VAR;
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf(errmsg,
      "Warning: invalid variable type %d requested from file id %d",
      obj_type, exoid);
    ex_err("ex_get_variable_names",errmsg,exerrval);
    return (EX_WARN);
  }

  /* inquire previously defined variables  */
  if ((status = nc_inq_varid(exoid, vvarname, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg, "Warning: no %s variables names stored in file id %d",
      ex_name_of_object(obj_type),exoid);
    ex_err("ex_get_variable_names",errmsg,exerrval);
    return (EX_WARN);
  }

  /* read the variable names */
  status = ex_get_names_internal(exoid, varid, num_vars, var_names, obj_type, "ex_get_variable_names");
  if (status != NC_NOERR) {
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
Example #14
0
int
main()
{
   int ncid, pres_varid, temp_varid;
   int lat_varid, lon_varid;

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

   /* Program variables to hold the data we will read. We will only
      need enough space to hold one timestep of data; one record. */
   float pres_in[NLVL][NLAT][NLON];
   float temp_in[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;

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

   /* 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[0])))
      ERR(retval);
   if ((retval = nc_get_var_float(ncid, lon_varid, &lons[0])))
      ERR(retval);

   /* Check the coordinate variable data. */
   for (lat = 0; lat < NLAT; lat++)
      if (lats[lat] != START_LAT + 5.*lat)
	 return 2;
   for (lon = 0; lon < NLON; lon++)
      if (lons[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 one timestep. */
   count[0] = 1;
   count[1] = NLVL;
   count[2] = NLAT;
   count[3] = NLON;
   start[1] = 0;
   start[2] = 0;
   start[3] = 0;

   /* Read and check one record at a time. */
   for (rec = 0; rec < NREC; rec++)
   {
      start[0] = rec;
      if ((retval = nc_get_vara_float(ncid, pres_varid, start, 
				      count, &pres_in[0][0][0])))
	 ERR(retval);
      if ((retval = nc_get_vara_float(ncid, temp_varid, start,
				      count, &temp_in[0][0][0])))
	 ERR(retval);

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

   } /* next record */

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

   printf("*** SUCCESS reading example file pres_temp_4D.nc!\n");
   return 0;
}
Example #15
0
/*! \internal */
int
cpy_var_val(int in_id,int out_id,char *var_nm)
/*
   int in_id: input netCDF input-file ID
   int out_id: input netCDF output-file ID
   char *var_nm: input variable name
 */
{
  /* Routine to copy the variable data from an input netCDF file
   * to an output netCDF file. 
   */

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

  void *void_ptr = NULL;

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

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

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

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

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

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

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

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

  /* Get the variable */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return(EX_NOERR);

} /* end cpy_var_val() */
Example #16
0
int ex_get_attr( int   exoid,
                 ex_entity_type obj_type,
                 ex_entity_id   obj_id,
                 void* attrib )

{
  int status;
  int attrid, obj_id_ndx;
  char errmsg[MAX_ERR_LENGTH];
  const char* vattrbname;

  exerrval = 0; /* clear error code */

  /* Determine index of obj_id in vobjids array */
  if (obj_type == EX_NODAL)
    obj_id_ndx = 0;
  else {
    obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id);
    
    if (exerrval != 0) {
      if (exerrval == EX_NULLENTITY) {
	sprintf(errmsg,
		"Warning: no attributes found for NULL %s %"PRId64" in file id %d",
		ex_name_of_object(obj_type),obj_id,exoid);
	ex_err("ex_get_attr",errmsg,EX_NULLENTITY);
	return (EX_WARN);              /* no attributes for this object */
      } else {
	sprintf(errmsg,
		"Warning: failed to locate %s id %"PRId64" in id array in file id %d",
		ex_name_of_object(obj_type),obj_id, exoid);
	ex_err("ex_get_attr",errmsg,exerrval);
	return (EX_WARN);
      }
    }
  }

  switch (obj_type) {
  case EX_SIDE_SET:
    vattrbname = VAR_SSATTRIB(obj_id_ndx);
    break;
  case EX_NODE_SET:
    vattrbname = VAR_NSATTRIB(obj_id_ndx);
    break;
  case EX_EDGE_SET:
    vattrbname = VAR_ESATTRIB(obj_id_ndx);
    break;
  case EX_FACE_SET:
    vattrbname = VAR_FSATTRIB(obj_id_ndx);
    break;
  case EX_ELEM_SET:
    vattrbname = VAR_ELSATTRIB(obj_id_ndx);
    break;
  case EX_NODAL:
    vattrbname = VAR_NATTRIB;
    break;
  case EX_EDGE_BLOCK:
    vattrbname = VAR_EATTRIB(obj_id_ndx);
    break;
  case EX_FACE_BLOCK:
    vattrbname = VAR_FATTRIB(obj_id_ndx);
    break;
  case EX_ELEM_BLOCK:
    vattrbname = VAR_ATTRIB(obj_id_ndx);
    break;
  default:
    exerrval = 1005;
    sprintf(errmsg,
	    "Internal Error: unrecognized object type in switch: %d in file id %d",
	    obj_type,exoid);
    ex_err("ex_get_attr",errmsg,EX_MSG);
    return (EX_FATAL);              /* number of attributes not defined */
  }

  /* inquire id's of previously defined dimensions  */
  if ((status = nc_inq_varid(exoid, vattrbname, &attrid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to locate attributes for %s %"PRId64" in file id %d",
            ex_name_of_object(obj_type), obj_id,exoid);
    ex_err("ex_get_attr",errmsg,exerrval);
    return (EX_FATAL);
  }


  /* read in the attributes */
  if (ex_comp_ws(exoid) == 4) {
    status = nc_get_var_float(exoid, attrid, attrib);
  } else {
    status = nc_get_var_double(exoid, attrid, attrib);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get attributes for %s %"PRId64" in file id %d",
            ex_name_of_object(obj_type),obj_id,exoid);
    ex_err("ex_get_attr",errmsg,exerrval);
    return (EX_FATAL);
  }
  return(EX_NOERR);
}
Example #17
0
/*! \internal */
int
cpy_coord_val(int in_id,int out_id,char *var_nm,
              int in_large, int out_large)
/*
   int in_id: input netCDF input-file ID
   int out_id: input netCDF output-file ID
   char *var_nm: input variable name
 */
{
  /* Routine to copy the coordinate data from an input netCDF file
   * to an output netCDF file. 
   */

  const char *routine = NULL;
  int temp;
  size_t i;
  size_t spatial_dim, num_nodes;
  size_t start[2], count[2];
  nc_type var_type_in, var_type_out;

  void *void_ptr = NULL;

  /* Handle easiest situation first: in_large matches out_large */
  if (in_large == out_large)
    return cpy_var_val(in_id, out_id, var_nm);
  
  /* At this point, know that in_large != out_large, so will need to
     either copy a vector to multiple scalars or vice-versa.  Also
     will need a couple dimensions, so get them now.*/
  ex_get_dimension(in_id, DIM_NUM_DIM, "dimension", &spatial_dim, &temp, routine);
  ex_get_dimension(in_id, DIM_NUM_NODES, "nodes",   &num_nodes, &temp, routine);

  if (in_large == 0 && out_large == 1) {
    /* output file will have coordx, coordy, coordz (if 3d). */
    /* Get the var_id for the requested variable from both files. */
    int var_in_id, var_out_id[3];
    (void)nc_inq_varid(in_id, VAR_COORD, &var_in_id);

    (void)nc_inq_varid(out_id, VAR_COORD_X, &var_out_id[0]);
    (void)nc_inq_varid(out_id, VAR_COORD_Y, &var_out_id[1]);
    (void)nc_inq_varid(out_id, VAR_COORD_Z, &var_out_id[2]);

    (void)nc_inq_vartype( in_id, var_in_id,     &var_type_in);
    (void)nc_inq_vartype(out_id, var_out_id[0], &var_type_out);

    if (num_nodes > 0)
        void_ptr=malloc(num_nodes * type_size(var_type_in));

    /* Copy each component of the variable... */
    for (i=0; i < spatial_dim; i++) {
      start[0] = i; start[1] = 0;
      count[0] = 1; count[1] = num_nodes;
      if (var_type_in == NC_FLOAT) {
	nc_get_vara_float(in_id, var_in_id,     start, count, void_ptr);
	nc_put_var_float(out_id, var_out_id[i],               void_ptr);
      } else {
	assert(var_type_in == NC_DOUBLE);
	nc_get_vara_double(in_id, var_in_id,    start, count, void_ptr);
	nc_put_var_double(out_id, var_out_id[i],              void_ptr);
      }
    }
  }

  if (in_large == 1 && out_large == 0) {
    /* input file will have coordx, coordy, coordz (if 3d); output has only "coord" */
    int var_in_id[3], var_out_id;
    (void)nc_inq_varid(in_id,  VAR_COORD_X, &var_in_id[0]);
    (void)nc_inq_varid(in_id,  VAR_COORD_Y, &var_in_id[1]);
    (void)nc_inq_varid(in_id,  VAR_COORD_Z, &var_in_id[2]);
    (void)nc_inq_varid(out_id, VAR_COORD,   &var_out_id);
    
    (void)nc_inq_vartype(in_id,  var_in_id[0], &var_type_in);
    (void)nc_inq_vartype(out_id, var_out_id,   &var_type_out);

    if (num_nodes > 0)
        void_ptr=malloc(num_nodes * type_size(var_type_in));

    /* Copy each component of the variable... */
    for (i=0; i < spatial_dim; i++) {
      start[0] = i; start[1] = 0;
      count[0] = 1; count[1] = num_nodes;

      if (var_type_in == NC_FLOAT) {
        nc_get_var_float( in_id,  var_in_id[i],               void_ptr);
        nc_put_vara_float(out_id, var_out_id,   start, count, void_ptr);
      
      } else {
        nc_get_var_double( in_id,  var_in_id[i],               void_ptr);
        nc_put_vara_double(out_id, var_out_id,   start, count, void_ptr);
      }
    }
  }

  /* Free the space that held the variable */
  (void)free(void_ptr);
  return(EX_NOERR);
} /* end cpy_coord_val() */
Example #18
0
void readAtmos_ncdf(int xi, int yi, Atmosphere *atmos, Geometry *geometry,
		    NCDF_Atmos_file *infile)
/* Reads the variables T, ne, vel, nh for a given (xi,yi) pair */ 
{
  const char routineName[] = "readAtmos_ncdf";
  size_t     start[]    = {0, 0, 0, 0}; /* starting values */
  size_t     count[]    = {1, 1, 1, 1};
  size_t     start_nh[] = {0, 0, 0, 0, 0};
  size_t     count_nh[] = {1, 1, 1, 1, 1};
  int        ncid, ierror, i, j, z_varid;
  bool_t     old_moving;
  double    *Bx, *By, *Bz;

  ncid = infile->ncid;

  atmos->Nspace = geometry->Ndep = infile->nz;

  /* read full T column, to see where to zcut */
  start[0] = input.p15d_nt; count[0] = 1;
  start[1] = (size_t) xi;   count[1] = 1;
  start[2] = (size_t) yi;   count[2] = 1;
  start[3] = 0;             count[3] = infile->nz;
  
  atmos->T = (double *) realloc(atmos->T, infile->nz * sizeof(double)); 

  if ((ierror = nc_get_vara_double(ncid, infile->T_varid,  start, count, atmos->T)))
    ERR(ierror,routineName);

  /* Finds z value for Tmax cut, redefines Nspace, reallocates arrays */
  /* Tiago: not using this at the moment, only z cut in depth_refine */
  if (input.p15d_zcut) {
    setTcut(atmos, geometry, input.p15d_tmax);
  } else {
    mpi.zcut = 0;
  }

  /* Get z again */
  start[0] = input.p15d_nt; count[0] = 1;
  start[1] = mpi.zcut;      count[1] = atmos->Nspace;

  if ((ierror=nc_inq_varid(ncid, "z",  &z_varid)))          
    ERR(ierror,routineName);
  if ((ierror = nc_get_vara_double(ncid, z_varid, start, count, geometry->height))) 
    ERR(ierror,routineName);
 

  start[0] = input.p15d_nt; count[0] = 1;
  start[1] = (size_t) xi;   count[1] = 1;
  start[2] = (size_t) yi;   count[2] = 1;
  start[3] = mpi.zcut;      count[3] = atmos->Nspace;

   /* read variables */
  if ((ierror = nc_get_vara_double(ncid, infile->T_varid,  start, count, atmos->T)))
    ERR(ierror,routineName);
  if ((ierror = nc_get_vara_double(ncid, infile->ne_varid, start, count, atmos->ne)))
    ERR(ierror,routineName);
  if ((ierror = nc_get_vara_double(ncid, infile->vz_varid, start, count, geometry->vel)))
    ERR(ierror,routineName);
  /* vturb, if available */   
  if (infile->vturb_varid != -1) {
    if ((ierror = nc_get_vara_double(ncid, infile->vturb_varid, &start[3], &count[3],
				     atmos->vturb))) ERR(ierror,routineName);
  }

  /* Read magnetic field */
  if (atmos->Stokes) {
    Bx = (double *) malloc(atmos->Nspace * sizeof(double));
    By = (double *) malloc(atmos->Nspace * sizeof(double));
    Bz = (double *) malloc(atmos->Nspace * sizeof(double));
    /* Read in cartesian coordinates */
    if ((ierror = nc_get_vara_double(ncid, infile->Bx_varid,  start, count,
				     Bx))) ERR(ierror,routineName);
    if ((ierror = nc_get_vara_double(ncid, infile->By_varid,  start, count,
				     By))) ERR(ierror,routineName);
    if ((ierror = nc_get_vara_double(ncid, infile->Bz_varid,  start, count,
				     Bz))) ERR(ierror,routineName);
    
    /* Convert to spherical coordinates */
    for (j = 0; j < atmos->Nspace; j++) {
      atmos->B[j]       = sqrt(SQ(Bx[j]) + SQ(By[j]) + SQ(Bz[j]));
      atmos->gamma_B[j] = acos(Bz[j]/atmos->B[j]);
      atmos->chi_B[j]   = atan(By[j]/Bx[j]);
      
      /* Protect from undefined cases */
      if ((Bx[j] == 0) && (By[j] == 0) && (Bz[j] == 0))
	atmos->gamma_B[j] = 0.0;
      
      if ((Bx[j] == 0) && (By[j] == 0))
	atmos->chi_B[j]   = 1.0;
    }

    free(Bx); free(By); free(Bz);
  }
  


  /* allocate and zero nHtot */
  atmos->nH = matrix_double(atmos->NHydr, atmos->Nspace);  
  for (j = 0; j < atmos->Nspace; j++) atmos->nHtot[j] = 0.0; 

  /* read nH, all at once */
  start_nh[0] = input.p15d_nt; count_nh[0] = 1;
  start_nh[1] = 0;             count_nh[1] = atmos->NHydr;
  start_nh[2] = (size_t) xi;   count_nh[2] = 1;
  start_nh[3] = (size_t) yi;   count_nh[3] = 1;
  start_nh[4] = mpi.zcut;      count_nh[4] = atmos->Nspace;
  if ((ierror = nc_get_vara_double(ncid, infile->nh_varid, start_nh, count_nh, 
				   atmos->nH[0]))) ERR(ierror,routineName);

  /* Depth grid refinement */
  if (input.p15d_refine)
    depth_refine(atmos, geometry, input.p15d_tmax);
  
  /* Fix vturb: remove zeros, use multiplier and add */
  for (i = 0; i < atmos->Nspace; i++) {
    if (atmos->vturb[i] < 0.0) atmos->vturb[i] = 0.0;
    atmos->vturb[i] = atmos->vturb[i] * input.vturb_mult + input.vturb_add;
  }

  /* Sum to get nHtot */
  for (i = 0; i < atmos->NHydr; i++){
    for (j = 0; j < atmos->Nspace; j++) atmos->nHtot[j] += atmos->nH[i][j];
  }
  
  /* Some other housekeeping */
  old_moving = atmos->moving;
  atmos->moving = FALSE;
  for (i = 0;  i < atmos->Nspace;  i++) {
    if (fabs(geometry->vel[i]) >= atmos->vmacro_tresh) {
      atmos->moving = TRUE;
      /* old_moving should only be false*/
      if ((old_moving == FALSE) & (atmos->moving == TRUE)) {
	sprintf(messageStr,
		"Moving atmosphere detected when the previous column\n"
		" (or column [0,0] in file) was not. This will cause problems\n"
		" and the code will abort.\n"
		" To prevent this situation one can force all columns\n"
		" to be moving by setting VMACRO_TRESH = 0 in keyword.input\n");
	Error(ERROR_LEVEL_2, routineName, messageStr);
      }
      break;
    }
  }

  return;
}
Example #19
0
int ex_put_set_param (int exoid,
                      ex_entity_type set_type,
                      int set_id,
                      int num_entries_in_set,
                      int num_dist_fact_in_set)
{
  int status;
  size_t temp;
  int dimid, varid, set_id_ndx, dims[1]; 
  size_t start[1]; 
  int num_sets;
  int ldum;
  int cur_num_sets, set_stat;
  char errmsg[MAX_ERR_LENGTH];
  char* dimptr = NULL;
  char* idsptr = NULL;
  char* statptr = NULL;
  char* numentryptr = NULL;
  char* numdfptr = NULL;
  char* factptr = NULL;
  char* entryptr = NULL;
  char* extraptr = NULL;

  exerrval = 0; /* clear error code */

  /* setup pointers based on set_type 
     NOTE: there is another block that sets more stuff later ... */
  if (set_type == EX_NODE_SET) {
    dimptr = DIM_NUM_NS;
    idsptr = VAR_NS_IDS;
    statptr = VAR_NS_STAT;
  }
  else if (set_type == EX_EDGE_SET) {
    dimptr = DIM_NUM_ES;
    idsptr = VAR_ES_IDS;
    statptr = VAR_ES_STAT;
  }
  else if (set_type == EX_FACE_SET) {
    dimptr = DIM_NUM_FS;
    idsptr = VAR_FS_IDS;
    statptr = VAR_FS_STAT;
  }
  else if (set_type == EX_SIDE_SET) {
    dimptr = DIM_NUM_SS;
    idsptr = VAR_SS_IDS;
    statptr = VAR_SS_STAT;
  }
  else if (set_type == EX_ELEM_SET) {
    dimptr = DIM_NUM_ELS;
    idsptr = VAR_ELS_IDS;
    statptr = VAR_ELS_STAT;
  }
  else {
    exerrval = EX_FATAL;
    sprintf(errmsg,
      "Error: invalid set type (%d)", set_type);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* first check if any of that set type is specified */

  if ((status = nc_inq_dimid(exoid, dimptr, &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: no %ss specified in file id %d", ex_name_of_object(set_type),
      exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* Check for duplicate set id entry */
  ex_id_lkup(exoid, set_type, set_id);
  if (exerrval != EX_LOOKUPFAIL) {  /* found the side set id */
    sprintf(errmsg,
      "Error: %s %d already defined in file id %d", ex_name_of_object(set_type),
      set_id,exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return(EX_FATAL);
  }

  /* Get number of sets specified for this file */
  if ((status = nc_inq_dimlen(exoid,dimid,&temp)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get number of %ss in file id %d",
      ex_name_of_object(set_type), exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }
  num_sets = temp;


  /* Keep track of the total number of sets defined using a counter stored
     in a linked list keyed by exoid.
     NOTE: ex_get_file_item finds the maximum number of sets defined
     for a specific file and returns that value.
  */
  cur_num_sets=ex_get_file_item(exoid, ex_get_counter_list(set_type));
  if (cur_num_sets >= num_sets) {
    exerrval = EX_FATAL;
    sprintf(errmsg,
      "Error: exceeded number of %ss (%d) defined in file id %d",
      ex_name_of_object(set_type), num_sets,exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /*   NOTE: ex_inc_file_item finds the current number of sets defined
       for a specific file and returns that value incremented. */

  cur_num_sets=ex_inc_file_item(exoid, ex_get_counter_list(set_type));
  set_id_ndx = cur_num_sets + 1;

  /* setup more pointers based on set_type */
  if (set_type == EX_NODE_SET) {
    numentryptr = DIM_NUM_NOD_NS(set_id_ndx);
    entryptr = VAR_NODE_NS(set_id_ndx);
    extraptr = NULL;
    /* note we are using DIM_NUM_NODE_NS instead of DIM_NUM_DF_NS */
    numdfptr = DIM_NUM_NOD_NS(set_id_ndx);
    factptr = VAR_FACT_NS(set_id_ndx);
  }
  else if (set_type == EX_EDGE_SET) {
    numentryptr = DIM_NUM_EDGE_ES(set_id_ndx);
    entryptr = VAR_EDGE_ES(set_id_ndx);
    extraptr = VAR_ORNT_ES(set_id_ndx);
    numdfptr = DIM_NUM_DF_ES(set_id_ndx);
    factptr = VAR_FACT_ES(set_id_ndx);
  }
  else if (set_type == EX_FACE_SET) {
    numentryptr = DIM_NUM_FACE_FS(set_id_ndx);
    entryptr = VAR_FACE_FS(set_id_ndx);
    extraptr = VAR_ORNT_FS(set_id_ndx);
    numdfptr = DIM_NUM_DF_FS(set_id_ndx);
    factptr = VAR_FACT_FS(set_id_ndx);
  }
  else if (set_type == EX_SIDE_SET) {
    numentryptr = DIM_NUM_SIDE_SS(set_id_ndx);
    entryptr = VAR_ELEM_SS(set_id_ndx);
    extraptr = VAR_SIDE_SS(set_id_ndx);
    numdfptr = DIM_NUM_DF_SS(set_id_ndx);
    factptr = VAR_FACT_SS(set_id_ndx);
  }
  if (set_type == EX_ELEM_SET) {
    numentryptr = DIM_NUM_ELE_ELS(set_id_ndx);
    entryptr = VAR_ELEM_ELS(set_id_ndx);
    extraptr = NULL;
    numdfptr = DIM_NUM_DF_ELS(set_id_ndx);
    factptr = VAR_FACT_ELS(set_id_ndx);
  }

  /* write out information to previously defined variable */

  /* first: get id of set id variable */
  if ((status = nc_inq_varid(exoid, idsptr, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to locate %s %d in file id %d", ex_name_of_object(set_type),
      set_id, exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* write out set id */
  start[0] = cur_num_sets;

  ldum = (int)set_id;
  if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to store %s id %d in file id %d", ex_name_of_object(set_type),
      set_id, exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_entries_in_set == 0) /* Is this a NULL  set? */
    set_stat = 0; /* change set status to NULL */
  else
    set_stat = 1; /* change set status to TRUE */

  if ((status = nc_inq_varid(exoid, statptr, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to locate %s status in file id %d", ex_name_of_object(set_type),
      exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  ldum = (int)set_stat;
  if ((status = nc_put_var1_int(exoid, varid, start, &ldum)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to store %s %d status to file id %d", ex_name_of_object(set_type),
      set_id, exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_entries_in_set == 0) {/* Is this a NULL set? */
    return(EX_NOERR);
  }

  /* put netcdf file into define mode  */
  if ((status = nc_redef (exoid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to put file id %d into define mode",
      exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }


  /* define dimensions and variables */
  if ((status = nc_def_dim(exoid, numentryptr,
         num_entries_in_set, &dimid)) != NC_NOERR) {
    exerrval = status;
    if (status == NC_ENAMEINUSE)
      {
  sprintf(errmsg,
    "Error: %s %d size already defined in file id %d",
    ex_name_of_object(set_type), set_id,exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
      }
    else {
      sprintf(errmsg,
        "Error: failed to define number of entries in %s %d in file id %d",
        ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_put_set_param",errmsg,exerrval);
    }
    goto error_ret;
  }

  /* create variable array in which to store the entry lists */

  dims[0] = dimid;
  if ((status = nc_def_var(exoid, entryptr, NC_INT, 1, dims, &varid)) != NC_NOERR) {
    exerrval = status;
    if (status == NC_ENAMEINUSE) {
      sprintf(errmsg,
        "Error: entry list already exists for %s %d in file id %d",
        ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_put_set_param",errmsg,exerrval);
    } else {
      sprintf(errmsg,
        "Error: failed to create entry list for %s %d in file id %d",
        ex_name_of_object(set_type), set_id,exoid);
      ex_err("ex_put_set_param",errmsg,exerrval);
    }
    goto error_ret;            /* exit define mode and return */
  }

  if (extraptr) {
    if ((status = nc_def_var(exoid, extraptr, NC_INT, 1, dims, &varid)) != NC_NOERR) {
      exerrval = status;
      if (status == NC_ENAMEINUSE) {
  sprintf(errmsg,
    "Error: extra list already exists for %s %d in file id %d",
    ex_name_of_object(set_type), set_id, exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
      } else {
  sprintf(errmsg,
    "Error: failed to create extra list for %s %d in file id %d",
    ex_name_of_object(set_type), set_id,exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
      }
      goto error_ret;         /* exit define mode and return */
           
    }
  }

  /* Create distribution factors variable if required */

  if (num_dist_fact_in_set > 0) {

    if (set_type == EX_NODE_SET) {
      /* but num_dist_fact_in_set must equal number of nodes */
      if (num_dist_fact_in_set != num_entries_in_set) {
  exerrval = EX_FATAL;
  sprintf(errmsg,
    "Error: # dist fact (%d) not equal to # nodes (%d) in node  set %d file id %d",
    num_dist_fact_in_set, num_entries_in_set, set_id, exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
  goto error_ret;    /* exit define mode and return */
      }

      /* resuse dimid from entry lists */

    } else {
      if ((status = nc_def_dim(exoid, numdfptr, 
             num_dist_fact_in_set, &dimid)) != NC_NOERR) {
  exerrval = status;
  sprintf(errmsg,
    "Error: failed to define number of dist factors in %s %d in file id %d",
    ex_name_of_object(set_type), set_id,exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
  goto error_ret;          /* exit define mode and return */
      }
    }

    /* create variable array in which to store the set distribution factors
     */
    dims[0] = dimid;
    if ((status = nc_def_var(exoid, factptr, nc_flt_code(exoid), 1, dims, &varid)) != NC_NOERR) {
      exerrval = status;
      if (status == NC_ENAMEINUSE) {
  sprintf(errmsg,
    "Error: dist factors list already exists for %s %d in file id %d",
    ex_name_of_object(set_type), set_id,exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
      } else {
  sprintf(errmsg,
    "Error: failed to create dist factors list for %s %d in file id %d",
    ex_name_of_object(set_type), set_id,exoid);
  ex_err("ex_put_set_param",errmsg,exerrval);
      }
      goto error_ret;            /* exit define mode and return */
    }
  }

  /* leave define mode  */
  if ((status = nc_enddef (exoid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to complete definition in file id %d", exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  if (nc_enddef (exoid) != NC_NOERR) {    /* exit define mode */
    sprintf(errmsg,
      "Error: failed to complete definition for file id %d",
      exoid);
    ex_err("ex_put_set_param",errmsg,exerrval);
  }
  return (EX_FATAL);
}
Example #20
0
void init_ncdf_atmos(Atmosphere *atmos, Geometry *geometry, NCDF_Atmos_file *infile)
/* Initialises the input atmosphere file, gets dimensions and variable ids. 
   Also performs other basic RH initialisations like readAbundance       */
{ 
  const char routineName[] = "init_ncdf";
  struct  stat statBuffer;
  int ierror, ncid, x_varid, y_varid, z_varid, has_B, sn_varid;
  size_t nn;
  size_t start[] = {0, 0};
  size_t count[] = {1, 1};
  char *filename;


  /* --- Get abundances of background elements --      -------------- */

  readAbundance(atmos);

  /* --- Open input file for model atmosphere --       -------------- */
  if ((ierror = nc_open_par(input.atmos_input ,NC_NOWRITE | NC_MPIIO, mpi.comm, 
			    mpi.info, &infile->ncid))) ERR(ierror,routineName);

  ncid = infile->ncid;

  /* Is magnetic field included? */
  if ((ierror = nc_get_att_int( ncid, NC_GLOBAL, "has_B", &has_B))) 
    ERR(ierror,routineName);

  atmos->Stokes = FALSE;
  if ((has_B) && (strcmp(input.Stokes_input, "none"))) atmos->Stokes = TRUE;


  /* Get the dimids and values */
  if ((ierror = nc_inq_dimid( ncid, "nx", &infile->nx_id)))       ERR(ierror,routineName);
  if ((ierror = nc_inq_dimlen(ncid, infile->nx_id, &infile->nx))) ERR(ierror,routineName);

  if ((ierror = nc_inq_dimid( ncid, "ny", &infile->ny_id)))       ERR(ierror,routineName);
  if ((ierror = nc_inq_dimlen(ncid, infile->ny_id, &infile->ny))) ERR(ierror,routineName);

  if ((ierror = nc_inq_dimid( ncid, "nz", &infile->nz_id)))       ERR(ierror,routineName);
  if ((ierror = nc_inq_dimlen(ncid, infile->nz_id, &infile->nz))) ERR(ierror,routineName);

  if ((ierror = nc_inq_dimid( ncid, "nhydr", &infile->nhyd_id)))  ERR(ierror,routineName);
  if ((ierror = nc_inq_dimlen(ncid, infile->nhyd_id, &nn)))       ERR(ierror,routineName);

  /* get some values in atmos/geometry structures */
  geometry->Ndep = (int)  infile->nz;
  atmos->Nspace  = (long) infile->nz;
  atmos->NHydr   = (int)  nn;


  if (atmos->NHydr < 2  &&  !atmos->H_LTE) {
    sprintf(messageStr, "NHydr has to be at least 2, not %d to run with"
	    " NLTE hydrogen populations in background\n", atmos->NHydr);
    Error(ERROR_LEVEL_2, routineName, messageStr);
  }

  /* Get the varids */
  if ((ierror=nc_inq_varid(ncid, TEMP_NAME, &infile->T_varid)))  ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, NE_NAME,   &infile->ne_varid))) ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, VZ_NAME,   &infile->vz_varid))) ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, NH_NAME,   &infile->nh_varid))) ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, "z",       &z_varid)))          ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, "y",       &y_varid)))          ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, "x",       &x_varid)))          ERR(ierror,routineName);
  if ((ierror=nc_inq_varid(ncid, SNAPNAME,  &sn_varid)))         ERR(ierror,routineName);
  
  /* Microturbulence, get ID if variable found */
  if ((ierror=nc_inq_varid(ncid, VTURB_NAME, &infile->vturb_varid))) {
    /* exception for variable not found (errcode -49)*/
    if (ierror == -49) infile->vturb_varid = -1; else ERR(ierror,routineName);
  }

  if (atmos->Stokes) {
      if ((ierror = nc_inq_varid(ncid, BX_NAME, &infile->Bx_varid)))
	ERR(ierror,routineName);
      if ((ierror = nc_inq_varid(ncid, BY_NAME, &infile->By_varid)))
	ERR(ierror,routineName);
      if ((ierror = nc_inq_varid(ncid, BZ_NAME, &infile->Bz_varid)))
	ERR(ierror,routineName);
  }

  /* read things that don't depend on x, y */
  start[0] = input.p15d_nt; count[0] = 1;
  start[1] = 0;             count[1] = infile->nz;

  geometry->height = (double *) malloc(infile->nz * sizeof(double));
  if ((ierror = nc_get_vara_double(ncid, z_varid, start, count, geometry->height))) 
    ERR(ierror,routineName);

  infile->y   = (double *) malloc(infile->ny * sizeof(double));
  if ((ierror = nc_get_var_double(ncid, y_varid, infile->y))) ERR(ierror,routineName);
  infile->x   = (double *) malloc(infile->nx * sizeof(double));
  if ((ierror = nc_get_var_double(ncid, x_varid, infile->x))) ERR(ierror,routineName);

  if ((ierror = nc_get_var1_int(ncid, sn_varid, start, &mpi.snap_number)))
    ERR(ierror,routineName);

  /* allocate arrays */
  geometry->vel = (double *) malloc(atmos->Nspace * sizeof(double));
  atmos->T      = (double *) malloc(atmos->Nspace * sizeof(double));
  atmos->ne     = (double *) malloc(atmos->Nspace * sizeof(double));
  atmos->vturb  = (double *) calloc(atmos->Nspace , sizeof(double)); /* default zero */
  atmos->nHtot  = (double *) malloc(atmos->Nspace * sizeof(double));

  if (atmos->Stokes) {
    atmos->B       = (double *) malloc(atmos->Nspace * sizeof(double));
    atmos->gamma_B = (double *) malloc(atmos->Nspace * sizeof(double));
    atmos->chi_B   = (double *) malloc(atmos->Nspace * sizeof(double));
  }

  /* some other housekeeping */ 
  geometry->vboundary[TOP]    = ZERO;
  geometry->vboundary[BOTTOM] = THERMALIZED;
  geometry->scale             = GEOMETRIC;

  /* --- Construct atmosID from filename and last modification date - */
  // NOTE: perhaps later this should be built into the NetCDF file (description attr?)
  stat(input.atmos_input, &statBuffer);
  if ((filename = strrchr(input.atmos_input, '/')) != NULL)
    filename++;
  else
    filename = input.atmos_input;
  sprintf(atmos->ID, "%s (%.24s)", filename,
	  asctime(localtime(&statBuffer.st_mtime)));


  /* --- Get angle-quadrature and copy geometry independent quantity
         wmu to atmos structure. --                    -------------- */

  getAngleQuad(geometry);
  atmos->wmu = geometry->wmu;


  /* --- set up pointers for background opacities --- */

  atmos->chi_b = NULL;
  atmos->eta_b = NULL;
  atmos->sca_b = NULL;

  return;

}
Example #21
0
static int ex_inquire_internal (int      exoid,
				int      req_info,
				int64_t *ret_int,
				float   *ret_float,
				char    *ret_char)
{
  int dimid, varid, tmp_num;
  void_int *ids = NULL;
  size_t i;
  size_t ldum = 0;
  size_t num_sets, idum;
  int *stat_vals;
  char  errmsg[MAX_ERR_LENGTH];
  int status;
  char tmp_title[2048];

  exerrval = 0; /* clear error code */

  if (ret_char)  *ret_char  = '\0';  /* Only needs to be non-null for TITLE */
  
  if (!ret_int) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg,
	    "Warning: integer argument is NULL which is not allowed.");
    ex_err("ex_inquire",errmsg,exerrval);
    return (EX_FATAL);
  }
    

  switch (req_info) {
  case EX_INQ_FILE_TYPE:

    /* obsolete call */
    /*returns "r" for regular EXODUS II file or "h" for history EXODUS file*/
    exerrval = EX_BADPARAM;
    sprintf(errmsg,
	    "Warning: file type inquire is obsolete");
    ex_err("ex_inquire",errmsg,exerrval);
    return (EX_WARN);

  case EX_INQ_API_VERS:
    /* returns the EXODUS II API version number */
    if (!ret_float) {
      exerrval = EX_BADPARAM;
      sprintf(errmsg,
	      "Warning: float argument is NULL for EX_INQ_API_VERS which is not allowed.");
      ex_err("ex_inquire",errmsg,exerrval);
      return (EX_FATAL);
    }

    if (nc_get_att_float(exoid, NC_GLOBAL, ATT_API_VERSION, ret_float) != NC_NOERR)
      {  /* try old (prior to db version 2.02) attribute name */
	if ((status = nc_get_att_float (exoid, NC_GLOBAL, ATT_API_VERSION_BLANK,ret_float)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get EXODUS API version for file id %d", exoid);
	  ex_err("ex_inquire",errmsg,exerrval);
	  return (EX_FATAL);
	}
      }

    break;

  case EX_INQ_DB_VERS:
    /* returns the EXODUS II database version number */
    if (!ret_float) {
      exerrval = EX_BADPARAM;
      sprintf(errmsg,
	      "Warning: float argument is NULL for EX_INQ_DB_VERS which is not allowed.");
      ex_err("ex_inquire",errmsg,exerrval);
      return (EX_FATAL);
    }

    if ((status = nc_get_att_float (exoid, NC_GLOBAL, ATT_VERSION, ret_float)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get EXODUS database version for file id %d", exoid);
      ex_err("ex_inquire",errmsg,exerrval);
      return (EX_FATAL);
    }
    break;

  case EX_INQ_LIB_VERS:
    /* returns the EXODUS II Library version number */
    if (ret_float)
      flt_cvt(ret_float, EX_API_VERS);

    *ret_int = EX_API_VERS_NODOT;
    break;

  case EX_INQ_DB_MAX_ALLOWED_NAME_LENGTH:
    /* Return the MAX_NAME_LENGTH size for this database
       It will not include the space for the trailing null, so if it
       is defined as 33 on the database, 32 will be returned.
    */
    if ((status = nc_inq_dimid(exoid, DIM_STR_NAME, &dimid)) != NC_NOERR) {
      /* If not found, then an older database */
      *ret_int = 32;
    }
    else {
      /* Get the name string length */
      size_t name_length = 0;
      if ((status = nc_inq_dimlen(exoid,dimid,&name_length)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get name string length in file id %d", exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }
      else {
	*ret_int = name_length-1;
      }
    }
    break;

  case EX_INQ_DB_MAX_USED_NAME_LENGTH:
    /* Return the value of the ATT_MAX_NAME_LENGTH attribute (if it
       exists) which is the maximum length of any entity, variable,
       attribute, property name written to this database.  If the
       attribute does not exist, then '32' is returned.  The length
       does not include the trailing null.
    */
    {
      nc_type att_type = NC_NAT;
      size_t att_len = 0;
	
      *ret_int = 32; /* Default size consistent with older databases */

      status = nc_inq_att(exoid, NC_GLOBAL, ATT_MAX_NAME_LENGTH, &att_type, &att_len);
      if (status == NC_NOERR && att_type == NC_INT) {
	/* The attribute exists, return it... */
	nc_get_att_longlong(exoid, NC_GLOBAL, ATT_MAX_NAME_LENGTH, (long long*)ret_int);
      }
    }
    break;

  case EX_INQ_MAX_READ_NAME_LENGTH:
    {
      /* Returns the user-specified maximum size of names that will be
       * returned to the user by any of the ex_get_ routines.  If the
       * name is longer than this value, it will be truncated. The
       * default if not set by the client is 32 characters. The value
       * does not include the trailing null.
       */
      struct file_item* file = ex_find_file_item(exoid);

      if (!file ) {
	exerrval = EX_BADFILEID;
	sprintf(errmsg,"Error: unknown file id %d for ex_inquire_int().",exoid);
	ex_err("ex_intquire",errmsg,exerrval);
	*ret_int = 0;
      }
      else {
	*ret_int = file->maximum_name_length;
      }
    }
    break;

  case EX_INQ_TITLE:
    if (!ret_char) {
      sprintf(errmsg,
	      "Error: Requested title, but character pointer was null for file id %d", exoid);
      ex_err("ex_inquire",errmsg,exerrval);
      return (EX_FATAL);
    } else {
      /* returns the title of the database */
      if ((status = nc_get_att_text (exoid, NC_GLOBAL, ATT_TITLE, tmp_title)) != NC_NOERR) {
	*ret_char = '\0';
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get database title for file id %d", exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      } else {
	strncpy(ret_char, tmp_title, MAX_LINE_LENGTH+1);
	ret_char[MAX_LINE_LENGTH] = '\0';
      }
    }
    break;

  case EX_INQ_DIM:
    /* returns the dimensionality (2 or 3, for 2-d or 3-d) of the database */
    if (ex_get_dimension(exoid, DIM_NUM_DIM, "database dimensionality", &ldum, &dimid, "ex_inquire") != NC_NOERR)
      return EX_FATAL;
    *ret_int = ldum;
    break;

  case EX_INQ_NODES:
    /* returns the number of nodes */
    if (ex_get_dimension(exoid, DIM_NUM_NODES, "nodes", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_ELEM:
    /* returns the number of elements */
    if (ex_get_dimension(exoid, DIM_NUM_ELEM, "elements", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_ELEM_BLK:
    /* returns the number of element blocks */
    if (ex_get_dimension(exoid, DIM_NUM_EL_BLK, "element blocks", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_NODE_SETS:
    /* returns the number of node sets */
    if (ex_get_dimension(exoid, DIM_NUM_NS, "node sets", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_NS_NODE_LEN:
    /* returns the length of the concatenated node sets node list */
    ex_get_concat_set_len(exoid, ret_int,"node",EX_NODE_SET,DIM_NUM_NS,VAR_NS_STAT,"num_nod_ns",0);
    break;

  case EX_INQ_NS_DF_LEN:
    /*     returns the length of the concatenated node sets dist factor list */

    /*
      Determine the concatenated node sets distribution factor length:

      2. Check see if the dist factor variable for a node set id exists.
      3. If it exists, goto step 4, else the length is zero.
      4. Get the dimension of the number of nodes in the node set -0
      use this value as the length as by definition they are the same.
      5. Sum the individual lengths for the total list length.
    */

    *ret_int = 0;    /* default value if no node sets defined */

    if (nc_inq_dimid (exoid, DIM_NUM_NS, &dimid) == NC_NOERR) {
      if ((status = nc_inq_dimlen(exoid, dimid, &num_sets)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get number of node sets in file id %d",
		exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }


      for (i=0; i<num_sets; i++) {
	if ((status = nc_inq_varid (exoid, VAR_FACT_NS(i+1), &varid)) != NC_NOERR) {
	  if (status == NC_ENOTVAR) {
	    idum = 0;        /* this dist factor doesn't exist */
	  } else {
	    *ret_int = 0;
	    exerrval = status;
	    sprintf(errmsg,
		    "Error: failed to locate number of dist fact for %"ST_ZU"'th node set in file id %d",
		    i, exoid);
	    ex_err("ex_inquire",errmsg,exerrval);
	    return (EX_FATAL);
	  }
	} else {
	  if ((status = nc_inq_dimid (exoid, DIM_NUM_NOD_NS(i+1), &dimid)) != NC_NOERR) {
	    *ret_int = 0;
	    exerrval = status;
	    sprintf(errmsg,
		    "Error: failed to locate number of nodes in %"ST_ZU"'th node set in file id %d",
		    i, exoid);
	    ex_err("ex_inquire",errmsg,exerrval);
	    return (EX_FATAL);
	  }
	  if ((status = nc_inq_dimlen (exoid, dimid, &idum)) != NC_NOERR) {
	    *ret_int = 0;
	    exerrval = status;
	    sprintf(errmsg,
		    "Error: failed to get number of nodes in %"ST_ZU"'th node set in file id %d",
		    i,exoid);
	    ex_err("ex_inquire",errmsg,exerrval);
	    return (EX_FATAL);
	  }
	}
	*ret_int += idum;
      }
    }

    break;

  case EX_INQ_SIDE_SETS:
    /* returns the number of side sets */
    if (ex_get_dimension(exoid, DIM_NUM_SS, "side sets", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_SS_NODE_LEN:

    /*     returns the length of the concatenated side sets node list */

    *ret_int = 0;     /* default return value */

    if (nc_inq_dimid (exoid, DIM_NUM_SS, &dimid) == NC_NOERR) {
      if ((status = nc_inq_dimlen(exoid, dimid, &num_sets)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get number of side sets in file id %d",
		exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }


      if (!(ids = malloc(num_sets*sizeof(int64_t)))) { /* May be getting 2x what is needed, but should be OK */
	exerrval = EX_MEMFAIL;
	sprintf(errmsg,
		"Error: failed to allocate memory for side set ids for file id %d",
		exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }

      if (ex_get_side_set_ids (exoid, ids) == EX_FATAL) {
	sprintf(errmsg,
		"Error: failed to get side set ids in file id %d",
		exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	free(ids);
	return (EX_FATAL);
      }

      /* allocate space for stat array */
      if (!(stat_vals = malloc((int)num_sets*sizeof(int)))) {
	exerrval = EX_MEMFAIL;
	free (ids);
	sprintf(errmsg,
		"Error: failed to allocate memory for side set status array for file id %d",
		exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }
      /* get variable id of status array */
      if ((status = nc_inq_varid (exoid, VAR_SS_STAT, &varid)) == NC_NOERR) {
	/* if status array exists, use it, otherwise assume, object exists
	   to be backward compatible */

	if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) {
	  exerrval = status;
	  free (ids);
	  free(stat_vals);
	  sprintf(errmsg,
		  "Error: failed to get element block status array from file id %d",
		  exoid);
	  ex_err("ex_inquire",errmsg,exerrval);
	  return (EX_FATAL);
	}
      }
      else /* default: status is true */
	for(i=0;i<num_sets;i++)
	  stat_vals[i]=1;

      /* walk id list, get each side set node length and sum for total */

      for (i=0; i<num_sets; i++) {
	ex_entity_id id;
	if (stat_vals[i] == 0) /* is this object null? */
	  continue;

	if (ex_int64_status(exoid) & EX_IDS_INT64_API)
	  id = ((int64_t*)ids)[i];
	else
	  id = ((int*)ids)[i];
	  
	if ((status = ex_get_side_set_node_list_len(exoid, id, &tmp_num)) != NC_NOERR) {
	  *ret_int = 0;
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to side set %"PRId64" node length in file id %d",
		  id,exoid);
	  ex_err("ex_inquire",errmsg,exerrval);
	  free(stat_vals);
	  free(ids);
	  return (EX_FATAL);
	}
	*ret_int += tmp_num;
      }

      free(stat_vals);
      free (ids);
    }

    break;

  case EX_INQ_SS_ELEM_LEN:
    /*     returns the length of the concatenated side sets element list */
    ex_get_concat_set_len(exoid, ret_int,"side",EX_SIDE_SET,DIM_NUM_SS,VAR_SS_STAT,"num_side_ss",0);
    break;

  case EX_INQ_SS_DF_LEN:

    /*     returns the length of the concatenated side sets dist factor list */

    /*
      Determine the concatenated side sets distribution factor length:

      1. Get the side set ids list.
      2. Check see if the dist factor dimension for a side set id exists.
      3. If it exists, goto step 4, else set the individual length to zero.
      4. Sum the dimension value into the running total length.
    */

    *ret_int = 0;

    /* first check see if any side sets exist */

    if (nc_inq_dimid (exoid, DIM_NUM_SS, &dimid) == NC_NOERR) {
      if ((status = nc_inq_dimlen (exoid, dimid, &num_sets)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get number of side sets in file id %d",
		exoid);
	ex_err("ex_inquire",errmsg,exerrval);
	return (EX_FATAL);
      }

      for (i=0; i<num_sets; i++) {
	if ((status = nc_inq_dimid (exoid, DIM_NUM_DF_SS(i+1), &dimid)) != NC_NOERR) {
	  if (status == NC_EBADDIM) {
	    ldum = 0;        /* this dist factor doesn't exist */
	  } else {
	    *ret_int = 0;
	    exerrval = status;
	    sprintf(errmsg,
		    "Error: failed to locate number of dist fact for %"ST_ZU"'th side set in file id %d",
		    i, exoid);
	    ex_err("ex_inquire",errmsg,exerrval);
	    return (EX_FATAL);
	  }
	} else {
	  if ((status = nc_inq_dimlen (exoid, dimid, &ldum)) != NC_NOERR) {
	    *ret_int = 0;
	    exerrval = status;
	    sprintf(errmsg,
		    "Error: failed to get number of dist factors in %"ST_ZU"'th side set in file id %d",
		    i, exoid);
	    ex_err("ex_inquire",errmsg,exerrval);
	    return (EX_FATAL);
	  }
	}
	*ret_int += ldum;
      }
    }

    break;

  case EX_INQ_QA:
    /* returns the number of QA records */
    if (ex_get_dimension(exoid, DIM_NUM_QA, "QA records", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_INFO:
    /* returns the number of information records */
    if (ex_get_dimension(exoid, DIM_NUM_INFO, "info records", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_TIME:
    /*     returns the number of time steps stored in the database */
    if (ex_get_dimension(exoid, DIM_TIME, "time dimension", &ldum, &dimid, "ex_inquire") != NC_NOERR)
      return EX_FATAL;
    *ret_int = ldum;
    break;

  case EX_INQ_EB_PROP:
    /* returns the number of element block properties */
    *ret_int = ex_get_num_props (exoid, EX_ELEM_BLOCK);
    break;

  case EX_INQ_NS_PROP:
    /* returns the number of node set properties */
    *ret_int = ex_get_num_props (exoid, EX_NODE_SET);
    break;

  case EX_INQ_SS_PROP:
    /* returns the number of side set properties */
    *ret_int = ex_get_num_props (exoid, EX_SIDE_SET);
    break;

  case EX_INQ_ELEM_MAP:
    /* returns the number of element maps */
    if (ex_get_dimension(exoid, DIM_NUM_EM, "element maps", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_EM_PROP:
    /* returns the number of element map properties */
    *ret_int = ex_get_num_props (exoid, EX_ELEM_MAP);
    break;

  case EX_INQ_NODE_MAP:
    /* returns the number of node maps */
    if (ex_get_dimension(exoid, DIM_NUM_NM, "node maps", &ldum, &dimid, NULL) != NC_NOERR)
      *ret_int = 0;
    else
      *ret_int = ldum;
    break;

  case EX_INQ_NM_PROP:
    /* returns the number of node map properties */
    *ret_int = ex_get_num_props (exoid, EX_NODE_MAP);
    break;

  case EX_INQ_EDGE:
    /* returns the number of edges (defined across all edge blocks). */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_EDGE, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_EDGE_BLK:
    /* returns the number of edge blocks. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_ED_BLK, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_EDGE_SETS:
    /* returns the number of edge sets. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_ES, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_ES_LEN:
    /* returns the length of the concatenated edge set edge list. */
    ex_get_concat_set_len(exoid, ret_int,"edge",EX_EDGE_SET,DIM_NUM_ES,VAR_ES_STAT,"num_edge_es",0);
    break;

  case EX_INQ_ES_DF_LEN:
    /* returns the length of the concatenated edge set distribution factor list. */
    ex_get_concat_set_len(exoid, ret_int,"edge",EX_EDGE_SET,DIM_NUM_ES,VAR_ES_STAT,"num_df_es",1);
    break;

  case EX_INQ_EDGE_PROP:
    /* returns the number of integer properties stored for each edge block. This includes the "ID" property. */
    *ret_int = ex_get_num_props( exoid, EX_EDGE_BLOCK );
    break;

  case EX_INQ_ES_PROP:
    /* returns the number of integer properties stored for each edge set.. This includes the "ID" property */
    *ret_int = ex_get_num_props( exoid, EX_EDGE_SET );
    break;

  case EX_INQ_FACE:
    /* returns the number of faces (defined across all face blocks). */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_FACE, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_FACE_BLK:
    /* returns the number of face blocks. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_FA_BLK, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_FACE_SETS:
    /* returns the number of face sets. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_FS, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_FS_LEN:
    /* returns the length of the concatenated edge set edge list. */
    ex_get_concat_set_len(exoid, ret_int,"face",EX_FACE_SET,DIM_NUM_FS,VAR_FS_STAT,"num_face_fs",0);
    break;

  case EX_INQ_FS_DF_LEN:
    /* returns the length of the concatenated edge set distribution factor list. */
    ex_get_concat_set_len(exoid, ret_int,"face",EX_FACE_SET,DIM_NUM_FS,VAR_FS_STAT,"num_df_fs",1);
    break;

  case EX_INQ_FACE_PROP:
    /* returns the number of integer properties stored for each edge block. This includes the "ID" property. */
    *ret_int = ex_get_num_props( exoid, EX_FACE_BLOCK );
    break;

  case EX_INQ_FS_PROP:
    /* returns the number of integer properties stored for each edge set.. This includes the "ID" property */
    *ret_int = ex_get_num_props( exoid, EX_FACE_SET );
    break;

  case EX_INQ_ELEM_SETS:
    /* returns the number of element sets. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_ELS, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_ELS_LEN:
    /* returns the length of the concatenated element set element list. */
    ex_get_concat_set_len(exoid, ret_int,"element",EX_ELEM_SET,DIM_NUM_ELS,VAR_ELS_STAT,"num_ele_els",0);
    break;

  case EX_INQ_ELS_DF_LEN:
    /* returns the length of the concatenated element set distribution factor list. */
    ex_get_concat_set_len(exoid, ret_int,"element",EX_ELEM_SET,DIM_NUM_ELS,VAR_ELS_STAT,"num_df_els",1);
    break;

  case EX_INQ_ELS_PROP:
    /* returns the number of integer properties stored for each element set. */
    *ret_int = ex_get_num_props( exoid, EX_ELEM_SET );
    break;

  case EX_INQ_EDGE_MAP:
    /* returns the number of edge maps. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_EDM, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_FACE_MAP:
    /*     returns the number of face maps. */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_FAM, 1) != EX_NOERR) return EX_FATAL;
    break;

  case EX_INQ_COORD_FRAMES:
    /* return the number of coordinate frames */
    if (ex_get_dimension_value(exoid, ret_int, 0, DIM_NUM_CFRAMES, 1) != EX_NOERR) return EX_FATAL;
    break;

  default:
    *ret_int = 0;
    exerrval = EX_FATAL;
    sprintf(errmsg, "Error: invalid inquiry %d", req_info);
    ex_err("ex_inquire",errmsg,exerrval);
    return(EX_FATAL);
  }
  return (EX_NOERR);
}
Example #22
0
int
main(int argc, char **argv)
{
   printf("\n*** Testing netcdf-4 dimensions.\n");
   printf("*** Testing that netcdf-4 dimids inq works on netcdf-3 file...");
   {
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];

      /* Create a netcdf-3 file with one dim. */
      if (nc_create(FILE_NAME, 0, &ncid)) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open the file and make sure nc_inq_dimids yeilds correct
       * result. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing that netcdf-4 dimids inq works on more complex netcdf-3 file...");
   {
      int ncid, dimid;
      int lon_dimid;
      int ndims_in, dimids_in[MAX_DIMS];

      /* Create a netcdf-3 file with three dim. */
      if (nc_create(FILE_NAME, 0, &ncid)) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimid)) ERR;
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open the file and make sure nc_inq_dimids yeilds correct
       * result. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 3 || dimids_in[0] != 0 || dimids_in[1] != 1 ||
	 dimids_in[2] != 2) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** Testing file with just one dimension...");
   {
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int dimid_in;

      /* Create a file with one dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimid)) ERR;

      /* Check out what we've got. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (nc_inq_dimid(ncid, LAT_NAME, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (nc_inq_dimid(ncid, LAT_NAME, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** Testing renaming of one dimension...");
   {
      int ncid, dimid, dimid_in;
      char name_in[NC_MAX_NAME + 1];
      size_t len_in;
      int ndims_in, dimids_in[MAX_DIMS];

      /* Reopen the file with one dim, and change the name of the dim. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_rename_dim(ncid, 0, BUBBA)) ERR;

      /* Check out what we've got. */
      dimid = 0;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (dimids_in[0] != 0) ERR;
      if (nc_inq_dimid(ncid, BUBBA, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen and check out what we've got again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_dimid(ncid, BUBBA, &dimid_in)) ERR;
      if (dimid_in != 0) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, BUBBA)) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != LAT_LEN) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing renaming dimensions and vars...");
   {
#define FILE_NAME1 "foo1.nc"
#define FILE_NAME2 "foo2.nc"
#define FILE_NAME3 "foo3.nc"
#define FILE_NAME4 "foo4.nc"
#define DIM_NAME "lat_T42"
#define VAR_NAME DIM_NAME
#define DIM_NAME2 "lat"
#define VAR_NAME2 DIM_NAME2
#define RANK_lat_T42 1
      int  ncid, varid, dimid;
      int lat_T42_dim;
      size_t lat_T42_len = 3;
      int lat_T42_id;
      int lat_T42_dims[RANK_lat_T42];
      char name[NC_MAX_NAME + 1];

    /* =========== */
    /* Sub-test #1 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, rename coordinate dimension and then associated variable */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_rename_dim(ncid, dimid, DIM_NAME2)) ERR;
      if (nc_rename_var(ncid, varid, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like they created the file with DIM_NAME2 & VAR_NAME2 to
       *  begin with.
       */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME2, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME2)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


    /* =========== */
    /* Sub-test #2 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, just rename coordinate dimension */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_rename_dim(ncid, dimid, DIM_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like the file was created with DIM_NAME2 to begin with */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME2, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME2)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME)) ERR;
      if (nc_close(ncid)) ERR;


    /* =========== */
    /* Sub-test #3 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, just rename variable */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_rename_var(ncid, varid, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like the file was created with VAR_NAME2 to begin with */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


    /* =========== */
    /* Sub-test #4 */
    /* =========== */
      /* create file with dimension and associated coordinate variable */
      if (nc_create(FILE_NAME1, NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, lat_T42_len, &lat_T42_dim)) ERR;
      lat_T42_dims[0] = lat_T42_dim;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, RANK_lat_T42, lat_T42_dims, &lat_T42_id)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, rename associated variable and then coordinate dimension */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_rename_var(ncid, varid, VAR_NAME2)) ERR;
      if (nc_rename_dim(ncid, dimid, DIM_NAME2)) ERR;
      if (nc_close(ncid)) ERR;


      /* reopen file, check coordinate dimension and associated variable names */
      /* Should be just like they created the file with DIM_NAME2 & VAR_NAME2 to
       *  begin with.
       */
      if (nc_open(FILE_NAME1, NC_WRITE, &ncid)) ERR;
      if (nc_inq_dimid(ncid, DIM_NAME2, &dimid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
      if (nc_inq_dimname(ncid, dimid, name)) ERR;
      if (strcmp(name, DIM_NAME2)) ERR;
      if (nc_inq_varname(ncid, varid, name)) ERR;
      if (strcmp(name, VAR_NAME2)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing file with just one unlimited dimension...");
   {
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      int nunlimdims_in;

      /* Create a file with one unlimied dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, NC_UNLIMITED, &dimid)) ERR;

      /* Check it out before the enddef. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      
      /* Automatically enddef and close. */
      if (nc_close(ncid)) ERR;

      /* Reopen and check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
#define ROMULUS "Romulus"
#define REMUS "Remus"
#define DIMS2 2   
   printf("*** Testing file with two unlimited dimensions...");
   {
      int ncid, dimid[DIMS2];
      int ndims_in, dimids_in[DIMS2];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in[DIMS2];
      int nunlimdims_in;

      /* Create a file with two unlimited dims and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, REMUS, NC_UNLIMITED, &dimid[0])) ERR;
      if (nc_def_dim(ncid, ROMULUS, NC_UNLIMITED, &dimid[1])) ERR;

      /* Check it out before the enddef. */
      if (nc_inq_dim(ncid, dimid[0], name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, REMUS)) ERR;
      if (nc_inq_dim(ncid, dimid[1], name_in, &len_in)) ERR;
      if (len_in != NC_UNLIMITED || strcmp(name_in, ROMULUS)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 2 || dimids_in[0] != 0 || dimids_in[1] != 1) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in[0])) ERR;
      if (unlimdimid_in[0] != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, unlimdimid_in)) ERR;
      if (nunlimdims_in != 2 || unlimdimid_in[0] != 0 || unlimdimid_in[1] != 1) ERR;
      
      /* Automatically enddef and close. */
      if (nc_close(ncid)) ERR;

      /* Reopen and check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing ordering of dimensions...");
   {
#define A_NAME "a"
#define B_NAME "b"
#define A_LEN 50
#define B_LEN 92
#define A_DIMID 1
#define B_DIMID 0

      int ncid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int dimid_a, dimid_b;

      /* Create a file with two dims and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, B_NAME, B_LEN, &dimid_b)) ERR;
      if (nc_def_dim(ncid, A_NAME, A_LEN, &dimid_a)) ERR;
      if (dimid_b != B_DIMID || dimid_a != A_DIMID) ERR;

      /* Check out what we've got. */
      if (nc_inq_dim(ncid, dimid_a, name_in, &len_in)) ERR;
      if (len_in != A_LEN || strcmp(name_in, A_NAME)) ERR;
      if (nc_inq_dim(ncid, dimid_b, name_in, &len_in)) ERR;
      if (len_in != B_LEN || strcmp(name_in, B_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 2 || dimids_in[0] != 0 || dimids_in[1] != 1) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      if (nc_inq_dim(ncid, B_DIMID, name_in, &len_in)) ERR;
      if (len_in != B_LEN || strcmp(name_in, B_NAME)) ERR;
      if (nc_inq_dim(ncid, A_DIMID, name_in, &len_in)) ERR;
      if (len_in != A_LEN || strcmp(name_in, A_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 2 || dimids_in[0] != 0 ||
	  dimids_in[1] != 1) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing file with just one unlimited dimension and one var...");
   {
      int ncid, dimid, dimids[MAX_DIMS];
      int level_varid;
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      size_t start[MAX_DIMS], count[MAX_DIMS];
      int varid_in, nvars_in, nunlimdims_in;
      unsigned long long uint64_data[1] = {42};

      /* Create a file with one unlimied dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (dimid != 0) ERR;
      dimids[0] = dimid;
      if (nc_def_var(ncid, LEVEL_NAME, NC_UINT64, 1, dimids, &level_varid)) ERR;
      if (level_varid != 0) ERR;

      /* Check it out before enddef. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != 0 || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 || unlimdimid_in != 0) ERR;
      if (nc_inq_varid(ncid, LEVEL_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME) || xtype_in != NC_UINT64 || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME)) ERR;

      /* Now write one record of data to the var. */
      start[0] = 0;
      count[0] = 1;
      if (nc_put_vara_ulonglong(ncid, 0, start, count, uint64_data)) ERR;

      /* Check dimension informaiton again. Now the length of this
       * dimension should be one. */
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
      if (len_in != 1) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 || unlimdimid_in != 0) ERR;
      if (nc_inq_varid(ncid, LEVEL_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME) || xtype_in != NC_UINT64 || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME)) ERR;

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

      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_unlimdim(ncid, &unlimdimid_in)) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &nunlimdims_in, &unlimdimid_in)) ERR;
      if (nunlimdims_in != 1 || unlimdimid_in != 0) ERR;
      if (unlimdimid_in != 0) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 || unlimdimid_in != 0) ERR;
      if (nc_inq_varid(ncid, LEVEL_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME) || xtype_in != NC_UINT64 || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing adding a coordinate var to file with dimension...");
   {
      int ncid, dimid, dimids[MAX_DIMS];
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      int nvars_in, dim5_varid;

      /* Create a file with one dim and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM5_NAME, DIM5_LEN, &dimid)) ERR;

      /* Check out what we've got. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 0 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 0 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;

      /* Add a coordinate var for this dimension. */
      dimids[0] = 0;
      if (nc_def_var(ncid, DIM5_NAME, NC_FLOAT, 1, dimids, &dim5_varid)) ERR;

      /* Check it out. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != -1) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != DIM5_LEN || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing adding a coordinate var to file with unlimited dimension...");
   {
      int ncid, dimid, dimids[MAX_DIMS];
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int unlimdimid_in;
      size_t start[MAX_DIMS], count[MAX_DIMS], index[MAX_DIMS];
      unsigned short data[2] = {42, 24}, data_in[2];
      int nvars_in, hp_varid, dim5_varid;

      /* Create a file with one dim and one var. This time make
       * it an unlimited dim. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM5_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (dimid != 0) ERR;
      dimids[0] = dimid;
      if (nc_def_var(ncid, HP_NAME, NC_USHORT, 1, dimids, &hp_varid)) ERR;
      if (hp_varid != 0) ERR;

      /* Check out what we've got. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 0 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, HP_NAME) || xtype_in != NC_USHORT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      /* Add a record to the HP variable. */
      start[0] = 0;
      count[0] = 1;
      if (nc_put_vara(ncid, hp_varid, start, count, data)) ERR;

      /* Check to ensure dimension grew. */
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;

      /* Reread the value just written. */
      index[0] = 0;
      if (nc_get_var1_ushort(ncid, hp_varid, index, data_in)) ERR;
      if (data_in[0] != data[0]) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 1 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;

      /* Add a coordinate var for this dimension. */
      dimids[0] = 0;
      if (nc_def_var(ncid, DIM5_NAME, NC_FLOAT, 1, dimids, &dim5_varid)) ERR;

      /* Check it out. */
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 2 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, dim5_varid, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
      if (ndims_in != 1 || nvars_in != 2 || natts_in != 0 ||
	 unlimdimid_in != 0) ERR;
      if (nc_inq_dim(ncid, 0, name_in, &len_in)) ERR;
      if (len_in != 1 || strcmp(name_in, DIM5_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1 || dimids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, dim5_varid, name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, DIM5_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Creating file with 1 data var, 2 dims, and 2 coord. vars...");

   {
      int ncid, dimids[MAX_DIMS];
      int lat_dimid, lon_dimid, lat_varid, lon_varid;
      int pres_varid;
      char name_in[NC_MAX_NAME + 1];
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      float lat[LAT_LEN], lon[LON_LEN];
      float lat_in[LAT_LEN], lon_in[LON_LEN];
      double pres[LAT_LEN][LON_LEN], pres_in[LAT_LEN][LON_LEN];
      int i, j;

      /* Lats and lons suitable for some South American data. */
      for (lat[0] = 40.0, i = 1; i < LAT_LEN; i++)
	 lat[i] = lat[i - 1] + .5;
      for (lon[0] = 20.0, i = 1; i < LON_LEN; i++)
	 lon[i] = lon[i - 1] + 1.5;

      /* Some phoney 2D pressure data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    pres[i][j] = 1013.1 + j;
   
      /* Create a file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* Define lat and lon dimensions, with associated variables. */
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &lat_dimid)) ERR;
      dimids[0] = lat_dimid;
      if (nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, dimids, &lat_varid)) ERR;
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)) ERR;
      dimids[0] = lon_dimid;
      if (nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, dimids, &lon_varid)) ERR;

      /* Define a 2D variable called pressure, with NC_DOUBLE on a lat
       * lon grid. */
      dimids[0] = lat_dimid;
      dimids[1] = lon_dimid;
      if (nc_def_var(ncid, PRES_NAME, NC_DOUBLE, 2, dimids, &pres_varid)) ERR;

      /* Check our dimensions. */
      if (nc_inq_dim(ncid, lat_dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dim(ncid, lon_dimid, name_in, &len_in)) ERR;
      if (len_in != LON_LEN || strcmp(name_in, LON_NAME)) ERR;
      if (nc_inq_var(ncid, lat_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LAT_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lat_dimid || natts_in != 0) ERR;
      if (nc_inq_var(ncid, lon_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lon_dimid || natts_in != 0) ERR;

      /* Check our data variable. */
      if (nc_inq_var(ncid, pres_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, PRES_NAME) || xtype_in != NC_DOUBLE || ndims_in != 2 ||
	  dimids_in[0] != lat_dimid || dimids_in[1] != lon_dimid || natts_in != 0) ERR;
      
      /* Write our latitude and longitude values. This writes all
       * metadata to disk too. */
      if (nc_put_var_float(ncid, lat_varid, lat)) ERR;
      if (nc_put_var_float(ncid, lon_varid, lon)) ERR;

      /* Write our 2D pressure values. */
      if (nc_put_var_double(ncid, pres_varid, (double *)pres)) ERR;

      /* Check our latitude and longitude values. */
      if (nc_get_var(ncid, lat_varid, lat_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 if (lat[i] != lat_in[i]) ERR;
      if (nc_get_var_float(ncid, lon_varid, lon_in)) ERR;
      for (i = 0; i < LON_LEN; i++)
	 if (lon[i] != lon_in[i]) ERR;

      /* Check our pressure values. */
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (pres[i][j] != pres_in[i][j]) ERR;

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

      /* Reopen the file and check it out again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      /* Check our dimensions. */
      if (nc_inq_dim(ncid, lat_dimid, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dim(ncid, lon_dimid, name_in, &len_in)) ERR;
      if (len_in != LON_LEN || strcmp(name_in, LON_NAME)) ERR;
      if (nc_inq_var(ncid, lat_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LAT_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lat_dimid || natts_in != 0) ERR;
      if (nc_inq_var(ncid, lon_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != lon_dimid || natts_in != 0) ERR;

      /* Check our data variable. */
      if (nc_inq_var(ncid, pres_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, PRES_NAME) || xtype_in != NC_DOUBLE || ndims_in != 2 ||
	  dimids_in[0] != lat_dimid || dimids_in[1] != lon_dimid || natts_in != 0) ERR;
      
      /* Check our latitude and longitude values. */
      if (nc_get_var(ncid, lat_varid, lat_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 if (lat[i] != lat_in[i]) ERR;
      if (nc_get_var_float(ncid, lon_varid, lon_in)) ERR;
      for (i = 0; i < LON_LEN; i++)
	 if (lon[i] != lon_in[i]) ERR;

      /* Check our pressure values. */
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (pres[i][j] != pres_in[i][j]) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Creating file with 3 data vars, 4 dims, and 2 coord. vars...");

   {
      int ncid, lat_dimid, dimids[MAX_DIMS];
      int level_dimid, time_dimid, elev_varid;
      int lat_varid, lon_dimid, lon_varid, pres_varid, hp_varid;
      double pres[LAT_LEN][LON_LEN][LEVEL_LEN][TIME_LEN];
      double pres_in[LAT_LEN][LON_LEN][LEVEL_LEN][TIME_LEN];
      unsigned short hp[LAT_LEN][LON_LEN][TIME_LEN];
      unsigned short hp_in[LAT_LEN][LON_LEN][TIME_LEN];
      unsigned long long elev[LAT_LEN][LON_LEN], elev_in[LAT_LEN][LON_LEN];
      size_t start[4], count[4];
      int nvars, ndims, natts, unlimdimid;
      int natts_in, ndims_in, dimids_in[MAX_DIMS];
      nc_type xtype_in;
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      float lat[LAT_LEN], lon[LON_LEN];
      float lat_in[LAT_LEN], lon_in[LON_LEN];
      int i, j, k, l;

      /* Some phony 4D pressure data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (k = 0; k < LEVEL_LEN; k++)
	       for (l = 0; l <TIME_LEN; l++)
		  pres[i][j][k][l] = 1013.1 + j;
   
      /* Some phony 3D hp data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (l = 0; l <TIME_LEN; l++)
	       hp[i][j][l] = 100 + l;
   
      /* Some phony 2D elevaton data. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    elev[i][j] = 1010101022223333ULL  + i + j;

      /* Some phony 1D lats and lons. */
      for (i = 0; i < LAT_LEN; i++)
	 lat[i] = i * 5.;
      for (i = 0; i < LON_LEN; i++)
	 lon[i] = i * 5.;

      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* Define lat, lon, level, and timestep dimensions, with
       * associated coordinate variables for lat and lon only. Time is
       * an unlimited dimension. */
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &lat_dimid)) ERR;
      if (lat_dimid != LAT_DIMID) ERR;
      dimids[0] = lat_dimid;
      if (nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, dimids, &lat_varid)) ERR;
      if (lat_varid != LAT_VARID) ERR;
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &lon_dimid)) ERR;
      if (lon_dimid != LON_DIMID) ERR;
      dimids[0] = lon_dimid;
      if (nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, dimids, &lon_varid)) ERR;
      if (lon_varid != LON_VARID) ERR;
      if (nc_def_dim(ncid, LEVEL_NAME, LEVEL_LEN, &level_dimid)) ERR;
      if (level_dimid != LEVEL_DIMID) ERR;
      if (nc_def_dim(ncid, TIME_NAME, NC_UNLIMITED, &time_dimid)) ERR;
      if (time_dimid != TIME_DIMID) ERR;

      /* Define a 4D NC_DOUBLE variable called pressure. */
      dimids[0] = lat_dimid;
      dimids[1] = lon_dimid;
      dimids[2] = level_dimid;
      dimids[3] = time_dimid;
      if (nc_def_var(ncid, PRES_NAME, NC_DOUBLE, 4, dimids, &pres_varid)) ERR;
      if (pres_varid != PRES_VARID) ERR;

      /* Define a 2D variable for surface elevation. Use NC_INT64
       * because our units for this is Angstroms from Earth's
       * Center. */
      if (nc_def_var(ncid, ELEV_NAME, NC_INT64, 2, dimids, &elev_varid)) ERR;
      if (elev_varid != ELEV_VARID) ERR;
      
      /* Define a 3D NC_USHORT variable to store the number of Harry
       * Potter books in this grid square at this time (ignore HP
       * books in airplanes, dirigibles, hot air balloons, space
       * capsules, hang-gliders, parachutes, and flying on brooms). */
      dimids[2] = time_dimid;
      if (nc_def_var(ncid, HP_NAME, NC_USHORT, 3, dimids, &hp_varid)) ERR;
      if (hp_varid != HP_VARID) ERR;

      /* Did all our stuff make it into the internal metadata model
       * intact? */
      /* Check our dimensions. */
      if (nc_inq_dim(ncid, LAT_DIMID, name_in, &len_in)) ERR;
      if (len_in != LAT_LEN || strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dim(ncid, LON_DIMID, name_in, &len_in)) ERR;
      if (len_in != LON_LEN || strcmp(name_in, LON_NAME)) ERR;
      if (nc_inq_dim(ncid, LEVEL_DIMID, name_in, &len_in)) ERR;
      if (len_in != LEVEL_LEN || strcmp(name_in, LEVEL_NAME)) ERR;
      if (nc_inq_dim(ncid, TIME_DIMID, name_in, &len_in)) ERR;
      if (len_in != 0 || strcmp(name_in, TIME_NAME)) ERR;

      /* Check our coordinate variables. */
      if (nc_inq_var(ncid, LAT_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LAT_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != LAT_DIMID || natts_in != 0) ERR;
      if (nc_inq_var(ncid, LON_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	  dimids_in[0] != LON_DIMID || natts_in != 0) ERR;

      /* Check our data variables. */
      if (nc_inq_var(ncid, PRES_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, PRES_NAME) || xtype_in != NC_DOUBLE || ndims_in != 4 ||
	  dimids_in[0] != LAT_DIMID || dimids_in[1] != LON_DIMID ||
	  dimids_in[2] != LEVEL_DIMID || dimids_in[3] != TIME_DIMID ||
	  natts_in != 0) ERR;
      if (nc_inq_var(ncid, ELEV_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, ELEV_NAME) || xtype_in != NC_INT64 || ndims_in != 2 ||
	  dimids_in[0] != LAT_DIMID || dimids_in[1] != LON_DIMID ||
	  natts_in != 0) ERR;
      if (nc_inq_var(ncid, HP_VARID, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (strcmp(name_in, HP_NAME) || xtype_in != NC_USHORT || ndims_in != 3 ||
	  dimids_in[0] != LAT_DIMID || dimids_in[1] != LON_DIMID ||
	  dimids_in[2] != TIME_DIMID || natts_in != 0) ERR;
      
      /* Write our latitude and longitude values. This writes all
       * metadata to disk too. */
      if (nc_put_var_float(ncid, lat_varid, lat)) ERR;
      if (nc_put_var_float(ncid, lon_varid, lon)) ERR;

      /* Write our 4D pressure, elevation, and hp data. But this
       * should do nothing for pressure and hp, because these are
       * record vars, and nc_put_var_* doesn't do anything to record
       * vars, because it doesn't know how big the var is supposed to
       * be. */
      if (nc_put_var_double(ncid, pres_varid, (double *)pres)) ERR;
      if (nc_put_var_ulonglong(ncid, elev_varid, (unsigned long long *)elev)) ERR;
      if (nc_put_var_ushort(ncid, hp_varid, (unsigned short *)hp)) ERR;

      /* Check our latitude and longitude values. */
      if (nc_get_var(ncid, lat_varid, lat_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 if (lat[i] != lat_in[i]) ERR;
      if (nc_get_var_float(ncid, lon_varid, lon_in)) ERR;
      for (i = 0; i < LON_LEN; i++)
	 if (lon[i] != lon_in[i]) ERR;

      /* Make sure our pressure and hp variables are still
       * empty. get_var calls will return no error, but fetch no
       * data. */
      if (nc_inq_var(ncid, pres_varid, name_in, &xtype_in, &ndims_in,
		     dimids_in, &natts_in)) ERR;
      if (nc_inq_dim(ncid, dimids_in[3], NULL, &len_in)) ERR;
      if (len_in != 0) ERR;
      memset(pres_in, 0, sizeof(pres_in));
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;

      /* Check our pressure values. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (k = 0; k < LEVEL_LEN; k++)
	       for (l = 0; l <TIME_LEN; l++)
		  if (0 != pres_in[i][j][k][l]) ERR;

      if (nc_inq_var(ncid, hp_varid, NULL, NULL, &ndims_in,
		     dimids_in, NULL)) ERR;
      if (nc_inq_dim(ncid, dimids_in[2], NULL, &len_in)) ERR;
      if (len_in != 0) ERR;
      memset(hp_in, 0, sizeof(hp_in));
      if (nc_get_var_ushort(ncid, hp_varid, (unsigned short *)hp_in)) ERR;

      /* Check our hp values. */
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (l = 0; l <TIME_LEN; l++)
	       if (0 != hp_in[i][j][l]) ERR;

      /* Now use nc_put_vara to really write pressure and hp
       * data. Write TIME_LEN (4) records of each. */
      start[0] = start[1] = start[2] = start[3] = 0;
      count[0] = LAT_LEN;
      count[1] = LON_LEN;
      count[2] = LEVEL_LEN;
      count[3] = TIME_LEN;
      if (nc_put_vara(ncid, pres_varid, start, count, 
		      (double *)pres)) ERR;
      count[2] = TIME_LEN;
      if (nc_put_vara(ncid, hp_varid, start, count,
		      (double *)hp)) ERR;

      /* Check our pressure values. */
      if (nc_get_var_double(ncid, pres_varid, (double *)pres_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (k = 0; k < LEVEL_LEN; k++)
	       for (l = 0; l <TIME_LEN; l++)
		  if (pres[i][j][k][l] != pres_in[i][j][k][l]) ERR;

      /* Check our elevation values. */
      if (nc_get_var_ulonglong(ncid, elev_varid, (unsigned long long *)elev_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    if (elev[i][j] != elev_in[i][j]) ERR;

      /* Check our hp values. */
      if (nc_get_var_ushort(ncid, hp_varid, (unsigned short *)hp_in)) ERR;
      for (i = 0; i < LAT_LEN; i++)
	 for (j = 0; j < LON_LEN; j++)
	    for (l = 0; l <TIME_LEN; l++)
	       if (hp[i][j][l] != hp_in[i][j][l]) ERR;

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

      /* Reopen the file and check it out again. At the moment, we
       * can't count on the varids and dimids being the same. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 4 || nvars != 5 || natts != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** Testing file with dims and only some coordinate vars...");
#define NDIMS_EX 4
#define NLAT 6
#define NLON 12
#define LAT_NAME_EX "latitude"
#define LON_NAME_EX "longitude"
#define NREC 2
#define REC_NAME "time"
#define LVL_NAME "level"
#define NLVL 2

/* Names of things. */
#define PRES_NAME "pressure"
#define TEMP_NAME "temperature"
#define UNITS "units"
#define DEGREES_EAST "degrees_east"
#define DEGREES_NORTH "degrees_north"

/* There are 4 vars, two for data, two for coordinate data. */
#define NVARS_EX 4

/* These are used to construct some example data. */
#define SAMPLE_PRESSURE 900
#define SAMPLE_TEMP 9.0
#define START_LAT 25.0
#define START_LON -125.0

/* For the units attributes. */
#define UNITS "units"
#define PRES_UNITS "hPa"
#define TEMP_UNITS "celsius"
#define LAT_UNITS "degrees_north"
#define LON_UNITS "degrees_east"
#define MAX_ATT_LEN 80
   {
      /* IDs for the netCDF file, dimensions, and variables. */
      int ncid, lon_dimid, lat_dimid;
      int lon_varid;
      int ndims_in;
      int dimid[NDIMS_EX];
      char dim_name_in[NDIMS_EX][NC_MAX_NAME];
      int i;

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

      /* Define the dimensions. */
      if (nc_def_dim(ncid, LAT_NAME_EX, NLAT, &lat_dimid)) ERR;
      if (nc_def_dim(ncid, LON_NAME_EX, NLON, &lon_dimid)) ERR;

      /* Define a coordinate var. */
      if (nc_def_var(ncid, LON_NAME_EX, NC_FLOAT, 1, &lon_dimid,
			       &lon_varid)) ERR;

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

      if (nc_open(FILE_NAME, 0, &ncid)) ERR;

      /* Check dimensions. */
      ndims_in = 0;
      if (nc_inq_dimids(ncid, &ndims_in, dimid, 0)) ERR;
      if (ndims_in != 2) ERR;
      for (i = 0; i < 2; i++)
      {
	 if (dimid[i] != i) ERR;
	 if (nc_inq_dimname(ncid, i, dim_name_in[i])) ERR;
      }
      if (strcmp(dim_name_in[0], LAT_NAME_EX) ||
	  strcmp(dim_name_in[1], LON_NAME_EX)) ERR;

      /* Close the file. */
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** Testing file with just one very long dimension...");
   {
#define VERY_LONG_LEN (size_t)4500000000LL
      int ncid, dimid;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int varid_in;

      if (SIZEOF_SIZE_T == 8)
      {
	 /* Create a file with one dim and nothing else. */
	 if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
	 if (nc_def_dim(ncid, LAT_NAME, VERY_LONG_LEN, &dimid)) ERR;

	 /* Check it out. */
	 if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT) || 
	     strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
	 if (ndims_in != 1) ERR;
	 if (nc_inq_dimid(ncid, LAT_NAME, &varid_in)) ERR;
	 if (varid_in != 0) ERR;
	 if (nc_inq_dimname(ncid, 0, name_in)) ERR;
	 if (strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT)) ERR;
	 if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
	 if (ndims_in != 0) ERR;
	 if (nc_close(ncid)) ERR;

	 /* Reopen and check it out again. */
	 if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
	 /* Check it out. */
	 if (nc_inq_dim(ncid, dimid, name_in, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT) || 
	     strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
	 if (ndims_in != 1) ERR;
	 if (nc_inq_dimid(ncid, LAT_NAME, &varid_in)) ERR;
	 if (varid_in != 0) ERR;
	 if (nc_inq_dimname(ncid, 0, name_in)) ERR;
	 if (strcmp(name_in, LAT_NAME)) ERR;
	 if (nc_inq_dimlen(ncid, 0, &len_in)) ERR;
	 if (len_in != ((SIZEOF_SIZE_T == 8) ? VERY_LONG_LEN : NC_MAX_UINT)) ERR;
	 if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
	 if (ndims_in != 0) ERR;
	 if (nc_close(ncid)) ERR;
      }
   }
   SUMMARIZE_ERR;
   printf("*** Testing reference file with just one very long dimension...");
   {
#define REF_FILE_NAME "ref_tst_dims.nc"
      int ncid, dimid = 0;
      int ndims_in, dimids_in[MAX_DIMS];
      size_t len_in;
      char name_in[NC_MAX_NAME + 1];
      int varid_in;
      char file_in[NC_MAX_NAME + 1];
      int ret;

      strcpy(file_in, "");
      if (getenv("srcdir"))
      {
	 strcat(file_in, getenv("srcdir"));
	 strcat(file_in, "/");
      } 
      strcat(file_in, REF_FILE_NAME);

      /* Reopen and check it out again. */
      if (nc_open(file_in, NC_NOWRITE, &ncid)) ERR;

      /* Check it out. */
      ret = nc_inq_dim(ncid, dimid, name_in, &len_in);
      if ((SIZEOF_SIZE_T >= 8 && ret) ||
	  (SIZEOF_SIZE_T < 8 && ret != NC_EDIMSIZE)) ERR;
      if (SIZEOF_SIZE_T < 8)
      {
	 if (len_in != NC_MAX_UINT) ERR;
      }
      else
      {
	 if (len_in != VERY_LONG_LEN) ERR;
      }
      if (strcmp(name_in, LAT_NAME)) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != 1) ERR;
      if (nc_inq_dimid(ncid, LAT_NAME, &varid_in)) ERR;
      if (varid_in != 0) ERR;
      if (nc_inq_unlimdims(ncid, &ndims_in, dimids_in)) ERR;
      if (ndims_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
Example #23
0
int ex_put_name (int   exoid,
		 ex_entity_type obj_type,
		 ex_entity_id   entity_id,
		 const char *name)
{
  int status;
  int varid, ent_ndx; 
  char errmsg[MAX_ERR_LENGTH];
  const char *routine = "ex_put_name";
  const char *vobj;
   
  exerrval = 0; /* clear error code */

  switch(obj_type) {
  case EX_EDGE_BLOCK:
    vobj = VAR_NAME_ED_BLK;
    break;
  case EX_FACE_BLOCK:
    vobj = VAR_NAME_FA_BLK;
    break;
  case EX_ELEM_BLOCK:
    vobj = VAR_NAME_EL_BLK;
    break;
  case EX_NODE_SET:
    vobj = VAR_NAME_NS;
    break;
  case EX_SIDE_SET:
    vobj = VAR_NAME_SS;
    break;
  case EX_EDGE_SET:
    vobj = VAR_NAME_ES;
    break;
  case EX_FACE_SET:
    vobj = VAR_NAME_FS;
    break;
  case EX_ELEM_SET:
    vobj = VAR_NAME_ELS;
    break;
  case EX_NODE_MAP:
    vobj = VAR_NAME_NM;
    break;
  case EX_EDGE_MAP:
    vobj = VAR_NAME_EDM;
    break;
  case EX_FACE_MAP:
    vobj = VAR_NAME_FAM;
    break;
  case EX_ELEM_MAP:
    vobj = VAR_NAME_EM;
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf(errmsg,
	    "Error: Invalid type specified in file id %d", exoid);
    ex_err(routine,errmsg,exerrval);
    return(EX_FATAL);
  }
   
  if ((status = nc_inq_varid(exoid, vobj, &varid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to locate %s names in file id %d",
	    ex_name_of_object(obj_type), exoid);
    ex_err(routine,errmsg,exerrval);
    return (EX_FATAL);
  }

  ent_ndx = ex_id_lkup(exoid, obj_type, entity_id);

  if (exerrval == EX_LOOKUPFAIL) {   /* could not find the element block id */
    exerrval = EX_FATAL;
    sprintf(errmsg,
            "Error: %s id %"PRId64" not found in file id %d",
	    ex_name_of_object(obj_type), entity_id, exoid);
    ex_err("ex_put_name",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* If this is a null entity, then 'ent_ndx' will be negative.
   * We don't care in this routine, so make it positive and continue...
   */
  if (ent_ndx < 0) ent_ndx = -ent_ndx;
   
  /* write EXODUS entityname */
  status = ex_put_name_internal(exoid, varid, ent_ndx-1, name, obj_type, "", routine);

  return(status);
}
Example #24
0
int ex_get_truth_table (int  exoid,
      ex_entity_type obj_type,
      int  num_blk,
      int  num_var,
      int *var_tab)
{
  int dimid, varid, tabid, i, j, status, status1;
  size_t num_entity = 0;
  size_t num_var_db = 0;
  char errmsg[MAX_ERR_LENGTH];
  const char* routine = "ex_get_truth_table";

  /*
   * The ent_type and the var_name are used to build the netcdf
   * variables name.  Normally this is done via a macro defined in
   * exodusII_int.h
   */
  const char* ent_type = NULL;
  const char* var_name = NULL;

  exerrval = 0; /* clear error code */

  switch (obj_type) {
  case EX_EDGE_BLOCK:
    status = ex_get_dimension(exoid, DIM_NUM_EDG_VAR,  "edge variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_EBLK_TAB, &tabid);
    var_name = "vals_edge_var";
    ent_type = "eb";
    break;
  case EX_FACE_BLOCK:
    status = ex_get_dimension(exoid, DIM_NUM_FAC_VAR,  "face variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_FBLK_TAB, &tabid);
    var_name = "vals_face_var";
    ent_type = "fb";
    break;
  case EX_ELEM_BLOCK:
    status = ex_get_dimension(exoid, DIM_NUM_ELE_VAR,  "element variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_ELEM_TAB, &tabid);
    var_name = "vals_elem_var";
    ent_type = "eb";
    break;
  case EX_NODE_SET:
    status = ex_get_dimension(exoid, DIM_NUM_NSET_VAR, "nodeset variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_NSET_TAB, &tabid);
    var_name = "vals_nset_var";
    ent_type = "ns";
    break;
  case EX_EDGE_SET:
    status = ex_get_dimension(exoid, DIM_NUM_ESET_VAR, "edgeset variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_ESET_TAB, &tabid);
    var_name = "vals_eset_var";
    ent_type = "es";
    break;
  case EX_FACE_SET:
    status = ex_get_dimension(exoid, DIM_NUM_FSET_VAR, "faceset variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_FSET_TAB, &tabid);
    var_name = "vals_fset_var";
    ent_type = "fs";
    break;
  case EX_SIDE_SET:
    status = ex_get_dimension(exoid, DIM_NUM_SSET_VAR, "sideset variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_SSET_TAB, &tabid);
    var_name = "vals_sset_var";
    ent_type = "ss";
    break;
  case EX_ELEM_SET:
    status = ex_get_dimension(exoid, DIM_NUM_ELSET_VAR, "elemset variables", &num_var_db, &varid, routine);
    status1 = nc_inq_varid (exoid, VAR_ELSET_TAB, &tabid);
    var_name = "vals_elset_var";
    ent_type = "es";
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf(errmsg,
      "Error: Invalid variable type %d specified in file id %d",
      obj_type, exoid);
    ex_err(routine,errmsg,exerrval);
    return (EX_WARN);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    return (EX_WARN);
  }

  status  = ex_get_dimension(exoid, ex_dim_num_objects(obj_type),
           ex_name_of_object(obj_type), &num_entity, &dimid, routine);
  if (status != NC_NOERR) {
    exerrval = status;
    return (EX_FATAL);
  }

  if (num_entity != (size_t)num_blk) {
    exerrval = EX_FATAL;
    sprintf(errmsg,
      "Error: # of %s doesn't match those defined in file id %d",
      ex_name_of_object(obj_type), exoid);
    ex_err(routine,errmsg,exerrval);
    return (EX_FATAL);
  }

  if (num_var_db != (size_t)num_var) {
    exerrval = EX_FATAL;
    sprintf(errmsg,
      "Error: # of %s variables doesn't match those defined in file id %d",
      ex_name_of_object(obj_type), exoid);
    ex_err(routine,errmsg,exerrval);
    return (EX_FATAL);
  }

  if (status1 != NC_NOERR) {
    /* since truth table isn't stored in the data file, derive it dynamically */
    for (j=0; j<num_blk; j++) {

      for (i=0; i<num_var; i++) {
        /* NOTE: names are 1-based */
        if (nc_inq_varid (exoid, ex_catstr2(var_name, i+1, ent_type, j+1), &tabid) == NC_NOERR) {
          /* variable exists; put a 1 in the truth table */
          var_tab[j*num_var+i] = 1;
        } else {
          /* variable doesn't exist; put a 0 in the truth table */
          var_tab[j*num_var+i] = 0;
        }
      }
    }
  } else {
    /* read in the truth table */
    status = nc_get_var_int(exoid, tabid, var_tab);

    if (status != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to get %s truth table from file id %d",
        ex_name_of_object(obj_type), exoid);
      ex_err(routine,errmsg,exerrval);
      return (EX_FATAL);
    }
  } 
  return (EX_NOERR);
}
Example #25
0
int ex_put_conn (int   exoid,
                 ex_entity_type blk_type,
                 ex_entity_id   blk_id,
                 const void_int  *node_conn,
                 const void_int  *elem_edge_conn,
                 const void_int  *elem_face_conn)
{
   int connid=-1, blk_id_ndx, status;
   char errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

   blk_id_ndx = ex_id_lkup(exoid,blk_type,blk_id);
   if (exerrval != 0) {
     if (exerrval == EX_NULLENTITY) {
       sprintf(errmsg,
         "Warning: connectivity array not allowed for NULL %s %"PRId64" in file id %d",
	       ex_name_of_object(blk_type),blk_id,exoid);
       ex_err("ex_put_conn",errmsg,EX_NULLENTITY);
       return (EX_WARN);
       }
     else {
       sprintf(errmsg,
         "Error: failed to locate %s id %"PRId64" in id array in file id %d",
         ex_name_of_object(blk_type),blk_id, exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return (EX_FATAL);
       }
     }

/* inquire id's of previously defined dimensions  */
   if (node_conn) {
     switch (blk_type) {
     case EX_ELEM_BLOCK:
       status = nc_inq_varid (exoid, VAR_CONN(blk_id_ndx), &connid);
       break;
     case EX_FACE_BLOCK:
       status = nc_inq_varid (exoid, VAR_FBCONN(blk_id_ndx), &connid);
       break;
     case EX_EDGE_BLOCK:
       status = nc_inq_varid (exoid, VAR_EBCONN(blk_id_ndx), &connid);
       break;
     default:
       exerrval = 1005;
       sprintf(errmsg,
	       "Internal Error: unrecognized block type in switch: %d in file id %d",
	       blk_type,exoid);
       ex_err("ex_putt_conn",errmsg,EX_MSG);
       return (EX_FATAL);
     }
     if (status != NC_NOERR) {
       exerrval = status;
       sprintf(errmsg,
	       "Error: failed to locate connectivity array for %s %"PRId64" in file id %d",
	       ex_name_of_object(blk_type),blk_id,exoid);
       ex_err("ex_put_conn",errmsg, exerrval);
       return(EX_FATAL);
     }
     
     EX_WRITE_CONN(ex_name_of_object(blk_type),connid,node_conn);
   }

   /* If there are edge and face connectivity arrays that belong with the element
    * block, write them now. Warn if they are required but not specified or
    * specified but not required.
    */
   if ( blk_type == EX_ELEM_BLOCK ) {
     int nedpereldim, nfapereldim;
     size_t num_ed_per_elem, num_fa_per_elem;

     status = nc_inq_dimid (exoid, DIM_NUM_EDG_PER_EL(blk_id_ndx), &nedpereldim);
     if (status != NC_NOERR && elem_edge_conn != 0)
       {
       exerrval = status;
       sprintf(errmsg,
         "Error: edge connectivity specified but failed to "
         "locate number of edges/element in block %"PRId64" in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     status = nc_inq_dimid (exoid, DIM_NUM_FAC_PER_EL(blk_id_ndx), &nfapereldim);
     if (status != NC_NOERR && elem_face_conn != 0)
       {
       exerrval = status;
       sprintf(errmsg,
         "Error: face connectivity specified but failed to "
         "locate number of faces/element in block %"PRId64" in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     num_ed_per_elem = 0;
     if ((elem_edge_conn != 0) &&
	 (status = nc_inq_dimlen(exoid, nedpereldim, &num_ed_per_elem) != NC_NOERR))
       {
       exerrval = status;
       sprintf(errmsg,
         "Error: failed to get number of edges/elem in block %"PRId64" in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     num_fa_per_elem = 0;
     if ((elem_face_conn != 0) &&
	 (status = nc_inq_dimlen(exoid, nfapereldim, &num_fa_per_elem) != NC_NOERR))
       {
       exerrval = status;
       sprintf(errmsg,
         "Error: failed to get number of faces/elem in block %"PRId64" in file id %d",
         blk_id,exoid);
       ex_err("ex_put_conn",errmsg,exerrval);
       return(EX_FATAL);
       }

     if ( (num_ed_per_elem == 0 && elem_edge_conn != 0) ||
          (num_ed_per_elem != 0 && elem_edge_conn == 0) )
       {
       exerrval = (EX_FATAL);
       sprintf(errmsg,
         "Error: number of edges per element (%ld) doesn't "
         "agree with elem_edge_conn (0x%p)",
	       (long)num_ed_per_elem, (void*)elem_edge_conn );
       ex_err("ex_put_conn",errmsg,exerrval);
       return (EX_FATAL);
       }

     if ( (num_fa_per_elem == 0 && elem_face_conn != 0) ||
          (num_fa_per_elem != 0 && elem_face_conn == 0) )
       {
       exerrval = (EX_FATAL);
       sprintf(errmsg,
         "Error: number of faces per element (%ld) doesn't "
         "agree with elem_face_conn (0x%p)",
	       (long)num_fa_per_elem, (void*)elem_face_conn );
       ex_err("ex_put_conn",errmsg,exerrval);
       return (EX_FATAL);
       }

     if ( num_ed_per_elem != 0 ) {
       status = nc_inq_varid(exoid, VAR_ECONN(blk_id_ndx), &connid);
       if (status != NC_NOERR)
         {
         exerrval = status;
         sprintf(errmsg,
           "Error: failed to locate connectivity array for "
           "element edge block %"PRId64" in file id %d",
           blk_id,exoid);
         ex_err("ex_put_conn",errmsg, exerrval);
         return(EX_FATAL);
         }
       EX_WRITE_CONN("element edge",connid,elem_edge_conn);
     }

     if ( num_fa_per_elem != 0 ) {
       status = nc_inq_varid (exoid, VAR_FCONN(blk_id_ndx), &connid);
       if (status != NC_NOERR)
         {
         exerrval = status;
         sprintf(errmsg,
           "Error: failed to locate connectivity array for "
           "element face block %"PRId64" in file id %d",
           blk_id,exoid);
         ex_err("ex_put_conn",errmsg, exerrval);
         return(EX_FATAL);
         }
       EX_WRITE_CONN("element face",connid,elem_face_conn);
     }
   }

   return (EX_NOERR);

}
Example #26
0
/*! \internal */
int cpy_coord_def(int in_id,int out_id,int rec_dim_id,char *var_nm,
		  int in_large, int out_large)
/*
   int in_id: input netCDF input-file ID
   int out_id: input netCDF output-file ID
   int rec_dim_id: input input-file record dimension ID
   char *var_nm: input variable name
   int in_large: large file setting for input file
   int out_large: large file setting for output file
   int cpy_var_def(): output output-file variable ID
 */
{
  const char *routine = NULL;
  int status;
  size_t spatial_dim;
  int nbr_dim;
  int temp;

  int dim_out_id[2];
  int var_out_id = -1;
  
  /* Handle easiest situation first: in_large matches out_large */
  if (in_large == out_large) {
    return cpy_var_def(in_id, out_id, rec_dim_id, var_nm);
  }

  /* At this point, know that in_large != out_large, so some change to
     the coord variable definition is needed. Also will need the
     spatial dimension, so get that now.*/
  ex_get_dimension(in_id, DIM_NUM_DIM, "dimension", &spatial_dim, &temp, routine);
  
  if (in_large == 0 && out_large == 1) {
    /* output file will have coordx, coordy, coordz (if 3d).  See if
       they are already defined in output file. Assume either all or
       none are defined. */

    {
      int var_out_idx, var_out_idy, var_out_idz;
      int status1 = nc_inq_varid(out_id, VAR_COORD_X, &var_out_idx);
      int status2 = nc_inq_varid(out_id, VAR_COORD_Y, &var_out_idy);
      int status3 = nc_inq_varid(out_id, VAR_COORD_Y, &var_out_idz);

      if (status1 == NC_NOERR && status2 == NC_NOERR &&
          (spatial_dim == 2 || status3 == NC_NOERR)) {
        return NC_NOERR; /* already defined in output file */
      }
    }

    /* Get dimid of the num_nodes dimension in output file... */
    (void)nc_inq_dimid(out_id, DIM_NUM_NODES, &dim_out_id[0]);

    /* Define the variables in the output file */
    
    /* Define according to the EXODUS file's IO_word_size */
    nbr_dim = 1;
    (void)nc_def_var(out_id, VAR_COORD_X, nc_flt_code(out_id), nbr_dim, dim_out_id, &var_out_id);
    ex_compress_variable(out_id, var_out_id, 2);
    if (spatial_dim > 1) {
      (void)nc_def_var(out_id, VAR_COORD_Y, nc_flt_code(out_id), nbr_dim, dim_out_id, &var_out_id);
      ex_compress_variable(out_id, var_out_id, 2);
    }
    if (spatial_dim > 2) {
      (void)nc_def_var(out_id, VAR_COORD_Z, nc_flt_code(out_id), nbr_dim, dim_out_id, &var_out_id);
      ex_compress_variable(out_id, var_out_id, 2);
    }
  }

  if (in_large == 1 && out_large == 0) {
    /* input file has coordx, coordy, coordz (if 3d); output will only
       have "coord".  See if is already defined in output file. */
    status = nc_inq_varid(out_id, VAR_COORD, &var_out_id);
    if (status == NC_NOERR)
      return NC_NOERR; /* already defined in output file */

    /* Get dimid of the spatial dimension and num_nodes dimensions in output file... */
    (void)nc_inq_dimid(out_id, DIM_NUM_DIM,   &dim_out_id[0]);
    (void)nc_inq_dimid(out_id, DIM_NUM_NODES, &dim_out_id[1]);

    /* Define the variable in the output file */
    
    /* Define according to the EXODUS file's IO_word_size */
    nbr_dim = 2;
    (void)nc_def_var(out_id, VAR_COORD, nc_flt_code(out_id), nbr_dim, dim_out_id, &var_out_id);
  }
  return var_out_id;
}
int ex_get_info (int    exoid,
                 char **info)
{
  int status;
  size_t i;
  int dimid, varid;
  size_t num_info, start[2], count[2];
  char  errmsg[MAX_ERR_LENGTH];

  int rootid = exoid & EX_FILE_ID_MASK;

  exerrval = 0; /* clear error code */

  /* inquire previously defined dimensions and variables  */
  if ((status = nc_inq_dimid (rootid, DIM_NUM_INFO, &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Warning: failed to locate number of info records in file id %d",
	    rootid);
    ex_err("ex_get_info",errmsg,exerrval);
    return (EX_WARN);
  }

  if ((status = nc_inq_dimlen(rootid, dimid, &num_info)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to get number of info records in file id %d",
	    rootid);
    ex_err("ex_get_info",errmsg,exerrval);
    return (EX_FATAL);
  }


  /* do this only if there are any information records */
  if (num_info > 0) {
    if ((status = nc_inq_varid(rootid, VAR_INFO, &varid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to locate info record data in file id %d", rootid);
      ex_err("ex_get_info",errmsg,exerrval);
      return (EX_FATAL);
    }

    /* read the information records */
    for (i=0; i<num_info; i++) {
      start[0] = i; count[0] = 1;
      start[1] = 0; count[1] = MAX_LINE_LENGTH+1;

      if ((status = nc_get_vara_text(rootid, varid, start, count, info[i])) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get info record data in file id %d", rootid);
	ex_err("ex_get_info",errmsg,exerrval);
	return (EX_FATAL);
      }
      info[i][MAX_LINE_LENGTH] = '\0';
      ex_trim_internal(info[i]);
    }
  }
  return (EX_NOERR);
}
Example #28
0
/*! \internal */
int cpy_var_def(int in_id,int out_id,int rec_dim_id,char *var_nm)
/*
   int in_id: input netCDF input-file ID
   int out_id: input netCDF output-file ID
   int rec_dim_id: input input-file record dimension ID
   char *var_nm: input variable name
   int cpy_var_def(): output output-file variable ID
 */
{
  /* Routine to copy the variable metadata from an input netCDF file
   * to an output netCDF file. 
   */

  int status;
  int *dim_in_id;
  int *dim_out_id;
  int idx;
  int nbr_dim;
  int var_in_id;
  int var_out_id;

  nc_type var_type;

  /* See if the requested variable is already in the output file. */
  status = nc_inq_varid(out_id, var_nm, &var_out_id);
  if(status == NC_NOERR)
    return var_out_id;

  /* See if the requested variable is in the input file. */
  (void)nc_inq_varid(in_id, var_nm, &var_in_id);

  /* Get the type of the variable and the number of dimensions. */
  (void)nc_inq_vartype (in_id, var_in_id, &var_type);
  (void)nc_inq_varndims(in_id, var_in_id, &nbr_dim);

  /* Recall:
     1. The dimensions must be defined before the variable.
     2. The variable must be defined before the attributes. */

  /* Allocate space to hold the dimension IDs */
  dim_in_id=malloc(nbr_dim*sizeof(int)); 
  dim_out_id=malloc(nbr_dim*sizeof(int));

  /* Get the dimension IDs */
  (void)nc_inq_vardimid(in_id, var_in_id, dim_in_id);

  /* Get the dimension sizes and names */
  for(idx=0;idx<nbr_dim;idx++){
    char dim_nm[NC_MAX_NAME];
    size_t dim_sz;

    (void)nc_inq_dim(in_id, dim_in_id[idx], dim_nm, &dim_sz);

    /* See if the dimension has already been defined */
    status = nc_inq_dimid(out_id, dim_nm, &dim_out_id[idx]);

    /* If the dimension hasn't been defined, copy it */
    if (status != NC_NOERR) {
      if (dim_in_id[idx] != rec_dim_id) {
        (void)nc_def_dim(out_id, dim_nm, dim_sz, &dim_out_id[idx]);
      } else {
        (void)nc_def_dim(out_id, dim_nm, NC_UNLIMITED, &dim_out_id[idx]);
      } 
    } 
  } 

  /* Define the variable in the output file */

  /* If variable is float or double, define it according to the EXODUS
     file's IO_word_size */

  if ((var_type == NC_FLOAT) || (var_type == NC_DOUBLE)) {
    (void)nc_def_var(out_id, var_nm, nc_flt_code(out_id), nbr_dim, dim_out_id, &var_out_id);
    ex_compress_variable(out_id, var_out_id, 2);
  } else {
    (void)nc_def_var(out_id, var_nm, var_type,            nbr_dim, dim_out_id, &var_out_id);
    ex_compress_variable(out_id, var_out_id, 1);
  }

  /* Free the space holding the dimension IDs */
  (void)free(dim_in_id);
  (void)free(dim_out_id);

  return var_out_id;
} /* end cpy_var_def() */
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;
}
int ex_put_prop_array (int   exoid,
                       ex_entity_type obj_type,
                       const char *prop_name,
                       const int  *values)
{
  int oldfill, temp;
  int num_props, i, propid, dimid, dims[1], status;
  int found = FALSE;
  size_t num_obj; 
  char name[MAX_VAR_NAME_LENGTH+1];
  char tmpstr[MAX_STR_LENGTH+1];

  char errmsg[MAX_ERR_LENGTH];

  exerrval  = 0; /* clear error code */

  /* check if property has already been created */

  num_props = ex_get_num_props(exoid, obj_type);

  /* inquire id of previously defined dimension (number of objects) */
  status = ex_get_dimension(exoid, ex_dim_num_objects(obj_type), ex_name_of_object(obj_type),
			    &num_obj, &dimid, "ex_put_prop_array");
  if (status != NC_NOERR) return status;

  for (i=1; i<=num_props; i++) {
    switch (obj_type){
    case EX_ELEM_BLOCK:
      strcpy (name, VAR_EB_PROP(i));
      break;
    case EX_FACE_BLOCK:
      strcpy (name, VAR_FA_PROP(i));
      break;
    case EX_EDGE_BLOCK:
      strcpy (name, VAR_ED_PROP(i));
      break;
    case EX_NODE_SET:
      strcpy (name, VAR_NS_PROP(i));
      break;
    case EX_EDGE_SET:
      strcpy (name, VAR_ES_PROP(i));
      break;
    case EX_FACE_SET:
      strcpy (name, VAR_FS_PROP(i));
      break;
    case EX_ELEM_SET:
      strcpy (name, VAR_ELS_PROP(i));
      break;
    case EX_SIDE_SET:
      strcpy (name, VAR_SS_PROP(i));
      break;
    case EX_ELEM_MAP:
      strcpy (name, VAR_EM_PROP(i));
      break;
    case EX_FACE_MAP:
      strcpy (name, VAR_FAM_PROP(i));
      break;
    case EX_EDGE_MAP:
      strcpy (name, VAR_EDM_PROP(i));
      break;
    case EX_NODE_MAP:
      strcpy (name, VAR_NM_PROP(i));
      break;
    default:
      exerrval = EX_BADPARAM;
      sprintf(errmsg, "Error: object type %d not supported; file id %d",
	      obj_type, exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      return(EX_FATAL);
    }

    if ((status = nc_inq_varid(exoid, name, &propid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to get property array id in file id %d",
	      exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      return (EX_FATAL);
    }

    /* compare stored attribute name with passed property name   */
    memset(tmpstr, 0, MAX_STR_LENGTH+1);
    if ((status = nc_get_att_text(exoid, propid, ATT_PROP_NAME, tmpstr)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to get property name in file id %d", exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      return (EX_FATAL);
    }

    if (strcmp(tmpstr, prop_name) == 0) {
      found = TRUE;
      break;
    }
  }

  /* if property array has not been created, create it */
  if (!found) {

    /* put netcdf file into define mode  */
    if ((status = nc_redef (exoid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      return (EX_FATAL);
    }

    /*   create a variable with a name xx_prop#, where # is the new number   */
    /*   of properties                                                       */
    switch (obj_type){
    case EX_ELEM_BLOCK:
      strcpy (name, VAR_EB_PROP(num_props+1));
      break;
    case EX_FACE_BLOCK:
      strcpy (name, VAR_FA_PROP(num_props+1));
      break;
    case EX_EDGE_BLOCK:
      strcpy (name, VAR_ED_PROP(num_props+1));
      break;
    case EX_NODE_SET:
      strcpy (name, VAR_NS_PROP(num_props+1));
      break;
    case EX_EDGE_SET:
      strcpy (name, VAR_ES_PROP(num_props+1));
      break;
    case EX_FACE_SET:
      strcpy (name, VAR_FS_PROP(num_props+1));
      break;
    case EX_ELEM_SET:
      strcpy (name, VAR_ELS_PROP(num_props+1));
      break;
    case EX_SIDE_SET:
      strcpy (name, VAR_SS_PROP(num_props+1));
      break;
    case EX_ELEM_MAP:
      strcpy (name, VAR_EM_PROP(num_props+1));
      break;
    case EX_FACE_MAP:
      strcpy (name, VAR_FAM_PROP(num_props+1));
      break;
    case EX_EDGE_MAP:
      strcpy (name, VAR_EDM_PROP(num_props+1));
      break;
    case EX_NODE_MAP:
      strcpy (name, VAR_NM_PROP(num_props+1));
      break;
    default:
      exerrval = EX_BADPARAM;
      sprintf(errmsg, "Error: object type %d not supported; file id %d",
	      obj_type, exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      goto error_ret;        /* Exit define mode and return */
    }

    dims[0] = dimid;
    nc_set_fill(exoid, NC_FILL, &oldfill); /* fill with zeros per routine spec */

    if ((status = nc_def_var(exoid, name, NC_INT, 1, dims, &propid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to create property array variable in file id %d",
	      exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      goto error_ret;  /* Exit define mode and return */
    }
    nc_set_fill(exoid, oldfill, &temp); /* default: nofill */


    /*   store property name as attribute of property array variable */
    if ((status = nc_put_att_text(exoid, propid, ATT_PROP_NAME, 
				  strlen(prop_name)+1, prop_name)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to store property name %s in file id %d",
	      prop_name,exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      goto error_ret;  /* Exit define mode and return */
    }

    /* leave define mode  */

    if ((status = nc_enddef (exoid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to leave define mode in file id %d",
	      exoid);
      ex_err("ex_put_prop_array",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  /* put num_obj values in property array */
  status = nc_put_var_int(exoid, propid, values);

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

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  nc_set_fill(exoid, oldfill, &temp); /* default: nofill */
  if (nc_enddef (exoid) != NC_NOERR) {    /* exit define mode */
    sprintf(errmsg,
	    "Error: failed to complete definition for file id %d",
	    exoid);
    ex_err("ex_put_prop_array",errmsg,exerrval);
  }
  return (EX_FATAL);
}