source: XIOS/dev/branch_yushan_merged/src/io/onetcdf4.cpp @ 1205

Last change on this file since 1205 was 1205, checked in by yushan, 7 years ago

branch merged with trunk @1200

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