コード例 #1
0
ファイル: ex_utils.c プロジェクト: jbcarleton/seacas
int ex_get_name_internal(int exoid, int varid, size_t index, char *name, int name_size,
                         ex_entity_type obj_type, const char *routine)
{
  size_t start[2], count[2];
  int    status;
  char   errmsg[MAX_ERR_LENGTH];
  int    api_name_size = ex_inquire_int(exoid, EX_INQ_MAX_READ_NAME_LENGTH);

  /* read the name */
  start[0] = index;
  count[0] = 1;
  start[1] = 0;
  count[1] = name_size + 1;

  status = nc_get_vara_text(exoid, varid, start, count, name);
  if (status != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s name at index %d from file id %d",
             ex_name_of_object(obj_type), (int)index, exoid);
    ex_err(routine, errmsg, exerrval);
    return (EX_FATAL);
  }

  name[api_name_size] = '\0';

  ex_trim_internal(name);
  return EX_NOERR;
}
コード例 #2
0
ファイル: netcdf.cpp プロジェクト: mmase/wgrib2
NcBool NcVar::get( char* vals,
		     long edge0,
		     long edge1,
		     long edge2,
		     long edge3,
		     long edge4) const
{
    if (! the_file->data_mode())
      return FALSE;
    size_t count[5];
    count[0] = edge0;
    count[1] = edge1;
    count[2] = edge2;
    count[3] = edge3;
    count[4] = edge4;
    for (int i = 0; i < 5; i++) {
	if (count[i]) {
	    if (num_dims() < i)
	      return FALSE;
	} else
	  break;
    }
    size_t start[5];
    for (int j = 0; j < 5; j++) {
     start[j] = the_cur[j];
    }
    return NcError::set_err(
			    nc_get_vara_text (the_file->id(), the_id, start, count, vals)
			    ) == NC_NOERR;
}
コード例 #3
0
ファイル: ex_utils.c プロジェクト: ArtisticCoding/libmesh
int ex_get_name_internal(int exoid, int varid, size_t index, char *name,
			 ex_entity_type obj_type, const char *routine)
{
  size_t start[2], count[2];
  int status;
  char errmsg[MAX_ERR_LENGTH];

  /* read the name */
  start[0] = index;  count[0] = 1;
  start[1] = 0;      count[1] = ex_max_name_length+1;

  status = nc_get_vara_text(exoid, varid, start, count, name);
  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg, "Error: failed to get %s name at index %d from file id %d",
	    ex_name_of_object(obj_type), (int)index, exoid);
    ex_err(routine,errmsg,exerrval);
    return (EX_FATAL);
  }

  name[ex_max_name_length] = '\0';
  
  ex_trim_internal(name);
  return EX_NOERR;
}
コード例 #4
0
ファイル: netcdf.cpp プロジェクト: mmase/wgrib2
NcBool NcVar::get( char* vals, const long* count ) const
{
    if (! the_file->data_mode())
      return FALSE;
    size_t start[NC_MAX_DIMS];
    for (int i = 0; i < num_dims(); i++)
	start[i] = the_cur[i];
    return nc_get_vara_text (the_file->id(), the_id, start, (const size_t*) count, vals) == NC_NOERR;
}
コード例 #5
0
ファイル: netcdf.cpp プロジェクト: mmase/wgrib2
NcValues* NcVar::values( void ) const
{
    int ndims = num_dims();
    size_t crnr[NC_MAX_DIMS];
    size_t edgs[NC_MAX_DIMS];
    for (int i = 0; i < ndims; i++) {
	crnr[i] = 0;
	edgs[i] = get_dim(i)->size();
    }
    NcValues* valp = get_space();
    int status;
    switch (type()) {
    case ncFloat:
	status = NcError::set_err(
				  nc_get_vara_float(the_file->id(), the_id, crnr, edgs, 
				   (float *)valp->base())
				  );
	break;
    case ncDouble:
	status = NcError::set_err(
				  nc_get_vara_double(the_file->id(), the_id, crnr, edgs, 
				    (double *)valp->base())
				  );
	break;
    case ncInt:
	status = NcError::set_err(
				  nc_get_vara_int(the_file->id(), the_id, crnr, edgs, 
				 (int *)valp->base())
				  );
	break;
    case ncShort:
	status = NcError::set_err(
				  nc_get_vara_short(the_file->id(), the_id, crnr, edgs, 
				   (short *)valp->base())
				  );
	break;
    case ncByte:
	status = NcError::set_err(
				  nc_get_vara_schar(the_file->id(), the_id, crnr, edgs, 
				   (signed char *)valp->base())
				  );
	break;
    case ncChar:
	status = NcError::set_err(
				  nc_get_vara_text(the_file->id(), the_id, crnr, edgs, 
				   (char *)valp->base())
				  );
	break;
    case ncNoType:
    default:
	return 0;
    }
    if (status != NC_NOERR)
	return 0;
    return valp;
}
コード例 #6
0
ファイル: ncdf.c プロジェクト: cran/ncdf
void R_nc_get_vara_text( int *ncid, int *varid, int *start, 
	int *count, char **tempstore, char **data, int *retval )
{
	int	i, err, ndims;
	size_t	s_start[MAX_NC_DIMS], s_count[MAX_NC_DIMS], nstr, slen;
	char	vn[2048];

	err = nc_inq_varndims(*ncid, *varid, &ndims );
	if( err != NC_NOERR ) 
		REprintf( "Error in R_nc_get_vara_text while getting ndims: %s\n", 
			nc_strerror(*retval) );

	nstr = 1L;
	for( i=0; i<ndims; i++ ) {
		s_start[i] = (size_t)start[i];
		s_count[i] = (size_t)count[i];
		if( i < (ndims-1) ) 
			nstr *= s_count[i];
		}
	slen = s_count[ndims-1];

	*retval = nc_get_vara_text(*ncid, *varid, s_start, s_count, tempstore[0] );

	if( *retval != NC_NOERR ) {
		nc_inq_varname( *ncid, *varid, vn );
		REprintf( "Error in R_nc_get_vara_text: %s\n", 
			nc_strerror(*retval) );
		REprintf( "Var: %s  Ndims: %d   Start: ", vn, ndims );
		for( i=0; i<ndims; i++ ) {
			REprintf( "%u", (unsigned int)s_start[i] );
			if( i < ndims-1 )
				REprintf( "," );
			}
		REprintf( "Count: " );
		for( i=0; i<ndims; i++ ) {
			REprintf( "%u", (unsigned int)s_count[i] );
			if( i < ndims-1 )
				REprintf( "," );
			}
		}

	/* Now copy each string over to the final data array */
	for( i=0; i<nstr; i++ ) {
		strncpy( data[i], tempstore[0]+i*slen, slen );
		data[i][slen] = '\0';
		}
}
コード例 #7
0
ファイル: fort-v2compat.c プロジェクト: akiyoshi/wrf-fire
/*
 * Read a hypercube of character values from a netCDF variable.
 */
