コード例 #1
0
int
main(int argc, char **argv) { /* create a compressible file, for testing */

    int ncid;
    int dimid, varid;
    int var1_dims[VAR1_RANK];	/* variable shapes */
    int var1_data[DIM1_LEN];	/* data to write */
    int i;

    printf("*** Creating compressible test files %s, %s...", FILENAME, FILENAME2);
    if (nc_create(FILENAME, NC_CLOBBER, &ncid)) ERR;
    if (nc_def_dim(ncid, "dim1", DIM1_LEN, &dimid)) ERR;
    var1_dims[0] = dimid;
    if (nc_def_var(ncid, "var1", NC_INT, VAR1_RANK, var1_dims, &varid)) ERR;
    if (nc_enddef (ncid)) ERR;
    for(i=0; i < DIM1_LEN; i++) {
	var1_data[i] = i;
    }
    if (nc_put_var(ncid, varid, var1_data)) ERR;
    if (nc_close(ncid)) ERR;

    if (nc_create(FILENAME2, NC_CLOBBER|NC_NETCDF4, &ncid)) ERR;
    if (nc_def_dim(ncid, "dim1", DIM1_LEN, &dimid)) ERR;
    var1_dims[0] = dimid;
    if (nc_def_var(ncid, "var1", NC_INT, VAR1_RANK, var1_dims, &varid)) ERR;
    if (nc_enddef (ncid)) ERR;
    for(i=0; i < DIM1_LEN; i++) {
	var1_data[i] = i;
    }
    if (nc_put_var(ncid, varid, var1_data)) ERR;
    if (nc_close(ncid)) ERR;

    SUMMARIZE_ERR;
    FINAL_RESULTS;
}
コード例 #2
0
ファイル: tst_string_data.c プロジェクト: mmase/wgrib2
int
main(int argc, char **argv)
{
   int ncid;
   int dimid, varid;
   char name_in[NC_MAX_NAME+1];
   int class_in;
   size_t size_in;
   char *value_in;
   nc_type att_type;
   size_t att_len;

   int i;

   int var_dims[VAR4_RANK];
   const char *desc_data[DIM4_LEN] = {
       "first string", "second string", "third string", "", "last string"
   };
   const char *missing_val[ATT4_LEN] = {""};
   char *strings_in[DIM4_LEN];
   
#ifdef USE_PARALLEL
   MPI_Init(&argc, &argv);
#endif

#ifdef EXTRA_TESTS
   printf("*** creating strings test file %s...", FILE4_NAME);
   if (nc_create(FILE4_NAME, NC_CLOBBER | NC_NETCDF4, &ncid)) ERR;
   
   /* Declare a line dimension */
   if (nc_def_dim(ncid, DIM4_NAME, DIM4_LEN, &dimid)) ERR;
   
   /* Declare a string variable */
   var_dims[0] = dimid;
   if (nc_def_var(ncid, VAR4_NAME, NC_STRING, VAR4_RANK, var_dims, &varid)) ERR;
   
   /* Create and write a variable attribute of string type */
   if (nc_put_att_string(ncid, varid, ATT4_NAME, ATT4_LEN, missing_val)) ERR;
   if (nc_enddef(ncid)) ERR;
   
   /* Store some data of string type */
   if(nc_put_var(ncid, varid, desc_data)) ERR;
   
   /* Write the file. */
   if (nc_close(ncid)) ERR;
   
   /* Check it out. */
   if (nc_open(FILE4_NAME, NC_NOWRITE, &ncid)) ERR;
   if (nc_inq_varid(ncid, VAR4_NAME, &varid)) ERR;
   if (nc_inq_att(ncid, varid, ATT4_NAME, &att_type, &att_len)) ERR;
   if (att_type != NC_STRING || att_len != ATT4_LEN) ERR;
   if (nc_get_att_string(ncid, varid, ATT4_NAME, strings_in)) ERR;
   
   if (strcmp(strings_in[0], *missing_val) != 0) ERR;
   /* string atts should be explicitly freed when done with them */
   nc_free_string(ATT4_LEN, strings_in);
   
   if(nc_get_var_string(ncid, varid, strings_in)) ERR;
   for (i = 0; i < DIM4_LEN; i++) {
       if (strcmp(strings_in[i], desc_data[i]) != 0) ERR;
   }
   nc_free_string(DIM4_LEN, strings_in);

   /* Try reading strings in with typeless generic interface also */
   if(nc_get_var(ncid, varid, strings_in)) ERR;

   for (i = 0; i < DIM4_LEN; i++) {
       if (strcmp(strings_in[i], desc_data[i]) != 0) ERR;
   }
   nc_free_string(DIM4_LEN, strings_in);


   /* Try reading strings in with typeless generic array interface also */
   {
       size_t cor[VAR4_RANK], edg[VAR4_RANK];
       cor[0] = 0;
       edg[0] = DIM4_LEN;
       if(nc_get_vara(ncid, varid, cor, edg, strings_in)) ERR;

       for (i = 0; i < DIM4_LEN; i++) {
	   if (strcmp(strings_in[i], desc_data[i]) != 0) ERR;
       }
       nc_free_string(DIM4_LEN, strings_in);
   }

   if (nc_close(ncid)) ERR; 

   SUMMARIZE_ERR;
#endif /* EXTRA_TESTS */
   FINAL_RESULTS;
#ifdef USE_PARALLEL
   MPI_Finalize();
#endif   
}
コード例 #3
0
void bi::ParticleFilterNetCDFBuffer::writeLogLikelihood(const real ll) {
  nc_put_var(ncid, llVar, &ll);
}
コード例 #4
0
int main(int argc, char **argv)
{
    struct timeval start_time, end_time, diff_time;
    double sec;
    int nitem = 10000;		/* default number of objects of each type */
    int i;
    int ncid;
    int data[] = {42};
    int g, grp, numgrp;
    char gname[16];
    int v, var, numvar, vn, vleft, nvars;
    
    if(argc > 2) { 	/* Usage */
	printf("NetCDF performance test, writing many groups and variables.\n");
	printf("Usage:\t%s [N]\n", argv[0]);
	printf("\tN: number of objects\n");
	return(0);
    }
    for(i = 1; i < argc; i++) {
	nitem = atoi(argv[i]);
    }

    /*  create new file */
    if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
    if (gettimeofday(&start_time, NULL))
	ERR;
    /* create N groups, printing time after every 1000 */
    numgrp = nitem;
    for(g = 1; g < numgrp + 1; g++) {
	sprintf(gname, "group%d", g);
	if (nc_def_grp(ncid, gname, &grp)) ERR;
	if (nc_def_var(grp, "var", NC_INT, 0, NULL, &var)) ERR;
	if(nc_enddef (grp)) ERR;
	if(nc_put_var(grp, var, data)) ERR;
	if(g%1000 == 0) {		/* only print every 1000th group name */
	    if (gettimeofday(&end_time, NULL)) ERR;
	    if (nc4_timeval_subtract(&diff_time, &end_time, &start_time)) ERR;
	    sec = diff_time.tv_sec + 1.0e-6 * diff_time.tv_usec;
	    printf("%s\t%.3g sec\n", gname, sec);
	}
    }
    nc_close(ncid);
    
    /*  create new file */
    if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
    /* create N variables, printing time after every 1000.  Because only
     * NC_MAX_VARS are permitted per group, create the necessary number
     * of groups to hold nitem variables. */
    numvar = nitem;
    v = 1;
    numgrp = (numvar - 1) / NC_MAX_VARS + 1;
    vleft = numvar - (NC_MAX_VARS * (numgrp - 1));
    if (gettimeofday(&start_time, NULL))
	ERR;
    
    for(g = 1; g < numgrp + 1; g++) {
	sprintf(gname, "group%d", g);
	if (nc_def_grp(ncid, gname, &grp)) ERR;
	nvars = g < numgrp ? NC_MAX_VARS : vleft; /* leftovers on last time through */
	for(vn = 1; vn < nvars + 1; vn++) {
	    int var;
	    char vname[20];
	    sprintf(vname, "variable%d", v);
	    if(nc_def_var(grp, vname, NC_INT, 0, NULL, &var)) ERR;
	    if(nc_put_var(grp, var, data)) ERR;
	    if(v%1000 == 0) {		/* only print every 1000th variable name */
		if (gettimeofday(&end_time, NULL)) ERR;
		if (nc4_timeval_subtract(&diff_time, &end_time, &start_time)) ERR;
		sec = diff_time.tv_sec + 1.0e-6 * diff_time.tv_usec;
		printf("%s/%s\t%.3g sec\n", gname, vname, sec);
	    }
	    v++;
	}
    }
    nc_close(ncid);
    return(0);
}
コード例 #5
0
ファイル: tst_h_scalar.c プロジェクト: BJangeofan/netcdf-c
int
main()
{
    printf("\n*** Creating file with datasets & attributes that have scalar dataspaces...");
    {
	hid_t fileid;
        hid_t fcplid;
	hid_t dsetid;
        hid_t dcplid;
	hid_t scalar_spaceid;
        hid_t vlstr_typeid, fixstr_typeid;
	hid_t attid;

        /* Create scalar dataspace */
	if ((scalar_spaceid = H5Screate(H5S_SCALAR)) < 0) ERR;

        /* Set creation ordering for file, so we can revise its contents later */
        if ((fcplid = H5Pcreate(H5P_FILE_CREATE)) < 0) ERR;
        if (H5Pset_link_creation_order(fcplid, H5P_CRT_ORDER_TRACKED) < 0) ERR;
        if (H5Pset_attr_creation_order(fcplid, H5P_CRT_ORDER_TRACKED) < 0) ERR;
	
	/* Create new file, using default properties */
	if ((fileid = H5Fcreate(FILE_NAME, H5F_ACC_TRUNC, fcplid, H5P_DEFAULT)) < 0) ERR;
	
        /* Close file creation property list */
        if (H5Pclose(fcplid) < 0) ERR;


        /* Create variable-length string datatype */
        if ((vlstr_typeid = H5Tcreate(H5T_STRING, (size_t)H5T_VARIABLE)) < 0) ERR;

        /* Create fixed-length string datatype */
        if ((fixstr_typeid = H5Tcreate(H5T_STRING, (size_t)10)) < 0) ERR;


        /* Set creation ordering for dataset, so we can revise its contents later */
        if ((dcplid = H5Pcreate(H5P_DATASET_CREATE)) < 0) ERR;
        if (H5Pset_attr_creation_order(dcplid, H5P_CRT_ORDER_TRACKED) < 0) ERR;

	
        /* Create scalar dataset with VL string datatype */
        if ((dsetid = H5Dcreate2(fileid, VSTR_VAR1_NAME, vlstr_typeid, scalar_spaceid, H5P_DEFAULT, dcplid, H5P_DEFAULT)) < 0) ERR;

        /* Add attributes to dataset */
        if (add_attrs(dsetid) < 0) ERR;

        /* Close VL string dataset */
        if (H5Dclose(dsetid) < 0) ERR;


        /* Create scalar dataset with fixed-length string datatype */
        if ((dsetid = H5Dcreate2(fileid, FSTR_VAR_NAME, fixstr_typeid, scalar_spaceid, H5P_DEFAULT, dcplid, H5P_DEFAULT)) < 0) ERR;

        /* Add attributes to dataset */
        if (add_attrs(dsetid) < 0) ERR;

        /* Close fixed-length string dataset */
        if (H5Dclose(dsetid) < 0) ERR;


        /* Create scalar dataset with native integer datatype */
        if ((dsetid = H5Dcreate2(fileid, INT_VAR_NAME, H5T_NATIVE_INT, scalar_spaceid, H5P_DEFAULT, dcplid, H5P_DEFAULT)) < 0) ERR;

        /* Add attributes to dataset */
        if (add_attrs(dsetid) < 0) ERR;

        /* Close native integer dataset */
        if (H5Dclose(dsetid) < 0) ERR;


        /* Add attributes to root group */
        if (add_attrs(fileid) < 0) ERR;


        /* Close dataset creation property list */
        if (H5Pclose(dcplid) < 0) ERR;

        /* Close string datatypes */
        if (H5Tclose(vlstr_typeid) < 0) ERR;
        if (H5Tclose(fixstr_typeid) < 0) ERR;


        /* Close rest */
	if (H5Sclose(scalar_spaceid) < 0) ERR;
	if (H5Fclose(fileid) < 0) ERR;
    }
    SUMMARIZE_ERR;

    printf("*** Checking accessing file through netCDF-4 API...");
    {
	int ncid, varid;
        size_t len;
        nc_type type;
        int ndims;
        char *vlstr;
        int x;

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

        /* Check the global attributes are OK */
        if (check_attrs(ncid, NC_GLOBAL) < 0) ERR;

        /* Verify that the VL string dataset is present and OK */
	if (nc_inq_varid(ncid, VSTR_VAR1_NAME, &varid)) ERR;
        if (varid != 0) ERR;
	if (nc_inq_vartype(ncid, varid, &type)) ERR;
	if (type != NC_STRING) ERR;
        if (nc_inq_varndims(ncid, varid, &ndims)) ERR;
        if (ndims != 0) ERR;
        vlstr = NULL;
        if (nc_get_var(ncid, varid, &vlstr)) ERR;
        if (NULL != vlstr) ERR;

        /* Check the variable's attributes are OK */
        if (check_attrs(ncid, varid) < 0) ERR;

        /* Verify that the fixed-length string dataset is present and OK */
	if (nc_inq_varid(ncid, FSTR_VAR_NAME, &varid)) ERR;
        if (varid != 1) ERR;
	if (nc_inq_vartype(ncid, varid, &type)) ERR;
	if (type != NC_STRING) ERR;
        if (nc_inq_varndims(ncid, varid, &ndims)) ERR;
        if (ndims != 0) ERR;
        vlstr = NULL;
        if (nc_get_var(ncid, varid, &vlstr)) ERR;
        if ('\0' != *vlstr) ERR;
        free(vlstr);

        /* Check the variable's attributes are OK */
        if (check_attrs(ncid, varid) < 0) ERR;

        /* Verify that the integer dataset is present and OK */
	if (nc_inq_varid(ncid, INT_VAR_NAME, &varid)) ERR;
        if (varid != 2) ERR;
	if (nc_inq_vartype(ncid, varid, &type)) ERR;
	if (type != NC_INT) ERR;
        if (nc_inq_varndims(ncid, varid, &ndims)) ERR;
        if (ndims != 0) ERR;
        x = -1;
        if (nc_get_var(ncid, varid, &x)) ERR;
        if (0 != x) ERR;

        /* Check the variable's attributes are OK */
        if (check_attrs(ncid, varid) < 0) ERR;

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

    printf("*** Checking revising file through netCDF-4 API...");
    {
	int ncid, varid;
        char *vlstr;

	if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR;
        
        /* Write to the VL string variable */
	if (nc_inq_varid(ncid, VSTR_VAR1_NAME, &varid)) ERR;
        vlstr = NULL;
        if (nc_put_var(ncid, varid, &vlstr)) ERR;

        vlstr = malloc(10);
        *vlstr = '\0';
        if (nc_put_var(ncid, varid, &vlstr)) ERR;

        strcpy(vlstr, "foo");
        if (nc_put_var(ncid, varid, &vlstr)) ERR;
        free(vlstr);


        /* Write to a VL string attribute */
        vlstr = NULL;
        if (nc_put_att(ncid, varid, VSTR_ATT1_NAME, NC_STRING, 1, &vlstr)) ERR;

        vlstr = malloc(10);
        *vlstr = '\0';
        if (nc_put_att(ncid, varid, VSTR_ATT1_NAME, NC_STRING, 1, &vlstr)) ERR;

        strcpy(vlstr, "foo");
        if (nc_put_att(ncid, varid, VSTR_ATT1_NAME, NC_STRING, 1, &vlstr)) ERR;
        free(vlstr);


        /* Define a new VL string variable */
        if (nc_def_var(ncid, VSTR_VAR2_NAME , NC_STRING, 0, NULL, &varid)) ERR;

        /* Write to the variable's fill-value */
        vlstr = NULL;
        if (nc_put_att(ncid, varid, _FillValue, NC_STRING, 1, &vlstr)) ERR;

        vlstr = malloc(10);
        *vlstr = '\0';
        if (nc_put_att(ncid, varid, _FillValue, NC_STRING, 1, &vlstr)) ERR;

        strcpy(vlstr, "foo");
        if (nc_put_att(ncid, varid, _FillValue, NC_STRING, 1, &vlstr)) ERR;
        free(vlstr);


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

    FINAL_RESULTS;
}
コード例 #6
0
int
main(int argc, char **argv)
{
    printf("\n*** Testing netcdf-4 string type.\n");
    printf("*** testing string attribute...");
    {
#define ATT_LEN_1 1
#define MOUNTAIN_RANGE "mountain_range"
        size_t att_len;
        int ndims, nvars, natts, unlimdimid;
        nc_type att_type;
        int ncid, i;
        char *data_in[ATT_LEN_1] = {NULL};
        char *data[ATT_LEN_1] = {"R"};

        if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
        if (nc_put_att(ncid, NC_GLOBAL, MOUNTAIN_RANGE, NC_STRING, ATT_LEN_1, data)) ERR;
        if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
        if (ndims != 0 || nvars != 0 || natts != 1 || unlimdimid != -1) ERR;
        if (nc_inq_att(ncid, NC_GLOBAL, MOUNTAIN_RANGE, &att_type, &att_len)) ERR;
        if (att_type != NC_STRING || att_len != ATT_LEN_1) ERR;
        if (nc_close(ncid)) ERR;

        /* Check it out. */
        if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
        if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
        if (ndims != 0 || nvars != 0 || natts != 1 || unlimdimid != -1) ERR;
        if (nc_inq_att(ncid, NC_GLOBAL, MOUNTAIN_RANGE, &att_type, &att_len)) ERR;
        if (att_type != NC_STRING || att_len != ATT_LEN_1) ERR;
        if (nc_get_att(ncid, NC_GLOBAL, MOUNTAIN_RANGE, data_in)) ERR;
        for (i = 0; i < att_len; i++)
            if (strcmp(data_in[i], data[i])) ERR;
        if (nc_free_string(ATT_LEN_1, (char **)data_in)) ERR;
        if (nc_close(ncid)) ERR;
    }
    SUMMARIZE_ERR;
    printf("*** testing string attribute...");
    {
#define ATT_LEN 9
        size_t att_len;
        int ndims, nvars, natts, unlimdimid;
        nc_type att_type;
        int ncid, i;
        char *data_in[ATT_LEN];
        char *data[ATT_LEN] = {"Let but your honour know",
                               "Whom I believe to be most strait in virtue",
                               "That, in the working of your own affections",
                               "Had time cohered with place or place with wishing",
                               "Or that the resolute acting of your blood",
                               "Could have attain'd the effect of your own purpose",
                               "Whether you had not sometime in your life",
                               "Err'd in this point which now you censure him",
                               "And pull'd the law upon you."
                              };

        if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
        if (nc_put_att(ncid, NC_GLOBAL, ATT_NAME, NC_STRING, ATT_LEN, data)) ERR;
        if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
        if (ndims != 0 || nvars != 0 || natts != 1 || unlimdimid != -1) ERR;
        if (nc_inq_att(ncid, NC_GLOBAL, ATT_NAME, &att_type, &att_len)) ERR;
        if (att_type != NC_STRING || att_len != ATT_LEN) ERR;
        if (nc_close(ncid)) ERR;

        /* Check it out. */
        if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
        if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
        if (ndims != 0 || nvars != 0 || natts != 1 || unlimdimid != -1) ERR;
        if (nc_inq_att(ncid, NC_GLOBAL, ATT_NAME, &att_type, &att_len)) ERR;
        if (att_type != NC_STRING || att_len != ATT_LEN) ERR;
        if (nc_get_att(ncid, NC_GLOBAL, ATT_NAME, data_in)) ERR;
        for (i = 0; i < att_len; i++)
            if (strcmp(data_in[i], data[i])) ERR;
        if (nc_free_string(att_len, (char **)data_in)) ERR;
        if (nc_close(ncid)) ERR;
    }
    SUMMARIZE_ERR;
    printf("*** testing string var functions...");
    {
#define MOBY_LEN 16
        int ncid, varid, dimids[NDIMS];
        char *data[] = {"Perhaps a very little thought will now enable you to account for ",
                        "those repeated whaling disasters--some few of which are casually ",
                        "chronicled--of this man or that man being taken out of the boat by ",
                        "the line, and lost.",
                        "For, when the line is darting out, to be seated then in the boat, ",
                        "is like being seated in the midst of the manifold whizzings of a ",
                        "steam-engine in full play, when every flying beam, and shaft, and wheel, ",
                        "is grazing you.",
                        "It is worse; for you cannot sit motionless in the heart of these perils, ",
                        "because the boat is rocking like a cradle, and you are pitched one way and ",
                        "the other, without the slightest warning;",
                        "But why say more?",
                        "All men live enveloped in whale-lines.",
                        "All are born with halters round their necks; but it is only when caught ",
                        "in the swift, sudden turn of death, that mortals realize the silent, subtle, ",
                        "ever-present perils of life."
                       };
        char *data_in[MOBY_LEN];
        int i;

        if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
        if (nc_def_dim(ncid, DIM_NAME, MOBY_LEN, dimids)) ERR;
        if (nc_def_var(ncid, VAR_NAME, NC_STRING, NDIMS, dimids, &varid)) ERR;
        if (nc_put_var_string(ncid, varid, (const char **)data)) ERR;
        if (nc_close(ncid)) ERR;

        /* Check it out. */
        if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
        if (nc_get_var_string(ncid, varid, data_in)) ERR;
        for (i=0; i<MOBY_LEN; i++)
            if (strcmp(data_in[i], data[i])) ERR;
        if (nc_free_string(MOBY_LEN, (char **)data_in)) ERR;
        if (nc_close(ncid)) ERR;
    }
    SUMMARIZE_ERR;
    printf("*** testing string attributes...");
    {
#define SOME_PRES 16
#define NDIMS_PRES 1
#define ATT2_NAME "presidents"

        int ncid, i;
        char *data[SOME_PRES] = {"Washington", "Adams", "Jefferson", "Madison",
                                 "Monroe", "Adams", "Jackson", "VanBuren",
                                 "Harrison", "Tyler", "Polk", "Tayor",
                                 "Fillmore", "Peirce", "Buchanan", "Lincoln"
                                };
        char *data_in[SOME_PRES];

        /* Create a file with string attribute. */
        if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
        if (nc_put_att_string(ncid, NC_GLOBAL, ATT2_NAME, SOME_PRES, (const char **)data)) ERR;
        if (nc_close(ncid)) ERR;

        /* Check it out. */
        if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
        if (nc_get_att_string(ncid, NC_GLOBAL, ATT2_NAME, (char **)data_in)) ERR;
        for (i=0; i < SOME_PRES; i++)
            if (strcmp(data_in[i], data[i])) ERR;

        /* Must free your data! */
        if (nc_free_string(SOME_PRES, (char **)data_in)) ERR;

        if (nc_close(ncid)) ERR;
    }
    SUMMARIZE_ERR;
    printf("*** testing string fill value...");
    {
#define NUM_PRES 43
#define SOME_PRES 16
#define NDIMS_PRES 1
#define VAR_NAME_P "presidents"
        int ncid, varid, i, dimids[NDIMS_PRES];
        size_t start[NDIMS_PRES], count[NDIMS_PRES];
        char *data[SOME_PRES] = {"Washington", "Adams", "Jefferson", "Madison",
                                 "Monroe", "Adams", "Jackson", "VanBuren",
                                 "Harrison", "Tyler", "Polk", "Tayor",
                                 "Fillmore", "Peirce", "Buchanan", "Lincoln"
                                };
        char *data_in[NUM_PRES];

        /* Create a file with NUM_PRES strings, and write SOME_PRES of
         * them. */
        if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
        if (nc_def_dim(ncid, DIM_NAME, NUM_PRES, dimids)) ERR;
        if (nc_def_var(ncid, VAR_NAME_P, NC_STRING, NDIMS_PRES, dimids, &varid)) ERR;
        start[0] = 0;
        count[0] = SOME_PRES;
        if (nc_put_vara_string(ncid, varid, start, count, (const char **)data)) ERR;
        if (nc_close(ncid)) ERR;

        /* Check it out. */
        if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
        if (nc_get_var_string(ncid, varid, data_in)) ERR;
        for (i = 0; i < NUM_PRES; i++)
        {
            if (i < SOME_PRES && strcmp(data_in[i], data[i])) ERR;
            if (i >= SOME_PRES && strcmp(data_in[i], "")) ERR;
        }

        /* Must free your data! */
        if (nc_free_string(NUM_PRES, (char **)data_in)) ERR;

        if (nc_close(ncid)) ERR;
    }
    SUMMARIZE_ERR;
    printf("*** testing long string variable...");
    {
#define VAR_NAME2 "empty"
#define ATT_NAME2 "empty"
#define DHR_LEN 30
#define DIM_NAME1 "article"
#define VAR_NAME1 "universal_declaration_of_human_rights"
        int var_dimids[NDIMS];
        int ndims, nvars, natts, unlimdimid;
        nc_type var_type;
        char var_name[NC_MAX_NAME + 1];
        int var_natts, var_ndims;
        int ncid, varid, i, dimids[NDIMS], varid2;
        char *data_in[DHR_LEN];
        char *data[DHR_LEN] = {
            "All human beings are born free and equal in dignity and rights. "
            "They are endowed with reason and "
            "conscience and should act towards one another in a "
            "spirit of brotherhood.",
            "Everyone is entitled to all the rights and freedoms set "
            "forth in this Declaration, without distinction of "
            "any kind, such as race, colour, sex, language, religion, "
            "political or other opinion, national or social "
            "origin, property, birth or other status. Furthermore, no "
            "distinction shall be made on the basis of the "
            "political, jurisdictional or international status of the "
            "country or territory to which a person belongs, "
            "whether it be independent, trust, non-self-governing or "
            "under any other limitation of sovereignty.",
            "Everyone has the right to life, liberty and security of person.",
            "No one shall be held in slavery or servitude; slavery and the "
            "slave trade shall be prohibited in all their forms.",
            "No one shall be subjected to torture or to cruel, "
            "inhuman or degrading treatment or punishment.",
            "Everyone has the right to recognition everywhere as "
            "a person before the law.",
            "All are equal before the law and are entitled without "
            "any discrimination to equal protection of the law. All are "
            "entitled to equal protection against any discrimination in "
            "violation of this Declaration and against any incitement "
            "to such discrimination.",
            "Everyone has the right to an effective remedy by the "
            "competent national tribunals for acts violating the "
            "fundamental rights granted "
            "him by the constitution or by law.",
            "No one shall be subjected to arbitrary arrest, detention or exile.",
            "Everyone is entitled in full equality to a fair and public "
            "hearing by an independent and impartial tribunal, in the "
            "determination of his rights and obligations and of any "
            "criminal charge against him.",
            "(1) Everyone charged with a penal offence has the right "
            "to be presumed innocent until proved guilty according to law in a "
            "public trial at which he has had all the guarantees "
            "necessary for his defence."
            "(2) No one shall be held guilty of any penal offence "
            "on account of any act or omission which did not constitute a penal "
            "offence, under national or international law, at the time "
            "when it was committed. Nor shall a heavier penalty be imposed "
            "than the one that was applicable at the time the penal "
            "offence was committed.",
            "No one shall be subjected to arbitrary interference with "
            "his privacy, family, home or correspondence, nor to attacks upon "
            "his honour and reputation. Everyone has the right to the "
            "protection of the law against such interference or attacks.",
            "(1) Everyone has the right to freedom of movement and "
            "residence within the borders of each state."
            "(2) Everyone has the right to leave any country, "
            "including his own, and to return to his country.",
            "(1) Everyone has the right to seek and to enjoy in "
            "other countries asylum from persecution. "
            "(2) This right may not be invoked in the case of prosecutions "
            "genuinely arising from non-political crimes or from acts "
            "contrary to the purposes and principles of the United Nations.",
            "(1) Everyone has the right to a nationality. (2) No one shall "
            "be arbitrarily deprived of his nationality nor denied the "
            "right to change his nationality.",
            "(1) Men and women of full age, without any limitation "
            "due to race, nationality or religion, have the right "
            "to marry and to found a family. "
            "They are entitled to equal rights as to marriage, "
            "during marriage and at its dissolution. (2) Marriage "
            "shall be entered into only with the free and full "
            "consent of the intending spouses. (3) The family is "
            "the natural and fundamental group unit of society and "
            "is entitled to protection by society and the State.",
            "(1) Everyone has the right to own property alone as "
            "well as in association with others. (2) No one shall "
            "be arbitrarily deprived of his property.",
            "Everyone has the right to freedom of thought, conscience "
            "and religion; this right includes freedom to change "
            "his religion or belief, and freedom, "
            "either alone or in community with others and in "
            "public or private, to manifest his religion or "
            "belief in teaching, practice, worship and observance.",
            "Everyone has the right to freedom of opinion and "
            "expression; this right includes freedom to hold "
            "opinions without interference and to seek, receive "
            "and impart information and ideas through any media "
            "and regardless of frontiers.",
            "(1) Everyone has the right to freedom of peaceful assembly "
            "and association. (2) No one may be compelled to belong to "
            "an association.",
            "(1) Everyone has the right to take part in the government "
            "of his country, directly or through freely chosen representatives. "
            "(2) Everyone has the right of equal access to public "
            "service in his country. (3) The will of the people "
            "shall be the basis of the authority of government; "
            "this will shall be expressed in periodic and genuine "
            "elections which shall be by universal and equal suffrage "
            "and shall be held by secret vote or by "
            "equivalent free voting procedures.",
            "Everyone, as a member of society, has the right to "
            "social security and is entitled to realization, "
            "through national effort and international co-operation "
            "and in accordance with the organization and resources of "
            "each State, of the economic, social and cultural rights "
            "indispensable for his dignity and the free "
            "development of his personality.",
            "(1) Everyone has the right to work, to free choice "
            "of employment, to just and favourable conditions of "
            "work and to protection against unemployment. "
            "(2) Everyone, without any discrimination, has the right "
            "to equal pay for equal work. (3) Everyone who works "
            "has the right to just and favourable "
            "remuneration ensuring for himself and his family an "
            "existence worthy of human dignity, and supplemented, "
            "if necessary, by other means of social protection."
            "(4) Everyone has the right to form and to join trade "
            "unions for the protection of his interests.",
            "Everyone has the right to rest and leisure, including "
            "reasonable limitation of working hours and periodic "
            "holidays with pay.",
            "(1) Everyone has the right to a standard of living "
            "adequate for the health and well-being of himself "
            "and of his family, including food, clothing, housing "
            "and medical care and necessary social services, and "
            "the right to security in the event of unemployment, "
            "sickness, disability, widowhood, old age or other lack "
            "of livelihood in circumstances beyond his control. "
            "(2) Motherhood and childhood are entitled to special "
            "care and assistance. All children, whether "
            "born in or out of wedlock, shall enjoy the same "
            "social protection.",
            "(1) Everyone has the right to education. Education "
            "shall be free, at least in the elementary and "
            "fundamental stages. Elementary education shall be compulsory. "
            "Technical and professional education shall be made generally "
            "available and higher education "
            "shall be equally accessible to all on the basis of merit. "
            "(2) Education shall be directed to the full development of "
            "the human personality and to the strengthening of respect for "
            "human rights and fundamental freedoms. "
            "It shall promote understanding, tolerance and friendship among "
            "all nations, racial or religious groups, and shall further the "
            "activities of the United Nations "
            "for the maintenance of peace. (3) Parents have a prior right to "
            "choose the kind of education that shall be given to their children.",
            "(1) Everyone has the right freely to participate in the cultural "
            "life of the community, to enjoy the arts and to share in scientific "
            "advancement and its benefits. "
            "(2) Everyone has the right to the protection of the moral "
            "and material interests resulting from any scientific, "
            "literary or artistic production of which he is the author.",
            "Everyone is entitled to a social and international order in "
            "which the rights and freedoms set forth in this Declaration "
            "can be fully realized.",
            "(1) Everyone has duties to the community in which alone "
            "the free and full development of his personality is possible. "
            "(2) In the exercise of his rights and "
            "freedoms, everyone shall be subject only to such limitations "
            "as are determined by law solely for the purpose "
            "of securing due recognition and respect for the rights "
            "and freedoms of others and of meeting the just requirements "
            "of morality, public order and the general welfare in a "
            "democratic society. (3) These rights and freedoms may in no "
            "case be exercised contrary to the purposes and "
            "principles of the United Nations.",
            "Nothing in this Declaration may be interpreted as implying "
            "for any State, group or person any right to engage in any "
            "activity or to perform any act aimed at the destruction of "
            "any of the rights and freedoms set forth herein."
        };
        char *empty_string[] = {""};

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

        /* Create an array of strings for the Universal Declaraion of Human Rights. */
        if (nc_def_dim(ncid, DIM_NAME1, DHR_LEN, dimids)) ERR;
        if (nc_def_var(ncid, VAR_NAME1, NC_STRING, NDIMS, dimids, &varid)) ERR;

        /* Create a scalar variable for the empty string. */
        if (nc_def_var(ncid, VAR_NAME2, NC_STRING, 0, NULL, &varid2)) ERR;

        /* Check some stuff. */
        if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
        if (ndims != NDIMS || nvars != 2 || natts != 0 || unlimdimid != -1) ERR;
        if (nc_inq_var(ncid, varid, var_name, &var_type, &var_ndims,
                       var_dimids, &var_natts)) ERR;
        if (var_type != NC_STRING || strcmp(var_name, VAR_NAME1) || var_ndims != NDIMS ||
                var_dimids[0] != dimids[0]) ERR;

        /* Write the universal declaraion of human rights. */
        if (nc_put_var(ncid, varid, data)) ERR;

        /* Write an empty string with an empty attribute. */
        if (nc_put_var(ncid, varid2, empty_string)) ERR;
        if (nc_put_att(ncid, varid2, ATT_NAME2, NC_STRING, 0, empty_string)) ERR;

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

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

        /* Check declaration. */
        if (nc_inq_varid(ncid, VAR_NAME1, &varid)) ERR;
        if (nc_inq_var(ncid, varid, var_name, &var_type, &var_ndims,
                       var_dimids, &var_natts)) ERR;
        if (var_type != NC_STRING || strcmp(var_name, VAR_NAME1) || var_ndims != NDIMS ||
                var_dimids[0] != dimids[0]) ERR;
        if (nc_get_var(ncid, varid, data_in)) ERR;
        for (i = 0; i < DHR_LEN; i++)
            if (strcmp(data_in[i], data[i])) ERR;
        if (nc_free_string(DHR_LEN, data_in)) ERR;

        /* Check the empty var and att. */
        if (nc_inq_varid(ncid, VAR_NAME2, &varid)) ERR;
        if (nc_get_var(ncid, varid, data_in)) ERR;
        if (strcmp(data_in[0], empty_string[0])) ERR;
        if (nc_free_string(1, data_in)) ERR;
        if (nc_get_att(ncid, varid, ATT_NAME2, NULL)) ERR;
        if (nc_close(ncid)) ERR;
    }
    SUMMARIZE_ERR;
    FINAL_RESULTS;
}
コード例 #7
0
ファイル: surface3d.c プロジェクト: H2Lib/H2Lib
void
write_nc_surface3d(pcsurface3d gr, const char *filename)
{
#ifdef USE_NETCDF
  const     real(*x)[3] = (const real(*)[3]) gr->x;
  const     uint(*e)[2] = (const uint(*)[2]) gr->e;
  const     uint(*t)[3] = (const uint(*)[3]) gr->t;
  const     uint(*s)[3] = (const uint(*)[3]) gr->s;
  uint      vertices = gr->vertices;
  uint      edges = gr->edges;
  uint      triangles = gr->triangles;
  int       res, nc_out;
  int       x_id, e_id, t_id, s_id;
  int       vertices_id, edges_id, triangles_id;
  int       n2_id, n3_id;
  int       dimid[2];

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

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

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

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

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

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

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

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

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

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

  (void) printf("Sorry, no NetCDF support.\n");
#endif
}
コード例 #8
0
ファイル: filter_example.c プロジェクト: Unidata/netcdf-c
/*
Create the file, write it, then re-read for comparison.
*/
static int
test_bzip2(void)
{
    int i;
    unsigned int level = BZIP2_LEVEL;
    unsigned int id=0;
    size_t nparams = 0;

    printf("\n*** Testing API: bzip2 compression.\n");

    /* Clear the data array */
    memset(array,0,sizeof(float)*actualproduct);

    /* Create a file */
    CHECK(nc_create(TESTFILE, NC_NETCDF4|NC_CLOBBER, &ncid));

    /* Do not use fill for this file */
    CHECK(nc_set_fill(ncid, NC_NOFILL, NULL));

    /* Define the dimensions */
    for(i=0;i<actualdims;i++) {
	char dimname[1024];
	snprintf(dimname,sizeof(dimname),"dim%d",i);
        CHECK(nc_def_dim(ncid, dimname, dims[i], &dimids[i]));
    }

    /* Define the variable */
    CHECK(nc_def_var(ncid, "var", NC_FLOAT, actualdims, dimids, &varid));

    /* Set chunking on the variable */
    CHECK(nc_def_var_chunking(ncid,varid,NC_CHUNKED,chunks));

    /* Verify that chunking succeeded */
    if(!verifychunks())
	return NC_EINVAL;
    /* Set bzip2 compression for the variable: takes one parameter == level */
    CHECK(nc_def_var_filter(ncid,varid,BZIP2_ID,1,&level));

    /* Read back the compression info and verify it */
    level = 0;
    CHECK(nc_inq_var_filter(ncid,varid,&id,&nparams,&level));
    if(id != BZIP2_ID || nparams != 1 || level != BZIP2_LEVEL) {
        printf("test_filter: filter def/inq mismatch\n");
	return NC_EFILTER;
    }
    /* Show the level */
    printf("show parameters for bzip2: level=%u\n",level);
    /* Show chunking */ 
    printf("show chunks:");
    for(i=0;i<actualdims;i++)
	printf("%s%ld",(i==0?" chunks=":","),(unsigned long)chunks[i]);
    printf("\n");

    /* prepare to write */
    CHECK(nc_enddef(ncid));

    /* Fill in the array */
    for(i=0;i<actualproduct;i++)
	expected[i] = (float)i;

    /* write array */
    CHECK(nc_put_var(ncid,varid,expected));

    /* Close file */
    CHECK(nc_close(ncid));

    /* Now re-open and verify */
    printf("\n*** Testing API: bzip2 decompression.\n");

    /* Clear the data array */
    memset(array,0,sizeof(float)*actualproduct);

    /* Open the file */
    CHECK(nc_open(TESTFILE, NC_NOWRITE, &ncid));

    /* Get the variable id */
    CHECK(nc_inq_varid(ncid, "var", &varid));

    /* Check the compression algorithm */
    filterid = 0;
    nparams = 0;
    params = NULL;
    CHECK(nc_inq_var_filter(ncid,varid,&filterid,&nparams,NULL));
    if(nparams > 0) {
        params = (unsigned int*)malloc(sizeof(unsigned int)*nparams);
	if(params == NULL)
	    return NC_ENOMEM;
        CHECK(nc_inq_var_filter(ncid,varid,&filterid,&nparams,params));
    }
    if(filterid != BZIP2_ID) {
         printf("Bzip2 id mismatch: %d\n",filterid);
	return NC_EFILTER;
    }
    if(nparams != 1 && params != NULL && params[0] != BZIP2_LEVEL) {
	printf("Compression parameter mismatch\n");
	return NC_EFILTER; 
    }

    /* Verify chunking */
    if(!verifychunks())
	return 0;

    /* Read the data */
    CHECK(nc_get_var_float(ncid, varid, array));

    /* Close the file */
    CHECK(nc_close(ncid));
    return (compare() == NC_NOERR ? 0 : 1);
}
コード例 #9
0
ファイル: tst_strings.c プロジェクト: mmase/wgrib2
int
main(int argc, char **argv)
{
#ifdef USE_PARALLEL
   MPI_Init(&argc, &argv);
#endif

   printf("\n*** Testing netcdf-4 string type.\n");
   printf("*** testing string variable...");
   {
      int var_dimids[NDIMS];
      int ndims, nvars, natts, unlimdimid;
      nc_type var_type;
      char var_name[NC_MAX_NAME + 1];
      int var_natts, var_ndims;
      int ncid, varid, i, dimids[NDIMS];
      char *data_in[DIM_LEN];
      char *data[DIM_LEN] = {"Let but your honour know",
			     "Whom I believe to be most strait in virtue", 
			     "That, in the working of your own affections", 
			     "Had time cohered with place or place with wishing", 
			     "Or that the resolute acting of your blood",
			     "Could have attain'd the effect of your own purpose",
			     "Whether you had not sometime in your life",
			     "Err'd in this point which now you censure him", 
			     "And pull'd the law upon you."};
   
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, DIM_LEN, dimids)) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_STRING, NDIMS, dimids, &varid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != NDIMS || nvars != 1 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_var(ncid, varid, var_name, &var_type, &var_ndims,
		     var_dimids, &var_natts)) ERR;
      if (var_type != NC_STRING || strcmp(var_name, VAR_NAME) || var_ndims != NDIMS ||
	  var_dimids[0] != dimids[0]) ERR;
      if (nc_put_var(ncid, varid, data)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != NDIMS || nvars != 1 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_var(ncid, varid, var_name, &var_type, &var_ndims,
		     var_dimids, &var_natts)) ERR;
      if (var_type != NC_STRING || strcmp(var_name, VAR_NAME) || var_ndims != NDIMS ||
	  var_dimids[0] != dimids[0]) ERR;
      if (nc_get_var(ncid, varid, data_in)) ERR;
      for (i=0; i<DIM_LEN; i++)
	 if (strcmp(data_in[i], data[i])) ERR;
      for (i = 0; i < DIM_LEN; i++)
	 free(data_in[i]);
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing string attribute...");
   {
      
      size_t att_len;
      int ndims, nvars, natts, unlimdimid;
      nc_type att_type;
      int ncid, i;
      char *data_in[DIM_LEN];
      char *data[DIM_LEN] = {"Let but your honour know",
			     "Whom I believe to be most strait in virtue", 
			     "That, in the working of your own affections", 
			     "Had time cohered with place or place with wishing", 
			     "Or that the resolute acting of your blood",
			     "Could have attain'd the effect of your own purpose",
			     "Whether you had not sometime in your life",
			     "Err'd in this point which now you censure him", 
			     "And pull'd the law upon you."};
   

      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att(ncid, NC_GLOBAL, ATT_NAME, NC_STRING, DIM_LEN, data)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 0 || nvars != 0 || natts != 1 || unlimdimid != -1) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_NAME, &att_type, &att_len)) ERR;
      if (att_type != NC_STRING || att_len != DIM_LEN) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 0 || nvars != 0 || natts != 1 || unlimdimid != -1) ERR;
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_NAME, &att_type, &att_len)) ERR;
      if (att_type != NC_STRING || att_len != DIM_LEN) ERR;
      if (nc_get_att(ncid, NC_GLOBAL, ATT_NAME, data_in)) ERR; 
      for (i = 0; i < att_len; i++)
	 if (strcmp(data_in[i], data[i])) ERR;
      if (nc_free_string(att_len, (char **)data_in)) ERR;
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing string var functions...");

   {
#define MOBY_LEN 16
      int ncid, varid, i, dimids[NDIMS];
      char *data[] = {"Perhaps a very little thought will now enable you to account for ",
		      "those repeated whaling disasters--some few of which are casually ",
		      "chronicled--of this man or that man being taken out of the boat by ",
		      "the line, and lost.",
		      "For, when the line is darting out, to be seated then in the boat, ",
		      "is like being seated in the midst of the manifold whizzings of a ",
		      "steam-engine in full play, when every flying beam, and shaft, and wheel, ",
		      "is grazing you.",
		      "It is worse; for you cannot sit motionless in the heart of these perils, ",
		      "because the boat is rocking like a cradle, and you are pitched one way and ",
		      "the other, without the slightest warning;",
		      "But why say more?",
		      "All men live enveloped in whale-lines.",
		      "All are born with halters round their necks; but it is only when caught ",
		      "in the swift, sudden turn of death, that mortals realize the silent, subtle, ",
		      "ever-present perils of life."};
      char *data_in[MOBY_LEN];

      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, MOBY_LEN, dimids)) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_STRING, NDIMS, dimids, &varid)) ERR;
      if (nc_put_var_string(ncid, varid, (const char **)data)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
     if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
     if (nc_get_var_string(ncid, varid, data_in)) ERR;
     for (i=0; i<MOBY_LEN; i++)
	if (strcmp(data_in[i], data[i])) ERR;
     if (nc_free_string(MOBY_LEN, (char **)data_in)) ERR;
     if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;

   printf("*** testing string attributes...");
   {
#define SOME_PRES 16
#define NDIMS_PRES 1
#define ATT2_NAME "presidents"

      int ncid, i;
      char *data[SOME_PRES] = {"Washington", "Adams", "Jefferson", "Madison",
			       "Monroe", "Adams", "Jackson", "VanBuren",
			       "Harrison", "Tyler", "Polk", "Tayor", 
			       "Fillmore", "Peirce", "Buchanan", "Lincoln"};
      char *data_in[SOME_PRES];

      /* Create a file with string attribute. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_put_att_string(ncid, NC_GLOBAL, ATT2_NAME, SOME_PRES, (const char **)data)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_get_att_string(ncid, NC_GLOBAL, ATT2_NAME, (char **)data_in)) ERR;
      for (i=0; i < SOME_PRES; i++)
	 if (strcmp(data_in[i], data[i])) ERR;
      
      /* Must free your data! */
      if (nc_free_string(SOME_PRES, (char **)data_in)) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   printf("*** testing string fill value...");

   {
#define NUM_PRES 43
#define SOME_PRES 16
#define NDIMS_PRES 1

      int ncid, varid, i, dimids[NDIMS_PRES];
      size_t start[NDIMS_PRES], count[NDIMS_PRES];
      char *data[SOME_PRES] = {"Washington", "Adams", "Jefferson", "Madison",
			       "Monroe", "Adams", "Jackson", "VanBuren",
			       "Harrison", "Tyler", "Polk", "Tayor", 
			       "Fillmore", "Peirce", "Buchanan", "Lincoln"};
      char *data_in[NUM_PRES];

      /* Create a file with NUM_PRES strings, and write SOME_PRES of
       * them. */
      /*      nc_set_log_level(4);*/
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_dim(ncid, DIM_NAME, NUM_PRES, dimids)) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_STRING, NDIMS_PRES, dimids, &varid)) ERR;
      start[0] = 0;
      count[0] = SOME_PRES;
      if (nc_put_vara_string(ncid, varid, start, count, (const char **)data)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_get_var_string(ncid, varid, data_in)) ERR;
      for (i=0; i < NUM_PRES; i++)
      {
	 if (i < SOME_PRES && strcmp(data_in[i], data[i])) ERR;
	 if (i >= SOME_PRES && strcmp(data_in[i], "")) ERR;
      }
      
      /* Must free your data! */
      if (nc_free_string(SOME_PRES, (char **)data_in)) ERR;

      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   FINAL_RESULTS;
