int CNetCdfInterface::ncGetVaraType(int ncid, int varid, const StdSize* start, const StdSize* count, float* data) { return nc_get_vara_float(ncid, varid, start, count, data); }
void readHDstep(char ncfile[],int nxiu,int nxiv,int netau,int netav,int nl,int nt, int hdstep,int lev,float *&Uo,float *&Vo) { // int status; int ncid; int ndims,nvars,ngatts,unlimdimid; int uu_id,vv_id; printf("Reading HD step: %d ...",hdstep); size_t startl[]= {hdstep-1,lev,0,0}; size_t countlu[]= {1,1,netau,nxiu}; size_t countlv[]= {1,1,netav,nxiv}; static ptrdiff_t stridel[]= {1,1,1,1}; //Open NC file status =nc_open(ncfile,0,&ncid); if (status != NC_NOERR) handle_error(status); status = nc_inq_varid (ncid, "u", &uu_id); if (status != NC_NOERR) handle_error(status); status = nc_inq_varid (ncid, "v", &vv_id); if (status != NC_NOERR) handle_error(status); status = nc_get_vara_float(ncid,uu_id,startl,countlu,Uo); if (status != NC_NOERR) handle_error(status); status = nc_get_vara_float(ncid,vv_id,startl,countlv,Vo); if (status != NC_NOERR) handle_error(status); //Set land flag to 0.0m/s to allow particle to stick to the coast for (int i=0; i<nxiu; i++) { for (int j=0; j<netau; j++) { if (Uo[i+j*nxiu]>10.0f) { Uo[i+j*nxiu]=0.0f; } } } for (int i=0; i<nxiv; i++) { for (int j=0; j<netav; j++) { if (Vo[i+j*nxiv]>10.0f) { Vo[i+j*nxiv]=0.0f; } } } //printf("U[0][0]=%f\n",Uo[0]); status = nc_close(ncid); printf("...done\n"); }
int ex_get_var(int exoid, int time_step, ex_entity_type var_type, int var_index, ex_entity_id obj_id, int64_t num_entry_this_obj, void *var_vals) { int status; int varid, obj_id_ndx; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; ex_check_valid_file_id(exoid); if (var_type == EX_NODAL) { /* FIXME: Special case: ignore obj_id, possible large_file complications, * etc. */ return ex_get_nodal_var_int(exoid, time_step, var_index, num_entry_this_obj, var_vals); } if (var_type == EX_GLOBAL) { /* FIXME: Special case: all vars stored in 2-D single array. */ return ex_get_glob_vars_int(exoid, time_step, num_entry_this_obj, var_vals); } exerrval = 0; /* clear error code */ /* Determine index of obj_id in VAR_ID_EL_BLK array */ obj_id_ndx = ex_id_lkup(exoid, var_type, obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no %s variables for NULL block %" PRId64 " in file id %d", ex_name_of_object(var_type), obj_id, exoid); ex_err("ex_get_var", errmsg, EX_NULLENTITY); return (EX_WARN); } snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s id %" PRId64 " in id variable in file id %d", ex_name_of_object(var_type), obj_id, exoid); ex_err("ex_get_var", errmsg, exerrval); return (EX_FATAL); } /* inquire previously defined variable */ if ((status = nc_inq_varid(exoid, ex_name_var_of_object(var_type, var_index, obj_id_ndx), &varid)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s %" PRId64 " var %d in file id %d", ex_name_of_object(var_type), obj_id, var_index, exoid); ex_err("ex_get_var", errmsg, exerrval); return (EX_FATAL); } /* Verify that time_step is within bounds */ #ifndef NDEBUG { int num_time_steps = ex_inquire_int(exoid, EX_INQ_TIME); if (time_step <= 0 || time_step > num_time_steps) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: time_step is out-of-range. Value = %d, valid " "range is 1 to %d in file id %d", time_step, num_time_steps, exoid); ex_err("ex_get_var", errmsg, EX_BADPARAM); return (EX_FATAL); } } #endif /* read values of element variable */ start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_entry_this_obj; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s %" PRId64 " variable %d in file id %d", ex_name_of_object(var_type), obj_id, var_index, exoid); ex_err("ex_get_var", errmsg, exerrval); return (EX_FATAL); } return (EX_NOERR); }
/* * Read a hypercube of numeric values from a netCDF variable of an open * netCDF file. */ static void c_ncvgt( int ncid, /* netCDF ID */ int varid, /* variable ID */ const size_t* start, /* multidimensional index of hypercube corner */ const size_t* count, /* multidimensional hypercube edge lengths */ void* value, /* block of data values to be read */ int* rcode /* returned error code */ ) { int status; nc_type datatype; if ((status = nc_inq_vartype(ncid, varid, &datatype)) == 0) { switch (datatype) { case NC_CHAR: status = NC_ECHAR; break; case NC_BYTE: # if NF_INT1_IS_C_SIGNED_CHAR status = nc_get_vara_schar(ncid, varid, start, count, (signed char*)value); # elif NF_INT1_IS_C_SHORT status = nc_get_vara_short(ncid, varid, start, count, (short*)value); # elif NF_INT1_IS_C_INT status = nc_get_vara_int(ncid, varid, start, count, (int*)value); # elif NF_INT1_IS_C_LONG status = nc_get_vara_long(ncid, varid, start, count, (long*)value); # endif break; case NC_SHORT: # if NF_INT2_IS_C_SHORT status = nc_get_vara_short(ncid, varid, start, count, (short*)value); # elif NF_INT2_IS_C_INT status = nc_get_vara_int(ncid, varid, start, count, (int*)value); # elif NF_INT2_IS_C_LONG status = nc_get_vara_long(ncid, varid, start, count, (long*)value); # endif break; case NC_INT: # if NF_INT_IS_C_INT status = nc_get_vara_int(ncid, varid, start, count, (int*)value); # elif NF_INT_IS_C_LONG status = nc_get_vara_long(ncid, varid, start, count, (long*)value); # endif break; case NC_FLOAT: # if NF_REAL_IS_C_FLOAT status = nc_get_vara_float(ncid, varid, start, count, (float*)value); # elif NF_REAL_IS_C_DOUBLE status = nc_get_vara_double(ncid, varid, start, count, (double*)value); # endif break; case NC_DOUBLE: # if NF_DOUBLEPRECISION_IS_C_FLOAT status = nc_get_vara_float(ncid, varid, start, count, (float*)value); # elif NF_DOUBLEPRECISION_IS_C_DOUBLE status = nc_get_vara_double(ncid, varid, start, count, (double*)value); # endif break; } } if (status == 0) *rcode = 0; else { nc_advise("NCVGT", status, ""); *rcode = ncerr; } }
int main() { int ncid, varid; int retval,i; size_t start[RANK]; size_t count[RANK]; char URL[4096]; const char* svc = NULL; /* Find Test Server */ svc = nc_findtestserver("dts",0); if(svc == NULL) { fprintf(stderr,"Cannot locate test server\n"); exit(1); } printf("Using test server: %s\n",svc); strncpy(URL,svc,sizeof(URL)); strlcat(URL,DTSTEST,sizeof(URL)); memset((void*)target,0,sizeof(target)); if((retval = nc_open(URL, NC_NOWRITE, &ncid))) ERR(retval); if((retval = nc_inq_varid(ncid, NCVAR, &varid))) ERR(retval); printf("test 1: Read the whole variable\n"); memcpy(start,start0,sizeof(start0)); memcpy(count,count0,sizeof(count0)); if((retval = nc_get_vara_float(ncid,varid,start,count,(float*)target))) ERR(retval); if(!check(start,count)) goto fail; printf("test 2: Read the top half\n"); memcpy(start,start0,sizeof(start0)); memcpy(count,count0,sizeof(count0)); start[0] += count0[0]/2; count[0] = count0[0] - start[0]; if((retval = nc_get_vara_float(ncid,varid,start,count,(float*)target))) ERR(retval); if(!check(start,count)) goto fail; printf("test 3: Read the slice with X=1\n"); memcpy(start,start0,sizeof(start0)); memcpy(count,count0,sizeof(count0)); start[0] = 1; count[0] = 1; if((retval = nc_get_vara_float(ncid,varid,start,count,(float*)target))) ERR(retval); if(!check(start,count)) goto fail; if((retval = nc_close(ncid))) ERR(retval); printf("*** PASS\n"); return 0; fail: printf("*** FAIL\n"); return 1; }
int ex_get_nodal_var_time (int exoid, int nodal_var_index, int node_number, int beg_time_step, int end_time_step, void *nodal_var_vals) { int status; int varid; size_t start[3], count[3]; float fdum; char *cdum = 0; char errmsg[MAX_ERR_LENGTH]; /* inquire previously defined variable */ if (end_time_step < 0) { /* user is requesting the maximum time step; we find this out using the * database inquire function to get the number of time steps; the ending * time step number is 1 less due to 0 based array indexing in C */ if ((status = ex_inquire (exoid, EX_INQ_TIME, &end_time_step, &fdum, cdum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of time steps in file id %d", exoid); ex_err("ex_get_nodal_var_time",errmsg,exerrval); return (EX_FATAL); } } end_time_step--; if (ex_large_model(exoid) == 0) { /* read values of the nodal variable; * assume node number is 1-based (first node is numbered 1); adjust * so it is 0-based */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --beg_time_step; start[1] = --nodal_var_index; start[2] = --node_number; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; count[2] = 1; } else { if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } /* read values of the nodal variable; * assume node number is 1-based (first node is numbered 1); adjust * so it is 0-based */ start[0] = --beg_time_step; start[1] = --node_number; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; } if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get nodal variables in file id %d", exoid); ex_err("ex_get_nodal_var_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
NcValues* NcVar::get_rec(NcDim* rdim, long slice) { int idx = dim_to_index(rdim); long size = num_dims(); size_t* start = new size_t[size]; long* startl = new long[size]; for (int i=1; i < size ; i++) { start[i] = 0; startl[i] = 0; } start[idx] = slice; startl[idx] = slice; NcBool result = set_cur(startl); if (! result ) { delete [] start; delete [] startl; return 0; } long* edgel = edges(); size_t* edge = new size_t[size]; for (int i=1; i < size ; i++) { edge[i] = edgel[i]; } edge[idx] = 1; edgel[idx] = 1; NcValues* valp = get_space(rec_size(rdim)); int status; switch (type()) { case ncFloat: status = NcError::set_err( nc_get_vara_float(the_file->id(), the_id, start, edge, (float *)valp->base()) ); break; case ncDouble: status = NcError::set_err( nc_get_vara_double(the_file->id(), the_id, start, edge, (double *)valp->base()) ); break; case ncInt: status = NcError::set_err( nc_get_vara_int(the_file->id(), the_id, start, edge, (int *)valp->base()) ); break; case ncShort: status = NcError::set_err( nc_get_vara_short(the_file->id(), the_id, start, edge, (short *)valp->base()) ); break; case ncByte: status = NcError::set_err( nc_get_vara_schar(the_file->id(), the_id, start, edge, (signed char *)valp->base()) ); break; case ncChar: status = NcError::set_err( nc_get_vara_text(the_file->id(), the_id, start, edge, (char *)valp->base()) ); break; case ncNoType: default: return 0; } delete [] start; delete [] startl; delete [] edge; delete [] edgel; if (status != NC_NOERR) { delete valp; return 0; } return valp; }
int ex_get_partial_var( int exoid, int time_step, ex_entity_type var_type, int var_index, ex_entity_id obj_id, int64_t start_index, int64_t num_entities, void* var_vals ) { int status = 0; int varid, obj_id_ndx; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; if (num_entities == 0) return status; if (var_type == EX_NODAL) { /* FIXME: Special case: ignore obj_id, possible large_file complications, etc. */ return ex_get_partial_nodal_var( exoid, time_step, var_index, start_index, num_entities, var_vals ); } else if (var_type == EX_GLOBAL) { /* FIXME: Special case: all vars stored in 2-D single array. */ return ex_get_glob_vars( exoid, time_step, num_entities, var_vals ); } exerrval = 0; /* clear error code */ /* Determine index of obj_id in VAR_ID_EL_BLK array */ obj_id_ndx = ex_id_lkup(exoid,var_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no %s variables for NULL block %"PRId64" in file id %d", ex_name_of_object(var_type), obj_id,exoid); ex_err("ex_get_partial_var",errmsg,EX_NULLENTITY); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate %s id %"PRId64" in id variable in file id %d", ex_name_of_object(var_type), obj_id, exoid); ex_err("ex_get_partial_var",errmsg,exerrval); return (EX_FATAL); } } /* inquire previously defined variable */ if((status = nc_inq_varid(exoid, ex_name_var_of_object(var_type,var_index, obj_id_ndx), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s %"PRId64" var %d in file id %d", ex_name_of_object(var_type),obj_id,var_index,exoid); ex_err("ex_get_partial_var",errmsg,exerrval); return (EX_FATAL); } /* read values of element variable */ start[0] = --time_step; start[1] = start_index-1; count[0] = 1; count[1] = num_entities; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s %"PRId64" variable %d in file id %d", ex_name_of_object(var_type), obj_id, var_index,exoid); ex_err("ex_get_partial_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
int ex_get_partial_attr( int exoid, ex_entity_type obj_type, ex_entity_id obj_id, int64_t start_num, int64_t num_ent, void* attrib ) { int status; int attrid, obj_id_ndx; int temp; size_t num_entries_this_obj, num_attr; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; const char* dnumobjent; const char* dnumobjatt; const char* vattrbname; exerrval = 0; /* clear error code */ if (num_ent == 0) return 0; /* Determine index of obj_id in vobjids array */ if (obj_type != EX_NODAL) { obj_id_ndx = ex_id_lkup(exoid,obj_type,obj_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: no attributes found for NULL %s %"PRId64" in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_partial_attr",errmsg,EX_NULLENTITY); return (EX_WARN); /* no attributes for this object */ } else { sprintf(errmsg, "Warning: failed to locate %s id%"PRId64" in id array in file id %d", ex_name_of_object(obj_type),obj_id, exoid); ex_err("ex_get_partial_attr",errmsg,exerrval); return (EX_WARN); } } } switch (obj_type) { case EX_SIDE_SET: dnumobjent = DIM_NUM_SIDE_SS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_SS(obj_id_ndx); vattrbname = VAR_SSATTRIB(obj_id_ndx); break; case EX_NODE_SET: dnumobjent = DIM_NUM_NOD_NS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_NS(obj_id_ndx); vattrbname = VAR_NSATTRIB(obj_id_ndx); break; case EX_EDGE_SET: dnumobjent = DIM_NUM_EDGE_ES(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ES(obj_id_ndx); vattrbname = VAR_ESATTRIB(obj_id_ndx); break; case EX_FACE_SET: dnumobjent = DIM_NUM_FACE_FS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FS(obj_id_ndx); vattrbname = VAR_FSATTRIB(obj_id_ndx); break; case EX_ELEM_SET: dnumobjent = DIM_NUM_ELE_ELS(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_ELS(obj_id_ndx); vattrbname = VAR_ELSATTRIB(obj_id_ndx); break; case EX_NODAL: dnumobjent = DIM_NUM_NODES; dnumobjatt = DIM_NUM_ATT_IN_NBLK; vattrbname = VAR_NATTRIB; break; case EX_EDGE_BLOCK: dnumobjent = DIM_NUM_ED_IN_EBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_EBLK(obj_id_ndx); vattrbname = VAR_EATTRIB(obj_id_ndx); break; case EX_FACE_BLOCK: dnumobjent = DIM_NUM_FA_IN_FBLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_FBLK(obj_id_ndx); vattrbname = VAR_FATTRIB(obj_id_ndx); break; case EX_ELEM_BLOCK: dnumobjent = DIM_NUM_EL_IN_BLK(obj_id_ndx); dnumobjatt = DIM_NUM_ATT_IN_BLK(obj_id_ndx); vattrbname = VAR_ATTRIB(obj_id_ndx); break; default: exerrval = 1005; sprintf(errmsg, "Internal Error: unrecognized object type in switch: %d in file id %d", obj_type,exoid); ex_err("ex_get_partial_attr",errmsg,EX_MSG); return (EX_FATAL); /* number of attributes not defined */ } /* inquire id's of previously defined dimensions */ if (ex_get_dimension(exoid, dnumobjent,"entries", &num_entries_this_obj, &temp, "ex_get_partial_attr") != NC_NOERR) return EX_FATAL; if (start_num + num_ent -1 > num_entries_this_obj) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: start index (%"PRId64") + count (%"PRId64") is larger than total number of entities (%"ST_ZU") in file id %d", start_num, num_ent, num_entries_this_obj, exoid); ex_err("ex_get_partial_attr",errmsg,exerrval); return (EX_FATAL); } if (ex_get_dimension(exoid, dnumobjatt,"attributes", &num_attr, &temp, "ex_get_partial_attr") != NC_NOERR) return EX_FATAL; if ((status = nc_inq_varid(exoid, vattrbname, &attrid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate attributes for %s %"PRId64" in file id %d", ex_name_of_object(obj_type),obj_id,exoid); ex_err("ex_get_partial_attr",errmsg,exerrval); return (EX_FATAL); } /* read in the attributes */ start[0] = start_num-1; start[1] = 0; count[0] = num_ent; count[1] = num_attr; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, attrid, start, count, attrib); } else { status = nc_get_vara_double(exoid, attrid, start, count, attrib); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get attributes for %s %"PRId64" in file id %d", ex_name_of_object(obj_type), obj_id,exoid); ex_err("ex_get_partial_attr",errmsg,exerrval); return (EX_FATAL); } return(EX_NOERR); }
bool CNetCDFTraj::ReadSnapshot(CAmberRestart* p_snap) { if( Mode != AMBER_TRAJ_READ ){ ES_ERROR("illegal mode, it should be AMBER_TRAJ_READ"); return(false); } if( p_snap == NULL ){ INVALID_ARGUMENT("p_snap == NULL"); } if( p_snap->GetTopology() == NULL ) { ES_ERROR("snapshot does not have assigned topology"); return(false); } if( p_snap->GetNumberOfAtoms() != ActualAtoms ) { CSmallString error; error << "inconsistent number of atoms, trajectory: " << ActualAtoms; error << " topology: " << p_snap->GetNumberOfAtoms(); ES_ERROR(error); return(false); } bool has_box = p_snap->GetTopology()->BoxInfo.GetType() != AMBER_BOX_NONE; if( has_box != HasBox ) { CSmallString error; error << "topology and snapshot has different info about box presence"; ES_ERROR(error); return(false); } if( CoordinateVID < 0 ) { CSmallString error; error << "ReadHeader must be called before ReadSnapshot"; ES_ERROR(error); return(false); } if( Coordinates == NULL ) { CSmallString error; error << "Coordinates are NULL"; ES_ERROR(error); return(false); } if( CurrentSnapshot >= TotalSnapshots ) return(false); // end of trajectory int err; size_t start[3],count[3]; // coordinates ------------------------------- start[0] = CurrentSnapshot; start[1] = 0; start[2] = 0; count[0] = 1; count[1] = ActualAtoms; count[2] = 3; err = nc_get_vara_float(NCID,CoordinateVID,start,count,Coordinates); if( err != NC_NOERR ) { CSmallString error; error << "unable to get coordinates (" << nc_strerror(err) << ")"; ES_ERROR(error); return(false); } int j=0; for(int i=0; i < ActualAtoms; i++) { CPoint pos; pos.x = Coordinates[j++]; pos.y = Coordinates[j++]; pos.z = Coordinates[j++]; p_snap->SetPosition(i,pos); } // box --------------------------------------- if( HasBox ) { start[0] = CurrentSnapshot; start[1] = 0; start[2] = 0; count[0] = 1; count[1] = 3; count[2] = 0; err = nc_get_vara_double(NCID,CellLengthVID,start,count,CellLength); if( err != NC_NOERR ) { CSmallString error; error << "unable to get cell length (" << nc_strerror(err) << ")"; ES_ERROR(error); return(false); } CPoint tmp; tmp.x = CellLength[0]; tmp.y = CellLength[1]; tmp.z = CellLength[2]; p_snap->SetBox(tmp); err = nc_get_vara_double(NCID,CellAngleVID,start,count,CellAngle); if( err != NC_NOERR ) { CSmallString error; error << "unable to get cell length (" << nc_strerror(err) << ")"; ES_ERROR(error); return(false); } tmp.x = CellAngle[0]; tmp.y = CellAngle[1]; tmp.z = CellAngle[2]; p_snap->SetAngles(tmp); } // time -------------------------------------- start[0] = CurrentSnapshot; count[0] = 1; err = nc_get_vara_float(NCID,TimeVID,start,count,&Time); if( err != NC_NOERR ) { CSmallString error; error << "unable to get time (" << nc_strerror(err) << ")"; ES_ERROR(error); return(false); } p_snap->SetTime(Time); CurrentSnapshot++; return(true); }
int ex_get_var_time( int exoid, ex_entity_type var_type, int var_index, int64_t id, int beg_time_step, int end_time_step, void* var_vals ) { int dimid, varid, numel = 0, offset; int status; int *stat_vals; size_t num_obj, i; size_t num_entries_this_obj = 0; size_t start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; const char* varobjids; const char* varobstat; switch (var_type) { case EX_GLOBAL: return ex_get_glob_var_time( exoid, var_index, beg_time_step, end_time_step, var_vals ); case EX_NODAL: return ex_get_nodal_var_time( exoid, var_index, id, beg_time_step, end_time_step, var_vals ); case EX_EDGE_BLOCK: varobjids = VAR_ID_ED_BLK; varobstat = VAR_STAT_ED_BLK; break; case EX_FACE_BLOCK: varobjids = VAR_ID_FA_BLK; varobstat = VAR_STAT_FA_BLK; break; case EX_ELEM_BLOCK: varobjids = VAR_ID_EL_BLK; varobstat = VAR_STAT_EL_BLK; break; case EX_NODE_SET: varobjids = VAR_NS_IDS; varobstat = VAR_NS_STAT; break; case EX_EDGE_SET: varobjids = VAR_ES_IDS; varobstat = VAR_ES_STAT; break; case EX_FACE_SET: varobjids = VAR_FS_IDS; varobstat = VAR_FS_STAT; break; case EX_SIDE_SET: varobjids = VAR_SS_IDS; varobstat = VAR_SS_STAT; break; case EX_ELEM_SET: varobjids = VAR_ELS_IDS; varobstat = VAR_ELS_STAT; break; default: exerrval = EX_BADPARAM; sprintf( errmsg, "Error: Invalid variable type (%d) specified for file id %d", var_type, exoid ); ex_err( "ex_get_var_time", errmsg, exerrval ); return (EX_FATAL); } exerrval = 0; /* clear error code */ /* assume entry number is 1-based (the first entry of an object is 1, not 0); * adjust so it is 0-based */ id--; /* find what object the entry is in */ /* first, find out how many objects there are */ status = ex_get_dimension(exoid, ex_dim_num_objects(var_type), ex_name_of_object(var_type), &num_obj, &dimid, "ex_get_var_time"); if (status != NC_NOERR) return status; /* get the array of object ids */ /* don't think we need this anymore since the netcdf variable names associated with objects don't contain the object ids */ if ((status = nc_inq_varid (exoid, varobjids, &varid )) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate %s ids in file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } /* allocate space for stat array */ if (!(stat_vals = malloc((int)num_obj*sizeof(int)))) { exerrval = EX_MEMFAIL; sprintf(errmsg, "Error: failed to allocate memory for %s status array for file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } /* get variable id of status array */ if (nc_inq_varid (exoid, varobstat, &varid) == NC_NOERR) { /* if status array exists, use it, otherwise assume, object exists to be backward compatible */ if ((status = nc_get_var_int(exoid, varid, stat_vals)) != NC_NOERR) { exerrval = status; free(stat_vals); sprintf(errmsg, "Error: failed to get %s status array from file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } } else { /* default: status is true */ for(i=0;i<num_obj;i++) stat_vals[i]=1; } /* loop through each object until id is found; since entry * numbers are sequential (beginning with 1) id is in obj_i * when id_first_i <= id <= id_last_i, where * id_first_i is the entry number of the first entry in * obj_i and id_last_i is the entry number of the last * entry in obj_i */ i = 0; if (stat_vals[i] != 0) { if ((status = nc_inq_dimid(exoid, ex_dim_num_entries_in_object(var_type,i+1), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of entries in %"ST_ZU"th %s in file id %d", i, ex_name_of_object(var_type), exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &num_entries_this_obj)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of entries in %"ST_ZU"th %s in file id %d", i, ex_name_of_object(var_type), exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); return (EX_FATAL); } } /* End NULL object check */ numel = num_entries_this_obj; while (numel <= id) { if (stat_vals[++i] != 0) { if ((status = nc_inq_dimid(exoid,ex_dim_num_entries_in_object(var_type,i+1), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of entries in %"ST_ZU"th %s in file id %d", i, ex_name_of_object(var_type), exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &num_entries_this_obj)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of entries in %"ST_ZU"th %s in file id %d", i, ex_name_of_object(var_type), exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); return (EX_FATAL); } numel += num_entries_this_obj; } } offset = id - (numel - num_entries_this_obj); /* inquire previously defined variable */ if ((status = nc_inq_varid(exoid,ex_name_var_of_object(var_type,var_index,i+1), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate variable %"ST_ZU" for %dth %s in file id %d", i, var_index,ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); free(stat_vals); return (EX_FATAL); } free(stat_vals); /* read values of object variable */ start[0] = --beg_time_step; start[1] = offset; if (end_time_step < 0) { /* user is requesting the maximum time step; we find this out using the * database inquire function to get the number of time steps; the ending * time step number is 1 less due to 0 based array indexing in C */ end_time_step = ex_inquire_int (exoid, EX_INQ_TIME); } end_time_step--; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get %s variable values in file id %d", ex_name_of_object(var_type),exoid); ex_err("ex_get_var_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
NcValues* NcVar::values( void ) const { int ndims = num_dims(); size_t crnr[NC_MAX_DIMS]; size_t edgs[NC_MAX_DIMS]; for (int i = 0; i < ndims; i++) { crnr[i] = 0; edgs[i] = get_dim(i)->size(); } NcValues* valp = get_space(); int status; switch (type()) { case ncFloat: status = NcError::set_err( nc_get_vara_float(the_file->id(), the_id, crnr, edgs, (float *)valp->base()) ); break; case ncDouble: status = NcError::set_err( nc_get_vara_double(the_file->id(), the_id, crnr, edgs, (double *)valp->base()) ); break; case ncInt64: status = NcError::set_err( nc_put_vara_longlong(the_file->id(), the_id, crnr, edgs, (long long *)valp->base()) ); break; case ncUInt64: status = NcError::set_err( nc_put_vara_ulonglong(the_file->id(), the_id, crnr, edgs, (unsigned long long *)valp->base()) ); break; case ncInt: status = NcError::set_err( nc_get_vara_int(the_file->id(), the_id, crnr, edgs, (int *)valp->base()) ); break; case ncShort: status = NcError::set_err( nc_get_vara_short(the_file->id(), the_id, crnr, edgs, (short *)valp->base()) ); break; case ncByte: status = NcError::set_err( nc_get_vara_schar(the_file->id(), the_id, crnr, edgs, (signed char *)valp->base()) ); break; case ncChar: status = NcError::set_err( nc_get_vara_text(the_file->id(), the_id, crnr, edgs, (char *)valp->base()) ); break; case ncNoType: default: return 0; } if (status != NC_NOERR) return 0; return valp; }
void NetCDFInterface::readNetCDFData(std::string &ifname, std::vector<GEOLIB::Point*>* points_vec, GEOLIB::GEOObjects* obj, size_t &NRLAT, size_t &NRLON) { int ncid; int rlat_dimid, rlon_dimid; int lat_varid, lon_varid; int choose_varid; /* The start and count arrays will tell the netCDF library where to read our data. */ static size_t start2[2], count2[2]; static size_t start3[3], count3[3]; static size_t start4[4], count4[4]; /* Error handling. */ int status; /* Open the file. */ std::cout << "Open NetCDF file " << ifname << "\n" << std::flush; status = nc_open(ifname.c_str(), NC_NOWRITE, &ncid); if (status != NC_NOERR) HANDLE_ERROR(status); /* Get the lengths of dimensions, such as "rlat" and "rlat". */ status = nc_inq_dimid(ncid, DIM_RLAT, &rlat_dimid); if (status != NC_NOERR) HANDLE_ERROR(status); status = nc_inq_dimlen(ncid, rlat_dimid, &NRLAT); if (status != NC_NOERR) HANDLE_ERROR(status); status = nc_inq_dimid(ncid, DIM_RLON, &rlon_dimid); if (status != NC_NOERR) HANDLE_ERROR(status); status = nc_inq_dimlen(ncid, rlon_dimid, &NRLON); if (status != NC_NOERR) HANDLE_ERROR(status); /* Get the choosen variable name from the opened NetCDF file. */ std::string nc_fname; size_t indexChar; indexChar = ifname.find_last_of('/'); if(indexChar == std::string::npos) nc_fname = ifname; else nc_fname = ifname.substr(indexChar + 1); size_t len_varname = nc_fname.size() - LEN_ORIGINAL; std::string var_name; var_name = nc_fname.substr(0,len_varname); /* Get the varids of the netCDF variables, such as longitude, latitude, * temperature or precipitation, and so on. */ status = nc_inq_varid(ncid, LON_NAME, &lon_varid); if (status != NC_NOERR) HANDLE_ERROR(status); status = nc_inq_varid(ncid, LAT_NAME, &lat_varid); if (status != NC_NOERR) HANDLE_ERROR(status); status = nc_inq_varid(ncid, var_name.c_str(), &choose_varid); if (status != NC_NOERR) HANDLE_ERROR(status); /* Program variables to hold the data we will read. We will only need enough space to hold one timestep of data; one record.*/ size_t len_vals = NRLAT * NRLON; float* lat_in = new float[len_vals]; float* lon_in = new float[len_vals]; float* var_in = new float[len_vals]; /* Read the data. Since we know the contents of the file we know * that the data arrays in this program are the correct size to * hold one timestep. */ count2[0] = NRLAT; count2[1] = NRLON; count3[0] = 1; count3[1] = NRLAT; count3[2] = NRLON; count4[0] = 1; count4[1] = 1; count4[2] = NRLAT; count4[3] = NRLON; for (size_t i = 0; i < 2; i++) start2[i] = 0; for (size_t i = 0; i < 3; i++) start3[i] = 0; for (size_t i = 0; i < 4; i++) start4[i] = 0; /* Read the above netCDF variables with their corresponding varids. */ status = nc_get_vara_float(ncid, lon_varid, start2, count2, lon_in); if (status != NC_NOERR) HANDLE_ERROR(status); status = nc_get_vara_float(ncid, lat_varid, start2, count2, lat_in); if (status != NC_NOERR) HANDLE_ERROR(status); if (var_name.compare("T_2M") == 0) { status = nc_get_vara_float(ncid, choose_varid, start4, count4, var_in); if (status != NC_NOERR) HANDLE_ERROR(status); } else if (var_name.compare("TOT_PREC") == 0) { status = nc_get_vara_float(ncid, choose_varid, start3, count3, var_in); if (status != NC_NOERR) HANDLE_ERROR(status); } else if (var_name.compare("HSURF") == 0) { status = nc_get_vara_float(ncid, choose_varid, start3, count3, var_in); if (status != NC_NOERR) HANDLE_ERROR(status); } /* Close the file. */ status = nc_close(ncid); if (status != NC_NOERR) HANDLE_ERROR(status); printf("Reading netCDF file successfully!\n"); for (size_t i = 0; i < len_vals; i++) points_vec->push_back(new Point( lon_in[i], lat_in[i], var_in[i] )); delete [] lat_in; delete [] lon_in; delete [] var_in; obj->addPointVec(points_vec, ifname); }
/** Get the specified frame from amber netcdf file * Coords are a 1 dimensional array of format X1,Y1,Z1,X2,Y2,Z2,... */ int Traj_AmberNetcdf::readFrame(int set, Frame& frameIn) { start_[0] = set; start_[1] = 0; start_[2] = 0; count_[0] = 1; count_[1] = Ncatom(); count_[2] = 3; // Get temperature if (TempVID_!=-1) { if ( checkNCerr(nc_get_vara_double(ncid_, TempVID_, start_, count_, frameIn.tAddress())) ) { mprinterr("Error: Getting replica temperature for frame %i.\n", set+1); return 1; } //fprintf(stderr,"DEBUG: Replica Temperature %lf\n",F->T); } // Get time if (timeVID_!=-1) { float time; if (checkNCerr(nc_get_vara_float(ncid_, timeVID_, start_, count_, &time))) { mprinterr("Error: Getting time for frame %i.\n", set + 1); return 1; } frameIn.SetTime( (double)time ); } // Read Coords if ( checkNCerr(nc_get_vara_float(ncid_, coordVID_, start_, count_, Coord_)) ) { mprinterr("Error: Getting coordinates for frame %i\n", set+1); return 1; } FloatToDouble(frameIn.xAddress(), Coord_); // Read Velocities if (velocityVID_ != -1) { if ( checkNCerr(nc_get_vara_float(ncid_, velocityVID_, start_, count_, Coord_)) ) { mprinterr("Error: Getting velocities for frame %i\n", set+1); return 1; } FloatToDouble(frameIn.vAddress(), Coord_); } // Read indices. Input array must be allocated to be size remd_dimension. if (indicesVID_!=-1) { count_[1] = remd_dimension_; if ( checkNCerr(nc_get_vara_int(ncid_, indicesVID_, start_, count_, frameIn.iAddress())) ) { mprinterr("Error: Getting replica indices for frame %i.\n", set+1); return 1; } //mprintf("DEBUG:\tReplica indices:"); //for (int dim=0; dim < remd_dimension_; dim++) mprintf(" %i",remd_indices[dim]); //mprintf("\n"); } // Read box info if (cellLengthVID_ != -1) { count_[1] = 3; count_[2] = 0; if (checkNCerr(nc_get_vara_double(ncid_, cellLengthVID_, start_, count_, frameIn.bAddress()))) { mprinterr("Error: Getting cell lengths for frame %i.\n", set+1); return 1; } if (checkNCerr(nc_get_vara_double(ncid_, cellAngleVID_, start_, count_, frameIn.bAddress()+3))) { mprinterr("Error: Getting cell angles for frame %i.\n", set+1); return 1; } } return 0; }
OSErr NetCDFWindMoverCurv::TextRead(char *path, TMap **newMap, char *topFilePath) // don't want a map { // this code is for curvilinear grids OSErr err = 0; long i,j, numScanned, indexOfStart = 0; int status, ncid, latIndexid, lonIndexid, latid, lonid, recid, timeid, numdims; size_t latLength, lonLength, recs, t_len, t_len2; float timeVal; char recname[NC_MAX_NAME], *timeUnits=0, month[10]; char dimname[NC_MAX_NAME], s[256], topPath[256]; WORLDPOINTFH vertexPtsH=0; float *lat_vals=0,*lon_vals=0,yearShift=0.; static size_t timeIndex,ptIndex[2]={0,0}; static size_t pt_count[2]; Seconds startTime, startTime2; double timeConversion = 1.; char errmsg[256] = "",className[256]=""; char fileName[64],*modelTypeStr=0; Point where; OSType typeList[] = { 'NULL', 'NULL', 'NULL', 'NULL' }; MySFReply reply; Boolean bTopFile = false, fIsNavy = false; // for now keep code around but probably don't need Navy curvilinear wind //VelocityFH velocityH = 0; char outPath[256]; if (!path || !path[0]) return 0; strcpy(fPathName,path); strcpy(s,path); SplitPathFile (s, fileName); strcpy(fFileName, fileName); // maybe use a name from the file status = nc_open(path, NC_NOWRITE, &ncid); //if (status != NC_NOERR) {err = -1; goto done;} if (status != NC_NOERR) { #if TARGET_API_MAC_CARBON err = ConvertTraditionalPathToUnixPath((const char *) path, outPath, kMaxNameLen) ; status = nc_open(outPath, NC_NOWRITE, &ncid); #endif if (status != NC_NOERR) {err = -1; goto done;} } // check number of dimensions - 2D or 3D status = nc_inq_ndims(ncid, &numdims); if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_attlen(ncid,NC_GLOBAL,"generating_model",&t_len2); if (status != NC_NOERR) {fIsNavy = false; /*goto done;*/} else { fIsNavy = true; // may only need to see keyword is there, since already checked grid type modelTypeStr = new char[t_len2+1]; status = nc_get_att_text(ncid, NC_GLOBAL, "generating_model", modelTypeStr); if (status != NC_NOERR) {fIsNavy = false; goto done;} modelTypeStr[t_len2] = '\0'; strcpy(fFileName, modelTypeStr); } GetClassName(className); if (!strcmp("NetCDF Wind",className)) SetClassName(fFileName); //first check that name is now the default and not set by command file ("NetCDF Wind") //if (fIsNavy) { status = nc_inq_dimid(ncid, "time", &recid); //Navy //if (status != NC_NOERR) {err = -1; goto done;} if (status != NC_NOERR) { status = nc_inq_unlimdim(ncid, &recid); // issue of time not being unlimited dimension if (status != NC_NOERR) {err = -1; goto done;} } } /*else { status = nc_inq_unlimdim(ncid, &recid); // issue of time not being unlimited dimension if (status != NC_NOERR) {err = -1; goto done;} }*/ //if (fIsNavy) status = nc_inq_varid(ncid, "time", &timeid); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "ProjectionHr", &timeid); if (status != NC_NOERR) {err = -1; goto done;} } // if (status != NC_NOERR) {/*err = -1; goto done;*/timeid=recid;} //if (!fIsNavy) //status = nc_inq_attlen(ncid, recid, "units", &t_len); // recid is the dimension id not the variable id //else // LAS has them in order, and time is unlimited, but variable/dimension names keep changing so leave this way for now status = nc_inq_attlen(ncid, timeid, "units", &t_len); if (status != NC_NOERR) { timeUnits = 0; // files should always have this info timeConversion = 3600.; // default is hours startTime2 = model->GetStartTime(); // default to model start time //err = -1; goto done; } else { DateTimeRec time; char unitStr[24], junk[10]; timeUnits = new char[t_len+1]; //if (!fIsNavy) //status = nc_get_att_text(ncid, recid, "units", timeUnits); // recid is the dimension id not the variable id //else status = nc_get_att_text(ncid, timeid, "units", timeUnits); if (status != NC_NOERR) {err = -1; goto done;} timeUnits[t_len] = '\0'; // moved this statement before StringSubstitute, JLM 5/2/10 StringSubstitute(timeUnits, ':', ' '); StringSubstitute(timeUnits, '-', ' '); StringSubstitute(timeUnits, 'T', ' '); StringSubstitute(timeUnits, 'Z', ' '); numScanned=sscanf(timeUnits, "%s %s %hd %hd %hd %hd %hd %hd", unitStr, junk, &time.year, &time.month, &time.day, &time.hour, &time.minute, &time.second) ; if (numScanned==5) {time.hour = 0; time.minute = 0; time.second = 0; } else if (numScanned==7) // has two extra time entries ?? time.second = 0; else if (numScanned<8) //else if (numScanned!=8) { //timeUnits = 0; // files should always have this info //timeConversion = 3600.; // default is hours //startTime2 = model->GetStartTime(); // default to model start time err = -1; TechError("NetCDFWindMoverCurv::TextRead()", "sscanf() == 8", 0); goto done; } else { // code goes here, trouble with the DAYS since 1900 format, since converts to seconds since 1904 if (time.year ==1900) {time.year += 40; time.day += 1; /*for the 1900 non-leap yr issue*/ yearShift = 40.;} DateToSeconds (&time, &startTime2); // code goes here, which start Time to use ?? if (!strcmpnocase(unitStr,"HOURS") || !strcmpnocase(unitStr,"HOUR")) timeConversion = 3600.; else if (!strcmpnocase(unitStr,"MINUTES") || !strcmpnocase(unitStr,"MINUTE")) timeConversion = 60.; else if (!strcmpnocase(unitStr,"SECONDS") || !strcmpnocase(unitStr,"SECOND")) timeConversion = 1.; else if (!strcmpnocase(unitStr,"DAYS") || !strcmpnocase(unitStr,"DAY")) timeConversion = 24.*3600.; } } if (fIsNavy) { status = nc_inq_dimid(ncid, "gridy", &latIndexid); //Navy if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_dimlen(ncid, latIndexid, &latLength); if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_dimid(ncid, "gridx", &lonIndexid); //Navy if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_dimlen(ncid, lonIndexid, &lonLength); if (status != NC_NOERR) {err = -1; goto done;} // option to use index values? status = nc_inq_varid(ncid, "grid_lat", &latid); if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_varid(ncid, "grid_lon", &lonid); if (status != NC_NOERR) {err = -1; goto done;} } else { for (i=0;i<numdims;i++) { if (i == recid) continue; status = nc_inq_dimname(ncid,i,dimname); if (status != NC_NOERR) {err = -1; goto done;} if (!strncmpnocase(dimname,"X",1) || !strncmpnocase(dimname,"LON",3) || !strncmpnocase(dimname,"nx",2)) { lonIndexid = i; } if (!strncmpnocase(dimname,"Y",1) || !strncmpnocase(dimname,"LAT",3) || !strncmpnocase(dimname,"ny",2)) { latIndexid = i; } } status = nc_inq_dimlen(ncid, latIndexid, &latLength); if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_dimlen(ncid, lonIndexid, &lonLength); if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_varid(ncid, "LATITUDE", &latid); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "lat", &latid); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "latitude", &latid); if (status != NC_NOERR) {err = -1; goto done;} } } status = nc_inq_varid(ncid, "LONGITUDE", &lonid); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "lon", &lonid); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "longitude", &lonid); if (status != NC_NOERR) {err = -1; goto done;} } } } pt_count[0] = latLength; pt_count[1] = lonLength; vertexPtsH = (WorldPointF**)_NewHandleClear(latLength*lonLength*sizeof(WorldPointF)); if (!vertexPtsH) {err = memFullErr; goto done;} lat_vals = new float[latLength*lonLength]; lon_vals = new float[latLength*lonLength]; if (!lat_vals || !lon_vals) {err = memFullErr; goto done;} status = nc_get_vara_float(ncid, latid, ptIndex, pt_count, lat_vals); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_vara_float(ncid, lonid, ptIndex, pt_count, lon_vals); if (status != NC_NOERR) {err = -1; goto done;} for (i=0;i<latLength;i++) { for (j=0;j<lonLength;j++) { //if (lat_vals[(latLength-i-1)*lonLength+j]==fill_value) // this would be an error //lat_vals[(latLength-i-1)*lonLength+j]=0.; //if (lon_vals[(latLength-i-1)*lonLength+j]==fill_value) //lon_vals[(latLength-i-1)*lonLength+j]=0.; INDEXH(vertexPtsH,i*lonLength+j).pLat = lat_vals[(latLength-i-1)*lonLength+j]; INDEXH(vertexPtsH,i*lonLength+j).pLong = lon_vals[(latLength-i-1)*lonLength+j]; } } fVertexPtsH = vertexPtsH; status = nc_inq_dim(ncid, recid, recname, &recs); if (status != NC_NOERR) {err = -1; goto done;} if (recs<=0) {strcpy(errmsg,"No times in file. Error opening NetCDF wind file"); err = -1; goto done;} fTimeHdl = (Seconds**)_NewHandleClear(recs*sizeof(Seconds)); if (!fTimeHdl) {err = memFullErr; goto done;} for (i=0;i<recs;i++) { Seconds newTime; // possible units are, HOURS, MINUTES, SECONDS,... timeIndex = i; //if (!fIsNavy) //status = nc_get_var1_float(ncid, recid, &timeIndex, &timeVal); // recid is the dimension id not the variable id //else status = nc_get_var1_float(ncid, timeid, &timeIndex, &timeVal); if (status != NC_NOERR) {err = -1; goto done;} newTime = RoundDateSeconds(round(startTime2+timeVal*timeConversion)); //INDEXH(fTimeHdl,i) = startTime2+(long)(timeVal*timeConversion -yearShift*3600.*24.*365.25); // which start time where? //if (i==0) startTime = startTime2+(long)(timeVal*timeConversion -yearShift*3600.*24.*365.25); INDEXH(fTimeHdl,i) = newTime-yearShift*3600.*24.*365.25; // which start time where? if (i==0) startTime = newTime-yearShift*3600.*24.*365.25; } if (model->GetStartTime() != startTime || model->GetModelTime()!=model->GetStartTime()) { if (true) // maybe use NOAA.ver here? { short buttonSelected; //buttonSelected = MULTICHOICEALERT(1688,"Do you want to reset the model start time to the first time in the file?",FALSE); if(!gCommandFileRun) // also may want to skip for location files... buttonSelected = MULTICHOICEALERT(1688,"Do you want to reset the model start time to the first time in the file?",FALSE); else buttonSelected = 1; // TAP user doesn't want to see any dialogs, always reset (or maybe never reset? or send message to errorlog?) switch(buttonSelected){ case 1: // reset model start time //bTopFile = true; model->SetModelTime(startTime); model->SetStartTime(startTime); model->NewDirtNotification(DIRTY_RUNBAR); // must reset the runbar break; case 3: // don't reset model start time //bTopFile = false; break; case 4: // cancel err=-1;// user cancel goto done; } } //model->SetModelTime(startTime); //model->SetStartTime(startTime); //model->NewDirtNotification(DIRTY_RUNBAR); // must reset the runbar } fNumRows = latLength; fNumCols = lonLength; status = nc_close(ncid); if (status != NC_NOERR) {err = -1; goto done;} //err = this -> SetInterval(errmsg); //if(err) goto done; // look for topology in the file // for now ask for an ascii file, output from Topology save option // need dialog to ask for file //if (fIsNavy) // for now don't allow for wind files {if (topFilePath[0]) {err = ReadTopology(topFilePath,newMap); goto done;}} if (!gCommandFileRun) { short buttonSelected; buttonSelected = MULTICHOICEALERT(1688,"Do you have an extended topology file to load?",FALSE); switch(buttonSelected){ case 1: // there is an extended top file bTopFile = true; break; case 3: // no extended top file bTopFile = false; break; case 4: // cancel err=-1;// stay at this dialog goto done; } } if(bTopFile) { #if TARGET_API_MAC_CARBON mysfpgetfile(&where, "", -1, typeList, (MyDlgHookUPP)0, &reply, M38c, MakeModalFilterUPP(STDFilter)); if (!reply.good)/* return USERCANCEL;*/ { /*if (recs>0) err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg); else {strcpy(errmsg,"No times in file. Error opening NetCDF file"); err = -1;} if(err) goto done;*/ err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg); //err = ReorderPoints(fStartData.dataHdl,newMap,errmsg); // if u, v input separately only do this once? goto done; } else strcpy(topPath, reply.fullPath); #else where = CenteredDialogUpLeft(M38c); sfpgetfile(&where, "", (FileFilterUPP)0, -1, typeList, (DlgHookUPP)0, &reply, M38c, (ModalFilterUPP)MakeUPP((ProcPtr)STDFilter, uppModalFilterProcInfo)); if (!reply.good) { /*if (recs>0) err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg); else {strcpy(errmsg,"No times in file. Error opening NetCDF file"); err = -1;} if(err) goto done;*/ err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg); //err = ReorderPoints(fStartData.dataHdl,newMap,errmsg); /*if (err)*/ goto done; } my_p2cstr(reply.fName); #ifdef MAC GetFullPath(reply.vRefNum, 0, (char *)reply.fName, topPath); #else strcpy(topPath, reply.fName); #endif #endif strcpy (s, topPath); err = ReadTopology(topPath,newMap); goto done; } /*if (recs>0) err = this -> ReadTimeData(indexOfStart,&velocityH,errmsg); else {strcpy(errmsg,"No times in file. Error opening NetCDF wind file"); err = -1;} if(err) goto done;*/ err = dynamic_cast<NetCDFWindMoverCurv *>(this)->ReorderPoints(newMap,errmsg); //err = ReorderPoints(fStartData.dataHdl,newMap,errmsg); done: if (err) { printNote("Error opening NetCDF wind file"); if(fGrid) { fGrid ->Dispose(); delete fGrid; fGrid = 0; } if(vertexPtsH) {DisposeHandle((Handle)vertexPtsH); vertexPtsH = 0; fVertexPtsH = 0;} } if (timeUnits) delete [] timeUnits; if (lat_vals) delete [] lat_vals; if (lon_vals) delete [] lon_vals; if (modelTypeStr) delete [] modelTypeStr; //if (velocityH) {DisposeHandle((Handle)velocityH); velocityH = 0;} return err; }
int ex_get_glob_var_time (int exoid, int glob_var_index, int beg_time_step, int end_time_step, void *glob_var_vals) { int status; int varid; size_t start[2], count[2]; float fdum; char *cdum = 0; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if ((status = nc_inq_varid (exoid, VAR_GLO_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate global variables in file id %d", exoid); ex_err("ex_get_glob_var_time",errmsg,exerrval); return (EX_WARN); } /* read values of global variables */ start[0] = --beg_time_step; start[1] = --glob_var_index; if (end_time_step < 0) { /* user is requesting the maximum time step; we find this out using the * database inquire function to get the number of time steps */ if ((status = ex_inquire (exoid, EX_INQ_TIME, &end_time_step, &fdum, cdum)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of time steps in file id %d", exoid); ex_err("ex_get_glob_var_time",errmsg,exerrval); return (EX_FATAL); } } end_time_step--; count[0] = end_time_step - beg_time_step + 1; count[1] = 1; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, glob_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, glob_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get global variable %d values from file id %d", glob_var_index, exoid); ex_err("ex_get_glob_var_time",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
OSErr NetCDFWindMoverCurv::ReadTimeData(long index,VelocityFH *velocityH, char* errmsg) { OSErr err = 0; long i,j; char path[256], outPath[256]; char *velUnits=0; int status, ncid, numdims; int wind_ucmp_id, wind_vcmp_id, angle_id, uv_ndims; static size_t wind_index[] = {0,0,0,0}, angle_index[] = {0,0}; static size_t wind_count[4], angle_count[2]; size_t velunit_len; float *wind_uvals = 0,*wind_vvals = 0, fill_value=-1e-72, velConversion=1.; short *wind_uvals_Navy = 0,*wind_vvals_Navy = 0, fill_value_Navy; float *angle_vals = 0; long totalNumberOfVels = fNumRows * fNumCols; VelocityFH velH = 0; long latlength = fNumRows; long lonlength = fNumCols; float scale_factor = 1.,angle = 0.,u_grid,v_grid; Boolean bRotated = true, fIsNavy = false, bIsNWSSpeedDirData = false; errmsg[0]=0; strcpy(path,fPathName); if (!path || !path[0]) return -1; status = nc_open(path, NC_NOWRITE, &ncid); //if (status != NC_NOERR) {err = -1; goto done;} if (status != NC_NOERR) { #if TARGET_API_MAC_CARBON err = ConvertTraditionalPathToUnixPath((const char *) path, outPath, kMaxNameLen) ; status = nc_open(outPath, NC_NOWRITE, &ncid); #endif if (status != NC_NOERR) {err = -1; goto done;} } status = nc_inq_ndims(ncid, &numdims); if (status != NC_NOERR) {err = -1; goto done;} wind_index[0] = index; // time wind_count[0] = 1; // take one at a time if (numdims>=4) // should check what the dimensions are, CO-OPS uses sigma { wind_count[1] = 1; // depth wind_count[2] = latlength; wind_count[3] = lonlength; } else { wind_count[1] = latlength; wind_count[2] = lonlength; } angle_count[0] = latlength; angle_count[1] = lonlength; //wind_count[0] = latlength; // a fudge for the PWS format which has u(lat,lon) not u(time,lat,lon) //wind_count[1] = lonlength; if (fIsNavy) { // need to check if type is float or short, if float no scale factor? wind_uvals = new float[latlength*lonlength]; if(!wind_uvals) {TechError("GridVel::ReadNetCDFFile()", "new[]", 0); err = memFullErr; goto done;} wind_vvals = new float[latlength*lonlength]; if(!wind_vvals) {TechError("GridVel::ReadNetCDFFile()", "new[]", 0); err = memFullErr; goto done;} angle_vals = new float[latlength*lonlength]; if(!angle_vals) {TechError("GridVel::ReadNetCDFFile()", "new[]", 0); err = memFullErr; goto done;} status = nc_inq_varid(ncid, "air_gridu", &wind_ucmp_id); if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_varid(ncid, "air_gridv", &wind_vcmp_id); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_vara_float(ncid, wind_ucmp_id, wind_index, wind_count, wind_uvals); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_vara_float(ncid, wind_vcmp_id, wind_index, wind_count, wind_vvals); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_att_float(ncid, wind_ucmp_id, "_FillValue", &fill_value); //if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_att_float(ncid, wind_ucmp_id, "scale_factor", &scale_factor); //if (status != NC_NOERR) {err = -1; goto done;} status = nc_inq_varid(ncid, "grid_orient", &angle_id); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_vara_float(ncid, angle_id, angle_index, angle_count, angle_vals); if (status != NC_NOERR) {/*err = -1; goto done;*/bRotated = false;} } else { wind_uvals = new float[latlength*lonlength]; if(!wind_uvals) {TechError("NetCDFWindMoverCurv::ReadTimeData()", "new[]", 0); err = memFullErr; goto done;} wind_vvals = new float[latlength*lonlength]; if(!wind_vvals) {TechError("NetCDFWindMoverCurv::ReadTimeData()", "new[]", 0); err = memFullErr; goto done;} status = nc_inq_varid(ncid, "air_u", &wind_ucmp_id); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "u", &wind_ucmp_id); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "U", &wind_ucmp_id); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "WindSpd_SFC", &wind_ucmp_id); if (status != NC_NOERR) {err = -1; goto done;} bIsNWSSpeedDirData = true; } //{err = -1; goto done;} } //{err = -1; goto done;} } if (bIsNWSSpeedDirData) { status = nc_inq_varid(ncid, "WindDir_SFC", &wind_vcmp_id); if (status != NC_NOERR) {err = -2; goto done;} } else { status = nc_inq_varid(ncid, "air_v", &wind_vcmp_id); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "v", &wind_vcmp_id); if (status != NC_NOERR) { status = nc_inq_varid(ncid, "V", &wind_vcmp_id); if (status != NC_NOERR) {err = -1; goto done;} } //{err = -1; goto done;} } } status = nc_inq_varndims(ncid, wind_ucmp_id, &uv_ndims); if (status==NC_NOERR){if (uv_ndims < numdims && uv_ndims==3) {wind_count[1] = latlength; wind_count[2] = lonlength;}} // could have more dimensions than are used in u,v status = nc_get_vara_float(ncid, wind_ucmp_id, wind_index, wind_count, wind_uvals); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_vara_float(ncid, wind_vcmp_id, wind_index, wind_count, wind_vvals); if (status != NC_NOERR) {err = -1; goto done;} status = nc_get_att_float(ncid, wind_ucmp_id, "_FillValue", &fill_value); if (status != NC_NOERR) { status = nc_get_att_float(ncid, wind_ucmp_id, "Fill_Value", &fill_value); if (status != NC_NOERR) { status = nc_get_att_float(ncid, wind_ucmp_id, "fillValue", &fill_value);// nws 2.5km if (status != NC_NOERR) { status = nc_get_att_float(ncid, wind_ucmp_id, "missing_value", &fill_value); } /*if (status != NC_NOERR)*//*err = -1; goto done;*/}} // don't require //if (status != NC_NOERR) {err = -1; goto done;} // don't require } status = nc_inq_attlen(ncid, wind_ucmp_id, "units", &velunit_len); if (status == NC_NOERR) { velUnits = new char[velunit_len+1]; status = nc_get_att_text(ncid, wind_ucmp_id, "units", velUnits); if (status == NC_NOERR) { velUnits[velunit_len] = '\0'; if (!strcmpnocase(velUnits,"knots")) velConversion = KNOTSTOMETERSPERSEC; else if (!strcmpnocase(velUnits,"m/s")) velConversion = 1.0; } } status = nc_close(ncid); if (status != NC_NOERR) {err = -1; goto done;} velH = (VelocityFH)_NewHandleClear(totalNumberOfVels * sizeof(VelocityFRec)); if (!velH) {err = memFullErr; goto done;} //for (i=0;i<totalNumberOfVels;i++) for (i=0;i<latlength;i++) { for (j=0;j<lonlength;j++) { if (wind_uvals[(latlength-i-1)*lonlength+j]==fill_value) wind_uvals[(latlength-i-1)*lonlength+j]=0.; if (wind_vvals[(latlength-i-1)*lonlength+j]==fill_value) wind_vvals[(latlength-i-1)*lonlength+j]=0.; if (isnan(wind_uvals[(latlength-i-1)*lonlength+j])) wind_uvals[(latlength-i-1)*lonlength+j]=0.; if (isnan(wind_vvals[(latlength-i-1)*lonlength+j])) wind_vvals[(latlength-i-1)*lonlength+j]=0.; if (fIsNavy) { u_grid = (float)wind_uvals[(latlength-i-1)*lonlength+j]; v_grid = (float)wind_vvals[(latlength-i-1)*lonlength+j]; if (bRotated) angle = angle_vals[(latlength-i-1)*lonlength+j]; INDEXH(velH,i*lonlength+j).u = u_grid*cos(angle*PI/180.)-v_grid*sin(angle*PI/180.); INDEXH(velH,i*lonlength+j).v = u_grid*sin(angle*PI/180.)+v_grid*cos(angle*PI/180.); } else if (bIsNWSSpeedDirData) { //INDEXH(velH,i*lonlength+j).u = KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * sin ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]); // need units //INDEXH(velH,i*lonlength+j).v = KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * cos ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]); // since direction is from rather than to need to switch the sign //INDEXH(velH,i*lonlength+j).u = -1. * KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * sin ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]); // need units //INDEXH(velH,i*lonlength+j).v = -1. * KNOTSTOMETERSPERSEC * wind_uvals[(latlength-i-1)*lonlength+j] * cos ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]); INDEXH(velH,i*lonlength+j).u = -1. * velConversion * wind_uvals[(latlength-i-1)*lonlength+j] * sin ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]); // need units INDEXH(velH,i*lonlength+j).v = -1. * velConversion * wind_uvals[(latlength-i-1)*lonlength+j] * cos ((PI/180.) * wind_vvals[(latlength-i-1)*lonlength+j]); } else { // Look for a land mask, but do this if don't find one - float mask(lat,lon) - 1,0 which is which? //if (wind_uvals[(latlength-i-1)*lonlength+j]==0. && wind_vvals[(latlength-i-1)*lonlength+j]==0.) //wind_uvals[(latlength-i-1)*lonlength+j] = wind_vvals[(latlength-i-1)*lonlength+j] = 1e-06; // just leave fillValue as velocity for new algorithm - comment following lines out // should eliminate the above problem, assuming fill_value is a land mask // leave for now since not using a map...use the entire grid ///////////////////////////////////////////////// INDEXH(velH,i*lonlength+j).u = /*KNOTSTOMETERSPERSEC**/velConversion*wind_uvals[(latlength-i-1)*lonlength+j]; // need units INDEXH(velH,i*lonlength+j).v = /*KNOTSTOMETERSPERSEC**/velConversion*wind_vvals[(latlength-i-1)*lonlength+j]; } } } *velocityH = velH; fFillValue = fill_value; fWindScale = scale_factor; // hmm, this forces a reset of scale factor each time, overriding any set by hand done: if (err) { if (err==-2) strcpy(errmsg,"Error reading wind data from NetCDF file"); else strcpy(errmsg,"Error reading wind direction data from NetCDF file"); // We don't want to put up an error message here because it can lead to an infinite loop of messages. //printNote("Error opening NetCDF file"); if(velH) {DisposeHandle((Handle)velH); velH = 0;} } if (wind_uvals) {delete [] wind_uvals; wind_uvals = 0;} if (wind_vvals) {delete [] wind_vvals; wind_vvals = 0;} if (angle_vals) {delete [] angle_vals; angle_vals = 0;} return err; }
int main(int argc, char **argv) { extern int optind; extern int opterr; extern char *optarg; int c, header = 0, verbose = 0, timeseries = 0; int ncid, varid, storage; char name_in[NC_MAX_NAME + 1]; size_t len; size_t cs[NDIMS3] = {0, 0, 0}; int cache = MEGABYTE; int ndims, dimid[NDIMS3]; float hor_data[LAT_LEN * LON_LEN]; int read_1_us, avg_read_us; float ts_data[TIME_LEN]; size_t start[NDIMS3], count[NDIMS3]; int deflate, shuffle, deflate_level; struct timeval start_time, end_time, diff_time; while ((c = getopt(argc, argv, "vhtc:")) != EOF) switch(c) { case 'v': verbose++; break; case 'h': header++; break; case 't': timeseries++; break; case 'c': sscanf(optarg, "%d", &cache); break; case '?': usage("unknown option"); return 1; } argc -= optind; argv += optind; /* If no file arguments left, report and exit */ if (argc < 1) { printf("no file specified\n"); return 0; } /* Print the header if desired. */ if (header) { printf("cs[0]\tcs[1]\tcs[2]\tcache(MB)\tdeflate\tshuffle"); if (timeseries) printf("\t1st_read_ser(us)\tavg_read_ser(us)\n"); else printf("\t1st_read_hor(us)\tavg_read_hor(us)\n"); } #define PREEMPTION .75 /* Also tried NELEMS of 2500009*/ #define NELEMS 7919 if (nc_set_chunk_cache(cache, NELEMS, PREEMPTION)) ERR; if (nc_open(argv[0], 0, &ncid)) ERR; /* Check to make sure that all the dimension information is * correct. */ if (nc_inq_varid(ncid, DATA_VAR_NAME, &varid)) ERR; if (nc_inq_dim(ncid, LON_DIMID, name_in, &len)) ERR; if (strcmp(name_in, "lon") || len != LON_LEN) ERR; if (nc_inq_dim(ncid, LAT_DIMID, name_in, &len)) ERR; if (strcmp(name_in, "lat") || len != LAT_LEN) ERR; if (nc_inq_dim(ncid, BNDS_DIMID, name_in, &len)) ERR; if (strcmp(name_in, "bnds") || len != BNDS_LEN) ERR; if (nc_inq_dim(ncid, TIME_DIMID, name_in, &len)) ERR; if (strcmp(name_in, "time") || len != TIME_LEN) ERR; if (nc_inq_var(ncid, varid, NULL, NULL, &ndims, dimid, NULL)) ERR; if (ndims != NDIMS3 || dimid[0] != TIME_DIMID || dimid[1] != LAT_DIMID || dimid[2] != LON_DIMID) ERR; /* Get info about the main data var. */ if (nc_inq_var_chunking(ncid, varid, &storage, cs)) ERR; if (nc_inq_var_deflate(ncid, varid, &shuffle, &deflate, &deflate_level)) ERR; if (timeseries) { /* Read the var as a time series. */ start[0] = 0; start[1] = 0; start[2] = 0; count[0] = TIME_LEN; count[1] = 1; count[2] = 1; /* Read the first timeseries. */ if (gettimeofday(&start_time, NULL)) ERR; if (nc_get_vara_float(ncid, varid, start, count, ts_data)) ERR_RET; if (gettimeofday(&end_time, NULL)) ERR; if (nc4_timeval_subtract(&diff_time, &end_time, &start_time)) ERR; read_1_us = (int)diff_time.tv_sec * MILLION + (int)diff_time.tv_usec; /* Read all the rest. */ if (gettimeofday(&start_time, NULL)) ERR; for (start[1] = 0; start[1] < LAT_LEN; start[1]++) for (start[2] = 1; start[2] < LON_LEN; start[2]++) if (nc_get_vara_float(ncid, varid, start, count, ts_data)) ERR_RET; if (gettimeofday(&end_time, NULL)) ERR; if (nc4_timeval_subtract(&diff_time, &end_time, &start_time)) ERR; avg_read_us = ((int)diff_time.tv_sec * MILLION + (int)diff_time.tv_usec + read_1_us) / (LAT_LEN * LON_LEN); } else { /* Read the data variable in horizontal slices. */ start[0] = 0; start[1] = 0; start[2] = 0; count[0] = 1; count[1] = LAT_LEN; count[2] = LON_LEN; /* Read (and time) the first one. */ if (gettimeofday(&start_time, NULL)) ERR; if (nc_get_vara_float(ncid, varid, start, count, hor_data)) ERR_RET; if (gettimeofday(&end_time, NULL)) ERR; if (nc4_timeval_subtract(&diff_time, &end_time, &start_time)) ERR; read_1_us = (int)diff_time.tv_sec * MILLION + (int)diff_time.tv_usec; /* Read (and time) all the rest. */ if (gettimeofday(&start_time, NULL)) ERR; for (start[0] = 1; start[0] < TIME_LEN; start[0]++) if (nc_get_vara_float(ncid, varid, start, count, hor_data)) ERR_RET; if (gettimeofday(&end_time, NULL)) ERR; if (nc4_timeval_subtract(&diff_time, &end_time, &start_time)) ERR; avg_read_us = ((int)diff_time.tv_sec * MILLION + (int)diff_time.tv_usec + read_1_us) / TIME_LEN; } /* Close file. */ if (nc_close(ncid)) ERR; /* Print results. */ printf("%d\t%d\t%d\t%.1f\t\t%d\t%d\t\t", (int)cs[0], (int)cs[1], (int)cs[2], (storage == NC_CHUNKED) ? (cache/(float)MEGABYTE) : 0, deflate, shuffle); if (timeseries) printf("%d\t\t%d\n", (int)read_1_us, (int)avg_read_us); else printf("%d\t\t%d\n", (int)read_1_us, (int)avg_read_us); return 0; }
int main() { int ncid, varid; int retval; size_t start[RANK]; size_t count[RANK]; size_t offset; char url[4096]; const char* svc = NULL; /* Find Test Server */ svc = getenv("DTSTESTSERVER"); if(svc != NULL) { const char* dtstestserver[2]; dtstestserver[0] = svc; dtstestserver[1] = NULL; svc = NC_findtestserver("dts",dtstestserver); } else svc = NC_findtestserver("dts",NULL); if(svc == NULL) { fprintf(stderr,"Cannot locate test server\n"); exit(0); } strcpy(url,PARAMS); strcat(url,svc); strcat(url,DTSTEST); printf("test_partvar: url=%s\n",url); if((retval = nc_open(url, NC_NOWRITE, &ncid))) ERR(retval); if((retval = nc_inq_varid(ncid, VAR, &varid))) ERR(retval); /* read piece by piece */ memcpy(start,start0,sizeof(start0)); memcpy(count,count0,sizeof(count0)); count[0] = 1; memset((void*)targetpart,0,sizeof(targetpart)); for(offset=0;start[0] < count0[0];start[0]++) { size_t nslice; float* fpos = (float*)targetpart; fpos += offset; if((retval = nc_get_vara_float(ncid,varid,start,count,fpos))) ERR(retval); nslice = subslice(RANK,count,1); offset += nslice; } #ifdef DEBUG dump((float*)targetpart,0,ISTA*IZ); #endif /* validate the part var */ if(!check(targetpart,start0,count0)) goto fail; if((retval = nc_close(ncid))) ERR(retval); printf("*** PASS\n"); return 0; fail: printf("*** FAIL\n"); return 1; }
int main() { int ncid, pres_varid, temp_varid; int lat_varid, lon_varid; /* The start and count arrays will tell the netCDF library where to read our data. */ size_t start[NDIMS], count[NDIMS]; /* Program variables to hold the data we will read. We will only need enough space to hold one timestep of data; one record. */ float pres_in[NLVL][NLAT][NLON]; float temp_in[NLVL][NLAT][NLON]; /* These program variables hold the latitudes and longitudes. */ float lats[NLAT], lons[NLON]; /* Loop indexes. */ int lvl, lat, lon, rec, i = 0; /* Error handling. */ int retval; /* Open the file. */ if ((retval = nc_open(FILE_NAME, NC_NOWRITE, &ncid))) ERR(retval); /* Get the varids of the latitude and longitude coordinate * variables. */ if ((retval = nc_inq_varid(ncid, LAT_NAME, &lat_varid))) ERR(retval); if ((retval = nc_inq_varid(ncid, LON_NAME, &lon_varid))) ERR(retval); /* Read the coordinate variable data. */ if ((retval = nc_get_var_float(ncid, lat_varid, &lats[0]))) ERR(retval); if ((retval = nc_get_var_float(ncid, lon_varid, &lons[0]))) ERR(retval); /* Check the coordinate variable data. */ for (lat = 0; lat < NLAT; lat++) if (lats[lat] != START_LAT + 5.*lat) return 2; for (lon = 0; lon < NLON; lon++) if (lons[lon] != START_LON + 5.*lon) return 2; /* Get the varids of the pressure and temperature netCDF * variables. */ if ((retval = nc_inq_varid(ncid, PRES_NAME, &pres_varid))) ERR(retval); if ((retval = nc_inq_varid(ncid, TEMP_NAME, &temp_varid))) ERR(retval); /* Read the data. Since we know the contents of the file we know * that the data arrays in this program are the correct size to * hold one timestep. */ count[0] = 1; count[1] = NLVL; count[2] = NLAT; count[3] = NLON; start[1] = 0; start[2] = 0; start[3] = 0; /* Read and check one record at a time. */ for (rec = 0; rec < NREC; rec++) { start[0] = rec; if ((retval = nc_get_vara_float(ncid, pres_varid, start, count, &pres_in[0][0][0]))) ERR(retval); if ((retval = nc_get_vara_float(ncid, temp_varid, start, count, &temp_in[0][0][0]))) ERR(retval); /* Check the data. */ i = 0; for (lvl = 0; lvl < NLVL; lvl++) for (lat = 0; lat < NLAT; lat++) for (lon = 0; lon < NLON; lon++) { if (pres_in[lvl][lat][lon] != SAMPLE_PRESSURE + i) return 2; if (temp_in[lvl][lat][lon] != SAMPLE_TEMP + i) return 2; i++; } } /* next record */ /* Close the file. */ if ((retval = nc_close(ncid))) ERR(retval); printf("*** SUCCESS reading example file pres_temp_4D.nc!\n"); return 0; }
int ex_get_partial_node_set_df (int exoid, ex_entity_id node_set_id, int64_t start_num, int64_t num_df_to_get, void *node_set_dist_fact) { int status; int dimid, dist_id, node_set_id_ndx; size_t num_nodes_in_set, start[1], count[1]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* first check if any node sets are specified */ if ((status = nc_inq_dimid (exoid, DIM_NUM_NS, &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: no node sets defined in file id %d", exoid); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_WARN); } /* Lookup index of node set id in VAR_NS_IDS array */ if ((node_set_id_ndx = ex_id_lkup(exoid,EX_NODE_SET,node_set_id)) < 0) { if (exerrval == EX_NULLENTITY) { sprintf(errmsg, "Warning: node set %"PRId64" is NULL in file id %d", node_set_id,exoid); ex_err("ex_get_partial_node_set_df",errmsg,EX_MSG); return (EX_WARN); } else { sprintf(errmsg, "Error: failed to locate node set %"PRId64" in %s in file id %d", node_set_id,VAR_NS_IDS,exoid); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } } /* inquire id's of previously defined dimensions and variables */ if ((status = nc_inq_dimid (exoid, DIM_NUM_NOD_NS(node_set_id_ndx), &dimid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to locate number of nodes in node set %"PRId64" in file id %d", node_set_id,exoid); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, dimid, &num_nodes_in_set)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get number of nodes in node set %"PRId64" in file id %d", node_set_id, exoid); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } /* Check input parameters for a valid range of numbers */ if (start_num < 0 || start_num > num_nodes_in_set) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid input"); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } if (num_df_to_get < 0) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: Invalid number of nodes in nodes set!"); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } /* start_num now starts at 1, not 0 */ if ((start_num + num_df_to_get - 1) > num_nodes_in_set) { exerrval = EX_BADPARAM; sprintf(errmsg, "Error: request larger than number of nodes in set!"); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } if ((status = nc_inq_varid (exoid, VAR_FACT_NS(node_set_id_ndx), &dist_id)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: dist factors not stored for node set %"PRId64" in file id %d", node_set_id,exoid); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_WARN); /* complain - but not too loud */ } /* read in the distribution factors array */ start[0] = --start_num; count[0] = num_df_to_get; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, dist_id, start, count, node_set_dist_fact); } else { status = nc_get_vara_double(exoid, dist_id, start, count, node_set_dist_fact); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get distribution factors in file id %d", exoid); ex_err("ex_get_partial_node_set_df",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
static int read_amber_cdf_timestep(void *mydata, int natoms, molfile_timestep_t *ts) { cdfdata *cdf = (cdfdata *)mydata; amberdata *amber = &cdf->amber; int rc; /* Read in the atom coordinates and unit cell information */ /* only save coords if we're given a valid ts pointer */ /* otherwise VMD wants us to skip it. */ if (ts != NULL) { size_t start[3], count[3]; start[0] = cdf->curframe; /* frame */ start[1] = 0; /* atom */ start[2] = 0; /* spatial */ count[0] = 1; count[1] = amber->atomdim; count[2] = amber->spatialdim; rc = nc_get_vara_float(cdf->ncid, amber->coordinates_id, start, count, ts->coords); if (rc != NC_NOERR) return MOLFILE_ERROR; /* apply coordinate scaling factor if not 1.0 */ if (amber->coordinates_scalefactor != 1.0) { int i; float s = amber->coordinates_scalefactor; for (i=0; i<natoms*3; i++) { ts->coords[i] *= s; } } /* Read the PBC box info. */ if (amber->has_box) { double lengths[3]; double angles[3]; start[0] = cdf->curframe; /* frame */ start[1] = 0; /* spatial */ count[0] = 1; count[1] = amber->spatialdim; rc = nc_get_vara_double(cdf->ncid, amber->cell_lengths_id, start, count, lengths); if (rc != NC_NOERR) return MOLFILE_ERROR; rc = nc_get_vara_double(cdf->ncid, amber->cell_angles_id, start, count, angles); if (rc != NC_NOERR) return MOLFILE_ERROR; ts->A = lengths[0] * amber->cell_lengths_scalefactor; ts->B = lengths[1] * amber->cell_lengths_scalefactor; ts->C = lengths[2] * amber->cell_lengths_scalefactor; ts->alpha = angles[0] * amber->cell_angles_scalefactor; ts->beta = angles[1] * amber->cell_angles_scalefactor; ts->gamma = angles[2] * amber->cell_angles_scalefactor; } } cdf->curframe++; return MOLFILE_SUCCESS; }
vtkDataSet * avtLODIParticleFileFormat::GetMesh(int ts, const char *var) { const char *mName = "avtLODIParticleFileFormat::GetMesh: "; debug4 << mName << "ts=" << ts << ", var=" << var << endl; vtkDataSet *retval = 0; bool err = true; if(strcmp(var, "particles") == 0) { TypeEnum t = NO_TYPE; int ndims = 0, *dims = 0; if(fileObject->InqVariable("part_posn", &t, &ndims, &dims)) { size_t *starts = new size_t[ndims]; size_t *counts = new size_t[ndims]; int nElems = 1; for(int i = 1; i < ndims; ++i) { starts[i] = 0; counts[i] = dims[i]; nElems *= dims[i]; } starts[0] = ts; counts[0] = 1; int nPts = nElems / 3, varId = 0; vtkPoints *pts = vtkPoints::New(); fileObject->GetVarId("part_posn", &varId); // // Get the particle mask for the current time step. // bool *particleMask = GetParticleMask(ts); if(particleMask != 0) { debug4 << mName << "Adding particles using the " << "particle mask." << endl; pts->Allocate(nPts); float *points = new float[nElems]; int status = nc_get_vara_float(fileObject->GetFileHandle(), varId, starts, counts, points); if(status == NC_NOERR) { vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::New(); ugrid->SetPoints(pts); ugrid->Allocate(nPts); vtkIdType onevertex[1]; float *fptr = points; vtkIdType ptIndex = 0; for (int i = 0 ; i < nPts ; i++) { if(particleMask[i]) { pts->InsertNextPoint(fptr); onevertex[0] = ptIndex++; ugrid->InsertNextCell(VTK_VERTEX, 1, onevertex); } fptr += 3; } debug4 << mName << "Added " << ptIndex << " points to the mesh." << endl; err = false; retval = ugrid; } else fileObject->HandleError(status); delete [] points; } else { debug4 << mName << "Adding all particles." << endl; // // Read the coordinates into the VTK points array. // int nPts = nElems / 3, varId = 0; vtkPoints *pts = vtkPoints::New(); pts->SetNumberOfPoints(nPts); float *fptr = (float *)pts->GetVoidPointer(0); int status = nc_get_vara_float(fileObject->GetFileHandle(), varId, starts, counts, fptr); if(status == NC_NOERR) { vtkUnstructuredGrid *ugrid = vtkUnstructuredGrid::New(); ugrid->SetPoints(pts); ugrid->Allocate(nPts); vtkIdType onevertex[1]; for (int i = 0 ; i < nPts ; i++) { onevertex[0] = i; ugrid->InsertNextCell(VTK_VERTEX, 1, onevertex); } err = false; retval = ugrid; } else fileObject->HandleError(status); } pts->Delete(); delete [] starts; delete [] counts; delete [] dims; } } if(err) { EXCEPTION1(InvalidVariableException, var); } return retval; }
static int read_mmtk_cdf_timestep(void *mydata, int natoms, molfile_timestep_t *ts) { cdfdata *cdf = (cdfdata *)mydata; mmtkdata *mmtk = &cdf->mmtk; int rc; /* Read in the atom coordinates and unit cell information */ /* only save coords if we're given a valid ts pointer */ /* otherwise VMD wants us to skip it. */ if (ts != NULL) { size_t start[4], count[4]; int i; if (mmtk->minor_step_numberdim == 0) { start[0] = cdf->curframe; /* step */ start[1] = 0; /* atom */ start[2] = 0; /* spatial */ start[3] = 0; /* minor step */ } else { start[0] = cdf->curframe/mmtk->minor_step_numberdim; /* step */ start[1] = 0; /* atom */ start[2] = 0; /* spatial */ start[3] = cdf->curframe % mmtk->minor_step_numberdim; /* minor step */ } count[0] = 1; count[1] = mmtk->atom_numberdim; count[2] = mmtk->xyzdim; count[3] = 1; /* only want one minor step, regardless */ rc = nc_get_vara_float(cdf->ncid, mmtk->configuration_id, start, count, ts->coords); if (rc != NC_NOERR) return MOLFILE_ERROR; /* check for allocated but not yet used frame */ if (ts->coords[0] == NC_FILL_FLOAT) return MOLFILE_ERROR; /* scale coordinates from nanometers to angstroms */ for (i=0; i<(3 * mmtk->atom_numberdim); i++) { ts->coords[i] *= 10.0f; } /* Read the PBC box info. */ if (mmtk->has_box) { float lengths[3]; if (mmtk->minor_step_numberdim == 0) { start[0] = cdf->curframe; /* step */ start[1] = 0; /* box_size */ start[2] = 0; /* minor step */ } else { start[0] = cdf->curframe/mmtk->minor_step_numberdim; /* step */ start[1] = 0; /* box_size */ start[2] = cdf->curframe % mmtk->minor_step_numberdim; /* minor step */ } count[0] = 1; count[1] = 3; count[2] = 1; rc = nc_get_vara_float(cdf->ncid, mmtk->box_size_id, start, count, lengths); if (rc != NC_NOERR) return MOLFILE_ERROR; ts->A = 10.*lengths[0]; ts->B = 10.*lengths[1]; ts->C = 10.*lengths[2]; ts->alpha = 90.; ts->beta = 90.; ts->gamma = 90.; } } cdf->curframe++; return MOLFILE_SUCCESS; }
int ex_get_nodal_var (int exoid, int time_step, int nodal_var_index, int num_nodes, void *nodal_var_vals) { int varid; int status; size_t start[3], count[3]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* inquire previously defined variable */ if (ex_large_model(exoid) == 0) { /* read values of the nodal variable */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variables in file id %d", exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --time_step; start[1] = --nodal_var_index; start[2] = 0; count[0] = 1; count[1] = 1; count[2] = num_nodes; } else { /* read values of the nodal variable -- stored as separate variables... */ /* Get the varid.... */ if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) { exerrval = status; sprintf(errmsg, "Warning: could not find nodal variable %d in file id %d", nodal_var_index, exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_WARN); } start[0] = --time_step; start[1] = 0; count[0] = 1; count[1] = num_nodes; } if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, varid, start, count, nodal_var_vals); } else { status = nc_get_vara_double(exoid, varid, start, count, nodal_var_vals); } if (status != NC_NOERR) { exerrval = status; sprintf(errmsg, "Error: failed to get nodal variables in file id %d", exoid); ex_err("ex_get_nodal_var",errmsg,exerrval); return (EX_FATAL); } return (EX_NOERR); }
/*! \internal */ int cpy_coord_val(int in_id,int out_id,char *var_nm, int in_large, int out_large) /* int in_id: input netCDF input-file ID int out_id: input netCDF output-file ID char *var_nm: input variable name */ { /* Routine to copy the coordinate data from an input netCDF file * to an output netCDF file. */ const char *routine = NULL; int temp; size_t i; size_t spatial_dim, num_nodes; size_t start[2], count[2]; nc_type var_type_in, var_type_out; void *void_ptr = NULL; /* Handle easiest situation first: in_large matches out_large */ if (in_large == out_large) return cpy_var_val(in_id, out_id, var_nm); /* At this point, know that in_large != out_large, so will need to either copy a vector to multiple scalars or vice-versa. Also will need a couple dimensions, so get them now.*/ ex_get_dimension(in_id, DIM_NUM_DIM, "dimension", &spatial_dim, &temp, routine); ex_get_dimension(in_id, DIM_NUM_NODES, "nodes", &num_nodes, &temp, routine); if (in_large == 0 && out_large == 1) { /* output file will have coordx, coordy, coordz (if 3d). */ /* Get the var_id for the requested variable from both files. */ int var_in_id, var_out_id[3]; (void)nc_inq_varid(in_id, VAR_COORD, &var_in_id); (void)nc_inq_varid(out_id, VAR_COORD_X, &var_out_id[0]); (void)nc_inq_varid(out_id, VAR_COORD_Y, &var_out_id[1]); (void)nc_inq_varid(out_id, VAR_COORD_Z, &var_out_id[2]); (void)nc_inq_vartype( in_id, var_in_id, &var_type_in); (void)nc_inq_vartype(out_id, var_out_id[0], &var_type_out); if (num_nodes > 0) void_ptr=malloc(num_nodes * type_size(var_type_in)); /* Copy each component of the variable... */ for (i=0; i < spatial_dim; i++) { start[0] = i; start[1] = 0; count[0] = 1; count[1] = num_nodes; if (var_type_in == NC_FLOAT) { nc_get_vara_float(in_id, var_in_id, start, count, void_ptr); nc_put_var_float(out_id, var_out_id[i], void_ptr); } else { assert(var_type_in == NC_DOUBLE); nc_get_vara_double(in_id, var_in_id, start, count, void_ptr); nc_put_var_double(out_id, var_out_id[i], void_ptr); } } } if (in_large == 1 && out_large == 0) { /* input file will have coordx, coordy, coordz (if 3d); output has only "coord" */ int var_in_id[3], var_out_id; (void)nc_inq_varid(in_id, VAR_COORD_X, &var_in_id[0]); (void)nc_inq_varid(in_id, VAR_COORD_Y, &var_in_id[1]); (void)nc_inq_varid(in_id, VAR_COORD_Z, &var_in_id[2]); (void)nc_inq_varid(out_id, VAR_COORD, &var_out_id); (void)nc_inq_vartype(in_id, var_in_id[0], &var_type_in); (void)nc_inq_vartype(out_id, var_out_id, &var_type_out); if (num_nodes > 0) void_ptr=malloc(num_nodes * type_size(var_type_in)); /* Copy each component of the variable... */ for (i=0; i < spatial_dim; i++) { start[0] = i; start[1] = 0; count[0] = 1; count[1] = num_nodes; if (var_type_in == NC_FLOAT) { nc_get_var_float( in_id, var_in_id[i], void_ptr); nc_put_vara_float(out_id, var_out_id, start, count, void_ptr); } else { nc_get_var_double( in_id, var_in_id[i], void_ptr); nc_put_vara_double(out_id, var_out_id, start, count, void_ptr); } } } /* Free the space that held the variable */ (void)free(void_ptr); return(EX_NOERR); } /* end cpy_coord_val() */
int main(int argc, char *argv[]) { fprintf(stdout, "start\n"); int varid; int ndims; int dimids[NC_MAX_VAR_DIMS]; size_t nx, ny, size, var_size, var_offset, i; int shm_id, shm_key; int nhours, nvars, var_i, frame; float* shm_p; float* data_p; if (argc != 9) { fprintf(stdout, "usage: ./load-dap {SHM_KEY} {NHOURS} {NVARS} {VAR_ID} {FRAME} {URL} {VAR_NAME} {Z_LEVEL}\n"); exit(EXIT_FAILURE); } fprintf(stdout, "nc_open %s\n", argv[URL]); ne(nc_open(argv[URL], 0, &ncid)); fprintf(stdout, "nc_inq\n"); ne(nc_inq_varid (ncid, argv[VAR_NAME], &varid)); ne(nc_inq_varndims(ncid, varid, &ndims)); ne(nc_inq_vardimid(ncid, varid, dimids)); fprintf(stdout, "ndims\n"); if (ndims==2) { ne(nc_inq_dimlen(ncid, dimids[0], &ny)); ne(nc_inq_dimlen(ncid, dimids[1], &nx)); } else if (ndims==3) { ne(nc_inq_dimlen(ncid, dimids[1], &ny)); ne(nc_inq_dimlen(ncid, dimids[2], &nx)); } shm_key=atoi(argv[SHM_KEY]); shm_id=shmget(shm_key, 0, 0644); if (shm_id == -1) { fprintf(stderr, "Shared memory shmget() failed\n"); exit(EXIT_FAILURE); } shm_p = shmat(shm_id, NULL, 0); if (shm_p == (void *)-1) { fprintf(stderr, "Shared memory shmat() failed\n"); exit(EXIT_FAILURE); } size=nx*ny; data_p=malloc(size*sizeof(float)); if (data_p == NULL) { fprintf(stderr, "malloc() failed\n"); exit(EXIT_FAILURE); } if (ndims==2) { ne(nc_get_var_float(ncid, varid, data_p)); } else { size_t start[3]={0,0,0}; size_t count[3]={1,ny,nx}; start[0]=atoi(argv[Z_LEVEL]); ne(nc_get_vara_float(ncid, varid, start, count, data_p)); } // run[point[var[frames[]]]] nhours=atoi(argv[NHOURS]); nvars=atoi(argv[NVARS]); frame=atoi(argv[FRAME]); var_i=atoi(argv[VAR_ID]); size_t index; var_size=nhours*nvars; var_offset=var_i*nhours+frame; for (i=0; i<size; i++) { index=i*var_size+var_offset; shm_p[index]=data_p[i]; } free(data_p); if(shmdt(shm_p)==-1){ fprintf(stderr, "Shared memory shmdt() failed\n"); exit(EXIT_FAILURE); } nc_close(ncid); return 0; }
int ex_get_partial_elem_attr(int exoid, ex_entity_id elem_blk_id, int64_t start_elem_num, int64_t num_elems, void *attrib) { int numelbdim, numattrdim, attrid, elem_blk_id_ndx, status; size_t num_elem_this_blk, num_attr, start[2], count[2]; char errmsg[MAX_ERR_LENGTH]; exerrval = 0; /* clear error code */ /* Determine index of elem_blk_id in VAR_ID_EL_BLK array */ if ((elem_blk_id_ndx = ex_id_lkup(exoid, EX_ELEM_BLOCK, elem_blk_id)) < 0) { if (exerrval == EX_NULLENTITY) { snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no attributes found for NULL block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, EX_NULLENTITY); return (EX_WARN); /* no attributes for this element block */ } snprintf(errmsg, MAX_ERR_LENGTH, "Warning: failed to locate element block %" PRId64 " in %s array in file id %d", elem_blk_id, VAR_ID_EL_BLK, exoid); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_WARN); } /* inquire id's of previously defined dimensions */ if ((status = nc_inq_dimid(exoid, DIM_NUM_EL_IN_BLK(elem_blk_id_ndx), &numelbdim)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate number of elements for block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_FATAL); } if ((status = nc_inq_dimlen(exoid, numelbdim, &num_elem_this_blk)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of elements for block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_FATAL); } if ((status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_BLK(elem_blk_id_ndx), &numattrdim)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no attributes found for block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, EX_MSG); return (EX_WARN); /* no attributes for this element block */ } if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of attributes for block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_FATAL); } if ((status = nc_inq_varid(exoid, VAR_ATTRIB(elem_blk_id_ndx), &attrid)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate attributes for block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_FATAL); } /* do some error checking */ if (num_elem_this_blk < (start_elem_num + num_elems - 1)) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: requested attributes from too many elements in " "this block, %" PRId64 "", elem_blk_id); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_FATAL); } /* read in the attributes */ start[0] = --start_elem_num; start[1] = 0; count[0] = num_elems; count[1] = num_attr; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, attrid, start, count, attrib); } else { status = nc_get_vara_double(exoid, attrid, start, count, attrib); } if (status != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get attributes for block %" PRId64 " in file id %d", elem_blk_id, exoid); ex_err("ex_get_partial_elem_attr", errmsg, exerrval); return (EX_FATAL); } return (EX_NOERR); }
int ex_get_coord(int exoid, void *x_coor, void *y_coor, void *z_coor) { int status; int coordid; int coordidx, coordidy, coordidz; int numnoddim, ndimdim; size_t num_nod, num_dim, start[2], count[2], i; char errmsg[MAX_ERR_LENGTH]; EX_FUNC_ENTER(); ex_check_valid_file_id(exoid, __func__); /* inquire id's of previously defined dimensions */ if (ex_get_dimension(exoid, DIM_NUM_DIM, "dimension count", &num_dim, &ndimdim, __func__) != NC_NOERR) { EX_FUNC_LEAVE(EX_FATAL); } if (nc_inq_dimid(exoid, DIM_NUM_NODES, &numnoddim) != NC_NOERR) { /* If not found, then this file is storing 0 nodes. Return immediately */ EX_FUNC_LEAVE(EX_NOERR); } if ((status = nc_inq_dimlen(exoid, numnoddim, &num_nod)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get number of nodes in file id %d", exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } /* read in the coordinates */ if (ex_large_model(exoid) == 0) { if ((status = nc_inq_varid(exoid, VAR_COORD, &coordid)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate nodal coordinates in file id %d", exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } for (i = 0; i < num_dim; i++) { char *which = NULL; start[0] = i; start[1] = 0; count[0] = 1; count[1] = num_nod; if (i == 0 && x_coor != NULL) { which = "X"; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, coordid, start, count, x_coor); } else { status = nc_get_vara_double(exoid, coordid, start, count, x_coor); } } else if (i == 1 && y_coor != NULL) { which = "Y"; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, coordid, start, count, y_coor); } else { status = nc_get_vara_double(exoid, coordid, start, count, y_coor); } } else if (i == 2 && z_coor != NULL) { which = "Z"; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, coordid, start, count, z_coor); } else { status = nc_get_vara_double(exoid, coordid, start, count, z_coor); } } if (status != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s coord array in file id %d", which, exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } } } else { if ((status = nc_inq_varid(exoid, VAR_COORD_X, &coordidx)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate x nodal coordinates in file id %d", exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } if (num_dim > 1) { if ((status = nc_inq_varid(exoid, VAR_COORD_Y, &coordidy)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate y nodal coordinates in file id %d", exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } } else { coordidy = 0; } if (num_dim > 2) { if ((status = nc_inq_varid(exoid, VAR_COORD_Z, &coordidz)) != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate z nodal coordinates in file id %d", exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } } else { coordidz = 0; } /* write out the coordinates */ for (i = 0; i < num_dim; i++) { void *coor = NULL; char *which = NULL; if (i == 0) { coor = x_coor; which = "X"; coordid = coordidx; } else if (i == 1) { coor = y_coor; which = "Y"; coordid = coordidy; } else if (i == 2) { coor = z_coor; which = "Z"; coordid = coordidz; } if (coor != NULL && coordid != 0) { if (ex_comp_ws(exoid) == 4) { status = nc_get_var_float(exoid, coordid, coor); } else { status = nc_get_var_double(exoid, coordid, coor); } if (status != NC_NOERR) { snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get %s coord array in file id %d", which, exoid); ex_err(__func__, errmsg, status); EX_FUNC_LEAVE(EX_FATAL); } } } } EX_FUNC_LEAVE(EX_NOERR); }
int ex_get_partial_set_dist_fact(int exoid, ex_entity_type set_type, ex_entity_id set_id, int64_t offset, int64_t num_to_put, void *set_dist_fact) { int dimid, dist_id, set_id_ndx; int status; size_t start[1], count[1]; char errmsg[MAX_ERR_LENGTH]; char * factptr = NULL; ex_check_valid_file_id(exoid); exerrval = 0; /* clear error code */ /* first check if any sets are specified */ if ((status = nc_inq_dimid(exoid, ex_dim_num_objects(set_type), &dimid)) != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "Warning: no %s sets stored in file id %d", ex_name_of_object(set_type), exoid); ex_err("ex_get_partial_set_dist_fact", errmsg, exerrval); return (EX_WARN); } /* Lookup index of set id in VAR_*S_IDS array */ set_id_ndx = ex_id_lkup(exoid, set_type, set_id); if (exerrval != 0) { if (exerrval == EX_NULLENTITY) { snprintf(errmsg, MAX_ERR_LENGTH, "Warning: %s set %" PRId64 " is NULL in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_partial_set_dist_fact", errmsg, EX_NULLENTITY); return (EX_WARN); } snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate %s set %" PRId64 " in VAR_*S_IDS array in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_partial_set_dist_fact", errmsg, exerrval); return (EX_FATAL); } /* setup more pointers based on set_type */ if (set_type == EX_NODE_SET) { factptr = VAR_FACT_NS(set_id_ndx); } else if (set_type == EX_EDGE_SET) { factptr = VAR_FACT_ES(set_id_ndx); } else if (set_type == EX_FACE_SET) { factptr = VAR_FACT_FS(set_id_ndx); } else if (set_type == EX_SIDE_SET) { factptr = VAR_FACT_SS(set_id_ndx); } if (set_type == EX_ELEM_SET) { factptr = VAR_FACT_ELS(set_id_ndx); } /* inquire id's of previously defined dimensions and variables */ if ((status = nc_inq_varid(exoid, factptr, &dist_id)) != NC_NOERR) { exerrval = status; /* not an error for node sets because this is how we check that df's exist */ if (set_type == EX_NODE_SET) { snprintf(errmsg, MAX_ERR_LENGTH, "Warning: dist factors not stored for %s set %" PRId64 " in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_partial_set_dist_fact", errmsg, exerrval); return (EX_WARN); /* complain - but not too loud */ } /* is an error for other sets */ snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to locate dist factors list for %s set %" PRId64 " in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_partial_set_dist_fact", errmsg, exerrval); return (EX_FATAL); } /* read in the distribution factors array */ start[0] = offset - 1; count[0] = num_to_put; if (ex_comp_ws(exoid) == 4) { status = nc_get_vara_float(exoid, dist_id, start, count, set_dist_fact); } else { status = nc_get_vara_double(exoid, dist_id, start, count, set_dist_fact); } if (status != NC_NOERR) { exerrval = status; snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get dist factors list for %s set %" PRId64 " in file id %d", ex_name_of_object(set_type), set_id, exoid); ex_err("ex_get_partial_set_dist_fact", errmsg, exerrval); return (EX_FATAL); } return (EX_NOERR); }