Exemplo n.º 1
0
static int write_numeric_attribute(int ncid, int varid, const char *name, harp_data_type data_type, harp_scalar data)
{
    int result;

    result = NC_NOERR;
    switch (data_type)
    {
        case harp_type_int8:
            result = nc_put_att_schar(ncid, varid, name, NC_BYTE, 1, &data.int8_data);
            break;
        case harp_type_int16:
            result = nc_put_att_short(ncid, varid, name, NC_SHORT, 1, &data.int16_data);
            break;
        case harp_type_int32:
            result = nc_put_att_int(ncid, varid, name, NC_INT, 1, &data.int32_data);
            break;
        case harp_type_float:
            result = nc_put_att_float(ncid, varid, name, NC_FLOAT, 1, &data.float_data);
            break;
        case harp_type_double:
            result = nc_put_att_double(ncid, varid, name, NC_DOUBLE, 1, &data.double_data);
            break;
        default:
            assert(0);
            exit(1);
    }

    if (result != NC_NOERR)
    {
        harp_set_error(HARP_ERROR_NETCDF, "%s", nc_strerror(result));
        return -1;
    }

    return 0;
}
Exemplo n.º 2
0
int
add_attributes(int ncid, int varid, size_t num_atts, size_t att_len)
{
   char att_name[NC_MAX_NAME + 1];
   double *att_data;
   int i, a;

   /* Allocate space for attribute data. */
   if (!(att_data = malloc(att_len * sizeof(double))))
      return NC_ENOMEM;

   /* Fill up data. */
   for (i = 0; i < ATT_LEN; i++)
      att_data[i] = i;

   /* Write a bunch of attributes. */
   for (a = 0; a < num_atts; a++)
   {
      sprintf(att_name, "%s_varid_%d_att_%d", TEST, varid, a);
      if (nc_put_att_double(ncid, varid, att_name, NC_DOUBLE,
                            att_len, att_data)) ERR;
   }

   free(att_data);

   return 0;
}
Exemplo n.º 3
0
Arquivo: ncdf.c Projeto: cran/ncdf
void R_nc_put_att_double( int *ncid, int *varid, char **attname, 
		int *type_to_create, int *natts, double *attribute, int *retval )
{
	nc_type ttc;
	ttc = R_nc_ttc_to_nctype( *type_to_create );
	*retval = nc_put_att_double(*ncid, *varid, attname[0], 
		ttc, *natts, attribute );
	if( *retval != NC_NOERR ) 
		REprintf( "Error in R_nc_put_att_double: %s\n", 
			nc_strerror(*retval) );
}
Exemplo n.º 4
0
static void
createtestvars(int id, const struct tcdfvar *testvars, size_t count)
{
	int ii;
	int varid;
	const struct tcdfvar *vp = testvars;

	for(ii = 0; (size_t) ii < count; ii++, vp++ )
	{
		assert(nc_def_var(id, vp->mnem, vp->type, vp->ndims, vp->dims,
				 &varid)
			 == NC_NOERR ); 

	 	assert(
			nc_put_att_text(id,ii,reqattr[0],strlen(vp->units),
				vp->units)
			== NC_NOERR); 
	 	assert(
			nc_put_att_double(id,ii,reqattr[1],NC_DOUBLE,1,
				&vp->validmin)
			== NC_NOERR); 
	 	assert(
			nc_put_att_double(id,ii,reqattr[2],NC_DOUBLE,1,
				&vp->validmax)
			== NC_NOERR); 
	 	assert(
			nc_put_att_double(id,ii,reqattr[3],NC_DOUBLE,1,
				&vp->scalemin)
			== NC_NOERR); 
	 	assert(
			nc_put_att_double(id,ii,reqattr[4],NC_DOUBLE,1,
				&vp->scalemax)
			== NC_NOERR); 
	 	assert(
			nc_put_att_text(id,ii,reqattr[5],strlen(vp->fieldnam),
				vp->fieldnam)
			== NC_NOERR); 
	}
}
Exemplo n.º 5
0
/* NOTE that NA's are handled through this vector.  According to the 
 * docs as of 2010-11-02, NA's have the value MIN_INT */
void R_nc4_put_att_logical( int *ncid, int *varid, char **attname, 
		int *type_to_create, int *natts, int *attribute, int *retval )
{
	int	R_NA_val;
	float	C_NA_val_f;
	double 	C_NA_val_d;

	/* Rprintf( "in R_nc4_put_att_logical with val=%d\n", *attribute ); */
	nc_type ttc;
	ttc = R_nc4_ttc_to_nctype( *type_to_create );

	R_NA_val = -2147483648;		/* From R docs */

	if( *attribute == R_NA_val ) {
		/* Rprintf( "PUTTING a NA -- float \n" ); */
		/* Put a NA */
		if( ttc == NC_FLOAT ) {
			C_NA_val_f = 0./0.;
			*retval = nc_put_att_float(*ncid, *varid, attname[0], 
				ttc, *natts, &C_NA_val_f );
			if( *retval != NC_NOERR ) 
				Rprintf( "Error in R_nc4_put_att_logical: %s\n", 
					nc_strerror(*retval) );
			}

		else if( ttc == NC_DOUBLE ) {
			/* Rprintf( "PUTTING a NA -- double \n" ); */
			C_NA_val_d = 0./0.;
			*retval = nc_put_att_double(*ncid, *varid, attname[0], 
				ttc, *natts, &C_NA_val_d );
			if( *retval != NC_NOERR ) 
				Rprintf( "Error in R_nc4_put_att_logical: %s\n", 
					nc_strerror(*retval) );
			}
		else
			{
			Rprintf( "Error in R_nc4_put_att_logical: asked to put a NA value, but the variable's type is not a double or float, which are the only two types that have a defined NaN value\n" );
			*retval = -1;
			return;
			}

		}
	else
		*retval = nc_put_att_int(*ncid, *varid, attname[0], 
			ttc, *natts, attribute );

	if( *retval != NC_NOERR ) 
		Rprintf( "Error in R_nc4_put_att_logical: %s\n", 
			nc_strerror(*retval) );
}
Exemplo n.º 6
0
NCstate NCdsHandleGContUpdateRanges(const NCdsHandleGCont_t *gCont) {
    int status;
    double *minArray = (double *) NULL, *maxArray = (double *) NULL, *meanArray = (double *) NULL, meanRange[2], minRange[2], maxRange[2], varRange[2], glbRange[2];
    size_t i, offset, ncidx, level;
    size_t start[2], count[2];

    if ((gCont->MinIds == (int *) NULL) || (gCont->MaxIds == (int *) NULL)) {
        CMmsgPrint(CMmsgAppError, "Missing minimum or maximum variables in:  %s %d", __FILE__, __LINE__);
        goto ABORT;
    }

    if (((meanArray = (double *) calloc(gCont->TNum, sizeof(double))) == (double *) NULL) ||
        ((minArray = (double *) calloc(gCont->TNum, sizeof(double))) == (double *) NULL) ||
        ((maxArray = (double *) calloc(gCont->TNum, sizeof(double))) == (double *) NULL)) {
        CMmsgPrint(CMmsgSysError, "Memory allocation error in: %s %d", __FILE__, __LINE__);
        goto ABORT;
    }

    glbRange[0] = HUGE_VAL;
    glbRange[1] = -HUGE_VAL;
    start[0] = 0;
    count[1] = 1;
    for (ncidx = 0; ncidx < gCont->NCnum; ncidx++) {
        meanRange[0] = minRange[0] = maxRange[0] = HUGE_VAL;
        meanRange[1] = minRange[1] = maxRange[1] = -HUGE_VAL;
        if ((gCont->MinIds[ncidx] == NCundefined) || (gCont->MaxIds[ncidx] == NCundefined)) {
            CMmsgPrint(CMmsgAppError, "Missing minimum or maximum variables in: %s %d", __FILE__, __LINE__);
            goto ABORT;
        }
        count[0] = (ncidx + 1 < gCont->NCnum ? gCont->NCoffset[ncidx + 1] : gCont->TNum) - gCont->NCoffset[ncidx];
        offset = gCont->NCoffset[ncidx];
        for (level = 0; level < gCont->LNum; level++) {
            start[1] = level;
            if (((status = nc_get_vara_double(gCont->NCIds[ncidx], gCont->MeanIds[ncidx], start, count,
                                              meanArray + offset)) != NC_NOERR) ||
                ((status = nc_get_vara_double(gCont->NCIds[ncidx], gCont->MinIds[ncidx], start, count,
                                              minArray + offset)) != NC_NOERR) ||
                ((status = nc_get_vara_double(gCont->NCIds[ncidx], gCont->MaxIds[ncidx], start, count,
                                              maxArray + offset)) != NC_NOERR)) {
                NCprintNCError (status, "_NCdsHandleGContUpdateRange");
                goto ABORT;
            }
            for (i = 0; i < count[0]; i++) {
                if (meanArray[i + offset] < meanRange[0]) meanRange[0] = meanArray[i + offset];
                if (meanArray[i + offset] > meanRange[1]) meanRange[1] = meanArray[i + offset];
                if (minArray[i + offset] < minRange[0]) minRange[0] = minArray[i + offset];
                if (minArray[i + offset] > minRange[1]) minRange[1] = minArray[i + offset];
                if (maxArray[i + offset] < maxRange[0]) maxRange[0] = maxArray[i + offset];
                if (maxArray[i + offset] > maxRange[1]) maxRange[1] = maxArray[i + offset];
            }
            varRange[0] = minRange[0];
            varRange[1] = maxRange[1];
            if (varRange[0] < glbRange[0]) glbRange[0] = varRange[0];
            if (varRange[1] > glbRange[1]) glbRange[1] = varRange[1];
            if (((status = nc_redef(gCont->NCIds[ncidx])) != NC_NOERR) ||
                ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->GVarIds[ncidx], NCnameVAActualRange, NC_FLOAT,
                                             2, varRange)) != NC_NOERR) ||
                ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->MeanIds[ncidx], NCnameVAActualRange, NC_FLOAT,
                                             2, meanRange)) != NC_NOERR) ||
                ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->MinIds[ncidx], NCnameVAActualRange, NC_FLOAT,
                                             2, minRange)) != NC_NOERR) ||
                ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->MaxIds[ncidx], NCnameVAActualRange, NC_FLOAT,
                                             2, maxRange)) != NC_NOERR) ||
                ((status = nc_enddef(gCont->NCIds[ncidx])) != NC_NOERR)) {
                NCprintNCError (status, "_NCdsHandleGContUpdateRange");
                goto ABORT;
            }
        }
    }
    for (ncidx = 0; ncidx < gCont->NCnum; ncidx++)
        if (((status = nc_redef(gCont->NCIds[ncidx])) != NC_NOERR) ||
            ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->GVarIds[ncidx], NCnameVAValidRange, NC_FLOAT, 2,
                                         glbRange)) != NC_NOERR) ||
            ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->MeanIds[ncidx], NCnameVAValidRange, NC_FLOAT, 2,
                                         glbRange)) != NC_NOERR) ||
            ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->MinIds[ncidx], NCnameVAValidRange, NC_FLOAT, 2,
                                         glbRange)) != NC_NOERR) ||
            ((status = nc_put_att_double(gCont->NCIds[ncidx], gCont->MaxIds[ncidx], NCnameVAValidRange, NC_FLOAT, 2,
                                         glbRange)) != NC_NOERR) ||
            ((status = nc_enddef(gCont->NCIds[ncidx])) != NC_NOERR)) {
            NCprintNCError (status, "_NCdsHandleGContUpdateRange");
            goto ABORT;
        }
    free(meanArray);
    free(minArray);
    free(maxArray);
    return (NCsucceeded);

    ABORT:
    if (meanArray != (double *) NULL) free(meanArray);
    if (minArray != (double *) NULL) free(minArray);
    if (maxArray != (double *) NULL) free(maxArray);
    return (NCfailed);
}
Exemplo n.º 7
0
int
main(int argc, char **argv)
{
    int ncid, dimid, fvarid, dvarid;
    float fvals[NVALS], fvals_in[NVALS];
    double dvals[NVALS], dvals_in[NVALS];


    float fnan = NC_FNAN;//(NC_INFINITE-NC_INFINITE);//0.f/0.f;
    double dnan = NC_DNAN;//(NC_INFINITE-NC_INFINITE);//0.0/0.0;
    float fpinf = NC_FPINF;//NC_INFINITE;//1.0f/0.0f;
    float fninf = -fpinf;
    double dpinf = NC_DPINF;//NC_INFINITE;//1.0/0.0;
    double dninf = -dpinf;
    nc_type att_type;
    size_t att_len;
    float att_fvals[NVALS];
    double att_dvals[NVALS];

    printf("\n*** Testing NaN\n");
    printf("*** creating NaN test file %s...", FILE8_NAME);
    if (nc_create(FILE8_NAME, NC_CLOBBER, &ncid)) ERR;

    if (nc_def_dim(ncid, DIM_NAME, NVALS, &dimid)) ERR;

    if (nc_def_var(ncid, F_NAME, NC_FLOAT, NDIMS, &dimid, &fvarid)) ERR;
    if (nc_def_var(ncid, D_NAME, NC_DOUBLE, NDIMS, &dimid, &dvarid)) ERR;

    fvals[0] = fninf;
    fvals[1] = fnan;
    fvals[2] = fpinf;
    dvals[0] = dninf;
    dvals[1] = dnan;
    dvals[2] = dpinf;

    /* Create float and double attributes */
    if (nc_put_att_float(ncid, fvarid, FV_NAME, NC_FLOAT, FV_NVALS, &fnan)) ERR;
    if (nc_put_att_float(ncid, fvarid, ATT_NAME, NC_FLOAT, NVALS, fvals)) ERR;
    if (nc_put_att_double(ncid, dvarid, FV_NAME, NC_DOUBLE, FV_NVALS, &dnan)) ERR;
    if (nc_put_att_double(ncid, dvarid, ATT_NAME, NC_DOUBLE, NVALS, dvals)) ERR;

    if (nc_enddef(ncid)) ERR;

    /* Write float and double data */
   if (nc_put_var_float(ncid, fvarid, fvals)) ERR;
   if (nc_put_var_double(ncid, dvarid, dvals)) ERR;

   if (nc_close(ncid)) ERR;

   /* Check it out. */

   /* Reopen the file. */
   if (nc_open(FILE8_NAME, NC_NOWRITE, &ncid)) ERR;
   if (nc_inq_varid(ncid, F_NAME, &fvarid)) ERR;
   if (nc_inq_varid(ncid, D_NAME, &dvarid)) ERR;
   /* Check the values of the float attributes */
   if (nc_inq_att(ncid, fvarid, FV_NAME, &att_type, &att_len)) ERR;
   if (att_type != NC_FLOAT || att_len != FV_NVALS) ERR;
   if (nc_get_att_float(ncid, fvarid, FV_NAME, att_fvals)) ERR;
   if (!isnan(att_fvals[0])) ERR;
   if (nc_get_att_float(ncid, fvarid, ATT_NAME, att_fvals)) ERR;
   if (!(isinf(att_fvals[0]) && att_fvals[0] < 0)) ERR;
   if (!isnan(att_fvals[1])) ERR;
   if (!(isinf(att_fvals[2]) && att_fvals[2] > 0)) ERR;
   /* Check the values of double attributes */
   if (nc_inq_att(ncid, dvarid, FV_NAME, &att_type, &att_len)) ERR;
   if (att_type != NC_DOUBLE || att_len != FV_NVALS) ERR;
   if (nc_get_att_double(ncid, dvarid, FV_NAME, att_dvals)) ERR;
   if (!isnan(att_dvals[0])) ERR;
   if (nc_get_att_double(ncid, dvarid, ATT_NAME, att_dvals)) ERR;
   if (!(isinf(att_dvals[0]) && att_dvals[0] < 0)) ERR;
   if (!isnan(att_dvals[1])) ERR;
   if (!(isinf(att_dvals[2]) && att_dvals[2] > 0)) ERR;
   /* Check values of float data */
   if (nc_get_var_float(ncid, fvarid, fvals_in)) ERR;
   if (!(isinf(fvals_in[0]) && fvals_in[0] < 0)) ERR;
   if (!isnan(fvals_in[1])) ERR;
   if (!(isinf(fvals_in[2]) && fvals_in[2] > 0)) ERR;
   /* Check values of double data */
   if (nc_get_var_double(ncid, dvarid, dvals_in)) ERR;
   if (!(isinf(dvals_in[0]) && dvals_in[0] < 0)) ERR;
   if (!isnan(dvals_in[1])) ERR;
   if (!(isinf(dvals_in[2]) && dvals_in[2] > 0)) ERR;

   if (nc_close(ncid)) ERR;

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

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

	if(nc_close(ncid) != NC_NOERR) { CMmsgPrint (CMmsgUsrError, "Error commiting changes to file!"); return (NCfailed); }
	return 0;
}
Exemplo n.º 9
0
/*
 * Add or changes a numeric variable or global attribute of an open
 * netCDF file.
 */
