Exemple #1
0
// TODO: Use Box class
int NetcdfFile::SetupBox(double* boxIn, NCTYPE typeIn) {
    boxIn[0] = 0.0;
    boxIn[1] = 0.0;
    boxIn[2] = 0.0;
    boxIn[3] = 0.0;
    boxIn[4] = 0.0;
    boxIn[5] = 0.0;
    if ( nc_inq_varid(ncid_,NCCELL_LENGTHS,&cellLengthVID_)==NC_NOERR ) {
        if (checkNCerr(nc_inq_varid(ncid_,NCCELL_ANGLES,&cellAngleVID_)) ) {
            mprinterr("Error: Getting cell angles.\n");
            return 1;
        }
        if (ncdebug_>0) mprintf("  Netcdf Box information found.\n");
        // If present, get box angles. These will be used to determine the box
        // type in TrajectoryFile.
        start_[0]=0;
        start_[1]=0;
        start_[2]=0;
        start_[3]=0;
        switch (typeIn) {
        case NC_AMBERRESTART:
            count_[0]=3;
            count_[1]=0;
            count_[2]=0;
            break;
        case NC_AMBERTRAJ:
            count_[0]=1;
            count_[1]=3;
            count_[2]=0;
            break;
        case NC_AMBERENSEMBLE:
            count_[0]=1; // NOTE: All ensemble members must have same box type
            count_[1]=1; // TODO: Check all members?
            count_[2]=3;
            break;
        case NC_UNKNOWN:
            return 1; // Sanity check
        }
        count_[3]=0;
        if ( checkNCerr(nc_get_vara_double(ncid_, cellLengthVID_, start_, count_, boxIn )) )
        {
            mprinterr("Error: Getting cell lengths.\n");
            return 1;
        }
        if ( checkNCerr(nc_get_vara_double(ncid_, cellAngleVID_, start_, count_, boxIn+3)) )
        {
            mprinterr("Error: Getting cell angles.\n");
            return 1;
        }
        if (ncdebug_ > 0) mprintf("\tNetcdf Box: XYZ={%f %f %f} ABG={%f %f %f}\n",
                                      boxIn[0], boxIn[1], boxIn[2], boxIn[3], boxIn[4], boxIn[5]);
        return 0;
    }
    // No box information
    return -1;
}
/** 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,double *X, double *V,double *box, double *T) {
  // Get temperature
  if (TempVID_!=-1) {
    start_[0] = set;
    count_[0] = 1;
    if ( checkNCerr(nc_get_vara_double(ncid_, TempVID_, start_, count_, T)) ) {
      mprinterr("Error: Getting replica temperature.\n"); 
      return 1;
    }
    //fprintf(stderr,"DEBUG: Replica Temperature %lf\n",F->T);
  }

  // Read Coords 
  start_[0] = set;
  start_[1] = 0;
  start_[2] = 0;
  count_[0] = 1;
  count_[1] = Ncatom();
  count_[2] = 3;
  if ( checkNCerr(nc_get_vara_float(ncid_, coordVID_, start_, count_, Coord_)) ) {
    mprinterr("Error: Getting frame %i\n", set);
    return 1;
  }
  FloatToDouble(X, Coord_);

  // Read Velocities
  if (velocityVID_ != -1) {
    if ( checkNCerr(nc_get_vara_float(ncid_, velocityVID_, start_, count_, Veloc_)) ) {
      mprinterr("Error: Getting velocities for frame %i\n", set);
      return 1;
    }
    FloatToDouble(V, Veloc_);
  }

  // Read box info 
  if (cellLengthVID_ != -1) {
    count_[1] = 3;
    count_[2] = 0;
    if ( checkNCerr(nc_get_vara_double(ncid_, cellLengthVID_, start_, count_, box)) ) {
      mprinterr("Getting cell lengths.\n");
      return 1;
    }
    if ( checkNCerr(nc_get_vara_double(ncid_, cellAngleVID_, start_, count_, box+3)) ) {
      mprinterr("Getting cell angles.\n");
      return 1;
    }
  }


  return 0;
}
int ex_get_glob_vars (int   exoid,
                      int   time_step,
                      int   num_glob_vars,
                      void *glob_var_vals)
{
   int varid;
   int status;
   size_t start[2], count[2];
   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,
            "Warning: failed to locate global variables in file id %d",
            exoid);
     ex_err("ex_get_glob_vars",errmsg,exerrval);
     return (EX_WARN);
   }

   /* Verify that time_step is within bounds */
   {
    int num_time_steps = ex_inquire_int (exoid, EX_INQ_TIME);
    if (time_step <= 0 || time_step > num_time_steps) {
      sprintf(errmsg,
              "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_nodal_var",errmsg,EX_BADPARAM);
      return (EX_FATAL);
    }
  }

   /* read values of global variables */
   start[0] = --time_step;
   start[1] = 0;

   count[0] = 1;
   count[1] = num_glob_vars;

   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 values from file id %d",
            exoid);
     ex_err("ex_get_glob_vars",errmsg,exerrval);
     return (EX_FATAL);
   }
   return (EX_NOERR);
}
/** Get the specified frame from amber netcdf file
  * Coords are a 1 dimensional array of format X1,Y1,Z1,X2,Y2,Z2,...
  */
