当前位置: 首页>>代码示例>>C++>>正文


C++ NcVar::get_dim方法代码示例

本文整理汇总了C++中NcVar::get_dim方法的典型用法代码示例。如果您正苦于以下问题:C++ NcVar::get_dim方法的具体用法?C++ NcVar::get_dim怎么用?C++ NcVar::get_dim使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在NcVar的用法示例。


在下文中一共展示了NcVar::get_dim方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: file

ERMsg C20thReanalysisProject::ReadData( CString filePath, CString varName, CData3Array& data)
{
	//typedef boost::multi_array<int, 2> array_type;


	ERMsg msg;
	
	NcError::set_err( NcError::silent_nonfatal );

  
	//CString filePath = m_path + "cccma_cgcm3_1-20c3m-run1-pr-1961-2000_monthly.nc";//GetFilePath(v, year, m);
	NcFile file(filePath);	//current year file

	if( !file.is_valid() )
	{
		CString err;
		err.FormatMessage(IDS_CMN_UNABLE_OPEN_READ, filePath);
		msg.ajoute(err);
		return msg;
	}

	NcVar* pVarData = file.get_var((LPCTSTR)varName);//is the varaible always at ffirst???
	
	//CString varName = pVarData->name();
	
	size_t sizeTime = pVarData->get_dim(0)->size();
	size_t sizeY = pVarData->get_dim(1)->size();
	size_t sizeX = pVarData->get_dim(2)->size();
	float offset = pVarData->get_att("add_offset")->as_float(0);
	float scaleFactor = pVarData->get_att("scale_factor")->as_float(0);
	
	boost::multi_array<short, 3> tmp(boost::extents[sizeTime][sizeY][sizeX]);

	ENSURE( pVarData->num_dims() == 3);
	
	if( pVarData->get(&(tmp[0][0][0]), sizeTime, sizeY, sizeX) )
	{
		//tmp.extens()
		//data.resize(sizeTime);
		//data.resize(boost::extents[sizeTime][sizeY][sizeX]);
		//apply offset and scale factor
		for(size_t i=0; i<tmp.size(); i++)
			for(size_t j=0; j<tmp[i].size(); j++)
				for(size_t k=0; k<tmp[i][j].size(); k++)
					data[i][j][k] = tmp[i][j][k]*scaleFactor+offset;

		file.close();
	}
	else
	{
		msg.ajoute( "Unable to get NetCDFData");
	}

	return msg;
}
开发者ID:RNCan,项目名称:WeatherBasedSimulationFramework,代码行数:55,代码来源:20thReanalysisProject.cpp

示例2: dumpvars

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);
    }
}
开发者ID:akiyoshi,项目名称:wrf-fire,代码行数:25,代码来源:nctst.cpp

示例3: getDimEdges

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;
    }
}
开发者ID:WenjieXu,项目名称:ogs,代码行数:27,代码来源:NetCdfConfigureDialog.cpp

示例4: Var

 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) ) );
     }
 }
开发者ID:zkbreeze,项目名称:OceanVis,代码行数:9,代码来源:main.cpp

示例5: points

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;
}
开发者ID:seifer08ms,项目名称:icebin,代码行数:9,代码来源:ncutil.hpp

示例6: open

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;
}
开发者ID:nixz,项目名称:covise,代码行数:54,代码来源:ReadMeteoCosmo.cpp

示例7: main

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;
}
开发者ID:AlexandreRio,项目名称:climatology_pi,代码行数:53,代码来源:genrelativehumiditydata.cpp

示例8: readMatrix

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;
}
开发者ID:,项目名称:,代码行数:18,代码来源:

示例9: NcFile