#ifdef USE_PARALLEL
   MPI_Finalize();
#endif   
}
コード例 #10
0
ファイル: tst_endian_fill.c プロジェクト: balborian/libmesh
int
main(int argc, char **argv)
{
   printf("\n*** Testing specified endiannesss fill values.\n");
   printf("*** testing simple case with int...");
   {
      int  ncid, varid, var2id, var3id;
      int data_in;
      int fill = NC_FILL_INT;

      /* Create file with a scalar int var that's big-endian. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_var(ncid, VAR_NAME, NC_INT, VAR_RANK, 0, &varid)) ERR;
      if (nc_def_var_endian(ncid, varid, NC_ENDIAN_BIG)) ERR;
      if (nc_def_var(ncid, VAR2_NAME, NC_INT, VAR_RANK, 0, &var2id)) ERR;
      if (nc_def_var_endian(ncid, var2id, NC_ENDIAN_LITTLE)) ERR;
      /* close without writing data, so vars 1 and 2 should contain
       * NC_FILL_INT */
      if (nc_def_var(ncid, VAR3_NAME, NC_INT, VAR_RANK, 0, &var3id)) ERR;
      if (nc_def_var_endian(ncid, var3id, NC_ENDIAN_BIG)) ERR;
      if (nc_put_var(ncid, var3id, &fill)) ERR;
      if (nc_close(ncid)) ERR;

      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq_varid(ncid, VAR_NAME, &varid)) ERR;
      if (nc_inq_varid(ncid, VAR2_NAME, &var2id)) ERR;
      if (nc_get_var_int(ncid, varid, &data_in)) ERR;
      if (data_in != NC_FILL_INT) ERR;
      if (nc_get_var_int(ncid, var2id, &data_in)) ERR;
      if (data_in != NC_FILL_INT) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing short, int, int64, and unsigned...");
   {
#define NUM_TYPES_TO_CHECK 6
      int  ncid, varid[NUM_TYPES_TO_CHECK];
      int check_type[NUM_TYPES_TO_CHECK] = {NC_SHORT, NC_USHORT, NC_INT,
					    NC_UINT, NC_INT64, NC_UINT64};
      char var_name[NUM_TYPES_TO_CHECK][NC_MAX_NAME + 1] = {"SHORT", "USHORT",
							   "INT", "UINT", "INT64",
							   "UINT64"};
      long long fill_value[NUM_TYPES_TO_CHECK] = {NC_FILL_SHORT, NC_FILL_USHORT, NC_FILL_INT,
						  NC_FILL_UINT, NC_FILL_INT64, NC_FILL_UINT64};
      long long data_in;
      int t;

      /* Create file with a scalar vars. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      for (t = 0; t < NUM_TYPES_TO_CHECK; t++)
      {
	 if (nc_def_var(ncid, var_name[t], check_type[t], 0, 0, &varid[t])) ERR;
	 if (nc_def_var_endian(ncid, varid[t], NC_ENDIAN_BIG)) ERR;
      }
      if (nc_close(ncid)) ERR;

      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      for (t = 0; t < NUM_TYPES_TO_CHECK; t++)
      {
	 int err = nc_get_var_longlong(ncid, varid[t], &data_in);
	 if(err && err != NC_ERANGE)
	   ERR;
	 if (data_in != fill_value[t])
	   ERR;
      }
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   FINAL_RESULTS;

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

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

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

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

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

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

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

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

  if(use_doeclim == 1) {
    if((retval = nc_put_var(ncid, tempid, &temp[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, doeclim_forcid, &doeclim_forc[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, heat_mixedid, &heat_mixed[0][0][0]))) { ncError(retval); }
    if((retval = nc_put_var(ncid, oceandiffid, &oceandiff[0]))) { ncError(retval); }
	  if((retval = nc_put_var(ncid, alphaid, &alpha[0]))) { ncError(retval); }
  }
  
  
  if((retval = nc_put_var(ncid, miuid, &miu[0][0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, utilityid, &utility[0][0]))) { ncError(retval); }
  
  if((retval = nc_put_var(ncid, csid, &cs[0]))) { ncError(retval); }
  
  if((retval = nc_put_var(ncid, yearid, &year[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, lid, &l[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, gaid, &ga[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, alid, &al[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, gsigid, &gsig[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, sigmaid, &sigma[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, cost1id, &cost1[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, etreeid, &etree[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, rrid, &rr[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, forcothid, &forcoth[0]))) { ncError(retval); }
  if((retval = nc_put_var(ncid, partfractid, &partfract[0]))) { ncError(retval); }
  
  if (dice->ctrl.setSavings < 0) {
    if((retval = nc_put_var(ncid, sid, &s2[0][0]))) { ncError(retval); }
  }
  else {
    if((retval = nc_put_var(ncid, sid, &s1[0]))) { ncError(retval); }
  }
  
  
  // Close the netcdf file
  if((retval = nc_close(ncid))) { ncError(retval); }
  
  return;
}
コード例 #12
0
ファイル: cluster.c プロジェクト: H2Lib/H2Lib
void
write_cdf_cluster(pccluster t, const char *name)
{
  size_t    clusters, clusteridx;
  size_t    coeffs, coeffidx;
  int       nc_file, nc_sons, nc_size, nc_idx, nc_coeff;
  int       nc_clusters, nc_coeffs, nc_totalsize, nc_dim;
  int       result;

  /* Count number of clusters and coefficients */
  clusters = 0;
  coeffs = 0;
  write_count(t, &clusters, &coeffs);

  /* Create NetCDF file */
  result = nc_create(name, NC_64BIT_OFFSET, &nc_file);
  assert(result == NC_NOERR);

  /* Define "clusters" dimension */
  result = nc_def_dim(nc_file, "clusters", clusters, &nc_clusters);
  assert(result == NC_NOERR);

  /* Define "coeffs" dimension */
  result = nc_def_dim(nc_file, "coeffs", coeffs, &nc_coeffs);
  assert(result == NC_NOERR);

  /* Define "totalsize" dimension */
  result = nc_def_dim(nc_file, "totalsize", t->size, &nc_totalsize);
  assert(result == NC_NOERR);

  /* Define "dim" dimension */
  result = nc_def_dim(nc_file, "dim", t->dim, &nc_dim);
  assert(result == NC_NOERR);

  /* Define "sons" variable */
  result = nc_def_var(nc_file, "sons", NC_INT, 1, &nc_clusters, &nc_sons);
  assert(result == NC_NOERR);

  /* Define "size" variable */
  result = nc_def_var(nc_file, "size", NC_INT, 1, &nc_clusters, &nc_size);
  assert(result == NC_NOERR);

  /* Define "idx" variable */
  result = nc_def_var(nc_file, "idx", NC_INT, 1, &nc_totalsize, &nc_idx);
  assert(result == NC_NOERR);

  /* Define "coeff" variable */
  result = nc_def_var(nc_file, "coeff", NC_DOUBLE, 1, &nc_coeffs, &nc_coeff);
  assert(result == NC_NOERR);

  /* Finish NetCDF define mode */
  result = nc_enddef(nc_file);
  assert(result == NC_NOERR);

  /* Write index to NetCDF variable */
  result = nc_put_var(nc_file, nc_idx, t->idx);

  /* Write coefficiens to NetCDF variables */
  clusteridx = 0;
  coeffidx = 0;
  write_cdf(t, clusters, coeffs, &clusteridx, &coeffidx,
	    nc_file, nc_sons, nc_size, nc_coeff);
  assert(clusteridx == clusters);
  assert(coeffidx == coeffs);

  /* Close file */
  result = nc_close(nc_file);
  assert(result == NC_NOERR);
}
コード例 #13
0
ファイル: cluster.c プロジェクト: H2Lib/H2Lib
void
write_cdfpart_cluster(pccluster t, int nc_file, const char *prefix)
{
  size_t    clusters, clusteridx;
  size_t    coeffs, coeffidx;
  char     *buf;
  int       bufsize;
  int       nc_sons, nc_size, nc_idx, nc_coeff;
  int       nc_clusters, nc_coeffs, nc_totalsize, nc_dim;
  int       result;

  /* Prepare buffer for prefixed names */
  bufsize = strlen(prefix) + 16;
  buf = (char *) allocmem(sizeof(char) * bufsize);

  /* Count number of clusters and coefficients */
  clusters = 0;
  coeffs = 0;
  write_count(t, &clusters, &coeffs);

  /* Switch NetCDF file to define mode */
  result = nc_redef(nc_file);
  assert(result == NC_NOERR || result == NC_EINDEFINE);

  /* Define "clusters" dimension */
  prefix_name(buf, bufsize, prefix, "clusters");
  result = nc_def_dim(nc_file, buf, clusters, &nc_clusters);
  assert(result == NC_NOERR);

  /* Define "coeffs" dimension */
  prefix_name(buf, bufsize, prefix, "coeffs");
  result = nc_def_dim(nc_file, buf, coeffs, &nc_coeffs);
  assert(result == NC_NOERR);

  /* Define "totalsize" dimension */
  prefix_name(buf, bufsize, prefix, "totalsize");
  result = nc_def_dim(nc_file, buf, t->size, &nc_totalsize);
  assert(result == NC_NOERR);

  /* Define "dim" dimension */
  prefix_name(buf, bufsize, prefix, "dim");
  result = nc_def_dim(nc_file, buf, t->dim, &nc_dim);
  assert(result == NC_NOERR);

  /* Define "sons" variable */
  prefix_name(buf, bufsize, prefix, "sons");
  result = nc_def_var(nc_file, buf, NC_INT, 1, &nc_clusters, &nc_sons);
  assert(result == NC_NOERR);

  /* Define "size" variable */
  prefix_name(buf, bufsize, prefix, "size");
  result = nc_def_var(nc_file, buf, NC_INT, 1, &nc_clusters, &nc_size);
  assert(result == NC_NOERR);

  /* Define "idx" variable */
  prefix_name(buf, bufsize, prefix, "idx");
  result = nc_def_var(nc_file, buf, NC_INT, 1, &nc_totalsize, &nc_idx);
  assert(result == NC_NOERR);

  /* Define "coeff" variable */
  prefix_name(buf, bufsize, prefix, "coeff");
  result = nc_def_var(nc_file, buf, NC_DOUBLE, 1, &nc_coeffs, &nc_coeff);
  assert(result == NC_NOERR);

  /* Finish NetCDF define mode */
  result = nc_enddef(nc_file);
  assert(result == NC_NOERR);

  /* Write index to NetCDF variable */
  result = nc_put_var(nc_file, nc_idx, t->idx);

  /* Write coefficiencs to NetCDF variables */
  clusteridx = 0;
  coeffidx = 0;
  write_cdf(t, clusters, coeffs, &clusteridx, &coeffidx,
	    nc_file, nc_sons, nc_size, nc_coeff);
  assert(clusteridx == clusters);
  assert(coeffidx == coeffs);

  /* Clean up */
  nc_sync(nc_file);
  freemem(buf);
}
コード例 #14
0
ファイル: ParcelManager.cpp プロジェクト: dongli/lasm
void ParcelManager::
output(const TimeLevelIndex<2> &timeIdx, int ncId) const {
    int parcelDimId, skel1DimId, dimDimId, tracerDimId;
    int idVarId;
    int cDimIds[2], cVarId;
    int hDimIds[3], hVarId;
    int mDimIds[2], mVarId;
    int sDimIds[3], s1VarId;
#define OUTPUT_TRACER_SHAPE
#ifdef OUTPUT_TRACER_SHAPE
    int skel2DimId, s2VarId, numSkel2 = 40;
#endif
    char str[100];
    int l;
    int *intData;
    double *doubleData;

    nc_redef(ncId);

    nc_def_dim(ncId, "parcel", _parcels.size(), &parcelDimId);
    nc_def_dim(ncId, "dim", mesh->domain().numDim(), &dimDimId);
    nc_def_dim(ncId, "tracer", Tracers::numTracer(), &tracerDimId);
    nc_def_dim(ncId, "skel1", SkeletonPoints::numPoint(), &skel1DimId);

#ifdef OUTPUT_TRACER_SHAPE
    if (mesh->domain().numDim() == 2) {
        // Only output skeleton in 2D domain, since in 3D it could be messy.
        nc_def_dim(ncId, "skel2", numSkel2, &skel2DimId);
    }
#endif
    
    nc_def_var(ncId, "id", NC_INT, 1, &parcelDimId, &idVarId);
    sprintf(str, "parcel identifier");
    nc_put_att(ncId, idVarId, "long_name", NC_CHAR, strlen(str), str);

    cDimIds[0] = parcelDimId; cDimIds[1] = dimDimId;
    nc_def_var(ncId, "c", NC_DOUBLE, 2, cDimIds, &cVarId);
    sprintf(str, "parcel centroid coordinates on %s", mesh->domain().brief().c_str());
    nc_put_att(ncId, cVarId, "long_name", NC_CHAR, strlen(str), str);

    hDimIds[0] = parcelDimId; hDimIds[1] = dimDimId; hDimIds[2] = dimDimId;
    nc_def_var(ncId, "h", NC_DOUBLE, 3, hDimIds, &hVarId);
    sprintf(str, "parcel linear deformation matrix");
    nc_put_att(ncId, hVarId, "long_name", NC_CHAR, strlen(str), str);

    mDimIds[0] = parcelDimId; mDimIds[1] = tracerDimId;
    nc_def_var(ncId, "m", NC_DOUBLE, 2, mDimIds, &mVarId);
    sprintf(str, "tracer mass");
    nc_put_att(ncId, mVarId, "long_name", NC_CHAR, strlen(str), str);

    sDimIds[0] = parcelDimId; sDimIds[1] = skel1DimId; sDimIds[2] = dimDimId;
    nc_def_var(ncId, "s1", NC_DOUBLE, 3, sDimIds, &s1VarId);
    sprintf(str, "parcel actual skeleton");
    nc_put_att(ncId, s1VarId, "long_name", NC_CHAR, strlen(str), str);

#ifdef OUTPUT_TRACER_SHAPE
    if (mesh->domain().numDim() == 2) {
        sDimIds[1] = skel2DimId;
        nc_def_var(ncId, "s2", NC_DOUBLE, 3, sDimIds, &s2VarId);
        sprintf(str, "parcel fitted skeleton");
        nc_put_att(ncId, s2VarId, "long_name", NC_CHAR, strlen(str), str);
    }
#endif
    
    nc_enddef(ncId);

    intData = new int[_parcels.size()];
    l = 0;
    for (auto parcel : _parcels) {
        intData[l++] = parcel->id();
    }
    nc_put_var(ncId, idVarId, intData);
    delete [] intData;
    
    doubleData = new double[_parcels.size()*mesh->domain().numDim()];
    l = 0;
    for (auto parcel : _parcels) {
        for (uword m = 0; m < mesh->domain().numDim(); ++m) {
            doubleData[l++] = parcel->x(timeIdx)(m);
        }
    }
    nc_put_var(ncId, cVarId, doubleData);
    delete [] doubleData;

    doubleData = new double[_parcels.size()*mesh->domain().numDim()*mesh->domain().numDim()];
    l = 0;
    for (auto parcel : _parcels) {
        for (uword m1 = 0; m1 < mesh->domain().numDim(); ++m1) {
            for (uword m2 = 0; m2 < mesh->domain().numDim(); ++m2) {
                doubleData[l++] = parcel->H(timeIdx)(m1, m2);
            }
        }
    }
    nc_put_var(ncId, hVarId, doubleData);
    delete [] doubleData;
    
    doubleData = new double[_parcels.size()*Tracers::numTracer()];
    l = 0;
    for (auto parcel : _parcels) {
        for (int t = 0; t < Tracers::numTracer(); ++t) {
            doubleData[l++] = parcel->tracers().mass(t);
        }
    }
    nc_put_var(ncId, mVarId, doubleData);
    delete [] doubleData;

    doubleData = new double[_parcels.size()*SkeletonPoints::numPoint()*mesh->domain().numDim()];
    l = 0;
    for (auto parcel : _parcels) {
        for (auto xs : parcel->skeletonPoints().spaceCoords(timeIdx)) {
            for (uword m = 0; m < mesh->domain().numDim(); ++m) {
                doubleData[l++] = xs(m);
            }
        }
    }
    nc_put_var(ncId, s1VarId, doubleData);
    delete [] doubleData;

#ifdef OUTPUT_TRACER_SHAPE
    if (mesh->domain().numDim() == 2) {
        double dtheta = PI2/numSkel2;
        BodyCoord y(2); SpaceCoord x(2);
        doubleData = new double[_parcels.size()*numSkel2*mesh->domain().numDim()];
        l = 0;
        for (auto parcel : _parcels) {
            for (int i = 0; i < numSkel2; ++i) {
                double theta = i*dtheta;
                y(0) = cos(theta);
                y(1) = sin(theta);
                parcel->calcSpaceCoord(timeIdx, y, x);
                for (uword m = 0; m < mesh->domain().numDim(); ++m) {
                    doubleData[l++] = x(m);
                }
            }
        }
        nc_put_var(ncId, s2VarId, doubleData);
        delete [] doubleData;
    }
#endif
} // output
コード例 #15
0
ファイル: NetCdfWriter.cpp プロジェクト: tsunamiSim/SWE
io::NetCdfWriter::NetCdfWriter( const std::string &i_baseName,
		const Float2D &i_b,
		const BoundarySize &i_boundarySize,
		const BoundaryType &i_boundaryTypeLeft,
		const BoundaryType &i_boundaryTypeRight,
		const BoundaryType &i_boundaryTypeTop,
		const BoundaryType &i_boundaryTypeBottom,
		const float i_endOfSimulation,			
		int i_nX, int i_nY,
		float i_dX, float i_dY,
		float i_originX, float i_originY,
		unsigned int i_flush,
		bool useCheckpoints,
		unsigned int compression) :
	io::Writer(i_baseName + ".nc", i_b, i_boundarySize, i_nX, i_nY),
	flush(i_flush), compress(compression) {
	int retVal;

	if(useCheckpoints)
	{
		retVal = nc_open(fileName.c_str(), NC_WRITE, &dataFile);

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

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

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

	    //create a netCDF-file, an existing file will be replaced
	    /*int status = nc_create(fileName.c_str(), NC_NETCDF4, &dataFile);
	
	    //check if the netCDF-file creation constructor succeeded.
	    if (status != NC_NOERR) {
		    assert(false);
		    return;
	    }*/

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

	    //dimensions
	    int l_timeDim, l_xDim, l_yDim;
	    nc_def_dim(dataFile, "time", NC_UNLIMITED, &l_timeDim);
	    nc_def_dim(dataFile, "x", nX, &l_xDim);
	    nc_def_dim(dataFile, "y", nY, &l_yDim);

	    //variables (TODO: add rest of CF-1.5)
	    int l_xVar, l_yVar, l_eosVar;

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

	    nc_def_var(dataFile, "x", NC_FLOAT, 1, &l_xDim, &l_xVar);
	    nc_def_var(dataFile, "y", NC_FLOAT, 1, &l_yDim, &l_yVar);

	    // EndOfSimulation
	    nc_def_var(dataFile, "eos", NC_FLOAT, 0, 0, &l_eosVar); // The end of simulation variable
	    ncPutAttText(l_eosVar, "long_name", "End of Simulation");
	    if(retVal = nc_put_var(dataFile, l_eosVar, &i_endOfSimulation)) ERR(retVal);
	
	    // Boundary Types
	    int l_currBoundary, l_currInt;
	    nc_def_var(dataFile, "bL", NC_INT, 0, 0, &l_currBoundary); // Left boundadry
	    ncPutAttText(l_currBoundary, "long_name", "Boundary Type left. 0: Outflow, 1: Wall");
	    l_currInt = (int) i_boundaryTypeLeft;
	    if(retVal = nc_put_var(dataFile, l_currBoundary, &l_currInt)) ERR(retVal);
	    nc_def_var(dataFile, "bR", NC_INT, 0, 0, &l_currBoundary); // Right boundadry
	    ncPutAttText(l_currBoundary, "long_name", "Boundary Type right. 0: Outflow, 1: Wall");
	    l_currInt = (int) i_boundaryTypeRight;
	    if(retVal = nc_put_var(dataFile, l_currBoundary, &l_currInt)) ERR(retVal);
	    nc_def_var(dataFile, "bT", NC_INT, 0, 0, &l_currBoundary); // Top boundadry
	    ncPutAttText(l_currBoundary, "long_name", "Boundary Type top. 0: Outflow, 1: Wall");
	    l_currInt = (int) i_boundaryTypeTop;
	    if(retVal = nc_put_var(dataFile, l_currBoundary, &l_currInt)) ERR(retVal);
	    nc_def_var(dataFile, "bB", NC_INT, 0, 0, &l_currBoundary); // Bottom boundadry
	    ncPutAttText(l_currBoundary, "long_name", "Boundary Type bottom. 0: Outflow, 1: Wall");
	    l_currInt = (int) i_boundaryTypeBottom;
	    if(retVal = nc_put_var(dataFile, l_currBoundary, &l_currInt)) ERR(retVal);

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

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

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

		    gridPosition += i_dX;
	    }

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

        	gridPosition += i_dY;
	    }
    }
	nc_sync(dataFile);
	
}
コード例 #16
0
int
main(int argc, char **argv)
{
   int ncid;
   size_t size_in;
   nc_type xtype;
   unsigned char data[DIM_LEN][BASE_SIZE], data_in[DIM_LEN][BASE_SIZE];
   int i, j;

   printf("\n*** Testing netcdf-4 opaque type.\n");

   for (i=0; i<DIM_LEN; i++)
      for (j=0; j<BASE_SIZE; j++)
	 data[i][j] = 0;

   printf("*** testing scalar opaque variable...");
   {
      int varid;
      char name_in[NC_MAX_NAME+1];
      size_t nfields_in, base_size_in;
      nc_type base_nc_type_in, var_type;
      int class_in;
      char var_name[NC_MAX_NAME+1];
      int  nvars, natts, ndims, unlimdimid;

      /* Create a file that has an opaque variable. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLOBBER, &ncid)) ERR;
      if (nc_def_opaque(ncid, BASE_SIZE, TYPE_NAME, &xtype)) ERR;
      if (nc_inq_user_type(ncid, xtype, name_in, &base_size_in, &base_nc_type_in, &nfields_in, &class_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE || 
	  base_nc_type_in != 0 || nfields_in != 0 || class_in != NC_OPAQUE) ERR;
      if (nc_inq_opaque(ncid, xtype, name_in, &base_size_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE) ERR;
      if (nc_def_var(ncid, VAR_NAME, xtype, 0, NULL, &varid)) ERR; 
      if (nc_put_var(ncid, varid, &data[0])) ERR; 
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 0 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_var(ncid, 0, var_name, &var_type, &ndims, NULL, &natts)) ERR;
      if (ndims != 0 || strcmp(var_name, VAR_NAME) || natts != 0) ERR;
      if (nc_get_var(ncid, 0, &data_in[0])) ERR;
      for (j = 0; j < BASE_SIZE; j++)
	 if (data_in[0][j] != data[0][j]) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing opaque variable...");
   {
      int dimid, varid, dimids[] = {0};
      char name_in[NC_MAX_NAME+1];
      nc_type base_nc_type_in, var_type;
      size_t nfields_in, base_size_in;
      int class_in;
      char var_name[NC_MAX_NAME+1];
      int  nvars, natts, ndims, unlimdimid, dimids_var[1];

      /* Create a file that has an opaque variable. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLOBBER, &ncid)) ERR;
      if (nc_def_opaque(ncid, BASE_SIZE, TYPE_NAME, &xtype)) ERR;
      if (nc_inq_user_type(ncid, xtype, name_in, &base_size_in, &base_nc_type_in, &nfields_in, &class_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE ||
	  base_nc_type_in != 0 || nfields_in != 0 || class_in != NC_OPAQUE) ERR;
      if (nc_inq_opaque(ncid, xtype, name_in, &base_size_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE) ERR;
      if (nc_def_dim(ncid, DIM_NAME, DIM_LEN, &dimid)) ERR;
      if (nc_def_var(ncid, VAR_NAME, xtype, 1, dimids, &varid)) ERR;
      if (nc_put_var(ncid, varid, data)) ERR;
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 1 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_var(ncid, 0, var_name, &var_type, &ndims, dimids_var, &natts)) ERR;
      if (ndims != 1 || strcmp(var_name, VAR_NAME) ||
	  dimids_var[0] != dimids[0] || natts != 0) ERR;
      if (nc_get_var(ncid, 0, data_in)) ERR;
      for (i=0; i<DIM_LEN; i++)
 	 for (j=0; j<BASE_SIZE; j++)
 	    if (data_in[i][j] != data[i][j]) ERR;
      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing *really* simple opaque attribute...");
   {

      /* Create a file that has an opaque attribute. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;
      if (nc_def_opaque(ncid, BASE_SIZE, TYPE_NAME, &xtype)) ERR;

      /* Write an att. */
      if (nc_put_att(ncid, NC_GLOBAL, ATT_NAME, xtype, DIM_LEN, data)) ERR;
      if (nc_close(ncid)) ERR;

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

   SUMMARIZE_ERR;
   printf("*** testing opaque attribute...");
   {
      char name_in[NC_MAX_NAME+1];
      nc_type base_nc_type_in;
      size_t base_size_in;
      size_t nfields_in;
      int class_in;

      /* Create a file that has an opaque attribute. */
      if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR;

      if (nc_def_opaque(ncid, BASE_SIZE, TYPE_NAME, &xtype)) ERR;

      /* Check it out. */
      if (nc_inq_user_type(ncid, xtype, name_in, &base_size_in, &base_nc_type_in,
			   &nfields_in, &class_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE ||
	  base_nc_type_in != 0 || nfields_in != 0 || class_in != NC_OPAQUE) ERR;
      if (nc_inq_opaque(ncid, xtype, name_in, &base_size_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE) ERR;

      /* Write an att. */
      if (nc_put_att(ncid, NC_GLOBAL, ATT_NAME, xtype, DIM_LEN, data)) ERR;

      if (nc_close(ncid)) ERR;

      /* Reopen. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;

      /* Check it out. */
      if (nc_inq_att(ncid, NC_GLOBAL, ATT_NAME, &xtype, &size_in)) ERR;
      if (size_in != DIM_LEN) ERR;
      if (nc_inq_user_type(ncid, xtype, name_in, &base_size_in, &base_nc_type_in, &nfields_in, &class_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE ||
	  base_nc_type_in != 0 || nfields_in != 0 || class_in != NC_OPAQUE) ERR;
      if (nc_inq_opaque(ncid, xtype, name_in, &base_size_in)) ERR;
      if (strcmp(name_in, TYPE_NAME) || base_size_in != BASE_SIZE) ERR;
      if (nc_get_att(ncid, NC_GLOBAL, ATT_NAME, data_in)) ERR;
      for (i=0; i<DIM_LEN; i++)
 	 for (j=0; j<BASE_SIZE; j++)
 	    if (data_in[i][j] != data[i][j]) ERR;

      if (nc_close(ncid)) ERR;
   }
   SUMMARIZE_ERR;
   printf("*** testing 3 opaque types...");
   {
#define TYPE_SIZE1 20
#define NUM_TYPES 3

      char name_in[NC_MAX_NAME+1];
      nc_type base_nc_type_in;
      size_t nfields_in, base_size_in;
      nc_type otid[3];
      int class_in;
      char type_name[NUM_TYPES][NC_MAX_NAME + 1] = {"o1", "o2", "o3"};
      int  nvars, natts, ndims, unlimdimid;
      int ntypes, typeids[NUM_TYPES];
      int i;

      /* Create a file that has three opaque types. */
      if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLOBBER, &ncid)) ERR;
      for (i = 0; i < NUM_TYPES; i++)
      {
	 if (nc_def_opaque(ncid, TYPE_SIZE1, type_name[i], &otid[i])) ERR;
	 if (nc_inq_user_type(ncid, otid[i], name_in, &base_size_in, &base_nc_type_in, &nfields_in, &class_in)) ERR;
	 if (strcmp(name_in, type_name[i]) || base_size_in != TYPE_SIZE1 ||
	     base_nc_type_in != 0 || nfields_in != 0 || class_in != NC_OPAQUE) ERR;
	 if (nc_inq_opaque(ncid, otid[i], name_in, &base_size_in)) ERR;
	 if (strcmp(name_in, type_name[i]) || base_size_in != TYPE_SIZE1) ERR;
      }
      if (nc_close(ncid)) ERR;
      
      /* Check it out. */
      if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR;
      if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR;
      if (ndims != 0 || nvars != 0 || natts != 0 || unlimdimid != -1) ERR;
      if (nc_inq_typeids(ncid, &ntypes, typeids)) ERR;
      if (ntypes != NUM_TYPES) ERR;
      for (i = 0; i < NUM_TYPES; i++)
      {
	 if (nc_inq_user_type(ncid, otid[i], name_in, &base_size_in, &base_nc_type_in, &nfields_in, &class_in)) ERR;
	 if (strcmp(name_in, type_name[i]) || base_size_in != TYPE_SIZE1 ||
	     base_nc_type_in != 0 || nfields_in != 0 || class_in != NC_OPAQUE) ERR;
	 if (nc_inq_opaque(ncid, otid[i], name_in, &base_size_in)) ERR;
	 if (strcmp(name_in, type_name[i]) || base_size_in != TYPE_SIZE1) ERR;
      }
      if (nc_close(ncid)) ERR;
   }

   SUMMARIZE_ERR;
   FINAL_RESULTS;
}
コード例 #17
0
ファイル: nccreate.c プロジェクト: gengyifeng/fastbit_test
/*void generator(const char* fname,int * shapes,int *types,int dim_size,TYPE var_type){*/
int generator(const char* fname,char *dimnames[],char *varname,size_t * shapes,int dim_size,TYPE *types,TYPE var_type){
    int res;    
    int ncid,vlid;
    int *dimids=(int *)calloc(dim_size,sizeof(int));
    int *dimvarids=(int *)calloc(dim_size,sizeof(int));
/*        dimids[3],dimvarids[3];*/
/*    int d1_id,d2_id,d3_id;*/
    double coverage=1.0;
/*    char *dim_names[]={"d1","d2","d3"};*/
    size_t total_size=1;
    size_t max_pos=0;
    int i; 
    for(i=0;i<dim_size;i++){
        total_size*=shapes[i];
        max_pos+=shapes[i];
    }
/*    double min=0;*/
/*    double max=coverage;*/
/*    TYPE types[3]={DOUBLE,DOUBLE,DOUBLE};*/
/*    if((res=nc_create(fname,NC_CLOBBER|NC_64BIT_OFFSET,&ncid)))*/
/*        BAIL(res);*/
    if((res=nc_create(fname,NC_CLASSIC_MODEL|NC_NETCDF4,&ncid)))
        BAIL(res);
/*    if((res=nc_def_dim(ncid,"d1",dims.shape[0],&dimids[0])))*/
/*        BAIL(res);*/
    for(i=0;i<dim_size;i++){
        if(i==0){
/*            if((res=nc_def_dim(ncid,dimnames[i],NC_UNLIMITED,&dimids[i])))*/
/*                BAIL(res);*/
             if((res=nc_def_dim(ncid,dimnames[i],shapes[i],&dimids[i])))
                BAIL(res);
        }else{
             if((res=nc_def_dim(ncid,dimnames[i],shapes[i],&dimids[i])))
                BAIL(res);
        }
        if((res=nc_def_var(ncid,dimnames[i],get_nctype(types[i]),1,&dimids[i],&dimvarids[i])))
            BAIL(res);
    }
/*    if((res=nc_def_var(ncid,"d1",get_nctype(types[0]),1,&dimids[0],&dimvarids[0])))*/
/*        BAIL(res);*/
/*    if((res=nc_def_var(ncid,"d2",get_nctype(types[1]),1,&dimids[1],&dimvarids[1])))*/
/*        BAIL(res);*/
/*    if((res=nc_def_var(ncid,"d3",get_nctype(types[2]),1,&dimids[2],&dimvarids[2])))*/
/*        BAIL(res);*/
    if((res=nc_def_var(ncid,varname,get_nctype(var_type),dim_size,dimids,&vlid)))
        BAIL(res);
    if((res=nc_enddef(ncid)))
        BAIL(res);
    
    void **dimvar=(void **)calloc(dim_size,sizeof(void *));
    void *buffer=calloc(total_size/shapes[0],get_type_size(var_type));
    void *udata=calloc(1,get_type_size(types[0]));
    for(i=1;i<dim_size;i++){
        dimvar[i]=calloc(shapes[i],get_type_size(types[i]));
        init_dimvar(dimvar[i],shapes[i],types[i]);
        nc_put_var(types[i],ncid,dimvarids[i],dimvar[i]);
        free(dimvar[i]); 
    }
    size_t *start=(size_t *)calloc(dim_size,sizeof(size_t));
    size_t *count=(size_t *)calloc(dim_size,sizeof(size_t));
    size_t *dshape=(size_t *)calloc(dim_size,sizeof(size_t));
    size_t ustart[1]={0};
    size_t ucount[1]={1};
    for(i=1;i<dim_size;i++){ 
        count[i]=shapes[i];
    }
    count[0]=1;
    get_dshape(dshape,shapes,dim_size);
    double shift=0;
/*    double shift=0.01;*/
    for(i=0;i<shapes[0];i++){
        start[0]=i;
        ustart[0]=i;
        getval(((char *)udata),i,types[0]);
        nc_put_vara(types[0],ncid,dimids[0],ustart,ucount,udata);
        if(gm==RANDOM)
            init_var(buffer,total_size/shapes[0],0,1,var_type);
        if(gm==LOCALITY){
/*            printf("locality");*/
/*            init_var_locality(buffer,total_size/shapes[0],i*(total_size/shapes[0]),var_type);*/
            init_var_locality(buffer,total_size/shapes[0],i,shapes,dshape,dim_size,shift,var_type);
        }
        if(gm==FIXED){
            init_var_fixed(buffer,total_size/shapes[0],fixsize,var_type);
        }
        nc_put_vara(var_type,ncid,vlid,start,count,buffer);
    }
    if((res=nc_close(ncid)))
        BAIL(res);
    return 0;
}