예제 #1
0
// Traj_NcEnsemble::writeArray()
int Traj_NcEnsemble::writeArray(int set, FramePtrArray const& Farray) {
# ifdef HAS_PNETCDF
  MPI_Offset pstart_[4];
  MPI_Offset pcount_[4];
# define start_ pstart_
# define count_ pcount_
# endif
  start_[0] = ncframe_; // Frame
  start_[2] = 0;        // Atoms
  start_[3] = 0;        // XYZ
  count_[0] = 1; // Frame
  count_[1] = 1; // Ensemble
  count_[3] = 3; // XYZ
  for (int member = ensembleStart_; member != ensembleEnd_; member++) {
    //rprintf("DEBUG: Writing set %i, member %i\n", set+1, member); 
#   ifdef MPI
    Frame* frm = Farray[0];
#   else
    Frame* frm = Farray[member];
#   endif
    start_[1] = member;   // Ensemble
    count_[2] = Ncatom(); // Atoms
    // Write Coords
    //WriteIndices(); // DEBUG
    DoubleToFloat(Coord_, frm->xAddress());
#   ifdef HAS_PNETCDF
    if (ncmpi_put_vara_float_all(ncid_, coordVID_, start_, count_, Coord_))
#   else
    if (NC::CheckErr(nc_put_vara_float(ncid_, coordVID_, start_, count_, Coord_)))
#   endif
    {
      mprinterr("Error: Netcdf Writing coords frame %i\n", set+1);
      return 1;
    }
    // Write velocity.
    if (velocityVID_ != -1) {
      DoubleToFloat(Coord_, frm->vAddress());
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_float_all(ncid_, velocityVID_, start_, count_, Coord_))
#     else
      if (NC::CheckErr(nc_put_vara_float(ncid_, velocityVID_, start_, count_, Coord_)) )
#     endif
      {
        mprinterr("Error: Netcdf writing velocity frame %i\n", set+1);
        return 1;
      }
    }
    // Write box
    if (cellLengthVID_ != -1) {
      count_[2] = 3;
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_double_all(ncid_,cellLengthVID_,start_,count_,frm->bAddress()))
#     else
      if (NC::CheckErr(nc_put_vara_double(ncid_,cellLengthVID_,start_,count_,frm->bAddress())) )
#     endif
      {
        mprinterr("Error: Writing cell lengths frame %i.\n", set+1);
        return 1;
      }
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_double_all(ncid_,cellAngleVID_,start_,count_,frm->bAddress()+3))
#     else
      if (NC::CheckErr(nc_put_vara_double(ncid_,cellAngleVID_,start_,count_,frm->bAddress()+3)))
#     endif
      {
        mprinterr("Error: Writing cell angles frame %i.\n", set+1);
        return 1;
      }
    }
    // Write temperature
    if (TempVID_!=-1) {
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_double_all(ncid_,TempVID_,start_,count_,frm->tAddress()))
#     else
      if (NC::CheckErr(nc_put_vara_double(ncid_,TempVID_,start_,count_,frm->tAddress())))
#     endif
      {
        mprinterr("Error: Writing temperature frame %i.\n", set+1);
        return 1;
      }
    }
    // Write indices
    if (indicesVID_ != -1) {
      count_[2] = remd_dimension_;
#     ifdef HAS_PNETCDF
      if (ncmpi_put_vara_int_all(ncid_,indicesVID_,start_,count_,frm->iAddress()))
#     else
      if (NC::CheckErr(nc_put_vara_int(ncid_,indicesVID_,start_,count_,frm->iAddress())))
#     endif
      {
        mprinterr("Error: Writing indices frame %i.\n", set+1);
        return 1;
      }
    }
  }
# ifdef HAS_PNETCDF
  //ncmpi_sync(ncid_);
# else
  nc_sync(ncid_); // Necessary after every write??
# endif
  ++ncframe_;
# ifdef HAS_PNETCDF
  // DEBUG