CCatchmentSetupParams::CCatchmentSetupParams(const std::string & szFilenameForCatchment)
{
	if(!boost::filesystem::exists(szFilenameForCatchment))
		throw "szFilenameForCatchment doesn't exist";
	
	pCatchmentDescriptionFile = new NcFile(szFilenameForCatchment.c_str());
	
	if (!pCatchmentDescriptionFile->is_valid())
    {
        throw "Couldn't open file!";
    }
	
	NcVar * pReachIDs = pCatchmentDescriptionFile->get_var("rchid");
	NcDim* numReaches = pReachIDs->get_dim(0);
	const int nNumReaches = numReaches->size();
	
	cout << "numReaches=" << nNumReaches << endl;
	
	//std::vector<int> aReachIDs(nNumReaches, -1);
	int anReaches[nNumReaches];
	pReachIDs->get(anReaches, nNumReaches); //This is the mapping from rchid to nrch (=idx) 
	
	for(int nrch=0;nrch<nNumReaches;nrch++)
	{
		std::cout << "Reach: " << anReaches[nrch] << std::endl;
		aSubcatchments[nrch] = new CSubcatchmentParams(nrch, anReaches[nrch], this);
	}
	
	int anDownstreamReaches[nNumReaches];
	pCatchmentDescriptionFile->get_var("dsrch_nrch")->get(anDownstreamReaches, nNumReaches); 
	for(int nrch=0;nrch<nNumReaches;nrch++)
	{
		if(anDownstreamReaches[nrch]>=0)
		{
			std::cout << "Catchment " << nrch << " Downstream reach: " << anDownstreamReaches[nrch] << std::endl;
			//aSubcatchments[nrch] = new CSubcatchmentParams(nrch, this);
			aSubcatchments[nrch]->setDownstreamCatchment(aSubcatchments[anDownstreamReaches[nrch]]);
		}
	}
	
	std::cout << std::endl;
	
}
开发者ID:JustineSurGithub,项目名称:tom-cv,代码行数:43,代码来源:catchment_setup_params.cpp

示例10: DataInfo

const DataMatrix::DataInfo DataInterfaceNetCdfMatrix::dataInfo(const QString& matrix) const
{
  if (!netcdf._matrixList.contains( matrix ) ) {
    return DataMatrix::DataInfo();
  }

  QByteArray bytes = matrix.toLatin1();
  NcVar *var = netcdf._ncfile->get_var(bytes.constData());  // var is owned by _ncfile

  if (var->num_dims() != 2) {
    return DataMatrix::DataInfo();
  }

  DataMatrix::DataInfo info;
  info.samplesPerFrame = 1;
  // TODO is this right?
  info.xSize = var->get_dim(0)->size();
  info.ySize = var->get_dim(1)->size();

  return info;
}
开发者ID:,项目名称:,代码行数:21,代码来源:

示例11: exception

blitz::Array<T,rank> read_blitz(NcFile &nc, std::string const &var_name)
{
	// Read points vector
	NcVar *vpoints = nc.get_var(var_name.c_str());
	int ndims = vpoints->num_dims();
	if (ndims != rank) {
		fprintf(stderr, "NetCDF variable %s has rank %d, expected rank %d\n",
			var_name.c_str(), ndims, rank);
		throw std::exception();
	}

	blitz::TinyVector<int,rank> shape(0);
	long counts[rank];
	for (int i=0; i<rank; ++i) {
		shape[i] = vpoints->get_dim(i)->size();
printf("read_blitz: shape[%d] = %d\n", i, shape[i]);
		counts[i] = shape[i];
	}

	blitz::Array<T,rank> ret(shape);
for (int i=0; i<rank; ++i) printf("read_blitz: ret.extent(%d) = %d\n", i, ret.extent(i));
	vpoints->get(ret.data(), counts);
	return ret;
}
开发者ID:seifer08ms,项目名称:icebin,代码行数:24,代码来源:ncutil.hpp

示例12: ExtractLOC

