source: XIOS/dev/branch_openmp/src/io/onetcdf4.cpp @ 1520

Last change on this file since 1520 was 1520, checked in by yushan, 6 years ago

save dev. TO DO : test with xios

  • Property copyright set to
    Software name : XIOS (Xml I/O Server)
    http://forge.ipsl.jussieu.fr/ioserver
    Creation date : January 2009
    Licence : CeCCIL version2
    see license file in root directory : Licence_CeCILL_V2-en.txt
    or http://www.cecill.info/licences/Licence_CeCILL_V2-en.html
    Holder : CEA/LSCE (Laboratoire des Sciences du CLimat et de l'Environnement)
    CNRS/IPSL (Institut Pierre Simon Laplace)
    Project Manager : Yann Meurdesoif
    yann.meurdesoif@cea.fr
File size: 22.8 KB
Line 
1#include <fstream>
2
3#include "onetcdf4.hpp"
4#include "group_template.hpp"
5#include "ep_mpi.hpp"
6#include "netcdf.hpp"
7#include "netCdfInterface.hpp"
8#include "netCdfException.hpp"
9#include "timer.hpp"
10
11namespace xios
12{
13      /// ////////////////////// Définitions ////////////////////// ///
14
15      CONetCDF4::CONetCDF4(const StdString& filename, bool append, bool useClassicFormat,
16                                                        bool useCFConvention,
17                           const ep_lib::MPI_Comm* comm, bool multifile, const StdString& timeCounterName)
18        : path()
19        , wmpi(false)
20        , useClassicFormat(useClassicFormat)
21        , useCFConvention(useCFConvention)
22      {
23         this->initialize(filename, append, useClassicFormat, useCFConvention, comm, multifile, timeCounterName);
24      }
25
26      //---------------------------------------------------------------
27
28      CONetCDF4::~CONetCDF4(void)
29      {
30      }
31
32      ///--------------------------------------------------------------
33
34      void CONetCDF4::initialize(const StdString& filename, bool append, bool useClassicFormat, bool useCFConvention, 
35                                 const ep_lib::MPI_Comm* comm, bool multifile, const StdString& timeCounterName)
36      {
37         this->useClassicFormat = useClassicFormat;
38         this->useCFConvention = useCFConvention;
39
40         int mode = useClassicFormat ? 0 : NC_NETCDF4;
41
42         // Don't use parallel mode if there is only one process
43         if (comm)
44         {
45            int commSize = 0;
46            ep_lib::MPI_Comm_size(*comm, &commSize);
47            if (commSize <= 1)
48               comm = NULL;
49         }
50         wmpi = comm && !multifile;
51         ep_lib::MPI_Info info_null;
52
53         if (wmpi)
54            mode |= useClassicFormat ? NC_PNETCDF : NC_MPIIO;
55
56         // If the file does not exist, we always create it
57         if (!append || !std::ifstream(filename.c_str()))
58         {
59            CTimer::get("Files : create").resume();
60            if (wmpi)
61               CNetCdfInterface::createPar(filename, mode, to_mpi_comm((*comm)->mpi_comm), to_mpi_info(info_null), this->ncidp);
62            else
63               CNetCdfInterface::create(filename, mode, this->ncidp);
64            CTimer::get("Files : create").suspend();
65 
66            this->appendMode = false;
67         }
68         else
69         {
70            mode |= NC_WRITE;
71            CTimer::get("Files : open").resume();
72            if (wmpi)
73               CNetCdfInterface::openPar(filename, mode, to_mpi_comm((*comm)->mpi_comm), to_mpi_info(info_null), this->ncidp);
74            else
75               CNetCdfInterface::open(filename, mode, this->ncidp);
76            CTimer::get("Files : open").suspend();
77            this->appendMode = true;
78         }
79
80         // If the classic NetCDF format is used, we enable the "no-fill mode" globally.
81         // This is done per variable for the NetCDF4 format.
82         if (useClassicFormat)
83            CNetCdfInterface::setFill(this->ncidp, false);
84
85         this->timeCounterName = timeCounterName;
86      }
87
88      void CONetCDF4::close()
89      {
90        CTimer::get("Files : close").resume();
91        CNetCdfInterface::close(this->ncidp);
92        CTimer::get("Files : close").suspend();
93      }
94
95      //---------------------------------------------------------------
96
97      void CONetCDF4::definition_start(void)
98      {
99         CNetCdfInterface::reDef(this->ncidp);
100      }
101
102      //---------------------------------------------------------------
103
104      void CONetCDF4::definition_end(void)
105      {
106         CNetCdfInterface::endDef(this->ncidp);
107      }
108
109      //---------------------------------------------------------------
110
111      int CONetCDF4::getCurrentGroup(void)
112      {
113         return this->getGroup(this->getCurrentPath());
114      }
115
116      //---------------------------------------------------------------
117
118      int CONetCDF4::getGroup(const CONetCDF4Path& path)
119      {
120         int retvalue = this->ncidp;
121
122         CONetCDF4Path::const_iterator it = path.begin(), end = path.end();
123
124         for (; it != end; it++)
125         {
126            const StdString& groupid = *it;
127            CNetCdfInterface::inqNcId(retvalue, groupid, retvalue);
128         }
129         return retvalue;
130      }
131
132      //---------------------------------------------------------------
133
134      int CONetCDF4::getVariable(const StdString& varname)
135      {
136         int varid = 0;
137         int grpid = this->getCurrentGroup();
138         CNetCdfInterface::inqVarId(grpid, varname, varid);
139         return varid;
140      }
141
142      //---------------------------------------------------------------
143
144      int CONetCDF4::getDimension(const StdString& dimname)
145      {
146         int dimid = 0;
147         int grpid = this->getCurrentGroup();
148         CNetCdfInterface::inqDimId(grpid, dimname, dimid);
149         return dimid;
150      }
151
152      //---------------------------------------------------------------
153
154      int CONetCDF4::getUnlimitedDimension(void)
155      {
156         int dimid = 0;
157         int grpid = this->getCurrentGroup();
158         CNetCdfInterface::inqUnLimDim(grpid, dimid);
159         return dimid;
160      }
161
162      StdString CONetCDF4::getUnlimitedDimensionName(void)
163      {
164         int grpid = this->getGroup(path);
165         int dimid = this->getUnlimitedDimension();
166
167         StdString dimname;
168         if (dimid != -1)
169           CNetCdfInterface::inqDimName(grpid, dimid, dimname);
170         return dimname;
171      }
172
173      //---------------------------------------------------------------
174
175      std::vector<StdSize> CONetCDF4::getDimensions(const StdString& varname)
176      {
177         StdSize size = 0;
178         std::vector<StdSize> retvalue;
179         int grpid = this->getCurrentGroup();
180         int varid = this->getVariable(varname);
181         int nbdim = 0, *dimid = NULL;
182
183         CNetCdfInterface::inqVarNDims(grpid, varid, nbdim);
184         dimid = new int[nbdim]();
185         CNetCdfInterface::inqVarDimId(grpid, varid, dimid);
186
187         for (int i = 0; i < nbdim; i++)
188         {
189            CNetCdfInterface::inqDimLen(grpid, dimid[i], size);
190            if (size == NC_UNLIMITED)
191                size = UNLIMITED_DIM;
192            retvalue.push_back(size);
193         }
194         delete [] dimid;
195         return retvalue;
196      }
197
198      std::vector<std::string> CONetCDF4::getDimensionsIdList(const std::string* _varname)
199      {
200         int nDimNull = 0;
201         int nbdim = 0, *dimid = NULL;
202         int grpid = this->getCurrentGroup();
203         int varid = (_varname != NULL) ? this->getVariable(*_varname) : NC_GLOBAL;
204         std::vector<std::string> retvalue;
205
206         if (_varname != NULL)
207         {
208            CNetCdfInterface::inqVarNDims(grpid, varid, nbdim);
209            dimid = new int[nbdim]();
210            CNetCdfInterface::inqVarDimId(grpid, varid, dimid);
211         }
212         else
213         {
214            CNetCdfInterface::inqDimIds(grpid, nbdim, NULL, 1);
215            dimid = new int[nbdim]();
216            CNetCdfInterface::inqDimIds(grpid, nDimNull, dimid, 1);
217         }
218
219         for (int i = 0; i < nbdim; i++)
220         {
221            std::string dimname;
222            CNetCdfInterface::inqDimName(grpid, dimid[i], dimname);
223            retvalue.push_back(dimname);
224         }
225         delete [] dimid;
226
227         return retvalue;
228      }
229
230      //---------------------------------------------------------------
231
232      void CONetCDF4::getTimeAxisBounds(CArray<double,2>& timeAxisBounds, const StdString& name, bool collective)
233      {
234        int grpid = this->getCurrentGroup();
235        int varid = this->getVariable(name);
236
237        std::vector<StdSize> start(2), count(2);
238        start[0] = 0;
239        // Find out how many temporal records have been written already to the file we are opening
240        int ncUnlimitedDimId;
241        CNetCdfInterface::inqUnLimDim(this->ncidp, ncUnlimitedDimId);
242        CNetCdfInterface::inqDimLen(this->ncidp, ncUnlimitedDimId, count[0]);
243        start[1] = 0;
244        count[1] = 2;
245
246        timeAxisBounds.resize(count[1], count[0]);
247
248        if (this->wmpi && collective)
249          CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
250        if (this->wmpi && !collective)
251          CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
252
253        CNetCdfInterface::getVaraType(grpid, varid, &start[0], &count[0], timeAxisBounds.dataFirst());
254      }
255
256      void CONetCDF4::getTimeAxisBounds(CArray<double,2>& timeAxisBounds, const StdString& name, bool collective, size_t record)
257      {
258        int grpid = this->getCurrentGroup();
259        int varid = this->getVariable(name);
260
261        std::vector<StdSize> start(2), count(2);
262        start[0] = record;
263        count[0] = 1 ;
264        start[1] = 0;
265        count[1] = 2;
266
267        timeAxisBounds.resize(2, 1);
268
269        if (this->wmpi && collective)
270          CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
271        if (this->wmpi && !collective)
272          CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
273
274        CNetCdfInterface::getVaraType(grpid, varid, &start[0], &count[0], timeAxisBounds.dataFirst());
275      }
276
277
278
279      const CONetCDF4::CONetCDF4Path& CONetCDF4::getCurrentPath(void) const
280      { return this->path; }
281
282      void CONetCDF4::setCurrentPath(const CONetCDF4Path& path)
283      { this->path = path; }
284
285      //---------------------------------------------------------------
286
287      int CONetCDF4::addGroup(const StdString& name)
288      {
289         int retvalue = 0;
290         int grpid = this->getCurrentGroup();
291         CNetCdfInterface::defGrp(grpid, name, retvalue);
292         return retvalue;
293      }
294
295      //---------------------------------------------------------------
296
297      int CONetCDF4::addDimension(const StdString& name, const StdSize size)
298      {
299         int retvalue = 0;
300         int grpid = this->getCurrentGroup();
301         if (size != UNLIMITED_DIM)
302            CNetCdfInterface::defDim(grpid, name, size, retvalue);
303         else
304            CNetCdfInterface::defDim(grpid, name, NC_UNLIMITED, retvalue);
305         return retvalue;
306      }
307
308      //---------------------------------------------------------------
309
310      int CONetCDF4::addVariable(const StdString& name, nc_type type,
311                                 const std::vector<StdString>& dim, int compressionLevel)
312      {
313         int varid = 0;
314         std::vector<int> dimids;
315         std::vector<StdSize> dimsizes;
316         int dimSize = dim.size();
317         
318         StdSize size;
319         StdSize totalSize;
320         StdSize maxSize = 1024 * 1024 * 256; // == 2GB/8 if output double
321
322         int grpid = this->getCurrentGroup();
323
324         std::vector<StdString>::const_iterator it = dim.begin(), end = dim.end();
325
326         for (int idx = 0; it != end; it++, ++idx)
327         {
328            const StdString& dimid = *it;
329            dimids.push_back(this->getDimension(dimid));
330            CNetCdfInterface::inqDimLen(grpid, this->getDimension(dimid), size);
331            if (size == NC_UNLIMITED) size = 1;
332            dimsizes.push_back(size);
333         }
334
335         CNetCdfInterface::defVar(grpid, name, type, dimids.size(), &dimids[0], varid);
336
337         // The classic NetCDF format does not support chunking nor fill parameters
338         if (!useClassicFormat)
339         {
340            // set chunksize : size of one record
341            // but must not be > 2GB (netcdf or HDF5 problem)
342            totalSize = 1;
343            for (vector<StdSize>::reverse_iterator it = dimsizes.rbegin(); it != dimsizes.rend(); ++it)
344            {
345              totalSize *= *it;
346              if (totalSize >= maxSize) *it = 1;
347            }
348            int storageType = (0 == dimSize) ? NC_CONTIGUOUS : NC_CHUNKED;
349            CNetCdfInterface::defVarChunking(grpid, varid, storageType, &dimsizes[0]);
350            CNetCdfInterface::defVarFill(grpid, varid, true, NULL);
351         }
352
353         setCompressionLevel(name, compressionLevel) ;
354         
355         return varid;
356      }
357
358      //---------------------------------------------------------------
359
360      void CONetCDF4::setCompressionLevel(const StdString& varname, int compressionLevel)
361      {
362         if (compressionLevel < 0 || compressionLevel > 9)
363           ERROR("void CONetCDF4::setCompressionLevel(const StdString& varname, int compressionLevel)",
364                 "Invalid compression level for variable \"" << varname << "\", the value should range between 0 and 9.");
365         if (compressionLevel && wmpi)
366           ERROR("void CONetCDF4::setCompressionLevel(const StdString& varname, int compressionLevel)",
367                 "Impossible to use compression for variable \"" << varname << "\" when using parallel mode.");
368
369         int grpid = this->getCurrentGroup();
370         int varid = this->getVariable(varname);
371         CNetCdfInterface::defVarDeflate(grpid, varid, compressionLevel);
372      }
373
374      //---------------------------------------------------------------
375
376      template <>
377      void CONetCDF4::addAttribute(const StdString& name, const StdString& value, const StdString* varname)
378      {
379         int grpid = this->getCurrentGroup();
380         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
381         CNetCdfInterface::putAttType(grpid, varid, name, value.size(), value.c_str());
382      }
383
384      //---------------------------------------------------------------
385
386      template <>
387      void CONetCDF4::addAttribute(const StdString& name, const double& value, const StdString* varname)
388      {
389         int grpid = this->getCurrentGroup();
390         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
391         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
392      }
393
394      template <>
395      void CONetCDF4::addAttribute(const StdString& name, const CArray<double,1>& value, const StdString* varname)
396      {
397         int grpid = this->getCurrentGroup();
398         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
399         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
400      }
401      //---------------------------------------------------------------
402
403      template <>
404      void CONetCDF4::addAttribute(const StdString& name, const float& value, const StdString* varname)
405      {
406         int grpid = this->getCurrentGroup();
407         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
408         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
409      }
410
411      template <>
412      void CONetCDF4::addAttribute(const StdString& name, const CArray<float,1>& value, const StdString* varname)
413      {
414         int grpid = this->getCurrentGroup();
415         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
416         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
417      }
418
419      //---------------------------------------------------------------
420
421      template <>
422      void CONetCDF4::addAttribute(const StdString& name, const int& value, const StdString* varname)
423      {
424         int grpid = this->getCurrentGroup();
425         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
426         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
427      }
428
429      template <>
430      void CONetCDF4::addAttribute(const StdString& name, const CArray<int,1>& value, const StdString* varname)
431      {
432         int grpid = this->getCurrentGroup();
433         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
434         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
435      }
436
437      template <>
438      void CONetCDF4::addAttribute(const StdString& name, const short int& value, const StdString* varname)
439      {
440         int grpid = this->getCurrentGroup();
441         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
442         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
443      }
444
445      template <>
446      void CONetCDF4::addAttribute(const StdString& name, const CArray<short int,1>& value, const StdString* varname)
447      {
448         int grpid = this->getCurrentGroup();
449         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
450         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
451      }
452
453      template <>
454      void CONetCDF4::addAttribute(const StdString& name, const long int& value, const StdString* varname)
455      {
456         int grpid = this->getCurrentGroup();
457         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
458         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
459      }
460
461      template <>
462      void CONetCDF4::addAttribute(const StdString& name, const CArray<long int,1>& value, const StdString* varname)
463      {
464         int grpid = this->getCurrentGroup();
465         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
466         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
467      }
468
469      //---------------------------------------------------------------
470
471      void CONetCDF4::getWriteDataInfos(const StdString& name, StdSize record, StdSize& array_size,
472                                        std::vector<StdSize>& sstart,
473                                        std::vector<StdSize>& scount,
474                                        const std::vector<StdSize>* start,
475                                        const std::vector<StdSize>* count)
476      {
477         std::vector<std::size_t> sizes  = this->getDimensions(name);
478         if (sizes.size()==0) 
479         {
480            array_size=1 ;
481            sstart.push_back(0);
482            scount.push_back(1);
483         }
484         else
485         {
486           std::vector<std::string> iddims = this->getDimensionsIdList (&name);
487           std::vector<std::size_t>::const_iterator
488           it  = sizes.begin(), end = sizes.end();
489           int i = 0;
490
491           if (iddims.begin()->compare(timeCounterName) == 0)
492           {
493             sstart.push_back(record);
494             scount.push_back(1);
495              if ((start == NULL) &&
496                  (count == NULL)) i++;
497              it++;
498           }
499
500           for (;it != end; it++)
501           {
502              if ((start != NULL) && (count != NULL))
503              {
504                 sstart.push_back((*start)[i]);
505                 scount.push_back((*count)[i]);
506                 array_size *= (*count)[i];
507                 i++;
508              }
509              else
510              {
511                 sstart.push_back(0);
512                 scount.push_back(sizes[i]);
513                 array_size *= sizes[i];
514                 i++;
515              }
516           }
517
518         }
519      }
520
521
522      template <>
523      void CONetCDF4::writeData_(int grpid, int varid,
524                                 const std::vector<StdSize>& sstart,
525                                 const std::vector<StdSize>& scount, const double* data)
526      {
527         CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
528      }
529
530      //---------------------------------------------------------------
531
532      template <>
533      void CONetCDF4::writeData_(int grpid, int varid,
534                                 const std::vector<StdSize>& sstart,
535                                 const std::vector<StdSize>& scount, char* data)
536      {
537          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
538      }
539     
540      template <>
541
542      void CONetCDF4::writeData_(int grpid, int varid,
543                                 const std::vector<StdSize>& sstart,
544                                 const std::vector<StdSize>& scount, const int* data)
545      {
546          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
547      }
548      //---------------------------------------------------------------
549
550      template <>
551      void CONetCDF4::writeData_(int grpid, int varid,
552                                 const std::vector<StdSize>& sstart,
553                                 const std::vector<StdSize>& scount, const float* data)
554      {
555          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
556      }
557
558      //---------------------------------------------------------------
559
560      void CONetCDF4::writeData(const CArray<int, 2>& data, const StdString& name)
561      {
562         int grpid = this->getCurrentGroup();
563         int varid = this->getVariable(name);
564         StdSize array_size = 1;
565         std::vector<StdSize> sstart, scount;
566
567         this->getWriteDataInfos(name, 0, array_size,  sstart, scount, NULL, NULL);
568
569         this->writeData_(grpid, varid, sstart, scount, data.dataFirst());
570
571      }
572
573      void CONetCDF4::writeTimeAxisData(const CArray<double, 1>& data, const StdString& name,
574                                        bool collective, StdSize record, bool isRoot)
575      {
576         int grpid = this->getCurrentGroup();
577         int varid = this->getVariable(name);
578
579         map<int,size_t>::iterator it=timeAxis.find(varid);
580         if (it == timeAxis.end()) timeAxis[varid] = record;
581         else
582         {
583           if (it->second >= record) return;
584           else it->second =record;
585         }
586
587         StdSize array_size = 1;
588         std::vector<StdSize> sstart, scount;
589
590         if (this->wmpi && collective)
591            CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
592         if (this->wmpi && !collective)
593            CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
594
595         this->getWriteDataInfos(name, record, array_size,  sstart, scount, NULL, NULL);
596         this->writeData_(grpid, varid, sstart, scount, data.dataFirst());
597       }
598
599      void CONetCDF4::writeTimeAxisDataBounds(const CArray<double, 1>& data, const StdString& name,
600                                        bool collective, StdSize record, bool isRoot)
601      {
602         int grpid = this->getCurrentGroup();
603         int varid = this->getVariable(name);
604
605         map<int,size_t>::iterator it=timeAxis.find(varid);
606         if (it == timeAxis.end()) timeAxis[varid] = record;
607         else
608         {
609           if (it->second >= record) return;
610           else it->second =record;
611         }
612
613         StdSize array_size = 1;
614         std::vector<StdSize> sstart, scount;
615
616         if (this->wmpi && collective)
617            CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
618         if (this->wmpi && !collective)
619            CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
620
621         this->getWriteDataInfos(name, record, array_size,  sstart, scount, NULL, NULL);
622         this->writeData_(grpid, varid, sstart, scount, data.dataFirst());
623       }
624
625
626      //---------------------------------------------------------------
627
628      bool CONetCDF4::varExist(const StdString& varname)
629      {
630         int grpid = this->getCurrentGroup();
631         return CNetCdfInterface::isVarExisted(grpid, varname);
632      }
633
634      bool CONetCDF4::dimExist(const StdString& dimname)
635      {
636         int grpid = this->getCurrentGroup();
637         return CNetCdfInterface::isDimExisted(grpid, dimname);
638      }
639
640      void CONetCDF4::sync(void)
641      {
642         CNetCdfInterface::sync(this->ncidp);
643      }
644      ///--------------------------------------------------------------
645 } // namespace xios
Note: See TracBrowser for help on using the repository browser.