/* ----------------------------- MNI Header ----------------------------------- @NAME : setup_image_variables @INPUT : inmincid - id of input minc file (MI_ERROR if no file) mincid - id of output minc file ndims - number of dimensions dim - list of dimension ids @OUTPUT : (nothing) @RETURNS : (nothing) @DESCRIPTION: Routine to set up image, image-max and image-min variables in the output minc file @METHOD : @GLOBALS : @CALLS : @CREATED : August 26, 1993 (Peter Neelin) @MODIFIED : ---------------------------------------------------------------------------- */ void setup_image_variables(int inmincid, int mincid, int ndims, int dim[]) { int imgid, maxid, minid; static double valid_range[2] = {0.0, 255.0}; /* Create the image variable, copy attributes, set the signtype attribute, set the valid range attribute and delete valid max/min attributes */ imgid = micreate_std_variable(mincid, MIimage, NC_BYTE, ndims, dim); if (inmincid != MI_ERROR) { (void) micopy_all_atts(inmincid, ncvarid(inmincid, MIimage), mincid, imgid); ncopts = 0; (void) ncattdel(mincid, imgid, MIvalid_max); (void) ncattdel(mincid, imgid, MIvalid_min); ncopts = NC_OPTS_VAL; } (void) miattputstr(mincid, imgid, MIsigntype, MI_UNSIGNED); (void) ncattput(mincid, imgid, MIvalid_range, NC_DOUBLE, 2, valid_range); /* Create the image max and min variables (varying over slices) */ maxid = micreate_std_variable(mincid, MIimagemax, NC_DOUBLE, 1, dim); minid = micreate_std_variable(mincid, MIimagemin, NC_DOUBLE, 1, dim); if (inmincid != MI_ERROR) { (void) micopy_all_atts(inmincid, ncvarid(inmincid, MIimagemax), mincid, maxid); (void) micopy_all_atts(inmincid, ncvarid(inmincid, MIimagemin), mincid, minid); } }
/* ----------------------------- MNI Header ----------------------------------- @NAME : UpdateHistory @INPUT : ChildCDF - the MINC file which will have TimeStamp prepended to its history attribute TimeStamp - string to be added to history attribute in ChildCDF @OUTPUT : (none) @RETURNS : (void) @DESCRIPTION: Update the history of a MINC file by appending a string to it. The history attribute will be created if it does not exist in the file specified by CDF; otherwise, its current value will be read in, the string TimeStamp will be appended to it, and it will be re-written. @METHOD : @GLOBALS : @CALLS : NetCDF, MINC libraries @CREATED : 93-10-27, Greg Ward (from MW's code formerly in micreate) @MODIFIED : 93-11-16, Greg Ward: removed references to parent file; the attribute should now be copied from the parent file before UpdateHistory is ever called. ---------------------------------------------------------------------------- */ void UpdateHistory (int ChildCDF, char *TimeStamp) { nc_type HistType; int HistLen; #ifdef DEBUG printf ("UpdateHistory:\n"); #endif /* Update the history of the child file */ if (ncattinq (ChildCDF,NC_GLOBAL,MIhistory,&HistType,&HistLen) == MI_ERROR) { #ifdef DEBUG printf (" creating history attribute\n"); #endif ncattput (ChildCDF, NC_GLOBAL, MIhistory, NC_CHAR, strlen(TimeStamp), TimeStamp); } else { char *OldHist; char *NewHist; #ifdef DEBUG printf (" adding to history attribute\n"); #endif OldHist = (char *) malloc ((size_t) (HistLen*sizeof(char) + 1)); ncattget (ChildCDF, NC_GLOBAL, MIhistory, OldHist); NewHist = (char *) malloc ((size_t) (HistLen*sizeof(char) + strlen(TimeStamp)*sizeof(char) + 1)); strcpy (NewHist, OldHist); strcat (NewHist, TimeStamp); ncattput (ChildCDF, NC_GLOBAL, MIhistory, NC_CHAR, strlen(NewHist), NewHist); free (NewHist); free (OldHist); } } /* UpdateHistory () */
MNCAPI int MI2attput(int fd, int varid, const char *attnm, nc_type val_typ, int val_len, void *val_ptr) { if (MI2_ISH5OBJ(fd)) { return (hdf_attput(fd, varid, attnm, val_typ, val_len, val_ptr)); } else { int old_ncopts = ncopts; int result; ncopts = 0; result = ncattput(fd, varid, attnm, val_typ, val_len, val_ptr); ncopts = old_ncopts; return (result); } }
/* ----------------------------- MNI Header -----------------------------------@NAME : CreateImageVars @INPUT : CDF - ID of the MINC file in which to create MIimagemax and MIimagemin variables NumDim - *total* number of image dimensions (2,3, or 4) DimIDs - ID's of the NumDim image dimensions NCType - type of the image variable Signed - TRUE or FALSE, for the image variable ValidRange - for the image variable @OUTPUT : @RETURNS : TRUE on success FALSE if any error creating either variable (sets ErrMsg on error) @DESCRIPTION: Create the MIimagemax and MIimagemin variables in a newly created MINC file (must be in definition mode!). The variables will depend on the two lowest (slowest-varying) image dimensions, ie. frames and slices in the full 4-D case. If the file has no frames or no slices (or both), that will be handled properly. @METHOD : @GLOBALS : ErrMsg @CALLS : MINC library @CREATED : 93-10-28, Greg Ward: code moved from main() @MODIFIED : 93-11-10, GPW: renamed and modified from CreateMinMax ---------------------------------------------------------------------------- */ Boolean CreateImageVars (int CDF, int NumDim, int DimIDs[], nc_type NCType, Boolean Signed, double ValidRange[]) { int image_id; int max_id, min_id; /* ID's of the newly-created variables */ #ifdef DEBUG printf ("CreateImageVars:\n"); printf (" Creating MIimage variable with %d dimensions\n", NumDim); #endif image_id = micreate_std_variable (CDF, MIimage, NCType, NumDim, DimIDs); (void) miattputstr (CDF, image_id, MIsigntype, MI_SIGN_STR(Signed)); (void) miattputstr (CDF, image_id, MIcomplete, MI_FALSE); (void) ncattput (CDF, image_id, MIvalid_range, NC_DOUBLE, 2, ValidRange); /* * Create the image-max and image-min variables. They should be * dependent on the "non-image" dimensions (ie. time and slices, * if they exist), so pass NumDim-2 as the number of * dimensions, and DimIDs as the list of dimension ID's -- * micreate_std_variable should then only look at the first one * or two dimension IDs in the list. */ #ifdef DEBUG printf (" creating MIimagemin and MIimagemax with %d dimensions\n", NumDim-2); #endif max_id = micreate_std_variable (CDF, MIimagemax, NC_DOUBLE, NumDim-2, DimIDs); min_id = micreate_std_variable (CDF, MIimagemin, NC_DOUBLE, NumDim-2, DimIDs); if ((max_id == MI_ERROR) || (min_id == MI_ERROR)) { sprintf (ErrMsg, "Error creating image max/min variables: %s\n", NCErrMsg (ncerr, errno)); return (FALSE); } return (TRUE); } /* CreateImageVars () */
int ex_put_prop_array (int exoid, int obj_type, const char *prop_name, const int *values) { int num_props, i, propid, dimid, dims[1], iresult; int found = FALSE; long start[1], count[1], num_obj; nclong *lptr; char name[MAX_VAR_NAME_LENGTH+1]; char tmpstr[MAX_STR_LENGTH+1]; char obj_stype[MAX_VAR_NAME_LENGTH+1]; char dim_name[MAX_VAR_NAME_LENGTH+1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* check if property has already been created */ num_props = ex_get_num_props(exoid, obj_type); switch (obj_type) { case EX_ELEM_BLOCK: strcpy (obj_stype, VAR_ID_EL_BLK); strcpy (dim_name, DIM_NUM_EL_BLK); break; case EX_NODE_SET: strcpy (obj_stype, VAR_NS_IDS); strcpy (dim_name, DIM_NUM_NS); break; case EX_SIDE_SET: strcpy (obj_stype, VAR_SS_IDS); strcpy (dim_name, DIM_NUM_SS); break; case EX_ELEM_MAP: strcpy (obj_stype, VAR_EM_PROP(1)); strcpy (dim_name, DIM_NUM_EM); break; case EX_NODE_MAP: strcpy (obj_stype, VAR_NM_PROP(1)); strcpy (dim_name, DIM_NUM_NM); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } /* inquire id of previously defined dimension (number of objects) */ if ((dimid = ncdimid (exoid, dim_name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate number of %s objects in file id %d", obj_stype, exoid); ex_err("ex_put_prop_array",errmsg, exerrval); return (EX_FATAL); } /* get number of objects */ if (ncdiminq (exoid, dimid, dim_name, &num_obj) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get number of %s objects in file id %d", obj_stype, exoid); ex_err("ex_put_prop_array",errmsg, exerrval); return (EX_FATAL); } for (i=1; i<=num_props; i++) { switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return(EX_FATAL); } if ((propid = ncvarid (exoid, name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get property array id in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } /* compare stored attribute name with passed property name */ memset(tmpstr, 0, MAX_STR_LENGTH+1); if ((ncattget (exoid, propid, ATT_PROP_NAME, tmpstr)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get property name in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } if (strcmp(tmpstr, prop_name) == 0) { found = TRUE; break; } } /* if property array has not been created, create it */ if (!found) { /* put netcdf file into define mode */ if (ncredef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } /* create a variable with a name xx_prop#, where # is the new number */ /* of properties */ switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(num_props+1)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(num_props+1)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(num_props+1)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(num_props+1)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(num_props+1)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_array",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } dims[0] = dimid; ncsetfill(exoid, NC_FILL); /* fill with zeros per routine spec */ if ((propid = ncvardef (exoid, name, NC_LONG, 1, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create property array variable in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } ncsetfill(exoid, NC_NOFILL); /* default: nofill */ /* store property name as attribute of property array variable */ if ((ncattput (exoid, propid, ATT_PROP_NAME, NC_CHAR, strlen(prop_name)+1, prop_name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store property name %s in file id %d", prop_name,exoid); ex_err("ex_put_prop_array",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* leave define mode */ if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to leave define mode in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } } /* put num_obj values in property array */ /* this contortion is necessary because netCDF is expecting nclongs; fortunately it's necessary only when ints and nclongs aren't the same size */ start[0] = 0; count[0] = num_obj; if (sizeof(int) == sizeof(nclong)) { iresult = ncvarput (exoid, propid, start, count, values); } else { lptr = itol (values, (int)num_obj); iresult = ncvarput (exoid, propid, start, count, lptr); free(lptr); } if (iresult == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store property values in file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: ncsetfill(exoid, NC_NOFILL); /* default: nofill */ if (ncendef (exoid) == -1) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_prop_array",errmsg,exerrval); } return (EX_FATAL); }
int ex_put_elem_block (int exoid, int elem_blk_id, const char *elem_type, int num_elem_this_blk, int num_nodes_per_elem, int num_attr) { int varid, dimid, dims[2], elem_blk_id_ndx, elem_blk_stat, strdim; long start[2], num_elem_blk; nclong ldum; int cur_num_elem_blk, nelnoddim, numelbdim, numattrdim, connid; char *cdum; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ cdum = 0; /* first check if any element blocks are specified */ if ((dimid = (ncdimid (exoid, DIM_NUM_EL_BLK))) == -1 ) { exerrval = ncerr; sprintf(errmsg, "Error: no element blocks defined in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Get number of element blocks defined for this file */ if ((ncdiminq (exoid,dimid,cdum,&num_elem_blk)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get number of element blocks in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Next: Make sure that this is not a duplicate element block id by searching the VAR_ID_EL_BLK array. WARNING: This must be done outside of define mode because id_lkup accesses the database to determine the position */ if ((varid = ncvarid (exoid, VAR_ID_EL_BLK)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate element block ids in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } elem_blk_id_ndx = ex_id_lkup(exoid,VAR_ID_EL_BLK,elem_blk_id); if (exerrval != EX_LOOKUPFAIL) /* found the element block id */ { exerrval = EX_FATAL; sprintf(errmsg, "Error: element block id %d already exists in file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Keep track of the total number of element blocks defined using a counter stored in a linked list keyed by exoid. NOTE: ex_get_file_item is a function that finds the number of element blocks for a specific file and returns that value incremented. */ cur_num_elem_blk=ex_get_file_item(exoid, &eb_ctr_list); if (cur_num_elem_blk >= num_elem_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of element blocks (%ld) defined in file id %d", num_elem_blk,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* NOTE: ex_get_file_item is a function that finds the number of element blocks for a specific file and returns that value incremented. */ cur_num_elem_blk=ex_inc_file_item(exoid, &eb_ctr_list); start[0] = (long)cur_num_elem_blk; /* write out element block id to previously defined id array variable*/ ldum = (nclong)elem_blk_id; if (ncvarput1 (exoid, varid, start, &ldum) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element block id to file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } elem_blk_id_ndx = start[0]+1; /* element id index into VAR_ID_EL_BLK array*/ if (num_elem_this_blk == 0) /* Is this a NULL element block? */ elem_blk_stat = 0; /* change element block status to NULL */ else elem_blk_stat = 1; /* change element block status to TRUE */ if ((varid = ncvarid (exoid, VAR_STAT_EL_BLK)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate element block status in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } ldum = (nclong)elem_blk_stat; if (ncvarput1 (exoid, varid, start, &ldum) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element id %d status to file id %d", elem_blk_id, exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } if (num_elem_this_blk == 0) /* Is this a NULL element block? */ { return(EX_NOERR); } /* * Check that storage required for connectivity array is less * than 2GB which is maximum size permitted by netcdf * (in large file mode). 1<<29 == max number of integer items. */ if (num_elem_this_blk * num_nodes_per_elem > (1<<29)) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Size to store connectivity for element block %d exceeds 2GB in file id %d", elem_blk_id, exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* put netcdf file into define mode */ if (ncredef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* define some dimensions and variables*/ if ((numelbdim = ncdimdef (exoid, DIM_NUM_EL_IN_BLK(elem_blk_id_ndx), (long)num_elem_this_blk)) == -1) { if (ncerr == NC_ENAMEINUSE) /* duplicate entry */ { exerrval = ncerr; sprintf(errmsg, "Error: element block %d already defined in file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } else { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of elements/block for block %d file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } if ((nelnoddim = ncdimdef (exoid, DIM_NUM_NOD_PER_EL(elem_blk_id_ndx), (long)num_nodes_per_elem)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of nodes/element for block %d in file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* element attribute array */ if (num_attr > 0) { if ((numattrdim = ncdimdef (exoid, DIM_NUM_ATT_IN_BLK(elem_blk_id_ndx), (long)num_attr)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of attributes in block %d in file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } dims[0] = numelbdim; dims[1] = numattrdim; if ((ncvardef (exoid, VAR_ATTRIB(elem_blk_id_ndx), nc_flt_code(exoid), 2, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define attributes for element block %d in file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* inquire previously defined dimensions */ if ((strdim = ncdimid (exoid, DIM_STR)) < 0) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Attribute names... */ dims[0] = numattrdim; dims[1] = strdim; if (ncvardef (exoid, VAR_NAME_ATTRIB(elem_blk_id_ndx), NC_CHAR, 2, dims) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define element attribute name array in file id %d",exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* element connectivity array */ dims[0] = numelbdim; dims[1] = nelnoddim; if ((connid = ncvardef (exoid, VAR_CONN(elem_blk_id_ndx), NC_LONG, 2, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create connectivity array for block %d in file id %d", elem_blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store element type as attribute of connectivity variable */ if ((ncattput (exoid, connid, ATT_NAME_ELB, NC_CHAR, strlen(elem_type)+1, (void*) elem_type)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element type name %s in file id %d", elem_type,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* leave define mode */ if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to complete element block definition in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (ncendef (exoid) == -1) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } return (EX_FATAL); }
int ex_put_block( int exoid, int blk_type, int blk_id, const char* entry_descrip, int num_entries_this_blk, int num_nodes_per_entry, int num_edges_per_entry, int num_faces_per_entry, int num_attr_per_entry ) { int varid, dimid, dims[2], blk_id_ndx, blk_stat, strdim; long start[2], num_blk; nclong ldum; int cur_num_blk, numblkdim, numattrdim; int nnodperentdim, nedgperentdim = -1, nfacperentdim = -1; int connid, econnid, fconnid; char *cdum; char errmsg[MAX_ERR_LENGTH]; const char* tname; const char* dnumblk; const char* vblkids; const char* vblksta; const char* vnodcon = 0; const char* vedgcon = 0; const char* vfaccon = 0; const char* vattnam = 0; const char* vblkatt = 0; const char* dneblk = 0; const char* dnape = 0; const char* dnnpe = 0; const char* dnepe = 0; const char* dnfpe = 0; struct list_item** ctr_list; exerrval = 0; /* clear error code */ cdum = 0; switch (blk_type) { case EX_EDGE_BLOCK: tname = "edge"; dnumblk = DIM_NUM_ED_BLK; vblkids = VAR_ID_ED_BLK; vblksta = VAR_STAT_ED_BLK; ctr_list = &ed_ctr_list; break; case EX_FACE_BLOCK: tname = "face"; dnumblk = DIM_NUM_FA_BLK; vblkids = VAR_ID_FA_BLK; vblksta = VAR_STAT_FA_BLK; ctr_list = &fa_ctr_list; break; case EX_ELEM_BLOCK: tname = "element"; dnumblk = DIM_NUM_EL_BLK; vblkids = VAR_ID_EL_BLK; vblksta = VAR_STAT_EL_BLK; ctr_list = &eb_ctr_list; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Bad block type (%d) specified for file id %d", blk_type, exoid ); ex_err( "ex_put_block", errmsg, exerrval ); return (EX_FATAL); } /* first check if any element blocks are specified */ if ((dimid = (ncdimid (exoid, dnumblk))) == -1 ) { exerrval = ncerr; sprintf(errmsg, "Error: no element blocks defined in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Get number of element blocks defined for this file */ if ((ncdiminq (exoid,dimid,cdum,&num_blk)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get number of element blocks in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Next: Make sure that this is not a duplicate element block id by searching the vblkids array. WARNING: This must be done outside of define mode because id_lkup accesses the database to determine the position */ if ((varid = ncvarid (exoid, vblkids)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate element block ids in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } blk_id_ndx = ex_id_lkup(exoid,vblkids,blk_id); if (exerrval != EX_LOOKUPFAIL) /* found the element block id */ { exerrval = EX_FATAL; sprintf(errmsg, "Error: element block id %d already exists in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Keep track of the total number of element blocks defined using a counter stored in a linked list keyed by exoid. NOTE: ex_get_file_item is a function that finds the number of element blocks for a specific file and returns that value incremented. */ cur_num_blk=ex_get_file_item(exoid, ctr_list); if (cur_num_blk >= num_blk) { exerrval = EX_FATAL; sprintf(errmsg, "Error: exceeded number of element blocks (%ld) defined in file id %d", num_blk,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* NOTE: ex_get_file_item is a function that finds the number of element blocks for a specific file and returns that value incremented. */ cur_num_blk=ex_inc_file_item(exoid, ctr_list); start[0] = (long)cur_num_blk; /* write out element block id to previously defined id array variable*/ ldum = (nclong)blk_id; if (ncvarput1 (exoid, varid, start, &ldum) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element block id to file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } blk_id_ndx = start[0]+1; /* element id index into vblkids array*/ if (num_entries_this_blk == 0) /* Is this a NULL element block? */ blk_stat = 0; /* change element block status to NULL */ else blk_stat = 1; /* change element block status to TRUE */ if ((varid = ncvarid (exoid, vblksta)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate element block status in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } ldum = (nclong)blk_stat; if (ncvarput1 (exoid, varid, start, &ldum) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element id %d status to file id %d", blk_id, exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } if (num_entries_this_blk == 0) /* Is this a NULL element block? */ { return(EX_NOERR); } /* * Check that storage required for connectivity array is less * than 2GB which is maximum size permitted by netcdf * (in large file mode). 1<<29 == max number of integer items. */ if (num_entries_this_blk * num_nodes_per_entry > (1<<29)) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Size to store connectivity for element block %d exceeds 2GB in file id %d", blk_id, exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* put netcdf file into define mode */ if (ncredef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } switch (blk_type) { case EX_EDGE_BLOCK: dneblk = DIM_NUM_ED_IN_EBLK(blk_id_ndx); dnnpe = DIM_NUM_NOD_PER_ED(blk_id_ndx); dnepe = 0; dnfpe = 0; dnape = DIM_NUM_ATT_IN_EBLK(blk_id_ndx); vblkatt = VAR_EATTRIB(blk_id_ndx); vattnam = VAR_NAME_EATTRIB(blk_id_ndx); vnodcon = VAR_EBCONN(blk_id_ndx); vedgcon = 0; vfaccon = 0; break; case EX_FACE_BLOCK: dneblk = DIM_NUM_FA_IN_FBLK(blk_id_ndx); dnnpe = DIM_NUM_NOD_PER_FA(blk_id_ndx); dnepe = 0; dnfpe = 0; dnape = DIM_NUM_ATT_IN_FBLK(blk_id_ndx); vblkatt = VAR_FATTRIB(blk_id_ndx); vattnam = VAR_NAME_FATTRIB(blk_id_ndx); vnodcon = VAR_FBCONN(blk_id_ndx); vedgcon = 0; vfaccon = 0; break; case EX_ELEM_BLOCK: dneblk = DIM_NUM_EL_IN_BLK(blk_id_ndx); dnnpe = DIM_NUM_NOD_PER_EL(blk_id_ndx); dnepe = DIM_NUM_EDG_PER_EL(blk_id_ndx); dnfpe = DIM_NUM_FAC_PER_EL(blk_id_ndx); dnape = DIM_NUM_ATT_IN_BLK(blk_id_ndx); vblkatt = VAR_ATTRIB(blk_id_ndx); vattnam = VAR_NAME_ATTRIB(blk_id_ndx); vnodcon = VAR_CONN(blk_id_ndx); vedgcon = VAR_ECONN(blk_id_ndx); vfaccon = VAR_FCONN(blk_id_ndx); break; } /* define some dimensions and variables*/ if ((numblkdim = ncdimdef (exoid,dneblk,(long)num_entries_this_blk)) == -1) { if (ncerr == NC_ENAMEINUSE) /* duplicate entry */ { exerrval = ncerr; sprintf(errmsg, "Error: element block %d already defined in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } else { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of elements/block for block %d file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } goto error_ret; /* exit define mode and return */ } if ((nnodperentdim = ncdimdef (exoid,dnnpe,(long)num_nodes_per_entry)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of nodes/element for block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ( dnepe && num_edges_per_entry > 0 ) { if ((nedgperentdim = ncdimdef (exoid,dnepe,(long)num_edges_per_entry)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of edges/element for block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if ( dnfpe && num_faces_per_entry > 0 ) { if ((nfacperentdim = ncdimdef (exoid,dnfpe,(long)num_faces_per_entry)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of faces/element for block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* element attribute array */ if (num_attr_per_entry > 0) { if ((numattrdim = ncdimdef (exoid, dnape, (long)num_attr_per_entry)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of attributes in block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } dims[0] = numblkdim; dims[1] = numattrdim; if ((ncvardef (exoid, vblkatt, nc_flt_code(exoid), 2, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define attributes for element block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* inquire previously defined dimensions */ if ((strdim = ncdimid (exoid, DIM_STR)) < 0) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } /* Attribute names... */ dims[0] = numattrdim; dims[1] = strdim; if (ncvardef (exoid, vattnam, NC_CHAR, 2, dims) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define element attribute name array in file id %d",exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* element connectivity array */ dims[0] = numblkdim; dims[1] = nnodperentdim; if ((connid = ncvardef (exoid, vnodcon, NC_LONG, 2, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create connectivity array for block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store element type as attribute of connectivity variable */ if ((ncattput (exoid, connid, ATT_NAME_ELB, NC_CHAR, strlen(entry_descrip)+1, (void*) entry_descrip)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element type name %s in file id %d", entry_descrip,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ( vedgcon && num_edges_per_entry ) { dims[0] = numblkdim; dims[1] = nedgperentdim; if ((econnid = ncvardef (exoid, vedgcon, NC_LONG, 2, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create edge connectivity array for block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if ( vfaccon && num_faces_per_entry ) { dims[0] = numblkdim; dims[1] = nfacperentdim; if ((fconnid = ncvardef (exoid, vfaccon, NC_LONG, 2, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create face connectivity array for block %d in file id %d", blk_id,exoid); ex_err("ex_put_elem_block",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* leave define mode */ if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to complete element block definition in file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (ncendef (exoid) == -1) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_elem_block",errmsg,exerrval); } return (EX_FATAL); }
int main(int argc, char **argv) { int icv, cdfid, img, max, min; static char *typenm[]={"short", "double"}; static char *boolnm[] = {"true", "false"}; static nc_type intypes[] = {NC_SHORT, NC_DOUBLE}; static int norms[] = {TRUE, FALSE}; static nc_type outtypes[] = {NC_SHORT, NC_DOUBLE}; static int maxpresent[] = {TRUE, FALSE}; static int valpresent[] = {TRUE, FALSE}; static int dim[MAX_VAR_DIMS]; static struct { long len; char *name;} diminfo[] = { { 3, MIzspace }, { 1, MIyspace }, { 1, MIxspace } }; static int numdims=sizeof(diminfo)/sizeof(diminfo[0]); static long coord[]={0,0,0}; static long count[]={1,1,1}; static double max_values[] = {0.4, 0.6, 0.8}; double dvalue; short int ivalue; int i, intype, inorm, outtype, imax, ival; int cflag = 0; char filename[256]; #if MINC2 if (argc == 2 && !strcmp(argv[1], "-2")) { cflag = MI2_CREATE_V2; } #endif /* MINC2 */ snprintf(filename, sizeof(filename), "test_icv_range-%d.mnc", getpid()); for (intype=0; intype<MAX_IN_TYPES; intype++) { for (inorm=0; inorm<MAX_NORM; inorm++) { icv=miicv_create(); miicv_setint(icv, MI_ICV_TYPE, intypes[intype]); miicv_setint(icv, MI_ICV_DO_NORM, norms[inorm]); miicv_setdbl(icv, MI_ICV_VALID_MAX, 20000.0); miicv_setdbl(icv, MI_ICV_VALID_MIN, 0.0); for (outtype=0; outtype<MAX_OUT_TYPES; outtype++) { for (imax=0; imax<MAX_MAX; imax++) { for (ival=0; ival<MAX_VAL; ival++) { printf( "in : %s, out : %s, norm : %s, imgmax : %s, valid : %s\n", typenm[intype], typenm[outtype], boolnm[inorm], boolnm[imax], boolnm[ival]); cdfid=micreate(filename, NC_CLOBBER | cflag); for (i=0; i<numdims; i++) dim[i]=ncdimdef(cdfid, diminfo[i].name, diminfo[i].len); img=micreate_std_variable(cdfid, MIimage, outtypes[outtype], numdims, dim); if (maxpresent[imax]) { max=micreate_std_variable(cdfid, MIimagemax, NC_DOUBLE, 1, dim); min=micreate_std_variable(cdfid, MIimagemin, NC_DOUBLE, 1, dim); } if (valpresent[ival]) { dvalue = 32000; ncattput(cdfid, img, MIvalid_max, NC_DOUBLE, 1, &dvalue); dvalue = 0; ncattput(cdfid, img, MIvalid_min, NC_DOUBLE, 1, &dvalue); } ncendef(cdfid); if (maxpresent[imax]) { for (i=0; i<3; i++) { dvalue = max_values[i]; coord[0]=i; ncvarput1(cdfid, max, coord, &dvalue); dvalue = -dvalue; ncvarput1(cdfid, min, coord, &dvalue); } coord[0]=0; } miicv_attach(icv, cdfid, img); if (intypes[intype]==NC_DOUBLE) { dvalue = 0.2; miicv_put(icv, coord, count, &dvalue); } else { ivalue = 12500; miicv_put(icv, coord, count, &ivalue); } dvalue = 0; mivarget1(cdfid, img, coord, NC_DOUBLE, MI_SIGNED, &dvalue); printf(" file value = %g\n", dvalue); if (intypes[intype]==NC_DOUBLE) { miicv_get(icv, coord, count, &dvalue); } else { miicv_get(icv, coord, count, &ivalue); dvalue=ivalue; } printf(" icv value = %g\n", dvalue); miclose(cdfid); } } } miicv_free(icv); } } unlink(filename); return 0; }
int ex_create (const char *path, int cmode, int *comp_ws, int *io_ws) { int exoid, time_dim, dims[1]; nclong lio_ws; nclong filesiz; float vers; char errmsg[MAX_ERR_LENGTH]; char *mode_name; int mode = 0; exerrval = 0; /* clear error code */ /* * See if "large file" mode was specified in a ex_create cmode. If * so, then pass the NC_64BIT_OFFSET flag down to netcdf. */ if (cmode & EX_LARGE_MODEL || ex_large_model(-1) == 1) { mode |= NC_64BIT_OFFSET; } /* * set error handling mode to no messages, non-fatal errors */ ex_opts(exoptval); /* call required to set ncopts first time through */ if (cmode & EX_NOCLOBBER) { mode |= NC_NOCLOBBER; mode_name = "NOCLOBBER"; } else if (cmode & EX_CLOBBER) { mode |= NC_CLOBBER; mode_name = "CLOBBER"; } else { exerrval = EX_BADFILEMODE; sprintf(errmsg,"Error: invalid file create mode: %d, for file %s", cmode,path); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } #ifndef TFLOP mode |= NC_SHARE; #endif if ((exoid = nccreate (path, mode)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: file create failed for %s, mode: %s", path, mode_name); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } /* turn off automatic filling of netCDF variables */ if (ncsetfill (exoid, NC_NOFILL) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to set nofill mode in file id %d", exoid); ex_err("ex_create", errmsg, exerrval); return (EX_FATAL); } /* initialize floating point size conversion. since creating new file, * i/o wordsize attribute from file is zero. */ if (ex_conv_ini( exoid, comp_ws, io_ws, 0 ) != EX_NOERR) { exerrval = EX_FATAL; sprintf(errmsg, "Error: failed to init conversion routines in file id %d", exoid); ex_err("ex_create", errmsg, exerrval); return (EX_FATAL); } /* put the EXODUS version number, and i/o floating point word size as * netcdf global attributes */ /* store Exodus API version # as an attribute */ vers = (float)(EX_API_VERS); if (ncattput (exoid, NC_GLOBAL, ATT_API_VERSION, NC_FLOAT, 1, &vers) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store Exodus II API version attribute in file id %d", exoid); ex_err("ex_create",errmsg, exerrval); return (EX_FATAL); } /* store Exodus file version # as an attribute */ vers = (float)(EX_VERS); if (ncattput (exoid, NC_GLOBAL, ATT_VERSION, NC_FLOAT, 1, &vers) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store Exodus II file version attribute in file id %d", exoid); ex_err("ex_create",errmsg, exerrval); return (EX_FATAL); } /* store Exodus file float word size as an attribute */ lio_ws = (nclong)(*io_ws); if (ncattput (exoid, NC_GLOBAL, ATT_FLT_WORDSIZE, NC_LONG, 1, &lio_ws) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store Exodus II file float word size attribute in file id %d", exoid); ex_err("ex_create",errmsg, exerrval); return (EX_FATAL); } /* store Exodus file size (1=large, 0=normal) as an attribute */ filesiz = (nclong)(((cmode & EX_LARGE_MODEL) != 0) || (ex_large_model(-1) == 1)); if (ncattput (exoid, NC_GLOBAL, ATT_FILESIZE, NC_LONG, 1, &filesiz) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store Exodus II file size attribute in file id %d", exoid); ex_err("ex_create",errmsg, exerrval); return (EX_FATAL); } /* define some dimensions and variables */ /* create string length dimension */ if (ncdimdef (exoid, DIM_STR, (MAX_STR_LENGTH+1)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define string length in file id %d",exoid); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } /* create line length dimension */ if (ncdimdef (exoid, DIM_LIN, (MAX_LINE_LENGTH+1)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define line length in file id %d",exoid); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } /* create number "4" dimension; must be of type long */ if (ncdimdef (exoid, DIM_N4, 4L) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number \"4\" dimension in file id %d",exoid); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } if ((time_dim = ncdimdef (exoid, DIM_TIME, NC_UNLIMITED)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define time dimension in file id %d", exoid); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } dims[0] = time_dim; if ((ncvardef (exoid, VAR_WHOLE_TIME, nc_flt_code(exoid), 1, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define whole time step variable in file id %d", exoid); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_create",errmsg,exerrval); return (EX_FATAL); } return (exoid); }
int main(int argc, char **argv) { int ncid, dimids[NUM_DIMS]; int varid; int nvars_in, varids_in[NUM_DIMS]; signed char fill_value = 42, fill_value_in; nc_type xtype_in; size_t len_in; char name_in[NC_MAX_NAME + 1]; int attnum_in; int cnum; #ifdef USE_PARALLEL MPI_Init(&argc, &argv); #endif printf("\n*** Testing netcdf-4 variable functions, even more.\n"); for (cnum = 0; cnum < MAX_CNUM; cnum++) { int cmode; switch(cnum) { case 0: printf("*** Testing with classic format:\n"); cmode = 0; break; case 1: printf("*** Testing with 64-bit offset format:\n"); cmode = NC_64BIT_OFFSET; break; case 2: printf("*** Testing with HDF5:\n"); cmode = NC_NETCDF4|NC_CLOBBER; break; case 3: printf("*** Testing with HDF5, netCDF Classic Model:\n"); cmode = NC_CLASSIC_MODEL | NC_NETCDF4; } printf("**** testing simple fill value attribute creation..."); { /* Create a netcdf-4 file with one scalar var. Add fill * value. */ if (nc_create(FILE_NAME, cmode, &ncid)) ERR; if (nc_def_var(ncid, VAR_NAME, NC_BYTE, 0, NULL, &varid)) ERR; if (nc_enddef(ncid)) ERR; if (nc_redef(ncid)) ERR; if (nc_put_att_schar(ncid, varid, _FillValue, NC_BYTE, 1, &fill_value)) ERR; if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR; if (nvars_in != 1 || varids_in[0] != 0) ERR; if (nc_inq_varname(ncid, 0, name_in)) ERR; if (strcmp(name_in, VAR_NAME)) ERR; if (nc_inq_att(ncid, varid, _FillValue, &xtype_in, &len_in)) ERR; if (xtype_in != NC_BYTE || len_in != 1) ERR; if (nc_get_att(ncid, varid, _FillValue, &fill_value_in)) ERR; if (fill_value_in != fill_value) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing simple fill value with data read..."); { size_t start[NUM_DIMS], count[NUM_DIMS]; signed char data = 99, data_in; /* Create a netcdf-4 file with one unlimited dim and one * var. Add fill value. */ if (nc_create(FILE_NAME, cmode, &ncid)) ERR; if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR; if (nc_def_var(ncid, VAR_NAME, NC_BYTE, NUM_DIMS, dimids, &varid)) ERR; if (nc_enddef(ncid)) ERR; if (nc_redef(ncid)) ERR; if (nc_put_att_schar(ncid, varid, _FillValue, NC_BYTE, 1, &fill_value)) ERR; if (nc_enddef(ncid)) ERR; /* Write the second record. */ start[0] = 1; count[0] = 1; if (nc_put_vara_schar(ncid, varid, start, count, &data)) ERR; /* Read the first record, it should be the fill value. */ start[0] = 0; if (nc_get_vara_schar(ncid, varid, start, count, &data_in)) ERR; if (data_in != fill_value) ERR; /* Read the second record, it should be the value we just wrote * there. */ start[0] = 1; if (nc_get_vara_schar(ncid, varid, start, count, &data_in)) ERR; if (data_in != data) ERR; /* Close up. */ if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; /* Check metadata. */ if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR; if (nvars_in != 1 || varids_in[0] != 0) ERR; if (nc_inq_varname(ncid, 0, name_in)) ERR; if (strcmp(name_in, VAR_NAME)) ERR; /* Check fill value att. */ if (nc_inq_att(ncid, varid, _FillValue, &xtype_in, &len_in)) ERR; if (xtype_in != NC_BYTE || len_in != 1) ERR; if (nc_get_att(ncid, varid, _FillValue, &fill_value_in)) ERR; if (fill_value_in != fill_value) ERR; /* Read the first record, it should be the fill value. */ start[0] = 0; if (nc_get_vara_schar(ncid, varid, start, count, &data_in)) ERR; if (data_in != fill_value) ERR; /* Read the second record, it should be the value we just wrote * there. */ start[0] = 1; if (nc_get_vara_schar(ncid, varid, start, count, &data_in)) ERR; if (data_in != data) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing fill value with one other attribute..."); { int losses_value = 192, losses_value_in; /* Create a netcdf-4 file with one dim and one var. Add another * attribute, then fill value. */ if (nc_create(FILE_NAME, cmode, &ncid)) ERR; if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR; if (nc_def_var(ncid, VAR_NAME, NC_BYTE, NUM_DIMS, dimids, &varid)) ERR; if (nc_put_att_int(ncid, varid, LOSSES_NAME, NC_INT, 1, &losses_value)) ERR; if (nc_put_att_schar(ncid, varid, _FillValue, NC_BYTE, 1, &fill_value)) ERR; if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; if (nc_inq_att(ncid, 0, LOSSES_NAME, &xtype_in, &len_in)) ERR; if (xtype_in != NC_INT || len_in != 1) ERR; if (nc_get_att(ncid, 0, LOSSES_NAME, &losses_value_in)) ERR; if (losses_value_in != losses_value) ERR; if (nc_inq_att(ncid, 0, _FillValue, &xtype_in, &len_in)) ERR; if (xtype_in != NC_BYTE || len_in != 1) ERR; if (nc_get_att(ncid, 0, _FillValue, &fill_value_in)) ERR; if (fill_value_in != fill_value) ERR; if (nc_inq_attid(ncid, 0, LOSSES_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, _FillValue, &attnum_in)) ERR; if (attnum_in != 1) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing fill value with three other attributes..."); { #define NUM_LEADERS 3 char leader[NUM_LEADERS][NC_MAX_NAME + 1] = {"hair_length_of_strategoi", "hair_length_of_Miltiades", "hair_length_of_Darius_I"}; short hair_length[NUM_LEADERS] = {3, 11, 4}; short short_in; int a; /* Create a netcdf file with one dim and one var. Add 3 * attributes, then fill value. */ if (nc_create(FILE_NAME, cmode, &ncid)) ERR; if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimids[0])) ERR; if (nc_def_var(ncid, VAR_NAME, NC_BYTE, NUM_DIMS, dimids, &varid)) ERR; for (a = 0; a < NUM_LEADERS; a++) if (nc_put_att_short(ncid, varid, leader[a], NC_SHORT, 1, &hair_length[a])) ERR; if (nc_put_att_schar(ncid, varid, _FillValue, NC_BYTE, 1, &fill_value)) ERR; if (nc_close(ncid)) ERR; /* Open the file. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; /* Check our three hair-related attributes. */ for (a = 0; a < NUM_LEADERS; a++) { if (nc_inq_att(ncid, 0, leader[a], &xtype_in, &len_in)) ERR; if (xtype_in != NC_SHORT || len_in != 1) ERR; if (nc_get_att(ncid, 0, leader[a], &short_in)) ERR; if (short_in != hair_length[a]) ERR; if (nc_inq_attid(ncid, 0, leader[a], &attnum_in)) ERR; if (attnum_in != a) ERR; } /* Check our fill value attribute. */ if (nc_inq_att(ncid, 0, _FillValue, &xtype_in, &len_in)) ERR; if (xtype_in != NC_BYTE || len_in != 1) ERR; if (nc_get_att(ncid, 0, _FillValue, &fill_value_in)) ERR; if (fill_value_in != fill_value) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing fill value with simple example..."); { /* Dims stuff. */ #define NDIMS 3 #define VAR_DIMS 3 #define DIM_A "dim1" #define DIM_A_LEN 4 #define DIM_B "dim2" #define DIM_B_LEN 3 #define DIM_C "dim3" #define DIM_C_LEN NC_UNLIMITED /* Var stuff. */ #define CXX_VAR_NAME "P" /* Att stuff. */ #define NUM_ATTS 4 #define LONG_NAME "long_name" #define PRES_MAX_WIND "pressure at maximum wind" #define UNITS "units" #define HECTOPASCALS "hectopascals" int dimid[NDIMS], var_dimids[VAR_DIMS] = {2, 1, 0}; float fill_value = -9999.0f; char long_name[] = PRES_MAX_WIND; if (nc_create(FILE_NAME, cmode, &ncid)) ERR; /* Create dims. */ if (nc_def_dim(ncid, DIM_A, DIM_A_LEN, &dimid[0])) ERR; if (nc_def_dim (ncid, DIM_B, DIM_B_LEN, &dimid[1])) ERR; if (nc_def_dim(ncid, DIM_C, DIM_C_LEN, &dimid[2])) ERR; /* Create var. */ if (nc_def_var(ncid, CXX_VAR_NAME, NC_FLOAT, VAR_DIMS, var_dimids, &varid)) ERR; if (varid) ERR; if (nc_put_att(ncid, varid, LONG_NAME, NC_CHAR, strlen(long_name) + 1, long_name)) ERR; if (nc_put_att(ncid, varid, UNITS, NC_CHAR, strlen(UNITS) + 1, UNITS)) ERR; /* Check to ensure the atts have their expected attnums. */ if (nc_inq_attid(ncid, 0, LONG_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, UNITS, &attnum_in)) ERR; if (attnum_in != 1) ERR; /* Now add a fill value. This will acutually cause HDF5 to * destroy the dataset and recreate it, recreating also the * three attributes that are attached to it. */ if (nc_put_att(ncid, varid, _FillValue, NC_FLOAT, 1, &fill_value)) ERR; /* Check to ensure the atts have their expected attnums. */ if (nc_inq_attid(ncid, 0, LONG_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, UNITS, &attnum_in)) ERR; if (attnum_in != 1) ERR; if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, 0, &ncid)) ERR; if (nc_inq_attid(ncid, 0, LONG_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, UNITS, &attnum_in)) ERR; if (attnum_in != 1) ERR; if (nc_inq_attid(ncid, 0, _FillValue, &attnum_in)) ERR; if (attnum_in != 2) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; #ifndef NO_NETCDF_2 /* The following test is an attempt to recreate a problem occuring in the cxx tests. The file is created in c++ in nctsts.cpp. */ printf("**** testing fill value with example from cxx tests in v2 api..."); { /* Dims stuff. */ #define NDIMS_1 4 #define VAR_DIMS 3 #define LAT "lat" #define LAT_LEN 4 #define LON "lon" #define LON_LEN 3 #define FRTIMED "frtimed" #define FRTIMED_LEN NC_UNLIMITED #define TIMELEN "timelen" #define TIMELEN_LEN 20 /* Var stuff. */ #define CXX_VAR_NAME "P" /* Att stuff. */ #define NUM_ATTS 4 #define LONG_NAME "long_name" #define UNITS "units" int dimid[NDIMS_1], var_dimids[VAR_DIMS] = {2, 0, 1}; float fill_value = -9999.0f; char long_name[] = PRES_MAX_WIND; int i, attid[NUM_ATTS]; ncid = nccreate(FILE_NAME, NC_NETCDF4); /* Create dims. */ dimid[0] = ncdimdef(ncid, LAT, LAT_LEN); dimid[1] = ncdimdef(ncid, LON, LON_LEN); dimid[2] = ncdimdef(ncid, FRTIMED, FRTIMED_LEN); dimid[3] = ncdimdef(ncid, TIMELEN, TIMELEN_LEN); /* Just check our dimids to see that they are correct. */ for (i = 0; i < NDIMS_1; i++) if (dimid[i] != i) ERR; /* Create var. */ varid = ncvardef(ncid, CXX_VAR_NAME, NC_FLOAT, VAR_DIMS, var_dimids); if (varid) ERR; /* Add three atts to the var, long_name, units, and * valid_range. */ if (nc_put_att(ncid, varid, LONG_NAME, NC_CHAR, strlen(long_name) + 1, long_name)) ERR; if (nc_put_att(ncid, varid, UNITS, NC_CHAR, strlen(UNITS) + 1, UNITS)) ERR; /* Check to ensure the atts have their expected attnums. */ if (nc_inq_attid(ncid, 0, LONG_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, UNITS, &attnum_in)) ERR; if (attnum_in != 1) ERR; /* Now add a fill value. This will acutually cause HDF5 to * destroy the dataset and recreate it, recreating also the * three attributes that are attached to it. */ attid[3] = ncattput(ncid, varid, _FillValue, NC_FLOAT, 1, &fill_value); /* Check to ensure the atts have their expected attnums. */ if (nc_inq_attid(ncid, 0, LONG_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, UNITS, &attnum_in)) ERR; if (attnum_in != 1) ERR; ncclose(ncid); /* Open the file and check. */ ncid = ncopen(FILE_NAME, 0); if (nc_inq_attid(ncid, 0, LONG_NAME, &attnum_in)) ERR; if (attnum_in != 0) ERR; if (nc_inq_attid(ncid, 0, UNITS, &attnum_in)) ERR; if (attnum_in != 1) ERR; if (nc_inq_attid(ncid, 0, _FillValue, &attnum_in)) ERR; if (attnum_in != 2) ERR; ncclose(ncid); } SUMMARIZE_ERR; #endif /* NO_NETCDF_2 */ } printf("**** testing create order varids..."); #define UNITS "units" #define DIMNAME "x" #define VARNAME "data" { /* This test contributed by Jeff Whitaker of NOAA - Thanks Jeff! */ int ncid, dimid, varid, xvarid; char units[] = "zlotys"; if (nc_create(FILE_NAME, NC_NETCDF4|NC_CLASSIC_MODEL, &ncid)) ERR; if (nc_def_dim(ncid, DIMNAME, 1, &dimid)) ERR; if (nc_enddef(ncid)) ERR; if (nc_redef(ncid)) ERR; if (nc_def_var(ncid, DIMNAME, NC_INT, 1, &dimid, &xvarid)) ERR; if (nc_put_att_text(ncid, xvarid, UNITS, strlen(units), units)) ERR; if (nc_def_var(ncid, VARNAME, NC_INT, 1, &dimid, &varid)) ERR; if (nc_close(ncid)) ERR; if (nc_open(FILE_NAME, 0, &ncid)) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; #define RANK_wind 1 printf("**** testing simple variable renaming..."); { /* This test contributed by Jeff Whitaker of NOAA - Thanks Jeff! */ int ncid, lat_dim, time_dim, lon_dim, wind_id; size_t lat_len = 73, time_len = 10, lon_len = 145; int cdf_goober[1]; /* if (nc_set_default_format(NC_FORMAT_NETCDF4, NULL)) ERR;*/ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; /* define dimensions */ if (nc_def_dim(ncid, "a", lon_len, &lon_dim)) ERR; if (nc_def_dim(ncid, "b", lat_len, &lat_dim)) ERR; if (nc_def_dim(ncid, "c", time_len, &time_dim)) ERR; if (nc_put_att_text(ncid, NC_GLOBAL, "a", 3, "bar")) ERR; cdf_goober[0] = 2; if (nc_put_att_int(ncid, NC_GLOBAL, "b", NC_INT, 1, cdf_goober)) ERR; /* define variables */ if (nc_def_var(ncid, "aa", NC_FLOAT, RANK_wind, &lon_dim, &wind_id)) ERR; if (nc_close(ncid)) ERR; if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; if (nc_rename_var(ncid, 0, "az")) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing dimension and variable renaming..."); { /* This test contributed by Jeff Whitaker of NOAA - Thanks Jeff! */ int ncid, lat_dim, time_dim, lon_dim, wind_id; size_t lat_len = 73, time_len = 10, lon_len = 145; int wind_dims[RANK_wind], wind_slobber[1], cdf_goober[1]; if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; /* define dimensions */ if (nc_def_dim(ncid, "lon", lon_len, &lon_dim)) ERR; if (nc_def_dim(ncid, "lat", lat_len, &lat_dim)) ERR; if (nc_def_dim(ncid, "time", time_len, &time_dim)) ERR; if (nc_put_att_text(ncid, NC_GLOBAL, "foo", 3, "bar")) ERR; cdf_goober[0] = 2; if (nc_put_att_int(ncid, NC_GLOBAL, "goober", NC_INT, 1, cdf_goober)) ERR; /* define variables */ wind_dims[0] = lon_dim; if (nc_def_var(ncid, "temp", NC_FLOAT, RANK_wind, wind_dims, &wind_id)) ERR; if (nc_put_att_text(ncid, wind_id, "bar", 3, "foo")) ERR; wind_slobber[0] = 3; if (nc_put_att_int(ncid, wind_id, "slobber", NC_INT, 1, wind_slobber)) ERR; if (nc_close(ncid)) ERR; /* re-open dataset*/ if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; if (nc_inq_dimid(ncid, "lon", &lon_dim)) ERR; /* rename dimension */ if (nc_rename_dim(ncid, lon_dim, "longitude")) ERR; if (nc_inq_varid(ncid, "temp", &wind_id)) ERR; /* rename variable */ if (nc_rename_var(ncid, wind_id, "wind")) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; /* printf("*** testing 2D array of NC_CHAR..."); */ /* { */ /* int dimid[NDIMS_1], var_dimids[VAR_DIMS] = {2, 0, 1}; */ /* float fill_value = -9999.0f; */ /* char long_name[] = PRES_MAX_WIND; */ /* int i, attid[NUM_ATTS]; */ /* ncid = nccreate(FILE_NAME, NC_NETCDF4); */ /* /\* Create dims. *\/ */ /* dimid[0] = ncdimdef(ncid, LAT, LAT_LEN); */ /* dimid[1] = ncdimdef(ncid, LON, LON_LEN); */ /* /\* Create var. *\/ */ /* varid = ncvardef(ncid, CXX_VAR_NAME, NC_FLOAT, VAR_DIMS, var_dimids); */ /* if (varid) ERR; */ /* ncclose(ncid); */ /* /\* Open the file and check. *\/ */ /* ncid = ncopen(FILE_NAME, 0); */ /* ncclose(ncid); */ /* } */ /* SUMMARIZE_ERR; */ #define NDIMS 3 #define NNAMES 4 #define NLINES 13 /* printf("**** testing funny names for netCDF-4..."); */ /* { */ /* int ncid, wind_id; */ /* size_t len[NDIMS] = {7, 3, 1}; */ /* int dimids[NDIMS], dimids_in[NDIMS], ndims_in; */ /* char funny_name[NNAMES][NC_MAX_NAME] = {"\a\t", "\f\n", "\r\v", "\b"}; */ /* char name_in[NC_MAX_NAME + 1]; */ /* char *speech[NLINES] = {"who would fardels bear, ", */ /* "To grunt and sweat under a weary life, ", */ /* "But that the dread of something after death, ", */ /* "The undiscover'd country from whose bourn ", */ /* "No traveller returns, puzzles the will ", */ /* "And makes us rather bear those ills we have ", */ /* "Than fly to others that we know not of? ", */ /* "Thus conscience does make cowards of us all; ", */ /* "And thus the native hue of resolution ", */ /* "Is sicklied o'er with the pale cast of thought, ", */ /* "And enterprises of great pith and moment ", */ /* "With this regard their currents turn awry, ", */ /* "And lose the name of action."}; */ /* char *speech_in[NLINES]; */ /* int i; */ /* unsigned short nlines = NLINES; */ /* unsigned int nlines_in; */ /* if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; */ /* /\* Define dimensions. *\/ */ /* for (i = 0; i < NDIMS; i++) */ /* if (nc_def_dim(ncid, funny_name[i], len[i], &dimids[i])) ERR; */ /* /\* Write some global atts. *\/ */ /* if (nc_put_att_string(ncid, NC_GLOBAL, funny_name[0], NLINES, */ /* (const char **)speech)) ERR; */ /* if (nc_put_att_ushort(ncid, NC_GLOBAL, funny_name[1], NC_UINT, 1, &nlines)) ERR; */ /* /\* Define variables. *\/ */ /* if (nc_def_var(ncid, funny_name[3], NC_INT64, NDIMS, dimids, &wind_id)) ERR; */ /* if (nc_close(ncid)) ERR; */ /* /\* Open the file and check. *\/ */ /* if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; */ /* if (nc_inq_dimids(ncid, &ndims_in, dimids_in, 0)) ERR; */ /* if (ndims_in != NDIMS) ERR; */ /* for (i = 0; i < NDIMS; i++) */ /* { */ /* if (dimids_in[i] != i) ERR; */ /* if (nc_inq_dimname(ncid, i, name_in)) ERR; */ /* if (strcmp(name_in, funny_name[i])) ERR; */ /* } */ /* if (nc_get_att_string(ncid, NC_GLOBAL, funny_name[0], (char **)speech_in)) ERR; */ /* for (i = 0; i < NLINES; i++) */ /* if (strcmp(speech_in[i], speech[i])) ERR; */ /* if (nc_get_att_uint(ncid, NC_GLOBAL, funny_name[1], &nlines_in)) ERR; */ /* if (nlines_in != NLINES) ERR; */ /* if (nc_free_string(NLINES, (char **)speech_in)) ERR; */ /* if (nc_inq_varname(ncid, 0, name_in)) ERR; */ /* if (strcmp(name_in, funny_name[3])) ERR; */ /* if (nc_close(ncid)) ERR; */ /* } */ /* SUMMARIZE_ERR; */ printf("**** testing endianness..."); #define NDIMS4 1 #define DIM4_NAME "Joe" #define VAR_NAME4 "Ed" #define DIM4_LEN 10 { int dimids[NDIMS4], dimids_in[NDIMS4]; int varid; int ndims, nvars, natts, unlimdimid; nc_type xtype_in; char name_in[NC_MAX_NAME + 1]; int data[DIM4_LEN], data_in[DIM4_LEN]; int endian_in; int i; for (i = 0; i < DIM4_LEN; i++) data[i] = i; /* Create a netcdf-4 file with one dim and one var. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_dim(ncid, DIM4_NAME, DIM4_LEN, &dimids[0])) ERR; if (dimids[0] != 0) ERR; if (nc_def_var(ncid, VAR_NAME4, NC_INT, NDIMS4, dimids, &varid)) ERR; if (nc_def_var_endian(ncid, varid, NC_ENDIAN_BIG)) ERR; if (varid != 0) ERR; if (nc_put_var_int(ncid, varid, data)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS4 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME4) || xtype_in != NC_INT || ndims != 1 || natts != 0 || dimids_in[0] != 0) ERR; if (nc_inq_var_endian(ncid, 0, &endian_in)) ERR; if (endian_in != NC_ENDIAN_BIG) ERR; if (nc_close(ncid)) ERR; /* Open the file and check the same stuff. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS4 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME4) || xtype_in != NC_INT || ndims != 1 || natts != 0 || dimids_in[0] != 0) ERR; if (nc_inq_var_endian(ncid, 0, &endian_in)) ERR; if (endian_in != NC_ENDIAN_BIG) ERR; if (nc_get_var_int(ncid, varid, data_in)) ERR; for (i = 0; i < DIM4_LEN; i++) if (data[i] != data_in[i]) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing chunking..."); { #define NDIMS5 1 #define DIM5_NAME "D5" #define VAR_NAME5 "V5" #define DIM5_LEN 1000 int dimids[NDIMS5], dimids_in[NDIMS5]; int varid; int ndims, nvars, natts, unlimdimid; nc_type xtype_in; char name_in[NC_MAX_NAME + 1]; int data[DIM5_LEN], data_in[DIM5_LEN]; int chunksize[NDIMS5] = {5}; int chunksize_in[NDIMS5]; int contiguous_in; int i, d; for (i = 0; i < DIM5_LEN; i++) data[i] = i; /* Create a netcdf-4 file with one dim and one var. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_dim(ncid, DIM5_NAME, DIM5_LEN, &dimids[0])) ERR; if (dimids[0] != 0) ERR; if (nc_def_var(ncid, VAR_NAME5, NC_INT, NDIMS5, dimids, &varid)) ERR; if (nc_def_var_chunking(ncid, varid, 0, chunksize)) ERR; if (nc_put_var_int(ncid, varid, data)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS5 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME5) || xtype_in != NC_INT || ndims != 1 || natts != 0 || dimids_in[0] != 0) ERR; if (nc_inq_var_chunking(ncid, 0, &contiguous_in, chunksize_in)) ERR; for (d = 0; d < NDIMS5; d++) if (chunksize[d] != chunksize_in[d]) ERR; if (contiguous_in != 0) ERR; if (nc_get_var_int(ncid, varid, data_in)) ERR; for (i = 0; i < DIM5_LEN; i++) if (data[i] != data_in[i]) ERR_RET; if (nc_close(ncid)) ERR; /* Open the file and check the same stuff. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS5 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME5) || xtype_in != NC_INT || ndims != 1 || natts != 0 || dimids_in[0] != 0) ERR; if (nc_inq_var_chunking(ncid, 0, &contiguous_in, chunksize_in)) ERR; for (d = 0; d < NDIMS5; d++) if (chunksize[d] != chunksize_in[d]) ERR; if (contiguous_in != 0) ERR; if (nc_get_var_int(ncid, varid, data_in)) ERR; for (i = 0; i < DIM5_LEN; i++) if (data[i] != data_in[i]) ERR_RET; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing contiguous storage..."); { #define NDIMS6 1 #define DIM6_NAME "D5" #define VAR_NAME6 "V5" #define DIM6_LEN 100 int dimids[NDIMS6], dimids_in[NDIMS6]; int varid; int ndims, nvars, natts, unlimdimid; nc_type xtype_in; char name_in[NC_MAX_NAME + 1]; int data[DIM6_LEN], data_in[DIM6_LEN]; int chunksize_in[NDIMS6]; int contiguous_in; int i, d; for (i = 0; i < DIM6_LEN; i++) data[i] = i; /* Create a netcdf-4 file with one dim and one var. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_dim(ncid, DIM6_NAME, DIM6_LEN, &dimids[0])) ERR; if (dimids[0] != 0) ERR; if (nc_def_var(ncid, VAR_NAME6, NC_INT, NDIMS6, dimids, &varid)) ERR; if (nc_def_var_chunking(ncid, varid, 1, NULL)) ERR; if (nc_put_var_int(ncid, varid, data)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS6 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME6) || xtype_in != NC_INT || ndims != 1 || natts != 0 || dimids_in[0] != 0) ERR; if (nc_inq_var_chunking(ncid, 0, &contiguous_in, chunksize_in)) ERR; for (d = 0; d < NDIMS6; d++) if (chunksize_in[d] != 0) ERR; if (!contiguous_in) ERR; if (nc_get_var_int(ncid, varid, data_in)) ERR; for (i = 0; i < DIM6_LEN; i++) if (data_in[i] != data[i]) ERR_RET; if (nc_close(ncid)) ERR; /* Open the file and check the same stuff. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS6 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME6) || xtype_in != NC_INT || ndims != 1 || natts != 0 || dimids_in[0] != 0) ERR; if (nc_inq_var_chunking(ncid, 0, &contiguous_in, chunksize_in)) ERR; for (d = 0; d < NDIMS6; d++) if (chunksize_in[d] != 0) ERR; if (!contiguous_in) ERR; if (nc_get_var_int(ncid, varid, data_in)) ERR; for (i = 0; i < DIM6_LEN; i++) if (data[i] != data_in[i]) ERR_RET; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing extreme numbers dude..."); { #define VAR_NAME7 "V5" #define DIM6_LEN 100 int varid; int ndims, nvars, natts, unlimdimid; nc_type xtype_in; char name_in[NC_MAX_NAME + 1]; /* unsigned long long data = 9223372036854775807ull, data_in;*/ unsigned long long data = 9223372036854775817ull, data_in; /* Create a netcdf-4 file with scalar var. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_var(ncid, VAR_NAME7, NC_UINT64, 0, NULL, &varid)) ERR; if (nc_put_var_ulonglong(ncid, varid, &data)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != 0 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1 || varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, NULL, &natts)) ERR; if (strcmp(name_in, VAR_NAME7) || xtype_in != NC_UINT64 || ndims != 0 || natts != 0) ERR; if (nc_get_var_ulonglong(ncid, varid, &data_in)) ERR; if (data_in != data) ERR; if (nc_close(ncid)) ERR; /* Open the file and check the same stuff. */ 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_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1 || varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, NULL, &natts)) ERR; if (strcmp(name_in, VAR_NAME7) || xtype_in != NC_UINT64 || ndims != 0 || natts != 0) ERR; if (nc_get_var_ulonglong(ncid, varid, &data_in)) ERR; if (data_in != data) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing error codes for name clashes..."); { #define GENERIC_NAME "bob" int ncid, varid, numgrps, ntypes; /* Create a netcdf-4 file with one var. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_var(ncid, GENERIC_NAME, NC_BYTE, 0, NULL, &varid)) ERR; /* These don'e work, becuase the name is already in use. Make * sure the correct error is returned. */ if (nc_def_grp(ncid, GENERIC_NAME, NULL) != NC_ENAMEINUSE) ERR; if (nc_def_opaque(ncid, 1, GENERIC_NAME, NULL) != NC_ENAMEINUSE) ERR; /* Close it. */ if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR; if (nvars_in != 1 || varids_in[0] != 0) ERR; if (nc_inq_varname(ncid, 0, name_in)) ERR; if (strcmp(name_in, GENERIC_NAME)) ERR; if (nc_inq_grps(ncid, &numgrps, NULL)) ERR; if (numgrps) ERR; if (nc_inq_typeids(ncid, &ntypes, NULL)) ERR; if (ntypes) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing error codes for name clashes some more..."); { #define GENERIC_NAME "bob" int ncid, varid, numgrps, ntypes; /* Create a netcdf-4 file with one type. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_opaque(ncid, 1, GENERIC_NAME, NULL)) ERR; /* These don'e work, becuase the name is already in use. Make * sure the correct error is returned. */ if (nc_def_grp(ncid, GENERIC_NAME, NULL) != NC_ENAMEINUSE) ERR; if (nc_def_var(ncid, GENERIC_NAME, NC_BYTE, 0, NULL, &varid) != NC_ENAMEINUSE) ERR; /* Close it. */ if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR; if (nvars_in) ERR; if (nc_inq_grps(ncid, &numgrps, NULL)) ERR; if (numgrps) ERR; if (nc_inq_typeids(ncid, &ntypes, NULL)) ERR; if (ntypes != 1) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing error codes for name clashes even more..."); { #define GENERIC_NAME "bob" int ncid, varid, numgrps, ntypes; /* Create a netcdf-4 file with one group. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_grp(ncid, GENERIC_NAME, NULL)) ERR; /* These don'e work, becuase the name is already in use. Make * sure the correct error is returned. */ if (nc_def_opaque(ncid, 1, GENERIC_NAME, NULL) != NC_ENAMEINUSE) ERR; if (nc_def_var(ncid, GENERIC_NAME, NC_BYTE, 0, NULL, &varid) != NC_ENAMEINUSE) ERR; /* Close it. */ if (nc_close(ncid)) ERR; /* Open the file and check. */ if (nc_open(FILE_NAME, NC_WRITE, &ncid)) ERR; if (nc_inq_varids(ncid, &nvars_in, varids_in)) ERR; if (nvars_in) ERR; if (nc_inq_grps(ncid, &numgrps, NULL)) ERR; if (numgrps != 1) ERR; if (nc_inq_typeids(ncid, &ntypes, NULL)) ERR; if (ntypes) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; printf("**** testing error code for too-large chunks..."); { #define NDIMS17 2 #define DIM17_NAME "personality" #define DIM17_NAME_2 "good_looks" #define VAR_NAME17 "ed" #define DIM17_LEN 2147483644 /* max dimension size - 2GB - 4. */ #define DIM17_2_LEN 1000 int dimids[NDIMS17], dimids_in[NDIMS17]; int varid; int ndims, nvars, natts, unlimdimid; nc_type xtype_in; char name_in[NC_MAX_NAME + 1]; int chunksize[NDIMS17] = {5, 5}; int bad_chunksize[NDIMS17] = {5, DIM17_LEN}; int chunksize_in[NDIMS17]; int contiguous_in; int d; /* Create a netcdf-4 file with two dims and one var. */ if (nc_create(FILE_NAME, NC_NETCDF4, &ncid)) ERR; if (nc_def_dim(ncid, DIM17_NAME, DIM17_LEN, &dimids[0])) ERR; if (nc_def_dim(ncid, DIM17_NAME_2, DIM17_2_LEN, &dimids[1])) ERR; if (dimids[0] != 0 || dimids[1] != 1) ERR; if (nc_def_var(ncid, VAR_NAME17, NC_UINT64, NDIMS17, dimids, &varid)) ERR; if (nc_def_var_chunking(ncid, varid, 0, bad_chunksize) != NC_EBADCHUNK) ERR; if (nc_def_var_chunking(ncid, varid, 0, chunksize)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS17 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME17) || xtype_in != NC_UINT64 || ndims != 2 || natts != 0 || dimids_in[0] != 0 || dimids_in[1] != 1) ERR; if (nc_inq_var_chunking(ncid, 0, &contiguous_in, chunksize_in)) ERR; for (d = 0; d < NDIMS17; d++) if (chunksize[d] != chunksize_in[d]) ERR; if (contiguous_in != 0) ERR; if (nc_close(ncid)) ERR; /* Open the file and check the same stuff. */ if (nc_open(FILE_NAME, NC_NOWRITE, &ncid)) ERR; /* Check stuff. */ if (nc_inq(ncid, &ndims, &nvars, &natts, &unlimdimid)) ERR; if (ndims != NDIMS17 || nvars != 1 || natts != 0 || unlimdimid != -1) ERR; if (nc_inq_varids(ncid, &nvars, varids_in)) ERR; if (nvars != 1) ERR; if (varids_in[0] != 0) ERR; if (nc_inq_var(ncid, 0, name_in, &xtype_in, &ndims, dimids_in, &natts)) ERR; if (strcmp(name_in, VAR_NAME17) || xtype_in != NC_UINT64 || ndims != 2 || natts != 0 || dimids_in[0] != 0 || dimids_in[1] != 1) ERR; if (nc_inq_var_chunking(ncid, 0, &contiguous_in, chunksize_in)) ERR; for (d = 0; d < NDIMS17; d++) if (chunksize[d] != chunksize_in[d]) ERR; if (contiguous_in != 0) ERR; if (nc_close(ncid)) ERR; } SUMMARIZE_ERR; FINAL_RESULTS; #ifdef USE_PARALLEL MPI_Finalize(); #endif }
int ex_put_prop (int exoid, int obj_type, int obj_id, const char *prop_name, int value) { int found = FALSE; int num_props, i, dimid, propid, dims[1]; long start[1]; nclong ldum; char name[MAX_VAR_NAME_LENGTH+1]; char obj_stype[MAX_VAR_NAME_LENGTH+1]; char obj_vtype[MAX_VAR_NAME_LENGTH+1]; char tmpstr[MAX_VAR_NAME_LENGTH+1]; char dim_name[MAX_VAR_NAME_LENGTH+1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* check if property has already been created */ num_props = ex_get_num_props(exoid, obj_type); switch (obj_type) { case EX_ELEM_BLOCK: strcpy (obj_vtype, VAR_ID_EL_BLK); strcpy (obj_stype, "element block"); break; case EX_NODE_SET: strcpy (obj_vtype, VAR_NS_IDS); strcpy (obj_stype, "node set"); break; case EX_SIDE_SET: strcpy (obj_vtype, VAR_SS_IDS); strcpy (obj_stype, "side set"); break; case EX_ELEM_MAP: strcpy (obj_vtype, VAR_EM_PROP(1)); strcpy (obj_stype, "element map"); break; case EX_NODE_MAP: strcpy (obj_vtype, VAR_NM_PROP(1)); strcpy (obj_stype, "node map"); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop",errmsg,exerrval); return(EX_FATAL); } if (num_props > 1) /* any properties other than the default 1? */ { for (i=1; i<=num_props; i++) { switch (obj_type) { case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop",errmsg,exerrval); return(EX_FATAL); } if ((propid = ncvarid (exoid, name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get property array id in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } /* compare stored attribute name with passed property name */ if ((ncattget (exoid, propid, ATT_PROP_NAME, tmpstr)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get property name in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } if (strcmp(tmpstr, prop_name) == 0) { found = TRUE; break; } } } /* if property array has not been created, create it */ if (!found) { /* put netcdf file into define mode */ if (ncredef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } /* create a variable with a name xx_prop#, where # is the new number */ /* of the property */ switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_EL_BLK); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_NS); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_SS); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_EM); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(num_props+1)); strcpy (dim_name, DIM_NUM_NM); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* inquire id of previously defined dimension (number of objects) */ if ((dimid = ncdimid (exoid, dim_name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate number of objects in file id %d", exoid); ex_err("ex_put_prop",errmsg, exerrval); goto error_ret; /* Exit define mode and return */ } dims[0] = dimid; ncsetfill(exoid, NC_FILL); /* fill with zeros per routine spec */ if ((propid = ncvardef (exoid, name, NC_LONG, 1, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create property array variable in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } ncsetfill(exoid, NC_NOFILL); /* default: nofill */ /* store property name as attribute of property array variable */ if ((ncattput (exoid, propid, ATT_PROP_NAME, NC_CHAR, strlen(prop_name)+1, prop_name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store property name %s in file id %d", prop_name,exoid); ex_err("ex_put_prop",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* leave define mode */ if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to leave define mode in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } } /* find index into property array using obj_id; put value in property */ /* array at proper index; ex_id_lkup returns an index that is 1-based,*/ /* but netcdf expects 0-based arrays so subtract 1 */ /* special case: property name ID - check for duplicate ID assignment */ if (strcmp("ID",prop_name) == 0) { start[0] = ex_id_lkup (exoid, obj_vtype, value); if (exerrval != EX_LOOKUPFAIL) /* found the id */ { exerrval = EX_BADPARAM; sprintf(errmsg, "Warning: attempt to assign duplicate %s ID %d in file id %d", obj_stype, value, exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_WARN); } } start[0] = ex_id_lkup (exoid, obj_vtype, obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no properties allowed for NULL %s id %d in file id %d", obj_stype, obj_id,exoid); ex_err("ex_put_prop",errmsg,EX_MSG); return (EX_WARN); } else { exerrval = ncerr; sprintf(errmsg, "Error: failed to find value %d in %s property array in file id %d", obj_id, obj_stype, exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } } start[0] = start[0] - 1; ldum = (nclong)value; if (ncvarput1 (exoid, propid, start, &ldum) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store property value in file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: ncsetfill(exoid, NC_NOFILL); /* default: nofill */ if (ncendef (exoid) == -1) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_prop",errmsg,exerrval); } return (EX_FATAL); }
int main(int argc, char *argv[]) { char *pname; char *filename, *tempfile, *newfile; char string[1024]; char *variable_name, *attribute_name; int created_tempfile; int done_redef; int iatt; int mincid, varid; int variable_exists, attribute_exists; nc_type attribute_type, new_type; int attribute_length, new_length; void *new_value; int total_length, alloc_length, ival; char *zeros; int old_ncopts; /* Parse the command line */ pname=argv[0]; if (ParseArgv(&argc, argv, argTable, 0) || (argc != 2)) { (void) fprintf(stderr, "\nUsage: %s [<options>] <file.mnc>\n", pname); (void) fprintf(stderr, " %s [-help]\n\n", pname); exit(EXIT_FAILURE); } filename = argv[1]; /* Create temp file name. First try looking for minc extension, then a compression extension. Chop off the unwanted extension. */ (void) strncpy(string, filename, sizeof(string)-1); tempfile = strstr(string, MINC_EXTENSION); if (tempfile != NULL) { tempfile += strlen(MINC_EXTENSION); if (*tempfile == '\0') tempfile = NULL; } else { tempfile = strstr(string, GZIP_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, BZIP_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, BZIP2_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, COMPRESS_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, PACK_EXTENSION); if (tempfile == NULL) tempfile = strstr(string, ZIP_EXTENSION); } if (tempfile != NULL) { *tempfile = '\0'; tempfile = string; } /* If tempfile == NULL, then either we have a minc file or we don't know how to edit the file in place. Check that it is a minc file. */ if (tempfile == NULL) { newfile = miexpand_file(filename, tempfile, TRUE, &created_tempfile); if (created_tempfile) { if (newfile != NULL) { (void) remove(newfile); free(newfile); } (void) fprintf(stderr, "Cannot edit file \"%s\" in place.\n", filename); exit(EXIT_FAILURE); } } /* Expand the file. */ newfile = miexpand_file(filename, tempfile, FALSE, &created_tempfile); if (newfile == NULL) { (void) fprintf(stderr, "Error decompressing file \"%s\"\n", filename); exit(EXIT_FAILURE); } /* If a new file was created, get rid of the old one */ if (created_tempfile) { (void) remove(filename); } /* Open the file */ mincid = miopen(newfile, NC_WRITE); /* Loop through attribute list, modifying values */ done_redef = FALSE; ncopts = NC_VERBOSE; zeros = NULL; alloc_length = 0; for (iatt=0; iatt < attribute_list_size; iatt++) { /* Get variable and attribute name */ variable_name = attribute_list[iatt].variable; attribute_name = attribute_list[iatt].attribute; /* Check for attribute existence */ if (strlen(variable_name) == 0) { varid = NC_GLOBAL; variable_exists = TRUE; } else { old_ncopts = ncopts; ncopts = 0; varid = ncvarid(mincid, variable_name); ncopts = old_ncopts; variable_exists = (varid != MI_ERROR); } attribute_type = NC_CHAR; attribute_length = 0; if (variable_exists) { old_ncopts = ncopts; ncopts = 0; attribute_exists = (ncattinq(mincid, varid, attribute_name, &attribute_type, &attribute_length) != MI_ERROR); ncopts = old_ncopts; } else attribute_exists = FALSE; /* Are we inserting or deleting? */ switch (attribute_list[iatt].action) { case Insert_attribute: case Append_attribute: if (attribute_list[iatt].value != NULL) { new_type = NC_CHAR; new_length = strlen(attribute_list[iatt].value)+1; new_value = (void *) attribute_list[iatt].value; } else { new_type = NC_DOUBLE; new_length = attribute_list[iatt].num_doubles; new_value = (void *) attribute_list[iatt].double_values; } /* For append we have to copy the entire attribute, if it * already exists. */ if (attribute_list[iatt].action == Append_attribute && attribute_exists) { char *tmp_value; /* Verify that the existing type matches the newly * requested type. Don't allow a -dappend on a * string attribute, for example. */ if (new_type != attribute_type) { fprintf(stderr, "Can't append %s data to %s attribute %s:%s.\n", (new_type == NC_DOUBLE) ? "double" : "string", (attribute_type == NC_DOUBLE) ? "double" : "string", variable_name, attribute_name); exit(EXIT_FAILURE); } new_type = attribute_type; tmp_value = malloc((attribute_length + new_length) * nctypelen(new_type)); ncattget(mincid, varid, attribute_name, tmp_value); /* For string attributes, remove any trailing null * character before appending. */ if (new_type == NC_CHAR && tmp_value[attribute_length-1] == 0) { attribute_length--; } memcpy(tmp_value + attribute_length * nctypelen(new_type), new_value, new_length * nctypelen(new_type)); new_length += attribute_length; new_value = (void *) tmp_value; } total_length = attribute_length*nctypelen(attribute_type); if (!attribute_exists || (total_length < new_length*nctypelen(new_type))) { if (! done_redef) { done_redef = TRUE; (void) ncredef(mincid); } } else if (!done_redef && attribute_exists && (total_length > 0)) { if (total_length > alloc_length) { if (zeros != NULL) free(zeros); zeros = malloc(total_length); alloc_length = total_length; for (ival=0; ival < alloc_length; ival++) zeros[ival] = '\0'; } (void) ncattput(mincid, varid, attribute_name, NC_CHAR, total_length, zeros); (void) ncsync(mincid); } if (!variable_exists) { old_ncopts = ncopts; ncopts = 0; varid = micreate_group_variable(mincid, variable_name); ncopts = old_ncopts; if (varid == MI_ERROR) { varid = ncvardef(mincid, variable_name, NC_INT, 0, NULL); } variable_exists = (varid != MI_ERROR); } if (variable_exists) { (void) ncattput(mincid, varid, attribute_name, new_type, new_length, new_value); } break; case Delete_attribute: if (attribute_exists) { if (! done_redef) { done_redef = TRUE; (void) ncredef(mincid); } (void) ncattdel(mincid, varid, attribute_name); } break; default: (void) fprintf(stderr, "Program error: unknown action %d\n", (int) attribute_list[iatt].action); exit(EXIT_FAILURE); } } ncopts = NC_VERBOSE | NC_FATAL; /* Close the file */ (void) miclose(mincid); /* Free stuff */ free(newfile); if (zeros != NULL) free(zeros); exit(EXIT_SUCCESS); }
int main() { /* create example.cdf */ int ncid; /* netCDF id */ /* dimension ids */ int lat_dim, lon_dim, frtime_dim, timelen_dim; /* variable ids */ int P_id, lat_id, lon_id, frtime_id, reftime_id, scalarv_id; /* variable shapes */ int dims[3]; /* containers for scalar attributes */ float float_val; double double_val; /* attribute vectors */ float P_valid_range[2]; /* enter define mode */ ncid = nccreate("example.nc", NC_CLOBBER); /* define dimensions */ lat_dim = ncdimdef(ncid, "lat", 4L); lon_dim = ncdimdef(ncid, "lon", 3L); frtime_dim = ncdimdef(ncid, "frtime", NC_UNLIMITED); timelen_dim = ncdimdef(ncid, "timelen", 20L); /* define variables and assign attributes */ dims[0] = frtime_dim; dims[1] = lat_dim; dims[2] = lon_dim; P_id = ncvardef (ncid, "P", NC_FLOAT, 3, dims); ncattput (ncid, P_id, "long_name", NC_CHAR, 24, (void *)"pressure at maximum wind"); ncattput (ncid, P_id, "units", NC_CHAR, 12, (void *)"hectopascals"); P_valid_range[0] = 0; P_valid_range[1] = 1500; ncattput (ncid, P_id, "valid_range", NC_FLOAT, 2, (void *) P_valid_range); float_val = -9999; ncattput (ncid, P_id, "_FillValue", NC_FLOAT, 1, (void *) &float_val); dims[0] = lat_dim; lat_id = ncvardef (ncid, "lat", NC_FLOAT, 1, dims); ncattput (ncid, lat_id, "long_name", NC_CHAR, 8, (void *)"latitude"); ncattput (ncid, lat_id, "units", NC_CHAR, 13, (void *)"degrees_north"); dims[0] = lon_dim; lon_id = ncvardef (ncid, "lon", NC_FLOAT, 1, dims); ncattput (ncid, lon_id, "long_name", NC_CHAR, 9, (void *)"longitude"); ncattput (ncid, lon_id, "units", NC_CHAR, 12, (void *)"degrees_east"); dims[0] = frtime_dim; frtime_id = ncvardef (ncid, "frtime", NC_LONG, 1, dims); ncattput (ncid, frtime_id, "long_name", NC_CHAR, 13, (void *)"forecast time"); ncattput (ncid, frtime_id, "units", NC_CHAR, 5, (void *)"hours"); dims[0] = timelen_dim; reftime_id = ncvardef (ncid, "reftime", NC_CHAR, 1, dims); ncattput (ncid, reftime_id, "long_name", NC_CHAR, 14, (void *)"reference time"); ncattput (ncid, reftime_id, "units", NC_CHAR, 9, (void *)"text_time"); scalarv_id = ncvardef (ncid, "scalarv", NC_LONG, 0, 0); double_val = 1; ncattput (ncid, scalarv_id, "scalar_att", NC_DOUBLE, 1, (void *) &double_val); /* Global attributes */ ncattput (ncid, NC_GLOBAL, "history", NC_CHAR, 41, (void *)"created by Unidata LDM from NPS broadcast"); ncattput (ncid, NC_GLOBAL, "title", NC_CHAR, 48, (void *)"NMC Global Product Set: Pressure at Maximum Wind"); /* leave define mode */ ncendef (ncid); { /* store lat */ static long lat_start[] = {0}; static long lat_edges[] = {4}; static float lat[] = {-90, -87.5, -85, -82.5}; ncvarput(ncid, lat_id, lat_start, lat_edges, (void *)lat); } { /* store lon */ static long lon_start[] = {0}; static long lon_edges[] = {3}; static float lon[] = {-180, -175, -170}; ncvarput(ncid, lon_id, lon_start, lon_edges, (void *)lon); } { /* store frtime */ static long frtime_start[] = {0}; static long frtime_edges[] = {1}; static long frtime[] = {12}; ncvarput(ncid, frtime_id, frtime_start, frtime_edges, (void *)frtime); } { /* store frtime */ static long frtime_start[] = {1}; static long frtime_edges[] = {1}; static long frtime[] = {18}; ncvarput(ncid, frtime_id, frtime_start, frtime_edges, (void *)frtime); } { /* store reftime */ static long reftime_start[] = {0}; static long reftime_edges[] = {20}; static char reftime[] = {"1992 03 04 12:00"}; ncvarput(ncid, reftime_id, reftime_start, reftime_edges, (void *)reftime); } { /* store P */ static long P_start[] = {0, 0, 0}; static long P_edges[] = {2, 4, 3}; static float P[2][4][3] = { {{950, 951, 952}, {953, 954, 955}, {956, 957, 958}, {959, 960, 961}}, {{962, 963, 964}, {965, 966, 967}, {968, 969, 970}, {971, 972, 973}} }; ncvarput(ncid, P_id, P_start, P_edges, (void *)&P[0][0][0]); } { /* store scalarv */ static long scalarv = {-2147483647}; ncvarput1(ncid, scalarv_id, (long *)0, (void *)&scalarv); } ncclose (ncid); return 0; }
/* Test case 1 - file creation & definition. */ static int test1(struct testinfo *ip, struct dimdef *dims, int ndims) { int varid; int stat; int i; /* Test case #1 - file creation */ ip->name = micreate_tempfile(); if (ip->name == NULL) { FUNC_ERROR("micreate_tempfile\n"); } ip->fd = micreate(ip->name, NC_CLOBBER); if (ip->fd < 0) { FUNC_ERROR("micreate"); } /* Have to use ncdimdef() here since there is no MINC equivalent. Sigh. */ for (i = 0; i < ndims; i++) { /* Define the dimension */ ip->dim[i] = ncdimdef(ip->fd, dims[i].name, dims[i].length); if (ip->dim[i] < 0) { FUNC_ERROR("ncdimdef"); } /* Create the dimension variable. */ varid = micreate_std_variable(ip->fd, dims[i].name, NC_DOUBLE, 0, &ip->dim[i]); if (varid < 0) { FUNC_ERROR("micreate_std_variable"); } stat = miattputdbl(ip->fd, varid, MIstep, 0.8); if (stat < 0) { FUNC_ERROR("miattputdbl"); } stat = miattputdbl(ip->fd, varid, MIstart, 22.0); if (stat < 0) { FUNC_ERROR("miattputdbl"); } } /* Create the image-max variable. */ ip->maxid = micreate_std_variable(ip->fd, MIimagemax, NC_FLOAT, 0, NULL); if (ip->maxid < 0) { FUNC_ERROR("micreate_std_variable"); } /* Create the image-min variable. */ ip->minid = micreate_std_variable(ip->fd, MIimagemin, NC_FLOAT, 0, NULL); if (ip->minid < 0) { FUNC_ERROR("micreate_std_variable"); } ip->imgid = micreate_std_variable(ip->fd, MIimage, NC_INT, ndims, ip->dim); if (ip->imgid < 0) { FUNC_ERROR("micreate_std_variable"); } ip->test_group = ncvardef(ip->fd,(char*)"test",NC_INT,0,0);/* micreate_group_variable(ip->fd,(char*)"test");*/ if(ip->test_group<0) { FUNC_ERROR("micreate_group_variable"); } ip->large_attribute=calloc(ip->attribute_size,sizeof(char)); memset(ip->large_attribute,'X',ip->attribute_size-1); ip->test_attribute = ncattput(ip->fd, ip->test_group, "test", NC_CHAR, ip->attribute_size, ip->large_attribute); return (0); }
/* ----------------------------- MNI Header ----------------------------------- @NAME : CreateBloodCDF @INPUT : @OUTPUT : @RETURNS : @DESCRIPTION: @METHOD : @GLOBALS : @CALLS : @CREATED : @MODIFIED : ---------------------------------------------------------------------------- */ int CreateBloodCDF (char name[], header *cnt_header) { int file_CDF; int dim_id[1]; int parent_id; int sample_start_id; int sample_stop_id; int sample_length_id; int count_start_id; int count_length_id; int counts_id; int empty_weight_id; int full_weight_id; int corrected_activity_id; int activity_id; file_CDF = nccreate (name, NC_CLOBBER); if (file_CDF == MI_ERROR) { return (file_CDF); } /* Create the dimension */ dim_id[0] = ncdimdef (file_CDF, "sample", (long)cnt_header->num_samples); /* Create the variables */ sample_start_id = ncvardef (file_CDF, MIsamplestart, NC_DOUBLE, 1, dim_id); sample_stop_id = ncvardef (file_CDF, MIsamplestop, NC_DOUBLE, 1, dim_id); sample_length_id = ncvardef (file_CDF, MIsamplelength, NC_DOUBLE, 1, dim_id); count_start_id = ncvardef (file_CDF, MIcountstart, NC_DOUBLE, 1, dim_id); count_length_id = ncvardef (file_CDF, MIcountlength, NC_DOUBLE, 1, dim_id); counts_id = ncvardef (file_CDF, MIcounts, NC_DOUBLE, 1, dim_id); empty_weight_id = ncvardef (file_CDF, MIemptyweight, NC_DOUBLE, 1, dim_id); full_weight_id = ncvardef (file_CDF, MIfullweight, NC_DOUBLE, 1, dim_id); corrected_activity_id = ncvardef (file_CDF, MIcorrectedactivity, NC_DOUBLE, 1, dim_id); activity_id = ncvardef (file_CDF, MIactivity, NC_DOUBLE, 1, dim_id); /* Create variable attributes */ miattputstr (file_CDF, sample_start_id, "units", "seconds"); miattputstr (file_CDF, sample_stop_id, "units", "seconds"); miattputstr (file_CDF, sample_length_id, "units", "seconds"); miattputstr (file_CDF, count_start_id, "units", "seconds"); miattputstr (file_CDF, count_length_id, "units", "seconds"); miattputstr (file_CDF, counts_id, "units", "counts"); miattputstr (file_CDF, empty_weight_id, "units", "grams"); miattputstr (file_CDF, full_weight_id, "units", "grams"); miattputstr (file_CDF, corrected_activity_id, "units", "Bq/gram"); miattputstr (file_CDF, activity_id, "units", "Bq"); /* Make a root for the blood analysis info */ parent_id = ncvardef (file_CDF, MIbloodroot, NC_LONG, 0, NULL); (void) miattputstr (file_CDF, parent_id, MIbloodname, cnt_header->patient_name); (void) ncattput (file_CDF, parent_id, MIbloodrunnumber, NC_LONG, 1, &(cnt_header->run_number)); (void) miattputstr (file_CDF, parent_id, MIbloodstarttime, cnt_header->start_time); (void) miattputstr (file_CDF, parent_id, MIblooddate, cnt_header->date); (void) miattputstr (file_CDF, parent_id, MIbloodisotope, cnt_header->isotope); (void) miattputstr (file_CDF, parent_id, MIbloodstudytype, cnt_header->study_type); (void) miattputint (file_CDF, parent_id, MIbloodbackground, cnt_header->background); (void) miattputstr (file_CDF, parent_id, MIbloodcomplete, "false"); /* Set up the hierarchy */ (void) miadd_child (file_CDF, parent_id, sample_start_id); (void) miadd_child (file_CDF, parent_id, sample_stop_id); (void) miadd_child (file_CDF, parent_id, sample_length_id); (void) miadd_child (file_CDF, parent_id, count_start_id); (void) miadd_child (file_CDF, parent_id, count_length_id); (void) miadd_child (file_CDF, parent_id, counts_id); (void) miadd_child (file_CDF, parent_id, empty_weight_id); (void) miadd_child (file_CDF, parent_id, full_weight_id); (void) miadd_child (file_CDF, parent_id, corrected_activity_id); (void) miadd_child (file_CDF, parent_id, activity_id); /* End definition mode */ ncendef (file_CDF); return (file_CDF); }
int ex_put_prop_names (int exoid, int obj_type, int num_props, char **prop_names) { int i, propid, dimid, dims[1]; char name[MAX_VAR_NAME_LENGTH+1]; long vals[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* determine what type of object (element block, node set, or side set) */ switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, DIM_NUM_EL_BLK); break; case EX_NODE_SET: strcpy (name, DIM_NUM_NS); break; case EX_SIDE_SET: strcpy (name, DIM_NUM_SS); break; case EX_ELEM_MAP: strcpy (name, DIM_NUM_EM); break; case EX_NODE_MAP: strcpy (name, DIM_NUM_NM); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_names",errmsg,exerrval); return(EX_FATAL); } /* inquire id of previously defined dimension (number of objects) */ if ((dimid = ncdimid (exoid, name)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to locate number of objects in file id %d", exoid); ex_err("ex_put_prop_names",errmsg, exerrval); return(EX_FATAL); } ncsetfill(exoid, NC_FILL); /* fill with zeros per routine spec */ /* put netcdf file into define mode */ if (ncredef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg,"Error: failed to place file id %d into define mode",exoid); ex_err("ex_put_prop_names",errmsg,exerrval); return (EX_FATAL); } /* define num_props variables; we postpend the netcdf variable name with */ /* a counter starting at 2 because "xx_prop1" is reserved for the id array*/ dims[0] = dimid; for (i=0; i<num_props; i++) { switch (obj_type){ case EX_ELEM_BLOCK: strcpy (name, VAR_EB_PROP(i+2)); break; case EX_NODE_SET: strcpy (name, VAR_NS_PROP(i+2)); break; case EX_SIDE_SET: strcpy (name, VAR_SS_PROP(i+2)); break; case EX_ELEM_MAP: strcpy (name, VAR_EM_PROP(i+2)); break; case EX_NODE_MAP: strcpy (name, VAR_NM_PROP(i+2)); break; default: exerrval = EX_BADPARAM; sprintf(errmsg, "Error: object type %d not supported; file id %d", obj_type, exoid); ex_err("ex_put_prop_names",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } if ((propid = ncvardef (exoid, name, NC_LONG, 1, dims)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create property array variable in file id %d", exoid); ex_err("ex_put_prop_names",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } vals[0] = 0; /* fill value */ /* create attribute to cause variable to fill with zeros per routine spec */ if ((ncattput (exoid, propid, _FillValue, NC_LONG, 1, vals)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create property name fill attribute in file id %d", exoid); ex_err("ex_put_prop_names",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } /* store property name as attribute of property array variable */ if ((ncattput (exoid, propid, ATT_PROP_NAME, NC_CHAR, strlen(prop_names[i])+1, prop_names[i])) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store property name %s in file id %d", prop_names[i],exoid); ex_err("ex_put_prop_names",errmsg,exerrval); goto error_ret; /* Exit define mode and return */ } } /* leave define mode */ if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to leave define mode in file id %d", exoid); ex_err("ex_put_prop_names",errmsg,exerrval); return (EX_FATAL); } ncsetfill(exoid, NC_NOFILL); /* default: turn off fill */ return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (ncendef (exoid) == -1) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_prop_names",errmsg,exerrval); } return (EX_FATAL); }
/* ----------------------------- MNI Header ----------------------------------- @NAME : PutMaxMin @INPUT : ImInfo - pointer to struct describing the image variable ImVals - pointer to array of doubles containing the image data SliceNum, FrameNum - needed to correctly place the max and min values into the MIimagemax and MIimagemin variables DoFrames - whether or not there is a time dimension in this file @OUTPUT : (none) @RETURNS : (void) @DESCRIPTION: Finds the max and min values of an image, and puts them into the MIimagemax and MIimagemin variables associated with the specified image variable. Note: the caller must make sure that MIimagemax and MIimagemin exist in the file, and ensure that ImInfo->MaxID and ImInfo->MinID contain their variable ID's. @METHOD : @GLOBALS : @CALLS : @CREATED : 93-6-3, Greg Ward @MODIFIED : ---------------------------------------------------------------------------- */ void PutMaxMin (ImageInfoRec *ImInfo, double *ImVals, long SliceNum, long FrameNum, Boolean DoSlices, Boolean DoFrames) { int i; double Max, Min; long Coord [2]; /* might use 0, 1 or 2 elements */ int old_ncopts; int ret; nc_type range_type; int range_len; int update_vr; double valid_range[2]; double vr_max; #ifdef DEBUG int NumDims; /* number of dimensions in imagemax/imagemin */ int Dims [4]; /* dimension ID's of imagemax/imagemin */ printf ("Slice dimension is %d\n", ImInfo->SliceDim); printf ("Frame dimension is %d\n", ImInfo->FrameDim); ncvarinq (ImInfo->CDF, ImInfo->MaxID, NULL, NULL, &NumDims, Dims, NULL); printf ("MIimagemax has %d dimensions: ", NumDims); for (i = 0; i < NumDims; i++) { printf ("%5d", Dims [i]); } putchar ('\n'); ncvarinq (ImInfo->CDF, ImInfo->MinID, NULL, NULL, &NumDims, Dims, NULL); printf ("MIimagemin has %d dimensions: ", NumDims); for (i = 0; i < NumDims; i++) { printf ("%5d", Dims [i]); } putchar ('\n'); #endif Max = - DBL_MAX; Min = DBL_MAX; /* * Find the actual max and min values in the buffer */ for (i = 0; i < ImInfo->ImageSize; i++) { if (ImVals [i] > Max) { Max = ImVals [i]; } if (ImVals [i] < Min) { Min = ImVals [i]; } } /* for i */ /* * Now figure out the Coord vector (where to put the max and min * within the MIimagemax and MIimagemin variables), and put 'em there */ if (DoFrames) /* i.e. some frame was specified */ { Coord [ImInfo->FrameDim] = FrameNum; } if (DoSlices) { Coord [ImInfo->SliceDim] = SliceNum; } #ifdef DEBUG printf ("Slice %ld, frame %ld: max is %lg, min is %lg\n", (DoSlices) ? (SliceNum) : -1, (DoFrames) ? (FrameNum) : -1, Max, Min); if (DoSlices && DoFrames) printf ("Coord vector is: %ld %ld\n", Coord [0], Coord [1]); #endif mivarput1 (ImInfo->CDF, ImInfo->MaxID, Coord, NC_DOUBLE, MI_SIGNED, &Max); mivarput1 (ImInfo->CDF, ImInfo->MinID, Coord, NC_DOUBLE, MI_SIGNED, &Min); /* * Update the image valid_range attribute for floating-point volumes */ if ((ImInfo->DataType == NC_FLOAT) || (ImInfo->DataType == NC_DOUBLE)) { /* Get type and length of valid_range attribute */ old_ncopts = ncopts; ncopts = 0; ret = ncattinq(ImInfo->CDF, ImInfo->ID, MIvalid_range, &range_type, &range_len); ncopts = old_ncopts; /* If type and length are okay, then read in old value and update */ if ((ret != MI_ERROR) && (range_type == NC_DOUBLE) && (range_len == 2)) { (void) ncattget(ImInfo->CDF, ImInfo->ID, MIvalid_range, valid_range); /* Test for first write of valid range */ vr_max = (ImInfo->DataType == NC_DOUBLE ? 1.79769313e+308 : 3.402e+38); update_vr = ((valid_range[0] < -vr_max) && (valid_range[1] > vr_max)); /* Check the range */ if ((Min < valid_range[0]) || update_vr) valid_range[0] = Min; if ((Max > valid_range[1]) || update_vr) valid_range[1] = Max; /* Check for whether float rounding is needed */ if (ImInfo->DataType == NC_FLOAT) { valid_range[0] = (float) valid_range[0]; valid_range[1] = (float) valid_range[1]; } /* Write it out */ (void) ncattput(ImInfo->CDF, ImInfo->ID, MIvalid_range, NC_DOUBLE, 2, valid_range); } } /* if DataType is floating-point */ } /* PutMaxMin */
void mexFunction ( INT nlhs, Matrix * plhs[], INT nrhs, const Matrix * prhs[] ) { char * opname; OPCODE opcode; Matrix * mat; int status; char * path; int cmode; int mode; int cdfid; int ndims; int nvars; int natts; int recdim; char * name; long length; int dimid; nc_type datatype; int * dim; int varid; long * coords; VOIDP value; long * start; long * count; int * intcount; long * stride; long * imap; long recnum; int nrecvars; int * recvarids; long * recsizes; VOIDPP datap; /* pointers for record access. */ int len; int incdf; int invar; int outcdf; int outvar; int attnum; char * attname; char * newname; int fillmode; int i; int m; int n; char * p; char buffer[MAX_BUFFER]; DOUBLE * pr; DOUBLE addoffset; DOUBLE scalefactor; int autoscale; /* do auto-scaling if this flag is non-zero. */ /* Disable the NC_FATAL option from ncopts. */ if (ncopts & NC_FATAL) { ncopts -= NC_FATAL; } /* Display usage if less than one input argument. */ if (nrhs < 1) { Usage(); return; } /* Convert the operation name to its opcode. */ opname = Mat2Str(prhs[0]); for (i = 0; i < strlen(opname); i++) { opname[i] = (char) tolower((int) opname[i]); } p = opname; if (strncmp(p, "nc", 2) == 0) { /* Trim away "nc". */ p += 2; } i = 0; opcode = NONE; while (ops[i].opcode != NONE) { if (!strcmp(p, ops[i].opname)) { opcode = ops[i].opcode; if (ops[i].nrhs > nrhs) { mexPrintf("MEXCDF: opname = %s\n", opname); mexErrMsgTxt("MEXCDF: Too few input arguments.\n"); } else if (0 && ops[i].nlhs > nlhs) { /* Disabled. */ mexPrintf("MEXCDF: opname = %s\n", opname); mexErrMsgTxt("MEXCDF: Too few output arguments.\n"); } break; } else { i++; } } if (opcode == NONE) { mexPrintf("MEXCDF: opname = %s\n", opname); mexErrMsgTxt("MEXCDF: No such operation.\n"); } Free((VOIDPP) & opname); /* Extract the cdfid by number. */ switch (opcode) { case USAGE: case CREATE: case OPEN: case TYPELEN: case SETOPTS: case ERR: case PARAMETER: break; default: cdfid = Scalar2Int(prhs[1]); break; } /* Extract the dimid by number or name. */ switch (opcode) { case DIMINQ: case DIMRENAME: if (mxIsNumeric(prhs[2])) { dimid = Scalar2Int(prhs[2]); } else { name = Mat2Str(prhs[2]); dimid = ncdimid(cdfid, name); Free((VOIDPP) & name); } break; default: break; } /* Extract the varid by number or name. */ switch (opcode) { case VARINQ: case VARPUT1: case VARGET1: case VARPUT: case VARGET: case VARPUTG: case VARGETG: case VARRENAME: case VARCOPY: case ATTPUT: case ATTINQ: case ATTGET: case ATTCOPY: case ATTNAME: case ATTRENAME: case ATTDEL: if (mxIsNumeric(prhs[2])) { varid = Scalar2Int(prhs[2]); } else { name = Mat2Str(prhs[2]); varid = ncvarid(cdfid, name); Free((VOIDPP) & name); if (varid == -1) { varid = Parameter(prhs[2]); } } break; default: break; } /* Extract the attname by name or number. */ switch (opcode) { case ATTPUT: case ATTINQ: case ATTGET: case ATTCOPY: case ATTRENAME: case ATTDEL: if (mxIsNumeric(prhs[3])) { attnum = Scalar2Int(prhs[3]); attname = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); status = ncattname(cdfid, varid, attnum, attname); } else { attname = Mat2Str(prhs[3]); } break; default: break; } /* Extract the "add_offset" and "scale_factor" attributes. */ switch (opcode) { case VARPUT1: case VARGET1: case VARPUT: case VARGET: case VARPUTG: case VARGETG: addoffset = Add_Offset(cdfid, varid); scalefactor = Scale_Factor(cdfid, varid); if (scalefactor == 0.0) { scalefactor = 1.0; } break; default: break; } /* Perform the NetCDF operation. */ switch (opcode) { case USAGE: Usage(); break; case CREATE: path = Mat2Str(prhs[1]); if (nrhs > 2) { cmode = Parameter(prhs[2]); } else { cmode = NC_NOCLOBBER; /* Default. */ } cdfid = nccreate(path, cmode); plhs[0] = Int2Scalar(cdfid); plhs[1] = Int2Scalar((cdfid >= 0) ? 0 : -1); Free((VOIDPP) & path); break; case OPEN: path = Mat2Str(prhs[1]); if (nrhs > 2) { mode = Parameter(prhs[2]); } else { mode = NC_NOWRITE; /* Default. */ } cdfid = ncopen(path, mode); plhs[0] = Int2Scalar(cdfid); plhs[1] = Int2Scalar((cdfid >= 0) ? 0 : -1); Free((VOIDPP) & path); break; case REDEF: status = ncredef(cdfid); plhs[0] = Int2Scalar(status); break; case ENDEF: status = ncendef(cdfid); plhs[0] = Int2Scalar(status); break; case CLOSE: status = ncclose(cdfid); plhs[0] = Int2Scalar(status); break; case INQUIRE: status = ncinquire(cdfid, & ndims, & nvars, & natts, & recdim); if (nlhs > 1) { plhs[0] = Int2Scalar(ndims); plhs[1] = Int2Scalar(nvars); plhs[2] = Int2Scalar(natts); plhs[3] = Int2Scalar(recdim); plhs[4] = Int2Scalar(status); } else { /* Default to 1 x 5 row vector. */ plhs[0] = mxCreateFull(1, 5, REAL); pr = mxGetPr(plhs[0]); if (status == 0) { pr[0] = (DOUBLE) ndims; pr[1] = (DOUBLE) nvars; pr[2] = (DOUBLE) natts; pr[3] = (DOUBLE) recdim; } pr[4] = (DOUBLE) status; } break; case SYNC: status = ncsync(cdfid); plhs[0] = Int2Scalar(status); break; case ABORT: status = ncabort(cdfid); plhs[0] = Int2Scalar(status); break; case DIMDEF: name = Mat2Str(prhs[2]); length = Parameter(prhs[3]); dimid = ncdimdef(cdfid, name, length); plhs[0] = Int2Scalar(dimid); plhs[1] = Int2Scalar((dimid >= 0) ? 0 : dimid); Free((VOIDPP) & name); break; case DIMID: name = Mat2Str(prhs[2]); dimid = ncdimid(cdfid, name); plhs[0] = Int2Scalar(dimid); plhs[1] = Int2Scalar((dimid >= 0) ? 0 : dimid); Free((VOIDPP) & name); break; case DIMINQ: name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); status = ncdiminq(cdfid, dimid, name, & length); plhs[0] = Str2Mat(name); plhs[1] = Long2Scalar(length); plhs[2] = Int2Scalar(status); Free((VOIDPP) & name); break; case DIMRENAME: name = Mat2Str(prhs[3]); status = ncdimrename(cdfid, dimid, name); plhs[0] = Int2Scalar(status); Free((VOIDPP) & name); break; case VARDEF: name = Mat2Str(prhs[2]); datatype = (nc_type) Parameter(prhs[3]); ndims = Scalar2Int(prhs[4]); if (ndims == -1) { ndims = Count(prhs[5]); } dim = Mat2Int(prhs[5]); varid = ncvardef(cdfid, name, datatype, ndims, dim); Free((VOIDPP) & name); plhs[0] = Int2Scalar(varid); plhs[1] = Int2Scalar((varid >= 0) ? 0 : varid); break; case VARID: name = Mat2Str(prhs[2]); varid = ncvarid(cdfid, name); Free((VOIDPP) & name); plhs[0] = Int2Scalar(varid); plhs[1] = Int2Scalar((varid >= 0) ? 0 : varid); break; case VARINQ: name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); plhs[0] = Str2Mat(name); plhs[1] = Int2Scalar(datatype); plhs[2] = Int2Scalar(ndims); plhs[3] = Int2Mat(dim, 1, ndims); plhs[4] = Int2Scalar(natts); plhs[5] = Int2Scalar(status); Free((VOIDPP) & name); Free((VOIDPP) & dim); break; case VARPUT1: coords = Mat2Long(prhs[3]); name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); Free((VOIDPP) & name); Free((VOIDPP) & dim); if (datatype == NC_CHAR) { mat = SetNum(prhs[4]); } else { mat = prhs[4]; } if (mat == NULL) { mat = prhs[4]; } pr = mxGetPr(mat); autoscale = (nrhs > 5 && Scalar2Int(prhs[5]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } status = Convert(opcode, datatype, 1, buffer, scalefactor, addoffset, pr); status = ncvarput1(cdfid, varid, coords, buffer); plhs[0] = Int2Scalar(status); Free((VOIDPP) & coords); break; case VARGET1: coords = Mat2Long(prhs[3]); autoscale = (nrhs > 4 && Scalar2Int(prhs[4]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); Free((VOIDPP) & name); Free((VOIDPP) & dim); mat = Int2Scalar(0); pr = mxGetPr(mat); status = ncvarget1(cdfid, varid, coords, buffer); status = Convert(opcode, datatype, 1, buffer, scalefactor, addoffset, pr); if (datatype == NC_CHAR) { plhs[0] = SetStr(mat); } else { plhs[0] = mat; } if (plhs[0] == NULL) { /* prhs[0] = mat; */ plhs[0] = mat; /* ZYDECO 24Jan2000 */ } plhs[1] = Int2Scalar(status); Free((VOIDPP) & coords); break; case VARPUT: start = Mat2Long(prhs[3]); count = Mat2Long(prhs[4]); autoscale = (nrhs > 6 && Scalar2Int(prhs[6]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); if (datatype == NC_CHAR) { mat = SetNum(prhs[5]); } else { mat = prhs[5]; } if (mat == NULL) { mat = prhs[5]; } pr = mxGetPr(mat); for (i = 0; i < ndims; i++) { if (count[i] == -1) { status = ncdiminq(cdfid, dim[i], name, & count[i]); count[i] -= start[i]; } } Free((VOIDPP) & name); Free((VOIDPP) & dim); len = 0; if (ndims > 0) { len = 1; for (i = 0; i < ndims; i++) { len *= count[i]; } } value = (VOIDP) mxCalloc(len, nctypelen(datatype)); status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr); status = ncvarput(cdfid, varid, start, count, value); Free((VOIDPP) & value); plhs[0] = Int2Scalar(status); Free((VOIDPP) & start); Free((VOIDPP) & count); break; case VARGET: start = Mat2Long(prhs[3]); count = Mat2Long(prhs[4]); intcount = Mat2Int(prhs[4]); autoscale = (nrhs > 5 && Scalar2Int(prhs[5]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); for (i = 0; i < ndims; i++) { if (count[i] == -1) { status = ncdiminq(cdfid, dim[i], name, & count[i]); count[i] -= start[i]; } } Free((VOIDPP) & name); Free((VOIDPP) & dim); m = 0; n = 0; if (ndims > 0) { m = count[0]; n = count[0]; for (i = 1; i < ndims; i++) { n *= count[i]; if (count[i] > 1) { m = count[i]; } } n /= m; } len = m * n; if (ndims < 2) { m = 1; n = len; } for (i = 0; i < ndims; i++) { intcount[i] = count[ndims-i-1]; /* Reverse order. */ } if (MEXCDF_4 || ndims < 2) { mat = mxCreateFull(m, n, mxREAL); /* mxCreateDoubleMatrix */ } # if MEXCDF_5 else { mat = mxCreateNumericArray(ndims, intcount, mxDOUBLE_CLASS, mxREAL); } # endif pr = mxGetPr(mat); value = (VOIDP) mxCalloc(len, nctypelen(datatype)); status = ncvarget(cdfid, varid, start, count, value); status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr); Free((VOIDPP) & value); if (datatype == NC_CHAR) { plhs[0] = SetStr(mat); } else { plhs[0] = mat; } if (plhs[0] == NULL) { plhs[0] = mat; } plhs[1] = Int2Scalar(status); Free((VOIDPP) & intcount); Free((VOIDPP) & count); Free((VOIDPP) & start); break; case VARPUTG: name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); if (nrhs > 7) { if (datatype == NC_CHAR) { mat = SetStr(prhs[7]); } else { mat = prhs[7]; } if (mat == NULL) { mat = prhs[7]; } } else { if (datatype == NC_CHAR) { mat = SetStr(prhs[6]); } else { mat = prhs[6]; } if (mat == NULL) { mat = prhs[6]; } } pr = mxGetPr(mat); start = Mat2Long(prhs[3]); count = Mat2Long(prhs[4]); stride = Mat2Long(prhs[5]); imap = NULL; for (i = 0; i < ndims; i++) { if (count[i] == -1) { status = ncdiminq(cdfid, dim[i], name, & count[i]); count[i] -= start[i]; } } Free((VOIDPP) & name); Free((VOIDPP) & dim); len = 0; if (ndims > 0) { len = 1; for (i = 0; i < ndims; i++) { len *= count[i]; } } autoscale = (nrhs > 8 && Scalar2Int(prhs[8]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } value = (VOIDP) mxCalloc(len, nctypelen(datatype)); status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr); status = ncvarputg(cdfid, varid, start, count, stride, imap, value); Free((VOIDPP) & value); plhs[0] = Int2Scalar(status); Free((VOIDPP) & stride); Free((VOIDPP) & count); Free((VOIDPP) & start); break; case VARGETG: start = Mat2Long(prhs[3]); count = Mat2Long(prhs[4]); intcount = Mat2Int(prhs[4]); stride = Mat2Long(prhs[5]); imap = NULL; autoscale = (nrhs > 7 && Scalar2Int(prhs[7]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } name = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); dim = (int *) mxCalloc(MAX_NC_DIMS, sizeof(int)); status = ncvarinq(cdfid, varid, name, & datatype, & ndims, dim, & natts); datatype = RepairBadDataType(datatype); for (i = 0; i < ndims; i++) { if (count[i] == -1) { status = ncdiminq(cdfid, dim[i], name, & count[i]); count[i] -= start[i]; } } Free((VOIDPP) & name); Free((VOIDPP) & dim); m = 0; n = 0; if (ndims > 0) { m = count[0]; n = count[0]; for (i = 1; i < ndims; i++) { n *= count[i]; if (count[i] > 1) { m = count[i]; } } n /= m; } len = m * n; if (ndims < 2) { m = 1; n = len; } for (i = 0; i < ndims; i++) { intcount[i] = count[ndims-i-1]; /* Reverse order. */ } if (MEXCDF_4 || ndims < 2) { mat = mxCreateFull(m, n, mxREAL); /* mxCreateDoubleMatrix */ } # if MEXCDF_5 else { mat = mxCreateNumericArray(ndims, intcount, mxDOUBLE_CLASS, mxREAL); } # endif pr = mxGetPr(mat); value = (VOIDP) mxCalloc(len, nctypelen(datatype)); status = ncvargetg(cdfid, varid, start, count, stride, imap, value); status = Convert(opcode, datatype, len, value, scalefactor, addoffset, pr); Free((VOIDPP) & value); if (datatype == NC_CHAR) { plhs[0] = SetStr(mat); } else { plhs[0] = mat; } if (plhs[0] == NULL) { /* prhs[0] = mat; */ plhs[0] = mat; /* ZYDECO 24Jan2000 */ } plhs[1] = Int2Scalar(status); Free((VOIDPP) & stride); Free((VOIDPP) & intcount); Free((VOIDPP) & count); Free((VOIDPP) & start); break; case VARRENAME: name = Mat2Str(prhs[3]); status = ncvarrename(cdfid, varid, name); plhs[0] = Int2Scalar(status); Free((VOIDPP) & name); break; case VARCOPY: incdf = cdfid; invar = varid; outcdf = Scalar2Int(prhs[3]); outvar = -1; /* outvar = ncvarcopy(incdf, invar, outcdf); */ plhs[0] = Int2Scalar(outvar); plhs[1] = Int2Scalar((outvar >= 0) ? 0 : outvar); break; case ATTPUT: datatype = (nc_type) Parameter(prhs[4]); datatype = RepairBadDataType(datatype); if (datatype == NC_CHAR) { mat = SetNum(prhs[6]); } else { mat = prhs[6]; } if (mat == NULL) { mat = prhs[6]; } len = Scalar2Int(prhs[5]); if (len == -1) { len = Count(mat); } pr = mxGetPr(mat); value = (VOIDP) mxCalloc(len, nctypelen(datatype)); status = Convert(opcode, datatype, len, value, (DOUBLE) 1.0, (DOUBLE) 0.0, pr); status = ncattput(cdfid, varid, attname, datatype, len, value); if (value != NULL) { Free((VOIDPP) & value); } plhs[0] = Int2Scalar(status); Free((VOIDPP) & attname); break; case ATTINQ: status = ncattinq(cdfid, varid, attname, & datatype, & len); datatype = RepairBadDataType(datatype); plhs[0] = Int2Scalar((int) datatype); plhs[1] = Int2Scalar(len); plhs[2] = Int2Scalar(status); Free((VOIDPP) & attname); break; case ATTGET: status = ncattinq(cdfid, varid, attname, & datatype, & len); datatype = RepairBadDataType(datatype); value = (VOIDP) mxCalloc(len, nctypelen(datatype)); status = ncattget(cdfid, varid, attname, value); mat = mxCreateDoubleMatrix(1, len, mxREAL); pr = mxGetPr(mat); status = Convert(opcode, datatype, len, value, (DOUBLE) 1.0, (DOUBLE) 0.0, pr); if (value != NULL) { Free((VOIDPP) & value); } if (datatype == NC_CHAR) { plhs[0] = SetStr(mat); } else { plhs[0] = mat; } if (plhs[0] == NULL) { /* prhs[4] = mat; */ plhs[0] = mat; /* ZYDECO 24Jan2000 */ } plhs[1] = Int2Scalar(status); Free((VOIDPP) & attname); break; case ATTCOPY: incdf = cdfid; invar = varid; outcdf = Scalar2Int(prhs[4]); if (mxIsNumeric(prhs[5])) { outvar = Scalar2Int(prhs[2]); } else { name = Mat2Str(prhs[5]); outvar = ncvarid(cdfid, name); Free((VOIDPP) & name); } status = ncattcopy(incdf, invar, attname, outcdf, outvar); plhs[0] = Int2Scalar(status); Free((VOIDPP) & attname); break; case ATTNAME: attnum = Scalar2Int(prhs[3]); attname = (char *) mxCalloc(MAX_NC_NAME, sizeof(char)); status = ncattname(cdfid, varid, attnum, attname); plhs[0] = Str2Mat(attname); plhs[1] = Int2Scalar(status); Free((VOIDPP) & attname); break; case ATTRENAME: newname = Mat2Str(prhs[4]); status = ncattrename(cdfid, varid, attname, newname); plhs[0] = Int2Scalar(status); Free((VOIDPP) & attname); Free((VOIDPP) & newname); break; case ATTDEL: status = ncattdel(cdfid, varid, attname); plhs[0] = Int2Scalar(status); Free((VOIDPP) & attname); break; case RECPUT: recnum = Scalar2Long(prhs[2]); pr = mxGetPr(prhs[3]); autoscale = (nrhs > 4 && Scalar2Int(prhs[4]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } recvarids = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int)); recsizes = (long *) mxCalloc(MAX_VAR_DIMS, sizeof(long)); datap = (VOIDPP) mxCalloc(MAX_VAR_DIMS, sizeof(VOIDP)); status = ncrecinq(cdfid, & nrecvars, recvarids, recsizes); if (status == -1) { plhs[0] = Int2Scalar(status); break; } length = 0; n = 0; for (i = 0; i < nrecvars; i++) { ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL); datatype = RepairBadDataType(datatype); length += recsizes[i]; n += (recsizes[i] / nctypelen(datatype)); } if (Count(prhs[3]) < n) { status = -1; plhs[0] = Int2Scalar(status); break; } if ((value = (VOIDP) mxCalloc((int) length, sizeof(char))) == NULL) { status = -1; plhs[0] = Int2Scalar(status); break; } length = 0; p = value; for (i = 0; i < nrecvars; i++) { datap[i] = p; p += recsizes[i]; } p = (char *) value; pr = mxGetPr(prhs[3]); for (i = 0; i < nrecvars; i++) { ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL); datatype = RepairBadDataType(datatype); length = recsizes[i] / nctypelen(datatype); if (autoscale) { addoffset = Add_Offset(cdfid, recvarids[i]); scalefactor = Scale_Factor(cdfid, recvarids[i]); if (scalefactor == 0.0) { scalefactor = 1.0; } } Convert(opcode, datatype, length, (VOIDP) p, scalefactor, addoffset, pr); pr += length; p += recsizes[i]; } status = ncrecput(cdfid, recnum, datap); plhs[0] = Int2Scalar(status); Free ((VOIDPP) & value); Free ((VOIDPP) & datap); Free ((VOIDPP) & recsizes); Free ((VOIDPP) & recvarids); break; case RECGET: recnum = Scalar2Long(prhs[2]); autoscale = (nrhs > 3 && Scalar2Int(prhs[3]) != 0); if (!autoscale) { scalefactor = 1.0; addoffset = 0.0; } recvarids = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int)); recsizes = (long *) mxCalloc(MAX_VAR_DIMS, sizeof(long)); datap = (VOIDPP) mxCalloc(MAX_VAR_DIMS, sizeof(VOIDP)); status = ncrecinq(cdfid, & nrecvars, recvarids, recsizes); if (status == -1) { Free ((VOIDPP) & recsizes); Free ((VOIDPP) & recvarids); plhs[1] = Int2Scalar(status); break; } if (nrecvars == 0) { Free ((VOIDPP) & recsizes); Free ((VOIDPP) & recvarids); plhs[0] = mxCreateFull(0, 0, REAL); break; } length = 0; n = 0; for (i = 0; i < nrecvars; i++) { ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL); datatype = RepairBadDataType(datatype); length += recsizes[i]; n += (recsizes[i] / nctypelen(datatype)); } if ((value = (VOIDP) mxCalloc((int) length, sizeof(char))) == NULL) { status = -1; plhs[1] = Int2Scalar(status); break; } if (value == NULL) { status = -1; plhs[1] = Int2Scalar(status); break; } length = 0; p = value; for (i = 0; i < nrecvars; i++) { datap[i] = p; p += recsizes[i]; } if ((status = ncrecget(cdfid, recnum, datap)) == -1) { plhs[1] = Int2Scalar(status); break; } m = 1; plhs[0] = mxCreateFull(m, n, REAL); if (plhs[0] == NULL) { status = -1; plhs[1] = Int2Scalar(status); break; } pr = mxGetPr(plhs[0]); p = (char *) value; for (i = 0; i < nrecvars; i++) { status = ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL); datatype = RepairBadDataType(datatype); if (status == -1) { plhs[1] = Int2Scalar(status); break; } length = recsizes[i] / nctypelen(datatype); if (autoscale) { addoffset = Add_Offset(cdfid, recvarids[i]); scalefactor = Scale_Factor(cdfid, recvarids[i]); if (scalefactor == 0.0) { scalefactor = 1.0; } } Convert(opcode, datatype, length, (VOIDP) p, scalefactor, addoffset, pr); pr += length; p += recsizes[i]; } plhs[1] = Int2Scalar(status); Free ((VOIDPP) & value); Free ((VOIDPP) & datap); Free ((VOIDPP) & recsizes); Free ((VOIDPP) & recvarids); break; case RECINQ: recvarids = (int *) mxCalloc(MAX_VAR_DIMS, sizeof(int)); recsizes = (long *) mxCalloc(MAX_VAR_DIMS, sizeof(long)); status = ncrecinq(cdfid, & nrecvars, recvarids, recsizes); if (status != -1) { for (i = 0; i < nrecvars; i++) { ncvarinq(cdfid, recvarids[i], NULL, & datatype, NULL, NULL, NULL); datatype = RepairBadDataType(datatype); recsizes[i] /= nctypelen(datatype); } m = 1; n = nrecvars; plhs[0] = Int2Mat(recvarids, m, n); plhs[1] = Long2Mat(recsizes, m, n); } plhs[2] = Int2Scalar(status); Free ((VOIDPP) & recsizes); Free ((VOIDPP) & recvarids); break; case TYPELEN: datatype = (nc_type) Parameter(prhs[1]); len = nctypelen(datatype); plhs[0] = Int2Scalar(len); plhs[1] = Int2Scalar((len >= 0) ? 0 : 1); break; case SETFILL: fillmode = Scalar2Int(prhs[1]); status = ncsetfill(cdfid, fillmode); plhs[0] = Int2Scalar(status); plhs[1] = Int2Scalar(0); break; case SETOPTS: plhs[0] = Int2Scalar(ncopts); plhs[1] = Int2Scalar(0); ncopts = Scalar2Int(prhs[1]); break; case ERR: plhs[0] = Int2Scalar(ncerr); ncerr = 0; plhs[1] = Int2Scalar(0); break; case PARAMETER: if (nrhs > 1) { plhs[0] = Int2Scalar(Parameter(prhs[1])); plhs[1] = Int2Scalar(0); } else { i = 0; while (strcmp(parms[i].name, "NONE") != 0) { mexPrintf("%12d %s\n", parms[i].code, parms[i].name); i++; } plhs[0] = Int2Scalar(0); plhs[1] = Int2Scalar(-1); } break; default: break; } return; }
MNCAPI int minc_save_start(char *path, /* Path to the file */ int filetype, /* Date type as stored in the file */ long ct, /* Total length of time axis, in voxels */ long cz, /* Total length of Z axis, in voxels */ long cy, /* Total length of Y axis, in voxels */ long cx, /* Total length of X axis, in voxels */ double dt, /* Sample width along time axis, in seconds */ double dz, /* Sample width along Z axis, in mm */ double dy, /* Sample width along Y axis, in mm */ double dx, /* Sample width along X axis, in mm */ void *infoptr, /* Opaque file structure information */ const char *history) /* New history information */ { int fd; /* MINC file descriptor */ int dim_id[MI_S_NDIMS]; /* netCDF dimension ID array */ int var_ndims; /* Number of dimensions per variable */ int var_dims[MI_S_NDIMS]; /* Dimension ID's per variable */ int i, j; /* Generic loop counters */ int old_ncopts; /* For supressing fatal error messages */ struct file_info *p_file; /* For accessing the file structure */ struct var_info *p_var; struct att_info *p_att; int var_id; /* netCDF ID for variable */ char *signstr; nc_type nctype; old_ncopts =get_ncopts(); set_ncopts(0); fd = micreate(path, NC_CLOBBER); set_ncopts(old_ncopts); if (fd < 0) { return (MINC_STATUS_ERROR); } if (ct > 0) { dim_id[MI_S_T] = ncdimdef(fd, MItime, ct); micreate_std_variable(fd, MItime, NC_INT, 0, NULL); if (dt > 0.0) { miattputdbl(fd, ncvarid(fd, MItime), MIstep, dt); } } else { dim_id[MI_S_T] = -1; } if (cz > 0) { dim_id[MI_S_Z] = ncdimdef(fd, MIzspace, cz); micreate_std_variable(fd, MIzspace, NC_INT, 0, NULL); if (dz > 0.0) { miattputdbl(fd, ncvarid(fd, MIzspace), MIstep, dz); } } else { dim_id[MI_S_Z] = -1; } if (cy > 0) { dim_id[MI_S_Y] = ncdimdef(fd, MIyspace, cy); micreate_std_variable(fd, MIyspace, NC_INT, 0, NULL); if (dy > 0.0) { miattputdbl(fd, ncvarid(fd, MIyspace), MIstep, dy); } } else { return (MINC_STATUS_ERROR); /* Must define Y */ } if (cx > 0) { dim_id[MI_S_X] = ncdimdef(fd, MIxspace, cx); micreate_std_variable(fd, MIxspace, NC_INT, 0, NULL); if (dx > 0.0) { miattputdbl(fd, ncvarid(fd, MIxspace), MIstep, dx); } } else { return (MINC_STATUS_ERROR); /* Must define X */ } /* The var_dims[] array is the array of actual dimension ID's to * be used in defining the image variables. Here I set it up by * copying all valid dimension ID's from the dim_id[] array. */ var_ndims = 0; for (i = 0; i < MI_S_NDIMS; i++) { if (dim_id[i] >= 0) { var_dims[var_ndims] = dim_id[i]; var_ndims++; } } minc_simple_to_nc_type(filetype, &nctype, &signstr); /* Create the image variable with the standard * dimension order, and the same type as the template * file. */ micreate_std_variable(fd, MIimage, nctype, var_ndims, var_dims); micreate_std_variable(fd, MIimagemin, NC_DOUBLE, 1, var_dims); micreate_std_variable(fd, MIimagemax, NC_DOUBLE, 1, var_dims); /* Copy information from the infoptr to the output. */ if ((p_file = infoptr) != NULL) { old_ncopts =get_ncopts(); set_ncopts(0); for (i = 0; i < p_file->file_natts; i++) { p_att = &p_file->file_atts[i]; if (strcmp(p_att->att_name, "ident") != 0) { ncattput(fd, NC_GLOBAL, p_att->att_name, p_att->att_type, p_att->att_len, p_att->att_val); } } for (i = 0; i < p_file->file_nvars; i++) { p_var = &p_file->file_vars[i]; if ((var_id = ncvarid(fd, p_var->var_name)) < 0) { var_id = ncvardef(fd, p_var->var_name, p_var->var_type, p_var->var_ndims, p_var->var_dims); } for (j = 0; j < p_var->var_natts; j++) { p_att = &p_var->var_atts[j]; ncattput(fd, var_id, p_att->att_name, p_att->att_type, p_att->att_len, p_att->att_val); } } set_ncopts(old_ncopts); } miattputstr(fd, ncvarid(fd, MIimage), MIcomplete, MI_FALSE); miattputstr(fd, ncvarid(fd, MIimage), MIsigntype, signstr); miappend_history(fd, history); ncendef(fd); return fd; }
int ex_put_init (int exoid, const char *title, int num_dim, int num_nodes, int num_elem, int num_elem_blk, int num_node_sets, int num_side_sets) { int numdimdim, numnoddim, elblkdim, nsetdim, ssetdim, strdim, dim[2], varid; #if 0 /* used for header size calculations which are turned off for now */ int header_size, fixed_var_size, iows; #endif char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ if ((ncdimid (exoid, DIM_NUM_DIM)) != -1) { exerrval = EX_MSG; sprintf(errmsg, "Error: initialization already done for file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } /* put file into define mode */ if (ncredef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to put file id %d into define mode", exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } /* define some attributes... */ if (ncattput (exoid, NC_GLOBAL, (const char*) ATT_TITLE, NC_CHAR, strlen(title)+1, (void *)title) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define title attribute to file id %d", exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* ...and some dimensions... */ if ((numdimdim = ncdimdef (exoid, DIM_NUM_DIM, (long)num_dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of dimensions in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* * Need to handle "empty file" that may be the result of a strange * load balance or some other strange run. Note that if num_node * == 0, then num_elem must be zero since you cannot have elements * with no nodes. It *is* permissible to have zero elements with * non-zero node count. */ if (num_nodes > 0) { if ((numnoddim = ncdimdef (exoid, DIM_NUM_NODES, (long)num_nodes)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of nodes in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (num_elem > 0) { if (num_nodes <= 0) { exerrval = EX_MSG; sprintf(errmsg, "Error: Cannot have non-zero element count if node count is zero.in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } if ((ncdimdef (exoid, DIM_NUM_ELEM, (long)num_elem)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of elements in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* Can have nonzero num_elem_blk even if num_elem == 0 */ if (num_elem_blk > 0) { if ((elblkdim = ncdimdef (exoid, DIM_NUM_EL_BLK, (long)num_elem_blk)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of element blocks in file id %d", exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* ...and some variables */ /* element block id status array */ dim[0] = elblkdim; if ((varid = ncvardef (exoid, VAR_STAT_EL_BLK, NC_LONG, 1, dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define element block status array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } #if 0 /* store property name as attribute of property array variable */ if ((ncattput (exoid, varid, ATT_PROP_NAME, NC_CHAR, 7, "STATUS")) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element block property name %s in file id %d", "STATUS",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } #endif /* element block id array */ if ((varid = ncvardef (exoid, VAR_ID_EL_BLK, NC_LONG, 1, dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define element block id array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store property name as attribute of property array variable */ if ((ncattput (exoid, varid, ATT_PROP_NAME, NC_CHAR, 3, "ID")) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store element block property name %s in file id %d", "ID",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } } /* node set id array: */ nsetdim = 0; if (num_node_sets > 0) { if ((nsetdim = ncdimdef (exoid, DIM_NUM_NS, (long)num_node_sets)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of node sets in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* node set id status array: */ dim[0] = nsetdim; if ((varid = ncvardef (exoid, VAR_NS_STAT, NC_LONG, 1, dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create node sets status array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } #if 0 /* store property name as attribute of property array variable */ if ((ncattput (exoid, varid, ATT_PROP_NAME, NC_CHAR, 7, "STATUS")) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store node set property name %s in file id %d", "ID",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } #endif /* node set id array: */ dim[0] = nsetdim; if ((varid = ncvardef (exoid, VAR_NS_IDS, NC_LONG, 1, dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to create node sets property array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store property name as attribute of property array variable */ if ((ncattput (exoid, varid, ATT_PROP_NAME, NC_CHAR, 3, "ID")) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store node set property name %s in file id %d", "ID",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } } /* side set id array: */ ssetdim = 0; if (num_side_sets > 0) { if ((ssetdim = ncdimdef (exoid, DIM_NUM_SS, (long)num_side_sets)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define number of side sets in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* side set id status array: */ dim[0] = ssetdim; if ((varid = ncvardef (exoid, VAR_SS_STAT, NC_LONG, 1, dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define side set status in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } #if 0 /* store property name as attribute of property array variable */ if ((ncattput (exoid, varid, ATT_PROP_NAME, NC_CHAR, 7, "STATUS")) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store side set property name %s in file id %d", "ID",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } #endif /* side set id array: */ if ((varid = ncvardef (exoid, VAR_SS_IDS, NC_LONG, 1, dim)) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define side set property in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* store property name as attribute of property array variable */ if ((ncattput (exoid, varid, ATT_PROP_NAME, NC_CHAR, 3, "ID")) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to store side set property name %s in file id %d", "ID",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } } /* * To reduce the maximum dataset sizes, the storage of the nodal * coordinates and the nodal variables was changed from a single * dataset to a dataset per component or variable. However, we * want to maintain some form of compatability with the old * exodusII version. It is easy to do this on read; however, we * also want to be able to store in the old format using the new * library. * * The mode is set in the ex_create call. The setting can be checked * via the ATT_FILESIZE attribute in the file (1=large, * 0=normal). Also handle old files that do not contain this * attribute. */ if (num_nodes > 0) { if (ex_large_model(exoid) == 1) { /* node coordinate arrays -- separate storage... */ /* * Check that storage required for coordinates is less * than 2GB which is maximum size permitted by netcdf * (in large file mode). 1<<29 == max number of integer items. */ int shift = nc_flt_code(exoid) == NC_DOUBLE ? 28 : 29; if (num_nodes > (1<<shift)) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Size to store nodal coordinates exceeds 2GB in file id %d", exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } dim[0] = numnoddim; if (num_dim > 0) { if (ncvardef (exoid, VAR_COORD_X, nc_flt_code(exoid), 1, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define node x coordinate array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (num_dim > 1) { if (ncvardef (exoid, VAR_COORD_Y, nc_flt_code(exoid), 1, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define node y coordinate array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } if (num_dim > 2) { if (ncvardef (exoid, VAR_COORD_Z, nc_flt_code(exoid), 1, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define node z coordinate array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } else { /* node coordinate arrays: -- all stored together (old method) */ dim[0] = numdimdim; dim[1] = numnoddim; if (ncvardef (exoid, VAR_COORD, nc_flt_code(exoid), 2, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define node coordinate array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } } /* inquire previously defined dimensions */ if ((strdim = ncdimid (exoid, DIM_STR)) < 0) { exerrval = ncerr; sprintf(errmsg, "Error: failed to get string length in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* coordinate names array */ dim[0] = numdimdim; dim[1] = strdim; if (ncvardef (exoid, VAR_NAME_COOR, NC_CHAR, 2, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define coordinate name array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } /* Element block names... */ if (num_elem_blk > 0) { dim[0] = elblkdim; dim[1] = strdim; if (ncvardef (exoid, VAR_NAME_EL_BLK, NC_CHAR, 2, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define element block name array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* Nodeset names... */ if (num_node_sets > 0) { dim[0] = nsetdim; dim[1] = strdim; if (ncvardef (exoid, VAR_NAME_NS, NC_CHAR, 2, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define nodeset name array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* Sideset names... */ if (num_side_sets > 0) { dim[0] = ssetdim; dim[1] = strdim; if (ncvardef (exoid, VAR_NAME_SS, NC_CHAR, 2, dim) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to define sideset name array in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); goto error_ret; /* exit define mode and return */ } } /* leave define mode */ #if 1 if (ncendef (exoid) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to complete variable definitions in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } #else /* estimate (guess) size of header of netCDF file */ header_size = 1200 + num_elem_blk * 800 + num_node_sets * 220 + num_side_sets * 300; if (header_size > MAX_HEADER_SIZE) header_size = MAX_HEADER_SIZE; /* estimate (guess) size of fixed size variable section of netCDF file */ if (nc_flt_code(exoid) == NC_DOUBLE) iows = 8; else iows = 4; fixed_var_size = num_dim * num_nodes * iows + num_nodes * sizeof(int) + num_elem * 16 * sizeof(int) + num_elem_blk * sizeof(int) + num_node_sets * num_nodes/100 * sizeof(int) + num_node_sets * num_nodes/100 * iows + num_node_sets * sizeof(int) + num_side_sets * num_elem/100 * 2 * sizeof(int) + num_side_sets * num_elem/100 * iows + num_side_sets * sizeof(int); /* With netcdf-3.4, this produces very large files on the * SGI. Also with netcdf-3.5beta3 */ /* * This is also causing other problems on other systems .. disable for now */ if (nc__enddef (exoid, header_size, NC_ALIGN_CHUNK, fixed_var_size, NC_ALIGN_CHUNK) == -1) { exerrval = ncerr; sprintf(errmsg, "Error: failed to complete variable definitions in file id %d",exoid); ex_err("ex_put_init",errmsg,exerrval); return (EX_FATAL); } #endif return (EX_NOERR); /* Fatal error: exit definition mode and return */ error_ret: if (ncendef (exoid) == -1) /* exit define mode */ { sprintf(errmsg, "Error: failed to complete definition for file id %d", exoid); ex_err("ex_put_init",errmsg,exerrval); } return (EX_FATAL); }
/* Open an input netCDF file and get some information about it */ int process_ncinfile(char *ncname, unsigned char appendnc, int outncfid, char *outncname, int *nfiles, unsigned char verbose) { struct fileinfo ncinfile; /* Information about an input netCDF file */ int nfiles2; /* Number of files in the decomposed domain */ int d, v, n; /* Loop variables */ int dimid; /* ID of a dimension */ int decomp[4]; /* "domain_decomposition" information */ char attname[MAX_NC_NAME]; /* Name of a global or variable attribute */ unsigned char ncinfileerror=0; /* Were there any file errors? */ /* Open an input netCDF file; return if not openable - possibly IEEE */ if ((ncinfile.ncfid=ncopen(ncname,NC_NOWRITE))==(-1)) return(2); /* Determine the number of files in the decomposed domain */ if (ncattget(ncinfile.ncfid,NC_GLOBAL,"NumFilesInSet", (void *)&nfiles2)==(-1)) { if (*nfiles==1) { fprintf(stderr,"Error: missing the \"NumFilesInSet\" global attribute!\n"); return(1); } else if (*nfiles==(-1)) { fprintf(stderr,"Warning: missing the \"NumFilesInSet\" global attribute.\n"); } } *nfiles=nfiles2; /* Get some general information about the input netCDF file */ if (ncinquire(ncinfile.ncfid,&(ncinfile.ndims),&(ncinfile.nvars), &(ncinfile.ngatts),&(ncinfile.recdim))==(-1)) { fprintf(stderr,"Error: cannot read the file's metadata!\n"); ncclose(ncinfile.ncfid); return(1); } /* Get some information about the dimensions */ for (d=0; d < ncinfile.ndims; d++) { if ((ncdiminq(ncinfile.ncfid,d,ncinfile.dimname[d], &(ncinfile.dimsize[d])))==(-1)) { fprintf(stderr,"Error: cannot read dimension #%d's metadata!\n",d); ncclose(ncinfile.ncfid); return(1); } ncinfile.dimfullsize[d]=ncinfile.dimsize[d]; ncinfile.dimstart[d]=1; ncinfile.dimend[d]=(-1); } /* Get some information about the variables */ for (v=0; v < ncinfile.nvars; v++) { if ((ncvarinq(ncinfile.ncfid,v,ncinfile.varname[v], &(ncinfile.datatype[v]),&(ncinfile.varndims[v]), ncinfile.vardim[v],&(ncinfile.natts[v])))==(-1)) { fprintf(stderr,"Error: cannot read variable #%d's metadata!\n",v); ncclose(ncinfile.ncfid); return(1); } /* If the variable is also a dimension then get decomposition info */ if ((dimid=ncdimid(ncinfile.ncfid,ncinfile.varname[v]))!=(-1)) { if (ncattget(ncinfile.ncfid,v,"domain_decomposition", (void *)decomp)!=(-1)) { ncinfile.dimfullsize[dimid]=decomp[1]-decomp[0]+1; ncinfile.dimstart[dimid]=decomp[2]-(decomp[0]-1); ncinfile.dimend[dimid]=decomp[3]-(decomp[0]-1); } else { ncinfile.dimfullsize[dimid]=ncinfile.dimsize[dimid]; ncinfile.dimstart[dimid]=1; ncinfile.dimend[dimid]=(-1); } } } #if DEBUG==1 print_debug(&ncinfile,verbose); #endif /* If the output netCDF file was just created then define its structure */ if (!appendnc) { #if DEBUG==1 printf("Creating output netCDF file... \"%s\"\n",outncname); #endif /* Define the dimensions */ for (d=0; d < ncinfile.ndims; d++) { if (d==ncinfile.recdim) ncdimdef(outncfid,ncinfile.dimname[d],NC_UNLIMITED); else ncdimdef(outncfid,ncinfile.dimname[d],ncinfile.dimfullsize[d]); } /* Define the variables and copy their attributes */ for (v=0; v < ncinfile.nvars; v++) { ncvardef(outncfid,ncinfile.varname[v],ncinfile.datatype[v], ncinfile.varndims[v],ncinfile.vardim[v]); for (n=0; n < ncinfile.natts[v]; n++) { ncattname(ncinfile.ncfid,v,n,attname); if (!strcmp(attname,"domain_decomposition")) continue; else { if (ncattcopy(ncinfile.ncfid,v,attname,outncfid,v)==(-1)) { fprintf(stderr,"Error: cannot copy variable \"%s\"'s attributes!\n", ncinfile.varname[v]); return(1); } } } } /* Copy the global attributes */ for (n=0; n < ncinfile.ngatts; n++) { ncattname(ncinfile.ncfid,NC_GLOBAL,n,attname); if (!strcmp(attname,"NumFilesInSet")) continue; else if (!strcmp(attname,"filename")) ncattput(outncfid,NC_GLOBAL,attname,NC_CHAR,strlen(outncname), (void *)outncname); else { if (ncattcopy(ncinfile.ncfid,NC_GLOBAL,attname,outncfid, NC_GLOBAL)==(-1)) { fprintf(stderr,"Error: cannot copy the file's global attributes!\n"); return(1); } } } /* Definitions done */ ncendef(outncfid); } /* Copy all the data values of the dimensions and variables */ ncinfileerror=copy_nc_data(&ncinfile,outncfid,appendnc,verbose); /* Done */ ncclose(ncinfile.ncfid); return(ncinfileerror); }
int upet_to_minc(char *hdr_fname, char *img_fname, char *out_fname, char *prog_name) { char *line_ptr; char line_buf[1024]; char *val_ptr; int in_header; double dbl_tmp; int int_tmp; struct conversion_info ci; struct keywd_entry *ke_ptr; int is_known; char *argv_tmp[5]; char *out_history; ci.hdr_fp = fopen(hdr_fname, "r"); /* Text file */ if (ci.hdr_fp == NULL) { perror(hdr_fname); return (-1); } ci.img_fp = fopen(img_fname, "rb"); /* Binary file */ if (ci.img_fp == NULL) { perror(img_fname); return (-1); } ci.mnc_fd = micreate(out_fname, NC_NOCLOBBER); if (ci.mnc_fd < 0) { perror(out_fname); return (-1); } ci.frame_zero = -1; /* Initial frame is -1 until set. */ /* Define the basic MINC group variables. */ micreate_group_variable(ci.mnc_fd, MIstudy); micreate_group_variable(ci.mnc_fd, MIacquisition); micreate_group_variable(ci.mnc_fd, MIpatient); ncvardef(ci.mnc_fd, "micropet", NC_SHORT, 0, NULL); /* Fake the history here */ argv_tmp[0] = prog_name; argv_tmp[1] = VERSIONSTR; argv_tmp[2] = hdr_fname; argv_tmp[3] = img_fname; argv_tmp[4] = out_fname; out_history = time_stamp(5, argv_tmp); miattputstr(ci.mnc_fd, NC_GLOBAL, MIhistory, out_history); free(out_history); in_header = 1; ci.frame_nbytes = 1; ci.frame_nvoxels = 1; /* When we read voxels, we need COMBINED_SCALE_FACTOR() to have a sane * value for all modalities. Set defaults for these in case the modality * does not define one of these factors. For example, a CT (modality 2) * will not define isotope_branching_fraction or calibration_factor. */ ci.scale_factor = 1.0; ci.calibration_factor = 1.0; ci.isotope_branching_fraction = 1.0; /* Collect the headers */ while (fgets(line_buf, sizeof(line_buf), ci.hdr_fp) != NULL) { if (line_buf[0] == '#') /* */ continue; line_ptr = line_buf; while (!isspace(*line_ptr)) { line_ptr++; } *line_ptr++ = '\0'; val_ptr = line_ptr; while (*line_ptr != '\n' && *line_ptr != '\r' && *line_ptr != '\0') { line_ptr++; } *line_ptr = '\0'; is_known = 0; if (in_header) { if (*val_ptr != '\0') { /* Save the raw attribute into the file */ ncattput(ci.mnc_fd, ncvarid(ci.mnc_fd, "micropet"), line_buf, NC_CHAR, strlen(val_ptr), val_ptr); } for (ke_ptr = vol_atts; ke_ptr->upet_kwd != NULL; ke_ptr++) { if (!strcmp(ke_ptr->upet_kwd, line_buf)) { is_known = 1; if (ke_ptr->func != NULL) { (*ke_ptr->func)(&ci, val_ptr, ke_ptr->mnc_var, ke_ptr->mnc_att); } else if (ke_ptr->mnc_var != NULL && ke_ptr->mnc_att != NULL) { /* Interpret based upon type */ switch (ke_ptr->upet_type) { case UPET_TYPE_INT: int_tmp = atoi(val_ptr); miattputint(ci.mnc_fd, ncvarid(ci.mnc_fd, ke_ptr->mnc_var), ke_ptr->mnc_att, int_tmp); break; case UPET_TYPE_REAL: dbl_tmp = atof(val_ptr); miattputdbl(ci.mnc_fd, ncvarid(ci.mnc_fd, ke_ptr->mnc_var), ke_ptr->mnc_att, dbl_tmp); break; case UPET_TYPE_STR: miattputstr(ci.mnc_fd, ncvarid(ci.mnc_fd, ke_ptr->mnc_var), ke_ptr->mnc_att, val_ptr); break; } } break; } } } else { /* Not in the header any longer */ for (ke_ptr = frm_atts; ke_ptr->upet_kwd != NULL; ke_ptr++) { if (!strcmp(ke_ptr->upet_kwd, line_buf)) { is_known = 1; if (ke_ptr->func != NULL) { (*ke_ptr->func)(&ci, val_ptr, ke_ptr->mnc_var, ke_ptr->mnc_att); } break; } } } if (!is_known) { if (!strcmp(line_buf, "end_of_header")) { if (in_header) { in_header = 0; copy_init(&ci); } else { copy_frame(&ci); } } else { message(MSG_WARNING, "Unrecognized keyword %s\n", line_buf); } } } fclose(ci.hdr_fp); fclose(ci.img_fp); miclose(ci.mnc_fd); return (0); }