# undef start_
# undef count_
# endif
  return 0;
}
예제 #2
0
int main(int argc,char *argv[]) {
  struct DataMap *ptr;
  struct DataMapScalar *sx,*sy;
  struct DataMapArray *ax,*ay;
  size_t index[256];
  size_t start[256];
  size_t count[256];

  int s;
  unsigned char vbflg=0;
  unsigned char help=0;
  unsigned char option=0;
  unsigned char zflg=0;

  FILE *fp=NULL;
  gzFile zfp=0;

  FILE *mapfp;
  int n,c,x;
  int ncid;
  int block=0;
 
  int varid;
  
  int strsze;
  char **strptr;
  char *tmpbuf=NULL;

  OptionAdd(&opt,"-help",'x',&help);
  OptionAdd(&opt,"-option",'x',&option);
  OptionAdd(&opt,"vb",'x',&vbflg);
  OptionAdd(&opt,"z",'x',&zflg);


  if (argc>1) {
    arg=OptionProcess(1,argc,argv,&opt,NULL); 
    if (help==1) {
      OptionPrintInfo(stdout,hlpstr);
      exit(0);
    }
    if (option==1) {
      OptionDump(stdout,&opt);
      exit(0);
    }

    if (zflg) {
      zfp=gzopen(argv[arg],"r");
      if (zfp==0) {
        fprintf(stderr,"File not found.\n");
        exit(-1);
      }
    } else {
      fp=fopen(argv[arg],"r");
      if (fp==NULL) {
        fprintf(stderr,"File not found.\n");
        exit(-1);
      }
    }  

  } else {
    OptionPrintInfo(stdout,errstr);
    exit(-1);
  }


  /* load the map */

  mapfp=fopen(argv[arg+1],"r");
  loadmap(mapfp);
  fclose(mapfp);

 

  s=nc_open(argv[arg+2],NC_WRITE,&ncid);
  if (s !=NC_NOERR) {
    fprintf(stderr,"Error opening CDF file.\n");
    exit(-1);
  }


   


  block=0;
  while (1) {

    if (zflg) ptr=DataMapReadZ(zfp);
    else ptr=DataMapFread(fp);

    if (ptr==NULL) break;

    for (c=0;c<ptr->snum;c++) {
      sx=ptr->scl[c];
      for (n=0;n<snum;n++) {
        sy=sptr[n];
        if (strcmp(sx->name,sy->name) !=0) continue;
        if (sx->type !=sy->type) continue;
        break;
      }
      if (n !=snum) { /* mapped variable */
        s=nc_inq_varid(ncid,cdfsname[n],&varid);
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error accessing CDF file.\n");
          exit(-1);
        }
        index[0]=block;
        switch (sx->type) {
        case DATACHAR:
          s=nc_put_var1_text(ncid,varid,index,sx->data.cptr);
          break;
        case DATASHORT:
          s=nc_put_var1_short(ncid,varid,index,sx->data.sptr);
          break;
        case DATAINT:
          s=nc_put_var1_long(ncid,varid,index,(long *) sx->data.iptr);
          break;
        case DATAFLOAT:
          s=nc_put_var1_float(ncid,varid,index,sx->data.fptr);
          break;
        case DATADOUBLE:
          s=nc_put_var1_double(ncid,varid,index,sx->data.dptr);
          break;
        case DATASTRING:
          start[0]=block;
          start[1]=0;
          count[0]=1;
          count[1]=strlen(*((char **) sx->data.vptr))+1;
          s=nc_put_vara_text(ncid,varid,start,count,
                             *((char **) sx->data.vptr));
          break;
	}
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error writing CDF file (%d).\n",s);
          exit(-1);
        }
       
      }
    }

    for (c=0;c<ptr->anum;c++) {
      ax=ptr->arr[c];
      for (n=0;n<anum;n++) {
        ay=aptr[n];
      
        if (strcmp(ax->name,ay->name) !=0) continue;
        if (ax->type !=ay->type) continue;
        if (ax->dim !=ay->dim) continue;
        break;
      }
      if (n !=anum) { /* mapped variable */
      
        s=nc_inq_varid(ncid,cdfaname[n],&varid);
        if (s !=NC_NOERR) {
          fprintf(stderr,"Error accessing CDF file.\n");
          exit(-1);
        }
        start[0]=block;
        count[0]=1;
        n=1;
        for (x=0;x<ax->dim;x++) {
          start[1+x]=0;
          count[1+x]=ax->rng[x];
          n=n*ax->rng[x];
	}

        if (ax->type==DATASTRING) {
          int ndims;
          int dimids[NC_MAX_VAR_DIMS];
          size_t dimlen;
          s=nc_inq_varndims(ncid,varid,&ndims);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          s=nc_inq_vardimid(ncid,varid,dimids);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          if (ndims-2!=ax->dim) {
            fprintf(stderr,"Error matching dimensions.\n");
            exit(-1);
	  }
          
          s=nc_inq_dimlen(ncid,dimids[ndims-1],&dimlen);
          if (s !=NC_NOERR) {
            fprintf(stderr,"Error accessing CDF file.\n");
            exit(-1);
          }
          strsze=dimlen;
          tmpbuf=malloc(n*strsze);
          if (tmpbuf==NULL) {
            fprintf(stderr,"Failed to allocate buffer.\n");
            exit(-1);
	  }
          memset(tmpbuf,0,n*strsze);
          start[1+ax->dim]=0;
          count[1+ax->dim]=strsze;
          strptr=(char **) ax->data.vptr;
          for (x=0;x<n;x++) strncpy(tmpbuf+x*strsze,strptr[x],strsze);
	}               

        switch (ax->type) { 
        case DATACHAR:
           s=nc_put_vara_text(ncid,varid,start,count,ax->data.cptr);
           break;
        case DATASHORT:
           s=nc_put_vara_short(ncid,varid,start,count,ax->data.sptr);
           break;
        case DATAINT:
	  s=nc_put_vara_long(ncid,varid,start,count,(long *) ax->data.iptr);
           break;
        case DATAFLOAT:
           s=nc_put_vara_float(ncid,varid,start,count,ax->data.fptr);
           break;
        case DATADOUBLE:
           s=nc_put_vara_double(ncid,varid,start,count,ax->data.dptr);
           break;
        case DATASTRING:
           s=nc_put_vara_text(ncid,varid,start,count,tmpbuf);
	   break;
	}
        if (tmpbuf !=NULL) {
	  free(tmpbuf);
          tmpbuf=NULL;
	}

        if (s !=NC_NOERR) {
          fprintf(stderr,"Error writing CDF file (%d).\n",s);
          exit(-1);
        }
 
      }
    }
  

    DataMapFree(ptr);
    block++;
  }
  nc_close(ncid);
  if (zflg) gzclose(zfp);
  else fclose(fp);
  return 0;
}
예제 #3
0
// Traj_AmberNetcdf::writeFrame() 
int Traj_AmberNetcdf::writeFrame(int set, Frame const& frameOut) {
  DoubleToFloat(Coord_, frameOut.xAddress());

  // Write coords
  start_[0] = ncframe_;
  start_[1] = 0;
  start_[2] = 0;
  count_[0] = 1;
  count_[1] = Ncatom();
  count_[2] = 3;
  if (NC::CheckErr(nc_put_vara_float(ncid_,coordVID_,start_,count_,Coord_)) ) {
    mprinterr("Error: Netcdf Writing coords frame %i\n", set+1);
    return 1;
  }

  // Write velocity. FIXME: Should check in setup
  if (CoordInfo().HasVel() && frameOut.HasVelocity()) {
    DoubleToFloat(Coord_, frameOut.vAddress());
    if (NC::CheckErr(nc_put_vara_float(ncid_, velocityVID_, start_, count_, Coord_)) ) {
      mprinterr("Error: Netcdf writing velocity frame %i\n", set+1);
      return 1;
    }
  }

  // Write forces. FIXME: Should check in setup
  if (CoordInfo().HasForce() && frameOut.HasForce()) {
    DoubleToFloat(Coord_, frameOut.fAddress());
    if (NC::CheckErr(nc_put_vara_float(ncid_, frcVID_, start_, count_, Coord_)) ) {
      mprinterr("Error: Netcdf writing force frame %i\n", set+1);
      return 1;
    }
  }

  // Write box
  if (cellLengthVID_ != -1) {
    count_[1] = 3;
    count_[2] = 0;
    if (NC::CheckErr(nc_put_vara_double(ncid_, cellLengthVID_, start_, count_,
                                        frameOut.bAddress())) )
    {
      mprinterr("Error: Writing cell lengths frame %i.\n", set+1);
      return 1;
    }
    if (NC::CheckErr(nc_put_vara_double(ncid_, cellAngleVID_, start_, count_, 
                                        frameOut.bAddress()+3)) )
    {
      mprinterr("Error: Writing cell angles frame %i.\n", set+1);
      return 1;
    }
  }

  // Write temperature
  if (TempVID_!=-1) {
    if ( NC::CheckErr( nc_put_vara_double(ncid_,TempVID_,start_,count_,frameOut.tAddress())) ) {
      mprinterr("Error: Writing temperature frame %i.\n", set+1);
      return 1;
    }
  }

  // Write time
  if (timeVID_ != -1) {
    float tVal = (float)frameOut.Time();
    if ( NC::CheckErr( nc_put_vara_float(ncid_,timeVID_,start_,count_,&tVal)) ) {
      mprinterr("Error: Writing time frame %i.\n", set+1);
      return 1;
    }
  }
    
  // Write indices
  if (indicesVID_ != -1) {
    count_[1] = remd_dimension_;
    if ( NC::CheckErr(nc_put_vara_int(ncid_,indicesVID_,start_,count_,frameOut.iAddress())) ) {
      mprinterr("Error: Writing indices frame %i.\n", set+1);
      return 1;
    }
  }

  nc_sync(ncid_); // Necessary after every write??

  ++ncframe_;

  return 0;
}  
예제 #4
0
int ne_put_elem_var_slab (int   neid,
		          int   time_step,
		          int   elem_var_index,
		          int   elem_blk_id,
                          int   start_pos,
		          int   num_vals,
		          void *elem_var_vals)
{
  int status;
  int varid, dimid,time_dim, numelbdim, dims[2], elem_blk_id_ndx;
  size_t num_elem_blk, num_elem_var, start[2], count[2];
  int *elem_var_tab;
  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(neid, EX_ELEM_BLOCK, elem_blk_id)) < 0) {
    if (exerrval == EX_NULLENTITY) {
      sprintf(errmsg,
	      "Warning: no variables allowed for NULL block %d in file id %d",
	      elem_blk_id, neid);
      ex_err("ne_put_elem_var_slab", errmsg, EX_MSG);
      return (EX_WARN);
    } else {
      sprintf(errmsg,
	      "Error: failed to locate element block id %d in %s array in file id %d",
	      elem_blk_id, VAR_ID_EL_BLK, neid);
      ex_err("ne_put_elem_var_slab", errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  if ((status = nc_inq_varid (neid,
			      VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx), &varid)) != NC_NOERR) {
    if (status == NC_ENOTVAR) { /* variable doesn't exist, create it! */

      /*    inquire previously defined dimensions */

      /* check for the existance of an element variable truth table */
      if ((status = nc_inq_varid (neid, VAR_ELEM_TAB, &varid)) == NC_NOERR) {
	/* find out number of element blocks and element variables */
	if ((status = nc_inq_dimid (neid, DIM_NUM_EL_BLK, &dimid)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to locate number of element blocks in file id %d",
		  neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if ((status = nc_inq_dimlen(neid, dimid, &num_elem_blk)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get number of element blocks in file id %d",
		  neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if ((status = nc_inq_dimid (neid, DIM_NUM_ELE_VAR, &dimid)) != NC_NOERR) {
	  exerrval = EX_BADPARAM;
	  sprintf(errmsg,
		  "Error: no element variables stored in file id %d",
		  neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if ((status = nc_inq_dimlen(neid, dimid, &num_elem_var)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get number of element variables in file id %d",
		  neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if (!(elem_var_tab =
	      (int *)malloc(num_elem_blk*num_elem_var*sizeof(int)))) {
	  exerrval = EX_MEMFAIL;
	  sprintf(errmsg,
		  "Error: failed to allocate memory for element variable truth table in file id %d",
		  neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	/*   read in the element variable truth table */
	if ((status = nc_get_var_int(neid, varid, elem_var_tab)) != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to get truth table from file id %d", neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}

	if (elem_var_tab[num_elem_var*(elem_blk_id_ndx-1)+elem_var_index-1] == 0L) {
	  free(elem_var_tab);
	  exerrval = EX_BADPARAM;
	  sprintf(errmsg,
		  "Error: Invalid element variable %d, block %d in file id %d",
		  elem_var_index, elem_blk_id, neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	  return (EX_FATAL);
	}
	free(elem_var_tab);
      }

      if ((status = nc_inq_dimid (neid, DIM_TIME, &time_dim)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to locate time dimension in file id %d", neid);
	ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	goto error_ret;		/* exit define mode and return */
      }

      if ((status = nc_inq_dimid(neid, DIM_NUM_EL_IN_BLK(elem_blk_id_ndx), &numelbdim)) != NC_NOERR) {
	if (status == NC_EBADDIM) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: number of elements in element block %d not defined in file id %d",
		  elem_blk_id, neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	} else {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to locate number of elements in element block %d in file id %d",
		  elem_blk_id, neid);
	  ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	}
	goto error_ret;
      }

      /*    variable doesn't exist so put file into define mode  */
      if ((status = nc_redef (neid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to put file id %d into define mode", neid);
	ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	return (EX_FATAL);
      }


      /*    define netCDF variable to store element variable values */
      dims[0] = time_dim;
      dims[1] = numelbdim;
      if ((status = nc_def_var(neid, VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx),
			       nc_flt_code(neid), 2, dims, &varid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to define element variable %d in file id %d",
		elem_var_index, neid);
	ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	goto error_ret;
      }


      /*    leave define mode  */
      if ((status = nc_enddef(neid)) != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to complete element variable %s definition to file id %d",
		VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx), neid);
	ex_err("ne_put_elem_var_slab", errmsg, exerrval);
	return (EX_FATAL);
      }
    } else {
      exerrval = status;
      sprintf(errmsg,
	      "Error: failed to locate element variable %s in file id %d",
	      VAR_ELEM_VAR(elem_var_index, elem_blk_id_ndx),neid);
      ex_err("ne_put_elem_var_slab", errmsg, exerrval);
      return (EX_FATAL);
    }
  }

  /* store element variable values */
  start[0] = --time_step;
  start[1] = --start_pos;

  count[0] = 1;
  count[1] = num_vals;

  if (ex_comp_ws(neid) == 4) {
    status = nc_put_vara_float(neid, varid, start, count, elem_var_vals);
  } else {
    status = nc_put_vara_double(neid, varid, start, count, elem_var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to store element variable %d in file id %d", 
	    elem_var_index, neid);
    ex_err("ne_put_elem_var_slab", errmsg, exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  if (nc_enddef (neid) != NC_NOERR)     /* exit define mode */
    {
      sprintf(errmsg,
	      "Error: failed to complete definition for file id %d", neid);
      ex_err("ne_put_elem_var_slab", errmsg, exerrval);
    }
  return (EX_FATAL);
}
  void NetCDFFileIOHandler::Write( const Teuchos::RCP<const Epetra_MultiVector>& MV, const std::string& filename )
  {
#ifdef EPETRA_MPI
    Epetra_MpiComm comm( MPI_COMM_WORLD );
#else
    Epetra_SerialComm comm;
#endif
    //
    // Variables for NetCDF
    //
    int status;
    int ncid, len_string_id, num_nodes_id, num_nod_var_id, row_id, col_id, ss_id, name_nod_var_id;
    int i,j;
    int ss_dimids[2];
    
    //size_t start[1],count[1];
    size_t start2[2],count2[2];
    //
    // Variables for Epetra
    //
    int num_vecs = MV->NumVectors();
    int dim = MV->GlobalLength();
    Epetra_Map Map( dim, 0, comm );
    Epetra_Map* Proc0Map;
    const Epetra_Vector* col_newMV;
    //
    // Create map putting all elements of vector on Processor 0.
    //
    if ( comm.MyPID() == 0 ) {
      Proc0Map = new Epetra_Map( dim, dim, 0, comm );
    } else {
      Proc0Map = new Epetra_Map( dim, 0, 0, comm );
    }
    Epetra_Vector Proc0Vector( *Proc0Map );
    //
    // Create an exporter to get the global Epetra_Vector to a local Epetra_Vector.
    //
    Epetra_Export exporter( MV->Map(), *Proc0Map );
    //
    if ( comm.MyPID() == 0 ) {	
      //
      // Open basis output file and define output variables going into the file.
      //
      std::string temp_filename = out_path + filename;
      status=nc_create(temp_filename.c_str(),NC_CLOBBER,&ncid);
      if (status != NC_NOERR) handle_error(status);
      
      status=nc_def_dim(ncid,"len_string",(long)len_string,&len_string_id);
      if (status != NC_NOERR) handle_error(status);
      
      status=nc_def_dim(ncid,"num_nodes",(long)num_nodes,&num_nodes_id);
      if (status != NC_NOERR) handle_error(status);
      
      status=nc_def_dim(ncid,"num_nod_var",(long)num_nod_var,&num_nod_var_id);
      if (status != NC_NOERR) handle_error(status);
      
      status=nc_def_dim(ncid,"row",NC_UNLIMITED,&row_id);
      if (status != NC_NOERR) handle_error(status);
      
      status=nc_def_dim(ncid,"col",(long)dim,&col_id);
      if (status != NC_NOERR) handle_error(status);

      ss_dimids[0]=row_id;
      ss_dimids[1]=col_id;
      status=nc_def_var(ncid,"snapshot",NC_FLOAT,2,ss_dimids,&ss_id);
      if (status != NC_NOERR) handle_error(status);
      
      ss_dimids[0]=num_nod_var_id;
      ss_dimids[1]=len_string_id;
      status=nc_def_var(ncid,"name_nod_var",NC_CHAR,2,ss_dimids,&name_nod_var_id);
      if (status != NC_NOERR) handle_error(status);
      
      status=nc_enddef(ncid);
      if (status != NC_NOERR) handle_error(status);

    }

    // Initialize data pointers for writing out basis to file.
    float* temp_vec = 0;
    if ( comm.MyPID() == 0 )
      temp_vec = new float[ dim ];

    for (i=0; i<num_vecs; ++i) {
      //
      // Get column of Epetra_MultiVector in terms of Epetra_Vector.
      //
      col_newMV = (*MV)( i );
      //
      Proc0Vector.Export(*col_newMV, exporter, Insert);
      //
      if ( comm.MyPID()==0 ) {
	start2[0] = i;
	start2[1] = 0;
	count2[0] = 1;
	count2[1] = dim;
	//
	// Copy double precision vector to single precision and write out.
	//
	for (j=0; j<dim; ++j)
	  temp_vec[j] = Proc0Vector[j];
	
	status=nc_put_vara_float(ncid,ss_id,start2,count2,temp_vec);
	if (status != NC_NOERR) handle_error(status);
      }
    }     
    
    // Write the list of names of the nodal variables to the Netcdf file */
    if ( comm.MyPID() == 0 ) {
      for(i=0; i<num_nod_var; ++i) {
	start2[0] = i;
	start2[1] = 0;
	count2[0] = 1;
	count2[1] = strlen(var_name[i]);
	/*    printf("start2=%d %d\n",start2[0],start2[1]);
	      printf("count2=%d %d\n",count2[0],count2[1]); */
	
	status=nc_put_vara_text(ncid,name_nod_var_id,start2,count2,var_name[i]);
	if (status != NC_NOERR) handle_error(status);
      } 
      
      status=nc_close(ncid);
      if (status != NC_NOERR) handle_error(status);
    }

    // Clean up.
    delete Proc0Map;
    if (temp_vec) delete [] temp_vec;
  }
예제 #6
0
파일: expnv.c 프로젝트: 151706061/VTK
int ex_put_nodal_var (int   exoid,
                      int   time_step,
                      int   nodal_var_index,
                      int   num_nodes, 
                      const void *nodal_var_vals)

{
  int status;
  int varid;
  size_t start[3], count[3];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  if (ex_large_model(exoid) == 0) {
    /* write 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_put_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 {
    /* nodal variables stored separately, find variable for this variable
       index */
    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_put_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_put_vara_float(exoid, varid, start, count, nodal_var_vals);
  } else {
    status = nc_put_vara_double(exoid, varid, start, count, nodal_var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to store nodal variables in file id %d",
      exoid);
    ex_err("ex_put_nodal_var",errmsg,exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
예제 #7
0
파일: Int2ncdf.c 프로젝트: nshrine/code
int main(int argc, char* argv[])
{
	program_name = argv[0];

	if (argc < 3) {
		print_help();
		exit(EXIT_FAILURE);
	}
	
	char binfile[50];
	base = argv[1];
	strapp(binfile, ".nc");

	int total_ids = atoi(argv[2]);

	FILE *fp;
	if (argc > 2) {
		infile = argv[3];
		fp = fopen(infile, "r");
		if (!fp) 
			error(1, errno, "%s", infile);
	} else {
		infile = "stdin";
		fp = stdin;
	}

	/* Get the first line with the SNP names */
	char *line = NULL;
	size_t n = 0;
	int read = getlin(&line, &n, fp);
	if (read == -1)
		error(1, errno, "%s", infile);
   	int nsnps = getsnps(line);
	free(line);
	line = NULL;
	printf("%d markers\n", nsnps);

	printf("Converting intensity values to binary\n");
	int ncid, stat, sampid, varid;
	size_t nids = 0, perkey;
	size_t count[3] = { 1, 0, 0 };
	size_t start[3] = { 0, 0, 0 };
	char *id;	
	float *vals;

	while (getlin(&line, &n, fp) != -1) {
		if (nids == 0) {
			/* Count number of vals in first line to alloc indv_dat */
			read = getstrings(line, NULL, DELIM) - 1;
			if (read < 1)
				error(2, 0, "No values found");
			if (read % nsnps != 0)
				error(2, 0, "Not same number of values for each marker");
			perkey = read / nsnps;
			printf("%zu values per marker\n", perkey);
			vals = malloc(sizeof(float) * read);
			if (vals == NULL)
				error(1, errno, "dat.vals");


			/* Create netcdf file and write snp names */
 			ncid = create_nc(binfile, total_ids, nsnps, perkey);
			stat = nc_inq_varid(ncid, "sample", &sampid);
			check_err(stat,__LINE__,__FILE__);
			stat = nc_inq_varid(ncid, "intensity", &varid);
			check_err(stat,__LINE__,__FILE__);
			writesnps(ncid, nsnps);

			count[1] = nsnps;
			count[2] = perkey;
		}
				
		/* Read valuess from line */
		id = linevals(line, vals);

		/* Write sample id */
		stat = nc_put_var1_string(ncid, sampid, &nids, (const char **) &id);
		check_err(stat,__LINE__,__FILE__);

		/* Write intensity values */
		start[0] = nids;
		stat = nc_put_vara_float(ncid, varid, start, count, vals);
    	check_err(stat,__LINE__,__FILE__);

		free(line);
		line = NULL;
		nids++;
		printf("Read %zu\r", nids);
		fflush(stdout);
	}
			
	fclose(fp);
    stat = nc_close(ncid);
    check_err(stat,__LINE__,__FILE__);
	free(vals);
	free(line);

	printf("Wrote %zu samples to [ %s ]\n", nids, binfile);
	exit(EXIT_SUCCESS);
}
예제 #8
0
파일: load.c 프로젝트: SiggyF/netcdf-c
/* write out variable's data from in-memory structure */
void
load_netcdf(
    void *rec_start
    )
{
    int idim;
    int stat = NC_NOERR;
    size_t start[NC_MAX_VAR_DIMS];
    size_t count[NC_MAX_VAR_DIMS];
    char *charvalp;
    short *shortvalp;
    int *intvalp;
    float *floatvalp;
    double *doublevalp;

    /* load values into variable */

    switch (vars[varnum].type) {
      case NC_CHAR:
      case NC_BYTE:
	charvalp = (char *) rec_start;
	break;
      case NC_SHORT:
	shortvalp = (short *) rec_start;
	break;
      case NC_INT:
	intvalp = (int *) rec_start;
	break;
      case NC_FLOAT:
	floatvalp = (float *) rec_start;
	break;
      case NC_DOUBLE:
	doublevalp = (double *) rec_start;
	break;
      default: break;
    }
    if (vars[varnum].ndims > 0) {
	/* initialize start to upper left corner (0,0,0,...) */
	start[0] = 0;
	if (vars[varnum].dims[0] == rec_dim) {
	    count[0] = vars[varnum].nrecs;
	}
	else {
	    count[0] = dims[vars[varnum].dims[0]].size;
	}
    }

    for (idim = 1; idim < vars[varnum].ndims; idim++) {
	start[idim] = 0;
	count[idim] = dims[vars[varnum].dims[idim]].size;
    }
    
    switch (vars[varnum].type) {
      case NC_BYTE:
	stat = nc_put_vara_schar(ncid, varnum, start, count,
				 (signed char *)charvalp);
	break;
      case NC_CHAR:
	stat = nc_put_vara_text(ncid, varnum, start, count, charvalp);
	break;
      case NC_SHORT:
	stat = nc_put_vara_short(ncid, varnum, start, count, shortvalp);
	break;
      case NC_INT:
	stat = nc_put_vara_int(ncid, varnum, start, count, intvalp);
	break;
      case NC_FLOAT:
	stat = nc_put_vara_float(ncid, varnum, start, count, floatvalp);
	break;
      case NC_DOUBLE:
	stat = nc_put_vara_double(ncid, varnum, start, count, doublevalp);
	break;
      default: break;
    }
    check_err(stat);
}
예제 #9
0
int
main()
{
   /* IDs for the netCDF file, dimensions, and variables. */
   int ncid, lon_dimid, lat_dimid, lvl_dimid, rec_dimid;
   int lat_varid, lon_varid, pres_varid, temp_varid;
   int dimids[NDIMS];

   /* The start and count arrays will tell the netCDF library where to
      write our data. */
   size_t start[NDIMS], count[NDIMS];

   /* Program variables to hold the data we will write out. We will only
      need enough space to hold one timestep of data; one record. */
   float pres_out[NLVL][NLAT][NLON];
   float temp_out[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;

   /* Create some pretend data. If this wasn't an example program, we
    * would have some real data to write, for example, model
    * output. */
   for (lat = 0; lat < NLAT; lat++)
      lats[lat] = START_LAT + 5.*lat;
   for (lon = 0; lon < NLON; lon++)
      lons[lon] = START_LON + 5.*lon;
   
   for (lvl = 0; lvl < NLVL; lvl++)
      for (lat = 0; lat < NLAT; lat++)
	 for (lon = 0; lon < NLON; lon++)
	 {
	    pres_out[lvl][lat][lon] = SAMPLE_PRESSURE + i;
	    temp_out[lvl][lat][lon] = SAMPLE_TEMP + i++;
	 }

   /* Create the file. */
   if ((retval = nc_create(FILE_NAME, NC_CLOBBER, &ncid)))
      ERR(retval);

   /* Define the dimensions. The record dimension is defined to have
    * unlimited length - it can grow as needed. In this example it is
    * the time dimension.*/
   if ((retval = nc_def_dim(ncid, LVL_NAME, NLVL, &lvl_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, LAT_NAME, NLAT, &lat_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, LON_NAME, NLON, &lon_dimid)))
      ERR(retval);
   if ((retval = nc_def_dim(ncid, REC_NAME, NC_UNLIMITED, &rec_dimid)))
      ERR(retval);

   /* Define the coordinate variables. We will only define coordinate
      variables for lat and lon.  Ordinarily we would need to provide
      an array of dimension IDs for each variable's dimensions, but
      since coordinate variables only have one dimension, we can
      simply provide the address of that dimension ID (&lat_dimid) and
      similarly for (&lon_dimid). */
   if ((retval = nc_def_var(ncid, LAT_NAME, NC_FLOAT, 1, &lat_dimid, 
			    &lat_varid)))
      ERR(retval);
   if ((retval = nc_def_var(ncid, LON_NAME, NC_FLOAT, 1, &lon_dimid, 
			    &lon_varid)))
      ERR(retval);

   /* Assign units attributes to coordinate variables. */
   if ((retval = nc_put_att_text(ncid, lat_varid, UNITS, 
				 strlen(DEGREES_NORTH), DEGREES_NORTH)))
      ERR(retval);
   if ((retval = nc_put_att_text(ncid, lon_varid, UNITS, 
				 strlen(DEGREES_EAST), DEGREES_EAST)))
      ERR(retval);

   /* The dimids array is used to pass the dimids of the dimensions of
      the netCDF variables. Both of the netCDF variables we are
      creating share the same four dimensions. In C, the
      unlimited dimension must come first on the list of dimids. */
   dimids[0] = rec_dimid;
   dimids[1] = lvl_dimid;
   dimids[2] = lat_dimid;
   dimids[3] = lon_dimid;

   /* Define the netCDF variables for the pressure and temperature
    * data. */
   if ((retval = nc_def_var(ncid, PRES_NAME, NC_FLOAT, NDIMS, 
			    dimids, &pres_varid)))
      ERR(retval);
   if ((retval = nc_def_var(ncid, TEMP_NAME, NC_FLOAT, NDIMS, 
			    dimids, &temp_varid)))
      ERR(retval);

   /* Assign units attributes to the netCDF variables. */
   if ((retval = nc_put_att_text(ncid, pres_varid, UNITS, 
				 strlen(PRES_UNITS), PRES_UNITS)))
      ERR(retval);
   if ((retval = nc_put_att_text(ncid, temp_varid, UNITS, 
				 strlen(TEMP_UNITS), TEMP_UNITS)))
      ERR(retval);

   /* End define mode. */
   if ((retval = nc_enddef(ncid)))
      ERR(retval);

   /* Write the coordinate variable data. This will put the latitudes
      and longitudes of our data grid into the netCDF file. */
   if ((retval = nc_put_var_float(ncid, lat_varid, &lats[0])))
      ERR(retval);
   if ((retval = nc_put_var_float(ncid, lon_varid, &lons[0])))
      ERR(retval);

   /* These settings tell netcdf to write one timestep of data. (The
     setting of start[0] inside the loop below tells netCDF which
     timestep to write.) */
   count[0] = 1;
   count[1] = NLVL;
   count[2] = NLAT;
   count[3] = NLON;
   start[1] = 0;
   start[2] = 0;
   start[3] = 0;

   /* Write the pretend data. This will write our surface pressure and
      surface temperature data. The arrays only hold one timestep worth
      of data. We will just rewrite the same data for each timestep. In
      a real application, the data would change between timesteps. */
   for (rec = 0; rec < NREC; rec++)
   {
      start[0] = rec;
      if ((retval = nc_put_vara_float(ncid, pres_varid, start, count, 
				      &pres_out[0][0][0])))
	 ERR(retval);
      if ((retval = nc_put_vara_float(ncid, temp_varid, start, count, 
				      &temp_out[0][0][0])))
	 ERR(retval);
   }

   /* Close the file. */
   if ((retval = nc_close(ncid)))
      ERR(retval);
   
   printf("*** SUCCESS writing example file %s!\n", FILE_NAME);
   return 0;
}
예제 #10
0
/* Case 2: create four dimensional integer data,
   one dimension is unlimited. */
int test_pio_4d(size_t cache_size, int facc_type, int access_flag, MPI_Comm comm, 
		MPI_Info info, int mpi_size, int mpi_rank, size_t *chunk_size) 
{
   int ncid, dimuids[NDIMS2], varid2[NUMVARS];
   size_t ustart[NDIMS2], ucount[NDIMS2];
   float *udata, *tempudata;
   char file_name[NC_MAX_NAME + 1];
   char var_name2[NUMVARS][NC_MAX_NAME + 1] = {"JKP", "ZTa", "MFi", "FPi", "JBu", 
					       "ALi", "AJo", "USG", "RBH", "JAG"};
   double starttime, endtime, write_time = 0, bandwidth = 0;
   size_t nelems_in;
   float preemption_in;
   int k, j, i, t;

   udata = malloc(DIMSIZE3 * DIMSIZE2 * DIMSIZE1 / mpi_size * sizeof(int));

   /* Create phony data. */
   tempudata = udata;
   for(k = 0; k < DIMSIZE3; k++)
      for(j = 0; j < DIMSIZE2; j++)
	 for(i = 0; i < DIMSIZE1 / mpi_size; i++)
	 {
	    *tempudata = (float)(1 + mpi_rank) * 2 * (j + 1) * (k + 1);
	    tempudata++;
	 }

   /* Get the file name. */
   sprintf(file_name, "%s/%s", TEMP_LARGE, FILENAME);
      
   /* Set the cache size. */
   if (nc_get_chunk_cache(NULL, &nelems_in, &preemption_in)) ERR;
   if (nc_set_chunk_cache(cache_size, nelems_in, preemption_in)) ERR;

   for (t = 0; t < NUM_TRIES; t++)
   {
      /* Create a netcdf-4 file. */
      if (nc_create_par(file_name, facc_type|NC_NETCDF4, comm, info, 
			&ncid)) ERR;

      /* Create four dimensions. */
      if (nc_def_dim(ncid, "ud1", TIMELEN, dimuids)) ERR;
      if (nc_def_dim(ncid, "ud2", DIMSIZE3, &dimuids[1])) ERR;
      if (nc_def_dim(ncid, "ud3", DIMSIZE2, &dimuids[2])) ERR;
      if (nc_def_dim(ncid, "ud4", DIMSIZE1, &dimuids[3])) ERR;

      /* Create 10 variables. */
      for (i = 0; i < NUMVARS; i++)
	 if (nc_def_var(ncid, var_name2[i], NC_INT, NDIMS2,
			dimuids, &varid2[i])) ERR;

      if (nc_enddef(ncid)) ERR;
 
      /* Set up selection parameters */
      ustart[0] = 0;
      ustart[1] = 0;
      ustart[2] = 0;
      ustart[3] = DIMSIZE1 * mpi_rank / mpi_size;
      ucount[0] = 1;
      ucount[1] = DIMSIZE3;
      ucount[2] = DIMSIZE2;
      ucount[3] = DIMSIZE1 / mpi_size;

      /* Access parallel */
      for (i = 0; i < NUMVARS; i++)
	 if (nc_var_par_access(ncid, varid2[i], access_flag)) ERR;

      starttime = MPI_Wtime();

      /* Write slabs of phony data. */
      for(ustart[0] = 0; ustart[0] < TIMELEN; ustart[0]++)
	 for (i = 0; i < NUMVARS; i++)
	    if (nc_put_vara_float(ncid, varid2[i], ustart, ucount, udata)) ERR;

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

      endtime = MPI_Wtime();
      if (!mpi_rank)
      {
	 write_time += (endtime - starttime) / NUM_TRIES;
	 bandwidth += (sizeof(float) * TIMELEN * DIMSIZE1 * DIMSIZE2 * DIMSIZE3 * NUMVARS) / 
	    ((endtime - starttime) * 1024 * 1024 * NUM_TRIES);
      }
   }
   free(udata);
   if (!mpi_rank)
   {
      char chunk_string[NC_MAX_NAME + 1] = "";

      /* What was our chunking? */
      if (chunk_size[0])
	 sprintf(chunk_string, "%dx%dx%dx%d", (int)chunk_size[0], (int)chunk_size[1], 
		 (int)chunk_size[2], (int)chunk_size[3]);
      else
	 strcat(chunk_string, "contiguous");

      /* Print our results. */
      printf("%d\t\t%s\t%s\t%d\t\t%dx%dx%dx%d\t%s\t%f\t\t%f\t\t\t%d\n", mpi_size, 
	     (facc_type == NC_MPIIO ? "MPI-IO   " : "MPI-POSIX"), 
	     (access_flag == NC_INDEPENDENT ? "independent" : "collective"), 
	     (int)cache_size / MEGABYTE, TIMELEN, DIMSIZE3, DIMSIZE2, DIMSIZE1, chunk_string, write_time, 
	     bandwidth, NUM_TRIES); 
   }

   /* Delete this file. */
   remove(file_name); 

   return 0;
}
예제 #11
0
/* This function creates a file with 10 2D variables, no unlimited
 * dimension. */
int test_pio_2d(size_t cache_size, int facc_type, int access_flag, MPI_Comm comm, 
		MPI_Info info, int mpi_size, int mpi_rank, 
		size_t *chunk_size) 
{
   double starttime, endtime, write_time = 0, bandwidth = 0;
   int ncid;
   int dimids[NDIMS1];
   size_t start[NDIMS1], count[NDIMS1];
   float *data;
   char file_name[NC_MAX_NAME + 1];
   char var_name1[NUMVARS][NC_MAX_NAME + 1] = {"GWa", "JAd", "TJe", "JMa", "JMo", 
					       "JQA", "AJa", "MVB", "WHH", "JTy"};
   int varid1[NUMVARS];
   size_t nelems_in;
   float preemption_in;
   int j, i, t;

   /* Create some data. */
   if (!(data = malloc(sizeof(float) * DIMSIZE2 * DIMSIZE1 / mpi_size)))
      return -2;
   for (j = 0; j < DIMSIZE2; j++)
      for (i = 0; i < DIMSIZE1 / mpi_size; i++)
	 data[j * DIMSIZE1 / mpi_size + i] = (float)mpi_rank * (j + 1);

   /* Get the file name. */
   sprintf(file_name, "%s/%s", TEMP_LARGE, FILENAME);

   /* Set the cache size. */
   if (nc_get_chunk_cache(NULL, &nelems_in, &preemption_in)) ERR;
   if (nc_set_chunk_cache(cache_size, nelems_in, preemption_in)) ERR;

   for (t = 0; t < NUM_TRIES; t++)
   {
      /* Create a netcdf-4 file, opened for parallel I/O. */
      if (nc_create_par(file_name, facc_type|NC_NETCDF4, comm, 
			info, &ncid)) ERR;

      /* Create two dimensions. */
      if (nc_def_dim(ncid, "d1", DIMSIZE2, &dimids[0])) ERR;
      if (nc_def_dim(ncid, "d2", DIMSIZE1, &dimids[1])) ERR;

      /* Create our variables. */
      for (i = 0; i < NUMVARS; i++)
      {
	 if (nc_def_var(ncid, var_name1[i], NC_INT, NDIMS1,
			dimids, &varid1[i])) ERR;
	 if (chunk_size[0])
	    if (nc_def_var_chunking(ncid, varid1[i], 0, chunk_size)) ERR;
      }

      if (nc_enddef(ncid)) ERR;

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

      /* start parallel netcdf4 */
      for (i = 0; i < NUMVARS; i++) 
	 if (nc_var_par_access(ncid, varid1[i], access_flag)) ERR;

      starttime = MPI_Wtime();

      /* Write two dimensional float data */
      for (i = 0; i < NUMVARS; i++)
	 if (nc_put_vara_float(ncid, varid1[i], start, count, data)) ERR;

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

      endtime = MPI_Wtime();
      if (!mpi_rank) 
      {
	 bandwidth += ((sizeof(float) * DIMSIZE1 * DIMSIZE2 * NUMVARS) / 
		       ((endtime - starttime) * 1024 * 1024)) / NUM_TRIES;
	 write_time += (endtime - starttime) / NUM_TRIES;
      }
   }
   free(data);
   if (!mpi_rank) 
   {
      char chunk_string[NC_MAX_NAME + 1] = "";

      /* What was our chunking? */
      if (chunk_size[0])
	 sprintf(chunk_string, "%dx%d    ", (int)chunk_size[0], (int)chunk_size[1]);
      else
	 strcat(chunk_string, "contiguous");

      /* Print the results. */
      printf("%d\t\t%s\t%s\t%d\t\t%dx%d\t\t%s\t%f\t\t%f\t\t\t%d\n", mpi_size, 
	     (facc_type == NC_MPIIO ? "MPI-IO   " : "MPI-POSIX"), 
	     (access_flag == NC_INDEPENDENT ? "independent" : "collective"), 
	     (int)cache_size/MEGABYTE, DIMSIZE1, DIMSIZE2, chunk_string, 
	     write_time, bandwidth, NUM_TRIES); 
   }

   /* Delete this file. */
   remove(file_name); 

   return 0;
}
예제 #12
0
int ex_put_nodal_var_slab(int exoid, int time_step, int nodal_var_index, int64_t start_pos,
                          int64_t num_vals, void *nodal_var_vals)

{
  int    status;
  int    varid;
  size_t start[3], count[3];
  char   errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* inquire previously defined variable  -- if not found assume that
     the new separate 'blob' per nodal var storage is being used */

  if (ex_large_model(exoid) == 0) {
    /* write values of the nodal variable */
    if ((status = nc_inq_varid(exoid, VAR_NOD_VAR, &varid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "Warning: could not find nodal variable %d in file id %d",
               nodal_var_index, exoid);
      ex_err("ex_put_nodal_var_slab", errmsg, exerrval);
      return (EX_WARN);
    }

    start[0] = --time_step;
    start[1] = --nodal_var_index;
    start[2] = --start_pos;

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

    /* nodal variables stored separately, find variable for this variable
       index */
    if ((status = nc_inq_varid(exoid, VAR_NOD_VAR_NEW(nodal_var_index), &varid)) != NC_NOERR) {
      exerrval = status;
      snprintf(errmsg, MAX_ERR_LENGTH, "Warning: could not find nodal variable %d in file id %d",
               nodal_var_index, exoid);
      ex_err("ex_put_nodal_var_slab", errmsg, exerrval);
      return (EX_WARN);
    }

    start[0] = --time_step;
    start[1] = --start_pos;

    count[0] = 1;
    count[1] = num_vals;
  }

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, varid, start, count, nodal_var_vals);
  }
  else {
    status = nc_put_vara_double(exoid, varid, start, count, nodal_var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: failed to store nodal variables in file id %d", exoid);
    ex_err("ex_put_nodal_var_slab", errmsg, exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);
}
int ex_put_partial_elem_attr (int   exoid,
                        ex_entity_id   elem_blk_id,
                        int64_t   start_elem_num,
                        int64_t   num_elems,
                        void *attrib)
{
  int status;
  int numelbdim, numattrdim, attrid, elem_blk_id_ndx;
  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) {
      sprintf(errmsg,
              "Warning: no attributes allowed for NULL block %"PRId64" in file id %d",
              elem_blk_id, exoid);
      ex_err("ex_put_partial_elem_attr",errmsg,EX_NULLENTITY);
      return (EX_WARN);              /* no attributes for this element block */
    } 
      sprintf(errmsg,
             "Error: no element block id %"PRId64" in %s array in file id %d",
              elem_blk_id, VAR_ID_EL_BLK, exoid);
      ex_err("ex_put_partial_elem_attr",errmsg,exerrval);
      return (EX_FATAL);
    
  }

  /* 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) {
    if (status == NC_EBADDIM) {
      exerrval = status;
      sprintf(errmsg,
         "Error: no element block with id %"PRId64" in file id %d",
             elem_blk_id, exoid);
      ex_err("ex_put_partial_elem_attr",errmsg,exerrval);
      return (EX_FATAL);
    } 
      exerrval = status;
      sprintf(errmsg,
        "Error: failed to locate number of elements for block %"PRId64" in file id %d",
             elem_blk_id, exoid);
      ex_err("ex_put_partial_elem_attr",errmsg,exerrval);
      return (EX_FATAL);
    
  }


  if ((status = nc_inq_dimlen(exoid, numelbdim, &num_elem_this_blk)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
           "Error: failed to get number of elements for block %"PRId64" in file id %d",
            elem_blk_id, exoid);
    ex_err("ex_put_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;
    sprintf(errmsg,
           "Error: number of attributes not defined for block %"PRId64" in file id %d",
            elem_blk_id, exoid);
    ex_err("ex_put_partial_elem_attr",errmsg,EX_MSG);
    return (EX_FATAL);              /* number of attributes not defined */
  }

  if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
         "Error: failed to get number of attributes for block %"PRId64" in file id %d",
            elem_blk_id, exoid);
    ex_err("ex_put_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;
    sprintf(errmsg,
        "Error: failed to locate attribute variable for block %"PRId64" in file id %d",
            elem_blk_id, exoid);
    ex_err("ex_put_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;
    sprintf(errmsg,
      "Error: requested attributes from too many elements in block %"PRId64,
            elem_blk_id);
    ex_err("ex_put_partial_elem_attr",errmsg, exerrval);
    return(EX_FATAL);
  }

  /* write out the attributes  */
  start[0] = --start_elem_num;
  start[1] = 0;

  count[0] = num_elems;
  count[1] = num_attr;

  if (count[0] == 0) {
    start[0] = 0;
}
  
  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, attrid, start, count, attrib);
  } else {
    status = nc_put_vara_double(exoid, attrid, start, count, attrib);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to put attributes for block %"PRId64" in file id %d",
            elem_blk_id, exoid);
    ex_err("ex_put_partial_elem_attr",errmsg,exerrval);
    return (EX_FATAL);
  }
  return(EX_NOERR);
}
예제 #14
0
int ex_put_var (int   exoid,
		int   time_step,
		ex_entity_type var_type,
		int   var_index,
		ex_entity_id   obj_id,
		int64_t   num_entries_this_obj,
		const void *var_vals)
{
  int varid;
  size_t start[2], count[2];
  int status;
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  switch (var_type) {
  case EX_GLOBAL:
    if ( num_entries_this_obj <= 0 ) {
      exerrval = EX_MSG;
      sprintf(errmsg,
	      "Warning: no global variables specified for file id %d",
	      exoid);
      ex_err("ex_put_glob_vars",errmsg,exerrval);

      return (EX_WARN);
    }

    /* inquire previously defined variable */
    if ((status = nc_inq_varid (exoid, VAR_GLO_VAR, &varid)) != NC_NOERR) {
      if (status == NC_ENOTVAR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: no global variables defined in file id %d",
		exoid);
	ex_err("ex_put_glob_vars",errmsg,exerrval);
      } else {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to get global variables parameters in file id %d",
		exoid);
	ex_err("ex_put_glob_vars",errmsg,exerrval);
      }
      return (EX_FATAL);
    }
    break;
  case EX_NODAL:
    return ex_put_nodal_var(exoid, time_step, var_index, num_entries_this_obj, var_vals);
    break;
  case EX_EDGE_BLOCK:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
			    VAR_ID_ED_BLK,VAR_EBLK_TAB,DIM_NUM_ED_BLK,DIM_NUM_EDG_VAR, &varid);
    break;
  case EX_FACE_BLOCK:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_ID_FA_BLK,VAR_FBLK_TAB,DIM_NUM_FA_BLK,DIM_NUM_FAC_VAR, &varid);
    break;
  case EX_ELEM_BLOCK:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_ID_EL_BLK,VAR_ELEM_TAB,DIM_NUM_EL_BLK,DIM_NUM_ELE_VAR, &varid);
    break;
  case EX_NODE_SET:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_NS_IDS,VAR_NSET_TAB,DIM_NUM_NS,DIM_NUM_NSET_VAR, &varid);
    break;
  case EX_EDGE_SET:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_ES_IDS,VAR_ESET_TAB,DIM_NUM_ES,DIM_NUM_ESET_VAR, &varid);
    break;
  case EX_FACE_SET:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_FS_IDS,VAR_FSET_TAB,DIM_NUM_FS,DIM_NUM_FSET_VAR, &varid);
    break;
  case EX_SIDE_SET:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_SS_IDS,VAR_SSET_TAB,DIM_NUM_SS,DIM_NUM_SSET_VAR, &varid);
    break;
  case EX_ELEM_SET:
    status = ex_look_up_var(exoid, var_type, var_index, obj_id,
		   VAR_ELS_IDS,VAR_ELSET_TAB,DIM_NUM_ELS,DIM_NUM_ELSET_VAR, &varid);
    break;
  default:
    exerrval = EX_MSG;
    sprintf( errmsg, "Error: invalid variable type (%d) specified for file id %d",
	     var_type, exoid );
    ex_err( "ex_put_var", errmsg, exerrval );
    return (EX_FATAL);
  }

  if (status != EX_NOERR) {
    return status;
  }    

  /* store element variable values */
  start[0] = --time_step;
  start[1] = 0;

  if ( var_type == EX_GLOBAL ) {
    /* global variables may be written
     * - all at once (by setting var_index to 1 and num_entries_this_obj to num_glob, or
     * - one at a time (by setting var_index to the desired index and num_entries_this_obj to 1.
     */
    count[0] = var_index;
  } else {
    count[0] = 1;
  }
  count[1] = num_entries_this_obj;

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, varid, start, count, var_vals);
  } else {
    status = nc_put_vara_double(exoid, varid, start, count, var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to store %s %"PRId64" variable %d in file id %d",
	    ex_name_of_object(var_type), obj_id, var_index,exoid);
    ex_err("ex_put_var",errmsg,exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);
}
예제 #15
0
int ex_put_partial_side_set_df (int   exoid,
                          ex_entity_id   side_set_id,
                          int64_t   start_num,
                          int64_t   num_df_to_get,
                          void *side_set_dist_fact)
{
  int status;
  int dimid, side_set_id_ndx;
  int dist_id;
  size_t num_df_in_set,  start[1], count[1];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

  /* first check if any side sets are specified */

  if ((status = nc_inq_dimid (exoid, DIM_NUM_SS, &dimid)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: no side sets specified in file id %d",
            exoid);
    ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* Lookup index of side set id in VAR_SS_IDS array */

  if ((side_set_id_ndx = ex_id_lkup(exoid, EX_SIDE_SET, side_set_id)) < 0)
  {
    if (exerrval == EX_NULLENTITY) {
      sprintf(errmsg,
              "Warning: no data allowed for NULL side set %"PRId64" in file id %d",
              side_set_id, exoid);
      ex_err("ex_put_side_set_fact",errmsg,EX_MSG);
      return (EX_WARN);
    } else {
      sprintf(errmsg,
     "Error: failed to locate side set id %"PRId64" in VAR_SS_IDS array in file id %d",
              side_set_id, exoid);
      ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  /* inquire id's of previously defined dimension and variable */

  if ((status = nc_inq_dimid (exoid, DIM_NUM_DF_SS(side_set_id_ndx), &dimid)) != NC_NOERR) {
    if (status == NC_EBADDIM) {
      exerrval = EX_BADPARAM;
      sprintf(errmsg,
              "Warning: no dist factors defined for side set %"PRId64" in file id %d",
              side_set_id, exoid);
      ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
      return (EX_WARN);

    } else {
      exerrval = status;
      sprintf(errmsg,
  "Error: failed to locate number of dist factors in side set %"PRId64" in file id %d",
              side_set_id, exoid);
      ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
      return (EX_FATAL);
    }
  }

  if ((status = nc_inq_dimlen(exoid, dimid, &num_df_in_set)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
     "Error: failed to get number of dist factors in side set %"PRId64" in file id %d",
            side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }

  /* Check input parameters for a valid range of numbers */
  if (start_num < 0 || (num_df_to_get > 0 && start_num > num_df_in_set)) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Invalid input");
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  if (num_df_to_get < 0) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: Invalid number of df's to put!");
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  /* start_num now starts at 1, not 0 */
  if ((start_num + num_df_to_get) > num_df_in_set+1) {
    exerrval = EX_BADPARAM;
    sprintf(errmsg, "Error: request larger than number of df's in set!");
    ex_err("ex_put_partial_side_set_df", errmsg, exerrval);
    return (EX_FATAL);
  }

  if ((status = nc_inq_varid (exoid, VAR_FACT_SS(side_set_id_ndx), &dist_id)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to locate dist factors list for side set %"PRId64" in file id %d",
            side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }


  /* write out the distribution factors array */
  start[0] = --start_num;
  count[0] = num_df_to_get;
  if (num_df_to_get == 0)
    start[0] = 0;
  
  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, dist_id, start, count, side_set_dist_fact);
  } else {
    status = nc_put_vara_double(exoid, dist_id, start, count, side_set_dist_fact);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
            "Error: failed to store dist factors for side set %"PRId64" in file id %d",
            side_set_id, exoid);
    ex_err("ex_put_partial_side_set_df",errmsg,exerrval);
    return (EX_FATAL);
  }
  return (EX_NOERR);
}
예제 #16
0
파일: expnvar.c 프로젝트: 151706061/VTK
int ex_put_n_var (int   exoid,
      int   time_step,
      ex_entity_type var_type,
      int   var_index,
      int   obj_id,
      int   start_index,
      int   num_entities,
      const void *var_vals)
{
  int varid, dimid,time_dim, numobjdim, dims[2], obj_id_ndx;
  size_t num_obj;
  size_t num_obj_var;
  size_t num_entity;
  size_t start[2], count[2];
  int *obj_var_truth_tab;
  int status;
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

#define EX_LOOK_UP_VAR(VOBJID,VVAR,VOBJTAB,DNUMOBJ,DNUMOBJVAR)    \
  /* Determine index of obj_id in VOBJID array */     \
    obj_id_ndx = ex_id_lkup(exoid,var_type,obj_id);     \
    if (exerrval != 0)              \
      {                 \
  if (exerrval == EX_NULLENTITY)          \
    {               \
      sprintf(errmsg,           \
        "Warning: no variables allowed for NULL block %d in file id %d", \
        obj_id,exoid);          \
      ex_err("ex_put_n_var",errmsg,EX_MSG);       \
      return (EX_WARN);           \
    }               \
  else                \
    {               \
      sprintf(errmsg,           \
        "Error: failed to locate %s id %d in %s array in file id %d", \
        ex_name_of_object(var_type), obj_id, VOBJID, exoid); \
      ex_err("ex_put_n_var",errmsg,exerrval);     \
      return (EX_FATAL);            \
    }               \
      }                 \
                  \
    if ((status = nc_inq_varid (exoid, VVAR(var_index,obj_id_ndx), &varid)) != NC_NOERR) \
      {                 \
  if (status == NC_ENOTVAR) /* variable doesn't exist, create it! */ \
    {               \
      /* check for the existance of an TNAME variable truth table */ \
      if (nc_inq_varid(exoid, VOBJTAB, &varid) == NC_NOERR) { \
        /* find out number of TNAMEs and TNAME variables */ \
        status = ex_get_dimension(exoid, DNUMOBJ, ex_name_of_object(var_type), &num_obj, &dimid, "ex_put_n_var"); \
        if (status != NC_NOERR) return status;      \
                  \
        status = ex_get_dimension(exoid, DNUMOBJVAR, ex_name_of_object(var_type), &num_obj_var, &dimid, "ex_put_n_var"); \
        if (status != NC_NOERR) return status;      \
                  \
        if (!(obj_var_truth_tab = malloc(num_obj*num_obj_var*sizeof(int)))) \
    {             \
      exerrval = EX_MEMFAIL;        \
      sprintf(errmsg,         \
        "Error: failed to allocate memory for %s variable truth table in file id %d", \
        ex_name_of_object(var_type), exoid);    \
      ex_err("ex_put_n_var",errmsg,exerrval);     \
      return (EX_FATAL);          \
    }             \
                  \
        /*   read in the TNAME variable truth table */    \
        if ((status = nc_get_var_int (exoid, varid, obj_var_truth_tab)) != NC_NOERR) \
    {             \
      exerrval = status;          \
      sprintf(errmsg,         \
        "Error: failed to get truth table from file id %d", exoid); \
      ex_err("ex_put_n_var",errmsg,exerrval);     \
      return (EX_FATAL);          \
    }             \
                  \
        if(obj_var_truth_tab[num_obj_var*(obj_id_ndx-1)+var_index-1] \
     == 0L)             \
    {             \
      free(obj_var_truth_tab);        \
      exerrval = EX_BADPARAM;       \
      sprintf(errmsg,         \
        "Error: Invalid %s variable %d, %s %d in file id %d", \
        ex_name_of_object(var_type), var_index, ex_name_of_object(var_type), obj_id, exoid); \
      ex_err("ex_put_n_var",errmsg,exerrval);     \
      return (EX_FATAL);          \
    }             \
        free(obj_var_truth_tab);          \
      }               \
                  \
      if ((status = nc_inq_dimid(exoid, DIM_TIME, &time_dim)) != NC_NOERR) { \
        exerrval = status;          \
        sprintf(errmsg,           \
          "Error: failed to locate time dimension in file id %d", exoid); \
        ex_err("ex_put_n_var",errmsg,exerrval);     \
        goto error_ret;         /* exit define mode and return */ \
      }               \
                  \
      ex_get_dimension(exoid, ex_dim_num_entries_in_object(var_type, obj_id_ndx), \
           ex_name_of_object(var_type), &num_entity, &numobjdim,  "ex_put_n_var"); \
                  \
      /*    variable doesn't exist so put file into define mode  */ \
      if ((status = nc_redef (exoid)) != NC_NOERR) {    \
        exerrval = status;          \
        sprintf(errmsg,           \
          "Error: failed to put file id %d into define mode", exoid); \
        ex_err("ex_put_n_var",errmsg,exerrval);     \
        return (EX_FATAL);          \
      }               \
                  \
      /* define netCDF variable to store TNAME variable values */ \
      dims[0] = time_dim;           \
      dims[1] = numobjdim;          \
      if ((status = nc_def_var(exoid, VVAR(var_index,obj_id_ndx), \
             nc_flt_code(exoid), 2, dims, &varid)) != NC_NOERR) \
        {               \
    exerrval = status;          \
    sprintf(errmsg,           \
      "Error: failed to define %s variable %d in file id %d", \
      ex_name_of_object(var_type), var_index,exoid);  \
    ex_err("ex_put_n_var",errmsg,exerrval);     \
    goto error_ret;           \
        }               \
                  \
      /*    leave define mode  */         \
                  \
      if ((status = nc_enddef (exoid)) != NC_NOERR)   \
        {               \
    exerrval = status;          \
    sprintf(errmsg,           \
      "Error: failed to complete %s variable %s definition to file id %d", \
      ex_name_of_object(var_type), VVAR(var_index,obj_id_ndx), exoid); \
    ex_err("ex_put_n_var",errmsg,exerrval);     \
    return (EX_FATAL);          \
        }               \
    }               \
  else                \
    {               \
      exerrval = status;            \
      sprintf(errmsg,           \
        "Error: failed to locate %s variable %s in file id %d", \
        ex_name_of_object(var_type), VVAR(var_index,obj_id_ndx),exoid); \
      ex_err("ex_put_n_var",errmsg,exerrval);     \
      return (EX_FATAL);            \
    }               \
      }

  switch (var_type) {
  case EX_GLOBAL:
    if ( num_entities <= 0 ) {
      exerrval = EX_MSG;
      sprintf(errmsg,
        "Warning: no global variables specified for file id %d",
        exoid);
      ex_err("ex_put_glob_vars",errmsg,exerrval);

      return (EX_WARN);
    }
    /* inquire previously defined variable */

    if ((status = nc_inq_varid (exoid, VAR_GLO_VAR, &varid)) != NC_NOERR) {
      if (status == NC_ENOTVAR) {
        exerrval = status;
        sprintf(errmsg,
    "Error: no global variables defined in file id %d",
    exoid);
        ex_err("ex_put_glob_vars",errmsg,exerrval);
      } else {
        exerrval = status;
        sprintf(errmsg,
    "Error: failed to get global variables parameters in file id %d",
    exoid);
        ex_err("ex_put_glob_vars",errmsg,exerrval);
      }
      return (EX_FATAL);
    } 
    break;
  case EX_NODAL:
    return ex_put_n_nodal_var(exoid, time_step, var_index, start_index, num_entities, var_vals);
    break;
  case EX_EDGE_BLOCK:
    EX_LOOK_UP_VAR(VAR_ID_ED_BLK,VAR_EDGE_VAR,VAR_EBLK_TAB,DIM_NUM_ED_BLK,DIM_NUM_EDG_VAR);
    break;
  case EX_FACE_BLOCK:
    EX_LOOK_UP_VAR(VAR_ID_FA_BLK,VAR_FACE_VAR,VAR_FBLK_TAB,DIM_NUM_FA_BLK,DIM_NUM_FAC_VAR);
    break;
  case EX_ELEM_BLOCK:
    EX_LOOK_UP_VAR(VAR_ID_EL_BLK,VAR_ELEM_VAR,VAR_ELEM_TAB,DIM_NUM_EL_BLK,DIM_NUM_ELE_VAR);
    break;
  case EX_NODE_SET:
    EX_LOOK_UP_VAR(VAR_NS_IDS,VAR_NS_VAR,VAR_NSET_TAB,DIM_NUM_NS,DIM_NUM_NSET_VAR);
    break;
  case EX_EDGE_SET:
    EX_LOOK_UP_VAR(VAR_ES_IDS,VAR_ES_VAR,VAR_ESET_TAB,DIM_NUM_ES,DIM_NUM_ESET_VAR);
    break;
  case EX_FACE_SET:
    EX_LOOK_UP_VAR(VAR_FS_IDS,VAR_FS_VAR,VAR_FSET_TAB,DIM_NUM_FS,DIM_NUM_FSET_VAR);
    break;
  case EX_SIDE_SET:
    EX_LOOK_UP_VAR(VAR_SS_IDS,VAR_SS_VAR,VAR_SSET_TAB,DIM_NUM_SS,DIM_NUM_SSET_VAR);
    break;
  case EX_ELEM_SET:
    EX_LOOK_UP_VAR(VAR_ELS_IDS,VAR_ELS_VAR,VAR_ELSET_TAB,DIM_NUM_ELS,DIM_NUM_ELSET_VAR);
    break;
  default:
    exerrval = EX_MSG;
    sprintf( errmsg, "Error: invalid variable type (%d) specified for file id %d",
       var_type, exoid );
    ex_err( "ex_put_n_var", errmsg, exerrval );
    return (EX_FATAL);
  }
  /* store element variable values */

  start[0] = --time_step;
  start[1] = start_index-1;
  if ( var_type == EX_GLOBAL ) {
    /* global variables may be written
     * - all at once (by setting var_index to 1 and num_entries_this_obj to num_glob, or
     * - one at a time (by setting var_index to the desired index and num_entries_this_obj to 1.
     */
    count[0] = var_index;
  } else {
    count[0] = 1;
  }
  count[1] = num_entities;

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, varid, start, count, var_vals);
  } else {
    status = nc_put_vara_double(exoid, varid, start, count, var_vals);
  }

  if (status != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
      "Error: failed to store %s %d variable %d in file id %d", 
      ex_name_of_object(var_type), obj_id, var_index,exoid);
    ex_err("ex_put_n_var",errmsg,exerrval);
    return (EX_FATAL);
  }

  return (EX_NOERR);

  /* Fatal error: exit definition mode and return */
 error_ret:
  if (nc_enddef (exoid) != NC_NOERR)     /* exit define mode */
    {
      sprintf(errmsg,
        "Error: failed to complete definition for file id %d",
        exoid);
      ex_err("ex_put_n_var",errmsg,exerrval);
    }
  return (EX_FATAL);
}
예제 #17
0
int
main(int argc, char **argv)
{
    int i;
    char* filename = "tst_diskless.nc";

    /* Set defaults */
    persist = 0;
    usenetcdf4 = 0;
    mmap = 0;

    for(i=1;i<argc;i++) {
	if(strcmp(argv[i],"netcdf4")==0) usenetcdf4=1;
	else if(strcmp(argv[i],"persist")==0) persist=1;
	else if(strcmp(argv[i],"mmap")==0) mmap=1;
	/* ignore anything not recognized */
    }

#ifndef USE_NETCDF4
    usenetcdf4 = 0;
#endif

    if(mmap)
	usenetcdf4 = 0;

    flags = usenetcdf4?FLAGS4:FLAGS3;
    if(persist) flags |= PERSIST;
    if(mmap) flags |= NC_MMAP;

printf("\n*** Testing the diskless API.\n");
printf("*** testing diskless file with scalar vars...");
{
    int ncid, varid0, varid1, varid2;
    int ndims_in, nvars_in, natts_in, unlimdimid_in;
    char name_in[NC_MAX_NAME + 1];
    nc_type type_in;
    float float_data = 3.14, float_data_in;
    int int_data = 42, int_data_in;
    short short_data = 2, short_data_in;

    removefile(persist,filename);

    /* Create a netCDF file (which exists only in memory). */
    if (nc_create(filename, flags, &ncid)) ERR;

    /* Create some variables. */
    if (nc_def_var(ncid, RESISTOR, NC_INT, 0, NULL, &varid0)) ERR;
    if (nc_def_var(ncid, CAPACITOR, NC_FLOAT, 0, NULL, &varid1)) ERR;
    if (nc_def_var(ncid, NUM555, NC_SHORT, 0, NULL, &varid2)) ERR;
    if (nc_enddef(ncid)) ERR;

    /* Write some data to this file. */
    if (nc_put_vara_int(ncid, varid0, NULL, NULL, &int_data)) ERR;
    if (nc_put_vara_float(ncid, varid1, NULL, NULL, &float_data)) ERR;
    if (nc_put_vara_short(ncid, varid2, NULL, NULL, &short_data)) ERR;

    /* Now check the phony file. */
    if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
    if (ndims_in != 0 || nvars_in != 3 || natts_in != 0 || unlimdimid_in != -1) ERR;

    /* Check variables. */
    if (nc_inq_var(ncid, varid0, name_in, &type_in, &ndims_in, NULL, &natts_in)) ERR;
    if (strcmp(name_in, RESISTOR) || type_in != NC_INT || ndims_in != 0 ||
    natts_in != 0) ERR;
    if (nc_inq_var(ncid, varid1, name_in, &type_in, &ndims_in, NULL, &natts_in)) ERR;
    if (strcmp(name_in, CAPACITOR) || type_in != NC_FLOAT || ndims_in != 0 ||
    natts_in != 0) ERR;
    if (nc_inq_var(ncid, varid2, name_in, &type_in, &ndims_in, NULL, &natts_in)) ERR;
    if (strcmp(name_in, NUM555) || type_in != NC_SHORT || natts_in != 0) ERR;

    /* Read my absolutely crucial data. */
    if (nc_get_vara_int(ncid, varid0, NULL, NULL, &int_data_in)) ERR;
    if (int_data_in != int_data) ERR;
    if (nc_get_vara_float(ncid, varid1, NULL, NULL, &float_data_in)) ERR;
    if (float_data_in != float_data) ERR;
    if (nc_get_vara_short(ncid, varid2, NULL, NULL, &short_data_in)) ERR;
    if (short_data_in != short_data) ERR;

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

    if(!usenetcdf4 && persist) {
        int ncid, varid0, varid1, varid2;
        float float_data = 3.14, float_data_in;
        int int_data = 42, int_data_in;
        short short_data = 2, short_data_in;

        printf("*** testing diskless open of previously created file...");

        if (nc_open(filename, flags, &ncid)) ERR;

	/* Read and compare */
        if (nc_inq_varid(ncid, RESISTOR, &varid0)) ERR;
        if (nc_inq_varid(ncid, CAPACITOR, &varid1)) ERR;
        if (nc_inq_varid(ncid, NUM555, &varid2)) ERR;

        if (nc_get_vara_int(ncid, varid0, NULL, NULL, &int_data_in)) ERR;
        if (int_data_in != int_data) ERR;
        if (nc_get_vara_float(ncid, varid1, NULL, NULL, &float_data_in)) ERR;
        if (float_data_in != float_data) ERR;
        if (nc_get_vara_short(ncid, varid2, NULL, NULL, &short_data_in)) ERR;
        if (short_data_in != short_data) ERR;

	nc_close(ncid);
    }
    SUMMARIZE_ERR;

    printf("*** testing creation of simple diskless file...");
    {
    #define NDIMS 2
    #define DIM0_NAME "Fun"
    #define DIM1_NAME "Money"
    #define DIM1_LEN 200
    #define ATT0_NAME "home"
    #define ATT0_TEXT "earthship"
    #define VAR0_NAME "nightlife"
    #define VAR1_NAME "time"
    #define VAR2_NAME "taxi_distance"

    int ncid, dimid[NDIMS], dimid_in[NDIMS], varid0, varid1, varid2;
    int ndims_in, nvars_in, natts_in, unlimdimid_in;
    char name_in[NC_MAX_NAME + 1], att0_in[NC_MAX_NAME + 1];
    nc_type type_in;
    size_t len_in;
    short short_data[DIM1_LEN];
    size_t start[1] = {0};
    size_t count[1] = {DIM1_LEN};
    int i;
    float float_data = 42.22, float_data_in;

    /* This is some really important data that I want to save. */
    for (i = 0; i < DIM1_LEN; i++)
    short_data[i] = i;

    removefile(persist,filename);

    /* Create a netCDF file (which exists only in memory). I am
    * confident that the world-famous netCDF format is the way to
    * store my data! */
    if (nc_create(filename, flags, &ncid)) ERR;

    /* Create some atts. They will help document my data forever. */
    if (nc_put_att_text(ncid, NC_GLOBAL, ATT0_NAME,
    sizeof(ATT0_TEXT) + 1, ATT0_TEXT)) ERR;

    /* Create dimensions: money is limited, but fun is not! */
    if (nc_def_dim(ncid, DIM0_NAME, NC_UNLIMITED, &dimid[0])) ERR;
    if (nc_def_dim(ncid, DIM1_NAME, DIM1_LEN, &dimid[1])) ERR;

    /* Create some variables. The data they hold must persist
    * through the ages. */
    if (nc_def_var(ncid, VAR0_NAME, NC_INT, NDIMS, dimid, &varid0)) ERR;
    if (nc_def_var(ncid, VAR1_NAME, NC_FLOAT, 0, NULL, &varid1)) ERR;
    if (nc_def_var(ncid, VAR2_NAME, NC_SHORT, 1, &dimid[1], &varid2)) ERR;
    if (nc_enddef(ncid)) ERR;

    /* Write some data to this file. I'm glad I'm saving this
    * important data in such a safe format! */
    if (nc_put_vara_float(ncid, varid1, NULL, NULL, &float_data)) ERR;
    if (nc_put_vara_short(ncid, varid2, start, count, short_data)) ERR;

    /* Now check the phony file. Is my data safe? */
    if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
    if (ndims_in != 2 || nvars_in != 3 || natts_in != 1 || unlimdimid_in != 0) ERR;

    /* Check attributes - they will be needed by future generations
    * of scientists to understand my data. */
    if (nc_get_att_text(ncid, NC_GLOBAL, ATT0_NAME, att0_in)) ERR;
    if (strcmp(att0_in, ATT0_TEXT)) ERR;

    /* Check dimensions. */
    if (nc_inq_dim(ncid, dimid[0], name_in, &len_in)) ERR;
    if (strcmp(name_in, DIM0_NAME) || len_in != 0) ERR;
    if (nc_inq_dim(ncid, dimid[1], name_in, &len_in)) ERR;
    if (strcmp(name_in, DIM1_NAME) || len_in != DIM1_LEN) ERR;

    /* Check variables. */
    if (nc_inq_var(ncid, varid0, name_in, &type_in, &ndims_in, dimid_in, &natts_in)) ERR;
    if (strcmp(name_in, VAR0_NAME) || type_in != NC_INT || ndims_in != NDIMS ||
    dimid_in[0] != 0 || dimid_in[1] != 1 || natts_in != 0) ERR;
    if (nc_inq_var(ncid, varid1, name_in, &type_in, &ndims_in, dimid_in, &natts_in)) ERR;
    if (strcmp(name_in, VAR1_NAME) || type_in != NC_FLOAT || ndims_in != 0 ||
    natts_in != 0) ERR;
    if (nc_inq_var(ncid, varid2, name_in, &type_in, &ndims_in, dimid_in, &natts_in)) ERR;
    if (strcmp(name_in, VAR2_NAME) || type_in != NC_SHORT || ndims_in != 1 ||
    dimid_in[0] != 1 || natts_in != 0) ERR;

    /* Read my absolutely crucial data. */
    if (nc_get_vara_float(ncid, varid1, NULL, NULL, &float_data_in)) ERR;
    if (float_data_in != float_data) ERR;

    /* Close the file, losing all information. Hey! What kind of
    * storage format is this, anyway? */
    if (nc_close(ncid))
	abort(); //ERR;
    }
    SUMMARIZE_ERR;
    printf("*** testing diskless file with scalar vars and type conversion...");
    {
    #define DUNE "dune"
    #define STAR_TREK "capacitor_value"
    #define STAR_WARS "number_of_555_timer_chips"

    int ncid, varid0, varid1, varid2;
    int ndims_in, nvars_in, natts_in, unlimdimid_in;
    char name_in[NC_MAX_NAME + 1];
    nc_type type_in;
    float float_data = 3.14, float_data_in;
    int int_data = 42, int_data_in;
    short short_data = 2, short_data_in;

    removefile(persist,filename);

    /* Create a netCDF file (which exists only in memory). */
    if (nc_create(filename, flags, &ncid)) ERR;

    /* Create some variables. */
    if (nc_def_var(ncid, DUNE, NC_INT, 0, NULL, &varid0)) ERR;
    if (nc_def_var(ncid, STAR_TREK, NC_FLOAT, 0, NULL, &varid1)) ERR;
    if (nc_def_var(ncid, STAR_WARS, NC_SHORT, 0, NULL, &varid2)) ERR;
    if (nc_enddef(ncid)) ERR;

    /* Write some data to this file. */
    if (nc_put_vara_int(ncid, varid0, NULL, NULL, &int_data)) ERR;
    if (nc_put_vara_float(ncid, varid1, NULL, NULL, &float_data)) ERR;
    if (nc_put_vara_short(ncid, varid2, NULL, NULL, &short_data)) ERR;

    /* Now check the phony file. */
    if (nc_inq(ncid, &ndims_in, &nvars_in, &natts_in, &unlimdimid_in)) ERR;
    if (ndims_in != 0 || nvars_in != 3 || natts_in != 0 || unlimdimid_in != -1) ERR;

    /* Check variables. */
    if (nc_inq_var(ncid, varid0, name_in, &type_in, &ndims_in, NULL, &natts_in)) ERR;
    if (strcmp(name_in, DUNE) || type_in != NC_INT || ndims_in != 0 ||
    natts_in != 0) ERR;
    if (nc_inq_var(ncid, varid1, name_in, &type_in, &ndims_in, NULL, &natts_in)) ERR;
    if (strcmp(name_in, STAR_TREK) || type_in != NC_FLOAT || ndims_in != 0 ||

    natts_in != 0) ERR;
    if (nc_inq_var(ncid, varid2, name_in, &type_in, &ndims_in, NULL, &natts_in)) ERR;
    if (strcmp(name_in, STAR_WARS) || type_in != NC_SHORT || natts_in != 0) ERR;

    /* Read my absolutely crucial data. */
    if (nc_get_vara_int(ncid, varid0, NULL, NULL, &int_data_in)) ERR;
    if (int_data_in != int_data) ERR;
    if (nc_get_vara_float(ncid, varid1, NULL, NULL, &float_data_in)) ERR;
    if (float_data_in != float_data) ERR;
    if (nc_get_vara_short(ncid, varid2, NULL, NULL, &short_data_in)) ERR;
    if (short_data_in != short_data) ERR;

    /* Close the file. */
    if (nc_close(ncid))
	abort(); //ERR;
    }
    SUMMARIZE_ERR;
    FINAL_RESULTS;

    /* Unnecessary exit(0), FINAL_RESULTS returns. */
    //exit(0);
}
예제 #18
0
int ex_put_partial_coord (int   exoid,
                    int64_t start_node_num,
                    int64_t num_nodes,
		    const void *x_coor,
		    const void *y_coor,
		    const void *z_coor)
{
  int status;
  int coordid;
  int coordidx, coordidy, coordidz;

  int numnoddim, ndimdim;
  int64_t num_nod;
  size_t i, num_dim, start[2], count[2];
  char errmsg[MAX_ERR_LENGTH];

  exerrval = 0; /* clear error code */

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

  if ((status = 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);
  }

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

  if ((status = nc_inq_dimid(exoid, DIM_NUM_DIM, &ndimdim)) != NC_NOERR) {
    exerrval = status;
    sprintf(errmsg,
	    "Error: failed to locate number of dimensions in file id %d",
	    exoid);
    ex_err("ex_put_partial_coord",errmsg,exerrval);
    return (EX_FATAL);
  }

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

  if (start_node_num + num_nodes -1 > num_nod) {
    exerrval = EX_BADPARAM;
      sprintf(errmsg,
              "Error: start index (%"PRId64") + node count (%"PRId64") is larger than total number of nodes (%"PRId64") in file id %d",
              start_node_num, num_nodes, num_nod, exoid);
      ex_err("ex_put_partial_coord",errmsg,exerrval);
      return (EX_FATAL);
  }

  --start_node_num;

  /* write out 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_put_partial_coord",errmsg,exerrval);
      return (EX_FATAL);
    } 

    for (i=0; i<num_dim; i++) {
      char *which = 0;
      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_put_vara_float(exoid, coordid, start, count, x_coor);
	} else {
	  status = nc_put_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_put_vara_float(exoid, coordid, start, count, y_coor);
	} else {
	  status = nc_put_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_put_vara_float(exoid, coordid, start, count, z_coor);
	} else {
	  status = nc_put_vara_double(exoid, coordid, start, count, z_coor);
	}
      }
	  
      if (status != NC_NOERR) {
	exerrval = status;
	sprintf(errmsg,
		"Error: failed to put %s coord array in file id %d", which, exoid);
	ex_err("ex_put_partial_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_put_partial_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_put_partial_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_put_partial_coord",errmsg,exerrval);
	return (EX_FATAL);
      }
    } else {
      coordidz = 0;
    }

    /* write out the coordinates  */
    for (i=0; i<num_dim; i++) {
      const 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_put_vara_float(exoid, coordid, start, count, coor);
	} else {
	  status = nc_put_vara_double(exoid, coordid, start, count, coor);
	}

	if (status != NC_NOERR) {
	  exerrval = status;
	  sprintf(errmsg,
		  "Error: failed to put %s coord array in file id %d", which, exoid);
	  ex_err("ex_put_partial_coord",errmsg,exerrval);
	  return (EX_FATAL);
	}
      }
    }
  }
  return (EX_NOERR);
}
예제 #19
0
int ex_put_partial_attr(int exoid, ex_entity_type blk_type, ex_entity_id blk_id,
                        int64_t start_entity, int64_t num_entity, const void *attrib)
{
  int    status;
  int    attrid;
  int    blk_id_ndx = 0;
  int    numattrdim;
  size_t start[2], count[2];
  size_t num_attr;
  char   errmsg[MAX_ERR_LENGTH];

  EX_FUNC_ENTER();
  ex_check_valid_file_id(exoid, __func__);

  if (blk_type != EX_NODAL) {
    /* Determine index of blk_id in VAR_ID_EL_BLK array */
    blk_id_ndx = ex_id_lkup(exoid, blk_type, blk_id);
    if (blk_id_ndx <= 0) {
      ex_get_err(NULL, NULL, &status);

      if (status != 0) {
        if (status == EX_NULLENTITY) {
          snprintf(errmsg, MAX_ERR_LENGTH,
                   "Warning: no attributes allowed for NULL %s %" PRId64 " in file id %d",
                   ex_name_of_object(blk_type), blk_id, exoid);
          ex_err(__func__, errmsg, EX_NULLENTITY);
          EX_FUNC_LEAVE(EX_WARN); /* no attributes for this block */
        }
        snprintf(errmsg, MAX_ERR_LENGTH, "ERROR: no %s id %" PRId64 " in in file id %d",
                 ex_name_of_object(blk_type), blk_id, exoid);
        ex_err(__func__, errmsg, status);
        EX_FUNC_LEAVE(EX_FATAL);
      }
    }
  }

  switch (blk_type) {
  case EX_SIDE_SET: status = nc_inq_varid(exoid, VAR_SSATTRIB(blk_id_ndx), &attrid); break;
  case EX_NODE_SET: status = nc_inq_varid(exoid, VAR_NSATTRIB(blk_id_ndx), &attrid); break;
  case EX_EDGE_SET: status = nc_inq_varid(exoid, VAR_ESATTRIB(blk_id_ndx), &attrid); break;
  case EX_FACE_SET: status = nc_inq_varid(exoid, VAR_FSATTRIB(blk_id_ndx), &attrid); break;
  case EX_ELEM_SET: status = nc_inq_varid(exoid, VAR_ELSATTRIB(blk_id_ndx), &attrid); break;
  case EX_NODAL: status = nc_inq_varid(exoid, VAR_NATTRIB, &attrid); break;
  case EX_EDGE_BLOCK: status = nc_inq_varid(exoid, VAR_EATTRIB(blk_id_ndx), &attrid); break;
  case EX_FACE_BLOCK: status = nc_inq_varid(exoid, VAR_FATTRIB(blk_id_ndx), &attrid); break;
  case EX_ELEM_BLOCK: status = nc_inq_varid(exoid, VAR_ATTRIB(blk_id_ndx), &attrid); break;
  default:
    snprintf(errmsg, MAX_ERR_LENGTH,
             "Internal ERROR: unrecognized object type in switch: %d in file id %d", blk_type,
             exoid);
    ex_err(__func__, errmsg, EX_BADPARAM);
    EX_FUNC_LEAVE(EX_FATAL); /* number of attributes not defined */
  }

  if (status != NC_NOERR) {
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to locate attribute variable for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_FATAL);
  }

  /* Determine number of attributes */
  switch (blk_type) {
  case EX_SIDE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_SS(blk_id_ndx), &numattrdim); break;
  case EX_NODE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_NS(blk_id_ndx), &numattrdim); break;
  case EX_EDGE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_ES(blk_id_ndx), &numattrdim); break;
  case EX_FACE_SET: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_FS(blk_id_ndx), &numattrdim); break;
  case EX_ELEM_SET:
    status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_ELS(blk_id_ndx), &numattrdim);
    break;
  case EX_NODAL: status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_NBLK, &numattrdim); break;
  case EX_EDGE_BLOCK:
    status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_EBLK(blk_id_ndx), &numattrdim);
    break;
  case EX_FACE_BLOCK:
    status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_FBLK(blk_id_ndx), &numattrdim);
    break;
  case EX_ELEM_BLOCK:
    status = nc_inq_dimid(exoid, DIM_NUM_ATT_IN_BLK(blk_id_ndx), &numattrdim);
    break;
  default:
    /* No need for error message, handled in previous switch; just to quiet
     * compiler. */
    EX_FUNC_LEAVE(EX_FATAL);
  }

  if (status != NC_NOERR) {
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: number of attributes not defined for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_FATAL); /* number of attributes not defined */
  }

  if ((status = nc_inq_dimlen(exoid, numattrdim, &num_attr)) != NC_NOERR) {
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to get number of attributes for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_FATAL);
  }

  /* write out the attributes  */
  start[0] = --start_entity;
  start[1] = 0;

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

  if (ex_comp_ws(exoid) == 4) {
    status = nc_put_vara_float(exoid, attrid, start, count, attrib);
  }
  else {
    status = nc_put_vara_double(exoid, attrid, start, count, attrib);
  }

  if (status != NC_NOERR) {
    snprintf(errmsg, MAX_ERR_LENGTH,
             "ERROR: failed to put attributes for %s %" PRId64 " in file id %d",
             ex_name_of_object(blk_type), blk_id, exoid);
    ex_err(__func__, errmsg, status);
    EX_FUNC_LEAVE(EX_FATAL);
  }
  EX_FUNC_LEAVE(EX_NOERR);
}
예제 #20
0
int main(int argc, char* argv[])
{
    char* filename=argv[1];
    FILE* f;

    if(argc<3){
        printf("error:   ");
        printf("Call this program by \"%s volfile.vol out.nc\"\n",argv[0]);
        return -1;
    }

    char line[MAXLINE];
    long int nx,ny,nz;
    //char Shortline[100];
    int i,j,max=0,temp;
    int ncid, x_dimid, y_dimid, z_dimid, varid;
    int dimids[3],retval;
    size_t start[3],count[3];
    long int filesize;
    int x, y,z;
    DATATYPE* data,p;

    printf("input filename: %s \n",filename);
    if((f=fopen(filename,"rb"))){
        fseek(f,0,SEEK_END);
        filesize=ftell(f);
        printf("filesize=%ld\n",filesize);
        rewind(f);
        temp=0;
        while(temp!=3){
            i=0;
            while((line[i]=fgetc(f))!=0 && line[i]!=13 && line[i]!=10) i++;
            //printf("%s\n",line);
            temp=sscanf(line,"Volume Size: %ldx%ldx%ld",&ny,&nx,&nz);
        }
        printf("Volume Size: %ldx%ldx%ld\n",nx,ny,nz);
        fseek(f,filesize%(nx*ny*nz),SEEK_SET);

        data = (DATATYPE*)calloc(nx*ny, sizeof(DATATYPE));
        if(data==NULL){ perror("failed calloc call\n"); return -1; }

        if ((retval = nc_create(argv[2], NC_NETCDF4|NC_CLOBBER, &ncid))) ERR(retval);
        if ((retval = nc_def_dim(ncid, "x", nx, &x_dimid))) ERR(retval);
        if ((retval = nc_def_dim(ncid, "y", ny, &y_dimid))) ERR(retval);
        if ((retval = nc_def_dim(ncid, "z", nz, &z_dimid))) ERR(retval);

        dimids[0] = z_dimid;
        dimids[1] = x_dimid;
        dimids[2] = y_dimid;

        printf("Start to convert sin to NetCDF format ...\n");
#if FLOAT
        if ((retval = nc_def_var(ncid, "density", NC_FLOAT, 3, dimids, &varid))) ERR(retval);
#endif
        if ((retval = nc_enddef(ncid))) ERR(retval);

        count[0] = 1;
        count[1] = nx;
        count[2] = ny;
        start[0] = 0;
        start[1] = 0;
        start[2] = 0;

        memset(line,0,MAXLINE);
        for(z=0; z<nz; z++){
            temp=fread(data,sizeof(DATATYPE),nx*ny,f);
            if(temp!=(nx*ny)){
                printf("readed %d bytes intead of %ld\n",temp,nx*ny*sizeof(DATATYPE));
                return -1;
            }
            //printf("data: %f %f %f %f\n", data[0], data[1], data[2], data[3]);
            start[0]=z;
#if FLOAT
            if ((retval = nc_put_vara_float(ncid, varid, start, count, data))) ERR(retval);
#endif
            for(i=0; i<strlen(line); i++) printf("\b");
            sprintf(line,"z=%d/%ld",z,nz);
            printf("%s",line);
            fflush(stdout);
        }
        fclose(f);
        if ((retval = nc_close(ncid))) ERR(retval);
        printf("\n");
    }

    return 0;
}
예제 #21
0
int
create_file(char *file_name, int fill_mode, size_t* sizehintp) 
{
   int i;
   int  stat;			/* return status */
   int  ncid;			/* netCDF id */

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

   /* dimension lengths */
   size_t lon_len = LON_LEN;
   size_t lat_len = LAT_LEN;
   size_t lvl_len = LVL_LEN;
   size_t time_len = TIME_LEN;

   /* variable ids */
   int time_id;
   int lat_id;
   int lon_id;
   int lvl_id;
   int sfc_pres_id;
   int temp_scrn_id;
   int qsair_scrn_id;
   int topog_id;
   int mslp_id;
   int sfc_temp_id;
   int zonal_wnd_id;

   /* rank (number of dimensions) for each variable */
#  define RANK_time 1
#  define RANK_lat 1
#  define RANK_lon 1
#  define RANK_lvl 1
#  define RANK_sfc_pres 3
#  define RANK_temp_scrn 3
#  define RANK_qsair_scrn 3
#  define RANK_topog 3
#  define RANK_mslp 3
#  define RANK_sfc_temp 3
#  define RANK_zonal_wnd 4

   /* variable shapes */
   int time_dims[RANK_time];
   int lat_dims[RANK_lat];
   int lon_dims[RANK_lon];
   int lvl_dims[RANK_lvl];
   int sfc_pres_dims[RANK_sfc_pres];
   int temp_scrn_dims[RANK_temp_scrn];
   int qsair_scrn_dims[RANK_qsair_scrn];
   int topog_dims[RANK_topog];
   int mslp_dims[RANK_mslp];
   int sfc_temp_dims[RANK_sfc_temp];
   int zonal_wnd_dims[RANK_zonal_wnd];

   size_t zonal_wnd_start[RANK_zonal_wnd];
   size_t zonal_wnd_count[RANK_zonal_wnd];
   float zonal_wnd[LON_LEN*LAT_LEN*TIME_LEN];
   int ii;

   int old_fill_mode;
   size_t default_initialsize = 0;

   /* To test bug on filesystem without large block size, we can get
    * the same effect by providing the desired value as sizehint to
    * nc__create() instead of calling nc_create() and getting the
    * block size reported by fstat */
   stat = nc__create(file_name, NC_CLOBBER, default_initialsize, sizehintp, &ncid);
   check_err(stat,__LINE__,__FILE__);
   stat = nc_set_fill(ncid, fill_mode, &old_fill_mode);
   check_err(stat,__LINE__,__FILE__);

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

   /* define variables */
   time_dims[0] = time_dim;
   stat = nc_def_var(ncid, "time", NC_DOUBLE, RANK_time, time_dims, &time_id);
   check_err(stat,__LINE__,__FILE__);

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

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

   lvl_dims[0] = lvl_dim;
   stat = nc_def_var(ncid, "lvl", NC_FLOAT, RANK_lvl, lvl_dims, &lvl_id);
   check_err(stat,__LINE__,__FILE__);

   sfc_pres_dims[0] = time_dim;
   sfc_pres_dims[1] = lat_dim;
   sfc_pres_dims[2] = lon_dim;
   stat = nc_def_var(ncid, "sfc_pres", NC_FLOAT, RANK_sfc_pres, sfc_pres_dims, &sfc_pres_id);
   check_err(stat,__LINE__,__FILE__);

   temp_scrn_dims[0] = time_dim;
   temp_scrn_dims[1] = lat_dim;
   temp_scrn_dims[2] = lon_dim;
   stat = nc_def_var(ncid, "temp_scrn", NC_FLOAT, RANK_temp_scrn, temp_scrn_dims, &temp_scrn_id);
   check_err(stat,__LINE__,__FILE__);

   qsair_scrn_dims[0] = time_dim;
   qsair_scrn_dims[1] = lat_dim;
   qsair_scrn_dims[2] = lon_dim;
   stat = nc_def_var(ncid, "qsair_scrn", NC_FLOAT, RANK_qsair_scrn, qsair_scrn_dims, &qsair_scrn_id);
   check_err(stat,__LINE__,__FILE__);

   topog_dims[0] = time_dim;
   topog_dims[1] = lat_dim;
   topog_dims[2] = lon_dim;
   stat = nc_def_var(ncid, "topog", NC_FLOAT, RANK_topog, topog_dims, &topog_id);
   check_err(stat,__LINE__,__FILE__);

   mslp_dims[0] = time_dim;
   mslp_dims[1] = lat_dim;
   mslp_dims[2] = lon_dim;
   stat = nc_def_var(ncid, "mslp", NC_FLOAT, RANK_mslp, mslp_dims, &mslp_id);
   check_err(stat,__LINE__,__FILE__);

   sfc_temp_dims[0] = time_dim;
   sfc_temp_dims[1] = lat_dim;
   sfc_temp_dims[2] = lon_dim;
   stat = nc_def_var(ncid, "sfc_temp", NC_FLOAT, RANK_sfc_temp, sfc_temp_dims, &sfc_temp_id); 
   check_err(stat,__LINE__,__FILE__);

   zonal_wnd_dims[0] = time_dim;
   zonal_wnd_dims[1] = lvl_dim;
   zonal_wnd_dims[2] = lat_dim;
   zonal_wnd_dims[3] = lon_dim;
   stat = nc_def_var(ncid, "zonal_wnd", NC_FLOAT, RANK_zonal_wnd, zonal_wnd_dims, &zonal_wnd_id);
   check_err(stat,__LINE__,__FILE__);

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

   {				/* store time */
       size_t time_start[RANK_time];
       size_t time_count[RANK_time];
       double time[TIME_LEN] = {1.};
       time_len = 1;
       time_start[0] = 0;
       time_count[0] = time_len;
       stat = nc_put_vara_double(ncid, time_id, time_start, time_count, time);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store lat */
       float lat[] = {90, 88.5, 87, 85.5, 84, 82.5, 81, 79.5, 78, 76.5, 75, 73.5, 72, 70.5, 69, 67.5, 66, 64.5, 63, 61.5, 60, 58.5, 57, 55.5, 54, 52.5, 51, 49.5, 48, 46.5, 45, 43.5, 42, 40.5, 39, 37.5, 36, 34.5, 33, 31.5, 30, 28.5, 27, 25.5, 24, 22.5, 21, 19.5, 18, 16.5, 15, 13.5, 12, 10.5, 9, 7.5, 6, 4.5, 3, 1.5, 0, -1.5, -3, -4.5, -6, -7.5, -9, -10.5, -12, -13.5, -15, -16.5, -18, -19.5, -21, -22.5, -24, -25.5, -27, -28.5, -30, -31.5, -33, -34.5, -36, -37.5, -39, -40.5, -42, -43.5, -45, -46.5, -48, -49.5, -51, -52.5, -54, -55.5, -57, -58.5, -60, -61.5, -63, -64.5, -66, -67.5, -69, -70.5, -72, -73.5, -75, -76.5, -78, -79.5, -81, -82.5, -84, -85.5, -87, -88.5, -90};
       stat = nc_put_var_float(ncid, lat_id, lat);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store lon */
       float lon[] = {0, 1.5, 3, 4.5, 6, 7.5, 9, 10.5, 12, 13.5, 15, 16.5, 18, 19.5, 21, 22.5, 24, 25.5, 27, 28.5, 30, 31.5, 33, 34.5, 36, 37.5, 39, 40.5, 42, 43.5, 45, 46.5, 48, 49.5, 51, 52.5, 54, 55.5, 57, 58.5, 60, 61.5, 63, 64.5, 66, 67.5, 69, 70.5, 72, 73.5, 75, 76.5, 78, 79.5, 81, 82.5, 84, 85.5, 87, 88.5, 90, 91.5, 93, 94.5, 96, 97.5, 99, 100.5, 102, 103.5, 105, 106.5, 108, 109.5, 111, 112.5, 114, 115.5, 117, 118.5, 120, 121.5, 123, 124.5, 126, 127.5, 129, 130.5, 132, 133.5, 135, 136.5, 138, 139.5, 141, 142.5, 144, 145.5, 147, 148.5, 150, 151.5, 153, 154.5, 156, 157.5, 159, 160.5, 162, 163.5, 165, 166.5, 168, 169.5, 171, 172.5, 174, 175.5, 177, 178.5, 180, 181.5, 183, 184.5, 186, 187.5, 189, 190.5, 192, 193.5, 195, 196.5, 198, 199.5, 201, 202.5, 204, 205.5, 207, 208.5, 210, 211.5, 213, 214.5, 216, 217.5, 219, 220.5, 222, 223.5, 225, 226.5, 228, 229.5, 231, 232.5, 234, 235.5, 237, 238.5, 240, 241.5, 243, 244.5, 246, 247.5, 249, 250.5, 252, 253.5, 255, 256.5, 258, 259.5, 261, 262.5, 264, 265.5, 267, 268.5, 270, 271.5, 273, 274.5, 276, 277.5, 279, 280.5, 282, 283.5, 285, 286.5, 288, 289.5, 291, 292.5, 294, 295.5, 297, 298.5, 300, 301.5, 303, 304.5, 306, 307.5, 309, 310.5, 312, 313.5, 315, 316.5, 318, 319.5, 321, 322.5, 324, 325.5, 327, 328.5, 330, 331.5, 333, 334.5, 336, 337.5, 339, 340.5, 342, 343.5, 345, 346.5, 348, 349.5, 351, 352.5, 354, 355.5, 357, 358.5};
       stat = nc_put_var_float(ncid, lon_id, lon);
       check_err(stat,__LINE__,__FILE__);
   }

   {				/* store lvl */
       float lvl[] = {1000, 995, 990, 985, 975, 950, 925, 900, 875, 850, 800, 750, 700, 600, 500, 450, 400, 350, 300, 275, 250, 225, 200, 175, 150, 100, 70, 50, 30, 20, 10};
       stat = nc_put_var_float(ncid, lvl_id, lvl);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store sfc_pres */
       size_t sfc_pres_start[RANK_sfc_pres];
       size_t sfc_pres_count[RANK_sfc_pres];
       float sfc_pres[LON_LEN*LAT_LEN];
       
       for(ii = 0; ii < LAT_LEN * LON_LEN; ii++) {
	   sfc_pres[ii] = 6;
       }
       sfc_pres_start[0] = 0;
       sfc_pres_start[1] = 0;
       sfc_pres_start[2] = 0;
       sfc_pres_count[0] = time_len;
       sfc_pres_count[1] = lat_len;
       sfc_pres_count[2] = lon_len;
       stat = nc_put_vara_float(ncid, sfc_pres_id, sfc_pres_start, sfc_pres_count, sfc_pres);
       check_err(stat,__LINE__,__FILE__);
   }

   {				/* store temp_scrn */
       size_t temp_scrn_start[RANK_temp_scrn];
       size_t temp_scrn_count[RANK_temp_scrn];
       float temp_scrn[LON_LEN*LAT_LEN];
       
       for(ii = 0; ii < LAT_LEN * LON_LEN; ii++) {
	   temp_scrn[ii] = 11;
       }
       temp_scrn_start[0] = 0;
       temp_scrn_start[1] = 0;
       temp_scrn_start[2] = 0;
       temp_scrn_count[0] = time_len;
       temp_scrn_count[1] = lat_len;
       temp_scrn_count[2] = lon_len;
       stat = nc_put_vara_float(ncid, temp_scrn_id, temp_scrn_start, temp_scrn_count, temp_scrn);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store qsair_scrn */
       size_t qsair_scrn_start[RANK_qsair_scrn];
       size_t qsair_scrn_count[RANK_qsair_scrn];
       float qsair_scrn[LON_LEN*LAT_LEN];
       
       for(ii = 0; ii < LAT_LEN * LON_LEN; ii++) {
	   qsair_scrn[ii] = 22;
       }
       qsair_scrn_start[0] = 0;
       qsair_scrn_start[1] = 0;
       qsair_scrn_start[2] = 0;
       qsair_scrn_count[0] = time_len;
       qsair_scrn_count[1] = lat_len;
       qsair_scrn_count[2] = lon_len;
       stat = nc_put_vara_float(ncid, qsair_scrn_id, qsair_scrn_start, qsair_scrn_count, qsair_scrn);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store topog */
       size_t topog_start[RANK_topog];
       size_t topog_count[RANK_topog];
       float topog[LON_LEN*LAT_LEN];
       
       for(ii = 0; ii < LAT_LEN * LON_LEN; ii++) {
	   topog[ii] = 33;
       }
       topog_start[0] = 0;
       topog_start[1] = 0;
       topog_start[2] = 0;
       topog_count[0] = time_len;
       topog_count[1] = lat_len;
       topog_count[2] = lon_len;
       stat = nc_put_vara_float(ncid, topog_id, topog_start, topog_count, topog);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store mslp */
       size_t mslp_start[RANK_mslp];
       size_t mslp_count[RANK_mslp];
       float mslp[LON_LEN*LAT_LEN];
       
       for(ii = 0; ii < LAT_LEN * LON_LEN; ii++) {
	   mslp[ii] = 44;
       }
       mslp_start[0] = 0;
       mslp_start[1] = 0;
       mslp_start[2] = 0;
       mslp_count[0] = time_len;
       mslp_count[1] = lat_len;
       mslp_count[2] = lon_len;
       stat = nc_put_vara_float(ncid, mslp_id, mslp_start, mslp_count, mslp);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {				/* store sfc_temp */
       size_t sfc_temp_start[RANK_sfc_temp];
       size_t sfc_temp_count[RANK_sfc_temp];
       float sfc_temp[LON_LEN*LAT_LEN];
       
       for(ii = 0; ii < LAT_LEN * LON_LEN; ii++) {
	   sfc_temp[ii] = 55;
       }
       sfc_temp_start[0] = 0;
       sfc_temp_start[1] = 0;
       sfc_temp_start[2] = 0;
       sfc_temp_count[0] = time_len;
       sfc_temp_count[1] = lat_len;
       sfc_temp_count[2] = lon_len;
       stat = nc_put_vara_float(ncid, sfc_temp_id, sfc_temp_start, sfc_temp_count, sfc_temp);
       check_err(stat,__LINE__,__FILE__);
   }
   
   {		      /* store zonal_wnd */
       /* Bug exposed when written in reverse order. */
       for(i = LVL_LEN - 1; i>=0; i--)
       /* for(i = 0; i < LVL_LEN; i++) */
       {
	   int izw;
	   for(izw = 0; izw < TIME_LEN * LAT_LEN * LON_LEN; izw++) {
	       zonal_wnd[izw] = 100 + i;
	   }
	   zonal_wnd_start[0] = 0;
	   zonal_wnd_start[1] = i;
	   zonal_wnd_start[2] = 0;
	   zonal_wnd_start[3] = 0;
	   zonal_wnd_count[0] = time_len;
	   zonal_wnd_count[1] = 1;
	   zonal_wnd_count[2] = lat_len;
	   zonal_wnd_count[3] = lon_len;
	   stat = nc_put_vara_float(ncid, zonal_wnd_id, zonal_wnd_start, zonal_wnd_count, zonal_wnd);
	   check_err(stat,__LINE__,__FILE__);
       }
   }
   stat = nc_close(ncid);
   check_err(stat,__LINE__,__FILE__);
   return 0;
}
예제 #22
0
int
create_sample_file(char *file_name, int ndims, int *dim_len, 
		   int num_vars, int mode, int num_recs)
{
   int ncid, dimids[MAX_DIMS], *varids;
   char varname[NC_MAX_NAME + 1];
   char dim_name[NC_MAX_NAME + 1];
   float *data_out;
   size_t start[MAX_DIMS], count[MAX_DIMS];
   int slab_nelems;
   int i, d, ret;

   if (ndims != MAX_DIMS && ndims != MAX_DIMS - 1) ERR_RET;

   /* Create a file. */
   ret = nc_create(file_name, NC_NOCLOBBER|mode, &ncid);
   if (ret == NC_EEXIST)
      return NC_NOERR;
   else if (ret)
      ERR_RET;

   /* Initialize sample data. Slab of data will be full extent of last
    * two dimensions. */
   slab_nelems = dim_len[ndims - 1] * dim_len[ndims - 2];
   if (!(data_out = malloc(slab_nelems * sizeof(float)))) ERR_RET;
   for (i = 0; i < slab_nelems; i++)
      data_out[i] = 42.42 + i;

   /* Create the dimensions. */
   for (d = 0; d < ndims; d++)
   {
      sprintf(dim_name, "dim_%d", d);
      if (nc_def_dim(ncid, dim_name, dim_len[d], &dimids[d])) ERR_RET;
   }

   /* Define num_vars variables. */
   if (!(varids = malloc(num_vars * sizeof(int)))) ERR_RET;
   for (i = 0; i < num_vars; i++)
   {
      sprintf(varname, "a_%d", i);
      if (nc_def_var(ncid, varname, NC_FLOAT, ndims, dimids, 
		     &varids[i])) ERR_RET;
   }
   
   /* Enddef required for classic files. */
   if (nc_enddef(ncid)) ERR;

   /* Set up start/count to write slabs of data. */
   for (d = 0; d < ndims; d++)
   {
      if (d < ndims - 2)
	 count[d] = 1;
      else
      {
	 start[d] = 0;
	 count[d] = dim_len[d];
      }
   }

   /* Now write some data to the vars in slabs. */
   for (i = 0; i < num_vars; i++)
   {
      if (ndims == MAX_DIMS)
      {
	 for (start[0] = 0; start[0] < (dim_len[0] ? dim_len[0] : num_recs); start[0]++)
	    for (start[1] = 0; start[1] < dim_len[1]; start[1]++)
	       if (nc_put_vara_float(ncid, varids[i], start, count, 
				     data_out)) ERR_RET;
      }
      else
      {
	 for (start[0] = 0; start[0] < (dim_len[0] ? dim_len[0] : num_recs); start[0]++)
	    if (nc_put_vara_float(ncid, varids[i], start, count, 
				  data_out)) ERR_RET;
      }
   }

   /* Free data and close file. */
   free(data_out);
   free(varids);
   if (nc_close(ncid)) ERR_RET;

   return NC_NOERR;
}