ERMsg CMADIS::ExtractLOC(const CString& filePath, CSCCallBack& callback)
{
	ERMsg msg;

	callback.SetCurrentDescription("Extract location");
	callback.SetCurrentStepRange(0, 3, 1);
	callback.SetStartNewStep();

	CString outputFilePath(filePath);
	UtilWin::SetFileExtension( outputFilePath, ".loc");
	
//	CString outputFilePathGrid(filePath);
//	UtilWin::SetFileExtension( outputFilePathGrid, ".bil");

//	CShapeFileBase shapefile;
//	shapefile.Read("C:\\ouranos_data\\MapInput\\canada.shp");

	

	NcFile file(filePath);	

	if( !file.is_valid() )
	{
		CString err;
		err.FormatMessage(IDS_CMN_UNABLE_OPEN_READ, filePath);
		msg.ajoute(err);
	}

	//CMapBinaryFile grid;
 //   grid.SetProjection( GetDataGrid().GetPrj() );
 //   grid.SetNbCols(180);
 //   grid.SetNbRows(172);
 //   grid.SetBoundingBox(GetDataGrid());
 //   grid.SetNoData(-9999);
 //   grid.SetCellSizeX( 45000 );
 //   grid.SetCellSizeY( 45000 );
	CStdioFileEx fileOut;


	//msg += grid.Open(outputFilePathGrid, CGeoFileInterface::modeWrite);
	msg += fileOut.Open( outputFilePath, CFile::modeCreate|CFile::modeWrite);
	if(!msg)
		return msg;

	fileOut.WriteString("LOC_FILE 4 2,ID,Latitude,Longitude,Elevation,Slope(%),Orientation(°)\n");
	

	//char providerId(recNum, maxProviderIdLen) ;
	//	providerId:long_name = "Data Provider station Id" ;
	//	providerId:reference = "station table" ;
	//char stationId(recNum, maxStaIdLen) ;
	//	stationId:long_name = "alphanumeric station Id" ;
	//	stationId:reference = "station table" ;
	//char handbook5Id(recNum, maxStaIdLen) ;
	//	handbook5Id:long_name = "Handbook5 Id (AFOS or SHEF id)" ;
	//	handbook5Id:reference = "station table" ;
	//char stationName(recNum, maxNameLength) ;
	//	stationName:long_name = "alphanumeric station name" ;
	//	stationName:reference = "station table" ;

	//float latitude(recNum) ;
	//	latitude:long_name = "latitude" ;
	//	latitude:units = "degree_north" ;
	//	latitude:_FillValue = 3.4028235e+038f ;
	//	latitude:missing_value = -9999.f ;
	//	latitude:reference = "station table" ;
	//	latitude:standard_name = "latitude" ;
	//float longitude(recNum) ;
	//	longitude:long_name = "longitude" ;
	//	longitude:units = "degree_east" ;
	//	longitude:_FillValue = 3.4028235e+038f ;
	//	longitude:missing_value = -9999.f ;
	//	longitude:reference = "station table" ;
	//	longitude:standard_name = "longitude" ;
	//float elevation(recNum) ;
	//	elevation:long_name = "elevation" ;
	//	elevation:units = "meter" ;
	//	elevation:_FillValue = 3.4028235e+038f ;
	//	elevation:missing_value = -9999.f ;
	//	elevation:reference = "station table" ;
	//	elevation:standard_name = "elevation" ;

	//NcVar* pVarX = file.get_var("xc");
	//NcVar* pVarY = file.get_var("yc");
	
	NcVar* pVarLat = file.get_var("staLat");//file.get_var("latitude");
	NcVar* pVarLon = file.get_var("staLon");//file.get_var("longitude");
	NcVar* pVarElev = file.get_var("staElev");//file.get_var("elevation");
	NcDim* pDim = pVarLat->get_dim(0);
	//double offset = pVarElev->get_att("add_offset")->as_float(0);
	//double scaleFactor = pVarElev->get_att("scale_factor")->as_float(0);

	int nbRect = pDim->size();
	//delete pDim; pDim = NULL;

	//typedef boost::multi_array<char, 1> CDataCharArray;
	typedef boost::multi_array<float, 1> CDataFloatArray;
	//CDataFloatArray X(boost::extents[180]);
	//CDataFloatArray Y(boost::extents[172]);
	CDataFloatArray lat(boost::extents[nbRect]);
//.........这里部分代码省略.........
开发者ID:RNCan,项目名称:WeatherBasedSimulationFramework,代码行数:101,代码来源:MADIS.cpp

示例13: main

int main(int argc, char** argv) {

	NcError error(NcError::silent_nonfatal);

try {
	// Input filename
	std::string strInputFile;

	// Output mesh filename
	std::string strOutputFile;

	// Polynomial degree per element
	int nP = 2;

	// Parse the command line
	BeginCommandLine()
		CommandLineString(strInputFile, "in", "");
		CommandLineString(strOutputFile, "out", "");
		//CommandLineInt(nP, "np", 2);
		//CommandLineBool(fCGLL, "cgll");

		ParseCommandLine(argc, argv);
	EndCommandLine(argv)

	// Check file names
	if (strInputFile == "") {
		std::cout << "ERROR: No input file specified" << std::endl;
		return (-1);
	}
	if (strOutputFile == "") {
		std::cout << "ERROR: No output file specified" << std::endl;
		return (-1);
	}
	if (nP < 1) {
		std::cout << "ERROR: --np must be >= 2" << std::endl;
		return (-1);
	}

	AnnounceBanner();

	// Load input mesh
	AnnounceStartBlock("Loading input mesh");

	Mesh meshIn(strInputFile);
	meshIn.RemoveZeroEdges();

	AnnounceEndBlock("Done");

	// Construct edge map
	AnnounceStartBlock("Constructing edge map");

	meshIn.ConstructEdgeMap();

	AnnounceEndBlock("Done");

	// Build connectivity vector using edge map
	AnnounceStartBlock("Constructing connectivity");

    std::vector< std::set<int> > vecConnectivity;
    int err = GenerateConnectivityData(meshIn, vecConnectivity);
    if (err) return err;

	AnnounceEndBlock("Done");

	// Open output file
	AnnounceStartBlock("Writing connectivity file");

	NcFile ncmesh(strInputFile.c_str(), NcFile::ReadOnly);

	NcVar * varLat = ncmesh.get_var("grid_center_lat");
	NcVar * varLon = ncmesh.get_var("grid_center_lon");

	// Check if center latitudes and longitudes are already available
	DataArray1D<double> dAllLats;
	DataArray1D<double> dAllLons;

	bool fConvertLatToDegrees = true;
	bool fConvertLonToDegrees = true;

	if ((varLat == NULL) || (varLon == NULL)) {
		Announce("grid_center_lat not found, recalculating face centers");
	} else {
		Announce("grid_center_lat found in file, loading values");

		if (varLat->get_dim(0)->size() != vecConnectivity.size()) {
			_EXCEPTIONT("grid_center_lat dimension mismatch");
		}
		if (varLon->get_dim(0)->size() != vecConnectivity.size()) {
			_EXCEPTIONT("grid_center_lon dimension mismatch");
		}

		dAllLats.Allocate(vecConnectivity.size());
		varLat->set_cur((long)0);
		varLat->get(dAllLats, vecConnectivity.size());

		NcAtt * attLatUnits = varLat->get_att("units");
		std::string strLatUnits = attLatUnits->as_string(0);
		if (strLatUnits == "degrees") {
			fConvertLatToDegrees = false;
		}
//.........这里部分代码省略.........
开发者ID:ClimateGlobalChange,项目名称:tempestremap,代码行数:101,代码来源:GenerateConnectivityFile.cpp

示例14: ReadCFTimeDataFromNcFile

void ReadCFTimeDataFromNcFile(
	NcFile * ncfile,
	const std::string & strFilename,
	std::vector<Time> & vecTimes,
	bool fWarnOnMissingCalendar
) {
	// Empty existing Time vector
	vecTimes.clear();

	// Get time dimension
	NcDim * dimTime = ncfile->get_dim("time");
	if (dimTime == NULL) {
		_EXCEPTION1("Dimension \"time\" not found in file \"%s\"",
			strFilename.c_str());
	}

	// Get time variable
	NcVar * varTime = ncfile->get_var("time");
	if (varTime == NULL) {
		_EXCEPTION1("Variable \"time\" not found in file \"%s\"",
			strFilename.c_str());
	}
	if (varTime->num_dims() != 1) {
		_EXCEPTION1("Variable \"time\" has more than one dimension in file \"%s\"",
			strFilename.c_str());
	}
	if (strcmp(varTime->get_dim(0)->name(), "time") != 0) {
		_EXCEPTION1("Variable \"time\" does not have dimension \"time\" in file \"%s\"",
			strFilename.c_str());
	}

	// Calendar attribute
	NcAtt * attTimeCal = varTime->get_att("calendar");
	std::string strCalendar;
	if (attTimeCal == NULL) {
		if (fWarnOnMissingCalendar) {
			Announce("WARNING: Variable \"time\" is missing \"calendar\" attribute; assuming \"standard\"");
		}
		strCalendar = "standard";
	} else {
		strCalendar = attTimeCal->as_string(0);
	}
	Time::CalendarType eCalendarType =
		Time::CalendarTypeFromString(strCalendar);

	// Units attribute
	NcAtt * attTimeUnits = varTime->get_att("units");
	if (attTimeUnits == NULL) {
		_EXCEPTION1("Variable \"time\" is missing \"units\" attribute in file \"%s\"",
			strFilename.c_str());
	}
	std::string strTimeUnits = attTimeUnits->as_string(0);

	// Load in time data
	DataVector<int> vecTimeInt;
	DataVector<float> vecTimeFloat;
	DataVector<double> vecTimeDouble;
	DataVector<ncint64> vecTimeInt64;

	if (varTime->type() == ncInt) {
		vecTimeInt.Initialize(dimTime->size());
		varTime->set_cur((long)0);
		varTime->get(&(vecTimeInt[0]), dimTime->size());

	} else if (varTime->type() == ncFloat) {
		vecTimeFloat.Initialize(dimTime->size());
		varTime->set_cur((long)0);
		varTime->get(&(vecTimeFloat[0]), dimTime->size());

	} else if (varTime->type() == ncDouble) {
		vecTimeDouble.Initialize(dimTime->size());
		varTime->set_cur((long)0);
		varTime->get(&(vecTimeDouble[0]), dimTime->size());

	} else if (varTime->type() == ncInt64) {
		vecTimeInt64.Initialize(dimTime->size());
		varTime->set_cur((long)0);
		varTime->get(&(vecTimeInt64[0]), dimTime->size());

	} else {
		_EXCEPTION1("Variable \"time\" has invalid type "
			"(expected \"int\", \"int64\", \"float\" or \"double\")"
			" in file \"%s\"", strFilename.c_str());
	}

	for (int t = 0; t < dimTime->size(); t++) {
		Time time(eCalendarType);
		if (varTime->type() == ncInt) {
			time.FromCFCompliantUnitsOffsetInt(
				strTimeUnits,
				vecTimeInt[t]);

		} else if (varTime->type() == ncFloat) {
			time.FromCFCompliantUnitsOffsetDouble(
				strTimeUnits,
				static_cast<double>(vecTimeFloat[t]));

		} else if (varTime->type() == ncDouble) {
			time.FromCFCompliantUnitsOffsetDouble(
				strTimeUnits,
//.........这里部分代码省略.........
开发者ID:ClimateGlobalChange,项目名称:tempestextremes,代码行数:101,代码来源:NetCDFUtilities.cpp

示例15: CopyNcVar

void CopyNcVar(
	NcFile & ncIn,
	NcFile & ncOut,
	const std::string & strVarName,
	bool fCopyAttributes,
	bool fCopyData
) {
	if (!ncIn.is_valid()) {
		_EXCEPTIONT("Invalid input file specified");
	}
	if (!ncOut.is_valid()) {
		_EXCEPTIONT("Invalid output file specified");
	}
	NcVar * var = ncIn.get_var(strVarName.c_str());
	if (var == NULL) {
		_EXCEPTION1("NetCDF file does not contain variable \"%s\"",
			strVarName.c_str());
	}

	NcVar * varOut;

	std::vector<NcDim *> dimOut;
	dimOut.resize(var->num_dims());

	std::vector<long> counts;
	counts.resize(var->num_dims());

	long nDataSize = 1;

	for (int d = 0; d < var->num_dims(); d++) {
		NcDim * dimA = var->get_dim(d);

		dimOut[d] = ncOut.get_dim(dimA->name());

		if (dimOut[d] == NULL) {
			if (dimA->is_unlimited()) {
				dimOut[d] = ncOut.add_dim(dimA->name());
			} else {
				dimOut[d] = ncOut.add_dim(dimA->name(), dimA->size());
			}

			if (dimOut[d] == NULL) {
				_EXCEPTION2("Failed to add dimension \"%s\" (%i) to file",
					dimA->name(), dimA->size());
			}
		}
		if (dimOut[d]->size() != dimA->size()) {
			if (dimA->is_unlimited() && !dimOut[d]->is_unlimited()) {
				_EXCEPTION2("Mismatch between input file dimension \"%s\" and "
					"output file dimension (UNLIMITED / %i)",
					dimA->name(), dimOut[d]->size());
			} else if (!dimA->is_unlimited() && dimOut[d]->is_unlimited()) {
				_EXCEPTION2("Mismatch between input file dimension \"%s\" and "
					"output file dimension (%i / UNLIMITED)",
					dimA->name(), dimA->size());
			} else if (!dimA->is_unlimited() && !dimOut[d]->is_unlimited()) {
				_EXCEPTION3("Mismatch between input file dimension \"%s\" and "
					"output file dimension (%i / %i)",
					dimA->name(), dimA->size(), dimOut[d]->size());
			}
		}

		counts[d] = dimA->size();
		nDataSize *= counts[d];
	}

	// ncByte / ncChar type
	if ((var->type() == ncByte) || (var->type() == ncChar)) {
		DataVector<char> data;
		data.Initialize(nDataSize);

		varOut =
			ncOut.add_var(
				var->name(), var->type(),
				dimOut.size(), (const NcDim**)&(dimOut[0]));

		if (varOut == NULL) {
			_EXCEPTION1("Cannot create variable \"%s\"", var->name());
		}

		var->get(&(data[0]), &(counts[0]));
		varOut->put(&(data[0]), &(counts[0]));
	}

	// ncShort type
	if (var->type() == ncShort) {
		DataVector<short> data;
		data.Initialize(nDataSize);

		varOut =
			ncOut.add_var(
				var->name(), var->type(),
				dimOut.size(), (const NcDim**)&(dimOut[0]));

		if (varOut == NULL) {
			_EXCEPTION1("Cannot create variable \"%s\"", var->name());
		}

		if (fCopyData) {
			var->get(&(data[0]), &(counts[0]));
//.........这里部分代码省略.........
开发者ID:ClimateGlobalChange,项目名称:tempestextremes,代码行数:101,代码来源:NetCDFUtilities.cpp


注:本文中的NcVar::get_dim方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。