//TODO optimize this thing
void writeResultsFile(string dataFileName, string yDimension, vector<double> * pValues)
{
    NcFile file(dataFileName.c_str(), NcFile::ReadOnly);
    NcVar *geneNames = file.get_var("gene");
    int dataYsize = file.get_dim(yDimension.c_str())->size();

    FILE * pFile;
    pFile = fopen ("results.txt","w");

    cout << "Writing results to file.." << endl;

    int percentage = dataYsize / 10;
    int percentageCount = 10;
    for(int i = 0; i < dataYsize; i++){
        char * c = geneNames->as_string(i*28);
        std::string str;
        if(pValues->at(i) > 0.05){
            std::ostringstream strs;
            strs << pValues->at(i);
            str = strs.str();
        }else{
            str = "NA";
        }
        fprintf (pFile, "%-20s-%20s", c, str.c_str());
        fprintf (pFile, "\n");
        if(i == percentage)
        {
            cout <<  percentageCount << "% complete" << endl;
            percentageCount += 10;
            percentage += dataYsize / 10;
        }
        delete c;
    }
    fclose(pFile);
}
Esempio n. 2
0
FieldPtr FileArome::getFieldCore(std::string iVariable, int iTime) const {
   // Not cached, retrieve data
   NcVar* var = getVar(iVariable);
   int nLat  = mNLat;
   int nLon  = mNLon;

   int numDims = var->num_dims();

   long* count;
   long totalCount = nLat*nLon;
   if(numDims == 4) {
      // Variable has a surface dimension
      count = new long[4];
      count[0] = 1;
      count[1] = 1;
      count[2] = nLat;
      count[3] = nLon;
      var->set_cur(iTime, 0, 0, 0);
   }
   else if(numDims == 3) {
      count = new long[3];
      count[0] = 1;
      count[1] = nLat;
      count[2] = nLon;
      var->set_cur(iTime, 0, 0);
   }
   else {
      std::stringstream ss;
      ss << "Cannot read variable '" << iVariable << "' from '" << getFilename() << "'";
      Util::error(ss.str());
   }
   float* values = new float[nLat*nLon];
   var->get(values, count);
   float MV = getMissingValue(var);

   float offset = getOffset(var);
   float scale = getScale(var);
   int index = 0;
   FieldPtr field = getEmptyField();
   for(int lat = 0; lat < nLat; lat++) {
      for(int lon = 0; lon < nLon; lon++) {
         float value = values[index];
         assert(index < totalCount);
         if(value == MV) {
            // Field has missing value indicator and the value is missing
            // Save values using our own internal missing value indicator
            value = Util::MV;
         }
         else {
            value = scale*values[index] + offset;
         }
         (*field)(lat,lon,0) = value;
         index++;
      }
   }
   delete[] values;
   delete[] count;
   return field;
}
Esempio n. 3
0
int NetcdfSource::readScalar(double *v, const QString& field)
{
  // TODO error handling
  QByteArray bytes = field.toLatin1();
  NcVar *var = _ncfile->get_var(bytes.constData());  // var is owned by _ncfile
  var->get(v);
  return 1;
}
Esempio n. 4
0
void NetCdfConfigureDialog::setVariableSelect()
{
    for (int i=0; i<(_currentFile->num_vars()); i++)
    {
        NcVar *focusedVar = _currentFile->get_var(i);
        if (focusedVar->num_dims() > 0) comboBoxVariable->addItem(focusedVar->name());
    }
}
Esempio n. 5
0
 Var( const NcVar* var ):
     m_var( var )
 {
     const int ndims = m_var->num_dims();
     for ( int i = 0; i < ndims; i++ )
     {
         m_dims.push_back( new Dim( m_var->get_dim(i) ) );
     }
 }