static void
c_ncvgtc(
    int			ncid,	/* netCDF ID */
    int			varid,	/* variable ID */
    const size_t*	start,	/* multidimensional index of hypercube corner */
    const size_t*	count,	/* multidimensional hypercube edge lengths */
    char*		value,	/* block of data values to be read */
    int			lenstr,	/* declared length of the data argument */
    int*		rcode	/* returned error code */
)
{
    int		status;
    nc_type	datatype;

    if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0)
    {
	if (datatype != NC_CHAR)
	    status = NC_ECHAR;
	else if ((status = nc_get_vara_text(ncid, varid, start, count, value))
		 == 0)
	{
	    int	rank;

	    if ((status = nc_inq_varndims(ncid, varid, &rank)) == 0)
	    {
		size_t	total = dimprod(count, rank);

		(void) memset(value+total, ' ', lenstr - total);
	    }
	}
    }

    if (status == 0)
	*rcode = 0;
    else
    {
	nc_advise("NCVGTC", status, "");
	*rcode = ncerr;
    }
}
コード例 #8
0
ファイル: mpp_io.c プロジェクト: djibi2/AM3
/*********************************************************************
  void mpp_get_var_value_block(int fid, int vid, const size_t *start, const size_t *nread, void *data)
  read part of var data, the part is defined by start and nread.
*********************************************************************/
void mpp_get_var_value_block(int fid, int vid, const size_t *start, const size_t *nread, void *data)
{
  int status;
  char errmsg[512];
  
  if(fid<0 || fid >=nfiles) mpp_error("mpp_io(mpp_get_var_value_block): invalid fid number, fid should be "
				    "a nonnegative integer that less than nfiles");
  if(vid<0 || vid >=files[fid].nvar) mpp_error("mpp_io(mpp_get_var_value_block): invalid vid number, vid should be "
				    "a nonnegative integer that less than nvar");

  switch(files[fid].var[vid].type) {
  case NC_DOUBLE:case NC_FLOAT:
    status = nc_get_vara_double(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break;
  case NC_INT:
    status = nc_get_vara_int(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break;
  case NC_SHORT:
    status = nc_get_vara_short(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break;  
  case NC_CHAR:
    status = nc_get_vara_text(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break; 
  default:
    sprintf(errmsg, "mpp_io(mpp_get_var_value_block): field %s in file %s has an invalid type, "
	    "the type should be NC_DOUBLE, NC_FLOAT, NC_INT, NC_SHORT or NC_CHAR",
	    files[fid].var[vid].name, files[fid].name );
    mpp_error(errmsg);
  }    
  if(status != NC_NOERR) {
    sprintf(errmsg, "mpp_io(mpp_get_var_value_block): Error in getting value of variable %s from file %s",
	    files[fid].var[vid].name, files[fid].name );
    netcdf_error(errmsg, status);
  }
  
}; /* mpp_get_var_value_block */
コード例 #9
0
ファイル: read_mosaic.c プロジェクト: djibi2/AM3
/*******************************************************************************
   void get_string_data_level(const char *file, const char *name, const size_t *start, const size_t *nread, char *data)
   get string data of field with "name" from "file".
******************************************************************************/
void get_string_data_level(const char *file, const char *name, char *data, const int *level)
{
  int ncid, varid, status, i;
  size_t start[4], nread[4];
  char msg[512];

#ifdef use_netCDF  
  status = nc_open(file, NC_NOWRITE, &ncid);
  if(status != NC_NOERR) {
    sprintf(msg, "in opening file %s", file);
    handle_netcdf_error(msg, status);
  }
  status = nc_inq_varid(ncid, name, &varid);
  if(status != NC_NOERR) {
    sprintf(msg, "in getting varid of %s from file %s.", name, file);
    handle_netcdf_error(msg, status);
  }
  for(i=0; i<4; i++) {
    start[i] = 0; nread[i] = 1;
  }
  start[0] = *level; nread[1] = STRING;
  status = nc_get_vara_text(ncid, varid, start, nread, data);
  if(status != NC_NOERR) {
    sprintf(msg, "in getting data of %s from file %s.", name, file);
    handle_netcdf_error(msg, status);
  }
  status = nc_close(ncid);
  if(status != NC_NOERR) {
    sprintf(msg, "in closing file %s.", file);
    handle_netcdf_error(msg, status);
  }  
#else
  error_handler("read_mosaic: Add flag -Duse_netCDF when compiling");
#endif
  
}; /* get_string_data_level */
コード例 #10
0
ファイル: t_nc_p5.c プロジェクト: BJangeofan/netcdf-c
/*ARGSUSED*/
int
main(int argc, char *argv[])
{
	int cmode=NC_CLOBBER, omode, ret;
	int	 id;
	char buf[256];
#ifdef SYNCDEBUG
	char *str = "one";
#endif
	int ii;
	size_t ui;
	const struct tcdfvar *tvp = testvars;
	union getret got;
	const size_t initialsz = 8192;
	size_t chunksz = 8192;
	size_t align = 8192/32;

	MPI_Init(&argc, &argv);

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

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

	createtestvars(id, testvars, NUM_TESTVARS); 

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	MPI_Finalize();
	return 0;
}
コード例 #11
0
ファイル: netcdf.cpp プロジェクト: mmase/wgrib2
NcValues* NcVar::get_rec(NcDim* rdim, long slice)
{
    int idx = dim_to_index(rdim);
    long size = num_dims();
    size_t* start = new size_t[size];
    long* startl = new long[size];
    for (int i=1; i < size ; i++) {
	start[i] = 0;
	startl[i] = 0;
    }
    start[idx] = slice;
    startl[idx] = slice;
    NcBool result = set_cur(startl);
    if (! result ) {
	delete [] start;
	delete [] startl;
	return 0;
    }

    long* edgel = edges();
    size_t* edge = new size_t[size];
    for (int i=1; i < size ; i++) {
	edge[i] = edgel[i];
    }
    edge[idx] = 1;
    edgel[idx] = 1;
    NcValues* valp = get_space(rec_size(rdim));
    int status;
    switch (type()) {
    case ncFloat:
	status = NcError::set_err(
				  nc_get_vara_float(the_file->id(), the_id, start, edge, 
				   (float *)valp->base())
				  );
	break;
    case ncDouble:
	status = NcError::set_err(
				  nc_get_vara_double(the_file->id(), the_id, start, edge, 
				    (double *)valp->base())
				  );
	break;
    case ncInt:
	status = NcError::set_err(
				  nc_get_vara_int(the_file->id(), the_id, start, edge, 
				 (int *)valp->base())
				  );
	break;
    case ncShort:
	status = NcError::set_err(
				  nc_get_vara_short(the_file->id(), the_id, start, edge, 
				   (short *)valp->base())
				  );
	break;
    case ncByte:
	status = NcError::set_err(
				  nc_get_vara_schar(the_file->id(), the_id, start, edge, 
				   (signed char *)valp->base())
				  );
	break;
    case ncChar:
	status = NcError::set_err(
				  nc_get_vara_text(the_file->id(), the_id, start, edge, 
				   (char *)valp->base())
				  );
	break;
    case ncNoType:
    default:
	return 0;
    }
    delete [] start;
    delete [] startl;
    delete [] edge;
    delete [] edgel;
    if (status != NC_NOERR) {
	delete valp;
	return 0;
    }
    return valp;
} 
コード例 #12
0
ファイル: tst_coords.c プロジェクト: ArtisticCoding/libmesh
int
main(int argc, char **argv)
{
   printf("\n*** Testing netcdf-4 coordinate variables and dimensions.\n");

   printf("**** testing Jeff Whitakers reported 4.1 bug...");
   {
#define NDIMS 2
#define NLAT 10
#define NLON 20
#define LAT_NAME "lat"
#define LON_NAME "lon"
#define NVARS 2
#define START_LAT 25.0
#define START_LON -125.0
      {
	 int ncid, lon_dimid, lat_dimid;
	 int lat_varid, lon_varid;
	 float lats[NLAT], lons[NLON];
	 int lat, lon;
	 int nvars, ndims, ngatts, unlimdimid, nvars_in, varids_in[NVARS];
	 int ndims_in, natts_in, dimids_in[NDIMS];
	 char var_name_in[NC_MAX_NAME + 1];
	 nc_type xtype_in;

	 /* Initialize coord data. */
	 for (lat = 0; lat < NLAT; lat++)
	    lats[lat] = START_LAT + 5. * lat;
	 for (lon = 0; lon < NLON; lon++)
	    lons[lon] = START_LON + 5. * lon;

	 /* Create file with two dimensions. */
	 if (nc_create(FILE_NAME, NC_NETCDF4 | NC_CLOBBER, &ncid)) ERR;
	 if (nc_def_dim(ncid, LAT_NAME, NLAT, &lat_dimid)) ERR;
	 if (nc_def_dim(ncid, LON_NAME, NLON, &lon_dimid)) ERR;

	 if (nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, &lon_dimid, &lon_varid)) ERR;

	 /* Define and write longitude coord variable. */
	 if (nc_put_var_float(ncid, lon_varid, &lons[0])) ERR;

	 /* Define and write latitude coord variable. */
	 if (nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, &lat_dimid, &lat_varid)) ERR;
	 if (nc_put_var_float(ncid, lat_varid, &lats[0])) ERR;

	 if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
	 if (nvars != 2 || ndims != 2 || ngatts != 0 || unlimdimid != -1) ERR;
	 if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
	 if (nvars_in != 2 || varids_in[0] != 0 || varids_in[1] != 1) ERR;
	 if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
	 if (strcmp(var_name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	     dimids_in[0] != 1 || natts_in != 0) ERR;

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

	 /* Re-open and check the file. */
	 if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

	 if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
	 if (nvars != 2 || ndims != 2 || ngatts != 0 || unlimdimid != -1) ERR;
	 if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
	 if (nvars_in != 2 || varids_in[0] != 0 || varids_in[1] != 1) ERR;
	 if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
	 if (strcmp(var_name_in, LON_NAME) || xtype_in != NC_FLOAT || ndims_in != 1 ||
	 dimids_in[0] != 1 || natts_in != 0) ERR;

	 if (nc_close(ncid)) ERR;
      }

   }
   SUMMARIZE_ERR;
   printf("**** testing setting cache values for coordinate variables...");
   {
#define RANK_1 1
#define DIM0_NAME "d0"
#define CACHE_SIZE 1000000
#define CACHE_NELEMS 1009
#define CACHE_PREEMPTION .90

      int ncid, dimid, varid;
      char name_in[NC_MAX_NAME + 1];

      /* Create a test file with one dim and coord variable. */
      if (nc_create(FILE_NAME, NC_CLASSIC_MODEL|NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM0_NAME, NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_var(ncid, DIM0_NAME, NC_DOUBLE, 1, &dimid, &varid)) ERR;
      if (nc_set_var_chunk_cache(ncid, varid, CACHE_SIZE, CACHE_NELEMS, CACHE_PREEMPTION)) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen the file and check. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_varname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, DIM0_NAME)) ERR;
      if (nc_set_var_chunk_cache(ncid, 0, CACHE_SIZE, CACHE_NELEMS, CACHE_PREEMPTION)) ERR;
      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, DIM0_NAME)) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing multi-line strings in attributes...");
   {
      int ncid_classic, ncid_nc4;
      /*int attid;*/
      char att_in_classic[NC_MAX_NAME + 1], att_in_nc4[NC_MAX_NAME + 1];

#define FILE_CLASSIC "tst_coords_classic_att.nc"
#define FILE_NC4 "tst_coords_nc4_att.nc"
      /* Create a classic and a netcdf-4 file. */
      if (nc_create(FILE_CLASSIC, 0, &ncid_classic)) ERR;
      if (nc_create(FILE_NC4, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid_nc4)) ERR;

      /* Write an att to both. */
      if (nc_put_att_text(ncid_classic, NC_GLOBAL, INST_NAME, strlen(INSTITUTION) + 1, INSTITUTION)) ERR;
      if (nc_put_att_text(ncid_nc4, NC_GLOBAL, INST_NAME, strlen(INSTITUTION) + 1, INSTITUTION)) ERR;

      /* Close them. */
      if (nc_close(ncid_classic)) ERR;
      if (nc_close(ncid_nc4)) ERR;

      /* Reopen the files. */
      if (nc_open(FILE_CLASSIC, 0, &ncid_classic)) ERR;
      if (nc_open(FILE_NC4, 0, &ncid_nc4)) ERR;

      /* I'll show you mine, if you show me yours... */
      if (nc_get_att_text(ncid_classic, NC_GLOBAL, INST_NAME, att_in_classic)) ERR;
      if (nc_get_att_text(ncid_nc4, NC_GLOBAL, INST_NAME, att_in_nc4)) ERR;
      if (strcmp(att_in_classic, INSTITUTION) || strcmp(att_in_nc4, INSTITUTION) ||
	  strcmp(att_in_classic, att_in_nc4)) ERR;
      if (memcmp(att_in_classic, att_in_nc4, strlen(INSTITUTION) + 1)) ERR;

      /* Close them. */
      if (nc_close(ncid_classic)) ERR;
      if (nc_close(ncid_nc4)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing ar-4 example metadata with ncgen-generated code...");
   {
      int  stat;  /* return status */
      int  ncid;  /* netCDF id */

      /* group ids */
      int root_grp;

      /* dimension ids */
      int lon_dim;
      int lat_dim;
      int bnds_dim;
      int time_dim;

      /* dimension lengths */
      size_t lon_len = 256;
      size_t lat_len = 128;
      size_t bnds_len = 2;
      size_t time_len = NC_UNLIMITED;

      /* variable ids */
      int lon_bnds_id;
      int lat_bnds_id;
      int time_bnds_id;
      int time_id;
      int lat_id;
      int lon_id;
      int pr_id;

      /* rank (number of dimensions) for each variable */
#   define RANK_lon_bnds 2
#   define RANK_lat_bnds 2
#   define RANK_time_bnds 2
#   define RANK_time 1
#   define RANK_lat 1
#   define RANK_lon 1
#   define RANK_pr 3

      /* variable shapes */
      int lon_bnds_dims[RANK_lon_bnds];
      int lat_bnds_dims[RANK_lat_bnds];
      int time_bnds_dims[RANK_time_bnds];
      int time_dims[RANK_time];
      int lat_dims[RANK_lat];
      int lon_dims[RANK_lon];
      int pr_dims[RANK_pr];

      /* enter define mode */
      stat = nc_create(FILE_NAME, NC_NETCDF4 | NC_CLASSIC_MODEL, &ncid);
      check_err(stat,__LINE__,__FILE__);
      root_grp = ncid;

      /* define dimensions */
      stat = nc_def_dim(root_grp, "lon", lon_len, &lon_dim);
      check_err(stat,__LINE__,__FILE__);
      stat = nc_def_dim(root_grp, "lat", lat_len, &lat_dim);
      check_err(stat,__LINE__,__FILE__);
      stat = nc_def_dim(root_grp, "bnds", bnds_len, &bnds_dim);
      check_err(stat,__LINE__,__FILE__);
      stat = nc_def_dim(root_grp, "time", time_len, &time_dim);
      check_err(stat,__LINE__,__FILE__);

      /* define variables */

      lon_bnds_dims[0] = lon_dim;
      lon_bnds_dims[1] = bnds_dim;
      stat = nc_def_var(root_grp, "lon_bnds", NC_DOUBLE, RANK_lon_bnds, lon_bnds_dims, &lon_bnds_id);
      check_err(stat,__LINE__,__FILE__);

      lat_bnds_dims[0] = lat_dim;
      lat_bnds_dims[1] = bnds_dim;
      stat = nc_def_var(root_grp, "lat_bnds", NC_DOUBLE, RANK_lat_bnds, lat_bnds_dims, &lat_bnds_id);
      check_err(stat,__LINE__,__FILE__);

      time_bnds_dims[0] = time_dim;
      time_bnds_dims[1] = bnds_dim;
      stat = nc_def_var(root_grp, "time_bnds", NC_DOUBLE, RANK_time_bnds, time_bnds_dims, &time_bnds_id);
      check_err(stat,__LINE__,__FILE__);

      time_dims[0] = time_dim;
      stat = nc_def_var(root_grp, "time", NC_DOUBLE, RANK_time, time_dims, &time_id);
      check_err(stat,__LINE__,__FILE__);

      lat_dims[0] = lat_dim;
      stat = nc_def_var(root_grp, "lat", NC_DOUBLE, RANK_lat, lat_dims, &lat_id);
      check_err(stat,__LINE__,__FILE__);

      lon_dims[0] = lon_dim;
      stat = nc_def_var(root_grp, "lon", NC_DOUBLE, RANK_lon, lon_dims, &lon_id);
      check_err(stat,__LINE__,__FILE__);

      pr_dims[0] = time_dim;
      pr_dims[1] = lat_dim;
      pr_dims[2] = lon_dim;
      stat = nc_def_var(root_grp, "pr", NC_FLOAT, RANK_pr, pr_dims, &pr_id);
      check_err(stat,__LINE__,__FILE__);

      /* assign global attributes */
      { /* table_id */
	 static const char table_id_att[8] = {"Table A1"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "table_id", 8, table_id_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* title */
	 static const char title_att[34] = {"model output prepared for IPCC AR4"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "title", 34, title_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* institution */
	 static const char institution_att[66] = {INSTITUTION} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, INST_NAME, 66, institution_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* source */
	 static const char source_att[153] = {"CCSM3.0, version vector05 (2004): \natmosphere: CAM3.0, T85L26;\nocean     : POP1.4.3 (modified), gx1v3\nsea ice   : CSIM5.0, gx1v3;\nland      : CLM3.0, T85"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "source", 153, source_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* contact */
	 static const char contact_att[13] = {"*****@*****.**"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "contact", 13, contact_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* project_id */
	 static const char project_id_att[22] = {"IPCC Fourth Assessment"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "project_id", 22, project_id_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* Conventions */
	 static const char Conventions_att[6] = {"CF-1.0"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "Conventions", 6, Conventions_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* references */
	 static const char references_att[137] = {"Collins, W.D., et al., 2005:\n The Community Climate System Model, Version 3\n Journal of Climate\n \n Main website: http://www.ccsm.ucar.edu"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "references", 137, references_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* acknowledgment */
	 static const char acknowledgment_att[847] = {" Any use of CCSM data should acknowledge the contribution\n of the CCSM project and CCSM sponsor agencies with the \n following citation:\n 'This research uses data provided by the Community Climate\n System Model project (www.ccsm.ucar.edu), supported by the\n Directorate for Geosciences of the National Science Foundation\n and the Office of Biological and Environmental Research of\n the U.S. Department of Energy.'\nIn addition, the words 'Community Climate System Model' and\n 'CCSM' should be included as metadata for webpages referencing\n work using CCSM data or as keywords provided to journal or book\npublishers of your manuscripts.\nUsers of CCSM data accept the responsibility of emailing\n citations of publications of research using CCSM data to\n [email protected].\nAny redistribution of CCSM data must include this data\n acknowledgement statement."} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "acknowledgment", 847, acknowledgment_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* realization */
	 static const int realization_att[1] = {8} ;
	 stat = nc_put_att_int(root_grp, NC_GLOBAL, "realization", NC_INT, 1, realization_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* experiment_id */
	 static const char experiment_id_att[46] = {"climate of the 20th Century experiment (20C3M)"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "experiment_id", 46, experiment_id_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* history */
	 static const char history_att[139] = {"Created from CCSM3 case b30.030g.ES01\n by [email protected]\n on Wed Sep 10 12:22:06 MDT 2008\n \n For all data, added IPCC requested metadata"} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "history", 139, history_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* comment */
	 static const char comment_att[1105] = {"This simulation was initiated from year 460 of \n CCSM3 model run b30.020.ES01 and executed on \n hardware Earth Simulator Center, JAMSTEC. The input external forcings are\nozone forcing    : mozart.o3.128x64_L18_1870-2000_c040515.nc\naerosol optics   : AerosolOptics_c040105.nc\naerosol MMR      : AerosolMass_V_128x256_clim_c031022.nc\ncarbon scaling   : carbonscaling_1870-2000_c040225.nc\nsolar forcing    : scon_lean_1870-2100_c040123.nc\nGHGs             : ghg_1870_2100_c040122.nc\nGHG loss rates   : noaamisc.r8.nc\nvolcanic forcing : VolcanicMass_1870-1999_64x1_L18_c040123.nc\nDMS emissions    : DMS_emissions_128x256_clim_c040122.nc\noxidants         : oxid_128x256_L26_clim_c040112.nc\nSOx emissions    : SOx_emissions_128x256_L2_1850-2000_c040321.nc\n Physical constants used for derived data:\n Lv (latent heat of evaporation): 2.501e6 J kg-1\n Lf (latent heat of fusion     ): 3.337e5 J kg-1\n r[h2o] (density of water      ): 1000 kg m-3\n g2kg   (grams to kilograms    ): 1000 g kg-1\n \n Integrations were performed by NCAR and CRIEPI with support\n and facilities provided by NSF, DOE, MEXT and ESC/JAMSTEC."} ;
	 stat = nc_put_att_text(root_grp, NC_GLOBAL, "comment", 1105, comment_att);
	 check_err(stat,__LINE__,__FILE__);
      }


      /* assign per-variable attributes */
      { /* calendar */
	 static const char time_calendar_att[6] = {"noleap"} ;
	 stat = nc_put_att_text(root_grp, time_id, "calendar", 6, time_calendar_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* standard_name */
	 static const char time_standard_name_att[4] = {"time"} ;
	 stat = nc_put_att_text(root_grp, time_id, "standard_name", 4, time_standard_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* axis */
	 static const char time_axis_att[1] = {"T"} ;
	 stat = nc_put_att_text(root_grp, time_id, "axis", 1, time_axis_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* units */
	 static const char time_units_att[19] = {"days since 0000-1-1"} ;
	 stat = nc_put_att_text(root_grp, time_id, "units", 19, time_units_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* bounds */
	 static const char time_bounds_att[9] = {"time_bnds"} ;
	 stat = nc_put_att_text(root_grp, time_id, "bounds", 9, time_bounds_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* long_name */
	 static const char time_long_name_att[4] = {"time"} ;
	 stat = nc_put_att_text(root_grp, time_id, "long_name", 4, time_long_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* axis */
	 static const char lat_axis_att[1] = {"Y"} ;
	 stat = nc_put_att_text(root_grp, lat_id, "axis", 1, lat_axis_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* standard_name */
	 static const char lat_standard_name_att[8] = {"latitude"} ;
	 stat = nc_put_att_text(root_grp, lat_id, "standard_name", 8, lat_standard_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* bounds */
	 static const char lat_bounds_att[8] = {"lat_bnds"} ;
	 stat = nc_put_att_text(root_grp, lat_id, "bounds", 8, lat_bounds_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* long_name */
	 static const char lat_long_name_att[8] = {"latitude"} ;
	 stat = nc_put_att_text(root_grp, lat_id, "long_name", 8, lat_long_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* units */
	 static const char lat_units_att[13] = {"degrees_north"} ;
	 stat = nc_put_att_text(root_grp, lat_id, "units", 13, lat_units_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* axis */
	 static const char lon_axis_att[1] = {"X"} ;
	 stat = nc_put_att_text(root_grp, lon_id, "axis", 1, lon_axis_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* standard_name */
	 static const char lon_standard_name_att[9] = {"longitude"} ;
	 stat = nc_put_att_text(root_grp, lon_id, "standard_name", 9, lon_standard_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* bounds */
	 static const char lon_bounds_att[8] = {"lon_bnds"} ;
	 stat = nc_put_att_text(root_grp, lon_id, "bounds", 8, lon_bounds_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* long_name */
	 static const char lon_long_name_att[9] = {"longitude"} ;
	 stat = nc_put_att_text(root_grp, lon_id, "long_name", 9, lon_long_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* units */
	 static const char lon_units_att[12] = {"degrees_east"} ;
	 stat = nc_put_att_text(root_grp, lon_id, "units", 12, lon_units_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* comment */
	 static const char pr_comment_att[60] = {"Created using NCL code CCSM_atmm_2cf.ncl on\n machine mineral"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "comment", 60, pr_comment_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* missing_value */
	 static const float pr_missing_value_att[1] = {1e+20} ;
	 stat = nc_put_att_float(root_grp, pr_id, "missing_value", NC_FLOAT, 1, pr_missing_value_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* _FillValue */
	 static const float pr_FillValue_att[1] = {1e+20} ;
	 stat = nc_put_att_float(root_grp, pr_id, "_FillValue", NC_FLOAT, 1, pr_FillValue_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* cell_methods */
	 static const char pr_cell_methods_att[30] = {"time: mean (interval: 1 month)"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "cell_methods", 30, pr_cell_methods_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* history */
	 static const char pr_history_att[20] = {"(PRECC+PRECL)*r[h2o]"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "history", 20, pr_history_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* original_units */
	 static const char pr_original_units_att[7] = {"m-1 s-1"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "original_units", 7, pr_original_units_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* original_name */
	 static const char pr_original_name_att[12] = {"PRECC, PRECL"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "original_name", 12, pr_original_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* standard_name */
	 static const char pr_standard_name_att[18] = {"precipitation_flux"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "standard_name", 18, pr_standard_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* units */
	 static const char pr_units_att[10] = {"kg m-2 s-1"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "units", 10, pr_units_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* long_name */
	 static const char pr_long_name_att[18] = {"precipitation_flux"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "long_name", 18, pr_long_name_att);
	 check_err(stat,__LINE__,__FILE__);
      }
      { /* cell_method */
	 static const char pr_cell_method_att[10] = {"time: mean"} ;
	 stat = nc_put_att_text(root_grp, pr_id, "cell_method", 10, pr_cell_method_att);
	 check_err(stat,__LINE__,__FILE__);
      }

      /* don't initialize variables with fill values */
      stat = nc_set_fill(root_grp, NC_NOFILL, 0);
      check_err(stat,__LINE__,__FILE__);

      /* leave define mode */
      stat = nc_enddef (root_grp);
      check_err(stat,__LINE__,__FILE__);

      stat = nc_close(root_grp);
      check_err(stat,__LINE__,__FILE__);

      {
#define NDIMS4 4
	 int ndims, dimids_in[NDIMS4];
	 char name_in[NC_MAX_NAME + 1];
	 char institution_att_in[NC_MAX_NAME + 1];

	 /* Now open this file and check order of dimensions. */
	 if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

	 /* Check dimids. */
	 if (nc_inq_dimname(ncid, 0, name_in)) ERR;
	 if (strcmp(name_in, "lon")) ERR;
	 if (nc_inq_dimname(ncid, 1, name_in)) ERR;
	 if (strcmp(name_in, "lat")) ERR;
	 if (nc_inq_dimname(ncid, 2, name_in)) ERR;
	 if (strcmp(name_in, "bnds")) ERR;
	 if (nc_inq_dimname(ncid, 3, name_in)) ERR;
	 if (strcmp(name_in, "time")) ERR;

	 /* Check inq_dimids function. */
	 if (nc_inq_dimids(ncid, &ndims, dimids_in, 0)) ERR;
	 if (ndims != NDIMS4 || dimids_in[0] != 0 || dimids_in[1] != 1 ||
	     dimids_in[2] != 2 || dimids_in[3] != 3) ERR;

	 /* Check attribute with line breaks. */
	 if (nc_get_att_text(ncid, NC_GLOBAL, INST_NAME,
			     institution_att_in)) ERR;
	 if (strncmp(institution_att_in, INSTITUTION, strlen(INSTITUTION))) ERR;

	 if (nc_close(ncid)) ERR;
      }

   }
   SUMMARIZE_ERR;
   printf("**** testing dim order when coord vars are defined in the wrong order...");
   {
#define RANK_2 2
#define DIM0 "d0"
#define DIM1 "d1"
      int ncid, dimids[RANK_2], varid[RANK_2];
      char name_in[NC_MAX_NAME + 1];

      /* Create a test file. */
      if (nc_create(FILE_NAME, NC_CLASSIC_MODEL|NC_NETCDF4, &ncid)) ERR;

      /* Define dimensions in order. */
      if (nc_def_dim(ncid, DIM0, NC_UNLIMITED, &dimids[0])) ERR;
      if (nc_def_dim(ncid, DIM1, 4, &dimids[1])) ERR;

      /* Define coordinate variables in a different order. */
      if (nc_def_var(ncid, DIM1, NC_DOUBLE, 1, &dimids[1], &varid[1])) ERR;
      if (nc_def_var(ncid, DIM0, NC_DOUBLE, 1, &dimids[0], &varid[0])) ERR;

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

      /* Reopen the file and check dimension order. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, DIM0)) ERR;
      if (nc_inq_dimname(ncid, 1, name_in)) ERR;
      if (strcmp(name_in, DIM1)) ERR;

      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing order of coordinate dims...");
   {
#define RANK_3 3
#define DIM1_NAME "d1"
#define DIM2_NAME "d2"
#define DIM3_NAME "d3"
      int ncid, dimids[RANK_3], varid[RANK_3];
      char name_in[NC_MAX_NAME + 1];

      /* Create a 3D test file. */
      if (nc_create(FILE_NAME, NC_CLASSIC_MODEL|NC_NETCDF4, &ncid)) ERR;

      /* Define dimensions in order. */
      if (nc_def_dim(ncid, DIM1_NAME, NC_UNLIMITED, &dimids[0])) ERR;
      if (nc_def_dim(ncid, DIM2_NAME, 4, &dimids[1])) ERR;
      if (nc_def_dim(ncid, DIM3_NAME, 3, &dimids[2])) ERR;

      /* Define coordinate variables in a different order. */
      if (nc_def_var(ncid, DIM1_NAME, NC_DOUBLE, 1, &dimids[0], &varid[0])) ERR;
      if (nc_def_var(ncid, DIM2_NAME, NC_DOUBLE, 1, &dimids[1], &varid[1])) ERR;
      if (nc_def_var(ncid, DIM3_NAME, NC_DOUBLE, 1, &dimids[2], &varid[2])) ERR;

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

      /* Reopen the file and check dimension order. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      if (nc_inq_dimname(ncid, 0, name_in)) ERR;
      if (strcmp(name_in, DIM1_NAME)) ERR;
      if (nc_inq_dimname(ncid, 1, name_in)) ERR;
      if (strcmp(name_in, DIM2_NAME)) ERR;
      if (nc_inq_dimname(ncid, 2, name_in)) ERR;
      if (strcmp(name_in, DIM3_NAME)) ERR;

      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing coordinate vars...");
   {
#   define RANK_Coordinates_lat 1
      int ncid;
      int Coordinates_grp;
      int lat_dim;
      size_t lat_len = 3;
      int Coordinates_lat_id;

      if(nc_create(FILE_NAME, NC_CLOBBER|NC_NETCDF4, &ncid)) ERR;
      if (nc_def_grp(ncid, "Coordinates", &Coordinates_grp)) ERR;

      /* Define dimensions in root group. */
      if (nc_def_dim(ncid, "lat", lat_len, &lat_dim)) ERR;

      /* Define coordinate variable in Coordinates group. */
      if (nc_def_var(Coordinates_grp, "lat", NC_FLOAT,
		     1, &lat_dim, &Coordinates_lat_id)) ERR;

      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing 2D non-coordinate variable...");
   {
#define VAR_NAME "Britany"
#define NDIMS 2
#define TEXT_LEN 15
#define D0_NAME "time"
#define D1_NAME "tl"
      int ncid, nvars_in, varids_in[1];
      int time_dimids[NDIMS], time_id;
      size_t time_count[NDIMS], time_index[NDIMS] = {0, 0};
      const char ttext[TEXT_LEN]="20051224.150000";
      int nvars, ndims, ngatts, unlimdimid;
      int ndims_in, natts_in, dimids_in[NDIMS];
      char var_name_in[NC_MAX_NAME + 1];
      nc_type xtype_in;

      /* Create a netcdf-4 file with 2D coordinate var. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;

      if (nc_def_dim(ncid, D0_NAME, NC_UNLIMITED, &time_dimids[0])) ERR;
      if (nc_def_dim(ncid, D1_NAME, TEXT_LEN, &time_dimids[1])) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_USHORT, NDIMS, time_dimids,
		     &time_id) != NC_ESTRICTNC3) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_CHAR, NDIMS, time_dimids, &time_id)) ERR;
      if (nc_enddef(ncid)) ERR;

      /* Write one time to the coordinate variable. */
      time_count[0] = 1;
      time_count[1] = TEXT_LEN;
      if (nc_put_vara_text(ncid, time_id, time_index, time_count, ttext)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open the file and check. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != 1 || ndims != 2 || ngatts != 0 || unlimdimid != 0) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != 1 || varids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, VAR_NAME) || xtype_in != NC_CHAR || ndims_in != 2 ||
          dimids_in[0] != 0 || dimids_in[1] != 1 || natts_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing 2D coordinate variable...");
   {
#define NDIMS 2
#define TEXT_LEN 15
#define D0_NAME "time"
#define D1_NAME "tl"
      int ncid, nvars_in, varids_in[1];
      int time_dimids[NDIMS], time_id;
      size_t time_count[NDIMS], time_index[NDIMS] = {0, 0};
      const char ttext[TEXT_LEN + 1]="20051224.150000";
      int nvars, ndims, ngatts, unlimdimid;
      int ndims_in, natts_in, dimids_in[NDIMS];
      char var_name_in[NC_MAX_NAME + 1];
      nc_type xtype_in;

      /* Create a netcdf-4 file with 2D coordinate var. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, D0_NAME, NC_UNLIMITED, &time_dimids[0])) ERR;
      if (nc_def_dim(ncid, D1_NAME, TEXT_LEN, &time_dimids[1])) ERR;
      if (nc_def_var(ncid, D0_NAME, NC_CHAR, NDIMS, time_dimids, &time_id)) ERR;

      /* Write one time to the coordinate variable. */
      time_count[0] = 1;
      time_count[1] = TEXT_LEN;
      if (nc_put_vara_text(ncid, time_id, time_index, time_count, ttext)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open the file and check. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != 1 || ndims != 2 || ngatts != 0 || unlimdimid != 0) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != 1 || varids_in[0] != 0) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, D0_NAME) || xtype_in != NC_CHAR || ndims_in != 2 ||
	dimids_in[0] != 0 || dimids_in[1] != 1 || natts_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing new order of doing things with coordinate variable...");
   {
      /* In this test:
           define a dimension
           define a variable that uses that dimension
           put values in the variable
           define coordinate values for the dimension
      */
#define VAR_NAME_BB "The_Birth_of_Britain"
#define NDIMS_1 1
#define TEXT_LEN 15
#define WINSTON_CHURCHILL "Winston_S_Churchill"
#define D0_LEN 2
#define NUM_VARS_2 2
      int ncid, nvars_in, varids_in[NUM_VARS_2];
      int dimid, varid, varid2;
      int nvars, ndims, ngatts, unlimdimid;
      int ndims_in, natts_in, dimids_in[NDIMS];
      char var_name_in[NC_MAX_NAME + 1];
      nc_type xtype_in;
      int data[D0_LEN] = {42, -42};

      /* Create a netcdf-4 file with 2D coordinate var. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, WINSTON_CHURCHILL, NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, NDIMS_1, &dimid, &varid)) ERR;
      if (nc_put_var_int(ncid, varid, data)) ERR;
      if (nc_def_var(ncid, WINSTON_CHURCHILL, NC_INT, NDIMS_1, &dimid, &varid2)) ERR;
      if (nc_put_var_int(ncid, varid2, data)) ERR;

      /* Check things. */
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != 2 || ndims != 1 || ngatts != 0 || unlimdimid != 0) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != 2 || varids_in[0] != 0 || varids_in[1] != 1) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, VAR_NAME) || xtype_in != NC_INT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;

      if (nc_close(ncid)) ERR;

      /* Open the file and check. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != 2 || ndims != 1 || ngatts != 0 || unlimdimid != 0) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != 2 || varids_in[0] != 0 || varids_in[1] != 1) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, VAR_NAME) || xtype_in != NC_INT || ndims_in != 1 ||
	  dimids_in[0] != 0 || natts_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing 2D coordinate variable with dimensions defined in different order...");
   {
#define NDIMS 2
#define TEXT_LEN 15
#define D0_NAME "time"
#define D1_NAME "tl"
#define NUM_VARS 2
      int ncid, nvars_in, varids_in[NUM_VARS];
      int time_dimids[NDIMS], time_id, tl_id;
      size_t time_count[NDIMS], time_index[NDIMS] = {0, 0};
      const char ttext[TEXT_LEN + 1]="20051224.150000";
      char ttext_in[TEXT_LEN + 1];
      int nvars, ndims, ngatts, unlimdimid;
      int ndims_in, natts_in, dimids_in[NDIMS];
      char var_name_in[NC_MAX_NAME + 1], dim_name_in[NC_MAX_NAME + 1];
      size_t len_in;
      nc_type xtype_in;

      /* Create a netcdf-4 file with 2D coordinate var. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, D1_NAME, TEXT_LEN, &time_dimids[1])) ERR;
      if (nc_def_dim(ncid, D0_NAME, NC_UNLIMITED, &time_dimids[0])) ERR;
      if (nc_def_var(ncid, D0_NAME, NC_CHAR, NDIMS, time_dimids, &time_id)) ERR;
      if (nc_def_var(ncid, D1_NAME, NC_CHAR, 1, &time_dimids[0], &tl_id)) ERR;

      /* Write one time to the coordinate variable. */
      time_count[0] = 1;
      time_count[1] = TEXT_LEN;
      if (nc_put_vara_text(ncid, time_id, time_index, time_count, ttext)) ERR;

      /* Check the data. */
      if (nc_get_vara_text(ncid, time_id, time_index, time_count, ttext_in)) ERR;
      if (strncmp(ttext, ttext_in, TEXT_LEN)) ERR;

      /* Close up. */
      if (nc_close(ncid)) ERR;

      /* Open the file and check. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != NUM_VARS || ndims != NDIMS || ngatts != 0 || unlimdimid != 1) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != NUM_VARS || varids_in[0] != 0 || varids_in[1] != 1) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, D0_NAME) || xtype_in != NC_CHAR || ndims_in != NDIMS ||
	dimids_in[0] != 1 || dimids_in[1] != 0 || natts_in != 0) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != NDIMS || dimids_in[0] != 0 || dimids_in[1] != 1) ERR;
      if (nc_inq_dim(ncid, 0, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, D1_NAME) || len_in != TEXT_LEN) ERR;
      if (nc_inq_dim(ncid, 1, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, D0_NAME) || len_in != 1) ERR;

      /* Check the data. */
      if (nc_get_vara_text(ncid, time_id, time_index, time_count, ttext_in)) ERR;
      if (strncmp(ttext, ttext_in, TEXT_LEN)) ERR;

      /* Close up. */
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #13
0
  Teuchos::RCP<Epetra_MultiVector> NetCDFFileIOHandler::Read( const std::vector<std::string>& filenames )
  {
#ifdef EPETRA_MPI
    Epetra_MpiComm comm( MPI_COMM_WORLD );
#else
    Epetra_SerialComm comm;
#endif

    int ncid=0, row_id=0, col_id=0, ss_id=0, num_nod_var_id=0;
    int i, j, k, col_ptr=0;
    int rows=0, num_ss=0, num_vars=0, status=0;
    size_t rows_t=0, num_nod_var_t=0, start2[2],count2[2];
    //
    // Check to see if we have to create a scaling index vector
    //
    bool createSSIdx = false;
    std::vector< std::pair<int,int> > scaling_idx;
    std::pair<int, int> idx_pair;
    /*
    try {
      scaling_idx = Teuchos::getParameter< std::vector< std::pair<int,int> > >( *params_, "Snapshot Scaling Indices" );
    }
    catch (std::exception &e) {
      createSSIdx = true;
    }    
    */
    //
    // Open all the files and check that the snapshots have the same dimensions.
    //
    if ( comm.MyPID() == 0 ) {	
      size_t rows0=0, cols0=0, cols_t=0, total_rows=0;

      std::string temp_filename = in_path + filenames[0];
      status = nc_open(temp_filename.c_str(),NC_NOWRITE,&ncid);
      if (status != NC_NOERR) handle_error(status);
      //
      // If the scaling index vector is needed we can create it here.
      //	
      if (createSSIdx) {
	idx_pair.first = total_rows;
      }
      //
      // Get information on the number of snapshots in the file.
      status = nc_inq_dimid(ncid,"row",&row_id);
      if (status != NC_NOERR) handle_error(status); 
      status = nc_inq_dimlen(ncid,row_id, &rows0);
      if (status != NC_NOERR) handle_error(status);
      total_rows += rows0;
      //
      // Get information on the snapshot length.
      status = nc_inq_dimid(ncid,"col",&col_id);
      if (status != NC_NOERR) handle_error(status);
      status = nc_inq_dimlen(ncid,col_id, &cols0);
      if (status != NC_NOERR) handle_error(status);
      //
      if (!isInit) {
	int len_string_id, num_nodes_id, name_nod_var_id;
	size_t len_string_t, num_nodes_t;

	// Get maximum variable name length.
	status=nc_inq_dimid(ncid,"len_string",&len_string_id);
	if (status != NC_NOERR) handle_error(status);
	status=nc_inq_dimlen(ncid,len_string_id,&len_string_t);
	if (status != NC_NOERR) handle_error(status);
	
	// Get number of nodes.
	status=nc_inq_dimid(ncid,"num_nodes",&num_nodes_id);
	if (status != NC_NOERR) handle_error(status);
	status=nc_inq_dimlen(ncid,num_nodes_id, &num_nodes_t);
	if (status != NC_NOERR) handle_error(status);
	
	// Get number of nodal variables.
	status=nc_inq_dimid(ncid,"num_nod_var",&num_nod_var_id);
	if (status != NC_NOERR) handle_error(status);
	status=nc_inq_dimlen(ncid,num_nod_var_id,&num_nod_var_t);
	if (status != NC_NOERR) handle_error(status);
	
	len_string = len_string_t;
	num_nodes = num_nodes_t;
	num_nod_var = num_nod_var_t;
	
	// Read in names of nodal variables.
	status=nc_inq_varid(ncid,"name_nod_var",&name_nod_var_id);
	if (status != NC_NOERR) handle_error(status);
	
	var_name = new char*[ num_nod_var ];
	for (i=0; i<num_nod_var; ++i)
	  var_name[i] =  new char[ len_string ];
	
	for (i=0; i<num_nod_var; ++i) {
	  start2[0]=i;
	  start2[1]=0;
	  count2[0]=1;
	  count2[1]=len_string;
	  
	  status=nc_get_vara_text(ncid,name_nod_var_id,start2,count2,var_name[i]);
	  if (status != NC_NOERR) handle_error(status);
	}	
	//
	// If the scaling index vector is needed we can set the endpoint here.
	//
	if (createSSIdx) {
	  idx_pair.second = total_rows-1;
	  scaling_idx.push_back( idx_pair );
	}

	// Now we are initialized!
	isInit = true;
	
	// Output information.
	std::cout<<"len_string = "<<len_string<<std::endl;
	std::cout<<"num_nodes = "<<num_nodes<<std::endl;
	std::cout<<"num_nod_var = "<<num_nod_var<<std::endl;
	std::cout<<"var_name = ";
	for (i=0; i< num_nod_var; ++i)
	  std::cout<<var_name[i]<<" ";
	std::cout<<std::endl;
      }
      
      // Close first file.
      status = nc_close(ncid);
      if (status != NC_NOERR) handle_error(status);
      //
      for (i=1; i<(int)filenames.size(); i++) {
        std::string temp_filename = in_path + filenames[i];
	status = nc_open(temp_filename.c_str(),NC_NOWRITE,&ncid);
	if (status != NC_NOERR) handle_error(status);
	//
	// If the scaling index vector is needed we can create it here.
	//
	if (createSSIdx) {
	  idx_pair.first = total_rows;
	}
	//
	// Get information on the number of snapshots in the file.
	status = nc_inq_dimid(ncid,"row",&row_id);
	if (status != NC_NOERR) handle_error(status); 
	status = nc_inq_dimlen(ncid,row_id, &rows_t);
	if (status != NC_NOERR) handle_error(status);
	//
	// Get information on the snapshot length.
	status = nc_inq_dimid(ncid,"col",&col_id);
	if (status != NC_NOERR) handle_error(status);
	status = nc_inq_dimlen(ncid,col_id, &cols_t);
	if (status != NC_NOERR) handle_error(status);
	//
	// Get number of nodal variables.
	status=nc_inq_dimid(ncid,"num_nod_var",&num_nod_var_id);
	if (status != NC_NOERR) handle_error(status);
	status=nc_inq_dimlen(ncid,num_nod_var_id,&num_nod_var_t);
	if (status != NC_NOERR) handle_error(status);
	//
	//
        TEUCHOS_TEST_FOR_EXCEPTION(cols_t != cols0 || (int)num_nod_var_t != num_nod_var, std::runtime_error, "Data set in file "+temp_filename+" is of inconsistent size!");
	total_rows += rows_t;
	//
	// If the scaling index vector is needed we can set the endpoint here.
	//
	if (createSSIdx) {
	  idx_pair.second = total_rows-1;
	  scaling_idx.push_back( idx_pair );
	}
	// Close the file.
	status = nc_close(ncid);
	if (status != NC_NOERR) handle_error(status);
      }

      // Convert from size_t to int.
      num_ss = total_rows;
      num_vars = cols0;

      std::cout<<"Number of snapshots: "<< num_ss << std::endl;
      std::cout<<"Length of snapshot : "<< num_vars << std::endl;
    }
    // Broadcast information about size of snapshot matrix.
    comm.Broadcast( &num_ss, 1, 0 );
    comm.Broadcast( &num_vars, 1, 0 );
    //
    // Sync all other processors on the scaling index vector if necessary
    // 
    if (createSSIdx) {
      for (i=0; i<(int)filenames.size(); i++) {
	if ( comm.MyPID() != 0 )
	  scaling_idx.push_back( idx_pair );
	comm.Broadcast( &scaling_idx[i].first, 1, 0 );
	comm.Broadcast( &scaling_idx[i].second, 1, 0 );
      }
      // Set the scaling index vector
      //params_->set("Snapshot Scaling Indices", scaling_idx);   
    }
    //
    // Create maps for new Epetra_MultiVector to hold the snapshots and 
    // temporary Epetra_Vector used by processor 0 to import the information.
    //
    Epetra_Map Map( num_vars, 0, comm );
    Teuchos::RCP<Epetra_MultiVector> newMV = Teuchos::rcp( new Epetra_MultiVector( Map, num_ss ) );
    Epetra_Vector *col_newMV = 0;
    Epetra_Map *Proc0Map = 0;
    int *index = 0;
    float *temp_vec_f = 0;
    double *temp_vec_d = 0;
    //
    if ( comm.MyPID() == 0 ) {
      Proc0Map = new Epetra_Map( num_vars, num_vars, 0, comm );
      temp_vec_f = new float [ num_vars ];
      temp_vec_d = new double [ num_vars ];
      index = new int[ num_vars ];
      for ( i=0; i<num_vars; i++ ) { index[i] = i; }
    } else {
      Proc0Map = new Epetra_Map( num_vars, 0, 0, comm );
    }
    //
    // Create an importer to get this information into the global Epetra_MultiVector
    //
    Epetra_Import importer( Map, *Proc0Map );
    //
    // Processor 0 reads each file and then creates a local Epetra_Vector, which will be
    // imported into the i-th column of the Epetra_MultiVector.
    //
    // Read starting with row "start2[0]" for "count2[0]" rows, as the columns vary from
    // "start2[1]" to "count2[1]", i.e. specifically for this case, read starting with row i 
    // for 1 row, as the columns vary from first column to the last column
    //
    start2[1]=0;
    count2[0]=1;
    count2[1]=num_vars;
    col_ptr = 0;
    //
    for (i=0; i<(int)filenames.size(); i++) {

      if ( comm.MyPID() == 0 ) {
	// Open the next snapshot file;
        std::string temp_filename = in_path + filenames[i];
	status = nc_open(temp_filename.c_str(),NC_NOWRITE,&ncid);
	if (status != NC_NOERR) handle_error(status);
	//
	// Get information on the number of snapshots in the file.
	status = nc_inq_dimid(ncid,"row",&row_id);
	if (status != NC_NOERR) handle_error(status); 
	status = nc_inq_dimlen(ncid,row_id, &rows_t);
	
	if (status != NC_NOERR) handle_error(status);
	// Get the pointer for the snapshot matrix
	status = nc_inq_varid(ncid,"snapshot",&ss_id);
	if (status != NC_NOERR) handle_error(status); 
	//
	// Convert from size_t to int.
	rows = rows_t;
      }
      comm.Broadcast( &rows, 1, 0 );
      
      for (j=0; j<rows; j++) {
	//
	// Get column of Epetra_MultiVector in terms of Epetra_Vector.
	//
	col_newMV = (*newMV)( col_ptr );
	//
	// Let Processor 0 fill in the Epetra_Vector.
	//
	if ( comm.MyPID() == 0 ) {
	  //
	  // Read in next snapshot, set pointer to next row containing snapshot in NetCDF file.
	  //
	  start2[0]=j;
	  status=nc_get_vara_float(ncid,ss_id,start2,count2,temp_vec_f);
	  for (k=0; k<num_vars; k++) {
	    temp_vec_d[k] = temp_vec_f[k];
	  }
	}
	//
	// Create the Proc0Vector with values from temp_vec_d
	//
	Epetra_Vector Proc0Vector( View, *Proc0Map, temp_vec_d );
	//
	// Import the information.
	//
	col_newMV->Import(Proc0Vector, importer, Add);
	//
	// Increment the counter.
	//
	col_ptr++;
      }
      //
      // Close this snapshot file.
      if ( comm.MyPID() == 0 ) {
	status = nc_close(ncid);
	if (status != NC_NOERR) handle_error(status);
      }
    }
    //
    // Clean up
    delete Proc0Map;
    if ( index ) delete [] index;
    if ( temp_vec_f ) delete [] temp_vec_f;
    if ( temp_vec_d ) delete [] temp_vec_d;
    
    // Return.
    return newMV;
  }
コード例 #14
0
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);
}
コード例 #15
0
ファイル: exgvan.c プロジェクト: CPFDSoftware-Tony/gmv
int ex_get_var_names (int   exoid,
                      const char *var_type,
                      int   num_vars,
                      char *var_names[])
{
  int i, varid, status;
  char errmsg[MAX_ERR_LENGTH];
  int vartyp;
  const char* tname;
  const char* vvarname;

  exerrval = 0; /* clear error code */

  vartyp = tolower( *var_type );

  switch (vartyp) {
  case 'g':
    tname = "global";
    vvarname = VAR_NAME_GLO_VAR;
    break;
  case 'n':
    tname = "nodal";
    vvarname = VAR_NAME_NOD_VAR;
    break;
  case 'l':
    tname = "edge block";
    vvarname = VAR_NAME_EDG_VAR;
    break;
  case 'f':
    tname = "face block";
    vvarname = VAR_NAME_FAC_VAR;
    break;
  case 'e':
    tname = "element block";
    vvarname = VAR_NAME_ELE_VAR;
    break;
  case 'm':
    tname = "node set";
    vvarname = VAR_NAME_NSET_VAR;
    break;
  case 'd':
    tname = "edge set";
    vvarname = VAR_NAME_ESET_VAR;
    break;
  case 'a':
    tname = "face set";
    vvarname = VAR_NAME_FSET_VAR;
    break;
  case 's':
    tname = "side set";
    vvarname = VAR_NAME_SSET_VAR;
    break;
  case 't':
    tname = "element set";
    vvarname = VAR_NAME_ELSET_VAR;
    break;
  default:
    exerrval = EX_BADPARAM;
    sprintf(errmsg,
      "Warning: invalid variable type %c requested from file id %d",
      *var_type, exoid);
    ex_err("ex_get_var_param",errmsg,exerrval);
    return (EX_WARN);
  }

  /* inquire previously defined variables  */
  if ((varid = ncvarid (exoid, vvarname)) == -1) {
    exerrval = ncerr;
    sprintf(errmsg, "Warning: no %s variables names stored in file id %d", tname,exoid);
    ex_err("ex_get_var_names",errmsg,exerrval);
    return (EX_WARN);
  }

  /* read the variable names */

  /*
   * See if reading into contiguous memory in which case we can load 
   * all values in one call.  If not, we must load each name individually.
   */
  if (&var_names[num_vars-1][0] - &var_names[0][0] ==
      sizeof(char)*(MAX_STR_LENGTH+1)*(num_vars-1)) {
    status = nc_get_var_text(exoid, varid, &var_names[0][0]);
    if (status == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get results variable names from file id %d", exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_FATAL);
    }
  } else {
    for (i=0; i<num_vars; i++) {
      size_t start[2];
      size_t count[2];
      start[0] = i;  count[0] = 1;
      start[1] = 0;  count[1] = MAX_STR_LENGTH+1;
      status = nc_get_vara_text(exoid, varid, start, count, var_names[i]);
      if (status == -1) {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get results variable names from file id %d", exoid);
        ex_err("ex_get_var_names",errmsg,exerrval);
        return (EX_FATAL);
      }
    }
  }
  return (EX_NOERR);
}
コード例 #16
0
int
main(int argc, char **argv)
{
   printf("\n*** Testing netcdf-4 file functions.\n");
   {
      char str[NC_MAX_NAME+1];
      
      /* Actually we never make any promises about the length of the
       * version string, but it is always smaller than NC_MAX_NAME. */
      if (strlen(nc_inq_libvers()) > NC_MAX_NAME) ERR;
      strcpy(str, nc_inq_libvers());
      printf("*** testing version %s...", str);
   }
   SUMMARIZE_ERR;
   printf("*** testing with bad inputs...");
   {
      int ncid;

      /* Make sure bad create mode causes failure. */
      /*if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;*/
      
      /* Create an empty file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_close(ncid)) ERR;

      if (nc_open(FILE_NAME, NC_MPIIO|NC_MPIPOSIX, &ncid) != NC_EINVAL) ERR;

      if (nc_create(FILE_NAME, NC_64BIT_OFFSET|NC_NETCDF4, &ncid) != NC_EINVAL) ERR;
      if (nc_create(FILE_NAME, NC_CLASSIC_MODEL|NC_MPIIO|NC_MPIPOSIX, &ncid) != NC_EINVAL) ERR;
      if (nc_create(FILE_NAME, NC_MPIIO|NC_MPIPOSIX, &ncid) != NC_EINVAL) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing simple opens and creates...");
   {
      int ncid, ncid2, ncid3, varid, dimids[2];
      int ndims, nvars, natts, unlimdimid;
      int dimids_var[1], var_type;
      size_t dim_len;
      char dim_name[NC_MAX_NAME+1], var_name[NC_MAX_NAME+1];
      unsigned char uchar_out[DIM1_LEN] = {0, 128, 255};

      /* Open and close empty file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Recreate it again. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_def_dim(ncid, DIM2_NAME, DIM2_LEN, &dimids[1])) ERR;
      if (nc_def_var(ncid, VAR1_NAME, NC_INT, 1, dimids, &varid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_def_var(ncid, VAR2_NAME, NC_UINT, 2, dimids, &varid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Check the contents. Then define a new variable. Since it's
       * netcdf-4, nc_enddef isn't required - it's called
       * automatically. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 2 || nvars != 2 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_redef(ncid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_def_var(ncid, VAR3_NAME, NC_INT, 2, dimids, &varid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Open three copies of the same file. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_open(FILE_NAME, NC_WRITE, &ncid2)) ERR;
      if (nc_open(FILE_NAME, NC_WRITE, &ncid3)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 2 || nvars != 3 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq(ncid2, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 2 || nvars != 3 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq(ncid3, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 2 || nvars != 3 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_close(ncid)) ERR;
      if (nc_close(ncid2)) ERR;
      if (nc_close(ncid3)) ERR;
      
      /* Open and close empty file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Check the contents. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 0 || nvars != 0 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_close(ncid)) ERR;

      /* Create a file with one dimension and nothing else. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Check the contents. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 1 || nvars != 0 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_dim(ncid, 0, dim_name, &dim_len)) ERR;
      if (dim_len != DIM1_LEN || strcmp(dim_name, DIM1_NAME)) ERR;
      if (nc_close(ncid)) ERR;

      /* Create a simple file, and write some data to it. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_def_var(ncid, VAR1_NAME, NC_BYTE, 1, dimids, &varid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_put_var_uchar(ncid, varid, uchar_out) != NC_ERANGE) ERR;
      if (nc_close(ncid)) ERR;

      /* Check the contents. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 1 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_dim(ncid, 0, dim_name, &dim_len)) ERR;
      if (dim_len != DIM1_LEN || strcmp(dim_name, DIM1_NAME)) ERR;
      if (nc_inq_var(ncid, 0, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
      if (ndims != 1 || strcmp(var_name, VAR1_NAME) || var_type != NC_BYTE ||
	  dimids_var[0] != dimids[0] || natts != 0) ERR;
      if (nc_close(ncid)) ERR;

      /* Recreate the file. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_def_var(ncid, VAR1_NAME, NC_BYTE, 1, dimids, &varid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_put_var_uchar(ncid, varid, uchar_out)) ERR;
      if (nc_close(ncid)) ERR;

      /* Recreate it, then make sure NOCLOBBER works. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_close(ncid)) ERR;
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_NOCLOBBER, &ncid) != NC_EEXIST) ERR;

      /* Recreate it again. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_def_dim(ncid, DIM2_NAME, DIM2_LEN, &dimids[1])) ERR;
      if (nc_def_var(ncid, VAR1_NAME, NC_INT, 1, dimids, &varid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_def_var(ncid, VAR2_NAME, NC_UINT, 2, dimids, &varid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Check the contents. Then define a new variable. Since it's
       * netcdf-4, nc_enddef isn't required - it's called
       * automatically. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 2 || nvars != 2 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_redef(ncid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_def_var(ncid, VAR3_NAME, NC_INT, 2, dimids, &varid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Recreate it again with netcdf-3 rules turned on. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_def_var(ncid, VAR1_NAME, NC_INT, 1, dimids, &varid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_close(ncid)) ERR;

      /* Check the contents. Check that netcdf-3 rules are in effect. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 1 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_def_var(ncid, VAR2_NAME, NC_UINT, 2, dimids, &varid) != NC_ENOTINDEFINE) ERR;
      if (nc_close(ncid)) ERR;

      /* Check some other stuff about it. Closing and reopening the
       * file forces HDF5 to tell us if we forgot to free some HDF5
       * resource associated with the file. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (nc_inq_dim(ncid, 0, dim_name, &dim_len)) ERR;
      if (dim_len != DIM1_LEN || strcmp(dim_name, DIM1_NAME)) ERR;
      if (nc_inq_var(ncid, 0, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
      if (ndims != 1 || strcmp(var_name, VAR1_NAME) || var_type != NC_INT ||
	  dimids_var[0] != dimids[0] || natts != 0) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing more complex opens and creates...");
   {
      int ncid, varid, dimids[2];
      int ndims, nvars, natts, unlimdimid;
      int dimids_var[2], var_type;
      size_t dim_len;
      char dim_name[NC_MAX_NAME+1], var_name[NC_MAX_NAME+1];
      float float_in, float_out = 99.99;
      int int_in, int_out = -9999;

      /* Create a file, this time with attributes. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLOBBER, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR;
      if (nc_def_dim(ncid, DIM2_NAME, DIM2_LEN, &dimids[1])) ERR;
      if (nc_def_var(ncid, VAR1_NAME, NC_INT, 2, dimids, &varid)) ERR;
      if (nc_def_var(ncid, VAR2_NAME, NC_UINT, 2, dimids, &varid)) ERR;
      if (nc_put_att_float(ncid, NC_GLOBAL, ATT1_NAME, NC_FLOAT, 1, &float_out)) ERR;
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT2_NAME, NC_INT, 1, &int_out)) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen the file and check it. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 2 || nvars != 2 || natts != 2 || unlimdimid != -1) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen it and check each dim, var, and att. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_inq_dim(ncid, 0, dim_name, &dim_len)) ERR;
      if (dim_len != DIM1_LEN || strcmp(dim_name, DIM1_NAME)) ERR;
      if (nc_inq_dim(ncid, 1, dim_name, &dim_len)) ERR;
      if (dim_len != DIM2_LEN || strcmp(dim_name, DIM2_NAME)) ERR;
      if (nc_inq_var(ncid, 0, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
      if (ndims != 2 || strcmp(var_name, VAR1_NAME) || var_type != NC_INT ||
	  dimids_var[0] != dimids[0] || natts != 0) ERR;
      if (nc_inq_var(ncid, 1, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
      if (ndims != 2 || strcmp(var_name, VAR2_NAME) || var_type != NC_UINT ||
	  dimids_var[1] != dimids[1] || natts != 0) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT1_NAME, &float_in)) ERR;
      if (float_in != float_out) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT2_NAME, &int_in)) ERR;
      if (int_in != int_out) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;

   printf("*** testing redef for netCDF classic...");
   test_redef(NC_FORMAT_CLASSIC);
   SUMMARIZE_ERR;
   printf("*** testing redef for netCDF 64-bit offset...");
   test_redef(NC_FORMAT_64BIT);
   SUMMARIZE_ERR;
   printf("*** testing redef for netCDF-4 ...");
   test_redef(NC_FORMAT_NETCDF4);
   SUMMARIZE_ERR;
   printf("*** testing redef for netCDF-4, with strict netCDF-3 rules...");
   test_redef(NC_FORMAT_NETCDF4_CLASSIC);
   SUMMARIZE_ERR;
   printf("*** testing different formats...");
   {
      int ncid;
      int format;

      /* Create a netcdf-3 file. */
      if (nc_create(FILE_NAME, NC_CLOBBER, &ncid)) ERR;
      if (nc_inq_format(ncid, &format)) ERR;
      if (format != NC_FORMAT_CLASSIC) ERR;
      if (nc_close(ncid)) ERR;

      /* Create a netcdf-3 64-bit offset file. */
      if (nc_create(FILE_NAME, NC_64BIT_OFFSET|NC_CLOBBER, &ncid)) ERR;
      if (nc_inq_format(ncid, &format)) ERR;
      if (format != NC_FORMAT_64BIT) ERR;
      if (nc_close(ncid)) ERR;

      /* Create a netcdf-4 file. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLOBBER, &ncid)) ERR;
      if (nc_inq_format(ncid, &format)) ERR;
      if (format != NC_FORMAT_NETCDF4) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing CLASSIC_MODEL flag with classic formats...");
   {
      int ncid;
      int format;

      /* Create a netcdf-3 file. */
      if (nc_create(FILE_NAME, NC_CLOBBER|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_inq_format(ncid, &format)) ERR;
      if (format != NC_FORMAT_CLASSIC) ERR;
      if (nc_close(ncid)) ERR;

      /* Create a netcdf-3 64-bit offset file. */
      if (nc_create(FILE_NAME, NC_64BIT_OFFSET|NC_CLOBBER|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_inq_format(ncid, &format)) ERR;
      if (format != NC_FORMAT_64BIT) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing multiple open files...");
   {
#define VAR_NAME "Captain_Kirk"
#define NDIMS 1
#define NUM_FILES 30
#define TEXT_LEN 15
#define D1_NAME "tl"
      int ncid[NUM_FILES], varid;
      int dimid;
      size_t count[NDIMS], index[NDIMS] = {0};
      const char ttext[TEXT_LEN + 1] = "20051224.150000";
      char ttext_in[TEXT_LEN + 1];
      char file_name[NC_MAX_NAME + 1];
      size_t chunks[NDIMS] = {TEXT_LEN + 1};
      int f;

      /* Create a bunch of files. */
      for (f = 0; f < NUM_FILES; f++)
      {
	 sprintf(file_name, "tst_files2_%d.nc", f);
	 if (nc_create(file_name, NC_NETCDF4, &ncid[f])) ERR;
	 if (nc_def_dim(ncid[f], D1_NAME, TEXT_LEN + 1, &dimid)) ERR;
	 if (nc_def_var(ncid[f], VAR_NAME, NC_CHAR, NDIMS, &dimid, &varid)) ERR;
	 if (f % 2 == 0)
	    if (nc_def_var_chunking(ncid[f], varid, 0, chunks)) ERR;
	 
	 /* Write one time to the coordinate variable. */
	 count[0] = TEXT_LEN + 1;
	 if (nc_put_vara_text(ncid[f], varid, index, count, ttext)) ERR;
      }

      /* Read something from each file. */
      for (f = 0; f < NUM_FILES; f++)
      {
	 if (nc_get_vara_text(ncid[f], varid, index, count, (char *)ttext_in)) ERR;
	 if (strcmp(ttext_in, ttext)) ERR;
      }

      /* Close all open files. */
      for (f = 0; f < NUM_FILES; f++)
	 if (nc_close(ncid[f])) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #17
0
int ex_get_var_names (int   exoid,
                      const char *var_type,
                      int   num_vars,
                      char *var_names[])
{
  int i, varid, status;
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* inquire previously defined variables  */
  if (*var_type == 'g' || *var_type == 'G') {
    if ((varid = ncvarid (exoid, VAR_NAME_GLO_VAR)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Warning: no global variables names stored in file id %d", exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_WARN);
    }
  }

  else if (*var_type == 'n' || *var_type == 'N') {
    if ((varid = ncvarid (exoid, VAR_NAME_NOD_VAR)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Warning: no nodal variable names stored in file id %d",
              exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_WARN);
    }

  }

  else if (*var_type == 'e' || *var_type == 'E') {

    if ((varid = ncvarid (exoid, VAR_NAME_ELE_VAR)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Warning: no element variable names stored in file id %d",
              exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_WARN);
    }
  }

  else if (*var_type == 'm' || *var_type == 'M') {

    if ((varid = ncvarid (exoid, VAR_NAME_NSET_VAR)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Warning: no nodset variable names stored in file id %d",
              exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_WARN);
    }
  }

  else if (*var_type == 's' || *var_type == 'S') {

    if ((varid = ncvarid (exoid, VAR_NAME_SSET_VAR)) == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Warning: no sideset variable names stored in file id %d",
              exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_WARN);
    }
  }

  else       /* invalid variable type */
    {
      exerrval = EX_BADPARAM;
      sprintf(errmsg,
              "Error: Invalid variable type %c specified in file id %d",
              *var_type, exoid);
      ex_err("ex_put_var_names",errmsg,exerrval);
      return (EX_WARN);
    }


  /* read the variable names */

  /*
   * See if reading into contiguous memory in which case we can load 
   * all values in one call.  If not, we must load each name individually.
   */
  if (&var_names[num_vars-1][0] - &var_names[0][0] ==
      sizeof(char)*(MAX_STR_LENGTH+1)*(num_vars-1)) {
    status = nc_get_var_text(exoid, varid, &var_names[0][0]);
    if (status == -1) {
      exerrval = ncerr;
      sprintf(errmsg,
              "Error: failed to get results variable names from file id %d", exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_FATAL);
    }
  } else {
    for (i=0; i<num_vars; i++) {
      size_t start[2];
      size_t count[2];
      start[0] = i;  count[0] = 1;
      start[1] = 0;  count[1] = MAX_STR_LENGTH+1;
      status = nc_get_vara_text(exoid, varid, start, count, var_names[i]);
      if (status == -1) {
        exerrval = ncerr;
        sprintf(errmsg,
                "Error: failed to get results variable names from file id %d", exoid);
        ex_err("ex_get_var_names",errmsg,exerrval);
        return (EX_FATAL);
      }
    }
  }
  return (EX_NOERR);
}
コード例 #18
0
ファイル: tst_fills.c プロジェクト: Federico2014/edg4x-rose
int
main(int argc, char **argv) 
{			/* create tst_classic_fills.nc */
   printf("\n*** Testing fill values.\n");
   printf("*** testing empty fill values of a string var...");
   {
#define STRING_VAR_NAME "The_String"
#define NDIMS_STRING 1
#define FILLVALUE_LEN 1 /* There is 1 string, the empty one. */
#define DATA_START 2 /* Real data here. */

      int  ncid, varid, dimid, varid_in;
      const char *missing_val[FILLVALUE_LEN] = {""};
      const char *missing_val_in[FILLVALUE_LEN];
      const char *data_out[1] = {"The evil that men do lives after them; "
				 "the good is oft interred with their bones."};
      char **data_in;
      size_t index = DATA_START;
      int i;

      /* Create file with a 1D string var. Set its fill value to the
       * empty string. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, "rec", NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_var(ncid, STRING_VAR_NAME, NC_STRING, NDIMS_STRING, &dimid, &varid)) ERR;
      if (nc_put_att_string(ncid, varid, "_FillValue", FILLVALUE_LEN, missing_val)) ERR;

      /* Check it out. */
      if (nc_inq_varid(ncid, STRING_VAR_NAME, &varid_in)) ERR;
      if (nc_get_att_string(ncid, varid_in, "_FillValue", (char **)missing_val_in)) ERR;
      if (strcmp(missing_val[0], missing_val_in[0])) ERR;
      if (nc_free_string(FILLVALUE_LEN, (char **)missing_val_in)) ERR;

      /* Write one string, leaving some blank records which will then
       * get the fill value. */
      if (nc_put_var1_string(ncid, varid_in, &index, data_out)) ERR;

      /* Get all the data from the variable. */
      if (!(data_in = malloc((DATA_START + 1) * sizeof(char *)))) ERR;
      if (nc_get_var_string(ncid, varid_in, data_in)) ERR;

      /* First there should be fill values, then the data value we
       * wrote. */
      for (i = 0; i < DATA_START; i++)
	 if (strcmp(data_in[i], "")) ERR;
      if (strcmp(data_in[DATA_START], data_out[0])) ERR;

      /* Close everything up. */
      if (nc_close(ncid)) ERR;

      /* Now re-open file, read data, and check values again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_varid(ncid, STRING_VAR_NAME, &varid_in)) ERR;
      if (nc_get_att_string(ncid, varid_in, "_FillValue", (char **)missing_val_in)) ERR;
      if (strcmp(missing_val[0], missing_val_in[0])) ERR;
      if (nc_free_string(FILLVALUE_LEN, (char **)missing_val_in)) ERR;
      if (nc_close(ncid)) ERR;
      free(data_in);
   }

   SUMMARIZE_ERR;
   printf("*** testing non-empty fill values of a string var...");
   {
#define STRING_VAR_NAME2 "CASSIUS"
#define FILLVALUE_LEN2 1 /* There is 1 string in the fillvalue array. */
#define DATA_START2 9 /* Real data starts here. */

      int  ncid, varid, dimid, varid_in;
      const char *missing_val[FILLVALUE_LEN2] = {"I know that virtue to be in you, Brutus"};
      const char *missing_val_in[FILLVALUE_LEN2];
      const char *data_out[1] = {"The evil that men do lives after them; "
				 "the good is oft interred with their bones."};
      char **data_in;
      size_t index = DATA_START2;
      int i;

      /* Create file with a 1D string var. Set its fill value to the
       * a non-empty string. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, "rec", NC_UNLIMITED, &dimid)) ERR;
      if (nc_def_var(ncid, STRING_VAR_NAME2, NC_STRING, NDIMS_STRING, &dimid, &varid)) ERR;
      if (nc_put_att_string(ncid, varid, "_FillValue", FILLVALUE_LEN2, missing_val)) ERR;

      /* Check it out. */
      if (nc_inq_varid(ncid, STRING_VAR_NAME2, &varid_in)) ERR;
      if (nc_get_att_string(ncid, varid_in, "_FillValue", (char **)missing_val_in)) ERR;
      if (strcmp(missing_val[0], missing_val_in[0])) ERR;
      if (nc_free_string(FILLVALUE_LEN2, (char **)missing_val_in)) ERR;

      /* Write one string, leaving some blank records which will then
       * get the fill value. */
      if (nc_put_var1_string(ncid, varid_in, &index, data_out)) ERR;

      /* Get all the data from the variable. */
      if (!(data_in = malloc((DATA_START2 + 1) * sizeof(char *)))) ERR;
      if (nc_get_var_string(ncid, varid_in, data_in)) ERR;

      /* First there should be fill values, then the data value we
       * wrote. */
      for (i = 0; i < DATA_START2; i++)
	 if (strcmp(data_in[i], missing_val[0])) ERR;
      if (strcmp(data_in[DATA_START2], data_out[0])) ERR;

      /* Close everything up. */
      if (nc_close(ncid)) ERR;

      /* Now re-open file, read data, and check values again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_varid(ncid, STRING_VAR_NAME2, &varid_in)) ERR;
      if (nc_get_att_string(ncid, varid_in, "_FillValue", (char **)missing_val_in)) ERR;
      if (strcmp(missing_val[0], missing_val_in[0])) ERR;
      if (nc_free_string(FILLVALUE_LEN2, (char **)missing_val_in)) ERR;
      if (nc_close(ncid)) ERR;
      free(data_in);
   }

   SUMMARIZE_ERR;
   printf("*** testing fill values of one var...");
   {
#define V1_NAME "v1"
#define MAX_VALS 10
      int  ncid, varid, rec_id, dims[2];
      static int rec[1] = {1};
      size_t start[2] = {0, 0};
      size_t count[2] = {1, MAX_VALS};
      char vals[MAX_VALS];
      int i;

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

      /* Define dimensions and two vars, a 1D coordinate var for
       * unlimited dimension, and a 2D var which uses the unlimited
       * dimension. */
      if (nc_def_dim(ncid, "rec", NC_UNLIMITED, &dims[0])) ERR;
      if (nc_def_dim(ncid, "len", MAX_VALS, &dims[1])) ERR;
      if (nc_def_var(ncid, "rec", NC_INT, 1, dims, &rec_id)) ERR;
      if (nc_def_var(ncid, V1_NAME, NC_CHAR, 2, dims, &varid)) ERR;

      /* Extend record dimension by 1. */
      if (nc_put_vara_int(ncid, rec_id, start, count, rec)) ERR;

      /* Read the other variable; it must have only fill values. */
      if (nc_get_vara_text(ncid, 1, start, count, vals)) ERR;
      for (i = 0; i < MAX_VALS; i++)
	 if(vals[i] != NC_FILL_CHAR) ERR;

      if (nc_close(ncid)) ERR;

      /* Now re-open file, read data, and check values again. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      /* Read the other variable; it must have only fill values. */
      if (nc_get_vara_text(ncid, 1, start, count, vals)) ERR;
      for (i = 0; i < MAX_VALS; i++)
	 if(vals[i] != NC_FILL_CHAR) ERR;

      if(nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing fill values of lots of vars...");

   {
      int  ncid;			/* netCDF id */

#define NVALS 10		/* values per fixed-size variable or record */
#define NFIXVARS 6		/* number of fixed-size vars, one of each type */
#define NRECVARS 6		/* number of record vars, one of each type */
#define RANK_REC 1
#define RANK_FIXVARS 1
#define RANK_RECVARS 2

      /* dimension ids */
      int rec_dim;
      int len_dim;

      /* dimension lengths */
      size_t rec_len = NC_UNLIMITED;
      size_t len_len = NVALS;

      /* variable ids */
      int rec_id;
      int fixvar_ids[NFIXVARS];
      int recvar_ids[NRECVARS];
      int rec_dims[RANK_REC];
      int fixvar_dims[RANK_FIXVARS];
      int recvar_dims[RANK_RECVARS];
      int fixvar, recvar, i;

      char *fnames[] = {"c", "b", "s", "i", "f", "d"};
      char *rnames[] = {"cr", "br", "sr", "ir", "fr", "dr"};
      nc_type types[] = {NC_CHAR, NC_BYTE, NC_SHORT, NC_INT, NC_FLOAT, NC_DOUBLE};

      /*if (nc_set_default_format(format + 1, NULL)) ERR;*/
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* define dimensions */
      if (nc_def_dim(ncid, "rec", rec_len, &rec_dim)) ERR;
      if (nc_def_dim(ncid, "len", len_len, &len_dim)) ERR;

      rec_dims[0] = rec_dim;
      if (nc_def_var(ncid, "rec", NC_INT, RANK_REC, rec_dims, &rec_id)) ERR;

      /* define fixed and record variables of all 6 primitive types */
      fixvar_dims[0] = len_dim;
      for (fixvar = 0; fixvar < NFIXVARS; fixvar++)
	 if (nc_def_var(ncid, fnames[fixvar], types[fixvar], RANK_FIXVARS,
			fixvar_dims, &fixvar_ids[fixvar])) ERR;

      recvar_dims[0] = rec_dim;
      recvar_dims[1] = len_dim;
      for (recvar = 0; recvar < NRECVARS; recvar++)
	 if (nc_def_var(ncid, rnames[recvar], types[recvar], RANK_RECVARS,
			recvar_dims, &recvar_ids[recvar])) ERR;

      /* leave define mode */
      if (nc_enddef(ncid)) ERR;

      {			/* store rec */
	 static size_t rec_start[RANK_REC];
	 static size_t rec_count[RANK_REC];
	 static int rec[] = {1};
	 rec_len = 1;			/* number of records of rec data */
	 rec_start[0] = 0;
	 rec_count[0] = rec_len;
	 if (nc_put_vara_int(ncid, rec_id, rec_start, rec_count, rec)) ERR;
      }
      if (nc_close(ncid)) ERR;

      /* Now re-open file, read data, and check values */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      /* Check that fixed-size variables are full of fill values */
      for (fixvar = 0; fixvar < NFIXVARS; fixvar++) {
	 int varid;
	 nc_type type;

	 if (nc_inq_varid(ncid, fnames[fixvar], &varid)) ERR;
	 if (nc_inq_vartype(ncid, varid, &type)) ERR;
	 switch(type) {
	    case NC_CHAR:
	    {
	       char vals[NVALS];
	       if (nc_get_var_text(ncid, varid, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_CHAR) ERR;
	    }
	    break;
	    case NC_BYTE:
	    {
	       signed char vals[NVALS];
	       if (nc_get_var_schar(ncid, varid, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_BYTE) ERR;
	    }
	    break;
	    case NC_SHORT:
	    {
	       short vals[NVALS];
	       if (nc_get_var_short(ncid, varid, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_SHORT) ERR;
	    }
	    break;
	    case NC_INT:
	    {
	       int vals[NVALS];
	       if (nc_get_var_int(ncid, varid, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_INT) ERR;
	    }
	    break;
	    case NC_FLOAT:
	    {
	       float vals[NVALS];
	       if (nc_get_var_float(ncid, varid, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_FLOAT) ERR;
	    }
	    break;
	    case NC_DOUBLE:
	    {
	       double vals[NVALS];
	       if (nc_get_var_double(ncid, varid, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if (vals[i] != NC_FILL_DOUBLE) ERR;
	    }
	    break;
	    default:
	       ERR;
	 }
      }

      /* Read record, check record variables have only fill values */
      for (recvar = 0; recvar < NRECVARS; recvar++) {
	 int varid;
	 nc_type type;
	 size_t start[] = {0, 0};
	 size_t count[] = {1, NVALS};

	 if (nc_inq_varid(ncid, rnames[recvar], &varid)) ERR;
	 if (nc_inq_vartype(ncid, varid, &type)) ERR;
	 switch(type) {
	    case NC_CHAR:
	    {
	       char vals[NVALS];
	       if (nc_get_vara_text(ncid, varid, start, count, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_CHAR) ERR;
	    }
	    break;
	    case NC_BYTE:
	    {
	       signed char vals[NVALS];
	       if (nc_get_vara_schar(ncid, varid, start, count, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_BYTE) ERR;
	    }
	    break;
	    case NC_SHORT:
	    {
	       short vals[NVALS];
	       if (nc_get_vara_short(ncid, varid, start, count, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_SHORT) ERR;
	    }
	    break;
	    case NC_INT:
	    {
	       int vals[NVALS];
	       if (nc_get_vara_int(ncid, varid, start, count, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_INT) ERR;
	    }
	    break;
	    case NC_FLOAT:
	    {
	       float vals[NVALS];
	       if (nc_get_vara_float(ncid, varid, start, count, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_FLOAT) ERR;
	    }
	    break;
	    case NC_DOUBLE:
	    {
	       double vals[NVALS];
	       if (nc_get_vara_double(ncid, varid, start, count, vals)) ERR;
	       for (i = 0; i < NVALS; i++)
		  if(vals[i] != NC_FILL_DOUBLE) ERR;
	    }
	    break;
	    default:
	       ERR;
	 }
      }

      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;

   return 0;
}
コード例 #19
0
sta_struct *decode_fsl2(int cdfid, long miss, int *iret)
{
int ndims,nvars,natts,nunlim;
int tmpint[20];
int ier,i,j,unlimsiz;
int wmoStaNum_id,wmoStaNum,staName_id;
char staName[20];
int staLat_id,staLon_id,staElev_id,timeObs_id,levels_id;
int uwnd_id,vwnd_id,wwnd_id,uv_qual_id,w_qual_id,levelMode_id;
int sigma_uv_id,sigma_w_id;
int sfc_sped_id,sfc_drct_id,sfc_pres_id,sfc_temp_id,sfc_relh_id,sfc_rain_id;
float staLat,staLon,staElev,level;
float uwnd,vwnd,wwnd,sigma_uv,sigma_w;
int uv_qual,w_qual,levelMode;
float sfc_sped,sfc_drct,sfc_pres,sfc_temp,sfc_relh,sfc_rain;
double timeObs;
nc_type xtype;
int nvdims,nvatts,time_interval;
size_t dimsiz,var_i[5],vc[5],namelen;
float ufill,vfill,wfill;
float pfill,tfill,dfill,sfill,rfill,rrfill;
float fmiss,e;

time_t obs_time;
char timestr[80],*atttext;
int year,month,day,hour,minute;
struct tm *gmt_time=NULL,new_time;
sta_struct *stadat,*head=NULL;
prof_data *plev,*plast;


udebug("decoding fsl2\0");
fmiss = (float)miss;

ier = nc_inq(cdfid,&ndims,&nvars,&natts,&nunlim);

ier = nc_inq_atttype(cdfid,NC_GLOBAL,"avgTimePeriod",&xtype);
if(xtype == NC_CHAR)
   {
   ier = nc_inq_attlen(cdfid,NC_GLOBAL,"avgTimePeriod",&namelen);
   udebug("AvgTimPeriod name len is %d",namelen);
   atttext = (char *)malloc(namelen + 1);
   ier = nc_get_att_text(cdfid,NC_GLOBAL,"avgTimePeriod",atttext);
   sscanf(atttext,"%d",tmpint);
   udebug("AvgTimPeriod type is NC_CHAR %s VAL %d",atttext,tmpint[0]);
   free(atttext);
   }
else
   {
   ier = nc_get_att_int(cdfid,NC_GLOBAL,"avgTimePeriod",tmpint);
   }
udebug("AvgTimPeriod is %d\0",tmpint[0]);
time_interval = tmpint[0];

ier = 0;
ier += nc_inq_varid(cdfid,"wmoStaNum",&wmoStaNum_id);
ier += nc_inq_varid(cdfid,"staName",&staName_id);
ier += nc_inq_varid(cdfid,"staLat",&staLat_id);
ier += nc_inq_varid(cdfid,"staLon",&staLon_id);
ier += nc_inq_varid(cdfid,"staElev",&staElev_id);
ier += nc_inq_varid(cdfid,"timeObs",&timeObs_id);
ier += nc_inq_varid(cdfid,"levels",&levels_id);
ier += nc_inq_varid(cdfid,"uComponent",&uwnd_id);
ier += nc_inq_varid(cdfid,"vComponent",&vwnd_id);
ier += nc_inq_varid(cdfid,"wComponent",&wwnd_id);
ier += nc_get_att_float(cdfid,uwnd_id,"_FillValue",&ufill);
ier += nc_get_att_float(cdfid,vwnd_id,"_FillValue",&vfill);
ier += nc_get_att_float(cdfid,wwnd_id,"_FillValue",&wfill);

ier += nc_inq_varid(cdfid,"uvQualityCode",&uv_qual_id);
ier += nc_inq_varid(cdfid,"wQualityCode",&w_qual_id);
ier += nc_inq_varid(cdfid,"windSpeedStdDev",&sigma_uv_id);
ier += nc_inq_varid(cdfid,"wStdDev",&sigma_w_id);
ier += nc_inq_varid(cdfid,"levelMode",&levelMode_id);

ier += nc_inq_varid(cdfid,"windSpeedSfc",&sfc_sped_id);
ier += nc_inq_varid(cdfid,"windDirSfc",&sfc_drct_id);
ier += nc_inq_varid(cdfid,"pressure",&sfc_pres_id);
ier += nc_inq_varid(cdfid,"temperature",&sfc_temp_id);
ier += nc_inq_varid(cdfid,"relHumidity",&sfc_relh_id);
ier += nc_inq_varid(cdfid,"rainRate",&sfc_rain_id);
ier += nc_get_att_float(cdfid,sfc_sped_id,"_FillValue",&sfill);
ier += nc_get_att_float(cdfid,sfc_drct_id,"_FillValue",&dfill);
ier += nc_get_att_float(cdfid,sfc_pres_id,"_FillValue",&pfill);
ier += nc_get_att_float(cdfid,sfc_temp_id,"_FillValue",&tfill);
ier += nc_get_att_float(cdfid,sfc_relh_id,"_FillValue",&rfill);
ier += nc_get_att_float(cdfid,sfc_rain_id,"_FillValue",&rrfill);

if(ier != 0)
   {
   uerror("could not get station information\0");
   *iret = -1;
   return(NULL);
   }

ier = nc_inq_vardimid(cdfid,staName_id,tmpint);
ier += nc_inq_dimlen(cdfid,tmpint[1],&namelen);

tmpint[0] = 0;tmpint[1] = 0;
ier += nc_inq_var(cdfid,wmoStaNum_id,NULL, &xtype, &nvdims, tmpint, &nvatts);
ier += nc_inq_dimlen(cdfid,tmpint[0],&dimsiz);
if(ier == 0)
   unlimsiz = dimsiz;
   for(i=0;i<unlimsiz;i++)
      {
      var_i[0] = i; var_i[1] = 0; vc[0] = 1; vc[1] = namelen-1;
      memset(staName,'\0',20);
      ier = nc_get_vara_text(cdfid,staName_id,var_i,vc,staName);
      ier = nc_get_var1_int(cdfid,wmoStaNum_id,var_i,&wmoStaNum);
      ier = nc_get_var1_float(cdfid,staLat_id,var_i,&staLat);
      ier = nc_get_var1_float(cdfid,staLon_id,var_i,&staLon);
      ier = nc_get_var1_float(cdfid,staElev_id,var_i,&staElev);
      ier = nc_get_var1_float(cdfid,sfc_sped_id,var_i,&sfc_sped);
      ier = nc_get_var1_float(cdfid,sfc_drct_id,var_i,&sfc_drct);
      ier = nc_get_var1_float(cdfid,sfc_pres_id,var_i,&sfc_pres);
      ier = nc_get_var1_float(cdfid,sfc_temp_id,var_i,&sfc_temp);
      ier = nc_get_var1_float(cdfid,sfc_relh_id,var_i,&sfc_relh);
      ier = nc_get_var1_float(cdfid,sfc_rain_id,var_i,&sfc_rain);
      ier = nc_get_var1_double(cdfid,timeObs_id,var_i,&timeObs);
      obs_time = (time_t) timeObs;
      gmt_time = gmtime(&obs_time);
      new_time = *gmt_time;
      timestr[0] = '\0';
      strftime(timestr,80,"%Y %m %d %H %M",&new_time);
      sscanf(timestr,"%d %d %d %d %d",&year,&month,&day,&hour,&minute);
      udebug("Station %3d %8d %s = %6.2f %7.2f %5.0f %s\0",i,wmoStaNum,
         staName,staLat,staLon,staElev,timestr);

      stadat = (sta_struct *)malloc(sizeof(sta_struct));
      if(stadat == NULL)
         {
         uerror("Could not allocate station data structure\0");
         exit(-2);
         }
      stadat->wmoStaNum = wmoStaNum;
      stadat->staName = (char *)malloc(strlen(staName)+1);
      strcpy(stadat->staName,staName);
      stadat->staLat = staLat;      
      stadat->staLon = staLon;      
      stadat->staElev = staElev;      
      stadat->timeObs = timeObs;      
      stadat->year = year;
      stadat->month = month;
      stadat->day = day;
      stadat->hour = hour;
      stadat->minute = minute;
      stadat->time_interval = time_interval;
      stadat->pdata = NULL;
      stadat->rdata = NULL;
      stadat->sfc_pres = fmiss;
      stadat->sfc_temp = fmiss;
      stadat->sfc_sped = fmiss;
      stadat->sfc_drct = fmiss;
      stadat->sfc_relh = fmiss;
      stadat->sfc_rain_rate = fmiss;
      stadat->sfc_rain_amt = fmiss;
      stadat->sfc_dwpc = fmiss;
      if(sfc_pres != pfill) stadat->sfc_pres = sfc_pres;
      if(sfc_temp != tfill) stadat->sfc_temp = sfc_temp - 273.15;
      if(sfc_sped != sfill) stadat->sfc_sped = sfc_sped;
      if(sfc_drct != dfill) stadat->sfc_drct = sfc_drct;
      if(sfc_relh != rfill) stadat->sfc_relh = sfc_relh;
      if(sfc_rain != rrfill) stadat->sfc_rain_rate = sfc_rain;
      if((stadat->sfc_temp != fmiss)&&(stadat->sfc_relh != fmiss))
         {
         VAPOR_PRES(stadat->sfc_temp+273.15,&e);
         e = e * (stadat->sfc_relh / 100.);
         t_from_e(e,&stadat->sfc_dwpc);
         stadat->sfc_dwpc = stadat->sfc_dwpc - 273.15;
         }

      ier = nc_inq_var(cdfid,levels_id,NULL, &xtype, &nvdims, tmpint, &nvatts);
      if(ier == 0)
         {
         ier = nc_inq_dimlen(cdfid,tmpint[0],&dimsiz);
         stadat->numlevs = dimsiz;
         plast = stadat->pdata;
         for(j=0;j<stadat->numlevs;j++)
            {
            var_i[0] = j;
            ier = nc_get_var1_float(cdfid,levels_id,var_i,&level);
            ier = nc_get_var1_int(cdfid,levelMode_id,var_i,&levelMode);
            var_i[0] = i;
            var_i[1] = j;
            ier = nc_get_var1_float(cdfid,uwnd_id,var_i,&uwnd);
            ier = nc_get_var1_float(cdfid,vwnd_id,var_i,&vwnd);
            ier = nc_get_var1_float(cdfid,wwnd_id,var_i,&wwnd);
            ier = nc_get_var1_int(cdfid,uv_qual_id,var_i,&uv_qual);
            ier = nc_get_var1_int(cdfid,w_qual_id,var_i,&w_qual);
            ier = nc_get_var1_float(cdfid,sigma_uv_id,var_i,&sigma_uv);
            ier = nc_get_var1_float(cdfid,sigma_w_id,var_i,&sigma_w);
            plev = (prof_data *)malloc(sizeof(prof_data));
            if(plev != NULL)
               {
               plev->level = level;
               if(uwnd == ufill) uwnd = fmiss;
               if(vwnd == vfill) vwnd = fmiss;
               if(wwnd == wfill) wwnd = fmiss;
               if(uv_qual != 0) 
                  {
                  uwnd = fmiss;
                  vwnd = fmiss;
                  }
               if(w_qual != 0) wwnd = fmiss;
               if((uwnd == fmiss)||(vwnd == fmiss))
                  sigma_uv = fmiss;
               if(wwnd == fmiss) sigma_w = fmiss;
               plev->u = uwnd; plev->v = vwnd; plev->w = wwnd;
               plev->sigma_uv = sigma_uv;
               plev->sigma_w = sigma_w;
               plev->levmode = levelMode;
               plev->nextlev = NULL;
               if(plast == NULL)
                  stadat->pdata = plev;
               else
                  plast->nextlev = plev;
               plast = plev;
               }
            }
         }
      else
         stadat->numlevs = 0;

      stadat->next = head;
      head = stadat;
      }

return(head);

} 
コード例 #20
0
ファイル: NetCDFTraj.cpp プロジェクト: kulhanek/asl
bool CNetCDFTraj::ReadHeader(CAmberTopology* p_top)
{
    if( p_top == NULL ){
        INVALID_ARGUMENT("p_top == NULL");
    }

    if( NCID < 0 ) {
        ES_ERROR("file is not opened");
        return(false);
    }

    HasBox = p_top->BoxInfo.GetType() != AMBER_BOX_NONE;
    NumOfTopologyAtoms = p_top->AtomList.GetNumberOfAtoms();

    bool result = true;

    result &= GetVariableAttribute(NC_GLOBAL,"title",Title);
    result &= GetVariableAttribute(NC_GLOBAL,"application",Application);
    result &= GetVariableAttribute(NC_GLOBAL,"program",Program);
    result &= GetVariableAttribute(NC_GLOBAL,"programVersion",Version);
    result &= GetVariableAttribute(NC_GLOBAL,"Conventions",Conventions);
    result &= GetVariableAttribute(NC_GLOBAL,"ConventionVersion",ConventionVersion);

    if( Conventions != "AMBER" ) {
        CSmallString error;
        error << "illegal conventions '" << Conventions << "', expecting 'AMBER'";
        ES_ERROR(error);
        return(false);
    }
    if( ConventionVersion != "1.0" ) {
        CSmallString error;
        error << "illegal convention version '" << ConventionVersion << "', expecting '1.0'";
        ES_ERROR(error);
        return(false);
    }

    GetDimensionInfo("frame", &TotalSnapshots);
    GetDimensionInfo("spatial", &Spatial);
    GetDimensionInfo("atom", &ActualAtoms);

    if( Spatial != 3 ) {
        CSmallString error;
        error << "three dim expected but '" << Spatial << "' provided";
        ES_ERROR(error);
        return(false);
    }

    if( ActualAtoms != NumOfTopologyAtoms ) {
        CSmallString error;
        error << "number of atoms in the topology '" << ActualAtoms << "' is different than in topology '" << NumOfTopologyAtoms << "'";
        ES_ERROR(error);
        return(false);
    }

    // sanity check - spatial variable ---------------------

    SpatialVID = GetVariableID("spatial");
    if( SpatialVID < 0 ) {
        return(false);
    }

    size_t  start[3],count[3];
    char    xyz[3];
    int     err;

    start[0] = 0;
    count[0] = Spatial;
    xyz[0] = (char) 0;

    err = nc_get_vara_text(NCID,SpatialVID,start,count,xyz);
    if( err != NC_NOERR ) {
        CSmallString error;
        error << "unable to get spatial names (" << nc_strerror(err) << ")";
        ES_ERROR(error);
        return(false);
    }

    if( (xyz[0] != 'x') || (xyz[1] != 'y') || (xyz[2] != 'z') ) {
        CSmallString error;
        error << "incorrect spatial labels (" << xyz[0] << "," << xyz[1] << "," << xyz[2] << ")";
        ES_ERROR(error);
        return(false);
    }

    // sanity check - time ---------------------------------
    TimeVID = GetVariableID("time");
    if( TimeVID < 0 ) {
        return(false);
    }
    CSmallString unit;
    if( GetVariableAttribute(TimeVID,"units",unit) == false ) {
        return(false);
    }
    if( unit != "picosecond" ) {
        CSmallString error;
        error << "incorrect unit for time (" << unit << "), requested picosecond";
        ES_ERROR(error);
        return(false);
    }

    // sanity check - coordinates --------------------------
    CoordinateVID = GetVariableID("coordinates");
    if( CoordinateVID < 0 ) {
        return(false);
    }
    if( GetVariableAttribute(CoordinateVID,"units",unit) == false ) {
        return(false);
    }
    if( unit != "angstrom" ) {
        CSmallString error;
        error << "incorrect unit for coordinates (" << unit << "), requested angstrom";
        ES_ERROR(error);
        return(false);
    }

    CurrentSnapshot = 0;
    if( Coordinates != NULL ) {
        delete Coordinates;
    }
    Coordinates = new float[ActualAtoms*3];

    // sanity check - box ----------------------------------
    if( HasBox ){
        // optional
        CellLengthVID = GetVariableID("cell_lengths");
        CellAngleVID = GetVariableID("cell_angles");
    }

    return(true);
}
コード例 #21
0
ファイル: NetcdfFile.cpp プロジェクト: rmcgibbo/cpptraj
/** Setup ncatom, ncatom3, atomDID, coordVID, spatialDID, spatialVID,
  * velocityVID, frcVID. Check units and spatial dimensions.
  */
int NetcdfFile::SetupCoordsVelo(bool useVelAsCoords) {
    int spatial;
    atomDID_ = GetDimInfo(NCATOM, &ncatom_);
    if (atomDID_==-1) return 1;
    ncatom3_ = ncatom_ * 3;
    // Get coord info
    coordVID_ = -1;
    if ( nc_inq_varid(ncid_, NCCOORDS, &coordVID_) == NC_NOERR ) {
        if (ncdebug_ > 0) mprintf("\tNetcdf file has coordinates.\n");
        std::string attrText = GetAttrText(coordVID_, "units");
        if (attrText!="angstrom")
            mprintf("Warning: Netcdf file has length units of %s - expected angstrom.\n",
                    attrText.c_str());
    }
    // Get spatial info
    spatialDID_ = GetDimInfo(NCSPATIAL, &spatial);
    if (spatialDID_==-1) return 1;
    if (spatial!=3) {
        mprinterr("Error: Expected 3 spatial dimensions, got %i\n",spatial);
        return 1;
    }
    if ( checkNCerr(nc_inq_varid(ncid_, NCSPATIAL, &spatialVID_)) ) {
        mprintf("Warning: Could not get spatial VID. File may not be Amber NetCDF compliant.\n");
        mprintf("Warning: Assuming spatial variables are 'x', 'y', 'z'\n");
    } else {
        start_[0] = 0;
        count_[0] = 3;
        char xyz[3];
        if (checkNCerr(nc_get_vara_text(ncid_, spatialVID_, start_, count_, xyz))) {
            mprinterr("Error: Getting spatial variables.\n");
            return 1;
        }
        if (xyz[0] != 'x' || xyz[1] != 'y' || xyz[2] != 'z') {
            mprinterr("Error: NetCDF spatial variables are '%c', '%c', '%c', not 'x', 'y', 'z'\n",
                      xyz[0], xyz[1], xyz[2]);
            return 1;
        }
    }
    // Get velocity info
    velocityVID_ = -1;
    if ( nc_inq_varid(ncid_, NCVELO, &velocityVID_) == NC_NOERR ) {
        if (ncdebug_>0) mprintf("\tNetcdf file has velocities.\n");
    }
    // Return a error if no coords and no velocity
    if ( coordVID_ == -1 && velocityVID_ == -1 ) {
        mprinterr("Error: NetCDF file has no coords and no velocities.\n");
        return 1;
    }
    // If using velocities as coordinates, swap them now.
    if (useVelAsCoords) {
        if (velocityVID_ == -1) {
            mprinterr("Error: Cannot use velocities as coordinates; no velocities present.\n");
            return 1;
        }
        mprintf("\tUsing velocities as coordinates.\n");
        coordVID_ = velocityVID_;
        velocityVID_ = -1;
    }
    // Get force info
    frcVID_ = -1;
    if ( nc_inq_varid(ncid_, NCFRC, &frcVID_) == NC_NOERR ) {
        if (ncdebug_>0) mprintf("\tNetcdf file has forces.\n");
    }
    // Get overall replica and coordinate indices
    crdidxVID_ = -1;
    if ( nc_inq_varid(ncid_, NCREMD_REPIDX, &repidxVID_) == NC_NOERR ) {
        //if (ncdebug_ > 0)
        mprintf("    Netcdf file has overall replica indices.\n");
        if ( checkNCerr(nc_inq_varid(ncid_, NCREMD_CRDIDX, &crdidxVID_)) ) {
            mprinterr("Error: Getting overall coordinate index variable ID.\n");
            return 1;
        }
    } else
        repidxVID_ = -1;
    return 0;
}
コード例 #22
0
int CNetCdfInterface::ncGetVaraType(int ncid, int varid, const StdSize* start, const StdSize* count, char* data)
{
  return nc_get_vara_text(ncid, varid, start, count, data);
}
コード例 #23
0
ファイル: exgvarnams.c プロジェクト: FlorianChevassu/VTK
int ex_get_variable_names (int   exoid,
                           ex_entity_type obj_type,
                           int   num_vars,
                           char *var_names[])
{
  int i, 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_var_param",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 */

  /*
   * See if reading into contiguous memory in which case we can load 
   * all values in one call.  If not, we must load each name individually.
   */
  if ((size_t)(&var_names[num_vars-1][0] - &var_names[0][0]) ==
      sizeof(char)*(MAX_STR_LENGTH+1)*(num_vars-1)) {
    status = nc_get_var_text(exoid, varid, &var_names[0][0]);
    if (status != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to get results variable names from file id %d", exoid);
      ex_err("ex_get_var_names",errmsg,exerrval);
      return (EX_FATAL);
    }
  } else {
    for (i=0; i<num_vars; i++) {
      size_t start[2];
      size_t count[2];
      start[0] = i;  count[0] = 1;
      start[1] = 0;  count[1] = MAX_STR_LENGTH+1;
      status = nc_get_vara_text(exoid, varid, start, count, var_names[i]);
      if (status != NC_NOERR) {
        exerrval = status;
        sprintf(errmsg,
                "Error: failed to get results variable names from file id %d", exoid);
        ex_err("ex_get_var_names",errmsg,exerrval);
        return (EX_FATAL);
      }
    }
  }
  return (EX_NOERR);
}
コード例 #24
0
/* Get structure from an MMTK trajectory file */
static int read_mmtk_cdf_structure(void *mydata, int *optflags,
                                   molfile_atom_t *atoms) {
  int i, rc;
  molfile_atom_t *atom;
  cdfdata *cdf = (cdfdata *) mydata;
  mmtkdata *mmtk = &cdf->mmtk;
  size_t start[3], count[3];
  char *dstr;
  char **atom_pointers;
  int resnum;
  char resname[8];

  *optflags = MOLFILE_NOOPTIONS;

  mmtk->description = (char *) malloc((mmtk->description_lengthdim + 1) * sizeof(char));
  if (mmtk->description == NULL) 
    return MOLFILE_ERROR;

  start[0] = cdf->curframe; /* frame */
  count[0] = mmtk->description_lengthdim;

  rc = nc_get_vara_text(cdf->ncid, mmtk->description_id,
                        start, count, mmtk->description);
  if (rc != NC_NOERR)
    return MOLFILE_ERROR;

  /* initialize all atoms with name "X" to start with */
  /* indicating unknown atom types etc..              */
  for (i=0; i<cdf->natoms; i++) {
    atom = atoms + i;
    strncpy(atom->name, "X", sizeof(atom->name)-1);
    atom->name[sizeof(atom->name)-1] = '\0';
    strncpy(atom->type, atom->name, sizeof(atom->type)-1);
    atom->type[sizeof(atom->type)-1] = '\0';
    atom->resname[0] = '\0';
    atom->resid = 1;
    atom->chain[0] = '\0';
    atom->segid[0] = '\0';
  }

  /* Allocate a pointer array that will hold each atom's location in
     the description string. This will be used in a second pass through
     the description string in which residue names and indices will
     be assigned. */
  atom_pointers = (char **) malloc(cdf->natoms * sizeof(char *));
  if (atom_pointers == NULL)
    return MOLFILE_ERROR;

  /* First pass: look only at atoms */
  dstr = mmtk->description;
  while (dstr < (mmtk->description + mmtk->description_lengthdim)) {
    char *atomstr;
    atomstr = strstr(dstr, "A('");

    if (atomstr != NULL) {
      char name[1024];
      char *nmstart = NULL;
      char *nmend = NULL;
      char *indstart = NULL;
      char *endp = NULL;
      int index, len;

      endp = strchr(atomstr, ')');
      nmstart = strchr(atomstr, '\'');
      if (nmstart != NULL)
        nmend = strchr(nmstart+1, '\'');
      indstart = strchr(atomstr, ',');
      if (endp == NULL || nmstart == NULL || nmend == NULL || indstart == NULL) {
        printf("netcdfplugin) mmtk_read_structure(): unable to parse atom tag\n");
        break; /* something went wrong */
      }

      len = nmend - nmstart - 1;
      if (len > sizeof(name)) {
        printf("netcdfplugin) mmtk_read_structure(): bad length: %d\n", len);
        break; /* something went wrong */
      }
      memcpy(name, nmstart+1, len); 
      name[len] = '\0';

      index = -1;
      sscanf(indstart, ",%d)", &index);
      atom_pointers[index] = atomstr;

      if (index >= 0 && index < cdf->natoms) {
        atom = atoms + index;
        strncpy(atom->name, name, sizeof(atom->name)-1);
        atom->name[sizeof(atom->name)-1] = '\0';
        strncpy(atom->type, atom->name, sizeof(atom->type)-1);
        atom->type[sizeof(atom->type)-1] = '\0';
      }

      dstr = atomstr+1;
    } else {
      break; /* no more atom records found */
    }
  }

  /* Second pass: peptide chains */
  dstr = mmtk->description;
  while (dstr < (mmtk->description + mmtk->description_lengthdim)) {
    char *peptide, *pend;
    char *group, *gend;
    char *nmstart, *nmend;
    char chain_id = 'A';
    char *s;

    peptide = strstr(dstr, "S('");
    if (peptide == NULL)
      break;
    pend = find_closing_bracket(peptide+2);

    resnum = 1;
    group = peptide;
    while (1) {
      group = strstr(group, "G('");
      if (group == NULL || group >= pend)
	break;
      gend = find_closing_bracket(group+2);
      nmstart = strchr(group, '\'') + 1;
      nmend = strchr(nmstart, '\'');
      while (nmend > nmstart && isdigit(*(nmend-1)))
	nmend--;
      if (nmend-nmstart > 7)
	nmend = nmstart+7;
      strncpy(resname, nmstart, nmend-nmstart);
      resname[nmend-nmstart] = '\0';
      s = resname;
      while (*s) {
	*s = toupper(*s);
	s++;
      }
      set_atom_attributes(atoms, cdf->natoms, atom_pointers,
			  chain_id, resname, resnum, group, gend, 1);
      group = gend;
      resnum++;
    }

    if (chain_id == 'Z')
      chain_id = 'A';
    else
	chain_id++;
    dstr = pend;
  }

  /* Third pass: nucleic acid chains */
  dstr = mmtk->description;
  while (dstr < (mmtk->description + mmtk->description_lengthdim)) {
    char *nacid, *nend;
    char *group, *gend;
    char *nmstart, *nmend;
    char chain_id = 'a';
    char *s;

    nacid = strstr(dstr, "N('");
    if (nacid == NULL)
      break;
    nend = find_closing_bracket(nacid+2);

    resnum = 1;
    group = nacid;
    while (1) {
      group = strstr(group, "G('");
      if (group == NULL || group >= nend)
	break;
      gend = find_closing_bracket(group+2);
      nmstart = strchr(group, '\'') + 1;
      nmend = strchr(nmstart, '\'');
      while (nmend > nmstart && isdigit(*(nmend-1)))
	nmend--;
      if (nmend > nmstart && nmend[-1] == '_')
	nmend--;
      if (nmend-nmstart > 7)
	nmend = nmstart+7;
      strncpy(resname, nmstart, nmend-nmstart);
      resname[nmend-nmstart] = '\0';
      s = resname;
      while (*s) {
	*s = toupper(*s);
	s++;
      }
      if (resname[0] == 'R' || resname[0] == 'D') {
	switch (resname[1]) {
	case 'A':
	  strcpy(resname, "ADE");
	  break;
	case 'C':
	  strcpy(resname, "CYT");
	  break;
	case 'G':
	  strcpy(resname, "GUA");
	  break;
	case 'T':
	  strcpy(resname, "THY");
	  break;
	case 'U':
	  strcpy(resname, "URA");
	  break;
	}
      }
      set_atom_attributes(atoms, cdf->natoms, atom_pointers,
			  chain_id, resname, resnum, group, gend, 2);
      group = gend;
      resnum++;
    }

    if (chain_id == 'z')
      chain_id = 'a';
    else
	chain_id++;
    dstr = nend;
  }

  /* Fourth pass: non-chain molecules */
  resnum = 1;
  dstr = mmtk->description;
  while (dstr < (mmtk->description + mmtk->description_lengthdim)) {
    char *molecule, *mend;
    char *nmstart, *nmend;

    molecule = strstr(dstr, "M('");
    if (molecule == NULL)
      break;
    mend = find_closing_bracket(molecule+2);
    nmstart = strchr(molecule, '\'') + 1;
    nmend = strchr(nmstart, '\'');
    if (strncmp(nmstart, "water", 5) == 0)
      strcpy(resname, "HOH");
    else {
      if (nmend-nmstart > 7)
	nmend = nmstart+7;
      strncpy(resname, nmstart, nmend-nmstart);
      resname[nmend-nmstart] = '\0';
    }
    set_atom_attributes(atoms, cdf->natoms, atom_pointers,
			'_', resname, resnum, molecule, mend, 0);
    resnum++;
    dstr = mend;
  }

  free(atom_pointers);

  return MOLFILE_SUCCESS;
}
コード例 #25
0
ファイル: tst_coords2.c プロジェクト: BJangeofan/netcdf-c
int
main(int argc, char **argv)
{
   printf("\n*** Testing netcdf-4 coordinate dimensions and variables, some more.\n");

   printf("**** testing more complex 2D coordinate variable with dimensions defined in different order...");
   {
#define NDIMS 5
#define NVARS 4
#define LON_NAME "lon"
#define LAT_NAME "lat"
#define LVL_NAME "lvl"
#define TIME_NAME "time"
#define TEXT_LEN_NAME "text_len"
#define TEMP_NAME "temp"
#define PRES_NAME "pres"
#define LON_LEN 5
#define LAT_LEN 3
#define LVL_LEN 7
#define TIME_LEN 2
#define TEXT_LEN 15
#define TIME_NDIMS 2
#define DATA_NDIMS 4

      int ncid, nvars_in, varids_in[NVARS];
      int time_dimids[TIME_NDIMS];
      int dimids[NDIMS], time_id, lon_id, pres_id, temp_id;
      size_t time_count[NDIMS], time_index[NDIMS] = {0, 0};
      const char ttext[TEXT_LEN + 1]="20051224.150000";
      char ttext_in[TEXT_LEN + 1];
      int nvars, ndims, ngatts, unlimdimid;
      int ndims_in, natts_in, dimids_in[NDIMS];
      char var_name_in[NC_MAX_NAME + 1], dim_name_in[NC_MAX_NAME + 1];
      size_t len_in;
      nc_type xtype_in;
      int d;

      /* Create a netcdf-4 file. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      /* Define dimensions. */
      if (nc_def_dim(ncid, LON_NAME, LON_LEN, &dimids[0])) ERR;
      if (nc_def_dim(ncid, LAT_NAME, LAT_LEN, &dimids[1])) ERR;
      if (nc_def_dim(ncid, LVL_NAME, LVL_LEN, &dimids[2])) ERR;
      if (nc_def_dim(ncid, TIME_NAME, TIME_LEN, &dimids[3])) ERR;
      if (nc_def_dim(ncid, TEXT_LEN_NAME, TEXT_LEN, &dimids[4])) ERR;

      /* Define two coordinate variables out of order. */
      time_dimids[0] = dimids[3];
      time_dimids[1] = dimids[4];
      if (nc_def_var(ncid, TIME_NAME, NC_CHAR, TIME_NDIMS, time_dimids, &time_id)) ERR;
      if (nc_def_var(ncid, LON_NAME, NC_CHAR, 1, &dimids[0], &lon_id)) ERR;

      /* Write one time to the coordinate variable. */
      time_count[0] = 1;
      time_count[1] = TEXT_LEN;
      if (nc_put_vara_text(ncid, time_id, time_index, time_count, ttext)) ERR;

      /* Define two data variable. */
      if (nc_def_var(ncid, PRES_NAME, NC_CHAR, DATA_NDIMS, dimids, &pres_id)) ERR;
      if (nc_def_var(ncid, TEMP_NAME, NC_CHAR, DATA_NDIMS, dimids, &temp_id)) ERR;

      /* Check the data. */
      if (nc_get_vara_text(ncid, time_id, time_index, time_count, ttext_in)) ERR;
      if (strncmp(ttext, ttext_in, TEXT_LEN)) ERR;

      /* Check the metadata. */
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != NVARS || ndims != NDIMS || ngatts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != NVARS || varids_in[0] != 0 || varids_in[1] != 1 || 
	  varids_in[2] != 2 || varids_in[3] != 3) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, TIME_NAME) || xtype_in != NC_CHAR || ndims_in != TIME_NDIMS ||
	dimids_in[0] != time_dimids[0] || dimids_in[1] != time_dimids[1] || natts_in != 0) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != NDIMS) ERR;
      for (d = 0; d < NDIMS; d++)
	 if (dimids_in[d] != dimids[d]) ERR;
      if (nc_inq_dim(ncid, 0, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, LON_NAME) || len_in != LON_LEN) ERR;
      if (nc_inq_dim(ncid, 1, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, LAT_NAME) || len_in != LAT_LEN) ERR;
      if (nc_inq_dim(ncid, 2, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, LVL_NAME) || len_in != LVL_LEN) ERR;
      if (nc_inq_dim(ncid, 3, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, TIME_NAME) || len_in != TIME_LEN) ERR;
      if (nc_inq_dim(ncid, 4, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, TEXT_LEN_NAME) || len_in != TEXT_LEN) ERR;

      /* Close up. */
      if (nc_close(ncid)) ERR;

      /* Open the file and check the order of variables and dimensions. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &ngatts, &unlimdimid)) ERR;
      if (nvars != NVARS || ndims != NDIMS || ngatts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR;
      if (nvars_in != NVARS || varids_in[0] != 0 || varids_in[1] != 1 || 
	  varids_in[2] != 2 || varids_in[3] != 3) ERR;
      if (nc_inq_var(ncid, 0, var_name_in, &xtype_in, &ndims_in, dimids_in, &natts_in)) ERR;
      if (strcmp(var_name_in, TIME_NAME) || xtype_in != NC_CHAR || ndims_in != TIME_NDIMS ||
	dimids_in[0] != time_dimids[0] || dimids_in[1] != time_dimids[1] || natts_in != 0) ERR;
      if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR;
      if (ndims_in != NDIMS) ERR;
      for (d = 0; d < NDIMS; d++)
	 if (dimids_in[d] != dimids[d]) ERR;
      if (nc_inq_dim(ncid, 0, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, LON_NAME) || len_in != LON_LEN) ERR;
      if (nc_inq_dim(ncid, 1, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, LAT_NAME) || len_in != LAT_LEN) ERR;
      if (nc_inq_dim(ncid, 2, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, LVL_NAME) || len_in != LVL_LEN) ERR;
      if (nc_inq_dim(ncid, 3, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, TIME_NAME) || len_in != TIME_LEN) ERR;
      if (nc_inq_dim(ncid, 4, dim_name_in, &len_in)) ERR;
      if (strcmp(dim_name_in, TEXT_LEN_NAME) || len_in != TEXT_LEN) ERR;

      /* Check the data. */
      if (nc_get_vara_text(ncid, time_id, time_index, time_count, ttext_in)) ERR;
      if (strncmp(ttext, ttext_in, TEXT_LEN)) ERR;

      /* Close up. */
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("**** testing example from bug NCF-247, multidimensional coord variable in subgroup ...");
   {
#define GRPNAME "g1"
#define DIM0NAME "dim0"
#define DIM1NAME "dim1"
#define DIM2NAME "coord"
#define DIM3NAME "dim3"
#define VARNAME  DIM2NAME
#define VARRANK 2
       int  ncid, grpid, varid, var_dims[VARRANK], var_dims_in[VARRANK];
       char name2[NC_MAX_NAME], name3[NC_MAX_NAME];
       int dim0_dim, dim1_dim, dim2_dim, dim3_dim;
       size_t dim0_len = 3, dim1_len = 2, dim2_len = 5, dim3_len = 7;

       if (nc_create(FILE_NAME, NC_CLOBBER|NC_NETCDF4, &ncid)) ERR;
       if (nc_def_grp(ncid, GRPNAME, &grpid)) ERR;
       
       if (nc_def_dim(ncid, DIM0NAME, dim0_len, &dim0_dim)) ERR;
       if (nc_def_dim(ncid, DIM1NAME, dim1_len, &dim1_dim)) ERR;
       if (nc_def_dim(grpid, DIM2NAME, dim2_len, &dim2_dim)) ERR;
       if (nc_def_dim(grpid, DIM3NAME, dim3_len, &dim3_dim)) ERR;

       var_dims[0] = dim2_dim;
       var_dims[1] = dim3_dim;
       if (nc_def_var(grpid, VARNAME, NC_INT, VARRANK, var_dims, &varid)) ERR;
    
       if (nc_close(ncid)) ERR;
    
       if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
    
       if (nc_inq_grp_ncid(ncid, GRPNAME, &grpid)) ERR;
    
       if (nc_inq_varid(grpid, VARNAME, &varid)) ERR;
       if (nc_inq_vardimid(grpid, varid, var_dims_in)) ERR;
       if (nc_inq_dimname(grpid, var_dims_in[0], name2)) ERR;
       if (nc_inq_dimname(grpid, var_dims_in[1], name3)) ERR;
       if (strcmp(name2, DIM2NAME) != 0 || strcmp(name3, DIM3NAME) != 0) ERR;
       if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #26
0
 int ex_get_coordinate_frames( int exoid,
			       int *nframes,
			       void_int *cf_ids,
			       void* pt_coordinates,
			       char* tags)

{
  int status;
  int dimid; /* ID of the dimension of # frames */
  char errmsg[MAX_ERR_LENGTH];
  int varids;                    /* variable id for the frame ids  */
  size_t start=0;                /* start value for varputs        */
  size_t count=0;                /* number vars to put in varput   */

  /* get the dimensions */
  assert( nframes !=NULL );
  status = nc_inq_dimid(exoid, DIM_NUM_CFRAMES, &dimid);
  if (status != NC_NOERR){
    *nframes=0;
    return EX_NOERR;
  }

  (void)nc_inq_dimlen(exoid,dimid,&count);
  *nframes=(int)count;

  if ( count==0 )
    return (EX_NOERR);

  if ( cf_ids ) {
    if ((status = nc_inq_varid(exoid,VAR_FRAME_IDS, &varids))!= NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate ids from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }

    if (ex_int64_status(exoid) & EX_IDS_INT64_API) {
      status = nc_get_var_longlong(exoid,varids,cf_ids);
    } else {
      status = nc_get_var_int(exoid,varids,cf_ids);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read coordinate frame ids from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  if ( tags )
    if ( (status = nc_inq_varid(exoid,VAR_FRAME_TAGS,&varids))!= NC_NOERR  ||
         (nc_get_vara_text(exoid,varids,&start,&count,tags) != NC_NOERR)) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate tags from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }

  if (pt_coordinates ){
    if ( (status = nc_inq_varid(exoid,VAR_FRAME_COORDS,&varids))!= NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate tags from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }

    if (ex_comp_ws(exoid) == 4) {
      status = nc_get_var_float(exoid,varids,pt_coordinates);
    } else {
      status = nc_get_var_double(exoid,varids,pt_coordinates);
    }

    if (status != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to read number coordinate tags from file id %d",
              exoid);
      ex_err(PROCNAME,errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  return (EX_NOERR);
}
コード例 #27
0
int ex_get_qa (int exoid,
               char *qa_record[][4])
{
  int status;
  int dimid, varid;
  size_t i, j;
  size_t num_qa_records, start[3], count[3];

  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_QA, &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Warning: no qa records stored in file id %d", 
            rootid);
    ex_err("ex_get_qa",errmsg,exerrval);
    return (EX_WARN);
  }

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


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


    /* read the QA records */
    for (i=0; i<num_qa_records; i++) {
      for (j=0; j<4; j++) {
	start[0] = i; count[0] = 1;
	start[1] = j; count[1] = 1;
	start[2] = 0; count[2] = MAX_STR_LENGTH+1;
	if ((status = nc_get_vara_text(rootid, varid, start, count, qa_record[i][j])) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get qa record data in file id %d", rootid);
	  ex_err("ex_get_qa",errmsg,exerrval);
	  return (EX_FATAL);
	}
	qa_record[i][j][MAX_STR_LENGTH] = '\0';
	ex_trim_internal(qa_record[i][j]);
      }
    }
  }
  return (EX_NOERR);
}