int Traj_AmberRestartNC::readFrame(int set,double *X, double *V,double *box, double *T) {
  // Get temperature
  if (TempVID_!=-1) {
    if ( checkNCerr(nc_get_var_double(ncid_, TempVID_, T)) ) {
      mprinterr("Error: Getting replica temperature.\n");
      return 1;
    }
    if (debug_>1) mprintf("DEBUG: %s: Replica Temperature %lf\n",filename_.base(), T);
  }

  // Read Coords 
  start_[0] = 0;
  start_[1] = 0;
  count_[0] = Ncatom();
  count_[1] = 3;
  if ( checkNCerr(nc_get_vara_double(ncid_, coordVID_, start_, count_, X)) ) {
    mprinterr("Error: Getting Coords\n");
    return 1;
  }

  // Read Velocity
  if (velocityVID_!=-1 && V!=0) {
    if ( checkNCerr(nc_get_vara_double(ncid_, velocityVID_, start_, count_, V)) ) {
      mprinterr("Error: Getting velocities\n"); 
      return 1;
    }
  }

  // Read box info 
  if (cellLengthVID_ != -1) {
    count_[0] = 3;
    count_[1] = 0;
    if ( checkNCerr(nc_get_vara_double(ncid_, cellLengthVID_, start_, count_, box)) ) {
      mprinterr("Error: Getting cell lengths.\n"); 
      return 1;
    }
    if ( checkNCerr(nc_get_vara_double(ncid_, cellAngleVID_, start_, count_, box+3)) ) {
      mprinterr("Error: Getting cell angles.\n");
      return 1;
    }
  }

  return 0;
}
Exemple #5
0
NcValues* NcVar::values( void ) const
{
    int ndims = num_dims();
    size_t crnr[NC_MAX_DIMS];
    size_t edgs[NC_MAX_DIMS];
    for (int i = 0; i < ndims; i++) {
	crnr[i] = 0;
	edgs[i] = get_dim(i)->size();
    }
    NcValues* valp = get_space();
    int status;
    switch (type()) {
    case ncFloat:
	status = NcError::set_err(
				  nc_get_vara_float(the_file->id(), the_id, crnr, edgs, 
				   (float *)valp->base())
				  );
	break;
    case ncDouble:
	status = NcError::set_err(
				  nc_get_vara_double(the_file->id(), the_id, crnr, edgs, 
				    (double *)valp->base())
				  );
	break;
    case ncInt:
	status = NcError::set_err(
				  nc_get_vara_int(the_file->id(), the_id, crnr, edgs, 
				 (int *)valp->base())
				  );
	break;
    case ncShort:
	status = NcError::set_err(
				  nc_get_vara_short(the_file->id(), the_id, crnr, edgs, 
				   (short *)valp->base())
				  );
	break;
    case ncByte:
	status = NcError::set_err(
				  nc_get_vara_schar(the_file->id(), the_id, crnr, edgs, 
				   (signed char *)valp->base())
				  );
	break;
    case ncChar:
	status = NcError::set_err(
				  nc_get_vara_text(the_file->id(), the_id, crnr, edgs, 
				   (char *)valp->base())
				  );
	break;
    case ncNoType:
    default:
	return 0;
    }
    if (status != NC_NOERR)
	return 0;
    return valp;
}
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];
   char  errmsg[MAX_ERR_LENGTH];

   exerrval = 0; /* clear error code */

   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
      */
     end_time_step = ex_inquire_int(exoid, EX_INQ_TIME);
   }

   end_time_step--;

   /* read values of global variables */
   start[0] = --beg_time_step;
   start[1] = --glob_var_index;

   count[0] = end_time_step - beg_time_step + 1;
   count[1] = 1;

   /* 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);
   }

   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);
}
Exemple #7
0
NCstate NCdsHandleGContLoadCache(NCdsHandleGCont_t *gCont, size_t sTStep, size_t nTSteps, size_t sLevel,
                                 size_t nLevels) {
    int status;
    size_t start[4], count[4];
    size_t ncidx, tStep, level, row, col;
    double val;

    count[0] = 1;
    if (gCont->LVarIds[0] == NCundefined) {
        start[1] = (size_t) 0;
        count[1] = gCont->RowNum;
        start[2] = (size_t) 0;
        count[2] = gCont->ColNum;
    }
    else {
        count[1] = 1;
        start[2] = (size_t) 0;
        count[2] = gCont->RowNum;
        start[3] = (size_t) 0;
        count[3] = gCont->ColNum;
    }
    for (row = 0; row < gCont->RowNum; row++)
        for (col = 0; col < gCont->ColNum; col++) {
            gCont->ObsNum[gCont->ColNum * row + col] = (size_t) 0;
            gCont->Data[gCont->ColNum * row + col] = (double) 0.0;
        }
    for (tStep = sTStep; tStep < sTStep + nTSteps; tStep++)
        for (level = sLevel; level < sLevel + nLevels; level++) {
            ncidx = gCont->NCindex[tStep];
            start[0] = tStep - gCont->NCoffset[ncidx];
            if (gCont->LVarIds[ncidx] != NCundefined) start[1] = level;
            if ((status = nc_sync(gCont->NCIds[ncidx])) != NC_NOERR) {
                NCprintNCError (status, "NCdsHandleGContLoadCache");
                return (NCfailed);
            }
            if ((status = nc_get_vara_double(gCont->NCIds[ncidx], gCont->GVarIds[ncidx], start, count,
                                             gCont->AuxData)) != NC_NOERR) {
                NCprintNCError (status, "NCdsHandleGContLoadCache");
                return (NCfailed);
            }
            for (row = 0; row < gCont->RowNum; row++)
                for (col = 0; col < gCont->ColNum; col++)
                    if (_NCdsHandleGContTestNodata(gCont, (val = gCont->AuxData[gCont->ColNum * row + col])) == false) {
                        gCont->Data[gCont->ColNum * row + col] += val;
                        gCont->ObsNum[gCont->ColNum * row + col] += 1;
                    }
        }
    for (row = 0; row < gCont->RowNum; row++)
        for (col = 0; col < gCont->ColNum; col++)
            if (gCont->ObsNum[gCont->ColNum * row + col] == 0) NCdsHandleGContSetFill(gCont, row, col);
            else if (gCont->ObsNum[gCont->ColNum * row + col] > 1)
                gCont->Data[gCont->ColNum * row + col] /= (double) gCont->ObsNum[gCont->ColNum * row + col];
    return (NCsucceeded);
}
int ex_get_glob_vars_int(int exoid, int time_step, int num_glob_vars, void *glob_var_vals)
{
  int    varid;
  int    status;
  size_t start[2], count[2];
  char   errmsg[MAX_ERR_LENGTH];

  EX_FUNC_ENTER();
  ex_check_valid_file_id(exoid, __func__);

  /* inquire previously defined variable */
  if ((status = nc_inq_varid(exoid, VAR_GLO_VAR, &varid)) != NC_NOERR) {
    snprintf(errmsg, MAX_ERR_LENGTH, "Warning: failed to locate global variables in file id %d",
             exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_WARN);
  }

  /* Verify that time_step is within bounds */
  {
    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(__func__, errmsg, EX_BADPARAM);
      EX_FUNC_LEAVE(EX_FATAL);
    }
  }

  /* read values of global variables */
  start[0] = --time_step;
  start[1] = 0;

  count[0] = 1;
  count[1] = num_glob_vars;

  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) {
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to get global variable values from file id %d",
             exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_FATAL);
  }
  EX_FUNC_LEAVE(EX_NOERR);
}
Exemple #9
0
int ex_get_nodal_varid_var(int   exoid,
                           int   time_step,
                           int   nodal_var_index,
                           int   num_nodes, 
                           int   varid,
                           void *nodal_var_vals)
{
  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) {
    start[0] = --time_step;
    start[1] = --nodal_var_index;
    start[2] = 0;

    count[0] = 1;
    count[1] = 1;
    count[2] = num_nodes;
  } else {

    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_varid_var",errmsg,exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);
}
Exemple #10
0
int ex_get_glob_vars (int   exoid,
                      int   time_step,
                      int   num_glob_vars,
                      void *glob_var_vals)
{
    int varid;
    int status;
    size_t start[2], count[2];
    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,
                "Warning: failed to locate global variables in file id %d",
                exoid);
        ex_err("ex_get_glob_vars",errmsg,exerrval);
        return (EX_WARN);
    }

    /* read values of global variables */
    start[0] = --time_step;
    start[1] = 0;

    count[0] = 1;
    count[1] = num_glob_vars;

    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 values from file id %d",
                exoid);
        ex_err("ex_get_glob_vars",errmsg,exerrval);
        return (EX_FATAL);
    }
    return (EX_NOERR);
}
Exemple #11
0
CPLErr GMTRasterBand::IReadBlock( CPL_UNUSED int nBlockXOff, int nBlockYOff,
                                  void * pImage )
{
    size_t start[2], edge[2];
    int    nErr = NC_NOERR;
    int    cdfid = ((GMTDataset *) poDS)->cdfid;
    
    CPLMutexHolderD(&hNCMutex);

    start[0] = nBlockYOff * nBlockXSize;
    edge[0] = nBlockXSize;

    if( eDataType == GDT_Byte )
        nErr = nc_get_vara_uchar( cdfid, nZId, start, edge, 
                                  (unsigned char *) pImage );
    else if( eDataType == GDT_Int16 )
        nErr = nc_get_vara_short( cdfid, nZId, start, edge, 
                                  (short int *) pImage );
    else if( eDataType == GDT_Int32 )
    {
        if( sizeof(long) == 4 )
            nErr = nc_get_vara_long( cdfid, nZId, start, edge, 
                                     (long *) pImage );
        else
            nErr = nc_get_vara_int( cdfid, nZId, start, edge, 
                                    (int *) pImage );
    }
    else if( eDataType == GDT_Float32 )
        nErr = nc_get_vara_float( cdfid, nZId, start, edge, 
                                  (float *) pImage );
    else if( eDataType == GDT_Float64 )
        nErr = nc_get_vara_double( cdfid, nZId, start, edge, 
                                   (double *) pImage );

    if( nErr != NC_NOERR )
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "GMT scanline fetch failed: %s", 
                  nc_strerror( nErr ) );
        return CE_Failure;
    }
    else
        return CE_None;
}
Exemple #12
0
double *NCdataGetVector(int ncid, int dimid, int varid, size_t *len) {
    int status;
    size_t start;
    double *coords;

    if ((dimid == NCfailed) || (varid == NCfailed)) return ((double *) NULL);
    if ((status = nc_inq_dimlen(ncid, dimid, len)) != NC_NOERR) {
        NCprintNCError (status, "NCdataGetVector");
        return ((double *) NULL);
    }
    if ((coords = (double *) calloc(*len, sizeof(double))) == (double *) NULL) {
        CMmsgPrint(CMmsgSysError, "Memory allocation error in: %s %d", __FILE__, __LINE__);
        return ((double *) NULL);
    }
    start = 0;
    if ((status = nc_get_vara_double(ncid, varid, &start, len, coords)) != NC_NOERR) {
        NCprintNCError (status, "NCdataGetVector");
        free(coords);
        return ((double *) NULL);
    }
    return (coords);
}
void read_netcdf(char *filename, char *varname, size_t *start, size_t *count, double *snaps)
{
    int ncid_rd, retval_rd;
    int vel_varid_rd;

    /*  ******** PREPARE TO READ ************* */
    /* Open the file. NC_NOWRITE tells netCDF we want read-only access to the file.*/
    if ((retval_rd = nc_open(filename, NC_NOWRITE, &ncid_rd)))
        ERR(retval_rd);

    /* Get the varids of the velocity in netCDF */
    if ((retval_rd = nc_inq_varid(ncid_rd, varname, &vel_varid_rd)))
        ERR(retval_rd);

    if ((retval_rd = nc_get_vara_double(ncid_rd, vel_varid_rd, start, count, &snaps[0])))
        ERR(retval_rd);

    /* Close the file, freeing all resources. */
    if ((retval_rd = nc_close(ncid_rd)))
        ERR(retval_rd);

    printf("\n *** SUCCESS reading variables \"%s\" from \"%s\" \n", varname, filename);
}
Exemple #14
0
Fichier : ncdf.c Projet : cran/ncdf
void R_nc_get_vara_double( int *ncid, int *varid, int *start, 
	int *count, double *data, int *retval )
{
	int	i, err, ndims;
	size_t	s_start[MAX_NC_DIMS], s_count[MAX_NC_DIMS];
	char	vn[2048];

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

	for( i=0; i<ndims; i++ ) {
		s_start[i] = (size_t)start[i];
		s_count[i] = (size_t)count[i];
		}
		
	*retval = nc_get_vara_double(*ncid, *varid, s_start, s_count, data );
	if( *retval != NC_NOERR ) {
		nc_inq_varname( *ncid, *varid, vn );
		REprintf( "Error in R_nc_get_vara_double: %s\n", 
			nc_strerror(*retval) );
		REprintf( "Var: %s  Ndims: %d   Start: ", vn, ndims );
		for( i=0; i<ndims; i++ ) {
			REprintf( "%u", (unsigned int)s_start[i] );
			if( i < ndims-1 )
				REprintf( "," );
			}
		REprintf( "Count: " );
		for( i=0; i<ndims; i++ ) {
			REprintf( "%u", (unsigned int)s_count[i] );
			if( i < ndims-1 )
				REprintf( "," );
			}
		}
}
Exemple #15
0
/*********************************************************************
  void mpp_get_var_value_block(int fid, int vid, const size_t *start, const size_t *nread, void *data)
  read part of var data, the part is defined by start and nread.
*********************************************************************/
void mpp_get_var_value_block(int fid, int vid, const size_t *start, const size_t *nread, void *data)
{
  int status;
  char errmsg[512];
  
  if(fid<0 || fid >=nfiles) mpp_error("mpp_io(mpp_get_var_value_block): invalid fid number, fid should be "
				    "a nonnegative integer that less than nfiles");
  if(vid<0 || vid >=files[fid].nvar) mpp_error("mpp_io(mpp_get_var_value_block): invalid vid number, vid should be "
				    "a nonnegative integer that less than nvar");

  switch(files[fid].var[vid].type) {
  case NC_DOUBLE:case NC_FLOAT:
    status = nc_get_vara_double(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break;
  case NC_INT:
    status = nc_get_vara_int(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break;
  case NC_SHORT:
    status = nc_get_vara_short(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break;  
  case NC_CHAR:
    status = nc_get_vara_text(files[fid].ncid, files[fid].var[vid].fldid, start, nread, data);
    break; 
  default:
    sprintf(errmsg, "mpp_io(mpp_get_var_value_block): field %s in file %s has an invalid type, "
	    "the type should be NC_DOUBLE, NC_FLOAT, NC_INT, NC_SHORT or NC_CHAR",
	    files[fid].var[vid].name, files[fid].name );
    mpp_error(errmsg);
  }    
  if(status != NC_NOERR) {
    sprintf(errmsg, "mpp_io(mpp_get_var_value_block): Error in getting value of variable %s from file %s",
	    files[fid].var[vid].name, files[fid].name );
    netcdf_error(errmsg, status);
  }
  
}; /* mpp_get_var_value_block */
int ex_get_partial_coord(int exoid, int64_t start_node_num, int64_t num_nodes, void *x_coor,
                         void *y_coor, void *z_coor)
{
  int status;
  int coordid;
  int coordidx, coordidy, coordidz;

  int    numnoddim, ndimdim;
  size_t num_nod;
  size_t 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 (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);
  }

  --start_node_num;
  if (start_node_num + num_nodes > num_nod) {
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: start index (%" PRId64 ") + node count (%" PRId64
             ") is larger than total number of nodes (%" ST_ZU ") in file id %d",
             start_node_num, num_nodes, num_nod, exoid);
    ex_err(__func__, errmsg, EX_BADPARAM);
    EX_FUNC_LEAVE(EX_FATAL);
  }

  if (ex_get_dimension(exoid, DIM_NUM_DIM, "dimension count", &num_dim, &ndimdim, __func__) !=
      NC_NOERR) {
    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;
      start[0] = i;
      start[1] = start_node_num;

      count[0] = 1;
      count[1] = num_nodes;
      if (count[1] == 0) {
        start[1] = 0;
      }

      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;

      start[0] = start_node_num;
      count[0] = num_nodes;
      if (count[0] == 0) {
        start[0] = 0;
      }

      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_vara_float(exoid, coordid, start, count, coor);
        }
        else {
          status = nc_get_vara_double(exoid, coordid, start, count, 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);
}
Exemple #17
0
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);
}
Exemple #18
0
GDALDataset *GMTDataset::Open( GDALOpenInfo * poOpenInfo )

{
/* -------------------------------------------------------------------- */
/*      Does this file have the GMT magic number?                    */
/* -------------------------------------------------------------------- */
    if( poOpenInfo->fpL == NULL || poOpenInfo->nHeaderBytes < 50 )
        return NULL;

    if( poOpenInfo->pabyHeader[0] != 'C' 
        || poOpenInfo->pabyHeader[1] != 'D' 
        || poOpenInfo->pabyHeader[2] != 'F' 
        || poOpenInfo->pabyHeader[3] != 1 )
        return NULL;
    
    CPLMutexHolderD(&hNCMutex);

/* -------------------------------------------------------------------- */
/*      Try opening the dataset.                                        */
/* -------------------------------------------------------------------- */
    int cdfid, nm_id, dim_count, z_id;

    if( nc_open( poOpenInfo->pszFilename, NC_NOWRITE, &cdfid ) != NC_NOERR )
        return NULL;

    if( nc_inq_varid( cdfid, "dimension", &nm_id ) != NC_NOERR 
        || nc_inq_varid( cdfid, "z", &z_id ) != NC_NOERR )
    {
#ifdef notdef
        CPLError( CE_Warning, CPLE_AppDefined, 
                  "%s is a GMT file, but not in GMT configuration.",
                  poOpenInfo->pszFilename );
#endif
        nc_close( cdfid );
        return NULL;
    }

    if( nc_inq_ndims( cdfid, &dim_count ) != NC_NOERR || dim_count < 2 )
    {
        nc_close( cdfid );
        return NULL;
    }
    
/* -------------------------------------------------------------------- */
/*      Confirm the requested access is supported.                      */
/* -------------------------------------------------------------------- */
    if( poOpenInfo->eAccess == GA_Update )
    {
        nc_close( cdfid );
        CPLError( CE_Failure, CPLE_NotSupported, 
                  "The GMT driver does not support update access to existing"
                  " datasets.\n" );
        return NULL;
    }
    
/* -------------------------------------------------------------------- */
/*      Create a corresponding GDALDataset.                             */
/* -------------------------------------------------------------------- */
    GMTDataset 	*poDS;

    CPLReleaseMutex(hNCMutex);  // Release mutex otherwise we'll deadlock with GDALDataset own mutex
    poDS = new GMTDataset();
    CPLAcquireMutex(hNCMutex, 1000.0);

    poDS->cdfid = cdfid;
    poDS->z_id = z_id;
    
/* -------------------------------------------------------------------- */
/*      Get dimensions.  If we can't find this, then this is a          */
/*      GMT file, but not a normal grid product.                     */
/* -------------------------------------------------------------------- */
    size_t start[2], edge[2];
    int    nm[2];

    start[0] = 0;
    edge[0] = 2;

    nc_get_vara_int(cdfid, nm_id, start, edge, nm);
    
    poDS->nRasterXSize = nm[0];
    poDS->nRasterYSize = nm[1];

/* -------------------------------------------------------------------- */
/*      Fetch "z" attributes scale_factor, add_offset, and              */
/*      node_offset.                                                    */
/* -------------------------------------------------------------------- */
    double scale_factor=1.0, add_offset=0.0;
    int node_offset = 1;

    nc_get_att_double( cdfid, z_id, "scale_factor", &scale_factor );
    nc_get_att_double( cdfid, z_id, "add_offset", &add_offset );
    nc_get_att_int( cdfid, z_id, "node_offset", &node_offset );

/* -------------------------------------------------------------------- */
/*      Get x/y range information.                                      */
/* -------------------------------------------------------------------- */
    int x_range_id, y_range_id;

    if( nc_inq_varid (cdfid, "x_range", &x_range_id) == NC_NOERR 
        && nc_inq_varid (cdfid, "y_range", &y_range_id) == NC_NOERR )
    {
        double x_range[2], y_range[2];

        nc_get_vara_double( cdfid, x_range_id, start, edge, x_range );
        nc_get_vara_double( cdfid, y_range_id, start, edge, y_range );

        // Pixel is area
        if( node_offset == 1 )
        {
            poDS->adfGeoTransform[0] = x_range[0];
            poDS->adfGeoTransform[1] = 
                (x_range[1] - x_range[0]) / poDS->nRasterXSize;
            poDS->adfGeoTransform[2] = 0.0;
            poDS->adfGeoTransform[3] = y_range[1];
            poDS->adfGeoTransform[4] = 0.0;
            poDS->adfGeoTransform[5] = 
                (y_range[0] - y_range[1]) / poDS->nRasterYSize;
        }

        // Pixel is point - offset by half pixel. 
        else /* node_offset == 0 */ 
        {
            poDS->adfGeoTransform[1] = 
                (x_range[1] - x_range[0]) / (poDS->nRasterXSize-1);
            poDS->adfGeoTransform[0] = 
                x_range[0] - poDS->adfGeoTransform[1]*0.5;
            poDS->adfGeoTransform[2] = 0.0;
            poDS->adfGeoTransform[4] = 0.0;
            poDS->adfGeoTransform[5] = 
                (y_range[0] - y_range[1]) / (poDS->nRasterYSize-1);
            poDS->adfGeoTransform[3] = 
                y_range[1] - poDS->adfGeoTransform[5]*0.5;
        }
    }
    else
    {
        poDS->adfGeoTransform[0] = 0.0;
        poDS->adfGeoTransform[1] = 1.0;
        poDS->adfGeoTransform[2] = 0.0;
        poDS->adfGeoTransform[3] = 0.0;
        poDS->adfGeoTransform[4] = 0.0;
        poDS->adfGeoTransform[5] = 1.0;
    }

/* -------------------------------------------------------------------- */
/*      Create band information objects.                                */
/* -------------------------------------------------------------------- */
    poDS->nBands = 1;
    poDS->SetBand( 1, new GMTRasterBand( poDS, z_id, 1 ));

    if( scale_factor != 1.0 || add_offset != 0.0 )
    {
        poDS->GetRasterBand(1)->SetOffset( add_offset );
        poDS->GetRasterBand(1)->SetScale( scale_factor );
    }

/* -------------------------------------------------------------------- */
/*      Initialize any PAM information.                                 */
/* -------------------------------------------------------------------- */
    poDS->SetDescription( poOpenInfo->pszFilename );

    CPLReleaseMutex(hNCMutex); // Release mutex otherwise we'll deadlock with GDALDataset own mutex
    poDS->TryLoadXML();

/* -------------------------------------------------------------------- */
/*      Check for external overviews.                                   */
/* -------------------------------------------------------------------- */
    poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename, poOpenInfo->GetSiblingFiles() );
    CPLAcquireMutex(hNCMutex, 1000.0);

    return( poDS );
}
Exemple #19
0
bool
QA::postProc_outlierTest(void)
{
  bool retCode=false;

  for( size_t i=0 ; i < qaExp.varMeDa.size() ; ++i )
  {
     VariableMetaData &vMD = qaExp.varMeDa[i] ;

     if( ! vMD.qaData.enableOutlierTest )
        continue ;

     if( ! vMD.qaData.statAve.getSampleSize()  )
     {
       // compatibility mode: determine the statistics of old-fashioned results
       // note: the qa_<variable>.nc file becomes updated
       std::vector<std::string> vars ;
       std::string statStr;

       size_t recNum=nc->getNumOfRecords(true); // force new inquiry
       double val;
       std::vector<double> dv;
       MtrxArr<double> mv;

       if( vMD.var->isNoData() )
         continue;

       vars.clear();

       // post-processing of data before statistics was vMD inherent?
       vars.push_back( vMD.var->name + "_min" );
       vars.push_back( vMD.var->name + "_max" );
       vars.push_back( vMD.var->name + "_ave" );

       bool is=false;
       bool is2=true;
       for( size_t j=0 ; j < vars.size() ; ++j )
       {
         // read the statistics
         nc->getAttValues( dv, "valid_range", vars[j]);
         if( dv[0] == MAXDOUBLE )
         {
            is=true; // no valid statistics
            break;
         }
         statStr  ="sampleMin=" ;
         statStr += hdhC::double2String( dv[0] );
         statStr +=", sampleMax=" ;
         statStr += hdhC::double2String( dv[1] );
         statStr += ", ";
         statStr += nc->getAttString("statistics", vars[j], is2) ;
         if( ! is2 )
         {
            is=true; // no valid statistics
            break;
         }

         if( j == 0 )
           vMD.qaData.statMin.setSampleProperties( statStr );
         else if( j == 1 )
           vMD.qaData.statMax.setSampleProperties( statStr );
         else if( j == 2 )
           vMD.qaData.statAve.setSampleProperties( statStr );

         is=false;
       }

       if( is )
       {
         val = nc->getData(mv, vars[0]);
         if( val < MAXDOUBLE )
         {
           // build the statistics from scratch
           int nRecs = static_cast<int>(recNum);

           // constrain memory allocation to a buffer size
           int sz_max=1000;
           size_t start[] = {0};
           size_t count[] = {0};

           // buffer for netCDF data storage
           double vals_min[sz_max];
           double vals_max[sz_max];
           double vals_ave[sz_max];

           // read data from file, chunk by chunk
           while (nRecs > 0)
           {
             int sz = nRecs > sz_max ? sz_max : nRecs;
             nRecs -= sz;

             count[0]=static_cast<size_t>(sz);

             nc_get_vara_double(
                nc->getNcid(), nc->getVarID(vars[0]),
                   start, count, vals_min );
             nc_get_vara_double(
                nc->getNcid(), nc->getVarID(vars[1]),
                   start, count, vals_max );
             nc_get_vara_double(
                nc->getNcid(), nc->getVarID(vars[2]),
                   start, count, vals_ave );

             start[0] += static_cast<size_t>(sz) ;

             // feed data to the statistics
             vMD.qaData.statMin.add( vals_min, sz );
             vMD.qaData.statMax.add( vals_max, sz );
             vMD.qaData.statAve.add( vals_ave, sz );
           }

           // write statistics attributes
           vMD.qaData.setStatisticsAttribute(nc);
         }
       }
     }

     // the test: regular post-processing on the basis of stored statistics
     if( vMD.qaData.outlier->test(&vMD.qaData) )
       retCode = true;
  }

  return retCode;
}
Exemple #20
0
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);
}
Exemple #21
0
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];

  exerrval = 0;

  /* inquire id's of previously defined dimensions  */

  if (ex_get_dimension(exoid, DIM_NUM_DIM, "dimensions",
           &num_dim, &ndimdim, "ex_get_coord") != NC_NOERR) {
    return(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 */
      return (EX_NOERR);
    }

  if ((status = nc_inq_dimlen(exoid, numnoddim, &num_nod)) != NC_NOERR)
    {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to get number of nodes in file id %d",
              exoid);
      ex_err("ex_get_coord",errmsg,exerrval);
      return (EX_FATAL);
    }

  /* read in the coordinates  */
  if (ex_large_model(exoid) == 0) {
    if ((status = nc_inq_varid (exoid, VAR_COORD, &coordid)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
              "Error: failed to locate nodal coordinates in file id %d", exoid);
      ex_err("ex_get_coord",errmsg,exerrval);
      return (EX_FATAL);
    } 

    for (i=0; i<num_dim; i++) {
      char *which;
      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) {
  exerrval = status;
  sprintf(errmsg,
    "Error: failed to get %s coord array in file id %d", which, exoid);
  ex_err("ex_get_coord",errmsg,exerrval);
  return (EX_FATAL);
      }
    }

  } else {
    if ((status = nc_inq_varid (exoid, VAR_COORD_X, &coordidx)) != NC_NOERR) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to locate x nodal coordinates in file id %d", exoid);
      ex_err("ex_get_coord",errmsg,exerrval);
      return (EX_FATAL);
    }

    if (num_dim > 1) {
      if ((status = nc_inq_varid (exoid, VAR_COORD_Y, &coordidy)) != NC_NOERR) {
  exerrval = status;
  sprintf(errmsg,
    "Error: failed to locate y nodal coordinates in file id %d", exoid);
  ex_err("ex_get_coord",errmsg,exerrval);
  return (EX_FATAL);
      }
    } else {
      coordidy = 0;
    }

    if (num_dim > 2) {
      if ((status = nc_inq_varid (exoid, VAR_COORD_Z, &coordidz)) != NC_NOERR) {
  exerrval = status;
  sprintf(errmsg,
    "Error: failed to locate z nodal coordinates in file id %d", exoid);
  ex_err("ex_get_coord",errmsg,exerrval);
  return (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) {
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to get %s coord array in file id %d", which, exoid);
      ex_err("ex_put_coord",errmsg,exerrval);
      return (EX_FATAL);
    }
        }
      }
  }
  return (EX_NOERR);
}
Exemple #22
0
// Traj_NcEnsemble::readArray() //TODO RemdValues
int Traj_NcEnsemble::readArray(int set, FrameArray& f_ensemble) {
# ifdef HAS_PNETCDF
  MPI_Offset pstart_[4];
  MPI_Offset pcount_[4];
# define start_ pstart_
# define count_ pcount_
# endif
  start_[0] = set; // Frame
  start_[2] = 0;   // Atoms
  start_[3] = 0;   // XYZ
  count_[0] = 1;        // Frame
  count_[1] = 1;        // Ensemble
  count_[3] = 3;        // XYZ
  //rprintf("DEBUG: Reading frame %i\n", set+1);
  for (int member = ensembleStart_; member != ensembleEnd_; member++) {
#   ifdef MPI
    Frame& frm = f_ensemble[0];
#   else
    Frame& frm = f_ensemble[member];
#   endif
    start_[1] = member;   // Ensemble
    count_[2] = Ncatom(); // Atoms
    // Read Coords
#   ifdef HAS_PNETCDF
    if (checkPNCerr(ncmpi_get_vara_float_all(ncid_, coordVID_, start_, count_, Coord_)))
#   else
    if (NC::CheckErr(nc_get_vara_float(ncid_, coordVID_, start_, count_, Coord_)))
#   endif
    {
      rprinterr("Error: Getting coordinates for frame %i\n", set+1);
      return 1;
    }
    FloatToDouble(frm.xAddress(), Coord_);
    //mprintf("Frm=%8i Rep=%8i ", set+1, member+1); // DEBUG
    //frm.printAtomCoord(0); // DEBUG
    // Read Velocities
    if (velocityVID_ != -1) {
#     ifdef HAS_PNETCDF
      if (checkPNCerr(ncmpi_get_vara_float_all(ncid_, velocityVID_, start_, count_, Coord_)))
#     else
      if (NC::CheckErr(nc_get_vara_float(ncid_, velocityVID_, start_, count_, Coord_)))
#     endif
      {
        rprinterr("Error: Getting velocities for frame %i\n", set+1);
        return 1;
      }
      FloatToDouble(frm.vAddress(), Coord_);
    }
    // Read Box
    if (cellLengthVID_ != -1) {
      count_[2] = 3;
#     ifdef HAS_PNETCDF
      if (checkPNCerr(ncmpi_get_vara_double_all(ncid_, cellLengthVID_, start_, count_, frm.bAddress())))
#     else
      if (NC::CheckErr(nc_get_vara_double(ncid_, cellLengthVID_, start_, count_, frm.bAddress())))
#     endif
      {
        rprinterr("Error: Getting cell lengths for frame %i.\n", set+1);
        return 1;
      }
#     ifdef HAS_PNETCDF
      if (checkPNCerr(ncmpi_get_vara_double_all(ncid_, cellAngleVID_, start_, count_, frm.bAddress()+3)))
#     else
      if (NC::CheckErr(nc_get_vara_double(ncid_, cellAngleVID_, start_, count_, frm.bAddress()+3)))
#     endif
      {
        rprinterr("Error: Getting cell angles for frame %i.\n", set+1);
        return 1;
      }
    }
    // Read Temperature
    if (TempVID_!=-1) {
#     ifdef HAS_PNETCDF
      if (checkPNCerr(ncmpi_get_vara_double_all(ncid_, TempVID_, start_, count_, frm.tAddress())))
#     else
      if (NC::CheckErr(nc_get_vara_double(ncid_, TempVID_, start_, count_, frm.tAddress())))
#     endif
      {
        rprinterr("Error: Getting replica temperature for frame %i.\n", set+1);
        return 1;
      }
      //fprintf(stderr,"DEBUG: Replica Temperature %lf\n",F->T);
    }
    // Read indices
    if (indicesVID_!=-1) {
      count_[2] = remd_dimension_;
#     ifdef HAS_PNETCDF
      if (checkPNCerr(ncmpi_get_vara_int_all(ncid_, indicesVID_, start_, count_, frm.iAddress())))
#     else
      if (NC::CheckErr(nc_get_vara_int(ncid_, indicesVID_, start_, count_, frm.iAddress())))
#     endif
      {
        rprinterr("Error: Getting replica indices for frame %i.\n", set+1);
        return 1;
      }
      // DEBUG
      //char buffer[128];
      //char* ptr = buffer;
      //ptr += sprintf(buffer,"DEBUG:\tReplica indices:");
      //for (int dim=0; dim < remd_dimension_; dim++) ptr += sprintf(ptr, " %i", frm.RemdIndices()[dim]);
      //sprintf(ptr,"\n");
      //rprintf("%s", buffer);
    }
  }
# ifdef HAS_PNETCDF
  // DEBUG
# undef start_
# undef count_
# endif
  return 0;
}
Exemple #23
0
/* This function use the  first dimension to parallel and reads and writes all needed data only once, there is no iteration. Stride is not supported */
int extract_unary_1D_all(int mpi_rank,int mpi_size, int ncid,int vlid,int ncidout,int vlidout,int ndims,nc_type vtype,size_t *shape,size_t *begins,size_t *ends,size_t preLen,size_t *outLen){
	
	int i,res;
	size_t *start=(size_t*)malloc(sizeof(size_t)*ndims);     //start position for reading element from input file
	size_t *countOut=(size_t *)malloc(sizeof(size_t)*ndims);
	size_t *startOut=(size_t*)malloc(sizeof(size_t)*ndims);  //start position for writing element to output file
	size_t *shapeOut=(size_t*)malloc(sizeof(size_t)*ndims);  //output dimension shape
	size_t startOut0;
	size_t countOut0;
	int len0=1;
	int lenOut=1;
	for(i=0;i<ndims;++i){
/*            shapeOut[0]=(ends[0]-begins[0])/strides[0]+1;*/
		shapeOut[i]=ends[i]-begins[i]+1;	
		lenOut*=shapeOut[i];
		if(i>0){
			startOut[i]=0;
			countOut[i]=shapeOut[i];
			start[i]=begins[i];
			len0*=ends[i]-begins[i]+1;
		}
	}
	if(outLen!=NULL)
		*outLen=lenOut;
	if(shapeOut[0]>=mpi_size){
		startOut0=mpi_rank*(shapeOut[0]/mpi_size);
		if(mpi_rank!=mpi_size-1){
			countOut0=(shapeOut[0]/mpi_size);
		}else{
			countOut0=shapeOut[0]-startOut0;
		}
	}else{
		if(mpi_rank<shapeOut[0]){
			startOut0=mpi_rank;
			countOut0=1;
		}else{
			return 0;
		}
	}
	int dataEnd=countOut0*len0;
	printf("mpi_rank %d,countOut0 %d\n",mpi_rank,countOut0);
		startOut[0]=startOut0+preLen/len0;
		countOut[0]=countOut0;
/*        start[0]=begins[0]+startOut0*strides[0];*/
		start[0]=begins[0]+startOut0;
	switch(vtype){
		case NC_BYTE:
			{
			unsigned char* dataOut=(unsigned char *)malloc(sizeof(unsigned char)*dataEnd);
			if((res=nc_get_vara_uchar(ncid,vlid,start,countOut,dataOut)))
				BAIL(res);
			if((res=nc_put_vara_uchar(ncidout,vlidout,startOut,countOut,(unsigned char *)dataOut)))
				BAIL(res);
			free(dataOut);
			}
			break;
		case NC_CHAR:
			{
			char* dataOut=(char *)malloc(sizeof(char)*dataEnd);
			if((res=nc_get_vara_schar(ncid,vlid,start,countOut,(signed char *)dataOut)))
				BAIL(res);
			if((res=nc_put_vara_schar(ncidout,vlidout,startOut,countOut,(signed char *)dataOut)))
				BAIL(res);
			free(dataOut);
			}
			break;
		case NC_SHORT:
			{
			short *dataOut=(short *)malloc(sizeof(short)*dataEnd);
			if((res=nc_get_vara_short(ncid,vlid,start,countOut,(short *)dataOut)))
				BAIL(res);
			if((res=nc_put_vara_short(ncidout,vlidout,startOut,countOut,(short *)dataOut)))
				BAIL(res);
			free(dataOut);
			}
			break;
		case NC_INT:
			{
			int * dataOut=(int *)malloc(sizeof(int)*dataEnd);
			if((res=nc_get_vara_int(ncid,vlid,start,countOut,(int *)dataOut)))
				BAIL(res);
			if((res=nc_put_vara_int(ncidout,vlidout,startOut,countOut,(int *)dataOut)))
				BAIL(res);
			free(dataOut);
			}
			break;
		case NC_FLOAT:
			{
			float * dataOut=(float *)malloc(sizeof(float)*dataEnd);
			if((res=nc_get_vara_float(ncid,vlid,start,countOut,(float *)dataOut)))
				BAIL(res);
			if((res=nc_put_vara_float(ncidout,vlidout,startOut,countOut,(float *)dataOut)))
				BAIL(res);
			free(dataOut);
			}
			break;
		case NC_DOUBLE:
			{
			double* dataOut=(double *)malloc(sizeof(double)*dataEnd);
			if((res=nc_get_vara_double(ncid,vlid,start,countOut,dataOut)))
				BAIL(res);
			if((res=nc_put_vara_double(ncidout,vlidout,startOut,countOut,(double *)dataOut)))
				BAIL(res);
			free(dataOut);
			}
			break;
		default:
			printf("Unknown data type\n");
			}
	free(start);
	free(startOut);
	free(shapeOut);
	free(countOut);
	return 0;
}
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;
}
Exemple #25
0
int extract_unary_1D(int mpi_rank,int mpi_size, int ncid,int vlid,int ncidout,int vlidout,int ndims,nc_type vtype,size_t *shape,size_t *begins,size_t *ends, ptrdiff_t *strides,size_t preLen,size_t *outLen){
	
	int i,j,res;
	size_t *divider=(size_t *)malloc(sizeof(size_t)*ndims);    //input divider 
	size_t *dividerOut=(size_t *)malloc(sizeof(size_t)*ndims); // output divider
	size_t *start=(size_t*)malloc(sizeof(size_t)*ndims);     //start position for reading element from input file
	size_t *count=(size_t*)malloc(sizeof(size_t)*ndims);
	size_t *countOut=(size_t *)malloc(sizeof(size_t)*ndims);
	size_t *startOut=(size_t*)malloc(sizeof(size_t)*ndims);  //start position for writing element to output file
	size_t *shapeOut=(size_t*)malloc(sizeof(size_t)*ndims);  //output dimension shape
	size_t startOut0;
	size_t countOut0;
	int len0=1;
	int lenOut=1;
	for(i=0;i<ndims;++i){
		shapeOut[i]=(ends[i]-begins[i])/strides[i]+1;	
		lenOut*=shapeOut[i];
		if(i>0){
			startOut[i]=0;
			countOut[i]=shapeOut[i];
			start[i]=begins[i];
			count[i]=ends[i]-begins[i]+1;
			len0*=ends[i]-begins[i]+1;
		}
	}
	if(outLen!=NULL)
		*outLen=lenOut;
	if(shapeOut[0]>=mpi_size){
		startOut0=mpi_rank*(shapeOut[0]/mpi_size);
		if(mpi_rank!=mpi_size-1){
			countOut0=(shapeOut[0]/mpi_size);
		}else{
			countOut0=shapeOut[0]-startOut0;
		}
	}else{
		if(mpi_rank<shapeOut[0]){
			startOut0=mpi_rank;
			countOut0=1;
		}else{
			return 0;
		}
	}
	int dataEnd=lenOut/shapeOut[0];
	void* data=(void*)malloc(sizeof(double)*len0);
	void* dataOut=(void*)malloc(sizeof(double)*dataEnd);
	size_t* poses=(size_t*)malloc(sizeof(size_t)*dataEnd);
	getDivider(ndims,count,divider);
	getDivider(ndims,countOut,dividerOut);
	transfer_pos(poses,ndims-1,strides,dataEnd,dividerOut,divider);
	printf("mpi_rank %d,countOut0 %d\n",mpi_rank,countOut0);
	for(i=0;i<countOut0;++i){
		startOut[0]=startOut0+i+preLen/len0;
		countOut[0]=1;
		start[0]=begins[0]+(startOut0+i)*strides[0];
		count[0]=1;

	switch(vtype){
		case NC_BYTE:
			if((res=nc_get_vara_uchar(ncid,vlid,start,count,(unsigned char *)data)))
				BAIL(res);
			if(len0==dataEnd){
				if((res=nc_put_vara_uchar(ncidout,vlidout,startOut,countOut,(unsigned char *)data)))
					BAIL(res);
			}else{
				for(j=0;j<dataEnd;++j){
					((unsigned char *)dataOut)[j]=((unsigned char *)data)[poses[j]];
				}
				if((res=nc_put_vara_uchar(ncidout,vlidout,startOut,countOut,(unsigned char *)dataOut)))
					BAIL(res);
			}
			break;
		case NC_CHAR:
			if((res=nc_get_vara_schar(ncid,vlid,start,count,(signed char *)data)))
				BAIL(res);
			if(len0==dataEnd){
				if((res=nc_put_vara_schar(ncidout,vlidout,startOut,countOut,(signed char *)data)))
					BAIL(res);
			}else{
				for(j=0;j<dataEnd;++j){
					((signed char *)dataOut)[j]=((signed char *)data)[poses[j]];
				}
				if((res=nc_put_vara_schar(ncidout,vlidout,startOut,countOut,(signed char *)dataOut)))
					BAIL(res);
			}
			break;
		case NC_SHORT:
			if((res=nc_get_vara_short(ncid,vlid,start,count,data)))
				BAIL(res);
			if(len0==dataEnd){
				if((res=nc_put_vara_short(ncidout,vlidout,startOut,countOut,(short *)data)))
					BAIL(res);
			}else{
				for(j=0;j<dataEnd;++j){
					((short *)dataOut)[j]=((short *)data)[poses[j]];
				}
				if((res=nc_put_vara_short(ncidout,vlidout,startOut,countOut,(short *)dataOut)))
					BAIL(res);
			}
			break;
		case NC_INT:
			if((res=nc_get_vara_int(ncid,vlid,start,count,(int *)data)))
				BAIL(res);
			if(len0==dataEnd){
				if((res=nc_put_vara_int(ncidout,vlidout,startOut,countOut,(int *)data)))
					BAIL(res);
			}else{
				for(j=0;j<dataEnd;++j){
					((int *)dataOut)[j]=((int *)data)[poses[j]];
				}
				if((res=nc_put_vara_int(ncidout,vlidout,startOut,countOut,(int *)dataOut)))
					BAIL(res);
			}

			break;
		case NC_FLOAT:
			if((res=nc_get_vara_float(ncid,vlid,start,count,data)))
				BAIL(res);
			if(len0==dataEnd){
				if((res=nc_put_vara_float(ncidout,vlidout,startOut,countOut,(float *)data)))
					BAIL(res);
			}else{
				for(j=0;j<dataEnd;++j){
					((float *)dataOut)[j]=((float *)data)[poses[j]];
				}
				if((res=nc_put_vara_float(ncidout,vlidout,startOut,countOut,(float *)dataOut)))
					BAIL(res);
			}
			break;
		case NC_DOUBLE:
			if((res=nc_get_vara_double(ncid,vlid,start,count,(double *)data)))
				BAIL(res);
			if(len0==dataEnd){
				if((res=nc_put_vara_double(ncidout,vlidout,startOut,countOut,(double *)data)))
					BAIL(res);
			}else{
				for(j=0;j<dataEnd;++j){
					((double *)dataOut)[j]=((double *)data)[poses[j]];
				}
				if((res=nc_put_vara_double(ncidout,vlidout,startOut,countOut,(double *)dataOut)))
					BAIL(res);
			}
			break;
		default:
			printf("Unknown data type\n");
			}
		}

	/*free resourses*/
	free(divider);
	free(dividerOut);
	free(start);
	free(startOut);
	free(shapeOut);
	free(data);
	free(dataOut);
	free(poses);
	return 0;
}
Exemple #26
0
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;
} 
Exemple #27
0
/***************************************************************************************
 * Given a numeric varid, this reads the data from the file.
 * Does not return on errors.
 */