Esempio n. 6
0
std::vector<T> read_vector(NcFile &nc, std::string const &var_name)
{
	// Read points vector
	NcVar *vpoints = nc.get_var(var_name.c_str());
	long npoints = vpoints->get_dim(0)->size();
	std::vector<T> points(npoints);
	vpoints->get(&points[0], npoints);
	return points;
}
Esempio n. 7
0
void DumpableNcFile::dumpdata( )
{
    NcVar* vp;
    for (int n = 0; vp = get_var(n); n++) {
	cout << " " << vp->name() << " = ";
	NcValues* vals = vp->values();
	cout << *vals << " ;" << endl ;
	delete vals;
    }
}
Esempio n. 8
0
bool ReadAstro::open(const char *path)
{
    assert(!m_ncfile);
    m_ncfile = new NcFile(path, NcFile::ReadOnly);
    if (!m_ncfile->is_valid())
    {
        close();
        sendError("failed to open NetCDF file %s", path);
        return false;
    }

    if (m_ncfile->get_format() == NcFile::BadFormat)
    {
        close();
        sendError("bad NetCDF file");
        return false;
    }

    fprintf(stderr, "dims=%d, vars=%d, attrs=%d\n",
            m_ncfile->num_dims(), m_ncfile->num_vars(), m_ncfile->num_atts());

    for (int i = 0; i < m_ncfile->num_dims(); ++i)
    {
        fprintf(stderr, "%s: %ld\n",
                m_ncfile->get_dim(i)->name(),
                m_ncfile->get_dim(i)->size());
    }

    for (int i = 0; i < m_ncfile->num_vars(); ++i)
    {
        fprintf(stderr, "%s: dims=%d atts=%d vals=%ld type=%d\n",
                m_ncfile->get_var(i)->name(),
                m_ncfile->get_var(i)->num_dims(),
                m_ncfile->get_var(i)->num_atts(),
                m_ncfile->get_var(i)->num_vals(),
                m_ncfile->get_var(i)->type());
        //int dims = m_ncfile->get_var(i)->num_dims();
        NcVar *var = m_ncfile->get_var(i);
        for (int j = 0; j < var->num_dims(); ++j)
        {
            fprintf(stderr, "   %s: %ld edge=%ld\n",
                    var->get_dim(j)->name(),
                    var->get_dim(j)->size(),
                    var->edges()[j]);
        }
    }

    for (int i = 0; i < m_ncfile->num_atts(); ++i)
    {
        fprintf(stderr, "%s\n", m_ncfile->get_att(i)->name());
    }

    return true;
}
Esempio n. 9
0
vector<string>
eavlNetCDFImporter::GetFieldList(const string &mesh)
{
    vector<string> retval;
    for (unsigned int v=0; v<vars.size(); v++)
    {
        NcVar *var = vars[v];
        retval.push_back(var->name());
    }
    return retval;
}
Esempio n. 10
0
int NetcdfSource::samplesPerFrame(const QString& field) {
  if (field.toLower() == "index") {
    return 1;
  }
  QByteArray bytes = field.toLatin1();
  NcVar *var = _ncfile->get_var(bytes.constData());
  if (!var) {
    return 0;
  }
  return var->rec_size();
}
Esempio n. 11
0
int NetCdfConfigureDialog::getTimeStep()
{
    NcVar* timeVar = _currentFile->get_var(comboBoxDim2->currentIndex());

    const double datesToMinutes = convertDateToMinutes(_currentInitialDateTime,dateTimeEditDim3->date(),dateTimeEditDim3->time());

    double timeArray[1] = {datesToMinutes};
    double currentTime = timeVar->get_index(timeArray);
    if (currentTime < 0) currentTime=0; //if the value isn't found in the array, set it to 0 as default...
    return currentTime;
}
Esempio n. 12
0
void dumpatts(NcVar& var)
{
    NcToken vname = var.name();
    NcAtt* ap;
    for(int n = 0; ap = var.get_att(n); n++) {
	cout << "\t\t" << vname << ":" << ap->name() << " = " ;
	NcValues* vals = ap->values();
	cout << *vals << " ;" << endl ;
	delete ap;
	delete vals;
    }
}
int main(int argc, char *argv[])
{
    NcFile at(atpath, NcFile::ReadOnly);
    if(!at.is_valid() || at.num_dims() != 3 || at.num_vars() != 4) {
        fprintf(stderr, "failed reading file: %s\n", atpath);
        return 1;
    }

    NcVar* data = at.get_var("rhum");
    if(!data->is_valid() || data->num_dims() != 3) {
        fprintf(stderr, "rhum has incorrect dimensions");
        return 1;
    }

    NcDim* time = data->get_dim(0);
    int timecnt = time->size();
    float  *rhumd = new float[timecnt*LATS*LONS];
    data->get(rhumd, timecnt, LATS, LONS);

    float  rhumdmon[12][LATS][LONS];
    for(int i = 0; i<LATS; i++)
        for(int j = 0; j<LONS; j++) {
            float rhumdmoncnt[12];
            for(int k = 0; k<12; k++) {
                rhumdmon[k][i][j] = 0;
                rhumdmoncnt[k] = 0;
            }
            for(int k = 0; k<timecnt; k++) {
                double v = rhumd[(k*LATS+i)*LONS+j]*.1 + 3276.5;
                if(v >= 0 && v <= 100) {
                    rhumdmon[k%12][i][j] += v;
                    rhumdmoncnt[k%12]++;
                }
            }
            for(int k = 0; k<12; k++)
                rhumdmon[k][i][j] /= rhumdmoncnt[k];
        }
    delete [] rhumd;

    /* use a single byte instead of 2 to save memory,
       resolution of 1/5th of a mm/day resolution */
    uint8_t rhumbyte[12][LATS][LONS];
    for(int i = 0; i<12; i++)
        for(int j = 0; j<LATS; j++)
            for(int k = 0; k<LONS; k++)
                if(isnan(rhumdmon[i][j][k]) || fabs(rhumdmon[i][j][k]) > 100)
                    rhumbyte[i][j][k] = 255;
                else
                    rhumbyte[i][j][k] = rhumdmon[i][j][k]*2.0;
    
    fwrite(rhumbyte, sizeof rhumbyte, 1, stdout);
    return 0;
}
Esempio n. 14
0
void ConstantSet::read_from_netcdf(NcFile &nc, std::string const &vname)
{
	NcVar *ncvar = giss::get_var_safe(nc, vname.c_str(), true);
	if (!ncvar) {
		fprintf(stderr, "ConstantSet::read_from_netcdf() cannot find variable %s\n", vname.c_str());
		throw std::exception();
	}
	int n = ncvar->num_atts();

	// Read through the attributes, getting units and names separately
	std::map<std::string, std::string> units;
	std::map<std::string, double> consts;
	std::map<std::string, std::string> descriptions;
	for (int i=0; i<n; ++i) {
		auto att = giss::get_att(ncvar, i);
		std::string att_name(att->name());
		if (giss::ends_with(att_name, "_description")) {
			descriptions.insert(std::make_pair(
				att_name.substr(0, att_name.size() - std::strlen("_description")),
				std::string(att->as_string(0))));
		} else if (giss::ends_with(att_name, "_units")) {
			units.insert(std::make_pair(
				att_name.substr(0, att_name.size() - std::strlen("_units")),
				std::string(att->as_string(0))));
		} else {
			consts.insert(std::make_pair(
				att_name, att->as_double(0)));
		}
	}

	// Now go through them again, matching up constants and units
	for (auto ii = consts.begin(); ii != consts.end(); ++ii) {
		std::string const &name = ii->first;
		double const val = ii->second;

		auto ui = units.find(name);
		if (ui == units.end()) {
			fprintf(stderr, "Could not find _units attribute for %s\n", name.c_str());
		}

		auto di = descriptions.find(name);
		if (di == descriptions.end()) {
			fprintf(stderr, "Could not find _description attribute for %s\n", name.c_str());
		}

		std::string const &u = units.find(name)->second;
		std::string const &d = descriptions.find(name)->second;

		set(name, val, u, d);
	}
}
Esempio n. 15
0
int 
main(void)
@{
   // This is the data array we will write. It will just be filled
   // with a progression of numbers for this example.
   int dataOut[NX][NY];
  
   // Create some pretend data. If this wasn't an example program, we
   // would have some real data to write, for example, model output.
   for(int i = 0; i < NX; i++) 
      for(int j = 0; j < NY; j++)
	 dataOut[i][j] = i * NY + j;

   // Create the file. The Replace parameter tells netCDF to overwrite
   // this file, if it already exists.
   NcFile dataFile("simple_xy.nc", NcFile::Replace);

   // You should always check whether a netCDF file creation or open
   // constructor succeeded.
   if (!dataFile.is_valid())
   @{
      cout << "Couldn't open file!\n";
      return NC_ERR;
   @}
  
   // For other method calls, the default behavior of the C++ API is
   // to exit with a message if there is an error.  If that behavior
   // is OK, there is no need to check return values in simple cases
   // like the following.

   // When we create netCDF dimensions, we get back a pointer to an
   // NcDim for each one.
   NcDim* xDim = dataFile.add_dim("x", NX);
   NcDim* yDim = dataFile.add_dim("y", NY);
  
   // Define a netCDF variable. The type of the variable in this case
   // is ncInt (32-bit integer).
   NcVar *data = dataFile.add_var("data", ncInt, xDim, yDim);
     
   // Write the pretend data to the file. Although netCDF supports
   // reading and writing subsets of data, in this case we write all
   // the data in one operation.
   data->put(&dataOut[0][0], NX, NY);

   // The file will be automatically close when the NcFile object goes
   // out of scope. This frees up any internal netCDF resources
   // associated with the file, and flushes any buffers.
   cout << "*** SUCCESS writing example file simple_xy.nc!" << endl;

   return 0;
@}
Esempio n. 16
0
void LoadMetaDataFile(
	const std::string & strInputMeta,
	DataMatrix3D<int> & dataGLLNodes,
	DataMatrix3D<double> & dataGLLJacobian
) {
	NcFile ncMeta(strInputMeta.c_str(), NcFile::ReadOnly);

	NcDim * dimNp = ncMeta.get_dim("np");
	if (dimNp == NULL) {
		_EXCEPTIONT("Dimension \"np\" missing from metadata file");
	}

	NcDim * dimNelem = ncMeta.get_dim("nelem");
	if (dimNelem == NULL) {
		_EXCEPTIONT("Dimension \"nelem\" missing from metadata file");
	}

	NcVar * varGLLNodes = ncMeta.get_var("GLLnodes");
	if (dimNelem == NULL) {
		_EXCEPTIONT("Variable \"GLLnodes\" missing from metadata file");
	}

	NcVar * varGLLJacobian = ncMeta.get_var("J");
	if (dimNelem == NULL) {
		_EXCEPTIONT("Variable \"J\" missing from metadata file");
	}

	int nP = dimNp->size();
	int nElem = dimNelem->size();

	DataMatrix3D<int> dataGLLNodes_tmp;
	DataMatrix3D<double> dataGLLJacobian_tmp;
 
	dataGLLNodes.Initialize(nP, nP, nElem);
	dataGLLJacobian.Initialize(nP, nP, nElem);
	dataGLLNodes_tmp.Initialize(nP, nP, nElem);
	dataGLLJacobian_tmp.Initialize(nP, nP, nElem);
 
	varGLLNodes->get(&(dataGLLNodes_tmp[0][0][0]), nP, nP, nElem);
 	varGLLJacobian->get(&(dataGLLJacobian_tmp[0][0][0]), nP, nP, nElem);

	for (int i = 0; i < nP; i++) {
		for (int j = 0; j < nP; j++) {
			for (int k = 0; k < nElem; k++) {
				dataGLLNodes[i][j][k] = dataGLLNodes_tmp[j][i][k];
				dataGLLJacobian[i][j][k] = dataGLLJacobian_tmp[j][i][k];
			}
		}
	}
}
Esempio n. 17
0
//YUAN: recid - the order (from ZERO) in the .nc file, chtid - the cohort id
int SiteinInputer::getRecID(const int &siteid){
	NcError err(NcError::silent_nonfatal);

	NcFile siteFile(siteinfname.c_str(), NcFile::ReadOnly);
 	NcVar* siteidV = siteFile.get_var("CHTID");

 	int id = -1;
	for (int i=0; i<(int)siteidV->num_vals(); i++){
		siteidV->set_cur(i);
		siteidV->get(&id, 1);
		if(id==siteid) return i;
	}
	return -1;
}
Esempio n. 18
0
FileArome::FileArome(std::string iFilename, bool iReadOnly) : FileNetcdf(iFilename, iReadOnly) {
   // Set dimensions
   NcDim* dTime = getDim("time");
   NcDim* dLon  = getDim("x");
   NcDim* dLat  = getDim("y");
   mNTime = dTime->size();
   mNLat  = dLat->size();
   mNLon  = dLon->size();
   mNEns  = 1;

   mLats = getLatLonVariable("latitude");
   mLons = getLatLonVariable("longitude");
   if(hasVariableCore("surface_geopotential")) {
      FieldPtr elevField = getFieldCore("surface_geopotential", 0);
      mElevs.resize(getNumLat());
      for(int i = 0; i < getNumLat(); i++) {
         mElevs[i].resize(getNumLon());
         for(int j = 0; j < getNumLon(); j++) {
            float value = (*elevField)(i,j,0) / 9.81;
            mElevs[i][j] = value;
         }
      }
      std::cout << "Deriving altitude from geopotential height in " << getFilename() << std::endl;
   }
   else {
      mElevs = getLatLonVariable("altitude");
   }

   if(hasVar("time")) {
      NcVar* vTime = getVar("time");
      double* times = new double[mNTime];
      vTime->get(times , mNTime);
      setTimes(std::vector<double>(times, times+mNTime));
      delete[] times;
   }
   else {
      std::vector<double> times;
      times.resize(getNumTime(), Util::MV);
      setTimes(times);
   }

   if(hasVar("forecast_reference_time")) {
      NcVar* vReferenceTime = getVar("forecast_reference_time");
      double referenceTime = getReferenceTime();
      vReferenceTime->get(&referenceTime, 1);
      setReferenceTime(referenceTime);
   }

   Util::status( "File '" + iFilename + " 'has dimensions " + getDimenionString());
}
Esempio n. 19
0
bool NetcdfSource::initFile() {
  _ncfile = new NcFile(_filename.toUtf8().data(), NcFile::ReadOnly);
  if (!_ncfile->is_valid()) {
      qDebug() << _filename << ": failed to open in initFile()" << endl;
      return false;
    }

  KST_DBG qDebug() << _filename << ": building field list" << endl;
  _fieldList.clear();
  _fieldList += "INDEX";

  int nb_vars = _ncfile->num_vars();
  KST_DBG qDebug() << nb_vars << " vars found in total" << endl;

  _maxFrameCount = 0;

  for (int i = 0; i < nb_vars; i++) {
    NcVar *var = _ncfile->get_var(i);
    if (var->num_dims() == 0) {
      _scalarList += var->name();
    } else if (var->num_dims() == 1) {
      _fieldList += var->name();
      int fc = var->num_vals() / var->rec_size();
      _maxFrameCount = qMax(_maxFrameCount, fc);
      _frameCounts[var->name()] = fc;
    } else if (var->num_dims() == 2) {
      _matrixList += var->name();
    }
  }

  // Get strings
  int globalAttributesNb = _ncfile->num_atts();
  for (int i = 0; i < globalAttributesNb; ++i) {
    // Get only first value, should be enough for a start especially as strings are complete
    NcAtt *att = _ncfile->get_att(i);
    if (att) {
      QString attrName = QString(att->name());
      char *attString = att->as_string(0);
      QString attrValue = QString(att->as_string(0));
      delete[] attString;
      //TODO port
      //KstString *ms = new KstString(KstObjectTag(attrName, tag()), this, attrValue);
      _stringList += attrName;
    }
    delete att;
  }

  // TODO update(); // necessary?  slows down initial loading
  return true;
}
Esempio n. 20
0
int main()
{
  // This is the data array we will write. It will just be filled
  // with a progression of numbers for this example.
  int dataOut[NX][NY];
  
  // Create some pretend data. If this wasn't an example program, we
  // would have some real data to write, for example, model output.
  for(int i = 0; i < NX; i++)
    for(int j = 0; j < NY; j++)
      dataOut[i][j] = i * NY + j;
  
  // The default behavior of the C++ API is to throw an exception i
  // an error occurs. A try catch block is necessary.
   
  try
    {  
      // Create the file. The Replace parameter tells netCDF to overwrite
      // this file, if it already exists.
      NcFile dataFile("simple_xy.nc", NcFile::replace);
      
      // Create netCDF dimensions
      NcDim xDim = dataFile.addDim("x", NX);
      NcDim yDim = dataFile.addDim("y", NY);
      
      // Define the variable. The type of the variable in this case is
      // ncInt (32-bit integer).
      vector<NcDim> dims;
      dims.push_back(xDim);
      dims.push_back(yDim);
      NcVar data = dataFile.addVar("data", ncInt, dims);
   
      // Write the data to the file. Although netCDF supports
      // reading and writing subsets of data, in this case we write all
      // the data in one operation.
      data.putVar(dataOut);
      
      // The file will be automatically close when the NcFile object goes
      // out of scope. This frees up any internal netCDF resources
      // associated with the file, and flushes any buffers.
      
      //cout << "*** SUCCESS writing example file simple_xy.nc!" << endl;
      return 0; 
    }
  catch(NcException& e)
    {e.what();
      return NC_ERR;
    }
}
Esempio n. 21
0
QMap<QString, QString> DataInterfaceNetCdfVector::metaStrings(const QString& field)
{
  QMap<QString, QString> fieldStrings;
  QString tmpString;
  NcVar *var = netcdf._ncfile->get_var(field.toLatin1().constData());
  for (int i=0; i<var->num_atts(); ++i) {
    NcAtt *att = var->get_att(i);
    // Only handle char/unspecified attributes as fieldStrings, the others as fieldScalars
    if (att->type() == NC_CHAR || att->type() == NC_UNSPECIFIED) {
      fieldStrings[att->name()] = QString(att->values()->as_string(0));
    }
    // qDebug() << att->name() << ": " << att->values()->num() << endl;
  }
  return fieldStrings;
}
Esempio n. 22
0
void Regioner::createCohorList4Run(){
	// read in a list of cohorts to run

	//netcdf error
	NcError err(NcError::silent_nonfatal);

	//open file and check if valid
	string filename = md.runchtfile;
	NcFile runFile(filename.c_str(), NcFile::ReadOnly);
 	if(!runFile.is_valid()){
 		string msg = filename+" is not valid";
 		char* msgc = const_cast< char* > ( msg.c_str());
 		throw Exception(msgc, I_NCFILE_NOT_EXIST);
 	}
 	
 	NcDim* chtD = runFile.get_dim("CHTID");
 	if(!chtD->is_valid()){
 		string msg="CHT Dimension is not valid in createCohortList4Run";
 		char* msgc = const_cast<char*> (msg.c_str());
 		throw Exception(msgc, I_NCDIM_NOT_EXIST);
 	}
 	
 	NcVar* chtV = runFile.get_var("CHTID");
 	if(chtV==NULL){
 		string msg="Cannot get CHTID in createCohortList4Run ";
 		char* msgc = const_cast<char*> (msg.c_str());
 		throw Exception(msgc, I_NCVAR_NOT_EXIST);
 	}

 	int numcht = chtD->size();
 	
	int chtid  = -1;
	int chtid0 = -1;
	int chtidx = -1;
	for (int i=0; i<numcht; i++){
		chtV->set_cur(i);
   		chtV->get(&chtid, 1);
   		runchtlist.push_back(chtid);
	   	
	   	if (i==0) chtid0=chtid;
	   	if (i==numcht-1) chtidx=chtid;
   	}

	cout <<md.casename << ": " <<numcht <<"  cohorts to be run @" <<md.runstages<< "\n";
	cout <<"   from:  " <<chtid0<<"  to:  " <<chtidx <<"\n";
   
};
Esempio n. 23
0
int main(void)
{
   try
   {
   // This is the array we will read.
   int dataIn[NX][NY]; 

   // Open the file. The ReadOnly parameter tells netCDF we want
   // read-only access to the file.
   NcFile dataFile("simple_xy.nc", NcFile::ReadOnly);

   // You should always check whether a netCDF file open or creation
   // constructor succeeded.
//    if (!dataFile.is_valid())
//    {
//       cout << "Couldn't open file!\n";
//       return NC_ERR;
//    }
  
   // For other method calls, the default behavior of the C++ API is
   // to exit with a message if there is an error.  If that behavior
   // is OK, there is no need to check return values in simple cases
   // like the following.
      
   // Retrieve the variable named "data"
   NcVar *data = dataFile.getVar("data");

   // Read all the values from the "data" variable into memory. 
   data->get(&dataIn[0][0], NX, NY);

   // Check the values. 
   for (int i = 0; i < NX; i++)
      for (int j = 0; j < NY; j++)
	 if (dataIn[i][j] != i * NY + j)
	    return NC_ERR;
    
   // The netCDF file is automatically closed by the NcFile destructor
   cout << "*** SUCCESS reading example file simple_xy.nc!" << endl;

   return 0;
   }catch(NcException e)
   {
      e.what();
      cout<<"FAILURE*************************************"<<endl;
      return 1;
   }
}
Esempio n. 24
0
void ConstantSet::netcdf_define(NcFile &nc, std::string const &vname)
{
	// Create the variable to store our constants
	NcVar *ncvar = giss::get_var_safe(nc, vname.c_str(), false);
	if (!ncvar) {
		auto oneDim = giss::get_or_add_dim(nc, "one", 1);
		ncvar = nc.add_var(vname.c_str(), ncDouble, oneDim);
	}

	// Store the constants as attributes
	for (int i=0; i<fields.size_withunit(); ++i) {
		CoupledField const &field(fields.field(i));
		ncvar->add_att(field.name.c_str(), vals[i]);
		ncvar->add_att((field.name + "_units").c_str(), field.units.c_str());
		ncvar->add_att((field.name + "_description").c_str(), field.description.c_str());
	}
}
Esempio n. 25
0
void NetCdfConfigureDialog::getDimEdges(int dimId, unsigned &size, double &firstValue, double &lastValue)
{
    if ((_currentFile->get_var(_currentVar->get_dim(dimId)->name())) != NULL)
    {
        NcVar *tmpVarOfDim = _currentFile->get_var(_currentVar->get_dim(dimId)->name());
        if ((tmpVarOfDim->num_dims()) == 1)
        {
            int sizeOfDim = tmpVarOfDim->get_dim(0)->size();
            size = sizeOfDim;
            double arrayOfDimStart[1] = {0};
            size_t edgeOfArray[1] = {1};
            long edgeOrigin[1] = {0};
            tmpVarOfDim->set_cur(edgeOrigin);
            tmpVarOfDim->get(arrayOfDimStart,edgeOfArray);
            firstValue = arrayOfDimStart[0];
            double arrayOfDimEnd[1] = {0};
            edgeOrigin[0] = sizeOfDim - 1;
            tmpVarOfDim->set_cur(edgeOrigin);
            tmpVarOfDim->get(arrayOfDimEnd,edgeOfArray);
            lastValue = arrayOfDimEnd[0];
        }
    } else {
        size = 0;
        firstValue = 0;
        lastValue = 0;
    }
}
Esempio n. 26
0
template<class T> static bool load_nc_array(const NcFile& ncf, const string& name, vector<T>& dest, bool required = true, int offset = 0, int count = -1)
{
	NcVar *v = load_nc_variable(ncf, name.c_str(), required);
	if (v)
	{
		vector<long> offsets = list_of(offset).repeat(v->num_dims()-1, 0);
		v->set_cur(&offsets.front());
		vector<long> counts (v->num_dims());
		long* shape = v->edges();
		transform(shape, shape + v->num_dims(), offsets.begin(), counts.begin(), minus<long>());
		delete shape;
		if (count > 0)
		{
			counts[0] = count;
		}
		dest.resize(product(counts));
		bool success = v->get(&dest.front(), &counts.front());
		if (!success)
		{
			dest.resize(0);
			check(!required, string("NetcdfDataset::load_nc_array<") + typeid(T).name() + "> " + name + '\n' + "failed with offset " + str(offsets) + ", counts " + str(counts));
		}
		return success;
	}
	return false;
}
Esempio n. 27
0
void DumpableNcFile::dumpvars( void )
{
    int n;
    static const char* types[] =
      {"","byte","char","short","long","float","double"};
    NcVar* vp;

    for(n = 0; vp = get_var(n); n++) {
	cout << "\t" << types[vp->type()] << " " << vp->name() ;

	if (vp->num_dims() > 0) {
	    cout << "(";
	    for (int d = 0; d < vp->num_dims(); d++) {
		NcDim* dim = vp->get_dim(d);
		cout << dim->name();
		if (d < vp->num_dims()-1)
		  cout << ", ";		  
	    }
	    cout << ")";
	}
	cout << " ;\n";
	// now dump each of this variable's attributes
	dumpatts(*vp);
    }
}
Esempio n. 28
0
int NetcdfSource::readMatrix(double *v, const QString& field) 
{
  /* For a variable from the netCDF file */
  QByteArray bytes = field.toLatin1();
  NcVar *var = _ncfile->get_var(bytes.constData());  // var is owned by _ncfile
  if (!var) {
    KST_DBG qDebug() << "Queried field " << field << " which can't be read" << endl;
    return -1;
  }

  int xSize = var->get_dim(0)->size();
  int ySize = var->get_dim(1)->size();

  var->get(v, xSize, ySize);

 
  return  xSize * ySize;
}
Esempio n. 29
0
void InputNetcdf::getLocationsCore(std::vector<Location>& iLocations) const {
   iLocations.clear();
   std::string filename = getLocationFilename();
   NcFile ncfile(filename.c_str());
   if(ncfile.is_valid()) {
      NcDim* ncLocationDim = ncfile.get_dim("Location");
      int numLocations = ncLocationDim->size();
      NcVar* ncLats = ncfile.get_var("Lat");
      NcVar* ncLons = ncfile.get_var("Lon");
      NcError q(NcError::silent_nonfatal);
      NcVar* ncElevs = ncfile.get_var("Elev");
      NcVar* ncIds  = ncfile.get_var("Id");
      bool hasId = false;
      bool hasElev = false;
      if(ncIds)
         hasId = true;
      if(ncElevs)
         hasElev = true;

      float* lats  = new float[numLocations];
      float* lons  = new float[numLocations];
      float* elevs  = new float[numLocations];
      int* ids     = new int[numLocations];
      long count[1] = {numLocations};
      ncLats->get(lats, count);
      ncLons->get(lons, count);
      if(hasId)
         ncIds->get(ids, count);
      if(hasElev)
         ncElevs->get(elevs, count);

      for(int i = 0; i < numLocations; i++) {
         int   id   = i;
         if(hasId)
            id = ids[i];
         float lat  = lats[i];
         float lon  = lons[i];
         float elev = Global::MV;
         if(hasElev)
            elev = elevs[i];
         Location loc(getName(), id, lat, lon);
         loc.setElev(elev);
         iLocations.push_back(loc);
      }
      delete[] lats;
      delete[] lons;
      delete[] elevs;
      delete[] ids;
      ncfile.close();
   }
   else {
      notifyInvalidSampleFile();
   }
}
Esempio n. 30
0
    const kvs::AnyValueArray data(
        const size_t offset = 0,
        const size_t dim1 = 1,
        const size_t dim2 = 1,
        const size_t dim3 = 1 ) const
    {
        const void* head = m_var->values()->base();
        const size_t nvalues = dim1 * dim2 * dim3;

        switch ( m_var->type() )
        {
        case ncByte:
        {
            kvs::UInt8* values = (kvs::UInt8*)( head ) + offset;
            return( kvs::AnyValueArray( this->flip( dim1, dim2, dim3, values ), nvalues ) );
        }
        case ncChar:
        {
            kvs::Int8* values = (kvs::Int8*)( head ) + offset;
            return( kvs::AnyValueArray( this->flip( dim1, dim2, dim3, values ), nvalues ) );
        }
        case ncShort:
        {
            kvs::Int16* values = (kvs::Int16*)( head ) + offset;
            return( kvs::AnyValueArray( this->flip( dim1, dim2, dim3, values ), nvalues ) );
        }
        case ncInt:
        {
            kvs::Int32* values = (kvs::Int32*)( head ) + offset;
            return( kvs::AnyValueArray( this->flip( dim1, dim2, dim3, values ), nvalues ) );
        }
        case ncFloat:
        {
            kvs::Real32* values = (kvs::Real32*)( head ) + offset;
            return( kvs::AnyValueArray( this->flip( dim1, dim2, dim3, values ), nvalues ) );
        }
        case ncDouble:
        {
            kvs::Real64* values = (kvs::Real64*)( head ) + offset;
            return( kvs::AnyValueArray( this->flip( dim1, dim2, dim3, values ), nvalues ) );
        }
        default: return( kvs::AnyValueArray() );
        }
    }