static void
c_ncapt (
    int		ncid,		/* netCDF ID */
    int		varid,		/* variable ID */
    const char*	attname,	/* attribute name */
    nc_type	datatype,	/* attribute datatype */
    size_t	attlen,		/* attribute length */
    const void*	value,		/* pointer to data values */
    int*	rcode		/* returned error code */
)
{
    int		status;

    switch (datatype)
    {
    case NC_CHAR:
	status = NC_ECHAR;
	break;
    case NC_BYTE:
#	if NF_INT1_IS_C_SIGNED_CHAR
	    status = nc_put_att_schar(ncid, varid, attname, datatype,
				       attlen, (const signed char*)value);
#	elif NF_INT1_IS_C_SHORT
	    status = nc_put_att_short(ncid, varid, attname, datatype,
				       attlen, (const short*)value);
#	elif NF_INT1_IS_C_INT
	    status = nc_put_att_int(ncid, varid, attname, datatype,
				       attlen, (const int*)value);
#	elif NF_INT1_IS_C_LONG
	    status = nc_put_att_long(ncid, varid, attname, datatype,
				       attlen, (const long*)value);
#	endif
	break;
    case NC_SHORT:
#	if NF_INT2_IS_C_SHORT
	    status = nc_put_att_short(ncid, varid, attname, datatype,
				       attlen, (const short*)value);
#	elif NF_INT2_IS_C_INT
	    status = nc_put_att_int(ncid, varid, attname, datatype,
				       attlen, (const int*)value);
#	elif NF_INT2_IS_C_LONG
	    status = nc_put_att_long(ncid, varid, attname, datatype,
				       attlen, (const long*)value);
#	endif
	break;
    case NC_INT:
#	if NF_INT_IS_C_INT
	    status = nc_put_att_int(ncid, varid, attname, datatype,
				       attlen, (const int*)value);
#	elif NF_INT_IS_C_LONG
	    status = nc_put_att_long(ncid, varid, attname, datatype,
				       attlen, (const long*)value);
#	endif
	break;
    case NC_FLOAT:
#	if NF_REAL_IS_C_FLOAT
	    status = nc_put_att_float(ncid, varid, attname, datatype,
				       attlen, (const float*)value);
#	elif NF_REAL_IS_C_DOUBLE
	    status = nc_put_att_double(ncid, varid, attname, datatype,
				       attlen, (const double*)value);
#	endif
	break;
    case NC_DOUBLE:
#	if NF_DOUBLEPRECISION_IS_C_FLOAT
	    status = nc_put_att_float(ncid, varid, attname, datatype,
				       attlen, (const float*)value);
#	elif NF_DOUBLEPRECISION_IS_C_DOUBLE
	    status = nc_put_att_double(ncid, varid, attname, datatype,
				       attlen, (const double*)value);
#	endif
	break;
    }

    if (status == 0)
	*rcode = 0;
    else
    {
	nc_advise("NCAPT", status, "");
	*rcode = ncerr;
    }
}
Exemplo n.º 10
0
int
main() {/* create ctest0_64.nc */

    int  stat;  /* return status */
    int  ncid;  /* netCDF id */

    /* dimension ids */
    int Dr_dim;
    int D1_dim;
    int D2_dim;
    int D3_dim;
    int dim_MINUS_name_MINUS_dashes_dim;
    int dim_PERIOD_name_PERIOD_dots_dim;
    int dim_PLUS_name_PLUS_plusses_dim;
    int dim_ATSIGN_name_ATSIGN_ats_dim;

    /* dimension lengths */
    size_t Dr_len = NC_UNLIMITED;
    size_t D1_len = 1;
    size_t D2_len = 2;
    size_t D3_len = 3;
    size_t dim_MINUS_name_MINUS_dashes_len = 4;
    size_t dim_PERIOD_name_PERIOD_dots_len = 5;
    size_t dim_PLUS_name_PLUS_plusses_len = 6;
    size_t dim_ATSIGN_name_ATSIGN_ats_len = 7;

    /* variable ids */
    int c_id;
    int b_id;
    int s_id;
    int i_id;
    int f_id;
    int d_id;
    int cr_id;
    int br_id;
    int sr_id;
    int ir_id;
    int fr_id;
    int dr_id;
    int c1_id;
    int b1_id;
    int s1_id;
    int i1_id;
    int f1_id;
    int d1_id;
    int c2_id;
    int b2_id;
    int s2_id;
    int i2_id;
    int f2_id;
    int d2_id;
    int c3_id;
    int b3_id;
    int s3_id;
    int i3_id;
    int f3_id;
    int d3_id;
    int cr1_id;
    int br2_id;
    int sr3_id;
    int f11_id;
    int d12_id;
    int c13_id;
    int s21_id;
    int i22_id;
    int f23_id;
    int c31_id;
    int b32_id;
    int s33_id;
    int sr11_id;
    int ir12_id;
    int fr13_id;
    int cr21_id;
    int br22_id;
    int sr23_id;
    int fr31_id;
    int dr32_id;
    int cr33_id;
    int c111_id;
    int b112_id;
    int s113_id;
    int f121_id;
    int d122_id;
    int c123_id;
    int s131_id;
    int i132_id;
    int f133_id;
    int f211_id;
    int d212_id;
    int c213_id;
    int s221_id;
    int i222_id;
    int f223_id;
    int c231_id;
    int b232_id;
    int s233_id;
    int s311_id;
    int i312_id;
    int f313_id;
    int var_MINUS_name_MINUS_dashes_id;
    int var_PERIOD_name_PERIOD_dots_id;
    int var_PLUS_name_PLUS_plusses_id;
    int var_ATSIGN_name_ATSIGN_ats_id;

    /* rank (number of dimensions) for each variable */
#   define RANK_c 0
#   define RANK_b 0
#   define RANK_s 0
#   define RANK_i 0
#   define RANK_f 0
#   define RANK_d 0
#   define RANK_cr 1
#   define RANK_br 1
#   define RANK_sr 1
#   define RANK_ir 1
#   define RANK_fr 1
#   define RANK_dr 1
#   define RANK_c1 1
#   define RANK_b1 1
#   define RANK_s1 1
#   define RANK_i1 1
#   define RANK_f1 1
#   define RANK_d1 1
#   define RANK_c2 1
#   define RANK_b2 1
#   define RANK_s2 1
#   define RANK_i2 1
#   define RANK_f2 1
#   define RANK_d2 1
#   define RANK_c3 1
#   define RANK_b3 1
#   define RANK_s3 1
#   define RANK_i3 1
#   define RANK_f3 1
#   define RANK_d3 1
#   define RANK_cr1 2
#   define RANK_br2 2
#   define RANK_sr3 2
#   define RANK_f11 2
#   define RANK_d12 2
#   define RANK_c13 2
#   define RANK_s21 2
#   define RANK_i22 2
#   define RANK_f23 2
#   define RANK_c31 2
#   define RANK_b32 2
#   define RANK_s33 2
#   define RANK_sr11 3
#   define RANK_ir12 3
#   define RANK_fr13 3
#   define RANK_cr21 3
#   define RANK_br22 3
#   define RANK_sr23 3
#   define RANK_fr31 3
#   define RANK_dr32 3
#   define RANK_cr33 3
#   define RANK_c111 3
#   define RANK_b112 3
#   define RANK_s113 3
#   define RANK_f121 3
#   define RANK_d122 3
#   define RANK_c123 3
#   define RANK_s131 3
#   define RANK_i132 3
#   define RANK_f133 3
#   define RANK_f211 3
#   define RANK_d212 3
#   define RANK_c213 3
#   define RANK_s221 3
#   define RANK_i222 3
#   define RANK_f223 3
#   define RANK_c231 3
#   define RANK_b232 3
#   define RANK_s233 3
#   define RANK_s311 3
#   define RANK_i312 3
#   define RANK_f313 3
#   define RANK_var_MINUS_name_MINUS_dashes 0
#   define RANK_var_PERIOD_name_PERIOD_dots 0
#   define RANK_var_PLUS_name_PLUS_plusses 0
#   define RANK_var_ATSIGN_name_ATSIGN_ats 0

    /* variable shapes */
    int cr_dims[RANK_cr];
    int br_dims[RANK_br];
    int sr_dims[RANK_sr];
    int ir_dims[RANK_ir];
    int fr_dims[RANK_fr];
    int dr_dims[RANK_dr];
    int c1_dims[RANK_c1];
    int b1_dims[RANK_b1];
    int s1_dims[RANK_s1];
    int i1_dims[RANK_i1];
    int f1_dims[RANK_f1];
    int d1_dims[RANK_d1];
    int c2_dims[RANK_c2];
    int b2_dims[RANK_b2];
    int s2_dims[RANK_s2];
    int i2_dims[RANK_i2];
    int f2_dims[RANK_f2];
    int d2_dims[RANK_d2];
    int c3_dims[RANK_c3];
    int b3_dims[RANK_b3];
    int s3_dims[RANK_s3];
    int i3_dims[RANK_i3];
    int f3_dims[RANK_f3];
    int d3_dims[RANK_d3];
    int cr1_dims[RANK_cr1];
    int br2_dims[RANK_br2];
    int sr3_dims[RANK_sr3];
    int f11_dims[RANK_f11];
    int d12_dims[RANK_d12];
    int c13_dims[RANK_c13];
    int s21_dims[RANK_s21];
    int i22_dims[RANK_i22];
    int f23_dims[RANK_f23];
    int c31_dims[RANK_c31];
    int b32_dims[RANK_b32];
    int s33_dims[RANK_s33];
    int sr11_dims[RANK_sr11];
    int ir12_dims[RANK_ir12];
    int fr13_dims[RANK_fr13];
    int cr21_dims[RANK_cr21];
    int br22_dims[RANK_br22];
    int sr23_dims[RANK_sr23];
    int fr31_dims[RANK_fr31];
    int dr32_dims[RANK_dr32];
    int cr33_dims[RANK_cr33];
    int c111_dims[RANK_c111];
    int b112_dims[RANK_b112];
    int s113_dims[RANK_s113];
    int f121_dims[RANK_f121];
    int d122_dims[RANK_d122];
    int c123_dims[RANK_c123];
    int s131_dims[RANK_s131];
    int i132_dims[RANK_i132];
    int f133_dims[RANK_f133];
    int f211_dims[RANK_f211];
    int d212_dims[RANK_d212];
    int c213_dims[RANK_c213];
    int s221_dims[RANK_s221];
    int i222_dims[RANK_i222];
    int f223_dims[RANK_f223];
    int c231_dims[RANK_c231];
    int b232_dims[RANK_b232];
    int s233_dims[RANK_s233];
    int s311_dims[RANK_s311];
    int i312_dims[RANK_i312];
    int f313_dims[RANK_f313];

    /* enter define mode */
    stat = nc_create("ctest0_64.nc", NC_CLOBBER|NC_64BIT_OFFSET, &ncid);
    check_err(stat,__LINE__,__FILE__);

    /* define dimensions */
    stat = nc_def_dim(ncid, "Dr", Dr_len, &Dr_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "D1", D1_len, &D1_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "D2", D2_len, &D2_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "D3", D3_len, &D3_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "dim-name-dashes", dim_MINUS_name_MINUS_dashes_len, &dim_MINUS_name_MINUS_dashes_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "dim.name.dots", dim_PERIOD_name_PERIOD_dots_len, &dim_PERIOD_name_PERIOD_dots_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "dim+name+plusses", dim_PLUS_name_PLUS_plusses_len, &dim_PLUS_name_PLUS_plusses_dim);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_dim(ncid, "dim@name@ats", dim_ATSIGN_name_ATSIGN_ats_len, &dim_ATSIGN_name_ATSIGN_ats_dim);
    check_err(stat,__LINE__,__FILE__);

    /* define variables */

    stat = nc_def_var(ncid, "c", NC_CHAR, RANK_c, 0, &c_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "b", NC_BYTE, RANK_b, 0, &b_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "s", NC_SHORT, RANK_s, 0, &s_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "i", NC_INT, RANK_i, 0, &i_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "f", NC_FLOAT, RANK_f, 0, &f_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "d", NC_DOUBLE, RANK_d, 0, &d_id);
    check_err(stat,__LINE__,__FILE__);

    cr_dims[0] = Dr_dim;
    stat = nc_def_var(ncid, "cr", NC_CHAR, RANK_cr, cr_dims, &cr_id);
    check_err(stat,__LINE__,__FILE__);

    br_dims[0] = Dr_dim;
    stat = nc_def_var(ncid, "br", NC_BYTE, RANK_br, br_dims, &br_id);
    check_err(stat,__LINE__,__FILE__);

    sr_dims[0] = Dr_dim;
    stat = nc_def_var(ncid, "sr", NC_SHORT, RANK_sr, sr_dims, &sr_id);
    check_err(stat,__LINE__,__FILE__);

    ir_dims[0] = Dr_dim;
    stat = nc_def_var(ncid, "ir", NC_INT, RANK_ir, ir_dims, &ir_id);
    check_err(stat,__LINE__,__FILE__);

    fr_dims[0] = Dr_dim;
    stat = nc_def_var(ncid, "fr", NC_FLOAT, RANK_fr, fr_dims, &fr_id);
    check_err(stat,__LINE__,__FILE__);

    dr_dims[0] = Dr_dim;
    stat = nc_def_var(ncid, "dr", NC_DOUBLE, RANK_dr, dr_dims, &dr_id);
    check_err(stat,__LINE__,__FILE__);

    c1_dims[0] = D1_dim;
    stat = nc_def_var(ncid, "c1", NC_CHAR, RANK_c1, c1_dims, &c1_id);
    check_err(stat,__LINE__,__FILE__);

    b1_dims[0] = D1_dim;
    stat = nc_def_var(ncid, "b1", NC_BYTE, RANK_b1, b1_dims, &b1_id);
    check_err(stat,__LINE__,__FILE__);

    s1_dims[0] = D1_dim;
    stat = nc_def_var(ncid, "s1", NC_SHORT, RANK_s1, s1_dims, &s1_id);
    check_err(stat,__LINE__,__FILE__);

    i1_dims[0] = D1_dim;
    stat = nc_def_var(ncid, "i1", NC_INT, RANK_i1, i1_dims, &i1_id);
    check_err(stat,__LINE__,__FILE__);

    f1_dims[0] = D1_dim;
    stat = nc_def_var(ncid, "f1", NC_FLOAT, RANK_f1, f1_dims, &f1_id);
    check_err(stat,__LINE__,__FILE__);

    d1_dims[0] = D1_dim;
    stat = nc_def_var(ncid, "d1", NC_DOUBLE, RANK_d1, d1_dims, &d1_id);
    check_err(stat,__LINE__,__FILE__);

    c2_dims[0] = D2_dim;
    stat = nc_def_var(ncid, "c2", NC_CHAR, RANK_c2, c2_dims, &c2_id);
    check_err(stat,__LINE__,__FILE__);

    b2_dims[0] = D2_dim;
    stat = nc_def_var(ncid, "b2", NC_BYTE, RANK_b2, b2_dims, &b2_id);
    check_err(stat,__LINE__,__FILE__);

    s2_dims[0] = D2_dim;
    stat = nc_def_var(ncid, "s2", NC_SHORT, RANK_s2, s2_dims, &s2_id);
    check_err(stat,__LINE__,__FILE__);

    i2_dims[0] = D2_dim;
    stat = nc_def_var(ncid, "i2", NC_INT, RANK_i2, i2_dims, &i2_id);
    check_err(stat,__LINE__,__FILE__);

    f2_dims[0] = D2_dim;
    stat = nc_def_var(ncid, "f2", NC_FLOAT, RANK_f2, f2_dims, &f2_id);
    check_err(stat,__LINE__,__FILE__);

    d2_dims[0] = D2_dim;
    stat = nc_def_var(ncid, "d2", NC_DOUBLE, RANK_d2, d2_dims, &d2_id);
    check_err(stat,__LINE__,__FILE__);

    c3_dims[0] = D3_dim;
    stat = nc_def_var(ncid, "c3", NC_CHAR, RANK_c3, c3_dims, &c3_id);
    check_err(stat,__LINE__,__FILE__);

    b3_dims[0] = D3_dim;
    stat = nc_def_var(ncid, "b3", NC_BYTE, RANK_b3, b3_dims, &b3_id);
    check_err(stat,__LINE__,__FILE__);

    s3_dims[0] = D3_dim;
    stat = nc_def_var(ncid, "s3", NC_SHORT, RANK_s3, s3_dims, &s3_id);
    check_err(stat,__LINE__,__FILE__);

    i3_dims[0] = D3_dim;
    stat = nc_def_var(ncid, "i3", NC_INT, RANK_i3, i3_dims, &i3_id);
    check_err(stat,__LINE__,__FILE__);

    f3_dims[0] = D3_dim;
    stat = nc_def_var(ncid, "f3", NC_FLOAT, RANK_f3, f3_dims, &f3_id);
    check_err(stat,__LINE__,__FILE__);

    d3_dims[0] = D3_dim;
    stat = nc_def_var(ncid, "d3", NC_DOUBLE, RANK_d3, d3_dims, &d3_id);
    check_err(stat,__LINE__,__FILE__);

    cr1_dims[0] = Dr_dim;
    cr1_dims[1] = D1_dim;
    stat = nc_def_var(ncid, "cr1", NC_CHAR, RANK_cr1, cr1_dims, &cr1_id);
    check_err(stat,__LINE__,__FILE__);

    br2_dims[0] = Dr_dim;
    br2_dims[1] = D2_dim;
    stat = nc_def_var(ncid, "br2", NC_BYTE, RANK_br2, br2_dims, &br2_id);
    check_err(stat,__LINE__,__FILE__);

    sr3_dims[0] = Dr_dim;
    sr3_dims[1] = D3_dim;
    stat = nc_def_var(ncid, "sr3", NC_SHORT, RANK_sr3, sr3_dims, &sr3_id);
    check_err(stat,__LINE__,__FILE__);

    f11_dims[0] = D1_dim;
    f11_dims[1] = D1_dim;
    stat = nc_def_var(ncid, "f11", NC_FLOAT, RANK_f11, f11_dims, &f11_id);
    check_err(stat,__LINE__,__FILE__);

    d12_dims[0] = D1_dim;
    d12_dims[1] = D2_dim;
    stat = nc_def_var(ncid, "d12", NC_DOUBLE, RANK_d12, d12_dims, &d12_id);
    check_err(stat,__LINE__,__FILE__);

    c13_dims[0] = D1_dim;
    c13_dims[1] = D3_dim;
    stat = nc_def_var(ncid, "c13", NC_CHAR, RANK_c13, c13_dims, &c13_id);
    check_err(stat,__LINE__,__FILE__);

    s21_dims[0] = D2_dim;
    s21_dims[1] = D1_dim;
    stat = nc_def_var(ncid, "s21", NC_SHORT, RANK_s21, s21_dims, &s21_id);
    check_err(stat,__LINE__,__FILE__);

    i22_dims[0] = D2_dim;
    i22_dims[1] = D2_dim;
    stat = nc_def_var(ncid, "i22", NC_INT, RANK_i22, i22_dims, &i22_id);
    check_err(stat,__LINE__,__FILE__);

    f23_dims[0] = D2_dim;
    f23_dims[1] = D3_dim;
    stat = nc_def_var(ncid, "f23", NC_FLOAT, RANK_f23, f23_dims, &f23_id);
    check_err(stat,__LINE__,__FILE__);

    c31_dims[0] = D3_dim;
    c31_dims[1] = D1_dim;
    stat = nc_def_var(ncid, "c31", NC_CHAR, RANK_c31, c31_dims, &c31_id);
    check_err(stat,__LINE__,__FILE__);

    b32_dims[0] = D3_dim;
    b32_dims[1] = D2_dim;
    stat = nc_def_var(ncid, "b32", NC_BYTE, RANK_b32, b32_dims, &b32_id);
    check_err(stat,__LINE__,__FILE__);

    s33_dims[0] = D3_dim;
    s33_dims[1] = D3_dim;
    stat = nc_def_var(ncid, "s33", NC_SHORT, RANK_s33, s33_dims, &s33_id);
    check_err(stat,__LINE__,__FILE__);

    sr11_dims[0] = Dr_dim;
    sr11_dims[1] = D1_dim;
    sr11_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "sr11", NC_SHORT, RANK_sr11, sr11_dims, &sr11_id);
    check_err(stat,__LINE__,__FILE__);

    ir12_dims[0] = Dr_dim;
    ir12_dims[1] = D1_dim;
    ir12_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "ir12", NC_INT, RANK_ir12, ir12_dims, &ir12_id);
    check_err(stat,__LINE__,__FILE__);

    fr13_dims[0] = Dr_dim;
    fr13_dims[1] = D1_dim;
    fr13_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "fr13", NC_FLOAT, RANK_fr13, fr13_dims, &fr13_id);
    check_err(stat,__LINE__,__FILE__);

    cr21_dims[0] = Dr_dim;
    cr21_dims[1] = D2_dim;
    cr21_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "cr21", NC_CHAR, RANK_cr21, cr21_dims, &cr21_id);
    check_err(stat,__LINE__,__FILE__);

    br22_dims[0] = Dr_dim;
    br22_dims[1] = D2_dim;
    br22_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "br22", NC_BYTE, RANK_br22, br22_dims, &br22_id);
    check_err(stat,__LINE__,__FILE__);

    sr23_dims[0] = Dr_dim;
    sr23_dims[1] = D2_dim;
    sr23_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "sr23", NC_SHORT, RANK_sr23, sr23_dims, &sr23_id);
    check_err(stat,__LINE__,__FILE__);

    fr31_dims[0] = Dr_dim;
    fr31_dims[1] = D3_dim;
    fr31_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "fr31", NC_FLOAT, RANK_fr31, fr31_dims, &fr31_id);
    check_err(stat,__LINE__,__FILE__);

    dr32_dims[0] = Dr_dim;
    dr32_dims[1] = D3_dim;
    dr32_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "dr32", NC_DOUBLE, RANK_dr32, dr32_dims, &dr32_id);
    check_err(stat,__LINE__,__FILE__);

    cr33_dims[0] = Dr_dim;
    cr33_dims[1] = D3_dim;
    cr33_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "cr33", NC_CHAR, RANK_cr33, cr33_dims, &cr33_id);
    check_err(stat,__LINE__,__FILE__);

    c111_dims[0] = D1_dim;
    c111_dims[1] = D1_dim;
    c111_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "c111", NC_CHAR, RANK_c111, c111_dims, &c111_id);
    check_err(stat,__LINE__,__FILE__);

    b112_dims[0] = D1_dim;
    b112_dims[1] = D1_dim;
    b112_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "b112", NC_BYTE, RANK_b112, b112_dims, &b112_id);
    check_err(stat,__LINE__,__FILE__);

    s113_dims[0] = D1_dim;
    s113_dims[1] = D1_dim;
    s113_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "s113", NC_SHORT, RANK_s113, s113_dims, &s113_id);
    check_err(stat,__LINE__,__FILE__);

    f121_dims[0] = D1_dim;
    f121_dims[1] = D2_dim;
    f121_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "f121", NC_FLOAT, RANK_f121, f121_dims, &f121_id);
    check_err(stat,__LINE__,__FILE__);

    d122_dims[0] = D1_dim;
    d122_dims[1] = D2_dim;
    d122_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "d122", NC_DOUBLE, RANK_d122, d122_dims, &d122_id);
    check_err(stat,__LINE__,__FILE__);

    c123_dims[0] = D1_dim;
    c123_dims[1] = D2_dim;
    c123_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "c123", NC_CHAR, RANK_c123, c123_dims, &c123_id);
    check_err(stat,__LINE__,__FILE__);

    s131_dims[0] = D1_dim;
    s131_dims[1] = D3_dim;
    s131_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "s131", NC_SHORT, RANK_s131, s131_dims, &s131_id);
    check_err(stat,__LINE__,__FILE__);

    i132_dims[0] = D1_dim;
    i132_dims[1] = D3_dim;
    i132_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "i132", NC_INT, RANK_i132, i132_dims, &i132_id);
    check_err(stat,__LINE__,__FILE__);

    f133_dims[0] = D1_dim;
    f133_dims[1] = D3_dim;
    f133_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "f133", NC_FLOAT, RANK_f133, f133_dims, &f133_id);
    check_err(stat,__LINE__,__FILE__);

    f211_dims[0] = D2_dim;
    f211_dims[1] = D1_dim;
    f211_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "f211", NC_FLOAT, RANK_f211, f211_dims, &f211_id);
    check_err(stat,__LINE__,__FILE__);

    d212_dims[0] = D2_dim;
    d212_dims[1] = D1_dim;
    d212_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "d212", NC_DOUBLE, RANK_d212, d212_dims, &d212_id);
    check_err(stat,__LINE__,__FILE__);

    c213_dims[0] = D2_dim;
    c213_dims[1] = D1_dim;
    c213_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "c213", NC_CHAR, RANK_c213, c213_dims, &c213_id);
    check_err(stat,__LINE__,__FILE__);

    s221_dims[0] = D2_dim;
    s221_dims[1] = D2_dim;
    s221_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "s221", NC_SHORT, RANK_s221, s221_dims, &s221_id);
    check_err(stat,__LINE__,__FILE__);

    i222_dims[0] = D2_dim;
    i222_dims[1] = D2_dim;
    i222_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "i222", NC_INT, RANK_i222, i222_dims, &i222_id);
    check_err(stat,__LINE__,__FILE__);

    f223_dims[0] = D2_dim;
    f223_dims[1] = D2_dim;
    f223_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "f223", NC_FLOAT, RANK_f223, f223_dims, &f223_id);
    check_err(stat,__LINE__,__FILE__);

    c231_dims[0] = D2_dim;
    c231_dims[1] = D3_dim;
    c231_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "c231", NC_CHAR, RANK_c231, c231_dims, &c231_id);
    check_err(stat,__LINE__,__FILE__);

    b232_dims[0] = D2_dim;
    b232_dims[1] = D3_dim;
    b232_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "b232", NC_BYTE, RANK_b232, b232_dims, &b232_id);
    check_err(stat,__LINE__,__FILE__);

    s233_dims[0] = D2_dim;
    s233_dims[1] = D3_dim;
    s233_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "s233", NC_SHORT, RANK_s233, s233_dims, &s233_id);
    check_err(stat,__LINE__,__FILE__);

    s311_dims[0] = D3_dim;
    s311_dims[1] = D1_dim;
    s311_dims[2] = D1_dim;
    stat = nc_def_var(ncid, "s311", NC_SHORT, RANK_s311, s311_dims, &s311_id);
    check_err(stat,__LINE__,__FILE__);

    i312_dims[0] = D3_dim;
    i312_dims[1] = D1_dim;
    i312_dims[2] = D2_dim;
    stat = nc_def_var(ncid, "i312", NC_INT, RANK_i312, i312_dims, &i312_id);
    check_err(stat,__LINE__,__FILE__);

    f313_dims[0] = D3_dim;
    f313_dims[1] = D1_dim;
    f313_dims[2] = D3_dim;
    stat = nc_def_var(ncid, "f313", NC_FLOAT, RANK_f313, f313_dims, &f313_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "var-name-dashes", NC_DOUBLE, RANK_var_MINUS_name_MINUS_dashes, 0, &var_MINUS_name_MINUS_dashes_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "var.name.dots", NC_DOUBLE, RANK_var_PERIOD_name_PERIOD_dots, 0, &var_PERIOD_name_PERIOD_dots_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "var+name+plusses", NC_DOUBLE, RANK_var_PLUS_name_PLUS_plusses, 0, &var_PLUS_name_PLUS_plusses_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(ncid, "var@name@ats", NC_DOUBLE, RANK_var_ATSIGN_name_ATSIGN_ats, 0, &var_ATSIGN_name_ATSIGN_ats_id);
    check_err(stat,__LINE__,__FILE__);

    /* assign global attributes */

    {
    stat = nc_put_att_text(ncid, NC_GLOBAL, "Gc", 1, "");
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const signed char c0_Gb_att[2] = {-128, 127} ;
    stat = nc_put_att_schar(ncid, NC_GLOBAL, "Gb", NC_BYTE, 2, c0_Gb_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const short c0_Gs_att[3] = {-32768, 0, 32767} ;
    stat = nc_put_att_short(ncid, NC_GLOBAL, "Gs", NC_SHORT, 3, c0_Gs_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_Gi_att[3] = {-2147483647, 0, 2147483647} ;
    stat = nc_put_att_int(ncid, NC_GLOBAL, "Gi", NC_INT, 3, c0_Gi_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const float c0_Gf_att[3] = {((float)-9.9999996e+35), ((float)0), ((float)9.9999996e+35)} ;
    stat = nc_put_att_float(ncid, NC_GLOBAL, "Gf", NC_FLOAT, 3, c0_Gf_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const double c0_Gd_att[3] = {((double)-1e+308), ((double)0), ((double)1e+308)} ;
    stat = nc_put_att_double(ncid, NC_GLOBAL, "Gd", NC_DOUBLE, 3, c0_Gd_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_Gatt_MINUS_name_MINUS_dashes_att[1] = {-1} ;
    stat = nc_put_att_int(ncid, NC_GLOBAL, "Gatt-name-dashes", NC_INT, 1, c0_Gatt_MINUS_name_MINUS_dashes_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_Gatt_DOT_name_DOT_dots_att[1] = {-2} ;
    stat = nc_put_att_int(ncid, NC_GLOBAL, "Gatt.name.dots", NC_INT, 1, c0_Gatt_DOT_name_DOT_dots_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_Gatt_PLUS_name_PLUS_plusses_att[1] = {-3} ;
    stat = nc_put_att_int(ncid, NC_GLOBAL, "Gatt+name+plusses", NC_INT, 1, c0_Gatt_PLUS_name_PLUS_plusses_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_Gatt_ATSIGN_name_ATSIGN_ats_att[1] = {-4} ;
    stat = nc_put_att_int(ncid, NC_GLOBAL, "Gatt@name@ats", NC_INT, 1, c0_Gatt_ATSIGN_name_ATSIGN_ats_att);
    check_err(stat,__LINE__,__FILE__);
    }


    /* assign per-variable attributes */

    {
    static const int c0_att_MINUS_name_MINUS_dashes_att[1] = {4} ;
    stat = nc_put_att_int(ncid, c_id, "att-name-dashes", NC_INT, 1, c0_att_MINUS_name_MINUS_dashes_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_att_DOT_name_DOT_dots_att[1] = {5} ;
    stat = nc_put_att_int(ncid, c_id, "att.name.dots", NC_INT, 1, c0_att_DOT_name_DOT_dots_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_att_PLUS_name_PLUS_plusses_att[1] = {6} ;
    stat = nc_put_att_int(ncid, c_id, "att+name+plusses", NC_INT, 1, c0_att_PLUS_name_PLUS_plusses_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_att_ATSIGN_name_ATSIGN_ats_att[1] = {7} ;
    stat = nc_put_att_int(ncid, c_id, "att@name@ats", NC_INT, 1, c0_att_ATSIGN_name_ATSIGN_ats_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    stat = nc_put_att_text(ncid, b_id, "c", 1, "");
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const signed char c0_b_att[4] = {0, 127, -128, -1} ;
    stat = nc_put_att_schar(ncid, s_id, "b", NC_BYTE, 4, c0_b_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const short c0_s_att[3] = {-32768, 0, 32767} ;
    stat = nc_put_att_short(ncid, s_id, "s", NC_SHORT, 3, c0_s_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const int c0_i_att[3] = {-2147483647, 0, 2147483647} ;
    stat = nc_put_att_int(ncid, i_id, "i", NC_INT, 3, c0_i_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const float c0_f_att[3] = {((float)-9.9999996e+35), ((float)0), ((float)9.9999996e+35)} ;
    stat = nc_put_att_float(ncid, i_id, "f", NC_FLOAT, 3, c0_f_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    static const double c0_d_att[3] = {((double)-1e+308), ((double)0), ((double)1e+308)} ;
    stat = nc_put_att_double(ncid, i_id, "d", NC_DOUBLE, 3, c0_d_att);
    check_err(stat,__LINE__,__FILE__);
    }

    {
    stat = nc_put_att_text(ncid, f_id, "c", 1, "x");
    check_err(stat,__LINE__,__FILE__);
    }

    {
    stat = nc_put_att_text(ncid, d_id, "c", 8, "abcd\tZ$&");
    check_err(stat,__LINE__,__FILE__);
    }


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

    /* assign variable data */

    {
    size_t count = 0;
    static char c_data[1] = {'2'};
    stat = nc_put_var1(ncid, c_id, &count, c_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static signed char b_data[1] = {-2};
    stat = nc_put_var1(ncid, b_id, &count, b_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static short s_data[1] = {-5};
    stat = nc_put_var1(ncid, s_id, &count, s_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static int i_data[1] = {-20};
    stat = nc_put_var1(ncid, i_id, &count, i_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static float f_data[1] = {((float)-9)};
    stat = nc_put_var1(ncid, f_id, &count, f_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static double d_data[1] = {((double)-10)};
    stat = nc_put_var1(ncid, d_id, &count, d_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* cr_data = "ab\000\000" ;
    size_t cr_startset[1] = {0} ;
    size_t cr_countset[1] = {2};
    stat = nc_put_vara(ncid, cr_id, cr_startset, cr_countset, cr_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char br_data[2] = {-128, 127} ;
    size_t br_startset[1] = {0} ;
    size_t br_countset[1] = {2};
    stat = nc_put_vara(ncid, br_id, br_startset, br_countset, br_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short sr_data[2] = {-32768, 32767} ;
    size_t sr_startset[1] = {0} ;
    size_t sr_countset[1] = {2};
    stat = nc_put_vara(ncid, sr_id, sr_startset, sr_countset, sr_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int ir_data[2] = {-2147483646, 2147483647} ;
    size_t ir_startset[1] = {0} ;
    size_t ir_countset[1] = {2};
    stat = nc_put_vara(ncid, ir_id, ir_startset, ir_countset, ir_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float fr_data[2] = {((float)-9.9999996e+35), ((float)9.9999996e+35)} ;
    size_t fr_startset[1] = {0} ;
    size_t fr_countset[1] = {2};
    stat = nc_put_vara(ncid, fr_id, fr_startset, fr_countset, fr_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double dr_data[2] = {((double)-1e+308), ((double)1e+308)} ;
    size_t dr_startset[1] = {0} ;
    size_t dr_countset[1] = {2};
    stat = nc_put_vara(ncid, dr_id, dr_startset, dr_countset, dr_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c1_data = "\000" ;
    size_t c1_startset[1] = {0} ;
    size_t c1_countset[1] = {1};
    stat = nc_put_vara(ncid, c1_id, c1_startset, c1_countset, c1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char b1_data[1] = {-128} ;
    size_t b1_startset[1] = {0} ;
    size_t b1_countset[1] = {1};
    stat = nc_put_vara(ncid, b1_id, b1_startset, b1_countset, b1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s1_data[1] = {-32768} ;
    size_t s1_startset[1] = {0} ;
    size_t s1_countset[1] = {1};
    stat = nc_put_vara(ncid, s1_id, s1_startset, s1_countset, s1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i1_data[1] = {-2147483646} ;
    size_t i1_startset[1] = {0} ;
    size_t i1_countset[1] = {1};
    stat = nc_put_vara(ncid, i1_id, i1_startset, i1_countset, i1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f1_data[1] = {((float)-9.9999996e+35)} ;
    size_t f1_startset[1] = {0} ;
    size_t f1_countset[1] = {1};
    stat = nc_put_vara(ncid, f1_id, f1_startset, f1_countset, f1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double d1_data[1] = {((double)-1e+308)} ;
    size_t d1_startset[1] = {0} ;
    size_t d1_countset[1] = {1};
    stat = nc_put_vara(ncid, d1_id, d1_startset, d1_countset, d1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c2_data = "ab\000\000" ;
    size_t c2_startset[1] = {0} ;
    size_t c2_countset[1] = {2};
    stat = nc_put_vara(ncid, c2_id, c2_startset, c2_countset, c2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char b2_data[2] = {-128, 127} ;
    size_t b2_startset[1] = {0} ;
    size_t b2_countset[1] = {2};
    stat = nc_put_vara(ncid, b2_id, b2_startset, b2_countset, b2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s2_data[2] = {-32768, 32767} ;
    size_t s2_startset[1] = {0} ;
    size_t s2_countset[1] = {2};
    stat = nc_put_vara(ncid, s2_id, s2_startset, s2_countset, s2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i2_data[2] = {-2147483646, 2147483647} ;
    size_t i2_startset[1] = {0} ;
    size_t i2_countset[1] = {2};
    stat = nc_put_vara(ncid, i2_id, i2_startset, i2_countset, i2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f2_data[2] = {((float)-9.9999996e+35), ((float)9.9999996e+35)} ;
    size_t f2_startset[1] = {0} ;
    size_t f2_countset[1] = {2};
    stat = nc_put_vara(ncid, f2_id, f2_startset, f2_countset, f2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double d2_data[2] = {((double)-1e+308), ((double)1e+308)} ;
    size_t d2_startset[1] = {0} ;
    size_t d2_countset[1] = {2};
    stat = nc_put_vara(ncid, d2_id, d2_startset, d2_countset, d2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c3_data = "\001À.\000\000\000\000\000\000" ;
    size_t c3_startset[1] = {0} ;
    size_t c3_countset[1] = {3};
    stat = nc_put_vara(ncid, c3_id, c3_startset, c3_countset, c3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char b3_data[3] = {-128, 127, -1} ;
    size_t b3_startset[1] = {0} ;
    size_t b3_countset[1] = {3};
    stat = nc_put_vara(ncid, b3_id, b3_startset, b3_countset, b3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s3_data[3] = {-32768, 0, 32767} ;
    size_t s3_startset[1] = {0} ;
    size_t s3_countset[1] = {3};
    stat = nc_put_vara(ncid, s3_id, s3_startset, s3_countset, s3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i3_data[3] = {-2147483646, 0, 2147483647} ;
    size_t i3_startset[1] = {0} ;
    size_t i3_countset[1] = {3};
    stat = nc_put_vara(ncid, i3_id, i3_startset, i3_countset, i3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f3_data[3] = {((float)-9.9999996e+35), ((float)0), ((float)9.9999996e+35)} ;
    size_t f3_startset[1] = {0} ;
    size_t f3_countset[1] = {3};
    stat = nc_put_vara(ncid, f3_id, f3_startset, f3_countset, f3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double d3_data[3] = {((double)-1e+308), ((double)0), ((double)1e+308)} ;
    size_t d3_startset[1] = {0} ;
    size_t d3_countset[1] = {3};
    stat = nc_put_vara(ncid, d3_id, d3_startset, d3_countset, d3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* cr1_data = "xy" ;
    size_t cr1_startset[2] = {0, 0} ;
    size_t cr1_countset[2] = {2, 1};
    stat = nc_put_vara(ncid, cr1_id, cr1_startset, cr1_countset, cr1_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char br2_data[4] = {-24, -26, -20, -22} ;
    size_t br2_startset[2] = {0, 0} ;
    size_t br2_countset[2] = {2, 2};
    stat = nc_put_vara(ncid, br2_id, br2_startset, br2_countset, br2_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short sr3_data[6] = {-375, -380, -385, -350, -355, -360} ;
    size_t sr3_startset[2] = {0, 0} ;
    size_t sr3_countset[2] = {2, 3};
    stat = nc_put_vara(ncid, sr3_id, sr3_startset, sr3_countset, sr3_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f11_data[1] = {((float)-2187)} ;
    size_t f11_startset[2] = {0, 0} ;
    size_t f11_countset[2] = {1, 1};
    stat = nc_put_vara(ncid, f11_id, f11_startset, f11_countset, f11_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double d12_data[2] = {((double)-3000), ((double)-3010)} ;
    size_t d12_startset[2] = {0, 0} ;
    size_t d12_countset[2] = {1, 2};
    stat = nc_put_vara(ncid, d12_id, d12_startset, d12_countset, d12_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c13_data = "\tb\177" ;
    size_t c13_startset[2] = {0, 0} ;
    size_t c13_countset[2] = {1, 3};
    stat = nc_put_vara(ncid, c13_id, c13_startset, c13_countset, c13_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s21_data[2] = {-375, -350} ;
    size_t s21_startset[2] = {0, 0} ;
    size_t s21_countset[2] = {2, 1};
    stat = nc_put_vara(ncid, s21_id, s21_startset, s21_countset, s21_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i22_data[4] = {-24000, -24020, -23600, -23620} ;
    size_t i22_startset[2] = {0, 0} ;
    size_t i22_countset[2] = {2, 2};
    stat = nc_put_vara(ncid, i22_id, i22_startset, i22_countset, i22_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f23_data[6] = {((float)-2187), ((float)-2196), ((float)-2205), ((float)-2106), ((float)-2115), ((float)-2124)} ;
    size_t f23_startset[2] = {0, 0} ;
    size_t f23_countset[2] = {2, 3};
    stat = nc_put_vara(ncid, f23_id, f23_startset, f23_countset, f23_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c31_data = "+- " ;
    size_t c31_startset[2] = {0, 0} ;
    size_t c31_countset[2] = {3, 1};
    stat = nc_put_vara(ncid, c31_id, c31_startset, c31_countset, c31_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char b32_data[6] = {-24, -26, -20, -22, -16, -18} ;
    size_t b32_startset[2] = {0, 0} ;
    size_t b32_countset[2] = {3, 2};
    stat = nc_put_vara(ncid, b32_id, b32_startset, b32_countset, b32_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s33_data[9] = {-375, -380, -385, -350, -355, -360, -325, -330, -335} ;
    size_t s33_startset[2] = {0, 0} ;
    size_t s33_countset[2] = {3, 3};
    stat = nc_put_vara(ncid, s33_id, s33_startset, s33_countset, s33_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short sr11_data[2] = {2500, 2375} ;
    size_t sr11_startset[3] = {0, 0, 0} ;
    size_t sr11_countset[3] = {2, 1, 1};
    stat = nc_put_vara(ncid, sr11_id, sr11_startset, sr11_countset, sr11_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int ir12_data[4] = {640000, 639980, 632000, 631980} ;
    size_t ir12_startset[3] = {0, 0, 0} ;
    size_t ir12_countset[3] = {2, 1, 2};
    stat = nc_put_vara(ncid, ir12_id, ir12_startset, ir12_countset, ir12_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float fr13_data[6] = {((float)26244), ((float)26235), ((float)26226), ((float)25515), ((float)25506), ((float)25497)} ;
    size_t fr13_startset[3] = {0, 0, 0} ;
    size_t fr13_countset[3] = {2, 1, 3};
    stat = nc_put_vara(ncid, fr13_id, fr13_startset, fr13_countset, fr13_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* cr21_data = "@DHL" ;
    size_t cr21_startset[3] = {0, 0, 0} ;
    size_t cr21_countset[3] = {2, 2, 1};
    stat = nc_put_vara(ncid, cr21_id, cr21_startset, cr21_countset, cr21_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char br22_data[8] = {64, 62, 68, 66, 56, 54, 60, 58} ;
    size_t br22_startset[3] = {0, 0, 0} ;
    size_t br22_countset[3] = {2, 2, 2};
    stat = nc_put_vara(ncid, br22_id, br22_startset, br22_countset, br22_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short sr23_data[12] = {2500, 2495, 2490, 2525, 2520, 2515, 2375, 2370, 2365, 2400, 2395, 2390} ;
    size_t sr23_startset[3] = {0, 0, 0} ;
    size_t sr23_countset[3] = {2, 2, 3};
    stat = nc_put_vara(ncid, sr23_id, sr23_startset, sr23_countset, sr23_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float fr31_data[6] = {((float)26244), ((float)26325), ((float)26406), ((float)25515), ((float)25596), ((float)25677)} ;
    size_t fr31_startset[3] = {0, 0, 0} ;
    size_t fr31_countset[3] = {2, 3, 1};
    stat = nc_put_vara(ncid, fr31_id, fr31_startset, fr31_countset, fr31_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double dr32_data[12] = {((double)40000), ((double)39990), ((double)40100), ((double)40090), ((double)40200), ((double)40190), ((double)39000), ((double)38990), ((double)39100), ((double)39090), ((double)39200), ((double)39190)} ;
    size_t dr32_startset[3] = {0, 0, 0} ;
    size_t dr32_countset[3] = {2, 3, 2};
    stat = nc_put_vara(ncid, dr32_id, dr32_startset, dr32_countset, dr32_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* cr33_data = "1\000\000two3\000\0004\000\0005\000\000six" ;
    size_t cr33_startset[3] = {0, 0, 0} ;
    size_t cr33_countset[3] = {2, 3, 3};
    stat = nc_put_vara(ncid, cr33_id, cr33_startset, cr33_countset, cr33_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c111_data = "@" ;
    size_t c111_startset[3] = {0, 0, 0} ;
    size_t c111_countset[3] = {1, 1, 1};
    stat = nc_put_vara(ncid, c111_id, c111_startset, c111_countset, c111_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char b112_data[2] = {64, 62} ;
    size_t b112_startset[3] = {0, 0, 0} ;
    size_t b112_countset[3] = {1, 1, 2};
    stat = nc_put_vara(ncid, b112_id, b112_startset, b112_countset, b112_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s113_data[3] = {2500, 2495, 2490} ;
    size_t s113_startset[3] = {0, 0, 0} ;
    size_t s113_countset[3] = {1, 1, 3};
    stat = nc_put_vara(ncid, s113_id, s113_startset, s113_countset, s113_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f121_data[2] = {((float)26244), ((float)26325)} ;
    size_t f121_startset[3] = {0, 0, 0} ;
    size_t f121_countset[3] = {1, 2, 1};
    stat = nc_put_vara(ncid, f121_id, f121_startset, f121_countset, f121_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double d122_data[4] = {((double)40000), ((double)39990), ((double)40100), ((double)40090)} ;
    size_t d122_startset[3] = {0, 0, 0} ;
    size_t d122_countset[3] = {1, 2, 2};
    stat = nc_put_vara(ncid, d122_id, d122_startset, d122_countset, d122_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c123_data = "one2\000\000" ;
    size_t c123_startset[3] = {0, 0, 0} ;
    size_t c123_countset[3] = {1, 2, 3};
    stat = nc_put_vara(ncid, c123_id, c123_startset, c123_countset, c123_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s131_data[3] = {2500, 2525, 2550} ;
    size_t s131_startset[3] = {0, 0, 0} ;
    size_t s131_countset[3] = {1, 3, 1};
    stat = nc_put_vara(ncid, s131_id, s131_startset, s131_countset, s131_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i132_data[6] = {640000, 639980, 640400, 640380, 640800, 640780} ;
    size_t i132_startset[3] = {0, 0, 0} ;
    size_t i132_countset[3] = {1, 3, 2};
    stat = nc_put_vara(ncid, i132_id, i132_startset, i132_countset, i132_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f133_data[9] = {((float)26244), ((float)26235), ((float)26226), ((float)26325), ((float)26316), ((float)26307), ((float)26406), ((float)26397), ((float)26388)} ;
    size_t f133_startset[3] = {0, 0, 0} ;
    size_t f133_countset[3] = {1, 3, 3};
    stat = nc_put_vara(ncid, f133_id, f133_startset, f133_countset, f133_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f211_data[2] = {((float)26244), ((float)25515)} ;
    size_t f211_startset[3] = {0, 0, 0} ;
    size_t f211_countset[3] = {2, 1, 1};
    stat = nc_put_vara(ncid, f211_id, f211_startset, f211_countset, f211_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    double d212_data[4] = {((double)40000), ((double)39990), ((double)39000), ((double)38990)} ;
    size_t d212_startset[3] = {0, 0, 0} ;
    size_t d212_countset[3] = {2, 1, 2};
    stat = nc_put_vara(ncid, d212_id, d212_startset, d212_countset, d212_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c213_data = "\000\000\000\000\000\000" ;
    size_t c213_startset[3] = {0, 0, 0} ;
    size_t c213_countset[3] = {2, 1, 3};
    stat = nc_put_vara(ncid, c213_id, c213_startset, c213_countset, c213_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s221_data[4] = {2500, 2525, 2375, 2400} ;
    size_t s221_startset[3] = {0, 0, 0} ;
    size_t s221_countset[3] = {2, 2, 1};
    stat = nc_put_vara(ncid, s221_id, s221_startset, s221_countset, s221_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i222_data[8] = {640000, 639980, 640400, 640380, 632000, 631980, 632400, 632380} ;
    size_t i222_startset[3] = {0, 0, 0} ;
    size_t i222_countset[3] = {2, 2, 2};
    stat = nc_put_vara(ncid, i222_id, i222_startset, i222_countset, i222_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f223_data[12] = {((float)26244), ((float)26235), ((float)26226), ((float)26325), ((float)26316), ((float)26307), ((float)25515), ((float)25506), ((float)25497), ((float)25596), ((float)25587), ((float)25578)} ;
    size_t f223_startset[3] = {0, 0, 0} ;
    size_t f223_countset[3] = {2, 2, 3};
    stat = nc_put_vara(ncid, f223_id, f223_startset, f223_countset, f223_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    char* c231_data = "@DHHLP" ;
    size_t c231_startset[3] = {0, 0, 0} ;
    size_t c231_countset[3] = {2, 3, 1};
    stat = nc_put_vara(ncid, c231_id, c231_startset, c231_countset, c231_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    signed char b232_data[12] = {64, 62, 68, 66, 72, 70, 56, 54, 60, 58, 64, 62} ;
    size_t b232_startset[3] = {0, 0, 0} ;
    size_t b232_countset[3] = {2, 3, 2};
    stat = nc_put_vara(ncid, b232_id, b232_startset, b232_countset, b232_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s233_data[18] = {2500, 2495, 2490, 2525, 2520, 2515, 2550, 2545, 2540, 2375, 2370, 2365, 2400, 2395, 2390, 2425, 2420, 2415} ;
    size_t s233_startset[3] = {0, 0, 0} ;
    size_t s233_countset[3] = {2, 3, 3};
    stat = nc_put_vara(ncid, s233_id, s233_startset, s233_countset, s233_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    short s311_data[3] = {2500, 2375, 2250} ;
    size_t s311_startset[3] = {0, 0, 0} ;
    size_t s311_countset[3] = {3, 1, 1};
    stat = nc_put_vara(ncid, s311_id, s311_startset, s311_countset, s311_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    int i312_data[6] = {640000, 639980, 632000, 631980, 624000, 623980} ;
    size_t i312_startset[3] = {0, 0, 0} ;
    size_t i312_countset[3] = {3, 1, 2};
    stat = nc_put_vara(ncid, i312_id, i312_startset, i312_countset, i312_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    float f313_data[9] = {((float)26244), ((float)26235), ((float)26226), ((float)25515), ((float)25506), ((float)25497), ((float)24786), ((float)24777), ((float)24768)} ;
    size_t f313_startset[3] = {0, 0, 0} ;
    size_t f313_countset[3] = {3, 1, 3};
    stat = nc_put_vara(ncid, f313_id, f313_startset, f313_countset, f313_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static double var_MINUS_name_MINUS_dashes_data[1] = {((double)-1)};
    stat = nc_put_var1(ncid, var_MINUS_name_MINUS_dashes_id, &count, var_MINUS_name_MINUS_dashes_data);
    check_err(stat,__LINE__,__FILE__);
    }


    {
    size_t count = 0;
    static double var_PERIOD_name_PERIOD_dots_data[1] = {((double)-2)};
    stat = nc_put_var1(ncid, var_PERIOD_name_PERIOD_dots_id, &count, var_PERIOD_name_PERIOD_dots_data);
    check_err(stat,__LINE__,__FILE__);
    }


    stat = nc_close(ncid);
    check_err(stat,__LINE__,__FILE__);
    return 0;
}
Exemplo n.º 11
0
void write_output(char out_file[], char in_file[][FILE_NAME_SZ], char depth_file[],
     size_t nz, char var_names[MAX_VARS][NC_MAX_NAME], char time_names[2][NC_MAX_NAME], 
     char depth_names[2][NC_MAX_NAME], int *num_var,
     char arglist[]) {
  int i, j, v;
  int ncid, nc_den_id, status, ndims, ndim, nvariables, ngatt, recdim;
  int use_dim[NC_MAX_DIMS];
  int dv_id[NC_MAX_DIMS], dim2id[NC_MAX_DIMS], dim2vid[NC_MAX_DIMS];
  int dimids[NC_MAX_VAR_DIMS], dd2id[2];
  int ddvid[2], dd2vid[2];
  int num_att;
  int use_file[MAX_FILES], max_file;
  char dim_name[10][NC_MAX_NAME];
  char att_name[NC_MAX_NAME];
  nc_type xtype;

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

    free(coord_array);
  }

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

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

  nc_close(nc_den_id);
}
Exemplo n.º 12
0
static inline void setAttrDouble(int ncid,int varid,const char *key,double *val){
    int ret;
    if(NC_NOERR!=(ret=nc_put_att_double(ncid,varid,key,NC_DOUBLE,1,val)))
	nc_error(ret,__LINE__);
}
Exemplo n.º 13
0
int
main(int argc, char **argv)
{
    int ncid, dimid, fvarid, dvarid;
    int dimids[NDIMS];
    float fvals[NVALS], fvals_in[NVALS];
    double dvals[NVALS], dvals_in[NVALS];

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

#ifdef USE_PARALLEL
   MPI_Init(&argc, &argv);
#endif
    printf("*** creating NaN test file %s...", FILE8_NAME);
    if (nc_create(FILE8_NAME, NC_CLOBBER, &ncid)) ERR;
    
    if (nc_def_dim(ncid, DIM_NAME, NVALS, &dimid)) ERR;
    dimids[0] = dimid;
    
    if (nc_def_var(ncid, F_NAME, NC_FLOAT, NDIMS, NULL, &fvarid)) ERR;
    if (nc_def_var(ncid, D_NAME, NC_DOUBLE, NDIMS, NULL, &dvarid)) ERR;

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

   if (nc_close(ncid)) ERR;
   
   SUMMARIZE_ERR;
   FINAL_RESULTS;
#ifdef USE_PARALLEL
   MPI_Finalize();
#endif   

   printf("*** SUCCESS writing example file tst_nans.nc!\n");
   return 0;
}
Exemplo n.º 14
0
/* create netCDF from in-memory structure */
static void
gen_netcdf(
     char *filename)		/* name for output netcdf file */
{
    int idim, ivar, iatt;
    int dimid;
    int varid;
    int stat;

    stat = nc_create(filename, cmode_modifier, &ncid);
    check_err(stat);

    /* define dimensions from info in dims array */
    for (idim = 0; idim < ndims; idim++) {
	stat = nc_def_dim(ncid, dims[idim].name, dims[idim].size, &dimid);
	check_err(stat);
    }

    /* define variables from info in vars array */
    for (ivar = 0; ivar < nvars; ivar++) {
	stat = nc_def_var(ncid,
			  vars[ivar].name,
			  vars[ivar].type,
			  vars[ivar].ndims,
			  vars[ivar].dims,
			  &varid);
	check_err(stat);
    }

    /* define attributes from info in atts array */
    for (iatt = 0; iatt < natts; iatt++) {
	varid = (atts[iatt].var == -1) ? NC_GLOBAL : atts[iatt].var;
	switch(atts[iatt].type) {
	case NC_BYTE:
	    stat = nc_put_att_schar(ncid, varid, atts[iatt].name,
				    atts[iatt].type, atts[iatt].len,
				    (signed char *) atts[iatt].val);
	    break;
	case NC_CHAR:
	    stat = nc_put_att_text(ncid, varid, atts[iatt].name,
				   atts[iatt].len,
				   (char *) atts[iatt].val);
	    break;
	case NC_SHORT:
	    stat = nc_put_att_short(ncid, varid, atts[iatt].name,
				    atts[iatt].type, atts[iatt].len,
				    (short *) atts[iatt].val);
	    break;
	case NC_INT:
	    stat = nc_put_att_int(ncid, varid, atts[iatt].name,
				    atts[iatt].type, atts[iatt].len,
				    (int *) atts[iatt].val);
	    break;
	case NC_FLOAT:
	    stat = nc_put_att_float(ncid, varid, atts[iatt].name,
				    atts[iatt].type, atts[iatt].len,
				    (float *) atts[iatt].val);
	    break;
	case NC_DOUBLE:
	    stat = nc_put_att_double(ncid, varid, atts[iatt].name,
				    atts[iatt].type, atts[iatt].len,
				    (double *) atts[iatt].val);
	    break;
	default:
	    stat = NC_EBADTYPE;
	}
	check_err(stat);
    }

    if (nofill_flag) {
	stat = nc_set_fill(ncid, NC_NOFILL, 0);	/* don't initialize with fill values */
	check_err(stat);
    }

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

	MPI_Init(&argc, &argv);

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

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

	createtestvars(id, testvars, NUM_TESTVARS); 

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

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

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

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

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

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

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

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

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

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

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


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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	MPI_Finalize();
	return 0;
}
Exemplo n.º 16
0
/*******************************************************************************
  Function name: CreateMapFileNetCDF()

  Purpose      : Open and close a new file.  If the file already exists it 
                 will be overwritten.

  Required     : 
    FileName  - Name of the new file
    FileLabel - String describing file contents
    Map       - structure with information about spatial extent of model area

  Returns      : void

  Modifies     : 

  Comments     : NetCDF defines all the dimensions in the file before the file 
                 can be written to.  By default it creates the entire file
		 during when nc_endef() is called and fills all positions with
		 _FillValue.  This behavior is turned off here to speed up the
		 initialization process by or'ing  the  NC_NOFILL  flag  into
		 the  mode parameter of nc_create() 
*******************************************************************************/
void CreateMapFileNetCDF(char *FileName, ...)
{
  const char *Routine = "CreateMapFileNetCDF";
  va_list ap;
  MAPSIZE *Map = NULL;		/* pointer to structure with map info */
  char *FileLabel;		/* File label */
  double *Array;
  double missing_value[1];
  char *ptrstr[1];
  int x;
  int y;
  int varideast;
  int varidnorth;
  int varidtime;
  int ncstatus;
  int ncid;
  int dimids[3];		/* time, north, east */

  /****************************************************************************/
  /*                     HANDLE VARIABLE ARGUMENT LIST                        */
  /****************************************************************************/

  va_start(ap, FileName);
  FileLabel = va_arg(ap, char *);
  Map = va_arg(ap, MAPSIZE *);

  /* Go ahead and clobber any existing file */
  ncstatus = nc_create(FileName, NC_CLOBBER | NC_NOFILL, &ncid);
  nc_check_err(ncstatus, __LINE__, __FILE__);

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

  ncstatus = nc_def_dim(ncid, TIME_DIM, NC_UNLIMITED, &dimids[0]);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_def_dim(ncid, Y_DIM, Map->NY, &dimids[1]);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_def_dim(ncid, X_DIM, Map->NX, &dimids[2]);
  nc_check_err(ncstatus, __LINE__, __FILE__);

  /* Define dimension variables and their attributes */
  /* time */
  ncstatus = nc_def_var(ncid, TIME_DIM, NC_DOUBLE, 1, &dimids[0], &varidtime);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varidtime, ATT_NAME, strlen(TIME_DIM),
			     TIME_DIM);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varidtime, ATT_LONGNAME, strlen(TIME_DIM),
			     TIME_DIM);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varidtime, ATT_UNITS, strlen("index"),
			     "index");
  nc_check_err(ncstatus, __LINE__, __FILE__);
/*   ncstatus = nc_put_att_text(ncid, varidtime, ATT_FORMAT, strlen("%g"), "%g"); */
/*   nc_check_err(ncstatus, __LINE__, __FILE__); */

  /* northing */
  ncstatus = nc_def_var(ncid, Y_DIM, NC_DOUBLE, 1, &dimids[1], &varidnorth);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varidnorth, ATT_NAME, strlen(Y_DIM), Y_DIM);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus =
    nc_put_att_text(ncid, varidnorth, ATT_LONGNAME, strlen("Northing"),
		    "Northing");
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varidnorth, ATT_UNITS, strlen("m"), "m");
  nc_check_err(ncstatus, __LINE__, __FILE__);
/*   ncstatus = nc_put_att_text(ncid, varidnorth, ATT_FORMAT, strlen("%g"), "%g"); */
/*   nc_check_err(ncstatus, __LINE__, __FILE__); */

  /* easting */
  ncstatus = nc_def_var(ncid, X_DIM, NC_DOUBLE, 1, &dimids[2], &varideast);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varideast, ATT_NAME, strlen(X_DIM), X_DIM);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varideast, ATT_LONGNAME, strlen("Easting"),
			     "Easting");
  nc_check_err(ncstatus, __LINE__, __FILE__);
  ncstatus = nc_put_att_text(ncid, varideast, ATT_UNITS, strlen("m"), "m");
  nc_check_err(ncstatus, __LINE__, __FILE__);
/*   ncstatus = nc_put_att_text(ncid, varideast, ATT_FORMAT, strlen("%g"), "%g"); */
/*   nc_check_err(ncstatus, __LINE__, __FILE__); */

  /* Update the history attribute */
  ptrstr[0] = commandline;
  ncstatus = ncUpdateGlobalHistory(1, ptrstr, ncid);
  nc_check_err(ncstatus, __LINE__, __FILE__);

  /* Insert the file label and other global attributes */
  ncstatus = nc_put_att_text(ncid, NC_GLOBAL, ATT_COMMENT, strlen(FileLabel),
			     FileLabel);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  missing_value[0] = NA;
  ncstatus = nc_put_att_double(ncid, NC_GLOBAL, ATT_MISSINGVALUE, NC_DOUBLE, 1,
			       missing_value);
  nc_check_err(ncstatus, __LINE__, __FILE__);

  /* exit the define mode */
  ncstatus = nc_enddef(ncid);
  nc_check_err(ncstatus, __LINE__, __FILE__);

  /****************************************************************************/
  /*              WRITE X AND Y DIMENSIONS TO THE OUTPUT FILE                 */
  /****************************************************************************/

  Array = (double *) calloc(Map->NX, sizeof(double));
  if (Array == NULL)
    ReportError((char *) Routine, 1);
  for (x = 0; x < Map->NX; x++)
    Array[x] = Map->Xorig + x * Map->DX;
  ncstatus = nc_put_var_double(ncid, varideast, Array);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  free(Array);

  Array = (double *) calloc(Map->NY, sizeof(double));
  if (Array == NULL)
    ReportError((char *) Routine, 1);
  for (y = 0; y < Map->NY; y++)
    Array[y] = Map->Yorig - y * Map->DY;
  ncstatus = nc_put_var_double(ncid, varidnorth, Array);
  nc_check_err(ncstatus, __LINE__, __FILE__);
  free(Array);

  ncstatus = nc_close(ncid);
  nc_check_err(ncstatus, __LINE__, __FILE__);
}
Exemplo n.º 17
0
int
main() {/* create tst_diskless2.nc */

    int  stat;  /* return status */
    int  ncid;  /* netCDF id */

    /* group ids */
    int root_grp;
    int g_grp;
    int h_grp;

    /* type ids */
    int enum_t_typ;
    int opaque_t_typ;
    int vlen_t_typ;
    int g_cmpd_t_typ;

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

    /* dimension lengths */
    size_t lat_len = 10;
    size_t lon_len = 5;
    size_t time_len = NC_UNLIMITED;

    /* variable ids */
    int lat_id;
    int lon_id;
    int time_id;
    int Z_id;
    int t_id;
    int p_id;
    int rh_id;
    int country_id;
    int tag_id;
    int h_compoundvar_id;

    /* rank (number of dimensions) for each variable */
#   define RANK_lat 1
#   define RANK_lon 1
#   define RANK_time 1
#   define RANK_Z 3
#   define RANK_t 3
#   define RANK_p 3
#   define RANK_rh 3
#   define RANK_country 3
#   define RANK_tag 0
#   define RANK_h_compoundvar 0

    /* variable shapes */
    int lat_dims[RANK_lat];
    int lon_dims[RANK_lon];
    int time_dims[RANK_time];
    int Z_dims[RANK_Z];
    int t_dims[RANK_t];
    int p_dims[RANK_p];
    int rh_dims[RANK_rh];
    int country_dims[RANK_country];

    /* enter define mode */
    stat = nc_create("tst_diskless2.nc", NC_DISKLESS|NC_WRITE|NC_CLOBBER|NC_NETCDF4, &ncid);
    check_err(stat,__LINE__,__FILE__);
    root_grp = ncid;
    stat = nc_def_grp(root_grp, "g", &g_grp);
    check_err(stat,__LINE__,__FILE__);
    stat = nc_def_grp(root_grp, "h", &h_grp);
    check_err(stat,__LINE__,__FILE__);

    {
        unsigned char econst;
        stat = nc_def_enum(root_grp, NC_UBYTE, "enum_t", &enum_t_typ);
        check_err(stat,__LINE__,__FILE__);
        econst = 0;
        stat = nc_insert_enum(root_grp, enum_t_typ, "Clear", &econst);
        check_err(stat,__LINE__,__FILE__);
        econst = 1;
        stat = nc_insert_enum(root_grp, enum_t_typ, "Cumulonimbus", &econst);
        check_err(stat,__LINE__,__FILE__);
        econst = 2;
        stat = nc_insert_enum(root_grp, enum_t_typ, "Stratus", &econst);
        check_err(stat,__LINE__,__FILE__);
    }

    stat = nc_def_opaque(root_grp, 11, "opaque_t", &opaque_t_typ);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_vlen(root_grp, "vlen_t", NC_INT, &vlen_t_typ);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_compound(g_grp, sizeof(g_cmpd_t), "cmpd_t", &g_cmpd_t_typ);
    check_err(stat,__LINE__,__FILE__);
    {
        stat = nc_insert_compound(g_grp, g_cmpd_t_typ, "f1", NC_COMPOUND_OFFSET(g_cmpd_t,f1), vlen_t_typ);
        check_err(stat,__LINE__,__FILE__);
        stat = nc_insert_compound(g_grp, g_cmpd_t_typ, "f2", NC_COMPOUND_OFFSET(g_cmpd_t,f2), enum_t_typ);
        check_err(stat,__LINE__,__FILE__);
    }


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

    /* define variables */

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

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

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

    Z_dims[0] = time_dim;
    Z_dims[1] = lat_dim;
    Z_dims[2] = lon_dim;
    stat = nc_def_var(root_grp, "Z", NC_FLOAT, RANK_Z, Z_dims, &Z_id);
    check_err(stat,__LINE__,__FILE__);

    t_dims[0] = time_dim;
    t_dims[1] = lat_dim;
    t_dims[2] = lon_dim;
    stat = nc_def_var(root_grp, "t", NC_FLOAT, RANK_t, t_dims, &t_id);
    check_err(stat,__LINE__,__FILE__);

    p_dims[0] = time_dim;
    p_dims[1] = lat_dim;
    p_dims[2] = lon_dim;
    stat = nc_def_var(root_grp, "p", NC_DOUBLE, RANK_p, p_dims, &p_id);
    check_err(stat,__LINE__,__FILE__);

    rh_dims[0] = time_dim;
    rh_dims[1] = lat_dim;
    rh_dims[2] = lon_dim;
    stat = nc_def_var(root_grp, "rh", NC_INT, RANK_rh, rh_dims, &rh_id);
    check_err(stat,__LINE__,__FILE__);

    country_dims[0] = time_dim;
    country_dims[1] = lat_dim;
    country_dims[2] = lon_dim;
    stat = nc_def_var(root_grp, "country", NC_STRING, RANK_country, country_dims, &country_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(root_grp, "tag", NC_UBYTE, RANK_tag, 0, &tag_id);
    check_err(stat,__LINE__,__FILE__);

    stat = nc_def_var(h_grp, "compoundvar", g_cmpd_t_typ, RANK_h_compoundvar, 0, &h_compoundvar_id);
    check_err(stat,__LINE__,__FILE__);

    /* assign global attributes */

    {
        static const int vlen_2[] = {17, 18, 19} ;
        static const vlen_t globalatt_att[1] = {{3, (void*)vlen_2}} ;
        stat = nc_put_att(root_grp, NC_GLOBAL, "globalatt", vlen_t_typ, 1, globalatt_att);
        check_err(stat,__LINE__,__FILE__);
    }


    /* assign per-variable attributes */

    {
        stat = nc_put_att_text(root_grp, lat_id, "long_name", 8, "latitude");
        check_err(stat,__LINE__,__FILE__);
    }

    {
        stat = nc_put_att_text(root_grp, lat_id, "units", 13, "degrees_north");
        check_err(stat,__LINE__,__FILE__);
    }

    {
        stat = nc_put_att_text(root_grp, lon_id, "long_name", 9, "longitude");
        check_err(stat,__LINE__,__FILE__);
    }

    {
        stat = nc_put_att_text(root_grp, lon_id, "units", 12, "degrees_east");
        check_err(stat,__LINE__,__FILE__);
    }

    {
        stat = nc_put_att_text(root_grp, time_id, "units", 31, "seconds since 1992-1-1 00:00:00");
        check_err(stat,__LINE__,__FILE__);
    }

    {
        static const char* Z_units_att[1] = {"geopotential meters"} ;
        stat = nc_put_att_string(root_grp, Z_id, "units", 1, Z_units_att);
        check_err(stat,__LINE__,__FILE__);
    }

    {
        static const float Z_valid_range_att[2] = {((float)0), ((float)5000)} ;
        stat = nc_put_att_float(root_grp, Z_id, "valid_range", NC_FLOAT, 2, Z_valid_range_att);
        check_err(stat,__LINE__,__FILE__);
    }

    {
        static const double p_FillValue_att[1] = {((double)-9999)} ;
        stat = nc_put_att_double(root_grp, p_id, "_FillValue", NC_DOUBLE, 1, p_FillValue_att);
        check_err(stat,__LINE__,__FILE__);
    }

    {
        static const int rh_FillValue_att[1] = {-1} ;
        stat = nc_put_att_int(root_grp, rh_id, "_FillValue", NC_INT, 1, rh_FillValue_att);
        check_err(stat,__LINE__,__FILE__);
    }


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

    /* assign variable data */

    {
        int lat_data[10] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90} ;
        size_t lat_startset[1] = {0} ;
        size_t lat_countset[1] = {10};
        stat = nc_put_vara(root_grp, lat_id, lat_startset, lat_countset, lat_data);
        check_err(stat,__LINE__,__FILE__);
    }


    {
        int lon_data[5] = {-140, -118, -96, -84, -52} ;
        size_t lon_startset[1] = {0} ;
        size_t lon_countset[1] = {5};
        stat = nc_put_vara(root_grp, lon_id, lon_startset, lon_countset, lon_data);
        check_err(stat,__LINE__,__FILE__);
    }


    {
        static const int vlen_10[] = {3, 4, 5} ;
        size_t zero = 0;
        static g_cmpd_t h_compoundvar_data[1] = {{{3, (void*)vlen_10}, 2}};
        stat = nc_put_var1(h_grp, h_compoundvar_id, &zero, h_compoundvar_data);
        check_err(stat,__LINE__,__FILE__);
    }


    stat = nc_close(root_grp);
    check_err(stat,__LINE__,__FILE__);
    return 0;
}
Exemplo n.º 18
0
void define_nc_dim_var(int ncid, int dim_latlon, int *time_dim, int *time_var, int *x_dim, 
						int *y_dim, double dx, double dy,
                        double verf_utime, double ref_utime, double time_step, int time_step_type,
			    double date0, int time_ind, double *lat_data, double *lon_data)
{
     char *name, *str, *lname, *units;
     char ref_date[50];
     int dimids[2];
     int lat_var, lon_var, y_var, x_var;
     int ref_time_type;
     double fill_value = FILL_VALUE_DOUBLE;
     float  f_fill_value = FILL_VALUE_FLOAT;

     /* the variable need by put_nc_dim_var */
     double ttime;
     int i, j;
     double *test_ll;
     size_t start[2], count[2];
     size_t x_len, y_len;
     size_t dimlens[2];
     
// create coordinate variables...
     if (dim_latlon == 1)
    {

    dimids[0] = *y_dim;
    netcdf_func( nc_def_var (ncid, "latitude", NC_DOUBLE, 1, dimids, &lat_var) );
    dimids[0] = *x_dim;
    netcdf_func( nc_def_var (ncid, "longitude", NC_DOUBLE, 1, dimids, &lon_var) );
/*#ifdef DEBUG_NC
fprintf(stderr,"netcdf:create_nc_dims: latitude(dim,var,ny)=%d %d %d\n",*y_dim,lat_var,ny);
fprintf(stderr,"netcdf:create_nc_dims: longitude(dim,var,nx)=%d %d %d\n",*x_dim,lon_var,nx);
#endif*/
  }
  else if(dim_latlon == 2)
  {

    dimids[0] = *y_dim;
    netcdf_func( nc_def_var (ncid, "y", NC_DOUBLE, 1, dimids, &y_var) );
    str = "y coordinate of projection";
//    str = "projection_y_coordinate";    //it is standard_name,
                                        //but could require grid_mapping definition that is
                                        //projection-dependant; could do it later;
                                        //do not need lat-lon values in this case as these would be
                                        //computed in processing software (CF convention)
    netcdf_func( nc_put_att_text(ncid, y_var, "long_name", strlen(str), str) );
    str = "projection_y_coordinate";
    netcdf_func( nc_put_att_text(ncid, y_var, "standard_name", strlen(str), str) );
    dimids[0] = *x_dim;
    netcdf_func( nc_def_var (ncid, "x", NC_DOUBLE, 1, dimids, &x_var) );
    str = "x coordinate of projection";
    netcdf_func( nc_put_att_text(ncid, x_var, "long_name", strlen(str), str) );
    str = "projection_x_coordinate";
    netcdf_func( nc_put_att_text(ncid, x_var, "standard_name", strlen(str), str) );
    str = "m";
    netcdf_func( nc_put_att_text(ncid, y_var, "units", strlen(str), str) );
    netcdf_func( nc_put_att_text(ncid, x_var, "units", strlen(str), str) );
    netcdf_func( nc_put_att_double(ncid, x_var, "grid_spacing", NC_DOUBLE, 1, &dx) );
    netcdf_func( nc_put_att_double(ncid, y_var, "grid_spacing", NC_DOUBLE, 1, &dy) );
    dimids[0] = *y_dim;
    dimids[1] = *x_dim;
    netcdf_func( nc_def_var (ncid, "latitude", NC_DOUBLE, 2, dimids, &lat_var) );
    netcdf_func( nc_def_var (ncid, "longitude", NC_DOUBLE, 2, dimids, &lon_var) );
/*#ifdef DEBUG_NC
fprintf(stderr,"netcdf:create_nc_dims: y(dim,var,ny)=%d %d %d\n",*y_dim,y_var,ny);
fprintf(stderr,"netcdf:create_nc_dims: x(dim,var,nx)=%d %d %d\n",*x_dim,x_var,nx);
fprintf(stderr,"netcdf:create_nc_var (2D): latitude(xdim,ydim,var)=%d %d %d\n",*y_dim,*x_dim,lat_var);
fprintf(stderr,"netcdf:create_nc_var (2D): longitude(xdim,ydim,var)=%d %d %d\n",*y_dim,*x_dim,lon_var);
#endif*/
  }
  else
    print_error("netcdf:create_nc_dims: %s","unsupported lat-lon dimension");

  str = "degrees_north";
  netcdf_func( nc_put_att_text(ncid, lat_var, "units", strlen(str), str) );
  str = "degrees_east";
  netcdf_func( nc_put_att_text(ncid, lon_var, "units", strlen(str), str) );
  str = "latitude";
  netcdf_func( nc_put_att_text(ncid, lat_var, "long_name", strlen(str), str) );
  str = "longitude";
  netcdf_func( nc_put_att_text(ncid, lon_var, "long_name", strlen(str), str) );

  /* time settings */
  dimids[0] = *time_dim;
  netcdf_func(nc_def_var (ncid, "time", NC_DOUBLE, 1, dimids, time_var));
  netcdf_func(nc_put_att_double(ncid, *time_var, "_FillValue", NC_DOUBLE, 1, &fill_value));
  str = "seconds since 1970-01-01 00:00:00.0 0:00";
  netcdf_func( nc_put_att_text(ncid, *time_var, "units", strlen(str), str) );
  //str = "verification time generated by function verftime()";
  //netcdf_func( nc_put_att_text(ncid, *time_var, "long_name", strlen(str), str) );

  /* nc_ref_time is reference time value,
     nc_ref_time_type is the reference time type:
     0 - undefined
     1 - analyses, all for the same reference date, could be succeded by forecasts
     2 - analyses, but for different reference date/time (time serie)
     3 - forecasts from the same reference date/time
     For the type 0 or 2 nc_ref_time keeps first field reference date/time
  */
  if (fabs(ref_utime - verf_utime) < TM_TOLERANCE )
  {
    ref_time_type = 1;
    str = "analyses, reference date is fixed";
  }
  else
  {
    ref_time_type = 3;
    str = "forecast or accumulated, reference date is fixed";
  }
  netcdf_func( nc_put_att_double(ncid, *time_var, "reference_time", NC_DOUBLE, 1, &ref_utime) );
  netcdf_func( nc_put_att_int(ncid, *time_var,    "reference_time_type", NC_INT, 1, &ref_time_type) );
  my_get_unixdate(ref_utime, ref_date);
  netcdf_func( nc_put_att_text(ncid, *time_var,   "reference_date", strlen(ref_date), ref_date) );
  netcdf_func( nc_put_att_text(ncid, *time_var,   "reference_time_description", strlen(str), str) );
  /* write time step attributes, could be -1 (undefined) for first or single time step, then update */
  if ( time_step_type )
  {
    str="user";
  }
  else
  {
    str="auto";
  }
  netcdf_func( nc_put_att_text(ncid, *time_var, "time_step_setting", strlen(str), str) );
  netcdf_func( nc_put_att_double(ncid, *time_var,  "time_step", NC_DOUBLE, 1, &time_step) );

#ifdef DEBUG_NC
fprintf(stderr,"netcdf:create_nc_dims: time(dim,var)=%d %d, size unlimited\n",*time_dim,*time_var);
fprintf(stderr,"netcdf:create_nc_dims: time_step=%.1lf time_step_type=%d (%s)\n",
time_step,time_step_type,str);
#endif
  
     netcdf_func( nc_enddef(ncid) );


/*
  * put var
  */
     // populate coordinate variables...
  start[0] = 0;
  netcdf_func( nc_put_var1_double(ncid, *time_var, start, &date0) );

  if ( time_ind == 1 )
  {
    start[0] = 1;
    netcdf_func( nc_put_var1_double(ncid, *time_var, start, &verf_utime) );
  }
  else if (time_ind > 1)
  {
    for (j=1; j <= time_ind; j++)
    {
      start[0] = j;
      ttime = date0 + (time_step)*j;
      netcdf_func( nc_put_var1_double(ncid, *time_var, start, &ttime) );
    }
  }
  else if (time_ind < 0)
  {
   fatal_error("netcdf:create_nc_dims: %s","negative time index");
  }

    netcdf_func(nc_inq_dimlen(ncid, *x_dim, &x_len));
    netcdf_func(nc_inq_dimlen(ncid, *y_dim, &y_len));
    
  i = MAX(x_len, y_len);
  test_ll = (double*) malloc(i*sizeof(double));
  if (!test_ll) fatal_error("netcdf:create_nc_dims: %s",
    "error doing malloc of test_ll");
  
  if (dim_latlon == 1)
  {
        set_hyperslab(count, start, &y_len, 1);
        for (i=0; i < count[0] ; i++) 
            test_ll[i] = lat_data[(i+start[0])*x_len];
        //start[0] = 0; count[0] = y_len;
        netcdf_func( nc_put_vara_double(ncid, lat_var, start, count, test_ll) );

        set_hyperslab(count, start, &x_len, 1);
        for (i=0; i<count[0]; i++) 
            test_ll[i] = lon_data[i+start[0]];
        //start[0] = 0; count[0] = x_len;
        netcdf_func( nc_put_vara_double(ncid, lon_var, start, count, test_ll) );
  }
  else
  {
        set_hyperslab(count, start, &y_len, 1);
        for (i=0; i<count[0] ; i++) 
            test_ll[i] = dy*(i+start[0]);
        //start[0] = 0; count[0] = y_len;
        netcdf_func( nc_put_vara_double(ncid, y_var, start, count, test_ll) );

        set_hyperslab(count, start, &x_len, 1);
        for (i=0; i<count[0]; i++) 
            test_ll[i] = dx*(i+start[0]);
        //start[0] = 0; count[0] = x_len;
        netcdf_func( nc_put_vara_double(ncid, x_var, start, count, test_ll) );

        //start[0] = 0;  count[0] = y_len;
        //start[1] = 0;  count[1] = x_len;

        dimlens[0] = y_len;
        dimlens[1] = x_len;
        set_hyperslab(count, start, dimlens, 2);
        netcdf_func( nc_put_vara_double(ncid, lat_var, start, count, &(lat_data[start[0] * x_len + start[1]])) );
        netcdf_func( nc_put_vara_double(ncid, lon_var, start, count, &(lon_data[start[0] * x_len + start[1]])) );
  }
  free(test_ll);
}
Exemplo n.º 19
0
int CNetCdfInterface::ncPutAttType(int ncid, int varid, const char* attrName,
                                   StdSize numVal, const double* data)
{
  return nc_put_att_double(ncid, varid, attrName, NC_DOUBLE, numVal, data);
}
Exemplo n.º 20
0
int
test_redef(int format)   
{
   int ncid, varid, dimids[REDEF_NDIMS], dimids_in[REDEF_NDIMS];
   int ndims, nvars, natts, unlimdimid;
   int dimids_var[REDEF_NDIMS], var_type;
   int cflags = 0;
   size_t dim_len;
   char dim_name[NC_MAX_NAME+1], var_name[NC_MAX_NAME+1];
   float float_in;
   double double_out = 99E99;
   int int_in;
   unsigned char uchar_in, uchar_out = 255;
   short short_out = -999;
   nc_type xtype_in;
   size_t cache_size_in, cache_nelems_in;
   float cache_preemption_in;
   int ret;

   if (format == NC_FORMAT_64BIT)
      cflags |= NC_64BIT_OFFSET;
   else if (format == NC_FORMAT_NETCDF4_CLASSIC)
      cflags |= (NC_NETCDF4|NC_CLASSIC_MODEL);
   else if (format == NC_FORMAT_NETCDF4)
      cflags |= NC_NETCDF4;

   /* Change chunk cache. */
   if (nc_set_chunk_cache(NEW_CACHE_SIZE, NEW_CACHE_NELEMS, 
			  NEW_CACHE_PREEMPTION)) ERR;

   /* Create a file with two dims, two vars, and two atts. */
   if (nc_create(FILE_NAME, cflags|NC_CLOBBER, &ncid)) ERR;

   /* Retrieve the chunk cache settings, just for fun. */
   if (nc_get_chunk_cache(&cache_size_in, &cache_nelems_in, 
			  &cache_preemption_in)) ERR;
   if (cache_size_in != NEW_CACHE_SIZE || cache_nelems_in != NEW_CACHE_NELEMS ||
       cache_preemption_in != NEW_CACHE_PREEMPTION) ERR;

   /* This will fail, except for netcdf-4/hdf5, which permits any
    * name. */
   if (format != NC_FORMAT_NETCDF4)
      if ((ret = nc_def_dim(ncid, REDEF_NAME_ILLEGAL, REDEF_DIM2_LEN, 
			    &dimids[1])) != NC_EBADNAME) ERR;

   if (nc_def_dim(ncid, REDEF_DIM1_NAME, REDEF_DIM1_LEN, &dimids[0])) ERR;
   if (nc_def_dim(ncid, REDEF_DIM2_NAME, REDEF_DIM2_LEN, &dimids[1])) ERR;
   if (nc_def_var(ncid, REDEF_VAR1_NAME, NC_INT, REDEF_NDIMS, dimids, &varid)) ERR;
   if (nc_def_var(ncid, REDEF_VAR2_NAME, NC_BYTE, REDEF_NDIMS, dimids, &varid)) ERR;
   if (nc_put_att_double(ncid, NC_GLOBAL, REDEF_ATT1_NAME, NC_DOUBLE, 1, &double_out)) ERR;
   if (nc_put_att_short(ncid, NC_GLOBAL, REDEF_ATT2_NAME, NC_SHORT, 1, &short_out)) ERR;

   /* Check it out. */
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != REDEF_NDIMS || nvars != 2 || natts != 2 || unlimdimid != -1) ERR;
   if (nc_inq_var(ncid, 0, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR1_NAME) || xtype_in != NC_INT || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;
   if (nc_inq_var(ncid, 1, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR2_NAME) || xtype_in != NC_BYTE || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;

   /* Close it up. */
   if (format != NC_FORMAT_NETCDF4)
      if (nc_enddef(ncid)) ERR;
   if (nc_close(ncid)) ERR;

   /* Reopen as read only - make sure it doesn't let us change file. */
   if (nc_open(FILE_NAME, 0, &ncid)) ERR;
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != REDEF_NDIMS || nvars != 2 || natts != 2 || unlimdimid != -1) ERR;
   if (nc_inq_var(ncid, 0, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR1_NAME) || xtype_in != NC_INT || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;
   if (nc_inq_var(ncid, 1, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR2_NAME) || xtype_in != NC_BYTE || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;

   /* This will fail. */
   ret = nc_def_var(ncid, REDEF_VAR3_NAME, NC_UBYTE, REDEF_NDIMS, 
			  dimids, &varid);
   if(format == NC_FORMAT_NETCDF4) {
	if(ret != NC_EPERM) {
	    ERR;
	}
   } else {
	if(ret != NC_ENOTINDEFINE) {
	    ERR;
	}
   }
   /* This will fail. */
   if (!nc_put_att_uchar(ncid, NC_GLOBAL, REDEF_ATT3_NAME, NC_CHAR, 1, &uchar_out)) ERR;
   if (nc_close(ncid)) ERR;      

   /* Make sure we can't redef a file opened for NOWRITE. */
   if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
   if (nc_redef(ncid) != NC_EPERM) ERR;

   /* Check it out again. */
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != REDEF_NDIMS || nvars != 2 || natts != 2 || unlimdimid != -1) ERR;
   if (nc_inq_var(ncid, 0, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR1_NAME) || xtype_in != NC_INT || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;
   if (nc_inq_var(ncid, 1, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR2_NAME) || xtype_in != NC_BYTE || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;

   if (nc_close(ncid)) ERR;      

   /* Reopen the file and check it, add a variable and attribute. */
   if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;

   /* Check it out. */
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != REDEF_NDIMS || nvars != 2 || natts != 2 || unlimdimid != -1) ERR;

   /* Add var. */
   if ((format != NC_FORMAT_NETCDF4) && nc_redef(ncid)) ERR;
   if (nc_def_var(ncid, REDEF_VAR3_NAME, NC_BYTE, REDEF_NDIMS, dimids, &varid)) ERR;

   /* Add att. */
   ret = nc_put_att_uchar(ncid, NC_GLOBAL, REDEF_ATT3_NAME, NC_BYTE, 1, &uchar_out);
   if (format != NC_FORMAT_NETCDF4 && ret) ERR;
   else if (format == NC_FORMAT_NETCDF4 && ret != NC_ERANGE) ERR;

   /* Check it out. */
   if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
   if (ndims != REDEF_NDIMS || nvars != 3 || natts != 3 || unlimdimid != -1) ERR;
   if (nc_inq_var(ncid, 0, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR1_NAME) || xtype_in != NC_INT || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;
   if (nc_inq_var(ncid, 1, var_name, &xtype_in, &ndims, dimids_in, &natts)) ERR;
   if (strcmp(var_name, REDEF_VAR2_NAME) || xtype_in != NC_BYTE || ndims != REDEF_NDIMS || 
       dimids_in[0] != dimids[0] || dimids_in[1] != dimids[1]) ERR;
   if (nc_inq_var(ncid, 2, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
   if (ndims != REDEF_NDIMS || strcmp(var_name, REDEF_VAR3_NAME) || var_type != NC_BYTE ||
       natts != 0) 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 != REDEF_DIM1_LEN || strcmp(dim_name, REDEF_DIM1_NAME)) ERR;
   if (nc_inq_dim(ncid, 1, dim_name, &dim_len)) ERR;
   if (dim_len != REDEF_DIM2_LEN || strcmp(dim_name, REDEF_DIM2_NAME)) ERR;
   if (nc_inq_var(ncid, 0, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
   if (ndims != REDEF_NDIMS || strcmp(var_name, REDEF_VAR1_NAME) || var_type != NC_INT ||
       natts != 0) ERR;
   if (nc_inq_var(ncid, 1, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
   if (ndims != REDEF_NDIMS || strcmp(var_name, REDEF_VAR2_NAME) || var_type != NC_BYTE ||
       natts != 0) ERR;
   if (nc_inq_var(ncid, 2, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
   if (ndims != REDEF_NDIMS || strcmp(var_name, REDEF_VAR3_NAME) || var_type != NC_BYTE ||
       natts != 0) ERR;
   if (nc_get_att_float(ncid, NC_GLOBAL, REDEF_ATT1_NAME, &float_in) != NC_ERANGE) ERR;
   if (nc_get_att_int(ncid, NC_GLOBAL, REDEF_ATT2_NAME, &int_in)) ERR;
   if (int_in != short_out) ERR;
   ret = nc_get_att_uchar(ncid, NC_GLOBAL, REDEF_ATT3_NAME, &uchar_in);
   if (format == NC_FORMAT_NETCDF4)
   {
      if (ret != NC_ERANGE) ERR;
   }
   else if (ret) ERR;
	 
   if (uchar_in != uchar_out) ERR;
   if (nc_close(ncid)) ERR;      
   return NC_NOERR;
}
Exemplo n.º 21
0
int
main(int argc, char **argv)
{
    (void) signal(SIGFPE, SIG_IGN);

   printf("\n*** Testing netcdf-4 attribute functions.\n");
   printf("*** testing really simple global atts...");
#define NUM_SIMPLE_ATTS 9
   {
      int ncid;
      char name[NUM_SIMPLE_ATTS][ATT_MAX_NAME + 1] = {"Gc", "Gb", "Gs", "Gi", "Gf", 
						      "Gd", "G7", "G8", "G9"};
      char name_in[NC_MAX_NAME];
      int j;

      /* Create a file with some global atts. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLOBBER, &ncid)) ERR;
      for (j = 0; j < NUM_SIMPLE_ATTS; j++)
	 if (nc_put_att_int(ncid, NC_GLOBAL, name[j], NC_INT, 0, NULL)) ERR;      
      if (nc_close(ncid)) ERR;
      
      /* Reopen the file and check the order. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      for (j = 0; j < NUM_SIMPLE_ATTS; j++)
      {
	 if (nc_inq_attname(ncid, NC_GLOBAL, j, name_in)) ERR;
	 if (strcmp(name_in, name[j])) ERR;
      }

      /* Close up shop. */
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing simple global atts...");
   {      
      int ncid;
      nc_type att_type;
      size_t att_len;
      int i;

      char *speech_in;
      signed char schar_in[ATT_LEN], schar_out[ATT_LEN] = {NC_MIN_BYTE, 1, NC_MAX_BYTE};
      unsigned char uchar_in[ATT_LEN], uchar_out[ATT_LEN] = {0, 128, NC_MAX_CHAR};
      short short_in[ATT_LEN], short_out[ATT_LEN] = {NC_MIN_SHORT, -128, NC_MAX_SHORT};
      /*int int_in[ATT_LEN], int_out[ATT_LEN] = {NC_MIN_INT, 128, NC_MAX_INT};*/
      int int_in[ATT_LEN], int_out[ATT_LEN] = {-100000, 128, 100000};
      float float_in[ATT_LEN], float_out[ATT_LEN] = {.5, 0.25, 0.125};
      double double_in[ATT_LEN], double_out[ATT_LEN] = {0.25, .5, 0.125};
      unsigned short ushort_in[ATT_LEN], ushort_out[ATT_LEN] = {0, 128, NC_MAX_USHORT};
      unsigned int uint_in[ATT_LEN], uint_out[ATT_LEN] = {0, 128, NC_MAX_UINT};
      unsigned long long uint64_in[ATT_LEN], uint64_out[ATT_LEN] = {0, 128, 18446744073709551612ULL};
      long long int64_in[ATT_LEN], int64_out[ATT_LEN] = {NC_MIN_INT64, 128, NC_MAX_INT64};


      /* This won't work, because classic files can't create these types. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_put_att_ushort(ncid, NC_GLOBAL, ATT_USHORT_NAME, NC_USHORT, ATT_LEN, 
			    ushort_out) != NC_ESTRICTNC3) ERR;      
      if (nc_put_att_uint(ncid, NC_GLOBAL, ATT_UINT_NAME, NC_UINT, ATT_LEN, 
			  uint_out) != NC_ESTRICTNC3) ERR;      
      if (nc_put_att_longlong(ncid, NC_GLOBAL, ATT_INT64_NAME, NC_INT64, ATT_LEN, 
			      int64_out) != NC_ESTRICTNC3) ERR;      
      if (nc_put_att_ulonglong(ncid, NC_GLOBAL, ATT_UINT64_NAME, NC_UINT64, ATT_LEN, 
			       uint64_out) != NC_ESTRICTNC3) ERR;      
      if (nc_close(ncid)) ERR;

      /* Create a file with a global attribute of each type. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, strlen(speech)+1, speech)) ERR;      
      if (nc_put_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, NC_BYTE, ATT_LEN, schar_out)) ERR;      
      if (nc_put_att_uchar(ncid, NC_GLOBAL, ATT_UCHAR_NAME, NC_UBYTE, ATT_LEN, uchar_out)) ERR;
      if (nc_put_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, NC_SHORT, ATT_LEN, short_out)) ERR;      
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, NC_INT, ATT_LEN, int_out)) ERR;      
      if (nc_put_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, NC_FLOAT, ATT_LEN, float_out)) ERR;      
      if (nc_put_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, NC_DOUBLE, ATT_LEN, double_out)) ERR;      
      if (nc_put_att_ushort(ncid, NC_GLOBAL, ATT_USHORT_NAME, NC_USHORT, ATT_LEN, ushort_out)) ERR;      
      if (nc_put_att_uint(ncid, NC_GLOBAL, ATT_UINT_NAME, NC_UINT, ATT_LEN, uint_out)) ERR;      
      if (nc_put_att_longlong(ncid, NC_GLOBAL, ATT_INT64_NAME, NC_INT64, ATT_LEN, int64_out)) ERR;      
      if (nc_put_att_ulonglong(ncid, NC_GLOBAL, ATT_UINT64_NAME, NC_UINT64, ATT_LEN, uint64_out)) ERR;      
      if (nc_close(ncid)) ERR;

      /* Open the file and check attributes. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      /* Check text. */
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_TEXT_NAME, &att_type, &att_len))
	 ERR;
      if (att_type != NC_CHAR || att_len != strlen(speech) + 1) ERR;
      if (!(speech_in = malloc(att_len + 1))) ERR;
      if (nc_get_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, speech_in)) ERR;      
      if (strcmp(speech, speech_in)) ERR;
      free(speech_in);
      /* Check numeric values. */
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, schar_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (schar_in[i] != schar_out[i]) ERR;
      if (nc_get_att_uchar(ncid, NC_GLOBAL, ATT_UCHAR_NAME, uchar_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (uchar_in[i] != uchar_out[i]) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, short_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (short_in[i] != short_out[i]) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, int_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int_in[i] != int_out[i]) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, float_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (float_in[i] != float_out[i]) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, double_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (double_in[i] != double_out[i]) ERR;
      if (nc_get_att_ushort(ncid, NC_GLOBAL, ATT_USHORT_NAME, ushort_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (ushort_in[i] != ushort_out[i]) ERR;
      if (nc_get_att_uint(ncid, NC_GLOBAL, ATT_UINT_NAME, uint_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (uint_in[i] != uint_out[i]) ERR;
      if (nc_get_att_longlong(ncid, NC_GLOBAL, ATT_INT64_NAME, int64_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int64_in[i] != int64_out[i]) ERR;
      if (nc_get_att_ulonglong(ncid, NC_GLOBAL, ATT_UINT64_NAME, uint64_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (uint64_in[i] != uint64_out[i]) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing attribute data type conversions...");

   {
      int ncid;
      int i;

      signed char schar_in[ATT_LEN], schar_out[ATT_LEN] = {NC_MIN_BYTE, 1, NC_MAX_BYTE};
      short short_in[ATT_LEN], short_out[ATT_LEN] = {NC_MIN_SHORT, -128, NC_MAX_SHORT};
      /*int int_in[ATT_LEN], int_out[ATT_LEN] = {NC_MIN_INT, 128, NC_MAX_INT};*/
      int int_in[ATT_LEN], int_out[ATT_LEN] = {-100000, 128, 100000};
      float float_in[ATT_LEN], float_out[ATT_LEN] = {.5, 0.25, 0.125};
      double double_in[ATT_LEN], double_out[ATT_LEN] = {0.25, .5, 0.125};
      unsigned short ushort_in[ATT_LEN];
      unsigned int uint_in[ATT_LEN];
      unsigned long long uint64_in[ATT_LEN];
      long long int64_in[ATT_LEN];

      /* Reopen the file and try different type conversions. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;

      /* No text conversions are allowed, and people who try them shold
       * be locked up, away from decent folk! */
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_TEXT_NAME, short_in) != NC_ECHAR) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_TEXT_NAME, int_in) != NC_ECHAR) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_TEXT_NAME, float_in) != NC_ECHAR) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_TEXT_NAME, double_in) != NC_ECHAR) ERR;
/*   if (nc_get_att_ubyte(ncid, NC_GLOBAL, ATT_TEXT_NAME, uchar_in) != NC_ECHAR) ERR;*/
      if (nc_get_att_ushort(ncid, NC_GLOBAL, ATT_TEXT_NAME, ushort_in) != NC_ECHAR) ERR;
      if (nc_get_att_uint(ncid, NC_GLOBAL, ATT_TEXT_NAME, uint_in) != NC_ECHAR) ERR;
      if (nc_get_att_longlong(ncid, NC_GLOBAL, ATT_TEXT_NAME, int64_in) != NC_ECHAR) ERR;
      if (nc_get_att_ulonglong(ncid, NC_GLOBAL, ATT_TEXT_NAME, uint64_in) != NC_ECHAR) ERR;

      /* Read all atts (except text) as double. */
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_SCHAR_NAME, double_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (double_in[i] != schar_out[i]) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_SHORT_NAME, double_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (double_in[i] != short_out[i]) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_INT_NAME, double_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (double_in[i] != int_out[i]) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_FLOAT_NAME, double_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (double_in[i] != float_out[i]) ERR;
      /* Read all atts (except text) as float. */
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_SCHAR_NAME, float_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (float_in[i] != schar_out[i]) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_SHORT_NAME, float_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (float_in[i] != short_out[i]) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_INT_NAME, float_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (float_in[i] != (float)int_out[i]) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, float_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (float_in[i] != (float)double_out[i]) ERR;
      /* Read all atts (except text) as int. */
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_SCHAR_NAME, int_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int_in[i] != schar_out[i]) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_SHORT_NAME, int_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int_in[i] != short_out[i]) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_FLOAT_NAME, int_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int_in[i] != (int)float_out[i]) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, int_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int_in[i] != (int)double_out[i]) ERR;
      /* Read all atts (except text) as short. */
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_SCHAR_NAME, short_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (short_in[i] != schar_out[i]) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_INT_NAME, short_in) != NC_ERANGE) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (short_in[i] != (short)int_out[i]) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_FLOAT_NAME, short_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (short_in[i] != (short)float_out[i]) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, short_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (short_in[i] != (short)double_out[i]) ERR;
      /* Read all atts (except text) as schar. Some range errors will
       * result converting to schar. */
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SHORT_NAME, schar_in) != NC_ERANGE) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (schar_in[i] != (signed char)short_out[i]) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_INT_NAME, schar_in) != NC_ERANGE) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (schar_in[i] != (signed char)int_out[i]) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_FLOAT_NAME, schar_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (schar_in[i] != (signed char)float_out[i]) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, schar_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (schar_in[i] != (signed char)double_out[i]) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing simple variable atts...");
   {
      int ncid, varid, dimids[2];
      nc_type att_type;
      size_t att_len;
      int i, v;

      char *speech_in;
      signed char schar_in[ATT_LEN], schar_out[ATT_LEN] = {NC_MIN_BYTE, 1, NC_MAX_BYTE};
      short short_in[ATT_LEN], short_out[ATT_LEN] = {NC_MIN_SHORT, -128, NC_MAX_SHORT};
      /*int int_in[ATT_LEN], int_out[ATT_LEN] = {NC_MIN_INT, 128, NC_MAX_INT};*/
      int int_in[ATT_LEN], int_out[ATT_LEN] = {-100000, 128, 100000};
      float float_in[ATT_LEN], float_out[ATT_LEN] = {.5, 0.25, 0.125};
      double double_in[ATT_LEN], double_out[ATT_LEN] = {0.25, .5, 0.125};

      /* Create a file with two vars, attaching to each an attribute of
       * each type. */
      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, 2, dimids, &varid)) ERR;
      if (nc_put_att_text(ncid, varid, ATT_TEXT_NAME, strlen(speech)+1, speech)) ERR;      
      if (nc_put_att_schar(ncid, varid, ATT_SCHAR_NAME, NC_BYTE, ATT_LEN, schar_out)) ERR;      
      if (nc_put_att_short(ncid, varid, ATT_SHORT_NAME, NC_SHORT, 3, short_out)) ERR;      
      if (nc_put_att_int(ncid, varid, ATT_INT_NAME, NC_INT, 3, int_out)) ERR;      
      if (nc_put_att_float(ncid, varid, ATT_FLOAT_NAME, NC_FLOAT, 3, float_out)) ERR;      
      if (nc_put_att_double(ncid, varid, ATT_DOUBLE_NAME, NC_DOUBLE, 3, double_out)) ERR;      
      if (nc_def_var(ncid, VAR2_NAME, NC_UINT, 2, dimids, &varid)) ERR;
      if (nc_put_att_text(ncid, varid, ATT_TEXT_NAME, strlen(speech)+1, speech)) ERR;      
      if (nc_put_att_schar(ncid, varid, ATT_SCHAR_NAME, NC_BYTE, ATT_LEN, schar_out)) ERR; 
      if (nc_put_att_short(ncid, varid, ATT_SHORT_NAME, NC_SHORT, 3, short_out)) ERR;           
      if (nc_put_att_int(ncid, varid, ATT_INT_NAME, NC_INT, 3, int_out)) ERR;      
      if (nc_put_att_float(ncid, varid, ATT_FLOAT_NAME, NC_FLOAT, 3, float_out)) ERR;      
      if (nc_put_att_double(ncid, varid, ATT_DOUBLE_NAME, NC_DOUBLE, 3, double_out)) ERR;      
      if (nc_close(ncid)) ERR;

      /* Open the file and check attributes. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      for (v=0; v<2; v++)
      {
	 if (nc_inq_att(ncid, v, ATT_TEXT_NAME, &att_type, &att_len)) ERR;
	 if (att_type != NC_CHAR || att_len != strlen(speech) + 1) ERR;
	 if (!(speech_in = malloc(att_len + 1))) ERR;
	 if (nc_get_att_text(ncid, v, ATT_TEXT_NAME, speech_in)) ERR;      
	 if (strcmp(speech, speech_in)) ERR;
	 free(speech_in);
	 if (nc_get_att_schar(ncid, v, ATT_SCHAR_NAME, schar_in)) ERR;      
	 for (i = 0; i < ATT_LEN; i++)
	    if (schar_in[i] != schar_out[i]) ERR;
	 if (nc_get_att_short(ncid, v, ATT_SHORT_NAME, short_in)) ERR;      
	 for (i = 0; i < ATT_LEN; i++)
	    if (short_in[i] != short_out[i]) ERR;
	 if (nc_get_att_int(ncid, v, ATT_INT_NAME, int_in)) ERR;      
	 for (i = 0; i < ATT_LEN; i++)
	    if (int_in[i] != int_out[i]) ERR;
	 if (nc_get_att_float(ncid, v, ATT_FLOAT_NAME, float_in)) ERR;      
	 for (i = 0; i < ATT_LEN; i++)
	    if (float_in[i] != float_out[i]) ERR;
	 if (nc_get_att_double(ncid, v, ATT_DOUBLE_NAME, double_in)) ERR;      
	 for (i = 0; i < ATT_LEN; i++)
	    if (double_in[i] != double_out[i]) ERR;
      }
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing zero-length attributes...");
   {
      int ncid;

      /*int int_in[ATT_LEN], int_out[ATT_LEN] = {NC_MIN_INT, 128, NC_MAX_INT};*/

      /* Create a file with a global attribute of each type of zero length. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, 0, NULL)) ERR;
      if (nc_put_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, NC_BYTE, 0, NULL)) ERR;
/*   if (nc_put_att_uchar(ncid, NC_GLOBAL, ATT_UCHAR_NAME, NC_UCHAR, ATT_LEN, uchar_out)) ERR;*/
      if (nc_put_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, NC_SHORT, 0, NULL)) ERR;
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, NC_INT, 0, NULL)) ERR;
      if (nc_put_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, NC_FLOAT, 0, NULL)) ERR;
      if (nc_put_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, NC_DOUBLE, 0, NULL)) ERR;
      if (nc_close(ncid)) ERR;
   }

   /* Make sure we can read all these zero-length atts. */
   {
      int ncid;
      signed char schar_in[ATT_LEN];
      short short_in[ATT_LEN];
      /*int int_in[ATT_LEN], int_out[ATT_LEN] = {NC_MIN_INT, 128, NC_MAX_INT};*/
      int int_in[ATT_LEN];
      float float_in[ATT_LEN];
      double double_in[ATT_LEN];
      size_t len;
      nc_type xtype;

      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_get_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, NULL)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_TEXT_NAME, &xtype, &len)) ERR;
      if (len || xtype != NC_CHAR) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, schar_in)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_SCHAR_NAME, &xtype, &len)) ERR;
      if (len || xtype != NC_BYTE) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, short_in)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_SHORT_NAME, &xtype, &len)) ERR;
      if (len || xtype != NC_SHORT) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, int_in)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_INT_NAME, &xtype, &len)) ERR;
      if (len || xtype != NC_INT) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, float_in)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_FLOAT_NAME, &xtype, &len)) ERR;
      if (len || xtype != NC_FLOAT) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, double_in)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, &xtype, &len)) ERR;
      if (len || xtype != NC_DOUBLE) ERR;
      /* Conversions no longer result in range errors, since there's no data. */
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, schar_in)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_FLOAT_NAME, schar_in)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_INT_NAME, schar_in)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SHORT_NAME, schar_in)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing zero-length attributes and redef...(this test skipped for HDF5-1.8.0 beta1");
   {
      int ncid;
      signed char schar_in[ATT_LEN];
      short short_in[ATT_LEN];
      int int_in[ATT_LEN];
      float float_in[ATT_LEN];
      double double_in[ATT_LEN];


      /* Create a file with a global attribute of each type of zero length. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_redef(ncid)) ERR;
      if (nc_put_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, 0, NULL)) ERR;
      if (nc_put_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, NC_BYTE, 0, NULL)) ERR;
/*   if (nc_put_att_uchar(ncid, NC_GLOBAL, ATT_UCHAR_NAME, NC_UCHAR, ATT_LEN, uchar_out)) ERR;*/
      if (nc_put_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, NC_SHORT, 0, NULL)) ERR;
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, NC_INT, 0, NULL)) ERR;
      if (nc_put_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, NC_FLOAT, 0, NULL)) ERR;
      if (nc_put_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, NC_DOUBLE, 0, NULL)) ERR;
      if (nc_close(ncid)) ERR;

      /* Make sure we can read all these zero-length atts added during a
       * redef. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_get_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, NULL)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, schar_in)) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, short_in)) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, int_in)) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, float_in)) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, double_in)) ERR;
      /* Conversions no longer result in range errors, since there's no data. */
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, schar_in)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_FLOAT_NAME, schar_in)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_INT_NAME, schar_in)) ERR;
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SHORT_NAME, schar_in)) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;

   printf("*** testing attribute deletes and renames...");
   {
      int ncid, varid, dimids[2];
      nc_type att_type;
      size_t att_len;
      char *speech_in;
      char name_in[NC_MAX_NAME + 1];
      int attid_in, natts_in;
      int int_out[ATT_LEN] = {-100000, 128, 100000};

      /* Create a file with a global attribute. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, strlen(speech)+1, 
			  speech)) ERR;      
      if (nc_close(ncid)) ERR;
      
      /* Rename it. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq_attid(ncid, NC_GLOBAL, ATT_TEXT_NAME, &attid_in)) ERR;
      if (attid_in != 0) ERR;
      if (nc_inq_attname(ncid, NC_GLOBAL, attid_in, name_in)) ERR;
      if (strcmp(name_in, ATT_TEXT_NAME)) ERR;
      if (nc_rename_att(ncid, NC_GLOBAL, ATT_TEXT_NAME, ATT_TEXT_NAME2)) ERR;      
      if (nc_inq_attname(ncid, NC_GLOBAL, attid_in, name_in)) ERR;
      if (strcmp(name_in, ATT_TEXT_NAME2)) ERR;
      if (nc_close(ncid)) ERR;

      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_TEXT_NAME2, &att_type, &att_len)) ERR;
      if (att_type != NC_CHAR || att_len != strlen(speech) + 1) ERR;
      if (!(speech_in = malloc(att_len + 1))) ERR;
      if (nc_get_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME2, speech_in)) ERR;      
      if (strcmp(speech, speech_in)) ERR;
      free(speech_in);
      if (nc_get_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, speech_in) != NC_ENOTATT) ERR;      
      if (nc_close(ncid)) ERR;

      /* Now delete the att. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_del_att(ncid, NC_GLOBAL, ATT_TEXT_NAME2)) ERR;
      if (nc_close(ncid)) ERR;

      /* Now create a file with a variable, which has an att. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, strlen(speech)+1, speech)) 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_put_att_int(ncid, varid, ATT_INT_NAME, NC_INT, 3, int_out)) ERR;      
      if (nc_close(ncid)) ERR;
      
      /* Reopen the file and delete it. Make sure it's gone. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_del_att(ncid, 0, ATT_INT_NAME)) ERR;
      if (nc_close(ncid)) ERR;

      /* Reopen the file and readd the attribute. Enddef and redef,
       * and delete it, then check to make sure it's gone. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_put_att_int(ncid, varid, ATT_INT_NAME, NC_INT, 3, int_out)) ERR;      
      if (nc_enddef(ncid)) ERR;
      if (nc_redef(ncid)) ERR;
      if (nc_del_att(ncid, 0, ATT_INT_NAME)) ERR;
      if (nc_inq_varnatts(ncid, 0, &natts_in)) ERR;
      if (natts_in != 0) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing attribute create order...");

#define ATT0 "Maturin"
#define ATT1 "Aubery"
   {
      int ncid, varid, dimids[2];
      int attid_in;
      const int number = 42;

      /* Create a file with several global attributes. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT0, NC_INT, 1, &number)) ERR;
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT1, NC_INT, 1, &number)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Open it and check the order. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq_attid(ncid, NC_GLOBAL, ATT0, &attid_in)) ERR;
      if (attid_in != 0) ERR;
      if (nc_inq_attid(ncid, NC_GLOBAL, ATT1, &attid_in)) ERR;
      if (attid_in != 1) ERR;
      if (nc_close(ncid)) ERR;

      /* Now create a file with a variable, which has two atts. */
      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, 2, dimids, &varid)) ERR;
      if (nc_put_att_int(ncid, varid, ATT0, NC_INT, 1, &number)) ERR;
      if (nc_put_att_int(ncid, varid, ATT1, NC_INT, 1, &number)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Reopen the file and check the order of the attributes on the var. */
      if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
      if (nc_inq_attid(ncid, 0, ATT0, &attid_in)) ERR;
      if (attid_in != 0) ERR;
      if (nc_inq_attid(ncid, 0, ATT1, &attid_in)) ERR;
      if (attid_in != 1) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing attribute ordering some more...");

#define VAR_NAME "i"
#define A1_NAME "i"      
#define A2_NAME "f"      
#define A3_NAME "d"      
#define A1_LEN 3
#define A2_LEN 4
#define A3_LEN 5
   {
      int ncid;
      int varid, natts, nvars;
      double dvalue[] = {999.99, 999.99, 999.99, 999.99, 999.99};
      int varids[1];
      char name_in[NC_MAX_NAME + 1];

      /* Create a file with one var, and attach three atts to it. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, 0, NULL, &varid)) ERR;
      if (nc_put_att_double(ncid, varid, A1_NAME, NC_INT, A1_LEN, dvalue)) ERR;      
      if (nc_put_att_double(ncid, varid, A2_NAME, NC_INT, A2_LEN, dvalue)) ERR;      
      if (nc_put_att_double(ncid, varid, A3_NAME, NC_INT, A3_LEN, dvalue)) ERR;      
      if (nc_close(ncid)) ERR;
      
      /* Reopen the file and check. */
      if (nc_open(FILE_NAME, 0, &ncid)) ERR;
      if (nc_inq_varids(ncid, &nvars, varids)) ERR;
      if (nvars != 1 || varids[0] != 0) ERR;
      if (nc_inq_varnatts(ncid, 0, &natts)) ERR;
      if (natts != 3) ERR;
      if (nc_inq_attname(ncid, 0, 0, name_in)) ERR;
      if (strcmp(name_in, A1_NAME)) ERR;
      if (nc_inq_attname(ncid, 0, 1, name_in)) ERR;
      if (strcmp(name_in, A2_NAME)) ERR;
      if (nc_inq_attname(ncid, 0, 2, name_in)) ERR;
      if (strcmp(name_in, A3_NAME)) ERR;

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

   SUMMARIZE_ERR;
   printf("*** testing attribute ordering even more...");

   /* Test the ordering of atts for each cmode. */
   if (tst_att_ordering(NC_CLOBBER)) ERR;
   if (tst_att_ordering(NC_CLOBBER|NC_64BIT_OFFSET)) ERR;
   if (tst_att_ordering(NC_CLOBBER|NC_NETCDF4)) ERR;
   if (tst_att_ordering(NC_CLOBBER|NC_NETCDF4|NC_CLASSIC_MODEL)) ERR;

   SUMMARIZE_ERR;
   printf("*** testing attributes and enddef/redef...");

#define ATT_1 "a"
#define ATT_2 "b"
#define ATT_3 "c"
   {
      int ncid, att = 1;

      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL|NC_CLOBBER, &ncid)) ERR;
      if (nc_enddef(ncid)) ERR;
      if (nc_redef(ncid)) ERR;
      if (nc_put_att(ncid, NC_GLOBAL, ATT_1, NC_INT, 1, &att)) ERR;
      if (nc_put_att(ncid, NC_GLOBAL, ATT_2, NC_INT, 1, &att)) ERR;
      if (nc_put_att(ncid, NC_GLOBAL, ATT_3, NC_INT, 1, &att)) ERR;

      if (nc_close(ncid)) ERR;

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

   SUMMARIZE_ERR;
   printf("*** testing copy of simple global atts...");
   {      
      int ncid, ncid2;
      nc_type att_type;
      size_t att_len;
      int i;

      char *speech_in;
      signed char schar_in[ATT_LEN], schar_out[ATT_LEN] = {NC_MIN_BYTE, 1, NC_MAX_BYTE};
      unsigned char uchar_in[ATT_LEN], uchar_out[ATT_LEN] = {0, 128, NC_MAX_CHAR};
      short short_in[ATT_LEN], short_out[ATT_LEN] = {NC_MIN_SHORT, -128, NC_MAX_SHORT};
      int int_in[ATT_LEN], int_out[ATT_LEN] = {-100000, 128, 100000};
      float float_in[ATT_LEN], float_out[ATT_LEN] = {.5, 0.25, 0.125};
      double double_in[ATT_LEN], double_out[ATT_LEN] = {0.25, .5, 0.125};
      unsigned short ushort_in[ATT_LEN], ushort_out[ATT_LEN] = {0, 128, NC_MAX_USHORT};
      unsigned int uint_in[ATT_LEN], uint_out[ATT_LEN] = {0, 128, NC_MAX_UINT};
      unsigned long long uint64_in[ATT_LEN], uint64_out[ATT_LEN] = {0, 128, 18446744073709551612ULL};
      long long int64_in[ATT_LEN], int64_out[ATT_LEN] = {NC_MIN_INT64, 128, NC_MAX_INT64};

      /* Create a file with a global attribute of each type. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, strlen(speech)+1, speech)) ERR;      
      if (nc_put_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, NC_BYTE, ATT_LEN, schar_out)) ERR;      
      if (nc_put_att_uchar(ncid, NC_GLOBAL, ATT_UCHAR_NAME, NC_UBYTE, ATT_LEN, uchar_out)) ERR;
      if (nc_put_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, NC_SHORT, ATT_LEN, short_out)) ERR;      
      if (nc_put_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, NC_INT, ATT_LEN, int_out)) ERR;      
      if (nc_put_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, NC_FLOAT, ATT_LEN, float_out)) ERR;      
      if (nc_put_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, NC_DOUBLE, ATT_LEN, double_out)) ERR;      
      if (nc_put_att_ushort(ncid, NC_GLOBAL, ATT_USHORT_NAME, NC_USHORT, ATT_LEN, ushort_out)) ERR;      
      if (nc_put_att_uint(ncid, NC_GLOBAL, ATT_UINT_NAME, NC_UINT, ATT_LEN, uint_out)) ERR;      
      if (nc_put_att_longlong(ncid, NC_GLOBAL, ATT_INT64_NAME, NC_INT64, ATT_LEN, int64_out)) ERR;      
      if (nc_put_att_ulonglong(ncid, NC_GLOBAL, ATT_UINT64_NAME, NC_UINT64, ATT_LEN, uint64_out)) ERR;      

      /* Create another file and copy all the attributes. */
      if (nc_create(FILE_NAME2, NC_NETCDF4, &ncid2)) ERR;      
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_TEXT_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_SCHAR_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_UCHAR_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_SHORT_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_INT_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_FLOAT_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_USHORT_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_UINT_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_INT64_NAME, ncid2, NC_GLOBAL)) ERR;
      if (nc_copy_att(ncid, NC_GLOBAL, ATT_UINT64_NAME, ncid2, NC_GLOBAL)) ERR;

      /* Close both files. */
      if (nc_close(ncid)) ERR;
      if (nc_close(ncid2)) ERR;

      /* Open the file and check attributes. */
      if (nc_open(FILE_NAME2, 0, &ncid)) ERR;
      /* Check text. */
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_TEXT_NAME, &att_type, &att_len)) ERR;
      if (att_type != NC_CHAR || att_len != strlen(speech) + 1) ERR;
      if (!(speech_in = malloc(att_len + 1))) ERR;
      if (nc_get_att_text(ncid, NC_GLOBAL, ATT_TEXT_NAME, speech_in)) ERR;      
      if (strcmp(speech, speech_in)) ERR;
      free(speech_in);
      /* Check numeric values. */
      if (nc_get_att_schar(ncid, NC_GLOBAL, ATT_SCHAR_NAME, schar_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (schar_in[i] != schar_out[i]) ERR;
      if (nc_get_att_uchar(ncid, NC_GLOBAL, ATT_UCHAR_NAME, uchar_in)) ERR;
      for (i = 0; i < ATT_LEN; i++)
	 if (uchar_in[i] != uchar_out[i]) ERR;
      if (nc_get_att_short(ncid, NC_GLOBAL, ATT_SHORT_NAME, short_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (short_in[i] != short_out[i]) ERR;
      if (nc_get_att_int(ncid, NC_GLOBAL, ATT_INT_NAME, int_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (int_in[i] != int_out[i]) ERR;
      if (nc_get_att_float(ncid, NC_GLOBAL, ATT_FLOAT_NAME, float_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (float_in[i] != float_out[i]) ERR;
      if (nc_get_att_double(ncid, NC_GLOBAL, ATT_DOUBLE_NAME, double_in)) ERR;      
      for (i = 0; i < ATT_LEN; i++)
	 if (double_in[i] != double_out[i]) ERR;
      if (nc_get_att_ushort(ncid, NC_GLOBAL, ATT_USHORT_NAME, ushort_in)) ERR;
      for (i = 0; i < ATT_LEN; i++)
	 if (ushort_in[i] != ushort_out[i]) ERR;
      if (nc_get_att_uint(ncid, NC_GLOBAL, ATT_UINT_NAME, uint_in)) ERR;
      for (i = 0; i < ATT_LEN; i++)
	 if (uint_in[i] != uint_out[i]) ERR;
      if (nc_get_att_longlong(ncid, NC_GLOBAL, ATT_INT64_NAME, int64_in)) ERR;
      for (i = 0; i < ATT_LEN; i++)
	 if (int64_in[i] != int64_out[i]) ERR;
      if (nc_get_att_ulonglong(ncid, NC_GLOBAL, ATT_UINT64_NAME, uint64_in)) ERR;
      for (i = 0; i < ATT_LEN; i++)
	 if (uint64_in[i] != uint64_out[i]) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
Exemplo n.º 22
0
static GDALDataset *
GMTCreateCopy( const char * pszFilename, GDALDataset *poSrcDS,
               int bStrict, CPL_UNUSED char ** papszOptions,
               CPL_UNUSED GDALProgressFunc pfnProgress,
               CPL_UNUSED void * pProgressData )
{
/* -------------------------------------------------------------------- */
/*      Figure out general characteristics.                             */
/* -------------------------------------------------------------------- */
    nc_type nc_datatype;
    GDALRasterBand *poBand;
    int nXSize, nYSize;

    CPLMutexHolderD(&hNCMutex);

    if( poSrcDS->GetRasterCount() != 1 )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "Currently GMT export only supports 1 band datasets." );
        return NULL;
    }

    poBand = poSrcDS->GetRasterBand(1);

    nXSize = poSrcDS->GetRasterXSize();
    nYSize = poSrcDS->GetRasterYSize();
    
    if( poBand->GetRasterDataType() == GDT_Int16 )
        nc_datatype = NC_SHORT;
    else if( poBand->GetRasterDataType() == GDT_Int32 )
        nc_datatype = NC_INT;
    else if( poBand->GetRasterDataType() == GDT_Float32 )
        nc_datatype = NC_FLOAT;
    else if( poBand->GetRasterDataType() == GDT_Float64 )
        nc_datatype = NC_DOUBLE;
    else if( bStrict )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "Band data type %s not supported in GMT, giving up.",
                  GDALGetDataTypeName( poBand->GetRasterDataType() ) );
        return NULL;
    }
    else if( poBand->GetRasterDataType() == GDT_Byte )
        nc_datatype = NC_SHORT;
    else if( poBand->GetRasterDataType() == GDT_UInt16 )
        nc_datatype = NC_INT;
    else if( poBand->GetRasterDataType() == GDT_UInt32 )
        nc_datatype = NC_INT;
    else 
        nc_datatype = NC_FLOAT;
    
/* -------------------------------------------------------------------- */
/*      Establish bounds from geotransform.                             */
/* -------------------------------------------------------------------- */
    double adfGeoTransform[6];
    double dfXMax, dfYMin;

    poSrcDS->GetGeoTransform( adfGeoTransform );
    
    if( adfGeoTransform[2] != 0.0 || adfGeoTransform[4] != 0.0 )
    {
        CPLError( bStrict ? CE_Failure : CE_Warning, CPLE_AppDefined, 
                  "Geotransform has rotational coefficients not supported in GMT." );
        if( bStrict )
            return NULL;
    }

    dfXMax = adfGeoTransform[0] + adfGeoTransform[1] * nXSize;
    dfYMin = adfGeoTransform[3] + adfGeoTransform[5] * nYSize;
    
/* -------------------------------------------------------------------- */
/*      Create base file.                                               */
/* -------------------------------------------------------------------- */
    int cdfid, err;

    err = nc_create (pszFilename, NC_CLOBBER,&cdfid);
    if( err != NC_NOERR )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "nc_create(%s): %s", 
                  pszFilename, nc_strerror( err ) );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Define the dimensions and so forth.                             */
/* -------------------------------------------------------------------- */
    int side_dim, xysize_dim, dims[1];
    int x_range_id, y_range_id, z_range_id, inc_id, nm_id, z_id;

    nc_def_dim(cdfid, "side", 2, &side_dim);
    nc_def_dim(cdfid, "xysize", (int) (nXSize * nYSize), &xysize_dim);

    dims[0]		= side_dim;
    nc_def_var (cdfid, "x_range", NC_DOUBLE, 1, dims, &x_range_id);
    nc_def_var (cdfid, "y_range", NC_DOUBLE, 1, dims, &y_range_id);
    nc_def_var (cdfid, "z_range", NC_DOUBLE, 1, dims, &z_range_id);
    nc_def_var (cdfid, "spacing", NC_DOUBLE, 1, dims, &inc_id);
    nc_def_var (cdfid, "dimension", NC_LONG, 1, dims, &nm_id);

    dims[0]		= xysize_dim;
    nc_def_var (cdfid, "z", nc_datatype, 1, dims, &z_id);

/* -------------------------------------------------------------------- */
/*      Assign attributes.                                              */
/* -------------------------------------------------------------------- */
    double default_scale = 1.0;
    double default_offset = 0.0;
    int default_node_offset = 1; // pixel is area

    nc_put_att_text (cdfid, x_range_id, "units", 7, "meters");
    nc_put_att_text (cdfid, y_range_id, "units", 7, "meters");
    nc_put_att_text (cdfid, z_range_id, "units", 7, "meters");

    nc_put_att_double (cdfid, z_id, "scale_factor", NC_DOUBLE, 1, 
                       &default_scale );
    nc_put_att_double (cdfid, z_id, "add_offset", NC_DOUBLE, 1, 
                       &default_offset );

    nc_put_att_int (cdfid, z_id, "node_offset", NC_LONG, 1, 
                    &default_node_offset );
    nc_put_att_text (cdfid, NC_GLOBAL, "title", 1, "");
    nc_put_att_text (cdfid, NC_GLOBAL, "source", 1, "");
	
    /* leave define mode */
    nc_enddef (cdfid);

/* -------------------------------------------------------------------- */
/*      Get raster min/max.                                             */
/* -------------------------------------------------------------------- */
    double adfMinMax[2];
    GDALComputeRasterMinMax( (GDALRasterBandH) poBand, FALSE, adfMinMax );
	
/* -------------------------------------------------------------------- */
/*      Set range variables.                                            */
/* -------------------------------------------------------------------- */
    size_t start[2], edge[2];
    double dummy[2];
    int nm[2];
	
    start[0] = 0;
    edge[0] = 2;
    dummy[0] = adfGeoTransform[0];
    dummy[1] = dfXMax;
    nc_put_vara_double(cdfid, x_range_id, start, edge, dummy);

    dummy[0] = dfYMin;
    dummy[1] = adfGeoTransform[3];
    nc_put_vara_double(cdfid, y_range_id, start, edge, dummy);

    dummy[0] = adfGeoTransform[1];
    dummy[1] = -adfGeoTransform[5];
    nc_put_vara_double(cdfid, inc_id, start, edge, dummy);

    nm[0] = nXSize;
    nm[1] = nYSize;
    nc_put_vara_int(cdfid, nm_id, start, edge, nm);

    nc_put_vara_double(cdfid, z_range_id, start, edge, adfMinMax);

/* -------------------------------------------------------------------- */
/*      Write out the image one scanline at a time.                     */
/* -------------------------------------------------------------------- */
    double *padfData;
    int  iLine;

    padfData = (double *) CPLMalloc( sizeof(double) * nXSize );

    edge[0] = nXSize;
    for( iLine = 0; iLine < nYSize; iLine++ )
    {
        start[0] = iLine * nXSize;
        poBand->RasterIO( GF_Read, 0, iLine, nXSize, 1, 
                          padfData, nXSize, 1, GDT_Float64, 0, 0, NULL );
        err = nc_put_vara_double( cdfid, z_id, start, edge, padfData );
        if( err != NC_NOERR )
        {
            CPLError( CE_Failure, CPLE_AppDefined, 
                      "nc_put_vara_double(%s): %s", 
                      pszFilename, nc_strerror( err ) );
            nc_close (cdfid);
            return( NULL );
        }
    }
    
    CPLFree( padfData );

/* -------------------------------------------------------------------- */
/*      Close file, and reopen.                                         */
/* -------------------------------------------------------------------- */
    nc_close (cdfid);

/* -------------------------------------------------------------------- */
/*      Re-open dataset, and copy any auxiliary pam information.         */
/* -------------------------------------------------------------------- */
    GDALPamDataset *poDS = (GDALPamDataset *)
        GDALOpen( pszFilename, GA_ReadOnly );

    if( poDS )
        poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT );

    return poDS;
}
Exemplo n.º 23
0
int
main(int argc, char **argv)
{
   char *valid[] = {
       /* pressure in 23 languages */
       "\xd8\xa7\xd9\x84\xd8\xb6\xd8\xba\xd8\xb7",
       "\xd0\xbd\xd0\xb0\xd0\xbb\xd1\x8f\xd0\xb3\xd0\xb0\xd0\xbd\xd0\xb5",
       "\xe5\x8e\x8b\xe5\x8a\x9b",
       "\xe5\xa3\x93\xe5\x8a\x9b",
       "pritisak",
       "tlaku",
       "pres",
       "druk",
       "pressure",
       "paine",
       "pression",
       "Druck",
       "\xcf\x80\xce\xaf\xce\xb5\xcf\x83\xce\xb7",
       "\xe0\xa4\xa6\xe0\xa4\xac\xe0\xa4\xbe\xe0\xa4\xb5",
       "pressione",
       "\xe5\x9c\xa7\xe5\x8a\x9b",
       "\xec\x95\x95\xeb\xa0\xa5",
       "press",
       "ci\xc5\x9bnienie",
       "Press\xc3\xa3o",
       "presiune",
       "\xd0\xb4\xd0\xb0\xd0\xb2\xd0\xbb\xd0\xb5\xd0\xbd\xd0\xb8\xd0\xb5",
       "presi\xc3\xb3n",
       /* special characters in names, numeric characters at the start of names */
       "has blank",
       "has:colon",
       "a",
       "A",
       "0leading_numeric_char",
       "1",
       "0x123"
   };
   char *notvalid[] = {
       "-leading_special_char",
       "trailing_space ",
       "trailing_tab\t",
       "trailing_newline\n",
       "has_control_char_\a_in_name",
       "has ascii_del_\x7f_in name",
       /* Invalid UTF-8 of various sorts, thanks to Markus Kuhn */
       "\xA0\xB0\xC0\xD0",
       "xyz\x80", 		/* unexpected continuation bytes */
       "\x80xyz",
       "xyz\xBF",
       "\xBFxyz",
       "\xC0xyz",		/* lonely start characters */
       "x\xC0yz",
       "xy\xC0z",
       "xyz\xC0",
       "\xDFxyz",
       "x\xDFyz",
       "xy\xDFz",
       "xyz\xDF",
       "\xE0xyz",
       "x\xE0yz",
       "xy\xE0z",
       "xyz\xE0",
       "\xE0\xBFxy",
       "x\xE0\xBFy",
       "xy\xE0\xBF",
       "\xEFxyz",
       "x\xEFyz",
       "xy\xEFz",
       "xyz\xEF",
       "\xEF\x80xy",
       "x\xEF\x80y",
       "xy\xEF\x80",
       "\xF0xyz",
       "x\xF0yz",
       "xy\xF0z",
       "xyz\xF0",
       "\xF7xyz",
       "x\xF7yz",
       "xy\xF7z",
       "xyz\xF7",
       "\xF8xyz",
       "x\xF8yz",
       "xy\xF8z",
       "xyz\xF8",
       "\xFBxyz",
       "x\xFByz",
       "xy\xFBz",
       "xyz\xFB",
       "\xFCxyz",
       "x\xFCyz",
       "xy\xFCz",
       "xyz\xFC",
       "\xFDxyz",
       "x\xFDyz",
       "xy\xFDz",
       "xyz\xFD",
       "\xC0\xC0xy",		/* last continuation byte missing */
       "x\xC0\xC0y",
       "xy\xC0\xC0",
       "\xDF\xDFxy",
       "x\xDF\xDFy",
       "xy\xDF\xDF",
       "\xE0\x80xy",
       "x\xE0\x80y",
       "xy\xE0\x80",
       "\xEF\x80xy",
       "x\xEF\x80y",
       "xy\xEF\x80",
       "\xF0\x80\x80x",
       "x\xF0\x80\x80",
       "\xF7\x80\x80x",
       "x\xF7\x80\x80",
       "\xF8\x80\x80\x80x",
       "x\xF8\x80\x80\x80",
       "\xFB\x80\x80\x80x",
       "x\xFB\x80\x80\x80",
       "\xFC\x80\x80\x80\x80x",
       "x\xFC\x80\x80\x80\x80",
       "\xFD\x80\x80\x80\x80x",
       "x\xFD\x80\x80\x80\x80",
       "\xFExyz",		/* impossible bytes */
       "x\xFEyz",
       "xy\xFEz",
       "xyz\xFE",
       "\xFFxyz",
       "x\xFFyz",
       "xy\xFFz",
       "xyz\xFF",
       "\xC0\xAFxy",		/* overlong sequences */
       "x\xC0\xAFy",
       "xy\xC0\xAF",
       "\xE0\x80\xAFx",
       "x\xE0\x80\xAF",
       "\xF0\x80\x80\xAFx",
       "x\xF0\x80\x80\xAF",
       "\xF8\x80\x80\x80\xAFx",
       "x\xF8\x80\x80\x80\xAF",
       "\xFC\x80\x80\x80\x80\xAFx",
       "x\xFC\x80\x80\x80\x80\xAF",
       "\xC1\xBFxy",
       "x\xC1\xBFy",
       "xy\xC1\xBF",
       "\xE0\x9F\xBFx",
       "x\xE0\x9F\xBF",
       "\xF0\x8F\xBF\xBFx",
       "x\xF0\x8F\xBF\xBF",
       "\xF8\x87\xBF\xBF\xBFx",
       "x\xF8\x87\xBF\xBF\xBF",
       "\xFC\x83\xBF\xBF\xBF\xBFx",
       "x\xFC\x83\xBF\xBF\xBF\xBF",
       "x\xC0\x80",		/* overlong NULs */
       "x\xE0\x80\x80",
       "x\xF0\x80\x80\x80",
       "x\xF8\x80\x80\x80\x80",
       "x\xFC\x80\x80\x80\x80\x80",
       /* single UTF-16 surrogates */
       "x\xED\xA0\x80",
       "x\xED\xAD\xBF",
       "x\xED\xAE\x80",
       "x\xED\xAF\xBF",
       "x\xED\xB0\x80",
       "x\xED\xBE\x80",
       "x\xED\xBF\xBF",
       "x\xED\xA0\x80\xED\xB0\x80", /* paired UTF-16 surrogates */
       "x\xED\xA0\x80\xED\xBF\xBF",
       "x\xED\xAD\xBF\xED\xB0\x80",
       "x\xED\xAD\xBF\xED\xBF\xBF",
       "x\xED\xAE\x80\xED\xB0\x80",
       "x\xED\xAE\x80\xED\xBF\xBF",
       "x\xED\xAF\xBF\xED\xB0\x80",
       "x\xED\xAF\xBF\xED\xBF\xBF",
       "x\xEF\xBF\xBE",		/* other illegal code positions */
       "x\xEF\xBF\xBF"
   };
   int i, j;
#define NUM_BAD (sizeof notvalid / sizeof notvalid[0])
#define NUM_GOOD (sizeof valid / sizeof valid[0])
   int ncid, dimid, varid, res;
   double attvals[] = {-2.0};
   double attvals_in[1];
#define NATTVALS (sizeof attvals / sizeof attvals[0])
   char *attstring = "text";
#define MAX_ATTSTRING_LEN 100
   char attstr_in[MAX_ATTSTRING_LEN];
   int dimids[NUM_GOOD];
   int varids[NUM_GOOD];
#if 0
   int attnums[NUM_GOOD];
#endif
   char *testfile = FILE_NAME;
   int formats[] = {
       NC_FORMAT_CLASSIC
       ,
       NC_FORMAT_64BIT
#ifdef USE_NETCDF4
       ,
       NC_FORMAT_NETCDF4
       ,
       NC_FORMAT_NETCDF4_CLASSIC
#endif	/* USE_NETCDF4 */
   };
   int num_formats = (sizeof formats) / (sizeof formats[0]);
   char *format_names[] = {
       "classic", "64-bit offset", "netCDF-4/HDF5", "netCDF-4 classic model"
   };

   printf("\n*** testing names with file %s...\n", testfile);
   for (j = 0; j < num_formats; j++)
   {
       printf("*** switching to netCDF %s format...", format_names[j]);
       nc_set_default_format(formats[j], NULL);
       if((res = nc_create(testfile, NC_CLOBBER, &ncid)))
	   ERR;

       /* Define dimensions, variables, and attributes with various
	* acceptable names */
       for (i = 0; i < NUM_GOOD; i++) {
	   if ((res = nc_def_dim(ncid, valid[i], DIMLEN, &dimid)))
	       ERR;
	   dimids[i] = dimid;
	   /* Define variable with same name */
	   if ((res = nc_def_var(ncid, valid[i], NC_FLOAT, NDIMS, &dimids[i],
				 &varid)))
	       ERR;
	   varids[i] = varid;
	   /* Define variable and global attributes with same name and value */
	   if ((res = nc_put_att_text(ncid, varid, valid[i],
				      strlen(valid[i]), valid[i])))
	       ERR;
	   if ((res = nc_put_att_double(ncid, NC_GLOBAL, valid[i], NC_DOUBLE,
					NATTVALS, attvals)))
	       ERR;
#if 0
	   attnums[i] = i;
#endif
       }

       /* Try defining dimensions, variables, and attributes with various
	* bad names and make sure these are rejected */
       for (i = 0; i < NUM_BAD; i++) {
	   if ((res = nc_def_dim(ncid, notvalid[i], DIMLEN, &dimid))
	       != NC_EBADNAME) ERR;
	   if ((res = nc_def_var(ncid, notvalid[i], NC_FLOAT, NDIMS, dimids,
				 &varid))
	       != NC_EBADNAME) ERR;
	   if ((res = nc_put_att_text(ncid, varid, notvalid[i],
				      strlen(attstring), attstring))
	       != NC_EBADNAME) ERR;
	   if ((res = nc_put_att_double(ncid, NC_GLOBAL, notvalid[i], NC_DOUBLE,
					NATTVALS, attvals))
	       != NC_EBADNAME) ERR;
       }
       if ((res = nc_enddef(ncid)))
	   ERR;
       if ((res = nc_close(ncid)))
	   ERR;

       /* Check it out, make sure all objects with good names were defined OK */
       if ((res = nc_open(testfile, NC_NOWRITE, &ncid)))
	   ERR;
       for (i = 0; i < NUM_GOOD; i++) {
	   size_t attlen;
	   if ((res = nc_inq_dimid(ncid, valid[i], &dimid)) ||
	       dimid != dimids[i])
	       ERR;
	   if ((res = nc_inq_varid(ncid, valid[i], &varid)) ||
	       varid != varids[i])
	       ERR;
	   res = nc_inq_attlen(ncid, varid, valid[i], &attlen);
	   if ((res = nc_get_att_text(ncid, varid, valid[i], attstr_in)))
	       ERR;
	   attstr_in[attlen] = '\0';
	   if (strcmp(valid[i], attstr_in) != 0)
	       ERR;
	   if ((res = nc_get_att_double(ncid, NC_GLOBAL, valid[i],
					attvals_in))
	       || attvals[0] != attvals_in[0])
	       ERR;
       }
       if ((res = nc_close(ncid)))
	   ERR;
/*        (void) remove(testfile); */
       SUMMARIZE_ERR;
   }
   FINAL_RESULTS;

   return 0;
}
Exemplo n.º 24
0
int test_pio_attr(int flag)
{
   /* MPI stuff. */
   int mpi_size, mpi_rank;
   MPI_Comm comm = MPI_COMM_WORLD;
   MPI_Info info = MPI_INFO_NULL;

   /* Netcdf-4 stuff. */
   int ncid;
   int nvid;
   int j, i;

   double rh_range[2];
   static char title[] = "parallel attr to netCDF";
   nc_type    st_type,vr_type;
   size_t     vr_len,st_len;
   size_t     orivr_len;
   double *vr_val;
   char   *st_val;

   /* two dimensional integer data*/
   int dimids[NDIMS1];
   size_t start[NDIMS1];
   size_t count[NDIMS1];
   int *data;
   int *tempdata;

   /* Initialize MPI. */
   MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);
   MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);

   /* Create a parallel netcdf-4 file. */
/*    nc_set_log_level(NC_TURN_OFF_LOGGING); */
   /*    nc_set_log_level(3);*/

   if (nc_create_par(file_name, facc_type, comm, info, &ncid)) ERR;

   /* Create a 2-D variable so that an attribute can be added. */
   if (nc_def_dim(ncid, "d1", DIMSIZE2, dimids)) ERR;
   if (nc_def_dim(ncid, "d2", DIMSIZE, &dimids[1])) ERR;

   /* Create one var. */
   if (nc_def_var(ncid, "v1", NC_INT, NDIMS1, dimids, &nvid)) ERR;

   orivr_len = 2;
   rh_range[0] = 1.0;
   rh_range[1] = 1000.0;

   /* Write attributes of a variable */

   if (nc_put_att_double (ncid, nvid, "valid_range", NC_DOUBLE,
			  orivr_len, rh_range)) ERR;

   if (nc_put_att_text (ncid, nvid, "title", strlen(title),
			title)) ERR;

   /* Write global attributes */
   if (nc_put_att_double (ncid, NC_GLOBAL, "g_valid_range", NC_DOUBLE,
			  orivr_len, rh_range)) ERR;
   if (nc_put_att_text (ncid, NC_GLOBAL, "g_title", strlen(title), title)) ERR;

   if (nc_enddef(ncid)) ERR;

   /* Set up slab for this process. */
   start[0] = 0;
   start[1] = mpi_rank * DIMSIZE/mpi_size;
   count[0] = DIMSIZE2;
   count[1] = DIMSIZE/mpi_size;

   /* Access parallel */
   if (nc_var_par_access(ncid, nvid, flag)) ERR;

   /* Allocating data */
   data      = malloc(sizeof(int)*count[1]*count[0]);
   tempdata  = data;
   for(j = 0; j < count[0]; j++)
      for (i = 0; i < count[1]; i++)
      {
	 *tempdata = mpi_rank * (j + 1);
	 tempdata++;
      }

   if (nc_put_vara_int(ncid, nvid, start, count, data)) ERR;
   free(data);

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

   /* Read attributes */
if (nc_open_par(file_name, facc_type_open, comm, info, &ncid)) ERR;

   /* Set up slab for this process. */
   start[0] = 0;
   start[1] = mpi_rank * DIMSIZE/mpi_size;
   count[0] = DIMSIZE2;
   count[1] = DIMSIZE/mpi_size;

   /* Inquiry variable */
   if (nc_inq_varid(ncid, "v1", &nvid)) ERR;

   /* Access parallel */
   if (nc_var_par_access(ncid, nvid, flag)) ERR;

   /* Inquiry attribute */
   if (nc_inq_att (ncid, nvid, "valid_range", &vr_type, &vr_len)) ERR;

   /* check stuff */
   if(vr_type != NC_DOUBLE || vr_len != orivr_len) ERR;

   vr_val = (double *) malloc(vr_len * sizeof(double));

   /* Get variable attribute values */
   if (nc_get_att_double(ncid, nvid, "valid_range", vr_val)) ERR;

   /* Check variable attribute value */
   for(i = 0; i < vr_len; i++)
      if (vr_val[i] != rh_range[i])
	 ERR_RET;
   free(vr_val);

   /* Inquiry global attribute */
   if (nc_inq_att (ncid, NC_GLOBAL, "g_valid_range", &vr_type, &vr_len)) ERR;

   /* Check stuff. */
   if(vr_type != NC_DOUBLE || vr_len != orivr_len) ERR;

   /* Obtain global attribute value */
   vr_val = (double *) malloc(vr_len * sizeof(double));
   if (nc_get_att_double(ncid, NC_GLOBAL, "g_valid_range", vr_val)) ERR;

   /* Check global attribute value */
   for(i = 0; i < vr_len; i++)
      if (vr_val[i] != rh_range[i]) ERR_RET;
   free(vr_val);

   /* Inquiry string attribute of a variable */
   if (nc_inq_att (ncid, nvid, "title", &st_type, &st_len)) ERR;

   /* check string attribute length */
   if(st_len != strlen(title)) ERR_RET;

   /* Check string attribute type */
   if(st_type != NC_CHAR) ERR_RET;

   /* Allocate meory for string attribute */
   st_val = (char *) malloc(st_len * (sizeof(char)));

   /* Obtain variable string attribute value */
   if (nc_get_att_text(ncid, nvid,"title", st_val)) ERR;

   /*check string value */
   if(strncmp(st_val,title,st_len)) {
      free(st_val);
      ERR_RET;
   }
   free(st_val);

   /*Inquiry global attribute */
   if (nc_inq_att (ncid, NC_GLOBAL, "g_title", &st_type, &st_len)) ERR;

   /* check attribute length*/
   if(st_len != strlen(title)) ERR_RET;

   /*check attribute type*/
   if(st_type != NC_CHAR) ERR_RET;

   /* obtain global string attribute value */
   st_val = (char*)malloc(st_len*sizeof(char));
   if (nc_get_att_text(ncid, NC_GLOBAL,"g_title", st_val)) ERR;

   /* check attribute value */
   if(strncmp(st_val,title,st_len)){
      free(st_val);
      ERR_RET;
   }
   free(st_val);

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

   return 0;
}
Exemplo n.º 25
0
// NetcdfFile::NC_create()
int NetcdfFile::NC_create(std::string const& Name, NCTYPE type, int natomIn,
                          CoordinateInfo const& coordInfo, std::string const& title)
{
    if (Name.empty()) return 1;
    int dimensionID[NC_MAX_VAR_DIMS];
    int NDIM;
    nc_type dataType;

    if (ncdebug_>1)
        mprintf("DEBUG: NC_create: %s  natom=%i V=%i F=%i box=%i  temp=%i  time=%i\n",
                Name.c_str(),natomIn,(int)coordInfo.HasVel(),
                (int)coordInfo.HasForce(),(int)coordInfo.HasBox(),
                (int)coordInfo.HasTemp(),(int)coordInfo.HasTime());

    if ( checkNCerr( nc_create( Name.c_str(), NC_64BIT_OFFSET, &ncid_) ) )
        return 1;

    ncatom_ = natomIn;
    ncatom3_ = ncatom_ * 3;

    // Set number of dimensions based on file type
    switch (type) {
    case NC_AMBERENSEMBLE:
        NDIM = 4;
        dataType = NC_FLOAT;
        break;
    case NC_AMBERTRAJ:
        NDIM = 3;
        dataType = NC_FLOAT;
        break;
    case NC_AMBERRESTART:
        NDIM = 2;
        dataType = NC_DOUBLE;
        break;
    default:
        mprinterr("Error: NC_create (%s): Unrecognized type (%i)\n",Name.c_str(),(int)type);
        return 1;
    }

    if (type == NC_AMBERENSEMBLE) {
        // Ensemble dimension for ensemble
        if (coordInfo.EnsembleSize() < 1) {
            mprinterr("Internal Error: NetcdfFile: ensembleSize < 1\n");
            return 1;
        }
        if ( checkNCerr(nc_def_dim(ncid_, NCENSEMBLE, coordInfo.EnsembleSize(), &ensembleDID_)) ) {
            mprinterr("Error: Defining ensemble dimension.\n");
            return 1;
        }
        dimensionID[1] = ensembleDID_;
    }
    ncframe_ = 0;
    if (type == NC_AMBERTRAJ || type == NC_AMBERENSEMBLE) {
        // Frame dimension for traj
        if ( checkNCerr( nc_def_dim( ncid_, NCFRAME, NC_UNLIMITED, &frameDID_)) ) {
            mprinterr("Error: Defining frame dimension.\n");
            return 1;
        }
        // Since frame is UNLIMITED, it must be lowest dim.
        dimensionID[0] = frameDID_;
    }
    // Time variable and units
    if (coordInfo.HasTime()) {
        if ( checkNCerr( nc_def_var(ncid_, NCTIME, dataType, NDIM-2, dimensionID, &timeVID_)) ) {
            mprinterr("Error: Defining time variable.\n");
            return 1;
        }
        if ( checkNCerr( nc_put_att_text(ncid_, timeVID_, "units", 10, "picosecond")) ) {
            mprinterr("Error: Writing time VID units.\n");
            return 1;
        }
    }
    // Spatial dimension and variable
    if ( checkNCerr( nc_def_dim( ncid_, NCSPATIAL, 3, &spatialDID_)) ) {
        mprinterr("Error: Defining spatial dimension.\n");
        return 1;
    }
    dimensionID[0] = spatialDID_;
    if ( checkNCerr( nc_def_var( ncid_, NCSPATIAL, NC_CHAR, 1, dimensionID, &spatialVID_)) ) {
        mprinterr("Error: Defining spatial variable.\n");
        return 1;
    }
    // Atom dimension
    if ( checkNCerr( nc_def_dim( ncid_, NCATOM, ncatom_, &atomDID_)) ) {
        mprinterr("Error: Defining atom dimension.\n");
        return 1;
    }
    // Setup dimensions for Coords/Velocity
    // NOTE: THIS MUST BE MODIFIED IF NEW TYPES ADDED
    if (type == NC_AMBERENSEMBLE) {
        dimensionID[0] = frameDID_;
        dimensionID[1] = ensembleDID_;
        dimensionID[2] = atomDID_;
        dimensionID[3] = spatialDID_;
    } else if (type == NC_AMBERTRAJ) {
        dimensionID[0] = frameDID_;
        dimensionID[1] = atomDID_;
        dimensionID[2] = spatialDID_;
    } else {
        dimensionID[0] = atomDID_;
        dimensionID[1] = spatialDID_;
    }
    // Coord variable
    if ( checkNCerr( nc_def_var( ncid_, NCCOORDS, dataType, NDIM, dimensionID, &coordVID_)) ) {
        mprinterr("Error: Defining coordinates variable.\n");
        return 1;
    }
    if ( checkNCerr( nc_put_att_text( ncid_, coordVID_, "units", 8, "angstrom")) ) {
        mprinterr("Error: Writing coordinates variable units.\n");
        return 1;
    }
    // Velocity variable
    if (coordInfo.HasVel()) {
        if ( checkNCerr( nc_def_var( ncid_, NCVELO, dataType, NDIM, dimensionID, &velocityVID_)) ) {
            mprinterr("Error: Defining velocities variable.\n");
            return 1;
        }
        if ( checkNCerr( nc_put_att_text( ncid_, velocityVID_, "units", 19, "angstrom/picosecond")) )
        {
            mprinterr("Error: Writing velocities variable units.\n");
            return 1;
        }
        if ( checkNCerr( nc_put_att_double( ncid_, velocityVID_, "scale_factor", NC_DOUBLE, 1,
                                            &Constants::AMBERTIME_TO_PS)) )
        {
            mprinterr("Error: Writing velocities scale factor.\n");
            return 1;
        }
    }
    // Force variable
    if (coordInfo.HasForce()) {
        if ( checkNCerr( nc_def_var( ncid_, NCFRC, dataType, NDIM, dimensionID, &frcVID_)) ) {
            mprinterr("Error: Defining forces variable\n");
            return 1;
        }
        if ( checkNCerr( nc_put_att_text( ncid_, frcVID_, "units", 25, "kilocalorie/mole/angstrom")) )
        {
            mprinterr("Error: Writing forces variable units.\n");
            return 1;
        }
    }
    // Replica Temperature
    if (coordInfo.HasTemp()) {
        // NOTE: Setting dimensionID should be OK for Restart, will not be used.
        dimensionID[0] = frameDID_;
        if ( NC_defineTemperature( dimensionID, NDIM-2 ) ) return 1;
    }
    // Replica indices
    int remDimTypeVID = -1;
    if (coordInfo.HasReplicaDims()) {
        // Define number of replica dimensions
        remd_dimension_ = coordInfo.ReplicaDimensions().Ndims();
        int remDimDID = -1;
        if ( checkNCerr(nc_def_dim(ncid_, NCREMD_DIMENSION, remd_dimension_, &remDimDID)) ) {
            mprinterr("Error: Defining replica indices dimension.\n");
            return 1;
        }
        dimensionID[0] = remDimDID;
        // For each dimension, store the type
        if ( checkNCerr(nc_def_var(ncid_, NCREMD_DIMTYPE, NC_INT, 1, dimensionID, &remDimTypeVID)) )
        {
            mprinterr("Error: Defining replica dimension type variable.\n");
            return 1;
        }
        // Need to store the indices of replica in each dimension each frame
        // NOTE: THIS MUST BE MODIFIED IF NEW TYPES ADDED
        if (type == NC_AMBERENSEMBLE) {
            dimensionID[0] = frameDID_;
            dimensionID[1] = ensembleDID_;
            dimensionID[2] = remDimDID;
        } else if (type == NC_AMBERTRAJ) {
            dimensionID[0] = frameDID_;
            dimensionID[1] = remDimDID;
        } else {
            dimensionID[0] = remDimDID;
        }
        if (checkNCerr(nc_def_var(ncid_, NCREMD_INDICES, NC_INT, NDIM-1, dimensionID, &indicesVID_)))
        {
            mprinterr("Error: Defining replica indices variable ID.\n");
            return 1;
        }
        // TODO: Determine if groups are really necessary for restarts. If not,
        // remove from AmberNetcdf.F90.
    }
    // Box Info
    if (coordInfo.HasBox()) {
        // Cell Spatial
        if ( checkNCerr( nc_def_dim( ncid_, NCCELL_SPATIAL, 3, &cell_spatialDID_)) ) {
            mprinterr("Error: Defining cell spatial dimension.\n");
            return 1;
        }
        dimensionID[0] = cell_spatialDID_;
        if ( checkNCerr( nc_def_var(ncid_, NCCELL_SPATIAL, NC_CHAR, 1, dimensionID, &cell_spatialVID_)))
        {
            mprinterr("Error: Defining cell spatial variable.\n");
            return 1;
        }
        // Cell angular
        if ( checkNCerr( nc_def_dim( ncid_, NCLABEL, NCLABELLEN, &labelDID_)) ) {
            mprinterr("Error: Defining label dimension.\n");
            return 1;
        }
        if ( checkNCerr( nc_def_dim( ncid_, NCCELL_ANGULAR, 3, &cell_angularDID_)) ) {
            mprinterr("Error: Defining cell angular dimension.\n");
            return 1;
        }
        dimensionID[0] = cell_angularDID_;
        dimensionID[1] = labelDID_;
        if ( checkNCerr( nc_def_var( ncid_, NCCELL_ANGULAR, NC_CHAR, 2, dimensionID,
                                     &cell_angularVID_)) )
        {
            mprinterr("Error: Defining cell angular variable.\n");
            return 1;
        }
        // Setup dimensions for Box
        // NOTE: This must be modified if more types added
        int boxdim;
        if (type == NC_AMBERENSEMBLE) {
            dimensionID[0] = frameDID_;
            dimensionID[1] = ensembleDID_;
            boxdim = 2;
        } else if (type == NC_AMBERTRAJ) {
            dimensionID[0] = frameDID_;
            boxdim = 1;
        } else {
            boxdim = 0;
        }
        dimensionID[boxdim] = cell_spatialDID_;
        if ( checkNCerr( nc_def_var( ncid_, NCCELL_LENGTHS, NC_DOUBLE, NDIM-1, dimensionID,
                                     &cellLengthVID_)) )
        {
            mprinterr("Error: Defining cell length variable.\n");
            return 1;
        }
        if ( checkNCerr( nc_put_att_text( ncid_, cellLengthVID_, "units", 8, "angstrom")) ) {
            mprinterr("Error: Writing cell length variable units.\n");
            return 1;
        }
        dimensionID[boxdim] = cell_angularDID_;
        if ( checkNCerr( nc_def_var( ncid_, NCCELL_ANGLES, NC_DOUBLE, NDIM-1, dimensionID,
                                     &cellAngleVID_)) )
        {
            mprinterr("Error: Defining cell angle variable.\n");
            return 1;
        }
        if ( checkNCerr( nc_put_att_text( ncid_, cellAngleVID_, "units", 6, "degree")) ) {
            mprinterr("Error: Writing cell angle variable units.\n");
            return 1;
        }
    }

    // Attributes
    if (checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"title",title.size(),title.c_str())) ) {
        mprinterr("Error: Writing title.\n");
        return 1;
    }
    if (checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"application",5,"AMBER")) ) {
        mprinterr("Error: Writing application.\n");
        return 1;
    }
    if (checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"program",7,"cpptraj")) ) {
        mprinterr("Error: Writing program.\n");
        return 1;
    }
    if (checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"programVersion",
                                   NETCDF_VERSION_STRLEN, NETCDF_VERSION_STRING)) )
    {
        mprinterr("Error: Writing program version.\n");
        return 1;
    }
    // TODO: Make conventions a static string
    bool errOccurred = false;
    if ( type == NC_AMBERENSEMBLE )
        errOccurred = checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"Conventions",13,"AMBERENSEMBLE"));
    else if ( type == NC_AMBERTRAJ )
        errOccurred = checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"Conventions",5,"AMBER"));
    else
        errOccurred = checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"Conventions",12,"AMBERRESTART"));
    if (errOccurred) {
        mprinterr("Error: Writing conventions.\n");
        return 1;
    }
    if (checkNCerr(nc_put_att_text(ncid_,NC_GLOBAL,"ConventionVersion",3,"1.0")) ) {
        mprinterr("Error: Writing conventions version.\n");
        return 1;
    }

    // Set fill mode
    if (checkNCerr(nc_set_fill(ncid_, NC_NOFILL, dimensionID))) {
        mprinterr("Error: NetCDF setting fill value.\n");
        return 1;
    }

    // End netcdf definitions
    if (checkNCerr(nc_enddef(ncid_))) {
        mprinterr("NetCDF error on ending definitions.");
        return 1;
    }

    // Specify spatial dimension labels
    start_[0] = 0;
    count_[0] = 3;
    char xyz[3];
    xyz[0] = 'x';
    xyz[1] = 'y';
    xyz[2] = 'z';
    if (checkNCerr(nc_put_vara_text(ncid_, spatialVID_, start_, count_, xyz))) {
        mprinterr("Error on NetCDF output of spatial VID 'x', 'y' and 'z'");
        return 1;
    }
    if ( coordInfo.HasBox() ) {
        xyz[0] = 'a';
        xyz[1] = 'b';
        xyz[2] = 'c';
        if (checkNCerr(nc_put_vara_text(ncid_, cell_spatialVID_, start_, count_, xyz))) {
            mprinterr("Error on NetCDF output of cell spatial VID 'a', 'b' and 'c'");
            return 1;
        }
        char abc[15] = { 'a', 'l', 'p', 'h', 'a',
                         'b', 'e', 't', 'a', ' ',
                         'g', 'a', 'm', 'm', 'a'
                       };
        start_[0] = 0;
        start_[1] = 0;
        count_[0] = 3;
        count_[1] = NCLABELLEN;
        if (checkNCerr(nc_put_vara_text(ncid_, cell_angularVID_, start_, count_, abc))) {
            mprinterr("Error on NetCDF output of cell angular VID 'alpha', 'beta ' and 'gamma'");
            return 1;
        }
    }

    // Store the type of each replica dimension.
    if (coordInfo.HasReplicaDims()) {
        ReplicaDimArray const& remdDim = coordInfo.ReplicaDimensions();
        start_[0] = 0;
        count_[0] = remd_dimension_;
        int* tempDims = new int[ remd_dimension_ ];
        for (int i = 0; i < remd_dimension_; ++i)
            tempDims[i] = remdDim[i];
        if (checkNCerr(nc_put_vara_int(ncid_, remDimTypeVID, start_, count_, tempDims))) {
            mprinterr("Error: writing replica dimension types.\n");
            delete[] tempDims;
            return 1;
        }
        delete[] tempDims;
    }

    return 0;
}
Exemplo n.º 26
0
int main() {

  double *data_out;       // buffer
  int nx = 1/DX;          // hyperslab and output buffer dimensions 
  int ny = 1/DY;
  // int i, j;
 
  // Allocate memory for data
  if((data_out = (double *)malloc(STEPS * nx * ny * sizeof(double))) == NULL)
    printf("Error malloc matrix data_out[%d]\n",nx * ny);

  // Create NetCDF file. NC_CLOBBER tells NetCDF to overwrite this file, if it already exists
  int ncid, retval;
  // if( retval = nc_create( NC_FILE_NAME_NETCDF, NC_CLOBBER|NC_NETCDF4, &ncid ) ) {
  if( retval = nc_create( NC_FILE_NAME_NETCDF, NC_CLOBBER, &ncid ) ) {
    ERR_NETCDF(retval);
  }

  // Define the x and y dimensions. NetCDF will hand back and ID for each.
  int x_dimid, y_dimid, t_dimid;
  if( retval = nc_def_dim( ncid, "x", nx, &x_dimid ) ) {
    ERR_NETCDF(retval);
  }
  if( retval = nc_def_dim( ncid, "y", ny, &y_dimid ) ) {
    ERR_NETCDF(retval);
  }
  
  // Define the t dimension at NetCDF.
  if( retval = nc_def_dim( ncid, "t", NC_UNLIMITED, &t_dimid ) ) {
    ERR_NETCDF(retval);
  }
  
  // Define coordinate variables for x and y at NetCDF
  int x_varid, y_varid, t_varid;
  if( retval = nc_def_var( ncid, "x", NC_DOUBLE, 1, &x_dimid, &x_varid ) ) {
    ERR_NETCDF(retval);
  }
  if( retval = nc_def_var( ncid, "y", NC_DOUBLE, 1, &y_dimid, &y_varid ) ) {
    ERR_NETCDF(retval);
  }
  if( retval = nc_def_var( ncid, "t", NC_DOUBLE, 1, &t_dimid, &t_varid ) ) {
    ERR_NETCDF(retval);
  }
  
  // Define the nc-variable to store temperature data. The t dimension should be the one which varies more slowly at NetCDF.
  int varid;
  int dimids[3] = { t_dimid, x_dimid, y_dimid };
  if( retval = nc_def_var( ncid, "temperature", NC_DOUBLE, 3, dimids, &varid )){
    ERR_NETCDF(retval);
  }

  // Write x, y, t and temperature units at NetCDF
  char * space_units = "meters";
  char * time_units = "seconds since start of the experiment";
  char * temp_units = "kelvin";
  if( retval = nc_put_att_text( ncid, x_varid, "units", strlen(space_units), space_units ) ) {
    ERR_NETCDF(retval);
  }
  if( retval = nc_put_att_text( ncid, y_varid, "units", strlen(space_units), space_units ) ) {
    ERR_NETCDF(retval);
  }
  if( retval = nc_put_att_text( ncid, t_varid, "units", strlen(time_units), time_units ) ) {
    ERR_NETCDF(retval);
  }
  if( retval = nc_put_att_text( ncid, varid, "units", strlen(temp_units), temp_units ) ) {
    ERR_NETCDF(retval);
  }
  double scale_factor = 300.0;
  if( retval = nc_put_att_double( ncid, varid, "scale_factor", NC_DOUBLE, 1, &scale_factor ) ) {
    ERR_NETCDF(retval);
  }

  // End define mode: this tells NetCDF that we are done defining metadata at NetCDF
  if( retval = nc_enddef( ncid ) ) {
    ERR_NETCDF(retval);
  }

  // Write x coordinates at NetCDF
  size_t pos;
  for( pos = 0; pos < nx; ++pos ) {
    double x = DX*pos;
    if( retval = nc_put_var1_double( ncid, x_varid, &pos, &x ) ) {
      ERR_NETCDF(retval);
    }
  }
  
  // Write y coordinates at NetCDF
  for( pos = 0; pos < ny; ++pos ) {
    double y = DY*pos;
    if( retval = nc_put_var1_double( ncid, y_varid, &pos, &y ) ) {
      ERR_NETCDF(retval);
    }
  }

  // Open an existing HDF5 file for Output buffer
  hid_t file_id = H5Fopen(H5_FILE_NAME_HDF5, H5F_ACC_RDONLY, H5P_DEFAULT);
  if( file_id < 0 ) { ERR_HDF5; }

  // Open an existing HDF5 dataset
  hid_t tempD = H5Dopen(file_id, "temperature", H5P_DEFAULT);
  if( tempD < 0 ) { ERR_HDF5; }

  // Returns an identifier for a copy of the dataspace for a dataset HDF5
  hid_t tempSel  = H5Dget_space (tempD);    /* dataspace handle */
  if( tempSel < 0 ) { ERR_HDF5; }

  // Returns the number of dimensions in the HDF5 dataspace if successful; otherwise returns a negative value
  int rank;
  rank  = H5Sget_simple_extent_ndims (tempSel);

  // Retrieves dataspace dimension size and maximum size HDF5
  hsize_t dims_out[2];    // HDF5 dataset dimensions
  hid_t status_n  = H5Sget_simple_extent_dims (tempSel, dims_out, NULL);
  if( status_n < 0 ) { ERR_HDF5; }
  
  // Display the number of dimensions in the HDF5 dataspace and the dataspace dimension size and maximum size 
  printf("\nRank: %d\nDimensions: %lu x %lu \n", rank, (unsigned long)(dims_out[0]), (unsigned long)(dims_out[1]));

  // Define hyperslab in the dataset HDF5
  hsize_t sel_offset_in[4] = {0,0,0,SECTION}; // The temperature value for the last interaction (STEPS) is chosen
  hsize_t sel_length_in[4] = {STEPS, nx, ny, 1};   
  H5Sselect_hyperslab( tempSel, H5S_SELECT_SET, sel_offset_in, NULL, sel_length_in, NULL );
  if( tempSel < 0 ) { ERR_HDF5; }

  // Define the memory dataspace HDF5
  hsize_t memSdim[4]={STEPS,nx,ny};
  hid_t memS = H5Screate_simple( 3, memSdim, NULL );
  if( memS < 0 ) { ERR_HDF5; }

  // Define memory HDF5 hyperslab
  hsize_t sel_offset_out[3] = {0,0,0};
  hsize_t sel_length_out[3] = {STEPS, nx, ny};
  H5Sselect_hyperslab( memS, H5S_SELECT_SET, sel_offset_out, NULL, sel_length_out, NULL );
  if( memS < 0 ) { ERR_HDF5; }

  // Read dataset tempD data from HDF5 hyperslab in the file into the hyperslab in memory
  hsize_t status = H5Dread (tempD, H5T_NATIVE_DOUBLE, memS, tempSel, H5P_DEFAULT, data_out);
  if( status < 0 ) { ERR_HDF5; }
  
  // printf ("Data:\n ");
  // for( i = 0; i < nx; ++i ) {
  //   for( j = 0; j < ny; ++j ) {
  //     printf("%f ", data_out[i*ny+j]);
  //   }
  //   printf("\n ");
  // }
  // printf("\n");

  // Write the data to the NETCDF file
  size_t corner_vector[3] = {0,0,0};
  size_t edge_lengths[3] = {STEPS, nx, ny};
  if(retval = nc_put_vara_double(ncid, varid, corner_vector, edge_lengths, data_out)){
    ERR_NETCDF(retval);
  }
  pos = 0;
  double tval = 0;
  if( retval = nc_put_var1_double( ncid, t_varid, &pos, &tval ) ) {
    ERR_NETCDF(retval);
  }

  // Close the HDF5 memspace
  if( H5Sclose( memS ) <  0 ) { ERR_HDF5; }

  // Close the HDF5 dataspace
  if( H5Sclose( tempSel ) <  0 ) { ERR_HDF5; }

  // Close the HDF5 dataset
  if( H5Dclose( tempD ) <  0 ) { ERR_HDF5; }

  // Close the HDF5 file
  if( H5Fclose( file_id ) <  0 ) { ERR_HDF5; }

  // Close the file. This frees up any internal NetCDF resources associated with the file, and flushes any buffers
  if( retval = nc_close( ncid ) ) {
    ERR_NETCDF(retval);
  }

  // Free memory
  free(data_out);

  return 0;
  
}
Exemplo n.º 27
0
    void CONetCDF4::writeAttribute_
       (const std::string & _attname, const double * _value, std::size_t _size, int _grpid, int _varid)
 {       
      CheckError(nc_put_att_double(_grpid, _varid, _attname.c_str(), NC_DOUBLE, _size, _value));
 }