source: XIOS3/trunk/src/io/onetcdf4.cpp @ 2613

Last change on this file since 2613 was 2613, checked in by jderouillat, 2 months ago

Fix the attached mode for scalar output, and some bugs revealed by the adastra porting in debug mode

  • 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: 32.6 KB
Line 
1#include <fstream>
2
3#include "onetcdf4.hpp"
4#include "onetcdf4_plugin.hpp"
5#include "group_template.hpp"
6#include "mpi.hpp"
7#include "netcdf.hpp"
8#include "netCdfInterface.hpp"
9#include "netCdfException.hpp"
10#include "timer.hpp"
11#include "file.hpp"
12
13namespace xios
14{
15      /// ////////////////////// Définitions ////////////////////// ///
16
17      CONetCDF4::CONetCDF4(const StdString& filename, bool append, bool useClassicFormat,
18                                                        bool useCFConvention,
19                           const MPI_Comm* comm, bool multifile, const StdString& timeCounterName)
20        : path()
21        , wmpi(false)
22        , useClassicFormat(useClassicFormat)
23        , useCFConvention(useCFConvention)
24      {
25         this->initialize(filename, append, useClassicFormat, useCFConvention, comm, multifile, timeCounterName);
26      }
27
28      //---------------------------------------------------------------
29
30      CONetCDF4::~CONetCDF4(void)
31      {
32      }
33
34      ///--------------------------------------------------------------
35
36      void CONetCDF4::initialize(const StdString& filename, bool append, bool useClassicFormat, bool useCFConvention, 
37                                 const MPI_Comm* comm, bool multifile, const StdString& timeCounterName)
38      {
39         this->useClassicFormat = useClassicFormat;
40         this->useCFConvention = useCFConvention;
41
42         int mode = useClassicFormat ? 0 : NC_NETCDF4;
43
44         // Don't use parallel mode if there is only one process
45         if (comm)
46         {
47            int commSize = 0;
48            MPI_Comm_size(*comm, &commSize);
49            if (commSize <= 1)
50               comm = NULL;
51         }
52         wmpi = comm && !multifile;
53
54         if (wmpi)
55            mode |= useClassicFormat ? NC_PNETCDF : NC_MPIIO;
56
57         // If the file does not exist, we always create it
58         if (!append || !std::ifstream(filename.c_str()))
59         {
60            CTimer::get("Files : create").resume();
61            if (wmpi)
62               CNetCdfInterface::createPar(filename, mode, *comm, MPI_INFO_NULL, this->ncidp);
63            else
64               CNetCdfInterface::create(filename, mode, this->ncidp);
65            CTimer::get("Files : create").suspend();
66 
67            this->appendMode = false;
68         }
69         else
70         {
71            mode |= NC_WRITE;
72            CTimer::get("Files : open").resume();
73            if (wmpi)
74               CNetCdfInterface::openPar(filename, mode, *comm, MPI_INFO_NULL, this->ncidp);
75            else
76               CNetCdfInterface::open(filename, mode, this->ncidp);
77            CTimer::get("Files : open").suspend();
78            this->appendMode = true;
79         }
80
81         // If the classic NetCDF format is used, we enable the "no-fill mode" globally.
82         // This is done per variable for the NetCDF4 format.
83         if (useClassicFormat)
84            CNetCdfInterface::setFill(this->ncidp, false);
85
86         this->timeCounterName = timeCounterName;
87      }
88
89      void CONetCDF4::close()
90      {
91        CTimer::get("Files : close").resume();
92        CNetCdfInterface::close(this->ncidp);
93        CTimer::get("Files : close").suspend();
94      }
95
96      //---------------------------------------------------------------
97
98      void CONetCDF4::definition_start(void)
99      {
100         CNetCdfInterface::reDef(this->ncidp);
101      }
102
103      //---------------------------------------------------------------
104
105      void CONetCDF4::definition_end(void)
106      {
107         CNetCdfInterface::endDef(this->ncidp);
108      }
109
110      //---------------------------------------------------------------
111
112      int CONetCDF4::getCurrentGroup(void)
113      {
114         return this->getGroup(this->getCurrentPath());
115      }
116
117      //---------------------------------------------------------------
118
119      int CONetCDF4::getGroup(const CONetCDF4Path& path)
120      {
121         int retvalue = this->ncidp;
122
123         CONetCDF4Path::const_iterator it = path.begin(), end = path.end();
124
125         for (; it != end; it++)
126         {
127            const StdString& groupid = *it;
128            CNetCdfInterface::inqNcId(retvalue, groupid, retvalue);
129         }
130         return retvalue;
131      }
132
133      //---------------------------------------------------------------
134
135      int CONetCDF4::getVariable(const StdString& varname)
136      {
137         int varid = 0;
138         int grpid = this->getCurrentGroup();
139         CNetCdfInterface::inqVarId(grpid, varname, varid);
140         return varid;
141      }
142
143      //---------------------------------------------------------------
144
145      int CONetCDF4::getDimension(const StdString& dimname)
146      {
147         int dimid = 0;
148         int grpid = this->getCurrentGroup();
149         CNetCdfInterface::inqDimId(grpid, dimname, dimid);
150         return dimid;
151      }
152
153      //---------------------------------------------------------------
154
155      int CONetCDF4::getUnlimitedDimension(void)
156      {
157         int dimid = 0;
158         int grpid = this->getCurrentGroup();
159         CNetCdfInterface::inqUnLimDim(grpid, dimid);
160         return dimid;
161      }
162
163      StdString CONetCDF4::getUnlimitedDimensionName(void)
164      {
165         int grpid = this->getGroup(path);
166         int dimid = this->getUnlimitedDimension();
167
168         StdString dimname;
169         if (dimid != -1)
170           CNetCdfInterface::inqDimName(grpid, dimid, dimname);
171         return dimname;
172      }
173
174      //---------------------------------------------------------------
175
176      std::vector<StdSize> CONetCDF4::getDimensions(const StdString& varname)
177      {
178         StdSize size = 0;
179         std::vector<StdSize> retvalue;
180         int grpid = this->getCurrentGroup();
181         int varid = this->getVariable(varname);
182         int nbdim = 0, *dimid = NULL;
183
184         CNetCdfInterface::inqVarNDims(grpid, varid, nbdim);
185         dimid = new int[nbdim]();
186         CNetCdfInterface::inqVarDimId(grpid, varid, dimid);
187
188         for (int i = 0; i < nbdim; i++)
189         {
190            CNetCdfInterface::inqDimLen(grpid, dimid[i], size);
191            if (size == NC_UNLIMITED)
192                size = UNLIMITED_DIM;
193            retvalue.push_back(size);
194         }
195         delete [] dimid;
196         return retvalue;
197      }
198
199      std::vector<std::string> CONetCDF4::getDimensionsIdList(const std::string* _varname)
200      {
201         int nDimNull = 0;
202         int nbdim = 0, *dimid = NULL;
203         int grpid = this->getCurrentGroup();
204         int varid = (_varname != NULL) ? this->getVariable(*_varname) : NC_GLOBAL;
205         std::vector<std::string> retvalue;
206
207         if (_varname != NULL)
208         {
209            CNetCdfInterface::inqVarNDims(grpid, varid, nbdim);
210            dimid = new int[nbdim]();
211            CNetCdfInterface::inqVarDimId(grpid, varid, dimid);
212         }
213         else
214         {
215            CNetCdfInterface::inqDimIds(grpid, nbdim, NULL, 1);
216            dimid = new int[nbdim]();
217            CNetCdfInterface::inqDimIds(grpid, nDimNull, dimid, 1);
218         }
219
220         for (int i = 0; i < nbdim; i++)
221         {
222            std::string dimname;
223            CNetCdfInterface::inqDimName(grpid, dimid[i], dimname);
224            retvalue.push_back(dimname);
225         }
226         delete [] dimid;
227
228         return retvalue;
229      }
230
231      //---------------------------------------------------------------
232
233      void CONetCDF4::getTimeAxisBounds(CArray<double,2>& timeAxisBounds, const StdString& name, bool collective)
234      {
235        int grpid = this->getCurrentGroup();
236        int varid = this->getVariable(name);
237
238        std::vector<StdSize> start(2), count(2);
239        start[0] = 0;
240        // Find out how many temporal records have been written already to the file we are opening
241        int ncUnlimitedDimId;
242        CNetCdfInterface::inqUnLimDim(this->ncidp, ncUnlimitedDimId);
243        CNetCdfInterface::inqDimLen(this->ncidp, ncUnlimitedDimId, count[0]);
244        start[1] = 0;
245        count[1] = 2;
246
247        timeAxisBounds.resize(count[1], count[0]);
248
249        if (this->wmpi && collective)
250          CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
251        if (this->wmpi && !collective)
252          CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
253
254        CNetCdfInterface::getVaraType(grpid, varid, &start[0], &count[0], timeAxisBounds.dataFirst());
255      }
256
257      void CONetCDF4::getTimeAxisBounds(CArray<double,2>& timeAxisBounds, const StdString& name, bool collective, size_t record)
258      {
259        int grpid = this->getCurrentGroup();
260        int varid = this->getVariable(name);
261
262        std::vector<StdSize> start(2), count(2);
263        start[0] = record;
264        count[0] = 1 ;
265        start[1] = 0;
266        count[1] = 2;
267
268        timeAxisBounds.resize(2, 1);
269
270        if (this->wmpi && collective)
271          CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
272        if (this->wmpi && !collective)
273          CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
274
275        CNetCdfInterface::getVaraType(grpid, varid, &start[0], &count[0], timeAxisBounds.dataFirst());
276      }
277
278
279
280      const CONetCDF4::CONetCDF4Path& CONetCDF4::getCurrentPath(void) const
281      { return this->path; }
282
283      void CONetCDF4::setCurrentPath(const CONetCDF4Path& path)
284      { this->path = path; }
285
286      //---------------------------------------------------------------
287
288      int CONetCDF4::addGroup(const StdString& name)
289      {
290         int retvalue = 0;
291         int grpid = this->getCurrentGroup();
292         CNetCdfInterface::defGrp(grpid, name, retvalue);
293         return retvalue;
294      }
295
296      //---------------------------------------------------------------
297
298      int CONetCDF4::addDimension(const StdString& name, const StdSize size)
299      {
300         int retvalue = 0;
301         int grpid = this->getCurrentGroup();
302         if (size != UNLIMITED_DIM)
303            CNetCdfInterface::defDim(grpid, name, size, retvalue);
304         else
305            CNetCdfInterface::defDim(grpid, name, NC_UNLIMITED, retvalue);
306         return retvalue;
307      }
308
309      //---------------------------------------------------------------
310
311      int CONetCDF4::addVariable(const StdString& name, nc_type type,
312                                 const std::vector<StdString>& dim, bool defineChunking)
313      {
314         int varid = 0;
315         std::vector<int> dimids;
316         std::vector<StdSize> dimsizes;
317         int dimSize = dim.size();
318
319         StdSize size;
320
321         int grpid = this->getCurrentGroup();
322
323         std::vector<StdString>::const_iterator it = dim.begin(), end = dim.end();
324
325         for (int idx = 0; it != end; it++, ++idx)
326         {
327            const StdString& dimid = *it;
328            dimids.push_back(this->getDimension(dimid));
329            CNetCdfInterface::inqDimLen(grpid, this->getDimension(dimid), size);
330            if (size == NC_UNLIMITED) size = 1;
331            dimsizes.push_back(size);
332         }
333
334         CNetCdfInterface::defVar(grpid, name, type, dimids.size(), &dimids[0], varid);
335
336         if (defineChunking) {
337           int storageType = (0 == dimSize) ? NC_CONTIGUOUS : NC_CHUNKED;
338           CNetCdfInterface::defVarChunking(grpid, varid, storageType, &dimsizes[0]);
339           CNetCdfInterface::defVarFill(grpid, varid, true, NULL);
340         }
341
342         
343         return varid;
344      }
345
346      //---------------------------------------------------------------
347
348      int CONetCDF4::addChunk(CField* field, nc_type type,
349                              const std::vector<StdString>& dim, int compressionLevel)
350      {
351         const StdString& name = field->getFieldOutputName();
352         int varid = 0;
353         std::vector<StdSize> dimsizes;
354         int dimSize = dim.size();
355         
356         StdSize size;
357         StdSize totalSize;
358
359         // default chunk size         
360         StdSize maxSize = 1024 * 1024 * 20; // = 20 Mo (exp using large NEMO like grids)
361         StdSize targetSize = maxSize;
362         if (!field->chunking_blocksize_target.isEmpty())
363         {
364           targetSize = field->chunking_blocksize_target.getValue()*1024*1024;
365         }
366         StdSize recordSize = 1; //sizeof(type);
367         if (field->prec.isEmpty()) recordSize *= 4;
368         else recordSize *= field->prec;
369
370         int grpid = this->getCurrentGroup();
371
372         std::vector<StdString>::const_iterator it = dim.begin(), end = dim.end();
373
374         for (int idx = 0; it != end; it++, ++idx)
375         {
376            const StdString& dimid = *it;
377            CNetCdfInterface::inqDimLen(grpid, this->getDimension(dimid), size);
378            if (size == NC_UNLIMITED) size = 1;
379            recordSize *= size;
380            dimsizes.push_back(size);
381         }
382         double chunkingRatio = (double)recordSize / (double)targetSize;
383
384         varid = this->getVariable(name);
385
386         // The classic NetCDF format does not support chunking nor fill parameters
387         if (!useClassicFormat)
388         {
389            // Browse field's elements (domain, axis) and NetCDF meta-data to retrieve corresponding chunking coefficients
390            //   in the file order !
391            CGrid* grid = field->getGrid();
392            std::vector<CDomain*> domains = grid->getDomains();
393            std::vector<CAxis*> axis = grid->getAxis();
394            bool singleDomain = (field->getRelFile()->nbDomains == 1);
395
396            std::vector<double> userChunkingWeights; // store chunking coefficients defined by users
397            std::vector<StdString>::const_reverse_iterator itId = dim.rbegin(); // NetCDF is fed using dim, see this::addVariable()
398            int elementIdx(0);
399            int outerAxis(-1), outerDomJ(-1), outerDomI(-1);
400            for (vector<StdSize>::reverse_iterator itDim = dimsizes.rbegin(); itDim != dimsizes.rend(); ++itDim, ++itId, ++elementIdx)
401            {
402              bool isAxis(false);
403              for ( auto ax : axis )
404              {
405                StdString axisDim;
406                // Rebuild axis name from axis before comparing
407                if (ax->dim_name.isEmpty()) axisDim = ax->getAxisOutputName();
408                else axisDim=ax->dim_name.getValue();
409                if (axisDim == *itId)
410                {
411                  if (!ax->chunking_weight.isEmpty()) userChunkingWeights.push_back( ax->chunking_weight.getValue() );
412                  else userChunkingWeights.push_back( 0. );
413                  isAxis = true;
414                  outerAxis = elementIdx; // Going backward in dimsizes, overwriting will keep outer
415                  break;
416                }
417              } // end scanning axis
418              bool isDomain(false);
419              for ( auto dom : domains )
420              {
421                StdString axisDim;
422                // Rebuild axis I name from domain before comparing
423                if (!dom->dim_i_name.isEmpty()) axisDim = dom->dim_i_name.getValue();
424                else
425                {
426                  if (dom->type==CDomain::type_attr::curvilinear)  axisDim="x";
427                  if (dom->type==CDomain::type_attr::unstructured) axisDim="cell";
428                  if (dom->type==CDomain::type_attr::rectilinear)  axisDim="lon";
429                }
430                if (!singleDomain) axisDim+="_"+dom->getDomainOutputName();
431                if (axisDim == *itId)
432                {
433                  if (!dom->chunking_weight_i.isEmpty()) userChunkingWeights.push_back( dom->chunking_weight_i.getValue() );
434                  else userChunkingWeights.push_back( 0. );
435                  isDomain = true;
436                  outerDomI = elementIdx; // Going backward in dimsizes, overwriting will keep outer
437                  break;
438                }
439                // Rebuild axis J name from domain before comparing
440                if (!dom->dim_j_name.isEmpty()) axisDim = dom->dim_j_name.getValue();
441                else {
442                  if (dom->type==CDomain::type_attr::curvilinear)  axisDim="y";
443                  if (dom->type==CDomain::type_attr::rectilinear)  axisDim="lat";
444                }
445                if (!singleDomain) axisDim+="_"+dom->getDomainOutputName();
446                if (axisDim == *itId)
447                {
448                  if (!dom->chunking_weight_j.isEmpty()) userChunkingWeights.push_back( dom->chunking_weight_j.getValue() );
449                  else userChunkingWeights.push_back( 0. );
450                  outerDomJ = elementIdx; // Going backward in dimsizes, overwriting will keep outer
451                  isDomain = true;
452                  break;
453                }
454              } // end scanning domain
455              // No chunking applied on scalars or time
456              if ((!isAxis)&&(!isDomain))
457              {
458                userChunkingWeights.push_back( 0. );
459              }
460            }
461
462            double sumChunkingWeights(0);
463            for (int i=0;i<userChunkingWeights.size();i++) sumChunkingWeights += userChunkingWeights[i];
464            if ( (!sumChunkingWeights) && (chunkingRatio > 1) )
465            {
466              if (outerAxis!=-1) userChunkingWeights[outerAxis] = 1;      // chunk along outer axis
467              else if (outerDomJ!=-1) userChunkingWeights[outerDomJ] = 1; // if no axis ? -> along j
468              else if (outerDomI!=-1) userChunkingWeights[outerDomI] = 1; // if no j      -> along i
469              else {;}
470            }
471
472            int countChunkingDims(0); // number of dimensions on which chunking is operated : algo uses pow(value, 1/countChunkingDims)
473            double normalizingWeight(0); // use to relativize chunking coefficients for all dimensions
474            for (int i=0;i<userChunkingWeights.size();i++)
475              if (userChunkingWeights[i]>0.)
476              {
477                countChunkingDims++;
478                normalizingWeight = userChunkingWeights[i];
479              }
480            if (normalizingWeight!=0) // no chunk for scalar
481            {
482              std::vector<double> chunkingRatioPerDims; // will store coefficients used to compute chunk size
483              double productRatios = 1; // last_coeff = pow( shrink_ratio / (product of all ratios), 1/countChunkingDims )
484              for (int i=0;i<userChunkingWeights.size();i++)
485              {
486                chunkingRatioPerDims.push_back( userChunkingWeights[i] / normalizingWeight );
487                if (chunkingRatioPerDims[i]) productRatios *= chunkingRatioPerDims[i];
488              }
489              for (int i=0;i<userChunkingWeights.size();i++)
490              {
491                chunkingRatioPerDims[i] *= pow( chunkingRatio / productRatios, 1./countChunkingDims );
492              }
493             
494              std::vector<double>::iterator itChunkingRatios = chunkingRatioPerDims.begin();
495              //itId = dim.rbegin();
496              double correctionFromPreviousDim = 1.;
497              for (vector<StdSize>::reverse_iterator itDim = dimsizes.rbegin(); itDim != dimsizes.rend(); ++itDim, ++itChunkingRatios, ++itId)
498              {
499                *itChunkingRatios *= correctionFromPreviousDim;
500                correctionFromPreviousDim = 1;
501                if (*itChunkingRatios > 1) // else target larger than size !
502                {
503                  StdSize dimensionSize = *itDim;
504                  //info(0) << *itId << " " << *itDim << " " << *itChunkingRatios << " " << (*itDim)/(*itChunkingRatios) << endl;
505                  *itDim = ceil( *itDim / ceil(*itChunkingRatios) );
506                  correctionFromPreviousDim = *itChunkingRatios/ ((double)dimensionSize/(*itDim));
507                }
508              }
509            }
510            int storageType = (0 == dimSize) ? NC_CONTIGUOUS : NC_CHUNKED;
511            CNetCdfInterface::defVarChunking(grpid, varid, storageType, &dimsizes[0]);
512            CNetCdfInterface::defVarFill(grpid, varid, true, NULL);
513         }
514         
515         return varid;
516      }
517
518      //---------------------------------------------------------------
519
520      void CONetCDF4::setCompressionLevel(const StdString& varname, const StdString& compressionType, int compressionLevel, const CArray<double,1>& compressionParams)
521      {
522         if (compressionLevel < 0 || compressionLevel > 9)
523           ERROR("void CONetCDF4::setCompressionLevel(const StdString& varname, int compressionLevel)",
524                 "Invalid compression level for variable \"" << varname << "\", the value should range between 0 and 9.");
525#ifndef PARALLEL_COMPRESSION
526         if ( ((compressionLevel)||(compressionParams.numElements())) && wmpi)
527           ERROR("void CONetCDF4::setCompressionLevel(const StdString& varname, int compressionLevel)",
528                 "Impossible to use compression for variable \"" << varname << "\" when using parallel mode.");
529#endif
530         int grpid = this->getCurrentGroup();
531         int varid = this->getVariable(varname);
532         if (compressionType=="None")
533         {
534         }
535         else if (compressionType=="gzip")
536         {
537           CNetCdfInterface::defVarDeflate(grpid, varid, compressionLevel);
538         }
539         else
540         {
541           size_t cd_nelmts;
542           unsigned int* cd_values = NULL;
543           if (compressionType=="SZ")
544           {
545             CONetCDF4Plugin::interpretParametersSZ(compressionParams, &cd_nelmts, &cd_values);
546             CNetCdfInterface::defVarFilter(grpid, varid, 32017, cd_nelmts, cd_values);
547           }
548           else if (compressionType=="ZFP")
549           {
550             CONetCDF4Plugin::interpretParametersZFP(compressionParams, &cd_nelmts, &cd_values);
551             CNetCdfInterface::defVarFilter(grpid, varid, 32013, cd_nelmts, cd_values);
552           }
553           else
554           {
555               ERROR("void CONetCDF4::setCompressionLevel(...)", "compression_type = " << compressionType << " is not managed");
556           }
557           if (cd_values!=NULL) delete [] cd_values;
558         }
559                     
560      }
561
562      //---------------------------------------------------------------
563
564      template <>
565      void CONetCDF4::addAttribute(const StdString& name, const StdString& value, const StdString* varname)
566      {
567         int grpid = this->getCurrentGroup();
568         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
569         CNetCdfInterface::putAttType(grpid, varid, name, value.size(), value.c_str());
570      }
571
572      //---------------------------------------------------------------
573
574      template <>
575      void CONetCDF4::addAttribute(const StdString& name, const double& value, const StdString* varname)
576      {
577         int grpid = this->getCurrentGroup();
578         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
579         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
580      }
581
582      template <>
583      void CONetCDF4::addAttribute(const StdString& name, const CArray<double,1>& value, const StdString* varname)
584      {
585         int grpid = this->getCurrentGroup();
586         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
587         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
588      }
589      //---------------------------------------------------------------
590
591      template <>
592      void CONetCDF4::addAttribute(const StdString& name, const float& value, const StdString* varname)
593      {
594         int grpid = this->getCurrentGroup();
595         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
596         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
597      }
598
599      template <>
600      void CONetCDF4::addAttribute(const StdString& name, const CArray<float,1>& value, const StdString* varname)
601      {
602         int grpid = this->getCurrentGroup();
603         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
604         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
605      }
606
607      //---------------------------------------------------------------
608
609      template <>
610      void CONetCDF4::addAttribute(const StdString& name, const int& value, const StdString* varname)
611      {
612         int grpid = this->getCurrentGroup();
613         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
614         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
615      }
616
617      template <>
618      void CONetCDF4::addAttribute(const StdString& name, const CArray<int,1>& value, const StdString* varname)
619      {
620         int grpid = this->getCurrentGroup();
621         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
622         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
623      }
624
625      template <>
626      void CONetCDF4::addAttribute(const StdString& name, const short int& value, const StdString* varname)
627      {
628         int grpid = this->getCurrentGroup();
629         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
630         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
631      }
632
633      template <>
634      void CONetCDF4::addAttribute(const StdString& name, const CArray<short int,1>& value, const StdString* varname)
635      {
636         int grpid = this->getCurrentGroup();
637         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
638         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
639      }
640
641      template <>
642      void CONetCDF4::addAttribute(const StdString& name, const long int& value, const StdString* varname)
643      {
644         int grpid = this->getCurrentGroup();
645         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
646         CNetCdfInterface::putAttType(grpid, varid, name, 1, &value);
647      }
648
649      template <>
650      void CONetCDF4::addAttribute(const StdString& name, const CArray<long int,1>& value, const StdString* varname)
651      {
652         int grpid = this->getCurrentGroup();
653         int varid = (varname == NULL) ? NC_GLOBAL : this->getVariable(*varname);
654         CNetCdfInterface::putAttType(grpid, varid, name, value.numElements(), value.dataFirst());
655      }
656
657      //---------------------------------------------------------------
658
659      void CONetCDF4::getWriteDataInfos(const StdString& name, StdSize record, StdSize& array_size,
660                                        std::vector<StdSize>& sstart,
661                                        std::vector<StdSize>& scount,
662                                        const std::vector<StdSize>* start,
663                                        const std::vector<StdSize>* count)
664      {
665         std::vector<std::size_t> sizes  = this->getDimensions(name);
666         if (sizes.size()==0) 
667         {
668           
669            if ((start != NULL) && (count != NULL) && start->size()==1 && count->size()==1) // pur scalar case
670              array_size*=(*count)[0] ;
671            else array_size=1 ;
672         }
673         else
674         {
675           std::vector<std::string> iddims = this->getDimensionsIdList (&name);
676           std::vector<std::size_t>::const_iterator
677           it  = sizes.begin(), end = sizes.end();
678           int i = 0;
679
680           if (iddims.begin()->compare(timeCounterName) == 0)
681           {
682             sstart.push_back(record);
683             scount.push_back(1);
684             if ((start == NULL) && (count == NULL)) i++;
685             it++;
686             if (it==end)
687             {
688               if ((start != NULL) && (count != NULL) && start->size()==1 && count->size()==1) // pur scalar case
689               {
690                 scount[0]=(*count)[0] ;
691                 array_size *= (*count)[0];
692               }
693             }
694           }
695           
696           for (;it != end; it++)
697           {
698              if ((start != NULL) && (count != NULL))
699              {
700                 sstart.push_back((*start)[i]);
701                 scount.push_back((*count)[i]);
702                 array_size *= (*count)[i];
703                 i++;
704              }
705              else
706              {
707                 sstart.push_back(0);
708                 scount.push_back(sizes[i]);
709                 array_size *= sizes[i];
710                 i++;
711              }
712           }
713
714         }
715      }
716
717
718      template <>
719      void CONetCDF4::writeData_(int grpid, int varid,
720                                 const std::vector<StdSize>& sstart,
721                                 const std::vector<StdSize>& scount, const double* data)
722      {
723         CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
724      }
725
726      //---------------------------------------------------------------
727
728      template <>
729      void CONetCDF4::writeData_(int grpid, int varid,
730                                 const std::vector<StdSize>& sstart,
731                                 const std::vector<StdSize>& scount, char* data)
732      {
733          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
734      }
735     
736      template <>
737      void CONetCDF4::writeData_(int grpid, int varid,
738                                 const std::vector<StdSize>& sstart,
739                                 const std::vector<StdSize>& scount, const short* data)
740      {
741          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
742      }
743   
744      template <>
745      void CONetCDF4::writeData_(int grpid, int varid,
746                                 const std::vector<StdSize>& sstart,
747                                 const std::vector<StdSize>& scount, const int* data)
748      {
749          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
750      }
751      //---------------------------------------------------------------
752
753      template <>
754      void CONetCDF4::writeData_(int grpid, int varid,
755                                 const std::vector<StdSize>& sstart,
756                                 const std::vector<StdSize>& scount, const size_t* data)
757      {
758          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
759      }
760      //---------------------------------------------------------------
761
762      template <>
763      void CONetCDF4::writeData_(int grpid, int varid,
764                                 const std::vector<StdSize>& sstart,
765                                 const std::vector<StdSize>& scount, const float* data)
766      {
767          CNetCdfInterface::putVaraType(grpid, varid, &sstart[0], &scount[0], data);
768      }
769
770      //---------------------------------------------------------------
771
772      void CONetCDF4::writeData(const CArray<int, 2>& data, const StdString& name)
773      {
774         int grpid = this->getCurrentGroup();
775         int varid = this->getVariable(name);
776         
777         StdSize array_size = 1;
778         std::vector<StdSize> sstart, scount;
779
780         this->getWriteDataInfos(name, 0, array_size,  sstart, scount, NULL, NULL);
781
782         this->writeData_(grpid, varid, sstart, scount, data.dataFirst());
783
784      }
785
786      void CONetCDF4::writeTimeAxisData(const CArray<double, 1>& data, const StdString& name,
787                                        bool collective, StdSize record, bool isRoot)
788      {
789         int grpid = this->getCurrentGroup();
790         int varid = this->getVariable(name);
791
792         map<int,size_t>::iterator it=timeAxis.find(varid);
793         if (it == timeAxis.end()) timeAxis[varid] = record;
794         else
795         {
796           if (it->second >= record) return;
797           else it->second =record;
798         }
799
800         StdSize array_size = 1;
801         std::vector<StdSize> sstart, scount;
802
803         if (this->wmpi && collective)
804            CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
805         if (this->wmpi && !collective)
806            CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
807
808         this->getWriteDataInfos(name, record, array_size,  sstart, scount, NULL, NULL);
809         this->writeData_(grpid, varid, sstart, scount, data.dataFirst());
810       }
811
812      void CONetCDF4::writeTimeAxisDataBounds(const CArray<double, 1>& data, const StdString& name,
813                                        bool collective, StdSize record, bool isRoot)
814      {
815         int grpid = this->getCurrentGroup();
816         int varid = this->getVariable(name);
817
818         map<int,size_t>::iterator it=timeAxis.find(varid);
819         if (it == timeAxis.end()) timeAxis[varid] = record;
820         else
821         {
822           if (it->second >= record) return;
823           else it->second =record;
824         }
825
826         StdSize array_size = 1;
827         std::vector<StdSize> sstart, scount;
828
829         if (this->wmpi && collective)
830            CNetCdfInterface::varParAccess(grpid, varid, NC_COLLECTIVE);
831         if (this->wmpi && !collective)
832            CNetCdfInterface::varParAccess(grpid, varid, NC_INDEPENDENT);
833
834         this->getWriteDataInfos(name, record, array_size,  sstart, scount, NULL, NULL);
835         this->writeData_(grpid, varid, sstart, scount, data.dataFirst());
836       }
837
838
839      //---------------------------------------------------------------
840
841      bool CONetCDF4::varExist(const StdString& varname)
842      {
843         int grpid = this->getCurrentGroup();
844         return CNetCdfInterface::isVarExisted(grpid, varname);
845      }
846
847      bool CONetCDF4::dimExist(const StdString& dimname)
848      {
849         int grpid = this->getCurrentGroup();
850         return CNetCdfInterface::isDimExisted(grpid, dimname);
851      }
852
853      void CONetCDF4::sync(void)
854      {
855         CNetCdfInterface::sync(this->ncidp);
856      }
857      ///--------------------------------------------------------------
858 } // namespace xios
Note: See TracBrowser for help on using the repository browser.