SEXP R_nc_get_vara_numvarid( SEXP sx_nc, SEXP sx_varid, SEXP sx_start, SEXP sx_count ) 
{
	int 	varid, ncid, ndims, len_start, len_count, i, j, ierr,
		start_arg[MAX_NC_DIMS], count_arg[MAX_NC_DIMS],
		*data_addr_i, missval_i, ndims_cgt1;
	SEXP 	rv_data = R_NilValue /* -Wall */, sx_dim;
	size_t	start[MAX_NC_DIMS], count[MAX_NC_DIMS], varsize[MAX_NC_DIMS], tot_var_size,
		i_szt;
	double	*data_addr_d, missval_d, missval_tol;
	nc_type	vartype;

	/*--------------------------------------------------------------------------- 
	 * On entry, the following are guaranteed to be integers:
	 *	varid
	 *	*start
	 *	*count
	 *
	 * Note that varid, start, and/or count could be a single '-1' if the user
	 * has not specified the start and count to use.
	 * 'sx_nc' is guaranteed to be the full object of class 'ncdf'.
	 *----------------------------------------------------------------------------*/


	varid = INTEGER(sx_varid)[0];
	ncid  = INTEGER(R_ncu_getListElement( sx_nc, "id" ))[0];

	/*-----------------------------------------------------------------------
	 * Copy passed start and count to local vars so we can modify them safely
	 *----------------------------------------------------------------------*/
	len_start = length(sx_start);
	for( i=0; i<len_start; i++ )
		start_arg[i] = INTEGER(sx_start)[i];
	len_count = length(sx_count);
	for( i=0; i<len_count; i++ )
		count_arg[i] = INTEGER(sx_count)[i];
	
	/*-----------------------------------------
	 * Get varid to use, if passed value is -1.
	 *----------------------------------------*/
	if( varid == -1 ) {
		/*----------------------------------------------------
		 * Get how many vars are in this file ... if only one,
		 * use that one.  Otherwise, signal error.
		 *---------------------------------------------------*/
		varid = R_ncu_varid_onlyvar( ncid );
		if( varid == -1 ) 
			error( "Error: no var specified, and the file has more than one valid var!" );
		}
	else
		varid--;	/* go from R to C indexing */
	
	/*--------------------------------------------------------
	 * Get # of dims for this var, as a check to make sure any
	 * passed 'start' and 'count' are correct.
	 *-------------------------------------------------------*/
	ierr = nc_inq_varndims( ncid, varid, &ndims );
	if( ierr != NC_NOERR )
		error( "Internal error in ncdf package, routine R_nc_get_vara_numvarid: failed to get ndims for var!\n" );

	/*------------------------------------------------------
	 * Get our variable's size, and the start & count to use
	 *-----------------------------------------------------*/
	R_ncu_get_varsize( ncid, varid, ndims, varsize );
	R_ncu_calc_start_count( ncid, varid, start_arg, len_start, count_arg, len_count, 
			varsize, ndims, start, count );

	/*------------------------------------------------------------
	 * Allocate space for data, depending on the type of var it is
	 *-----------------------------------------------------------*/
	ierr = nc_inq_vartype( ncid, varid, &vartype );
	if( ierr != NC_NOERR )
		error( "Internal error in ncdf package, routine R_nc_get_vara_numvarid: failed to get type for var!\n" );

	tot_var_size = 1L;
	for( i=0; i<ndims; i++ ) {
		tot_var_size *= count[i];
		}

	switch( vartype ) {
		case NC_CHAR:
			error( "chars not handled yet, use old interface" );
			break;

		case NC_BYTE:
		case NC_SHORT:
		case NC_INT:
			/*---------------
			 * Allocate space
			 *--------------*/
			PROTECT( rv_data = allocVector( INTSXP, tot_var_size ));
			data_addr_i = &(INTEGER(rv_data)[0]);	/* Is this guaranteed to work?  Dunno. */

			/*--------------
			 * Read the data
			 *-------------*/
			ierr        = nc_get_vara_int( ncid, varid, start, count, data_addr_i );
			if( ierr != NC_NOERR )
				error( "Error while trying to read int data from file!" );

			/*---------------------
			 * Handle missing value
			 *--------------------*/
			ierr = nc_get_att_int( ncid, varid, "missing_value", &missval_i );
			if( ierr != NC_NOERR )
				/* No missing value attribute found, use default value */
				missval_i = NC_FILL_INT;
			for( i_szt=0L; i_szt<tot_var_size; i_szt++ ) 
				if( data_addr_i[i_szt] == missval_i )
					data_addr_i[i_szt] = NA_INTEGER;
			break;

		case NC_FLOAT:
		case NC_DOUBLE:
			/*---------------
			 * Allocate space
			 *--------------*/
			PROTECT( rv_data = allocVector( REALSXP, tot_var_size ));
			data_addr_d = &(REAL(rv_data)[0]);	/* Is this guaranteed to work?  Dunno. */

			/*--------------
			 * Read the data
			 *-------------*/
			ierr        = nc_get_vara_double( ncid, varid, start, count, data_addr_d );
			if( ierr != NC_NOERR )
				error( "Error while trying to read real data from file!" );

			/*---------------------
			 * Handle missing value
			 *--------------------*/
			ierr = nc_get_att_double( ncid, varid, "missing_value", &missval_d );
			if( ierr != NC_NOERR )
				/* No missing value attribute found, use default value */
				missval_d = 1.e30;
			missval_tol = 1.e-5*fabs(missval_d);
			for( i_szt=0L; i_szt<tot_var_size; i_szt++ ) 
				if( fabs(data_addr_d[i_szt] - missval_d) < missval_tol )
					data_addr_d[i_szt] = NA_REAL;
			break;

		default:
			error( "unhandled var type when allocating var space in R_nc_get_vara_numvarid");
		}

	/*-----------------------------------------
	 * Set our dims (note: non-degenerate only)
	 *----------------------------------------*/
	ndims_cgt1 = 0;  
	for( i=0; i<ndims; i++ )
		if( count[i] > 1 )
			ndims_cgt1++;
	if( ndims_cgt1 == 0 ) {
		PROTECT( sx_dim = allocVector( INTSXP, 1 ));
		INTEGER(sx_dim)[0] = 1;
		}
	else
		{
		PROTECT( sx_dim = allocVector( INTSXP, ndims_cgt1 ));
		j = 0;
		for( i=0; i<ndims; i++ )
			if( count[i] > 1 ) {
				INTEGER(sx_dim)[ndims_cgt1-j-1] = count[i];
				j++;
				}
		}
	setAttrib( rv_data, R_DimSymbol, sx_dim );

	UNPROTECT(2);
	return(rv_data);
}
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);
}
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;

  ex_check_valid_file_id(exoid);

  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) {
        snprintf(errmsg, MAX_ERR_LENGTH,
                 "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 */
      }
      snprintf(errmsg, MAX_ERR_LENGTH,
               "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;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "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;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "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;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "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;
    snprintf(errmsg, MAX_ERR_LENGTH,
             "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);
}
Exemple #30
0
/*
 * 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;
    }
}