source: XIOS3/trunk/src/io/nc4_data_output.cpp @ 2628

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

New timers integration/reporting

  • 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
  • Property svn:executable set to *
File size: 129.6 KB
RevLine 
[219]1#include "nc4_data_output.hpp"
2
[352]3#include "attribute_template.hpp"
4#include "group_template.hpp"
[219]5
6#include "file.hpp"
7#include "calendar.hpp"
[278]8#include "context.hpp"
[300]9#include "context_server.hpp"
[498]10#include "netCdfException.hpp"
11#include "exception.hpp"
[1158]12#include "timer.hpp"
13#include "uuid.hpp"
[2600]14
15#include <limits.h>
16#define X_FLOAT_MAX     FLT_MAX
17#define X_FLOAT_MIN     FLT_MIN
18#define X_SHORT_MAX     SHRT_MAX
19#define X_SHORT_MIN     SHRT_MIN
20
[335]21namespace xios
[219]22{
[2628]23      extern CLogType logProfile ;
[878]24      /// ////////////////////// Dfinitions ////////////////////// ///
[219]25      CNc4DataOutput::CNc4DataOutput
[1158]26         (CFile* file, const StdString & filename, bool exist)
[219]27            : SuperClass()
28            , SuperClassWriter(filename, exist)
29            , filename(filename)
[2389]30            , file(file),hasTimeInstant(false),hasTimeCentered(false), timeCounterType(none), relAxis_(), relDomains_()
[219]31      {
[1158]32        SuperClass::type = MULTI_FILE;
[1456]33        compressionLevel= file->compression_level.isEmpty() ? 0 :file->compression_level ;
[219]34      }
35
36      CNc4DataOutput::CNc4DataOutput
[1158]37         (CFile* file, const StdString & filename, bool exist, bool useClassicFormat, bool useCFConvention,
[1639]38          MPI_Comm comm_file, bool multifile, bool isCollective, const StdString& timeCounterName)
[219]39            : SuperClass()
[878]40            , SuperClassWriter(filename, exist, useClassicFormat, useCFConvention, &comm_file, multifile, timeCounterName)
[379]41            , comm_file(comm_file)
[219]42            , filename(filename)
[335]43            , isCollective(isCollective)
[2389]44            , file(file),hasTimeInstant(false),hasTimeCentered(false), timeCounterType(none), relAxis_(), relDomains_()
[219]45      {
[1158]46        SuperClass::type = (multifile) ? MULTI_FILE : ONE_FILE;
[1459]47        if (file==NULL) compressionLevel = 0 ;
48        else compressionLevel= file->compression_level.isEmpty() ? 0 :file->compression_level ;
[219]49      }
50
51      CNc4DataOutput::~CNc4DataOutput(void)
[879]52    { /* Ne rien faire de plus */ }
[219]53
54      ///--------------------------------------------------------------
55
56      const StdString & CNc4DataOutput::getFileName(void) const
57      {
58         return (this->filename);
59      }
60
61      //---------------------------------------------------------------
62
[347]63      void CNc4DataOutput::writeDomain_(CDomain* domain)
[1622]64      TRY
[219]65      {
[1391]66        StdString lonName,latName ;
[1249]67
[2387]68        // Check that the name associated to the current element is not in conflict with an existing element (due to CGrid::duplicateSentGrid)
69        if (!domain->lonvalue.isEmpty() )
70        {
71          // The hash of the element will be associated to the default element name (= map key), and to the name really written
72          int globalHash = domain->computeAttributesHash( comm_file ); // Need a MPI_Comm to distribute without redundancy some attributs (value)
73       
74          StdString defaultNameKey = domain->getDomainOutputName();
75          if ( !relDomains_.count ( defaultNameKey ) )
76          {
77            // if defaultNameKey not in the map, write the element such as it is defined
78            relDomains_.insert( make_pair( defaultNameKey, make_pair(globalHash, domain) ) );
79          }
80          else // look if a hash associated this key is equal
81          {
82            bool elementIsInMap(false);
83            auto defaultNameKeyElements = relDomains_.equal_range( defaultNameKey );
84            for (auto it = defaultNameKeyElements.first; it != defaultNameKeyElements.second; it++)
85            {
86              if ( it->second.first == globalHash )
87              {
88                // if yes, associate the same ids to current element
[2389]89                domain->renameAttributesBeforeWriting( it->second.second );
[2387]90                elementIsInMap = true;
91              }
92            }
93            // if no : inheritance has been excessive, define new names and store it (could be used by another grid)
94            if (!elementIsInMap)  // ! in MAP
95            {
[2389]96              domain->renameAttributesBeforeWriting();
[2387]97              relDomains_.insert( make_pair( defaultNameKey, make_pair(globalHash, domain) ) ) ;         
98            }
99          }
100        }
101
[881]102        if (domain->type == CDomain::type_attr::unstructured)
103        {
104          if (SuperClassWriter::useCFConvention)
105            writeUnstructuredDomain(domain) ;
106          else
107            writeUnstructuredDomainUgrid(domain) ;
108          return ;
109        }
[488]110
[347]111         CContext* context = CContext::getCurrent() ;
[219]112         if (domain->IsWritten(this->filename)) return;
113         domain->checkAttributes();
[488]114
115         if (domain->isEmpty())
[881]116           if (SuperClass::type==MULTI_FILE) return;
[219]117
[2381]118         
[219]119         std::vector<StdString> dim0, dim1;
[772]120         StdString domid = domain->getDomainOutputName();
[318]121         StdString appendDomid  = (singleDomain) ? "" : "_"+domid ;
[706]122         if (isWrittenDomain(domid)) return ;
[774]123         else setWrittenDomain(domid);
[1132]124       
125         int nvertex = (domain->nvertex.isEmpty()) ? 0 : domain->nvertex;
[449]126
[488]127
[1158]128        StdString dimXid, dimYid ;
129
130        nc_type typePrec ;
131        if (domain->prec.isEmpty()) typePrec =  NC_FLOAT ;
132        else if (domain->prec==4)  typePrec =  NC_FLOAT ;
133        else if (domain->prec==8)   typePrec =  NC_DOUBLE ;
134         
[664]135         bool isRegularDomain = (domain->type == CDomain::type_attr::rectilinear);
[449]136         switch (domain->type)
[433]137         {
[449]138           case CDomain::type_attr::curvilinear :
[1391]139
140             if (domain->lon_name.isEmpty()) lonName = "nav_lon";
141             else lonName = domain->lon_name;
142
143             if (domain->lat_name.isEmpty()) latName = "nav_lat";
144             else latName = domain->lat_name;
145
[1430]146             if (domain->dim_i_name.isEmpty()) dimXid=StdString("x").append(appendDomid);
147             else dimXid=domain->dim_i_name.getValue() + appendDomid;
148
149             if (domain->dim_j_name.isEmpty()) dimYid=StdString("y").append(appendDomid);
150             else dimYid=domain->dim_j_name.getValue() + appendDomid;
151
[449]152             break ;
[1391]153
[664]154           case CDomain::type_attr::rectilinear :
[1391]155
[1430]156             if (domain->lon_name.isEmpty())
157             {
158               if (domain->dim_i_name.isEmpty())
159                   lonName = "lon";
160               else
161                 lonName = domain->dim_i_name.getValue();
162             }
[1391]163             else lonName = domain->lon_name;
164
[1430]165             if (domain->lat_name.isEmpty())
166             {
167               if (domain->dim_j_name.isEmpty())
168                 latName = "lat";
169               else
170                 latName = domain->dim_j_name.getValue();
171             }
[1391]172             else latName = domain->lat_name;
173             
[1430]174             if (domain->dim_i_name.isEmpty()) dimXid = lonName+appendDomid;
175             else dimXid = domain->dim_i_name.getValue()+appendDomid;
176
177             if (domain->dim_j_name.isEmpty()) dimYid = latName+appendDomid;
178             else dimYid = domain->dim_j_name.getValue()+appendDomid;
[449]179             break;
[488]180         }
181
[617]182         StdString dimVertId = StdString("nvertex").append(appendDomid);
183
[449]184         string lonid,latid,bounds_lonid,bounds_latid ;
[611]185         string areaId = "area" + appendDomid;
[219]186
[498]187         try
[219]188         {
[498]189           switch (SuperClass::type)
190           {
191              case (MULTI_FILE) :
192              {
193                 switch (domain->type)
194                 {
195                   case CDomain::type_attr::curvilinear :
196                     dim0.push_back(dimYid); dim0.push_back(dimXid);
[1415]197                     lonid = lonName+appendDomid;
198                     latid = latName+appendDomid;
[498]199                     break ;
[664]200                   case CDomain::type_attr::rectilinear :
[1415]201                     lonid = lonName+appendDomid;
202                     latid = latName+appendDomid;
[498]203                     dim0.push_back(dimYid);
204                     dim1.push_back(dimXid);
205                     break;
206                 }
[1430]207                 if (!domain->bounds_lon_name.isEmpty()) bounds_lonid = domain->bounds_lon_name;
208                 else bounds_lonid = "bounds_"+lonName+appendDomid;
209                 if (!domain->bounds_lat_name.isEmpty()) bounds_latid = domain->bounds_lat_name;
210                 else bounds_latid = "bounds_"+latName+appendDomid;
[488]211
[2507]212                 SuperClassWriter::addDimension(dimXid, domain->niValue_);
213                 SuperClassWriter::addDimension(dimYid, domain->njValue_);
[488]214
[617]215                 if (domain->hasBounds)
216                   SuperClassWriter::addDimension(dimVertId, domain->nvertex);
217
[1853]218                 if (context->intraCommSize_ > 1)
[498]219                 {
[2507]220                   this->writeLocalAttributes(domain->ibeginValue_,
221                                              domain->niValue_,
222                                              domain->jbeginValue_,
223                                              domain->njValue_,
[616]224                                              appendDomid);
[488]225
[628]226                   if (singleDomain)
227                    this->writeLocalAttributes_IOIPSL(dimXid, dimYid,
[2507]228                                                      domain->ibeginValue_,
229                                                      domain->niValue_,
230                                                      domain->jbeginValue_,
231                                                      domain->njValue_,
[628]232                                                      domain->ni_glo,domain->nj_glo,
[1853]233                                                      context->intraCommRank_,context->intraCommSize_);
[449]234                 }
[488]235
[665]236                 if (domain->hasLonLat)
[498]237                 {
[665]238                   switch (domain->type)
239                   {
240                     case CDomain::type_attr::curvilinear :
[1456]241                       SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
242                       SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
[665]243                       break ;
244                      case CDomain::type_attr::rectilinear :
[1456]245                        SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
246                        SuperClassWriter::addVariable(lonid, typePrec, dim1, compressionLevel);
[665]247                        break ;
248                   }
[488]249
[665]250                   this->writeAxisAttributes(lonid, isRegularDomain ? "X" : "", "longitude", "Longitude", "degrees_east", domid);
251                   this->writeAxisAttributes(latid, isRegularDomain ? "Y" : "", "latitude", "Latitude", "degrees_north", domid);
[219]252
[665]253                   if (domain->hasBounds)
254                   {
255                     SuperClassWriter::addAttribute("bounds", bounds_lonid, &lonid);
256                     SuperClassWriter::addAttribute("bounds", bounds_latid, &latid);
[617]257
[665]258                     dim0.clear();
259                     dim0.push_back(dimYid);
260                     dim0.push_back(dimXid);
261                     dim0.push_back(dimVertId);
[1456]262                     SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
263                     SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
[665]264                   }
[617]265                 }
266
[498]267                 dim0.clear();
[616]268                 dim0.push_back(dimYid);
[498]269                 dim0.push_back(dimXid);
[219]270
[611]271                 if (domain->hasArea)
272                 {
[1456]273                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
[614]274                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
[611]275                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
276                 }
277
[498]278                 SuperClassWriter::definition_end();
[449]279
[665]280                 if (domain->hasLonLat)
[498]281                 {
[665]282                   switch (domain->type)
283                   {
[1129]284                     case CDomain::type_attr::curvilinear :                       
[1930]285                       SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0);
286                       SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0);
[665]287                       break;
288                     case CDomain::type_attr::rectilinear :
[2550]289                       //CArray<double,1> lat = domain->latvalue(Range(fromStart,toEnd,domain->ni)) ;
290                       CArray<double,1> lat;
291                       lat.resize( domain->njValue_);
292                       for (int j=0;j<domain->njValue_;j++) lat(j) = domain->latvalue(j*domain->niValue_);
[665]293                       SuperClassWriter::writeData(CArray<double,1>(lat.copy()), latid, isCollective, 0);
[2550]294                       //CArray<double,1> lon = domain->lonvalue(Range(0,domain->ni-1)) ;
295                       CArray<double,1> lon = domain->lonvalue(Range(0,domain->niValue_-1));
[665]296                       SuperClassWriter::writeData(CArray<double,1>(lon.copy()), lonid, isCollective, 0);
297                       break;
298                   }
[611]299
[665]300                   if (domain->hasBounds)
301                   {
[1930]302                     SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0);
303                     SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0);
[665]304                   }
[617]305                 }
306
[611]307                 if (domain->hasArea)
[1129]308                 {
[1930]309                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0);                   
[1129]310                 }
311
[498]312                 SuperClassWriter::definition_start();
[219]313
[498]314                 break;
315              }
316              case (ONE_FILE) :
317              {
[1553]318                SuperClassWriter::addDimension(dimXid, domain->ni_glo);
319                SuperClassWriter::addDimension(dimYid, domain->nj_glo);
[286]320
[617]321                 if (domain->hasBounds)
322                   SuperClassWriter::addDimension(dimVertId, domain->nvertex);
323
[665]324                 if (domain->hasLonLat)
[498]325                 {
[665]326                   switch (domain->type)
327                   {
328                     case CDomain::type_attr::curvilinear :
329                       dim0.push_back(dimYid); dim0.push_back(dimXid);
[1415]330                       lonid = lonName+appendDomid;
331                       latid = latName+appendDomid;
[1456]332                       SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
333                       SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
[665]334                       break;
[449]335
[665]336                     case CDomain::type_attr::rectilinear :
337                       dim0.push_back(dimYid);
338                       dim1.push_back(dimXid);
[1415]339                       lonid = lonName+appendDomid;
340                       latid = latName+appendDomid;
[1456]341                       SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
342                       SuperClassWriter::addVariable(lonid, typePrec, dim1, compressionLevel);
[665]343                       break;
344                   }
[1430]345                   if (!domain->bounds_lon_name.isEmpty()) bounds_lonid = domain->bounds_lon_name;
346                   else bounds_lonid = "bounds_"+lonName+appendDomid;
347                   if (!domain->bounds_lat_name.isEmpty()) bounds_latid = domain->bounds_lat_name;
348                   else bounds_latid = "bounds_"+latName+appendDomid;
[665]349
350                   this->writeAxisAttributes
351                      (lonid, isRegularDomain ? "X" : "", "longitude", "Longitude", "degrees_east", domid);
352                   this->writeAxisAttributes
353                      (latid, isRegularDomain ? "Y" : "", "latitude", "Latitude", "degrees_north", domid);
354
355                   if (domain->hasBounds)
356                   {
357                     SuperClassWriter::addAttribute("bounds", bounds_lonid, &lonid);
358                     SuperClassWriter::addAttribute("bounds", bounds_latid, &latid);
359
360                     dim0.clear();
[498]361                     dim0.push_back(dimYid);
[665]362                     dim0.push_back(dimXid);
363                     dim0.push_back(dimVertId);
[1456]364                     SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
365                     SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
[665]366                   }
[498]367                 }
[611]368
369                 if (domain->hasArea)
370                 {
371                   dim0.clear();
372                   dim0.push_back(dimYid); dim0.push_back(dimXid);
[1456]373                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
[614]374                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
[611]375                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
376                   dim0.clear();
377                 }
378
379                 SuperClassWriter::definition_end();
[286]380
[498]381                 switch (domain->type)
[384]382                 {
[498]383                   case CDomain::type_attr::curvilinear :
[449]384                   {
[498]385                     std::vector<StdSize> start(2) ;
386                     std::vector<StdSize> count(2) ;
[2507]387                     start[1]=domain->ibeginValue_;
388                     start[0]=domain->jbeginValue_;
389                     count[1]=domain->niValue_ ; count[0]=domain->njValue_ ;
[488]390
[665]391                     if (domain->hasLonLat)
392                     {
[1930]393                       SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0,&start,&count);
394                       SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0,&start,&count);
[665]395                     }
[498]396                     break;
397                   }
[664]398                   case CDomain::type_attr::rectilinear :
[449]399                   {
[665]400                     if (domain->hasLonLat)
[498]401                     {
[665]402                       std::vector<StdSize> start(1) ;
403                       std::vector<StdSize> count(1) ;
[1930]404                       
[2507]405                       start[0]=domain->jbeginValue_;
406                       count[0]=domain->njValue_;
[2394]407                       CArray<double,1> lat;
[2507]408                       lat.resize( domain->njValue_);
409                       for (int j=0;j<domain->njValue_;j++) lat(j) = domain->latvalue(j*domain->niValue_);
[1930]410                       SuperClassWriter::writeData(CArray<double,1>(lat.copy()), latid, isCollective, 0,&start,&count);
[665]411
[2507]412                       start[0]=domain->ibeginValue_;
413                       count[0]=domain->niValue_;
[2613]414                       CArray<double,1> lon;
415                       lon.resize( domain->niValue_);
416                       for (int i=0;i<domain->niValue_;i++) lon(i) = domain->lonvalue(i);
[1930]417                       SuperClassWriter::writeData(CArray<double,1>(lon.copy()), lonid, isCollective, 0,&start,&count);
[498]418                     }
419                     break;
[449]420                   }
[384]421                 }
[611]422
[617]423                 if (domain->hasBounds)
424                 {
425                   std::vector<StdSize> start(3);
426                   std::vector<StdSize> count(3);
427                   if (domain->isEmpty())
428                   {
429                     start[2] = start[1] = start[0] = 0;
430                     count[2] = count[1] = count[0] = 0;
431                   }
432                   else
433                   {
434                     start[2] = 0;
[2507]435                     start[1] = domain->ibeginValue_;
436                     start[0] = domain->jbeginValue_;
[1099]437                     count[2] = domain->nvertex;
[2507]438                     count[1] = domain->niValue_;
439                     count[0] = domain->njValue_;
[617]440                   }
[1143]441                 
[1930]442                   SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0, &start, &count); // will probably not working for rectilinear
443                   SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0, &start, &count);
[617]444                 }
445
[611]446                 if (domain->hasArea)
447                 {
448                   std::vector<StdSize> start(2);
449                   std::vector<StdSize> count(2);
450
[2507]451                   start[1] = domain->ibeginValue_;
452                   start[0] = domain->jbeginValue_;
453                   count[1] = domain->niValue_;
454                   count[0] = domain->njValue_;
[1143]455                   
[1930]456                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0, &start, &count);
[611]457                 }
458
[498]459                 SuperClassWriter::definition_start();
460                 break;
461              }
462              default :
463                 ERROR("CNc4DataOutput::writeDomain(domain)",
464                       << "[ type = " << SuperClass::type << "]"
465                       << " not implemented yet !");
466           }
[449]467         }
[498]468         catch (CNetCdfException& e)
469         {
470           StdString msg("On writing the domain : ");
471           msg.append(domid); msg.append("\n");
472           msg.append("In the context : ");
473           msg.append(context->getId()); msg.append("\n");
474           msg.append(e.what());
475           ERROR("CNc4DataOutput::writeDomain_(CDomain* domain)", << msg);
476         }
477
[449]478         domain->addRelFile(this->filename);
479      }
[1622]480      CATCH
[449]481
[879]482    //--------------------------------------------------------------
[878]483
[879]484    void CNc4DataOutput::writeUnstructuredDomainUgrid(CDomain* domain)
485    {
486      CContext* context = CContext::getCurrent() ;
[878]487
[879]488      if (domain->IsWritten(this->filename)) return;
[1494]489
490      StdString domid = domain->getDomainOutputName();
491
492      // The first domain for the same mesh that will be written is that with the highest value of nvertex.
493      // Thus the entire mesh connectivity will be generated at once.
494      if (isWrittenDomain(domid)) return ;
495      else setWrittenDomain(domid);
496
[879]497      domain->checkAttributes();
498      if (domain->isEmpty())
499        if (SuperClass::type==MULTI_FILE) return ;
[878]500
[1158]501     nc_type typePrec ;
502     if (domain->prec.isEmpty()) typePrec =  NC_FLOAT ;
503     else if (domain->prec==4)  typePrec =  NC_FLOAT ;
504     else if (domain->prec==8)   typePrec =  NC_DOUBLE ;
505
[879]506      std::vector<StdString> dim0;
507      StdString domainName = domain->name;
[878]508
[879]509      StdString node_x = domainName + "_node_x";
510      StdString node_y = domainName + "_node_y";
[878]511
[879]512      StdString edge_x = domainName + "_edge_x";
513      StdString edge_y = domainName + "_edge_y";
514      StdString edge_nodes = domainName + "_edge_nodes";
[878]515
[879]516      StdString face_x = domainName + "_face_x";
517      StdString face_y = domainName + "_face_y";
518      StdString face_nodes = domainName + "_face_nodes";
[902]519      StdString face_edges = domainName + "_face_edges";
520      StdString edge_faces = domainName + "_edge_face_links";
521      StdString face_faces = domainName + "_face_links";
[878]522
[879]523      StdString dimNode = "n" + domainName + "_node";
524      StdString dimEdge = "n" + domainName + "_edge";
525      StdString dimFace = "n" + domainName + "_face";
526      StdString dimVertex = "n" + domainName + "_vertex";
527      StdString dimTwo = "Two";
[878]528
[879]529      if (!SuperClassWriter::dimExist(dimTwo)) SuperClassWriter::addDimension(dimTwo, 2);
[1494]530      dim0.clear();
531      SuperClassWriter::addVariable(domainName, NC_INT, dim0, compressionLevel);
532      SuperClassWriter::addAttribute("cf_role", StdString("mesh_topology"), &domainName);
533      SuperClassWriter::addAttribute("long_name", StdString("Topology data of 2D unstructured mesh"), &domainName);
534      SuperClassWriter::addAttribute("topology_dimension", 2, &domainName);
535      SuperClassWriter::addAttribute("node_coordinates", node_x + " " + node_y, &domainName);
[878]536
[879]537      try
538      {
539        switch (SuperClass::type)
540        {
541          case (ONE_FILE) :
542          {
543            // Adding nodes
544            if (domain->nvertex == 1)
545            {
546              if (!SuperClassWriter::varExist(node_x) || !SuperClassWriter::varExist(node_y))
547              {
[902]548                SuperClassWriter::addDimension(dimNode, domain->ni_glo);
[879]549                dim0.clear();
550                dim0.push_back(dimNode);
[1456]551                SuperClassWriter::addVariable(node_x, typePrec, dim0, compressionLevel);
[879]552                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &node_x);
[924]553                SuperClassWriter::addAttribute("long_name", StdString("Longitude of mesh nodes."), &node_x);
[879]554                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &node_x);
[1456]555                SuperClassWriter::addVariable(node_y, typePrec, dim0, compressionLevel);
[879]556                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &node_y);
[924]557                SuperClassWriter::addAttribute("long_name", StdString("Latitude of mesh nodes."), &node_y);
[879]558                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &node_y);
559              }
560            } // domain->nvertex == 1
[878]561
[879]562            // Adding edges and nodes, if nodes have not been defined previously
563            if (domain->nvertex == 2)
564            {
565              if (!SuperClassWriter::varExist(node_x) || !SuperClassWriter::varExist(node_y))
566              {
[924]567                SuperClassWriter::addDimension(dimNode, domain->mesh->nbNodesGlo);
[879]568                dim0.clear();
569                dim0.push_back(dimNode);
[1456]570                SuperClassWriter::addVariable(node_x, typePrec, dim0, compressionLevel);
[879]571                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &node_x);
[924]572                SuperClassWriter::addAttribute("long_name", StdString("Longitude of mesh nodes."), &node_x);
[879]573                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &node_x);
[1456]574                SuperClassWriter::addVariable(node_y, typePrec, dim0, compressionLevel);
[879]575                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &node_y);
[924]576                SuperClassWriter::addAttribute("long_name", StdString("Latitude of mesh nodes."), &node_y);
[879]577                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &node_y);
578              }
[924]579              SuperClassWriter::addAttribute("edge_node_connectivity", edge_nodes, &domainName);
580              SuperClassWriter::addAttribute("edge_coordinates", edge_x + " " + edge_y, &domainName);
581              SuperClassWriter::addDimension(dimEdge, domain->ni_glo);
582              dim0.clear();
583              dim0.push_back(dimEdge);
[1456]584              SuperClassWriter::addVariable(edge_x, typePrec, dim0, compressionLevel);
[924]585              SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &edge_x);
586              SuperClassWriter::addAttribute("long_name", StdString("Characteristic longitude of mesh edges."), &edge_x);
587              SuperClassWriter::addAttribute("units", StdString("degrees_east"), &edge_x);
[1456]588              SuperClassWriter::addVariable(edge_y, typePrec, dim0, compressionLevel);
[924]589              SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &edge_y);
590              SuperClassWriter::addAttribute("long_name", StdString("Characteristic latitude of mesh edges."), &edge_y);
591              SuperClassWriter::addAttribute("units", StdString("degrees_north"), &edge_y);
592              dim0.clear();
593              dim0.push_back(dimEdge);
594              dim0.push_back(dimTwo);
[1456]595              SuperClassWriter::addVariable(edge_nodes, NC_INT, dim0, compressionLevel);
[924]596              SuperClassWriter::addAttribute("cf_role", StdString("edge_node_connectivity"), &edge_nodes);
597              SuperClassWriter::addAttribute("long_name", StdString("Maps every edge/link to two nodes that it connects."), &edge_nodes);
598              SuperClassWriter::addAttribute("start_index", 0, &edge_nodes);
[879]599            } // domain->nvertex == 2
[878]600
[879]601            // Adding faces, edges, and nodes, if edges and nodes have not been defined previously
602            if (domain->nvertex > 2)
603            {
604              // Nodes
605              if (!SuperClassWriter::varExist(node_x) || !SuperClassWriter::varExist(node_y))
606              {
[924]607                SuperClassWriter::addDimension(dimNode, domain->mesh->nbNodesGlo);
[879]608                dim0.clear();
609                dim0.push_back(dimNode);
[1456]610                SuperClassWriter::addVariable(node_x, typePrec, dim0, compressionLevel);
[879]611                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &node_x);
[924]612                SuperClassWriter::addAttribute("long_name", StdString("Longitude of mesh nodes."), &node_x);
[879]613                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &node_x);
[1456]614                SuperClassWriter::addVariable(node_y, typePrec, dim0, compressionLevel);
[879]615                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &node_y);
[924]616                SuperClassWriter::addAttribute("long_name", StdString("Latitude of mesh nodes."), &node_y);
[879]617                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &node_y);
618              }
619              if (!SuperClassWriter::varExist(edge_x) || !SuperClassWriter::varExist(edge_y))
620              {
621                SuperClassWriter::addAttribute("edge_coordinates", edge_x + " " + edge_y, &domainName);
622                SuperClassWriter::addAttribute("edge_node_connectivity", edge_nodes, &domainName);
[2409]623                SuperClassWriter::addAttribute("face_edge_connectivity", face_edges, &domainName);
624                SuperClassWriter::addAttribute("edge_face_connectivity", edge_faces, &domainName);
[924]625                SuperClassWriter::addDimension(dimEdge, domain->mesh->nbEdgesGlo);
[879]626                dim0.clear();
627                dim0.push_back(dimEdge);
[1456]628                SuperClassWriter::addVariable(edge_x, typePrec, dim0, compressionLevel);
[879]629                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &edge_x);
[924]630                SuperClassWriter::addAttribute("long_name", StdString("Characteristic longitude of mesh edges."), &edge_x);
[879]631                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &edge_x);
[1456]632                SuperClassWriter::addVariable(edge_y, typePrec, dim0, compressionLevel);
[879]633                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &edge_y);
[924]634                SuperClassWriter::addAttribute("long_name", StdString("Characteristic latitude of mesh edges."), &edge_y);
[879]635                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &edge_y);
636                dim0.clear();
637                dim0.push_back(dimEdge);
638                dim0.push_back(dimTwo);
[1456]639                SuperClassWriter::addVariable(edge_nodes, NC_INT, dim0, compressionLevel);
[879]640                SuperClassWriter::addAttribute("cf_role", StdString("edge_node_connectivity"), &edge_nodes);
641                SuperClassWriter::addAttribute("long_name", StdString("Maps every edge/link to two nodes that it connects."), &edge_nodes);
642                SuperClassWriter::addAttribute("start_index", 0, &edge_nodes);
643              }
[2409]644              SuperClassWriter::addAttribute("face_face_connectivity", face_faces, &domainName);
[924]645              SuperClassWriter::addAttribute("face_coordinates", face_x + " " + face_y, &domainName);
646              SuperClassWriter::addAttribute("face_node_connectivity", face_nodes, &domainName);
647              SuperClassWriter::addDimension(dimFace, domain->ni_glo);
648              SuperClassWriter::addDimension(dimVertex, domain->nvertex);
649              dim0.clear();
650              dim0.push_back(dimFace);
[1456]651              SuperClassWriter::addVariable(face_x, typePrec, dim0, compressionLevel);
[924]652              SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &face_x);
653              SuperClassWriter::addAttribute("long_name", StdString("Characteristic longitude of mesh faces."), &face_x);
654              SuperClassWriter::addAttribute("units", StdString("degrees_east"), &face_x);
[1456]655              SuperClassWriter::addVariable(face_y, typePrec, dim0, compressionLevel);
[924]656              SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &face_y);
657              SuperClassWriter::addAttribute("long_name", StdString("Characteristic latitude of mesh faces."), &face_y);
658              SuperClassWriter::addAttribute("units", StdString("degrees_north"), &face_y);
659              dim0.clear();
660              dim0.push_back(dimFace);
661              dim0.push_back(dimVertex);
[1456]662              SuperClassWriter::addVariable(face_nodes, NC_INT, dim0, compressionLevel);
[924]663              SuperClassWriter::addAttribute("cf_role", StdString("face_node_connectivity"), &face_nodes);
664              SuperClassWriter::addAttribute("long_name", StdString("Maps every face to its corner nodes."), &face_nodes);
665              SuperClassWriter::addAttribute("start_index", 0, &face_nodes);
666              dim0.clear();
667              dim0.push_back(dimFace);
668              dim0.push_back(dimVertex);
[1456]669              SuperClassWriter::addVariable(face_edges, NC_INT, dim0, compressionLevel);
[924]670              SuperClassWriter::addAttribute("cf_role", StdString("face_edge_connectivity"), &face_edges);
671              SuperClassWriter::addAttribute("long_name", StdString("Maps every face to its edges."), &face_edges);
672              SuperClassWriter::addAttribute("start_index", 0, &face_edges);
[929]673              SuperClassWriter::addAttribute("_FillValue", 999999, &face_edges);
[924]674              dim0.clear();
675              dim0.push_back(dimEdge);
676              dim0.push_back(dimTwo);
[1456]677              SuperClassWriter::addVariable(edge_faces, NC_INT, dim0, compressionLevel);
[2413]678              SuperClassWriter::addAttribute("cf_role", StdString("edge_face_connectivity"), &edge_faces);
[924]679              SuperClassWriter::addAttribute("long_name", StdString("neighbor faces for edges"), &edge_faces);
680              SuperClassWriter::addAttribute("start_index", 0, &edge_faces);
681              SuperClassWriter::addAttribute("_FillValue", -999, &edge_faces);
682              SuperClassWriter::addAttribute("comment", StdString("missing neighbor faces are indicated using _FillValue"), &edge_faces);
683              dim0.clear();
684              dim0.push_back(dimFace);
685              dim0.push_back(dimVertex);
[1456]686              SuperClassWriter::addVariable(face_faces, NC_INT, dim0, compressionLevel);
[2413]687              SuperClassWriter::addAttribute("cf_role", StdString("face_face_connectivity"), &face_faces);
[924]688              SuperClassWriter::addAttribute("long_name", StdString("Indicates which other faces neighbor each face"), &face_faces);
689              SuperClassWriter::addAttribute("start_index", 0, &face_faces);
[929]690              SuperClassWriter::addAttribute("_FillValue", 999999, &face_faces);
[924]691              SuperClassWriter::addAttribute("flag_values", -1, &face_faces);
692              SuperClassWriter::addAttribute("flag_meanings", StdString("out_of_mesh"), &face_faces);
[879]693            } // domain->nvertex > 2
[878]694
[879]695            SuperClassWriter::definition_end();
[878]696
[924]697            std::vector<StdSize> startEdges(1) ;
698            std::vector<StdSize> countEdges(1) ;
699            std::vector<StdSize> startNodes(1) ;
700            std::vector<StdSize> countNodes(1) ;
701            std::vector<StdSize> startFaces(1) ;
702            std::vector<StdSize> countFaces(1) ;
703            std::vector<StdSize> startEdgeNodes(2) ;
704            std::vector<StdSize> countEdgeNodes(2) ;
705            std::vector<StdSize> startEdgeFaces(2) ;
706            std::vector<StdSize> countEdgeFaces(2) ;
707            std::vector<StdSize> startFaceConctv(2) ;
708            std::vector<StdSize> countFaceConctv(2) ;
[902]709
[1494]710            if (domain->nvertex == 1)
[879]711            {
[1494]712              if (domain->isEmpty())
713               {
714                 startNodes[0]=0 ;
715                 countNodes[0]=0 ;
716               }
717               else
718               {
[2507]719                 startNodes[0] = domain->ibeginValue_;
720                 countNodes[0] = domain->niValue_ ;
[1494]721               }
[924]722
[1494]723              SuperClassWriter::writeData(domain->mesh->node_lat, node_y, isCollective, 0, &startNodes, &countNodes);
724              SuperClassWriter::writeData(domain->mesh->node_lon, node_x, isCollective, 0, &startNodes, &countNodes);
725            }
726            else if (domain->nvertex == 2)
727            {
728              if (domain->isEmpty())
729               {
730                startEdges[0]=0 ;
731                countEdges[0]=0 ;
732                startNodes[0]=0 ;
733                countNodes[0]=0 ;
734                startEdgeNodes[0]=0;
735                startEdgeNodes[1]=0;
736                countEdgeNodes[0]=0;
737                countEdgeNodes[1]=0;
[924]738
[1494]739               }
740               else
741               {
[2507]742                 startEdges[0] = domain->ibeginValue_;
743                 countEdges[0] = domain->niValue_;
[1494]744                 startNodes[0] = domain->mesh->node_start;
745                 countNodes[0] = domain->mesh->node_count;
[2409]746                 if (countNodes[0]==0) startNodes[0]=0 ; // for netcdf error
[2507]747                 startEdgeNodes[0] = domain->ibeginValue_;
[1494]748                 startEdgeNodes[1] = 0;
[2507]749                 countEdgeNodes[0] = domain->niValue_;
[1494]750                 countEdgeNodes[1] = 2;
751               }
752              SuperClassWriter::writeData(domain->mesh->node_lat, node_y, isCollective, 0, &startNodes, &countNodes);
753              SuperClassWriter::writeData(domain->mesh->node_lon, node_x, isCollective, 0, &startNodes, &countNodes);
754              SuperClassWriter::writeData(domain->mesh->edge_lat, edge_y, isCollective, 0, &startEdges, &countEdges);
755              SuperClassWriter::writeData(domain->mesh->edge_lon, edge_x, isCollective, 0, &startEdges, &countEdges);
756              SuperClassWriter::writeData(domain->mesh->edge_nodes, edge_nodes, isCollective, 0, &startEdgeNodes, &countEdgeNodes);
757            }
[879]758            else
759            {
[1494]760              if (domain->isEmpty())
761               {
762                 startFaces[0] = 0 ;
763                 countFaces[0] = 0 ;
764                 startNodes[0] = 0;
765                 countNodes[0] = 0;
766                 startEdges[0] = 0;
767                 countEdges[0] = 0;
768                 startEdgeFaces[0] = 0;
769                 startEdgeFaces[1] = 0;
770                 countEdgeFaces[0] = 0;
771                 countEdgeFaces[1] = 0;
772                 startFaceConctv[0] = 0;
773                 startFaceConctv[1] = 0;
774                 countFaceConctv[0] = 0;
775                 countFaceConctv[1] = 0;
776               }
777               else
778               {
[2507]779                 startFaces[0] = domain->ibeginValue_;
780                 countFaces[0] = domain->niValue_ ;
[1494]781                 startNodes[0] = domain->mesh->node_start;
782                 countNodes[0] = domain->mesh->node_count;
[2409]783                 if (countNodes[0]==0) startNodes[0]=0;
784
[1494]785                 startEdges[0] = domain->mesh->edge_start;
786                 countEdges[0] = domain->mesh->edge_count;
[2409]787                 if (countEdges[0]==0) startEdges[0]=0 ; // for netcdf error
788
[1494]789                 startEdgeNodes[0] = domain->mesh->edge_start;
[2409]790                 countEdgeNodes[0] = domain->mesh->edge_count;
791                 if (countEdgeNodes[0]==0) startEdgeNodes[0]=0; // for netcdf error
[1494]792                 startEdgeNodes[1] = 0;
793                 countEdgeNodes[1]= 2;
[2409]794                 
[1494]795                 startEdgeFaces[0] = domain->mesh->edge_start;
[2409]796                 countEdgeFaces[0] = domain->mesh->edge_count;
797                 if (countEdgeFaces[0]==0) startEdgeFaces[0]=0 ; // for netcdf error
[1494]798                 startEdgeFaces[1]= 0;
799                 countEdgeFaces[1]= 2;
[2409]800                 
[2507]801                 startFaceConctv[0] = domain->ibeginValue_;
802                 countFaceConctv[0] = domain->niValue_;
[1494]803                 startFaceConctv[1] = 0;
804                 countFaceConctv[1] = domain->nvertex;
805               }
806              SuperClassWriter::writeData(domain->mesh->node_lat, node_y, isCollective, 0, &startNodes, &countNodes);
807              SuperClassWriter::writeData(domain->mesh->node_lon, node_x, isCollective, 0, &startNodes, &countNodes);
808              SuperClassWriter::writeData(domain->mesh->edge_lat, edge_y, isCollective, 0, &startEdges, &countEdges);
809              SuperClassWriter::writeData(domain->mesh->edge_lon, edge_x, isCollective, 0, &startEdges, &countEdges);
810              SuperClassWriter::writeData(domain->mesh->edge_nodes, edge_nodes, isCollective, 0, &startEdgeNodes, &countEdgeNodes);
811              SuperClassWriter::writeData(domain->mesh->face_lat, face_y, isCollective, 0, &startFaces, &countFaces);
812              SuperClassWriter::writeData(domain->mesh->face_lon, face_x, isCollective, 0, &startFaces, &countFaces);
813              SuperClassWriter::writeData(domain->mesh->face_nodes, face_nodes, isCollective, 0, &startFaceConctv, &countFaceConctv);
814              SuperClassWriter::writeData(domain->mesh->face_edges, face_edges, isCollective, 0, &startFaceConctv, &countFaceConctv);
815              SuperClassWriter::writeData(domain->mesh->edge_faces, edge_faces, isCollective, 0, &startEdgeFaces, &countEdgeFaces);
816              SuperClassWriter::writeData(domain->mesh->face_faces, face_faces, isCollective, 0, &startFaceConctv, &countFaceConctv);
817            }
[879]818            SuperClassWriter::definition_start();
[878]819
[879]820            break;
821          } // ONE_FILE
[878]822
[879]823          case (MULTI_FILE) :
824          {
[1637]825            ERROR("CNc4DataOutput::writeDomain(domain)",
826            << "[ type = multiple_file ]"
827            << " is not yet implemented for UGRID files !");
[879]828            break;
829          }
[878]830
[879]831          default :
832          ERROR("CNc4DataOutput::writeDomain(domain)",
833          << "[ type = " << SuperClass::type << "]"
834          << " not implemented yet !");
835          } // switch
836        } // try
[878]837
[879]838        catch (CNetCdfException& e)
839        {
840          StdString msg("On writing the domain : ");
841          msg.append(domid); msg.append("\n");
842          msg.append("In the context : ");
843          msg.append(context->getId()); msg.append("\n");
844          msg.append(e.what());
[924]845          ERROR("CNc4DataOutput::writeUnstructuredDomainUgrid(CDomain* domain)", << msg);
[879]846        }
[878]847
[879]848  domain->addRelFile(this->filename);
849  }
[878]850
[879]851    //--------------------------------------------------------------
[878]852
[879]853    void CNc4DataOutput::writeUnstructuredDomain(CDomain* domain)
[449]854      {
855         CContext* context = CContext::getCurrent() ;
[488]856
[449]857         if (domain->IsWritten(this->filename)) return;
858         domain->checkAttributes();
[488]859
860         if (domain->isEmpty())
[449]861           if (SuperClass::type==MULTI_FILE) return ;
862
863         std::vector<StdString> dim0, dim1;
[772]864         StdString domid = domain->getDomainOutputName();
[705]865         if (isWrittenDomain(domid)) return ;
[774]866         else setWrittenDomain(domid);
[705]867
[449]868         StdString appendDomid  = (singleDomain) ? "" : "_"+domid ;
869
[1430]870         StdString lonName,latName, cellName ;
[1391]871         if (domain->lon_name.isEmpty()) lonName = "lon";
872         else lonName = domain->lon_name;
873
874         if (domain->lat_name.isEmpty()) latName = "lat";
875         else latName = domain->lat_name;
876
[1430]877         if (!domain->dim_i_name.isEmpty()) cellName=domain->dim_i_name;
878         else cellName="cell";
879         StdString dimXid = cellName+appendDomid;
[2387]880         StdString dimVertId;
[2535]881         if (domain->nvertex_name.isEmpty()) dimVertId = "nvertex"+appendDomid; 
[2395]882         else dimVertId = domain->nvertex_name;
[488]883
[449]884         string lonid,latid,bounds_lonid,bounds_latid ;
[611]885         string areaId = "area" + appendDomid;
[449]886
[1158]887         nc_type typePrec ;
888         if (domain->prec.isEmpty()) typePrec =  NC_FLOAT ;
889         else if (domain->prec==4)  typePrec =  NC_FLOAT ;
890         else if (domain->prec==8)   typePrec =  NC_DOUBLE ;
891
[1132]892         int nvertex = (domain->nvertex.isEmpty()) ? 0 : domain->nvertex;
[1025]893
[498]894         try
[449]895         {
[498]896           switch (SuperClass::type)
897           {
898              case (MULTI_FILE) :
899              {
900                 dim0.push_back(dimXid);
[1553]901                 SuperClassWriter::addDimension(dimXid, domain->ni);
[488]902
[1415]903                 lonid = lonName+appendDomid;
904                 latid = latName+appendDomid;
[1430]905                 if (!domain->bounds_lon_name.isEmpty()) bounds_lonid = domain->bounds_lon_name;
906                 else bounds_lonid = "bounds_"+lonName+appendDomid;
907                 if (!domain->bounds_lat_name.isEmpty()) bounds_latid = domain->bounds_lat_name;
908                 else bounds_latid = "bounds_"+latName+appendDomid;
909
[665]910                 if (domain->hasLonLat)
911                 {
[1456]912                   SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
913                   SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
[665]914                   this->writeAxisAttributes(lonid, "", "longitude", "Longitude", "degrees_east", domid);
915                   if (domain->hasBounds) SuperClassWriter::addAttribute("bounds",bounds_lonid, &lonid);
916                   this->writeAxisAttributes(latid, "", "latitude", "Latitude", "degrees_north", domid);
917                   if (domain->hasBounds) SuperClassWriter::addAttribute("bounds",bounds_latid, &latid);
918                   if (domain->hasBounds) SuperClassWriter::addDimension(dimVertId, domain->nvertex);
919                 }
[498]920                 dim0.clear();
921                 if (domain->hasBounds)
922                 {
923                   dim0.push_back(dimXid);
924                   dim0.push_back(dimVertId);
[1456]925                   SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
926                   SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
[498]927                 }
928
929                 dim0.clear();
[449]930                 dim0.push_back(dimXid);
[611]931                 if (domain->hasArea)
932                 {
[1456]933                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
[614]934                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
[611]935                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
936                 }
937
[498]938                 SuperClassWriter::definition_end();
[449]939
[665]940                 if (domain->hasLonLat)
[498]941                 {
[1930]942                   SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0);
943                   SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0);
[665]944                   if (domain->hasBounds)
945                   {
[1930]946                     SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0);
947                     SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0);
[665]948                   }
[498]949                 }
[611]950
951                 if (domain->hasArea)
[1930]952                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0);
[611]953
[498]954                 SuperClassWriter::definition_start();
955                 break ;
956              }
[488]957
[498]958              case (ONE_FILE) :
959              {
[1415]960                 lonid = lonName+appendDomid;
961                 latid = latName+appendDomid;
[1430]962                 if (!domain->bounds_lon_name.isEmpty()) bounds_lonid = domain->bounds_lon_name;
963                 else bounds_lonid = "bounds_"+lonName+appendDomid;
964                 if (!domain->bounds_lat_name.isEmpty()) bounds_latid = domain->bounds_lat_name;
965                 else bounds_latid = "bounds_"+latName+appendDomid;
[1391]966
[498]967                 dim0.push_back(dimXid);
[1132]968                 SuperClassWriter::addDimension(dimXid, domain->ni_glo);
[665]969                 if (domain->hasLonLat)
970                 {
[1456]971                   SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
972                   SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
[665]973
974                   this->writeAxisAttributes(lonid, "", "longitude", "Longitude", "degrees_east", domid);
975                   if (domain->hasBounds) SuperClassWriter::addAttribute("bounds",bounds_lonid, &lonid);
976                   this->writeAxisAttributes(latid, "", "latitude", "Latitude", "degrees_north", domid);
977                   if (domain->hasBounds) SuperClassWriter::addAttribute("bounds",bounds_latid, &latid);
[1025]978                   if (domain->hasBounds) SuperClassWriter::addDimension(dimVertId, nvertex);
[665]979                 }
[498]980                 dim0.clear();
[449]981
[498]982                 if (domain->hasBounds)
983                 {
984                   dim0.push_back(dimXid);
985                   dim0.push_back(dimVertId);
[1456]986                   SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
987                   SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
[498]988                 }
[488]989
[611]990                 if (domain->hasArea)
991                 {
992                   dim0.clear();
993                   dim0.push_back(dimXid);
[1456]994                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
[614]995                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
[611]996                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
997                 }
998
[498]999                 SuperClassWriter::definition_end();
[488]1000
[498]1001                 std::vector<StdSize> start(1), startBounds(2) ;
1002                 std::vector<StdSize> count(1), countBounds(2) ;
1003                 if (domain->isEmpty())
1004                 {
1005                   start[0]=0 ;
1006                   count[0]=0 ;
1007                   startBounds[1]=0 ;
[1025]1008                   countBounds[1]=nvertex ;
[498]1009                   startBounds[0]=0 ;
1010                   countBounds[0]=0 ;
1011                 }
1012                 else
1013                 {
[2507]1014                   start[0]=domain->ibeginValue_;
1015                   count[0]=domain->niValue_;
1016                   startBounds[0]=domain->ibeginValue_;
[498]1017                   startBounds[1]=0 ;
[2507]1018                   countBounds[0]=domain->niValue_;
[1025]1019                   countBounds[1]=nvertex ;
[498]1020                 }
[665]1021
1022                 if (domain->hasLonLat)
[498]1023                 {
[1930]1024                   SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0,&start,&count);
1025                   SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0,&start,&count);
[665]1026                   if (domain->hasBounds)
1027                   {
[1930]1028                     SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0,&startBounds,&countBounds);
1029                     SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0,&startBounds,&countBounds);
[665]1030                   }
[498]1031                 }
[488]1032
[611]1033                 if (domain->hasArea)
[1930]1034                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0, &start, &count);
[488]1035
[498]1036                 SuperClassWriter::definition_start();
[488]1037
[498]1038                 break;
1039              }
1040              default :
1041                 ERROR("CNc4DataOutput::writeDomain(domain)",
1042                       << "[ type = " << SuperClass::type << "]"
1043                       << " not implemented yet !");
1044           }
[219]1045         }
[498]1046         catch (CNetCdfException& e)
1047         {
1048           StdString msg("On writing the domain : ");
1049           msg.append(domid); msg.append("\n");
1050           msg.append("In the context : ");
1051           msg.append(context->getId()); msg.append("\n");
1052           msg.append(e.what());
1053           ERROR("CNc4DataOutput::writeUnstructuredDomain(CDomain* domain)", << msg);
1054         }
[219]1055         domain->addRelFile(this->filename);
1056      }
1057      //--------------------------------------------------------------
1058
[347]1059      void CNc4DataOutput::writeAxis_(CAxis* axis)
[219]1060      {
[1030]1061        if (axis->IsWritten(this->filename)) return;
[2381]1062
1063        // Check that the name associated to the current element is not in conflict with an existing element (due to CGrid::duplicateSentGrid)
1064        if (!axis->value.isEmpty() )
1065        {
[2386]1066          // The hash of the element will be associated to the default element name (= map key), and to the name really written
1067          int globalHash = axis->computeAttributesHash( comm_file ); // Need a MPI_Comm to distribute without redundancy some attributs (value)
[2381]1068
1069          StdString defaultNameKey = axis->getAxisOutputName();
[2389]1070          if ( !relAxis_.count ( defaultNameKey ) )
[2381]1071          {
1072            // if defaultNameKey not in the map, write the element such as it is defined
[2389]1073            relAxis_.insert( make_pair( defaultNameKey, make_pair(globalHash, axis) ) );
[2381]1074          }
1075          else // look if a hash associated this key is equal
1076          {
1077            bool elementIsInMap(false);
[2389]1078            auto defaultNameKeyElements = relAxis_.equal_range( defaultNameKey );
[2381]1079            for (auto it = defaultNameKeyElements.first; it != defaultNameKeyElements.second; it++)
1080            {
1081              if ( it->second.first == globalHash )
1082              {
1083                // if yes, associate the same ids to current element
[2389]1084                axis->renameAttributesBeforeWriting( it->second.second );
[2381]1085                elementIsInMap = true;
1086              }
1087            }
1088             // if no : inheritance has been excessive, define new names and store it (could be used by another grid)
1089            if (!elementIsInMap)  // ! in MAP
1090            {
[2389]1091              axis->renameAttributesBeforeWriting();
1092              relAxis_.insert( make_pair( defaultNameKey, make_pair(globalHash, axis) ) ) ;// = axis->getId()         
[2381]1093            }
1094          }
1095        }
1096
[1030]1097        axis->checkAttributes();
[488]1098
[1559]1099        int size  = (MULTI_FILE == SuperClass::type) ? axis->n.getValue()
1100                                                          : axis->n_glo.getValue();
[1099]1101
[1559]1102        if ((0 == axis->n) && (MULTI_FILE == SuperClass::type)) return;
[1235]1103
[1030]1104        std::vector<StdString> dims;
1105        StdString axisid = axis->getAxisOutputName();
[1435]1106        StdString axisDim, axisBoundsId;
[1030]1107        if (isWrittenAxis(axisid)) return ;
1108        else setWrittenAxis(axisid);
[705]1109
[1158]1110        nc_type typePrec ;
1111        if (axis->prec.isEmpty()) typePrec =  NC_FLOAT ;
[1235]1112        else if (axis->prec==4)   typePrec =  NC_FLOAT ;
[1158]1113        else if (axis->prec==8)   typePrec =  NC_DOUBLE ;
1114         
1115        if (!axis->label.isEmpty()) typePrec = NC_CHAR ;
1116        string strId="str_len" ;
[1030]1117        try
1118        {
[1433]1119          if (axis->dim_name.isEmpty()) axisDim = axisid;
1120          else axisDim=axis->dim_name.getValue();
[1559]1121          SuperClassWriter::addDimension(axisDim, size);
[1433]1122          dims.push_back(axisDim);
1123
[1439]1124          if (!axis->label.isEmpty() && !SuperClassWriter::dimExist(strId)) SuperClassWriter::addDimension(strId, stringArrayLen);
[1433]1125
[2507]1126          if (axis->hasValue() || !axis->label.isEmpty())
[816]1127          {
[1158]1128            if (!axis->label.isEmpty()) dims.push_back(strId);
[1430]1129
[1456]1130            SuperClassWriter::addVariable(axisid, typePrec, dims, compressionLevel);
[219]1131
[1030]1132            if (!axis->name.isEmpty())
1133              SuperClassWriter::addAttribute("name", axis->name.getValue(), &axisid);
[219]1134
[1030]1135            if (!axis->standard_name.isEmpty())
1136              SuperClassWriter::addAttribute("standard_name", axis->standard_name.getValue(), &axisid);
[540]1137
[1030]1138            if (!axis->long_name.isEmpty())
1139              SuperClassWriter::addAttribute("long_name", axis->long_name.getValue(), &axisid);
[219]1140
[1030]1141            if (!axis->unit.isEmpty())
1142              SuperClassWriter::addAttribute("units", axis->unit.getValue(), &axisid);
[219]1143
[1430]1144            if (!axis->axis_type.isEmpty())
1145            {
1146              switch(axis->axis_type)
1147              {
1148              case CAxis::axis_type_attr::X :
1149                SuperClassWriter::addAttribute("axis", string("X"), &axisid);
1150                break;
1151              case CAxis::axis_type_attr::Y :
1152                SuperClassWriter::addAttribute("axis", string("Y"), &axisid);
1153                break;
1154              case CAxis::axis_type_attr::Z :
1155                SuperClassWriter::addAttribute("axis", string("Z"), &axisid);
1156                break;
1157              case CAxis::axis_type_attr::T :
1158                SuperClassWriter::addAttribute("axis", string("T"), &axisid);
1159                break;
1160              }
1161            }
1162
[1030]1163            if (!axis->positive.isEmpty())
1164            {
1165              SuperClassWriter::addAttribute("positive",
1166                                             (axis->positive == CAxis::positive_attr::up) ? string("up") : string("down"),
1167                                             &axisid);
1168            }
[399]1169
[1266]1170            if (!axis->formula.isEmpty())
1171              SuperClassWriter::addAttribute("formula", axis->formula.getValue(), &axisid);
1172
1173            if (!axis->formula_term.isEmpty())
[2436]1174              SuperClassWriter::addAttribute("formula_terms", axis->formula_term.getValue(), &axisid);
[1266]1175             
[1435]1176            axisBoundsId = (axis->bounds_name.isEmpty()) ? axisid + "_bounds" : axis->bounds_name;
[1249]1177            if (!axis->bounds.isEmpty() && axis->label.isEmpty())
[1030]1178            {
1179              dims.push_back("axis_nbounds");
[1456]1180              SuperClassWriter::addVariable(axisBoundsId, typePrec, dims, compressionLevel);
[1030]1181              SuperClassWriter::addAttribute("bounds", axisBoundsId, &axisid);
[1288]1182
1183              if (!axis->standard_name.isEmpty())
1184                SuperClassWriter::addAttribute("standard_name", axis->standard_name.getValue(), &axisBoundsId);
1185
1186              if (!axis->unit.isEmpty())
1187                SuperClassWriter::addAttribute("units", axis->unit.getValue(), &axisBoundsId);
1188
[1266]1189              if (!axis->formula_bounds.isEmpty())
[1288]1190                SuperClassWriter::addAttribute("formula", axis->formula_bounds.getValue(), &axisBoundsId);
[1266]1191
1192              if (!axis->formula_term_bounds.isEmpty())
[2436]1193                SuperClassWriter::addAttribute("formula_terms", axis->formula_term_bounds.getValue(), &axisBoundsId);
[1030]1194            }
[1435]1195          }
[816]1196
[1435]1197          SuperClassWriter::definition_end();
[1950]1198         
[1435]1199          switch (SuperClass::type)
1200          {
1201            case MULTI_FILE:
[1030]1202            {
[1435]1203              if (axis->label.isEmpty())
[1437]1204              {
1205                if (!axis->value.isEmpty())
[1930]1206                  SuperClassWriter::writeData(axis->value, axisid, isCollective, 0);
[633]1207
[1437]1208                if (!axis->bounds.isEmpty())
[1930]1209                  SuperClassWriter::writeData(axis->bounds, axisBoundsId, isCollective, 0);
[1435]1210              }
[1437]1211              else
[1950]1212                SuperClassWriter::writeData(axis->label, axisid, isCollective, 0);
[1435]1213
1214              SuperClassWriter::definition_start();
1215              break;
1216            }
1217            case ONE_FILE:
1218            {
1219              std::vector<StdSize> start(1), startBounds(2) ;
1220              std::vector<StdSize> count(1), countBounds(2) ;
[1559]1221              start[0] = startBounds[0] = axis->begin;
1222              count[0] = countBounds[0] = axis->n;
[1435]1223              startBounds[1] = 0;
1224              countBounds[1] = 2;
1225
1226              if (axis->label.isEmpty())
[1437]1227              {
1228                if (!axis->value.isEmpty())
[1930]1229                  SuperClassWriter::writeData(axis->value, axisid, isCollective, 0, &start, &count);
[1435]1230
[1437]1231                if (!axis->bounds.isEmpty())
[1930]1232                  SuperClassWriter::writeData(axis->bounds, axisBoundsId, isCollective, 0, &startBounds, &countBounds);
[1435]1233              }
[1437]1234              else
[1435]1235              {
1236                std::vector<StdSize> startLabel(2), countLabel(2);
1237                startLabel[0] = start[0]; startLabel[1] = 0;
1238                countLabel[0] = count[0]; countLabel[1] = stringArrayLen;
[1950]1239                SuperClassWriter::writeData(axis->label, axisid, isCollective, 0, &startLabel, &countLabel);
[1435]1240              }
[609]1241
[1435]1242              SuperClassWriter::definition_start();
1243
1244              break;
[609]1245            }
[1435]1246            default :
1247              ERROR("CNc4DataOutput::writeAxis_(CAxis* axis)",
1248                    << "[ type = " << SuperClass::type << "]"
1249                    << " not implemented yet !");
[609]1250          }
[1030]1251        }
1252        catch (CNetCdfException& e)
1253        {
1254          StdString msg("On writing the axis : ");
1255          msg.append(axisid); msg.append("\n");
1256          msg.append("In the context : ");
1257          CContext* context = CContext::getCurrent() ;
1258          msg.append(context->getId()); msg.append("\n");
1259          msg.append(e.what());
1260          ERROR("CNc4DataOutput::writeAxis_(CAxis* axis)", << msg);
1261        }
[1158]1262        axis->addRelFile(this->filename);
[391]1263     }
[488]1264
[887]1265      void CNc4DataOutput::writeScalar_(CScalar* scalar)
1266      {
1267        if (scalar->IsWritten(this->filename)) return;
1268        scalar->checkAttributes();
1269        int scalarSize = 1;
1270
1271        StdString scalaId = scalar->getScalarOutputName();
[1430]1272        StdString boundsId;
[887]1273        if (isWrittenAxis(scalaId)) return ;
1274        else setWrittenAxis(scalaId);
1275
[1158]1276        nc_type typePrec ;
1277        if (scalar->prec.isEmpty()) typePrec =  NC_FLOAT ;
1278        else if (scalar->prec==4)  typePrec =  NC_FLOAT ;
1279        else if (scalar->prec==8)   typePrec =  NC_DOUBLE ;
1280
[1435]1281        if (!scalar->label.isEmpty()) typePrec = NC_CHAR ;
1282        string strId="str_len" ;
1283
[887]1284        try
1285        {
[1439]1286          if (!scalar->label.isEmpty() && !SuperClassWriter::dimExist(strId)) SuperClassWriter::addDimension(strId, stringArrayLen);
[1435]1287
1288          if (!scalar->value.isEmpty() || !scalar->label.isEmpty())
[887]1289          {
[1430]1290            std::vector<StdString> dims;
1291            StdString scalarDim = scalaId;
1292
[1435]1293            if (!scalar->label.isEmpty()) dims.push_back(strId);
1294
[1158]1295            SuperClassWriter::addVariable(scalaId, typePrec, dims);
[887]1296
1297            if (!scalar->name.isEmpty())
1298              SuperClassWriter::addAttribute("name", scalar->name.getValue(), &scalaId);
1299
1300            if (!scalar->standard_name.isEmpty())
1301              SuperClassWriter::addAttribute("standard_name", scalar->standard_name.getValue(), &scalaId);
1302
1303            if (!scalar->long_name.isEmpty())
1304              SuperClassWriter::addAttribute("long_name", scalar->long_name.getValue(), &scalaId);
1305
1306            if (!scalar->unit.isEmpty())
1307              SuperClassWriter::addAttribute("units", scalar->unit.getValue(), &scalaId);
1308
[1430]1309            if (!scalar->axis_type.isEmpty())
1310            {
1311              switch(scalar->axis_type)
1312              {
1313              case CScalar::axis_type_attr::X :
1314                SuperClassWriter::addAttribute("axis", string("X"), &scalaId);
1315                break;
1316              case CScalar::axis_type_attr::Y :
1317                SuperClassWriter::addAttribute("axis", string("Y"), &scalaId);
1318                break;
1319              case CScalar::axis_type_attr::Z :
1320                SuperClassWriter::addAttribute("axis", string("Z"), &scalaId);
1321                break;
1322              case CScalar::axis_type_attr::T :
1323                SuperClassWriter::addAttribute("axis", string("T"), &scalaId);
1324                break;
1325              }
1326            }
1327
[1435]1328            if (!scalar->positive.isEmpty())
[1430]1329            {
[1435]1330              SuperClassWriter::addAttribute("positive",
1331                                             (scalar->positive == CScalar::positive_attr::up) ? string("up") : string("down"),
1332                                             &scalaId);
1333            }
1334
1335            if (!scalar->bounds.isEmpty() && scalar->label.isEmpty())
1336            {
[1436]1337              dims.clear();
1338              dims.push_back("axis_nbounds");
[1435]1339              boundsId = (scalar->bounds_name.isEmpty()) ? (scalaId + "_bounds") : scalar->bounds_name.getValue();
[1430]1340              SuperClassWriter::addVariable(boundsId, typePrec, dims);
[1436]1341              SuperClassWriter::addAttribute("bounds", boundsId, &scalaId);
[1430]1342            }
1343
[887]1344            SuperClassWriter::definition_end();
1345
1346            switch (SuperClass::type)
1347            {
1348              case MULTI_FILE:
1349              {
1350                CArray<double,1> scalarValue(scalarSize);
[1435]1351                CArray<string,1> scalarLabel(scalarSize);
[1436]1352                CArray<double,1> scalarBounds(scalarSize*2);
[1435]1353
1354                if (!scalar->value.isEmpty() && scalar->label.isEmpty())
[1430]1355                {
[1435]1356                  scalarValue(0) = scalar->value;
1357                  SuperClassWriter::writeData(scalarValue, scalaId, isCollective, 0);
1358                }
1359
1360                if (!scalar->bounds.isEmpty() && scalar->label.isEmpty())
1361                {
[1436]1362                  scalarBounds(0) = scalar->bounds(0);
1363                  scalarBounds(1) = scalar->bounds(1);
1364                  SuperClassWriter::writeData(scalarBounds, boundsId, isCollective, 0);
[1430]1365                }
[1435]1366
1367                if (!scalar->label.isEmpty())
1368                {
1369                  scalarLabel(0) = scalar->label;
1370                  SuperClassWriter::writeData(scalarLabel, scalaId, isCollective, 0);
1371                }
1372
[887]1373                SuperClassWriter::definition_start();
1374
1375                break;
1376              }
1377              case ONE_FILE:
1378              {
1379                CArray<double,1> scalarValue(scalarSize);
[1435]1380                CArray<string,1> scalarLabel(scalarSize);
[1436]1381                CArray<double,1> scalarBounds(scalarSize*2);
[887]1382
1383                std::vector<StdSize> start(1);
1384                std::vector<StdSize> count(1);
1385                start[0] = 0;
1386                count[0] = 1;
[1435]1387                if (!scalar->value.isEmpty() && scalar->label.isEmpty())
[1430]1388                {
[1435]1389                  scalarValue(0) = scalar->value;
1390                  SuperClassWriter::writeData(scalarValue, scalaId, isCollective, 0, &start, &count);
1391                }
1392                if (!scalar->bounds.isEmpty() && scalar->label.isEmpty())
1393                {
[1436]1394                  scalarBounds(0) = scalar->bounds(0);
1395                  scalarBounds(1) = scalar->bounds(1);
1396                  count[0] = 2;
1397                  SuperClassWriter::writeData(scalarBounds, boundsId, isCollective, 0, &start, &count);
[1430]1398                }
[1435]1399                if (!scalar->label.isEmpty())
1400                {
1401                  scalarLabel(0) = scalar->label;
1402                  count[0] = stringArrayLen;
1403                  SuperClassWriter::writeData(scalarLabel, scalaId, isCollective, 0, &start, &count);
1404                }
1405
[887]1406                SuperClassWriter::definition_start();
1407
1408                break;
1409              }
1410              default :
1411                ERROR("CNc4DataOutput::writeAxis_(CAxis* scalar)",
1412                      << "[ type = " << SuperClass::type << "]"
1413                      << " not implemented yet !");
1414            }
1415          }
1416        }
1417        catch (CNetCdfException& e)
1418        {
1419          StdString msg("On writing the scalar : ");
1420          msg.append(scalaId); msg.append("\n");
1421          msg.append("In the context : ");
1422          CContext* context = CContext::getCurrent() ;
1423          msg.append(context->getId()); msg.append("\n");
1424          msg.append(e.what());
1425          ERROR("CNc4DataOutput::writeScalar_(CScalar* scalar)", << msg);
1426        }
1427        scalar->addRelFile(this->filename);
1428     }
1429
[676]1430     //--------------------------------------------------------------
1431
1432     void CNc4DataOutput::writeGridCompressed_(CGrid* grid)
1433     {
[1957]1434        if (grid->isScalarGrid() || grid->isWrittenCompressed(this->filename)) return;
1435       
1436        // NOTA : The cuurent algorithm to write compress elements of the grid
1437        //        will work pretting well when on server side you dont't get
1438        //        partial overlap on elements between differents participating process
1439        //        So the element must be totally distributed or non distributed
1440        //        If an element is partially overlaping betwwen process then the
1441        //        total compressed part will apear artificially greater than expected
1442        //        For the current implementation of writer which is decomposed only on
1443        //        one element, it will work as expected, but for future, it must be
1444        //        reconsidered again.
1445        try
1446        {
1447          CArray<int,1> axisDomainOrder = grid->axis_domain_order;
1448          std::vector<StdString> domainList = grid->getDomainList();
1449          std::vector<StdString> axisList   = grid->getAxisList();
1450          std::vector<StdString> scalarList = grid->getScalarList();
1451          int numElement = axisDomainOrder.numElements(), idxDomain = 0, idxAxis = 0, idxScalar = 0;
1452          int commRank ;
1453          MPI_Comm_rank(comm_file,&commRank) ;
[676]1454
[1957]1455          std::vector<StdString> dims;
[676]1456
[1957]1457          for (int i = 0; i < numElement; ++i)
1458          {
1459            StdString varId, compress;
1460            CArray<size_t, 1> indexes;
1461            bool isDistributed;
1462            size_t nbIndexes, totalNbIndexes, offset;
1463            size_t firstGlobalIndex;
1464           
1465            if (2 == axisDomainOrder(i))
1466            {
1467              CDomain* domain = CDomain::get(domainList[idxDomain]);
1468              StdString domId = domain->getDomainOutputName();
[676]1469
[1957]1470              if (!domain->isCompressible()
1471                  || domain->type == CDomain::type_attr::unstructured
1472                  || domain->isWrittenCompressed(this->filename)
1473                  || isWrittenCompressedDomain(domId))
1474                continue;
1475           
1476              // unstructured grid seems not be taken into account why ?
[676]1477
[1957]1478              string lonName,latName ;
[676]1479
[1957]1480              if (domain->lon_name.isEmpty())
1481              { 
1482                if (domain->type==CDomain::type_attr::curvilinear) lonName = "nav_lon";
1483                else lonName = "lon";
1484              }
1485              else lonName = domain->lon_name;
[676]1486
[1957]1487              if (domain->lat_name.isEmpty())
1488              {
1489                if (domain->type==CDomain::type_attr::curvilinear) latName = "nav_lat";
1490                else latName = "lat";
1491              }
1492              else latName = domain->lat_name;
1493             
1494              StdString appendDomId  = singleDomain ? "" : "_" + domId;
[676]1495
[1957]1496              varId = domId + "_points";
1497              compress = latName + appendDomId + " " + lonName + appendDomId;
1498     
[2267]1499              shared_ptr<CLocalView> workflowView = domain->getLocalView(CElementView::WORKFLOW) ;
[1957]1500              workflowView->getGlobalIndexView(indexes) ;
1501              nbIndexes = workflowView->getSize() ;
1502              isDistributed = domain->isDistributed();
1503              if (isDistributed)
1504              {
1505                MPI_Exscan(&nbIndexes, &offset, 1, MPI_SIZE_T, MPI_SUM, comm_file) ;
1506                if (commRank==0) offset=0 ;
1507                MPI_Allreduce(&nbIndexes,&totalNbIndexes,1 , MPI_SIZE_T, MPI_SUM, comm_file) ;
1508              }
1509              else
1510              {
1511                offset=0 ;
1512                totalNbIndexes = nbIndexes ;
1513              }
[676]1514
[2507]1515              firstGlobalIndex = domain->ibeginValue_ + domain->jbeginValue_ * domain->ni_glo;
[676]1516
[1957]1517              domain->addRelFileCompressed(this->filename);
1518              setWrittenCompressedDomain(domId);
1519              ++idxDomain;
1520            }
1521            else if (1 == axisDomainOrder(i))
1522            {
1523              CAxis* axis = CAxis::get(axisList[idxAxis]);
1524              StdString axisId = axis->getAxisOutputName();
[676]1525
[1957]1526              if (!axis->isCompressible()
1527                  || axis->isWrittenCompressed(this->filename)
1528                  || isWrittenCompressedAxis(axisId))
1529                continue;
[676]1530
[1957]1531              varId = axisId + "_points";
1532              compress = axisId;
[676]1533
[2267]1534              shared_ptr<CLocalView> workflowView = axis->getLocalView(CElementView::WORKFLOW) ;
[1957]1535              workflowView->getGlobalIndexView(indexes) ;
1536              nbIndexes = workflowView->getSize() ;
1537              isDistributed = axis->isDistributed();
1538              if (isDistributed)
1539              {
1540                MPI_Exscan(&nbIndexes, &offset, 1, MPI_SIZE_T, MPI_SUM, comm_file) ;
1541                if (commRank==0) offset=0 ;
1542                MPI_Allreduce(&nbIndexes,&totalNbIndexes,1 , MPI_SIZE_T, MPI_SUM, comm_file) ;
1543              }
1544              else
1545              {
1546                offset=0 ;
1547                totalNbIndexes = nbIndexes ;
1548              }
1549              firstGlobalIndex = axis->begin;
1550             
1551              axis->addRelFileCompressed(this->filename);
1552              setWrittenCompressedAxis(axisId);
1553              ++idxAxis;
1554            }
1555            else
1556            {
1557              //for scalar
1558            }
[676]1559
[1957]1560            if (!varId.empty())
1561            {
1562              SuperClassWriter::addDimension(varId, (SuperClass::type == MULTI_FILE) ? nbIndexes : totalNbIndexes);
[774]1563
[1957]1564              dims.clear();
1565              dims.push_back(varId);
1566              SuperClassWriter::addVariable(varId, NC_UINT64, dims);
[676]1567
[1957]1568              SuperClassWriter::addAttribute("compress", compress, &varId);
[676]1569
[1957]1570              switch (SuperClass::type)
1571              {
1572                case (MULTI_FILE):
1573                {
1574                  indexes -= firstGlobalIndex;
1575                  SuperClassWriter::writeData(indexes, varId, isCollective, 0);
1576                  break;
1577                }
1578                case (ONE_FILE):
1579                {
1580                  std::vector<StdSize> start, count;
1581                  start.push_back(offset);
1582                  count.push_back(nbIndexes);
[676]1583
[1957]1584                  SuperClassWriter::writeData(indexes, varId, isCollective, 0, &start, &count);
1585                  break;
1586                }
1587              }
[1144]1588            }
[1957]1589          }
[676]1590
[1957]1591          grid->addRelFileCompressed(this->filename);
1592        }
1593        catch (CNetCdfException& e)
1594        {
1595          StdString msg("On writing compressed grid : ");
1596          msg.append(grid->getId()); msg.append("\n");
1597          msg.append("In the context : ");
1598          CContext* context = CContext::getCurrent();
1599          msg.append(context->getId()); msg.append("\n");
1600          msg.append(e.what());
1601          ERROR("CNc4DataOutput::writeGridCompressed_(CGrid* grid)", << msg);
1602        }
1603      }
[676]1604
1605     //--------------------------------------------------------------
1606
[391]1607     void CNc4DataOutput::writeTimeDimension_(void)
1608     {
[498]1609       try
1610       {
[802]1611        SuperClassWriter::addDimension(getTimeCounterName());
[498]1612       }
1613       catch (CNetCdfException& e)
1614       {
[614]1615         StdString msg("On writing time dimension : time_couter\n");
[498]1616         msg.append("In the context : ");
1617         CContext* context = CContext::getCurrent() ;
1618         msg.append(context->getId()); msg.append("\n");
1619         msg.append(e.what());
1620         ERROR("CNc4DataOutput::writeTimeDimension_(void)", << msg);
1621       }
[391]1622     }
[676]1623
[219]1624      //--------------------------------------------------------------
1625
[347]1626      void CNc4DataOutput::writeField_(CField* field)
[219]1627      {
[1158]1628        CContext* context = CContext::getCurrent() ;
[300]1629
[1158]1630        std::vector<StdString> dims, coodinates;
[1869]1631        CGrid* grid = field->getGrid();
[1158]1632        if (!grid->doGridHaveDataToWrite())
[567]1633          if (SuperClass::type==MULTI_FILE) return ;
[488]1634
[1158]1635        CArray<int,1> axisDomainOrder = grid->axis_domain_order;
1636        int numElement = axisDomainOrder.numElements(), idxDomain = 0, idxAxis = 0, idxScalar = 0;
1637        std::vector<StdString> domainList = grid->getDomainList();
1638        std::vector<StdString> axisList   = grid->getAxisList();
1639        std::vector<StdString> scalarList = grid->getScalarList();       
[219]1640
[1158]1641        StdString timeid  = getTimeCounterName();
1642        StdString dimXid,dimYid;
1643        std::deque<StdString> dimIdList, dimCoordList;
1644        bool hasArea = false;
1645        StdString cellMeasures = "area:";
1646        bool compressedOutput = !field->indexed_output.isEmpty() && field->indexed_output;
[488]1647
[1158]1648        for (int i = 0; i < numElement; ++i)
1649        {
1650          if (2 == axisDomainOrder(i))
1651          {
1652            CDomain* domain = CDomain::get(domainList[idxDomain]);
1653            StdString domId = domain->getDomainOutputName();
1654            StdString appendDomId  = singleDomain ? "" : "_" + domId ;
[1391]1655            StdString lonName,latName ;
[1430]1656            StdString dimIname,dimJname ;
[676]1657
[1415]1658            if (domain->lon_name.isEmpty())
1659            { 
1660              if (domain->type==CDomain::type_attr::curvilinear) lonName = "nav_lon";
1661              else lonName = "lon";
1662            }
[1391]1663            else lonName = domain->lon_name;
1664
[1415]1665            if (domain->lat_name.isEmpty())
1666            {
1667              if (domain->type==CDomain::type_attr::curvilinear) latName = "nav_lat";
1668              else latName = "lat";
1669            }
[1391]1670            else latName = domain->lat_name;
[1430]1671
1672            if (domain->dim_i_name.isEmpty())
1673            {
1674              if (domain->type==CDomain::type_attr::curvilinear) dimIname = "x";
1675              else if (domain->type==CDomain::type_attr::unstructured) dimIname = "cell";
1676              else dimIname = lonName;
1677            }
1678            else dimIname = domain->dim_i_name;
1679
1680            if (domain->dim_j_name.isEmpty())
1681            {
1682              if (domain->type==CDomain::type_attr::curvilinear) dimJname = "y";
1683              else dimJname = latName;
1684            }
1685            else dimJname = domain->dim_j_name;
[1391]1686       
[1158]1687            if (compressedOutput && domain->isCompressible() && domain->type != CDomain::type_attr::unstructured)
1688            {
1689              dimIdList.push_back(domId + "_points");
1690              field->setUseCompressedOutput();
1691            }
[676]1692
[1158]1693            switch (domain->type)
[879]1694            {
[1158]1695              case CDomain::type_attr::curvilinear:
1696                if (!compressedOutput || !domain->isCompressible())
1697                {
[1430]1698                  dimXid=dimIname+appendDomId;
1699                  dimYid=dimJname+appendDomId;
[1158]1700                  dimIdList.push_back(dimXid);
1701                  dimIdList.push_back(dimYid);
1702                }
[1415]1703                dimCoordList.push_back(lonName+appendDomId);
1704                dimCoordList.push_back(latName+appendDomId);
[1158]1705              break ;
1706              case CDomain::type_attr::rectilinear:
1707                if (!compressedOutput || !domain->isCompressible())
1708                {
[1430]1709                  dimXid     = dimIname+appendDomId;
1710                  dimYid     = dimJname+appendDomId;
[1158]1711                  dimIdList.push_back(dimXid);
1712                  dimIdList.push_back(dimYid);
1713                }
[1430]1714                if (lonName != dimIname)  dimCoordList.push_back(lonName+appendDomId);
1715                if (latName != dimJname)  dimCoordList.push_back(latName+appendDomId);
1716
[1158]1717              break ;
1718              case CDomain::type_attr::unstructured:
1719              {
1720                if (SuperClassWriter::useCFConvention)
1721                {
[1430]1722                  dimXid     = dimIname + appendDomId;
[1158]1723                  dimIdList.push_back(dimXid);
[1415]1724                  dimCoordList.push_back(lonName+appendDomId);
1725                  dimCoordList.push_back(latName+appendDomId);
[1158]1726                }
1727                else
1728                {
1729                  StdString domainName = domain->name;
1730                  if (domain->nvertex == 1)
1731                  {
1732                    dimXid     = "n" + domainName + "_node";
1733                    dimIdList.push_back(dimXid);
1734                    dimCoordList.push_back(StdString(domainName + "_node_x"));
1735                    dimCoordList.push_back(StdString(domainName + "_node_y"));
1736                  }
1737                  else if (domain->nvertex == 2)
1738                  {
1739                    dimXid     = "n" + domainName + "_edge";
1740                    dimIdList.push_back(dimXid);
1741                    dimCoordList.push_back(StdString(domainName + "_edge_x"));
1742                    dimCoordList.push_back(StdString(domainName + "_edge_y"));
1743                  }
1744                  else
1745                  {
1746                    dimXid     = "n" + domainName + "_face";
1747                    dimIdList.push_back(dimXid);
1748                    dimCoordList.push_back(StdString(domainName + "_face_x"));
1749                    dimCoordList.push_back(StdString(domainName + "_face_y"));
1750                  }
1751                }  // ugrid convention
1752              }  // case unstructured domain
[879]1753            }
[1158]1754
1755            if (domain->hasArea)
[879]1756            {
[1158]1757              hasArea = true;
1758              cellMeasures += " area" + appendDomId;
[879]1759            }
[1158]1760            ++idxDomain;
1761          }
1762          else if (1 == axisDomainOrder(i))
1763          {
1764            CAxis* axis = CAxis::get(axisList[idxAxis]);
1765            StdString axisId = axis->getAxisOutputName();
[1430]1766            StdString axisDim;
[1158]1767
[1430]1768            if (axis->dim_name.isEmpty()) axisDim = axisId;
1769            else axisDim=axis->dim_name.getValue();
1770
[1158]1771            if (compressedOutput && axis->isCompressible())
[879]1772            {
[1430]1773              dimIdList.push_back(axisDim + "_points");
[1158]1774              field->setUseCompressedOutput();
[879]1775            }
[1158]1776            else
[1430]1777              dimIdList.push_back(axisDim);
[878]1778
[1430]1779            if (axisDim != axisId) dimCoordList.push_back(axisId);
[1158]1780            ++idxAxis;
1781          }
[1430]1782          else
[1158]1783          {
[1430]1784            CScalar* scalar = CScalar::get(scalarList[idxScalar]);
1785            StdString scalarId = scalar->getScalarOutputName();
[1446]1786            if (!scalar->value.isEmpty() || !scalar->label.isEmpty())
1787              dimCoordList.push_back(scalarId);
[1430]1788            ++idxScalar;
[1158]1789          }
1790        }
[488]1791
[1158]1792        StdString fieldid = field->getFieldOutputName();
[219]1793
[1158]1794        nc_type type ;
1795        if (field->prec.isEmpty()) type =  NC_FLOAT ;
1796        else
1797        {
1798          if (field->prec==2) type = NC_SHORT ;
1799          else if (field->prec==4)  type =  NC_FLOAT ;
1800          else if (field->prec==8)   type =  NC_DOUBLE ;
1801        }
[488]1802
[1158]1803        bool wtime   = !(!field->operation.isEmpty() && field->getOperationTimeType() == func::CFunctor::once);
[488]1804
[1158]1805        if (wtime)
1806        {
1807          if (field->hasTimeInstant && hasTimeInstant) coodinates.push_back(string("time_instant"));
1808          else if (field->hasTimeCentered && hasTimeCentered)  coodinates.push_back(string("time_centered"));
1809          dims.push_back(timeid);
1810        }
[488]1811
[1961]1812        while (!dimIdList.empty())
[1158]1813        {
[1961]1814          dims.push_back(dimIdList.back());
1815          dimIdList.pop_back();
[1158]1816        }
[219]1817
[1158]1818        while (!dimCoordList.empty())
1819        {
1820          coodinates.push_back(dimCoordList.back());
1821          dimCoordList.pop_back();
1822        }
[219]1823
[1158]1824        try
1825        {
[2481]1826           SuperClassWriter::addVariable(fieldid, type, dims, false);
[2479]1827           SuperClassWriter::addChunk(field, type, dims);
[488]1828
[498]1829           if (!field->standard_name.isEmpty())
1830              SuperClassWriter::addAttribute
1831                 ("standard_name",  field->standard_name.getValue(), &fieldid);
[219]1832
[498]1833           if (!field->long_name.isEmpty())
1834              SuperClassWriter::addAttribute
1835                 ("long_name", field->long_name.getValue(), &fieldid);
[219]1836
[498]1837           if (!field->unit.isEmpty())
1838              SuperClassWriter::addAttribute
1839                 ("units", field->unit.getValue(), &fieldid);
[463]1840
[1158]1841           // Ugrid field attributes "mesh" and "location"
1842           if (!SuperClassWriter::useCFConvention)
1843           {
1844            if (!domainList.empty())
1845            {
1846              CDomain* domain = CDomain::get(domainList[0]); // Suppose that we have only domain
1847              StdString mesh = domain->name;
1848              SuperClassWriter::addAttribute("mesh", mesh, &fieldid);
1849              StdString location;
1850              if (domain->nvertex == 1)
1851                location = "node";
1852              else if (domain->nvertex == 2)
1853                location = "edge";
1854              else if (domain->nvertex > 2)
1855                location = "face";
1856              SuperClassWriter::addAttribute("location", location, &fieldid);
1857            }
1858
1859           }
1860
1861           if (!field->valid_min.isEmpty())
[498]1862              SuperClassWriter::addAttribute
1863                 ("valid_min", field->valid_min.getValue(), &fieldid);
[463]1864
[498]1865           if (!field->valid_max.isEmpty())
1866              SuperClassWriter::addAttribute
1867                 ("valid_max", field->valid_max.getValue(), &fieldid);
[464]1868
[498]1869            if (!field->scale_factor.isEmpty())
1870              SuperClassWriter::addAttribute
1871                 ("scale_factor", field->scale_factor.getValue(), &fieldid);
[464]1872
[498]1873             if (!field->add_offset.isEmpty())
1874              SuperClassWriter::addAttribute
1875                 ("add_offset", field->add_offset.getValue(), &fieldid);
[488]1876
[498]1877           SuperClassWriter::addAttribute
1878                 ("online_operation", field->operation.getValue(), &fieldid);
[472]1879
[498]1880          // write child variables as attributes
[488]1881
1882
[1021]1883           bool alreadyAddCellMethod = false;
1884           StdString cellMethodsPrefix(""), cellMethodsSuffix("");
1885           if (!field->cell_methods.isEmpty())
1886           {
[1158]1887              StdString cellMethodString = field->cell_methods;
1888              if (field->cell_methods_mode.isEmpty() ||
[1021]1889                 (CField::cell_methods_mode_attr::overwrite == field->cell_methods_mode))
[1158]1890              {
1891                SuperClassWriter::addAttribute("cell_methods", cellMethodString, &fieldid);
1892                alreadyAddCellMethod = true;
1893              }
1894              else
1895              {
1896                switch (field->cell_methods_mode)
1897                {
1898                  case (CField::cell_methods_mode_attr::prefix):
1899                    cellMethodsPrefix = cellMethodString;
1900                    cellMethodsPrefix += " ";
1901                    break;
1902                  case (CField::cell_methods_mode_attr::suffix):
1903                    cellMethodsSuffix = " ";
1904                    cellMethodsSuffix += cellMethodString;
1905                    break;
1906                  case (CField::cell_methods_mode_attr::none):
1907                    break;
1908                  default:
1909                    break;
1910                }
1911              }
[1021]1912           }
[488]1913
[1021]1914
[498]1915           if (wtime)
1916           {
[614]1917              CDuration freqOp = field->freq_op.getValue();
1918              freqOp.solveTimeStep(*context->calendar);
1919              StdString freqOpStr = freqOp.toStringUDUnits();
[612]1920              SuperClassWriter::addAttribute("interval_operation", freqOpStr, &fieldid);
[437]1921
[614]1922              CDuration freqOut = field->getRelFile()->output_freq.getValue();
1923              freqOut.solveTimeStep(*context->calendar);
1924              SuperClassWriter::addAttribute("interval_write", freqOut.toStringUDUnits(), &fieldid);
[612]1925
[1021]1926              StdString cellMethods(cellMethodsPrefix + "time: ");
[612]1927              if (field->operation.getValue() == "instant") cellMethods += "point";
1928              else if (field->operation.getValue() == "average") cellMethods += "mean";
1929              else if (field->operation.getValue() == "accumulate") cellMethods += "sum";
1930              else cellMethods += field->operation;
[614]1931              if (freqOp.resolve(*context->calendar) != freqOut.resolve(*context->calendar))
1932                cellMethods += " (interval: " + freqOpStr + ")";
[1021]1933              cellMethods += cellMethodsSuffix;
1934              if (!alreadyAddCellMethod)
1935                SuperClassWriter::addAttribute("cell_methods", cellMethods, &fieldid);
[498]1936           }
[488]1937
[611]1938           if (hasArea)
1939             SuperClassWriter::addAttribute("cell_measures", cellMeasures, &fieldid);
1940
[498]1941           if (!field->default_value.isEmpty())
1942           {
[1424]1943             double default_value = field->default_value.getValue();
1944             if (type == NC_DOUBLE)
1945             {
1946               SuperClassWriter::setDefaultValue(fieldid, &default_value);
1947             }
1948             else if (type == NC_SHORT)
1949             {
1950               short sdefault_value = (short)default_value;
1951               SuperClassWriter::setDefaultValue(fieldid, &sdefault_value);
1952             }
1953             else
1954             {
1955               float fdefault_value = (float)default_value;
1956               SuperClassWriter::setDefaultValue(fieldid, &fdefault_value);
1957             }
[498]1958           }
1959           else
[517]1960              SuperClassWriter::setDefaultValue(fieldid, (double*)NULL);
[219]1961
[606]1962            if (field->compression_level.isEmpty())
[1872]1963              field->compression_level = field->getRelFile()->compression_level.isEmpty() ? 0 : field->getRelFile()->compression_level;
[2577]1964            if ( (field->compression_level.getValue()>0)&&(field->compression_type.isEmpty()) )
[2529]1965              field->compression_type.setValue( "gzip" );
1966            if (field->compression_type.isEmpty())
1967              field->compression_type = "None";
1968            if (field->compression_params.isEmpty())
1969              field->compression_params.resize( 0 );
1970            SuperClassWriter::setCompressionLevel(fieldid, field->compression_type, field->compression_level, field->compression_params);
[606]1971
[878]1972           {  // Ecriture des coordonnes
[488]1973
[498]1974              StdString coordstr; //boost::algorithm::join(coodinates, " ")
1975              std::vector<StdString>::iterator
1976                 itc = coodinates.begin(), endc = coodinates.end();
[488]1977
[498]1978              for (; itc!= endc; itc++)
1979              {
1980                 StdString & coord = *itc;
1981                 if (itc+1 != endc)
1982                       coordstr.append(coord).append(" ");
1983                 else  coordstr.append(coord);
1984              }
[219]1985
[498]1986              SuperClassWriter::addAttribute("coordinates", coordstr, &fieldid);
[219]1987
[498]1988           }
[1222]1989
1990           vector<CVariable*> listVars = field->getAllVariables() ;
1991           for (vector<CVariable*>::iterator it = listVars.begin() ;it != listVars.end(); it++) writeAttribute_(*it, fieldid) ;
1992
[219]1993         }
[498]1994         catch (CNetCdfException& e)
1995         {
1996           StdString msg("On writing field : ");
1997           msg.append(fieldid); msg.append("\n");
1998           msg.append("In the context : ");
1999           msg.append(context->getId()); msg.append("\n");
2000           msg.append(e.what());
2001           ERROR("CNc4DataOutput::writeField_(CField* field)", << msg);
2002         }
[879]2003      } // writeField_()
[219]2004
2005      //--------------------------------------------------------------
2006
[347]2007      void CNc4DataOutput::writeFile_ (CFile* file)
[219]2008      {
[773]2009         StdString filename = file->getFileOutputName();
[219]2010         StdString description = (!file->description.isEmpty())
2011                               ? file->description.getValue()
[335]2012                               : StdString("Created by xios");
[609]2013
2014         singleDomain = (file->nbDomains == 1);
2015
[1158]2016         StdString conv_str ;
2017         if (file->convention_str.isEmpty())
2018         {
2019            if (SuperClassWriter::useCFConvention) conv_str="CF-1.6" ;
2020            else conv_str="UGRID" ;
2021         }
2022         else conv_str=file->convention_str ;
2023           
[498]2024         try
2025         {
[1309]2026           if (!appendMode) this->writeFileAttributes(filename, description,
2027                                                      conv_str,
2028                                                      StdString("An IPSL model"),
2029                                                      this->getTimeStamp());
[609]2030
[701]2031           if (!appendMode)
2032             SuperClassWriter::addDimension("axis_nbounds", 2);
[498]2033         }
2034         catch (CNetCdfException& e)
2035         {
2036           StdString msg("On writing file : ");
2037           msg.append(filename); msg.append("\n");
2038           msg.append("In the context : ");
2039           CContext* context = CContext::getCurrent() ;
2040           msg.append(context->getId()); msg.append("\n");
2041           msg.append(e.what());
2042           ERROR("CNc4DataOutput::writeFile_ (CFile* file)", << msg);
2043         }
[219]2044      }
[488]2045
[472]2046      void CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)
2047      {
[773]2048        StdString name = var->getVariableOutputName();
[488]2049
[498]2050        try
2051        {
[527]2052          if (var->type.getValue() == CVariable::type_attr::t_int || var->type.getValue() == CVariable::type_attr::t_int32)
2053            addAttribute(name, var->getData<int>(), &fieldId);
2054          else if (var->type.getValue() == CVariable::type_attr::t_int16)
2055            addAttribute(name, var->getData<short int>(), &fieldId);
2056          else if (var->type.getValue() == CVariable::type_attr::t_float)
2057            addAttribute(name, var->getData<float>(), &fieldId);
2058          else if (var->type.getValue() == CVariable::type_attr::t_double)
2059            addAttribute(name, var->getData<double>(), &fieldId);
2060          else if (var->type.getValue() == CVariable::type_attr::t_string)
2061            addAttribute(name, var->getData<string>(), &fieldId);
2062          else
2063            ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)",
2064                  << "Unsupported variable of type " << var->type.getStringValue());
[498]2065        }
2066       catch (CNetCdfException& e)
2067       {
2068         StdString msg("On writing attributes of variable with name : ");
2069         msg.append(name); msg.append("in the field "); msg.append(fieldId); msg.append("\n");
2070         msg.append("In the context : ");
2071         CContext* context = CContext::getCurrent() ;
2072         msg.append(context->getId()); msg.append("\n");
2073         msg.append(e.what());
2074         ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)", << msg);
2075       }
[472]2076     }
[488]2077
[472]2078     void CNc4DataOutput::writeAttribute_ (CVariable* var)
2079     {
[773]2080        StdString name = var->getVariableOutputName();
2081
[498]2082        try
2083        {
[527]2084          if (var->type.getValue() == CVariable::type_attr::t_int || var->type.getValue() == CVariable::type_attr::t_int32)
2085            addAttribute(name, var->getData<int>());
2086          else if (var->type.getValue() == CVariable::type_attr::t_int16)
2087            addAttribute(name, var->getData<short int>());
2088          else if (var->type.getValue() == CVariable::type_attr::t_float)
2089            addAttribute(name, var->getData<float>());
2090          else if (var->type.getValue() == CVariable::type_attr::t_double)
2091            addAttribute(name, var->getData<double>());
2092          else if (var->type.getValue() == CVariable::type_attr::t_string)
2093            addAttribute(name, var->getData<string>());
2094          else
2095            ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var)",
2096                  << "Unsupported variable of type " << var->type.getStringValue());
[498]2097        }
2098       catch (CNetCdfException& e)
2099       {
2100         StdString msg("On writing attributes of variable with name : ");
2101         msg.append(name); msg.append("\n");
2102         msg.append("In the context : ");
2103         CContext* context = CContext::getCurrent() ;
2104         msg.append(context->getId()); msg.append("\n");
2105         msg.append(e.what());
2106         ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var)", << msg);
2107       }
[488]2108     }
2109
[321]2110      void CNc4DataOutput::syncFile_ (void)
2111      {
[498]2112        try
2113        {
2114          SuperClassWriter::sync() ;
2115        }
2116        catch (CNetCdfException& e)
2117        {
2118         StdString msg("On synchronizing the write among processes");
2119         msg.append("In the context : ");
2120         CContext* context = CContext::getCurrent() ;
2121         msg.append(context->getId()); msg.append("\n");
2122         msg.append(e.what());
2123         ERROR("CNc4DataOutput::syncFile_ (void)", << msg);
2124        }
[321]2125      }
[219]2126
[286]2127      void CNc4DataOutput::closeFile_ (void)
2128      {
[498]2129        try
2130        {
2131          SuperClassWriter::close() ;
2132        }
2133        catch (CNetCdfException& e)
2134        {
2135         StdString msg("On closing file");
2136         msg.append("In the context : ");
2137         CContext* context = CContext::getCurrent() ;
2138         msg.append(context->getId()); msg.append("\n");
2139         msg.append(e.what());
2140         ERROR("CNc4DataOutput::syncFile_ (void)", << msg);
2141        }
2142
[286]2143      }
2144
[219]2145      //---------------------------------------------------------------
2146
2147      StdString CNc4DataOutput::getTimeStamp(void) const
2148      {
2149         const int buffer_size = 100;
2150         time_t rawtime;
2151         struct tm * timeinfo = NULL;
2152         char buffer [buffer_size];
[1158]2153         StdString formatStr;
2154         if (file->time_stamp_format.isEmpty()) formatStr="%Y-%b-%d %H:%M:%S %Z" ;
2155         else formatStr=file->time_stamp_format;
[219]2156
[1158]2157//         time ( &rawtime );
2158//         timeinfo = localtime ( &rawtime );
[219]2159         time ( &rawtime );
[1158]2160         timeinfo = gmtime ( &rawtime );
2161         strftime (buffer, buffer_size, formatStr.c_str(), timeinfo);
[219]2162
2163         return (StdString(buffer));
2164      }
[488]2165
[219]2166      //---------------------------------------------------------------
[488]2167
[1961]2168      int CNc4DataOutput::writeFieldData_ (CField*  field, const CArray<double,1>& data, const CDate& lastWrite,
2169                                           const CDate& currentWrite, int nstep)
[219]2170      {
[707]2171        CContext* context = CContext::getCurrent();
[1869]2172        CGrid* grid = field->getGrid();
[1961]2173       
2174        if (nstep<1) 
[1158]2175        {
[1961]2176          return nstep;
[1158]2177        }
[952]2178       
[707]2179        if (!grid->doGridHaveDataToWrite())
[1158]2180          if (SuperClass::type == MULTI_FILE || !isCollective)
2181          {
[1961]2182            return nstep;
[1158]2183          }
[488]2184
[770]2185        StdString fieldid = field->getFieldOutputName();
[286]2186
[707]2187        StdOStringStream oss;
2188        string timeAxisId;
[1158]2189        if (field->hasTimeInstant) timeAxisId = "time_instant";
2190        else if (field->hasTimeCentered) timeAxisId = "time_centered";
[488]2191
[802]2192        StdString timeBoundId = getTimeCounterName() + "_bounds";
[449]2193
[707]2194        StdString timeAxisBoundId;
[1158]2195        if (field->hasTimeInstant) timeAxisBoundId = "time_instant_bounds";
2196        else if (field->hasTimeCentered) timeAxisBoundId = "time_centered_bounds";
[488]2197
[707]2198        if (!field->wasWritten())
2199        {
[1872]2200          if (appendMode && field->getRelFile()->record_offset.isEmpty() && 
[1158]2201              field->getOperationTimeType() != func::CFunctor::once)
[707]2202          {
[1158]2203            double factorUnit;
[1872]2204            if (!field->getRelFile()->time_units.isEmpty() && field->getRelFile()->time_units==CFile::time_units_attr::days)
[1158]2205            factorUnit=context->getCalendar()->getDayLengthInSeconds() ;
2206            else factorUnit=1 ;
[1962]2207            nstep = getRecordFromTime(currentWrite,factorUnit) + 1;
[707]2208          }
[488]2209
[707]2210          field->setWritten();
2211        }
[488]2212
2213
[707]2214        CArray<double,1> time_data(1);
2215        CArray<double,1> time_data_bound(2);
2216        CArray<double,1> time_counter(1);
2217        CArray<double,1> time_counter_bound(2);
2218
2219        bool wtime = (field->getOperationTimeType() != func::CFunctor::once);
[1158]2220        bool wtimeCounter =false ;
2221        bool wtimeData =false ;
2222       
[707]2223
[444]2224        if (wtime)
2225        {
[1158]2226         
2227          if (field->hasTimeInstant)
2228          {
[2542]2229            time_data(0) = time_data_bound(1) = (Time) currentWrite;
[1961]2230            time_data_bound(0) = time_data_bound(1) = (Time) currentWrite;
[1158]2231            if (timeCounterType==instant)
2232            {
2233              time_counter(0) = time_data(0);
2234              time_counter_bound(0) = time_data_bound(0);
2235              time_counter_bound(1) = time_data_bound(1);
2236              wtimeCounter=true ;
2237            }
2238            if (hasTimeInstant) wtimeData=true ;
2239          }
2240          else if (field->hasTimeCentered)
[488]2241          {
[1961]2242            time_data(0) = ((Time)currentWrite + (Time)lastWrite) / 2;
2243            time_data_bound(0) = (Time)lastWrite;
2244            time_data_bound(1) = (Time)currentWrite;
[1158]2245            if (timeCounterType==centered)
2246            {
2247              time_counter(0) = time_data(0) ;
2248              time_counter_bound(0) = time_data_bound(0) ;
2249              time_counter_bound(1) = time_data_bound(1) ;
2250              wtimeCounter=true ;
2251            }
2252            if (hasTimeCentered) wtimeData=true ;
[488]2253          }
2254
[1158]2255          if (timeCounterType==record)
2256          {
[1961]2257            time_counter(0) = nstep - 1;
2258            time_counter_bound(0) = time_counter_bound(1) = nstep - 1;
[1158]2259            wtimeCounter=true ;
2260          }
[692]2261
[1872]2262          if (!field->getRelFile()->time_units.isEmpty() && field->getRelFile()->time_units==CFile::time_units_attr::days)
[692]2263          {
[1158]2264            double secByDay=context->getCalendar()->getDayLengthInSeconds() ;
2265            time_data/=secByDay;
2266            time_data_bound/=secByDay;
2267            time_counter/=secByDay;
2268            time_counter_bound/=secByDay;
[692]2269          }
2270        }
2271
[1853]2272         bool isRoot = (context->intraCommRank_ == 0);
[488]2273
[498]2274         try
[219]2275         {
[567]2276           switch (SuperClass::type)
[498]2277           {
[567]2278              case (MULTI_FILE) :
2279              {
[2628]2280                 if (info.isActive(logProfile)) CTimer::get("Files : writing data").resume();
[2600]2281                 writeAndConvertData(field, data, nstep - 1);
[2628]2282                 if (info.isActive(logProfile)) CTimer::get("Files : writing data").suspend();
[567]2283                 if (wtime)
2284                 {
[2628]2285                   if (info.isActive(logProfile)) CTimer::get("Files : writing time axis").resume();
[1158]2286                   if ( wtimeData)
[692]2287                   {
[1961]2288                       SuperClassWriter::writeTimeAxisData(time_data, timeAxisId, isCollective, nstep - 1, isRoot);
2289                       SuperClassWriter::writeTimeAxisDataBounds(time_data_bound, timeAxisBoundId, isCollective, nstep - 1, isRoot);
[1158]2290                  }
2291                   if (wtimeCounter)
2292                   {
[1961]2293                     SuperClassWriter::writeTimeAxisData(time_counter, getTimeCounterName(), isCollective, nstep - 1,isRoot);
2294                     if (timeCounterType!=record) SuperClassWriter::writeTimeAxisDataBounds(time_counter_bound, timeBoundId, isCollective, nstep - 1, isRoot);
[692]2295                   }
[2628]2296                   if (info.isActive(logProfile)) CTimer::get("Files : writing time axis").suspend();
[567]2297                 }
[707]2298                 break;
[567]2299              }
2300              case (ONE_FILE) :
2301              {
[464]2302
[676]2303                std::vector<StdSize> start, count;
[464]2304
[676]2305                if (field->getUseCompressedOutput())
2306                {
[1957]2307                  CArray<int,1> axisDomainOrder = grid->axis_domain_order;
2308                  std::vector<StdString> domainList = grid->getDomainList();
2309                  std::vector<StdString> axisList   = grid->getAxisList();
2310                  int numElement = axisDomainOrder.numElements();
2311                  int idxDomain = domainList.size() - 1, idxAxis = axisList.size() - 1;
2312                  int idx = domainList.size() * 2 + axisList.size() - 1;
2313                  int commRank ;
[464]2314
[1957]2315                  MPI_Comm_rank(comm_file,&commRank) ;
[676]2316
[1957]2317                  start.reserve(idx+1);
2318                  count.reserve(idx+1);
2319
2320                  for (int i = numElement - 1; i >= 0; --i)
2321                  {
2322                    if (2 == axisDomainOrder(i))
[676]2323                    {
[1957]2324                      CDomain* domain = CDomain::get(domainList[idxDomain]);
2325
2326                      if (domain->isCompressible())
[676]2327                      {
[1957]2328                        size_t offset ;
2329                        size_t nbIndexes = domain->getLocalView(CElementView::WORKFLOW)->getSize() ;
2330                        if (domain->isDistributed())
[676]2331                        {
[1957]2332                          MPI_Exscan(&nbIndexes, &offset, 1, MPI_SIZE_T, MPI_SUM, comm_file) ;
2333                          if (commRank==0) offset=0 ;
[676]2334                        }
[1957]2335                        else offset=0 ;
2336
2337                        start.push_back(offset);
2338                        count.push_back(nbIndexes);
2339                        idx -= 2;
2340                      }
2341                      else
2342                      {
2343                        if ((domain->type) != CDomain::type_attr::unstructured)
[676]2344                        {
[2507]2345                          start.push_back(domain->jbeginValue_);
2346                          count.push_back(domain->njValue_);
[676]2347                        }
[1957]2348                        --idx;
[2507]2349                        start.push_back(domain->ibeginValue_);
2350                        count.push_back(domain->niValue_);
[1957]2351                        --idx;
[676]2352                      }
[1957]2353                      --idxDomain;
2354                    }
2355                    else if (1 == axisDomainOrder(i))
2356                    {
2357                      CAxis* axis = CAxis::get(axisList[idxAxis]);
2358
2359                      if (axis->isCompressible())
[676]2360                      {
[1957]2361                        size_t offset ;
2362                        size_t nbIndexes = axis->getLocalView(CElementView::WORKFLOW)->getSize() ;
2363                        if (axis->isDistributed())
[676]2364                        {
[1957]2365                          MPI_Exscan(&nbIndexes, &offset, 1, MPI_SIZE_T, MPI_SUM, comm_file) ;
2366                          if (commRank==0) offset=0 ;
[676]2367                        }
[1957]2368                        else offset=0 ;
2369
2370                        start.push_back(offset);
2371                        count.push_back(nbIndexes);
[676]2372                      }
[1957]2373                      else
2374                      {
2375                        start.push_back(axis->begin);
2376                        count.push_back(axis->n);
2377                      }
2378                      --idxAxis;
2379                      --idx;
[676]2380                    }
[1158]2381                  }
[1961]2382                }
[676]2383                else
[498]2384                {
[887]2385                  CArray<int,1> axisDomainOrder = grid->axis_domain_order;
[705]2386                  std::vector<StdString> domainList = grid->getDomainList();
2387                  std::vector<StdString> axisList   = grid->getAxisList();
[2264]2388                  std::vector<StdString> scalarList  = grid->getScalarList() ;
[705]2389                  int numElement = axisDomainOrder.numElements();
[2391]2390                  int idxDomain = domainList.size() - 1 ;
2391                  int idxAxis = axisList.size() - 1 ;
2392                  int idxScalar = scalarList.size() - 1 ;
[1553]2393                  int idx = domainList.size() * 2 + axisList.size() - 1;
[705]2394
[1553]2395                  start.reserve(idx+1);
2396                  count.reserve(idx+1);
[705]2397
2398                  for (int i = numElement - 1; i >= 0; --i)
2399                  {
[887]2400                    if (2 == axisDomainOrder(i))
[705]2401                    {
2402                      CDomain* domain = CDomain::get(domainList[idxDomain]);
[710]2403                      if ((domain->type) != CDomain::type_attr::unstructured)
[705]2404                      {
[2507]2405                        start.push_back(domain->jbeginValue_);
2406                        count.push_back(domain->njValue_);
[705]2407                      }
2408                      --idx ;
[1143]2409
[2507]2410                        start.push_back(domain->ibeginValue_);
2411                        count.push_back(domain->niValue_);
[705]2412                      --idx ;
2413                      --idxDomain;
2414                    }
[887]2415                    else if (1 == axisDomainOrder(i))
[705]2416                    {
[1143]2417                        CAxis* axis = CAxis::get(axisList[idxAxis]);
[1559]2418                        start.push_back(axis->begin);
2419                        count.push_back(axis->n);
[705]2420                      --idx;
[1025]2421                      --idxAxis;
[887]2422                    }
2423                    else
2424                    {
[2391]2425                      if (idx ==-1) 
[887]2426                      {
[2391]2427                        CScalar* scalar = CScalar::get(scalarList[idxScalar]);
[887]2428                        start.push_back(0);
[2264]2429                        count.push_back(scalar->n);
[2391]2430                        idx-- ;
[887]2431                      }
[2391]2432                      else if (idx<-1)
2433                      {
2434                        CScalar* scalar = CScalar::get(scalarList[idxScalar]);
2435                        count.back()*=scalar->n;
2436                        idx-- ;
2437                      }
2438                      --idxScalar;
[887]2439                    }
[705]2440                  }
[498]2441                }
[488]2442
[1158]2443
[2628]2444                if (info.isActive(logProfile)) CTimer::get("Files : writing data").resume();
[2600]2445                writeAndConvertData(field, data, nstep - 1, &start, &count);
[2628]2446                if (info.isActive(logProfile)) CTimer::get("Files : writing data").suspend();
[1158]2447
2448                 if (wtime)
2449                 {
[2628]2450                   if (info.isActive(logProfile)) CTimer::get("Files : writing time axis").resume();
[1158]2451                   if ( wtimeData)
[692]2452                   {
[1961]2453                     SuperClassWriter::writeTimeAxisData(time_data, timeAxisId, isCollective, nstep - 1, isRoot);
2454                     SuperClassWriter::writeTimeAxisDataBounds(time_data_bound, timeAxisBoundId, isCollective, nstep - 1, isRoot);
[692]2455                   }
[1158]2456                   if (wtimeCounter)
2457                   {
[1961]2458                     SuperClassWriter::writeTimeAxisData(time_counter, getTimeCounterName(), isCollective, nstep - 1,isRoot);
2459                     if (timeCounterType!=record) SuperClassWriter::writeTimeAxisDataBounds(time_counter_bound, timeBoundId, isCollective, nstep - 1, isRoot);
[586]2460
[1158]2461                   }
[2628]2462                   if (info.isActive(logProfile)) CTimer::get("Files : writing time axis").suspend(); 
[1158]2463                 }
2464
[586]2465                break;
[286]2466              }
[567]2467            }
[1961]2468            return nstep ;
[219]2469         }
[498]2470         catch (CNetCdfException& e)
2471         {
2472           StdString msg("On writing field data: ");
2473           msg.append(fieldid); msg.append("\n");
2474           msg.append("In the context : ");
2475           msg.append(context->getId()); msg.append("\n");
2476           msg.append(e.what());
[1130]2477           ERROR("CNc4DataOutput::writeFieldData_ (CField*  field)", << msg);
[498]2478         }
[219]2479      }
2480
[2600]2481      void CNc4DataOutput::writeAndConvertData(CField* field, const CArray<double,1>& data, StdSize record, const std::vector<StdSize> *start, const std::vector<StdSize> *count)
2482      {
2483        StdString fieldid = field->getFieldOutputName();
2484        nc_type type ;
2485        if (field->prec.isEmpty()) type =  NC_FLOAT ;
2486        else
2487        {
2488          if (field->prec==2) type = NC_SHORT ;
2489          else if (field->prec==4)  type =  NC_FLOAT ;
2490          else if (field->prec==8)   type =  NC_DOUBLE ;
2491        }
2492
2493        bool conversionByNetCDF = true; // default : conversion operated by NetCDF for now (legacy behaviour)
[2617]2494        if (!field->conversion_by_netcdf.isEmpty())
[2600]2495        {
[2617]2496          // use conversion_by_netcdf = ".false." to  bypass NetCDF conversion
[2600]2497          //   poor performances from NC_DOUBLE to NC_FLOAT with isgreater/isless in recent NetCDF available at TGCC
[2617]2498          conversionByNetCDF = field->conversion_by_netcdf;
[2600]2499        }
2500        if ( ( type == NC_DOUBLE ) || ( conversionByNetCDF ) )
2501        {
2502          SuperClassWriter::writeData(data, fieldid, isCollective, record, start, count);
2503        }
2504        else if ( type == NC_FLOAT )
2505        {
2506          CArray<float,1> f_data;
2507          f_data.resize( data.numElements() );
2508          for (int i = 0; i < data.numElements(); i++) 
2509          {
2510            if (data(i) <= X_FLOAT_MAX || data(i) >= X_FLOAT_MIN)
2511              f_data(i) = data(i);
2512            else if (data(i) > X_FLOAT_MAX)
2513              f_data(i) = X_FLOAT_MAX;
2514            else if (data(i) < X_FLOAT_MIN)
2515              f_data(i) = X_FLOAT_MIN;
2516          }
2517          SuperClassWriter::writeData(f_data, fieldid, isCollective, record, start, count);
2518        }
2519        else if ( type == NC_SHORT )
2520        {
2521          CArray<short,1> s_data;
2522          s_data.resize( data.numElements() );
2523          for (int i = 0; i < data.numElements(); i++) 
2524          {
2525            if (data(i) <= X_SHORT_MAX || data(i) >= X_SHORT_MIN)
2526              s_data(i) = data(i);
2527            else if (data(i) > X_SHORT_MAX)
2528              s_data(i) = X_SHORT_MAX;
2529            else if (data(i) < X_SHORT_MIN)
2530              s_data(i) = X_SHORT_MIN;
2531          }
2532          SuperClassWriter::writeData(s_data, fieldid, isCollective, record, start, count);
2533        }
2534        else
2535        {
2536            ERROR("CNc4DataOutput::writeAndConvertData(...)", << "Type conversion not managed for " << fieldid ); 
2537        }
2538       
2539      }
2540
[219]2541      //---------------------------------------------------------------
2542
2543      void CNc4DataOutput::writeTimeAxis_
[347]2544                  (CField*    field,
[1542]2545                   const std::shared_ptr<CCalendar> cal)
[219]2546      {
2547         StdOStringStream oss;
[1158]2548         bool createInstantAxis=false ;
2549         bool createCenteredAxis=false ;
2550         bool createTimeCounterAxis=false ;
2551         
[645]2552         if (field->getOperationTimeType() == func::CFunctor::once) return ;
[488]2553
2554
[1158]2555         StdString axisId ;
2556         StdString axisBoundId;
[802]2557         StdString timeid(getTimeCounterName());
[614]2558         StdString timeBoundId("axis_nbounds");
[488]2559
[1158]2560         StdString strTimeUnits ;
[1872]2561         if (!field->getRelFile()->time_units.isEmpty() && field->getRelFile()->time_units==CFile::time_units_attr::days) strTimeUnits="days since " ;
[1158]2562         else  strTimeUnits="seconds since " ;
2563 
2564         if (field->getOperationTimeType() == func::CFunctor::instant) field->hasTimeInstant = true;
2565         if (field->getOperationTimeType() == func::CFunctor::centered) field->hasTimeCentered = true;
2566
2567
[1872]2568         if (field->getRelFile()->time_counter.isEmpty())
[488]2569         {
[1158]2570           if (timeCounterType==none) createTimeCounterAxis=true ;
2571           if (field->hasTimeCentered)
2572           {
2573             timeCounterType=centered ;
2574             if (!hasTimeCentered) createCenteredAxis=true ;
2575           }
2576           if (field->hasTimeInstant)
2577           {
2578             if (timeCounterType==none) timeCounterType=instant ;
2579             if (!hasTimeInstant) createInstantAxis=true ;
2580           }
[488]2581         }
[1872]2582         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::instant)
[1158]2583         {
2584           if (field->hasTimeCentered)
2585           {
2586             if (!hasTimeCentered) createCenteredAxis=true ;
2587           }
2588           if (field->hasTimeInstant)
2589           {
2590             if (timeCounterType==none) createTimeCounterAxis=true ;
2591             timeCounterType=instant ;
2592             if (!hasTimeInstant) createInstantAxis=true ;
2593           }
2594         }
[1872]2595         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::centered)
[1158]2596         {
2597           if (field->hasTimeCentered)
2598           {
2599             if (timeCounterType==none) createTimeCounterAxis=true ;
2600             timeCounterType=centered ;
2601             if (!hasTimeCentered) createCenteredAxis=true ;
2602           }
2603           if (field->hasTimeInstant)
2604           {
2605             if (!hasTimeInstant) createInstantAxis=true ;
2606           }
2607         }
[1872]2608         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::instant_exclusive)
[1158]2609         {
2610           if (field->hasTimeCentered)
2611           {
2612             if (!hasTimeCentered) createCenteredAxis=true ;
2613           }
2614           if (field->hasTimeInstant)
2615           {
2616             if (timeCounterType==none) createTimeCounterAxis=true ;
2617             timeCounterType=instant ;
2618           }
2619         }
[1872]2620         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::centered_exclusive)
[1158]2621         {
2622           if (field->hasTimeCentered)
2623           {
2624             if (timeCounterType==none) createTimeCounterAxis=true ;
2625             timeCounterType=centered ;
2626           }
2627           if (field->hasTimeInstant)
2628           {
2629             if (!hasTimeInstant) createInstantAxis=true ;
2630           }
2631         }
[1872]2632         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::exclusive)
[1158]2633         {
2634           if (field->hasTimeCentered)
2635           {
2636             if (timeCounterType==none) createTimeCounterAxis=true ;
2637             if (timeCounterType==instant) createInstantAxis=true ;
2638             timeCounterType=centered ;
2639           }
2640           if (field->hasTimeInstant)
2641           {
2642             if (timeCounterType==none)
2643             {
2644               createTimeCounterAxis=true ;
2645               timeCounterType=instant ;
2646             }
2647             if (timeCounterType==centered)
2648             {
2649               if (!hasTimeInstant) createInstantAxis=true ;
2650             }
2651           }
2652         }
[1872]2653         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::none)
[1158]2654         {
2655           if (field->hasTimeCentered)
2656           {
2657             if (!hasTimeCentered) createCenteredAxis=true ;
2658           }
2659           if (field->hasTimeInstant)
2660           {
2661             if (!hasTimeInstant) createInstantAxis=true ;
2662           }
2663         }
[1872]2664         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::record)
[1158]2665         {
2666           if (timeCounterType==none) createTimeCounterAxis=true ;
2667           timeCounterType=record ;
2668           if (field->hasTimeCentered)
2669           {
2670             if (!hasTimeCentered) createCenteredAxis=true ;
2671           }
2672           if (field->hasTimeInstant)
2673           {
2674             if (!hasTimeInstant) createInstantAxis=true ;
2675           }
2676         }
2677         
2678         if (createInstantAxis)
2679         {
2680           axisId="time_instant" ;
2681           axisBoundId="time_instant_bounds";
2682           hasTimeInstant=true ;
2683         }
[488]2684
[1158]2685         if (createCenteredAxis)
2686         {
2687           axisId="time_centered" ;
2688           axisBoundId="time_centered_bounds";
2689           hasTimeCentered=true ;
2690         }
2691
2692         
[498]2693         try
[219]2694         {
[1158]2695            std::vector<StdString> dims;
2696           
2697            if (createInstantAxis || createCenteredAxis)
2698            {
2699              // Adding time_instant or time_centered
2700              dims.push_back(timeid);
2701              if (!SuperClassWriter::varExist(axisId))
2702              {
2703                SuperClassWriter::addVariable(axisId, NC_DOUBLE, dims);
[488]2704
[1158]2705                CDate timeOrigin=cal->getTimeOrigin() ;
2706                StdOStringStream oss2;
2707                StdString strInitdate=oss2.str() ;
2708                StdString strTimeOrigin=timeOrigin.toString() ;
2709                this->writeTimeAxisAttributes(axisId, cal->getType(),strTimeUnits+strTimeOrigin,
2710                                              strTimeOrigin, axisBoundId);
2711             }
[219]2712
[1158]2713             // Adding time_instant_bounds or time_centered_bounds variables
2714             if (!SuperClassWriter::varExist(axisBoundId))
2715             {
2716                dims.clear() ;
2717                dims.push_back(timeid);
2718                dims.push_back(timeBoundId);
2719                SuperClassWriter::addVariable(axisBoundId, NC_DOUBLE, dims);
2720             }
[498]2721           }
[488]2722
[1158]2723           if (createTimeCounterAxis)
[498]2724           {
[692]2725             // Adding time_counter
[1158]2726             axisId = getTimeCounterName();
[802]2727             axisBoundId = getTimeCounterName() + "_bounds";
[692]2728             dims.clear();
2729             dims.push_back(timeid);
[1158]2730             if (!SuperClassWriter::varExist(axisId))
[692]2731             {
[1158]2732                SuperClassWriter::addVariable(axisId, NC_DOUBLE, dims);
2733                SuperClassWriter::addAttribute("axis", string("T"), &axisId);
[488]2734
[1872]2735                if (field->getRelFile()->time_counter.isEmpty() || 
2736                   (field->getRelFile()->time_counter != CFile::time_counter_attr::record))
[692]2737                {
2738                  CDate timeOrigin = cal->getTimeOrigin();
2739                  StdString strTimeOrigin = timeOrigin.toString();
[498]2740
[1158]2741                  this->writeTimeAxisAttributes(axisId, cal->getType(),
2742                                                strTimeUnits+strTimeOrigin,
[692]2743                                                strTimeOrigin, axisBoundId);
2744                }
2745             }
2746
2747             // Adding time_counter_bound dimension
[1872]2748             if (field->getRelFile()->time_counter.isEmpty() || (field->getRelFile()->time_counter != CFile::time_counter_attr::record))
[692]2749             {
2750                if (!SuperClassWriter::varExist(axisBoundId))
2751                {
2752                  dims.clear();
2753                  dims.push_back(timeid);
2754                  dims.push_back(timeBoundId);
2755                  SuperClassWriter::addVariable(axisBoundId, NC_DOUBLE, dims);
2756                }
2757             }
[498]2758           }
[488]2759         }
[498]2760         catch (CNetCdfException& e)
[488]2761         {
[498]2762           StdString msg("On writing time axis data: ");
2763           msg.append("In the context : ");
2764           CContext* context = CContext::getCurrent() ;
2765           msg.append(context->getId()); msg.append("\n");
2766           msg.append(e.what());
2767           ERROR("CNc4DataOutput::writeTimeAxis_ (CField*    field, \
[1542]2768                  const std::shared_ptr<CCalendar> cal)", << msg);
[488]2769         }
[219]2770      }
2771
2772      //---------------------------------------------------------------
[488]2773
[219]2774      void CNc4DataOutput::writeTimeAxisAttributes(const StdString & axis_name,
2775                                                   const StdString & calendar,
2776                                                   const StdString & units,
2777                                                   const StdString & time_origin,
[488]2778                                                   const StdString & time_bounds,
[219]2779                                                   const StdString & standard_name,
[613]2780                                                   const StdString & long_name)
[219]2781      {
[498]2782         try
2783         {
2784           SuperClassWriter::addAttribute("standard_name", standard_name, &axis_name);
2785           SuperClassWriter::addAttribute("long_name",     long_name    , &axis_name);
2786           SuperClassWriter::addAttribute("calendar",      calendar     , &axis_name);
2787           SuperClassWriter::addAttribute("units",         units        , &axis_name);
2788           SuperClassWriter::addAttribute("time_origin",   time_origin  , &axis_name);
2789           SuperClassWriter::addAttribute("bounds",        time_bounds  , &axis_name);
2790         }
2791         catch (CNetCdfException& e)
2792         {
2793           StdString msg("On writing time axis Attribute: ");
2794           msg.append("In the context : ");
2795           CContext* context = CContext::getCurrent() ;
2796           msg.append(context->getId()); msg.append("\n");
2797           msg.append(e.what());
2798           ERROR("CNc4DataOutput::writeTimeAxisAttributes(const StdString & axis_name, \
[613]2799                                                          const StdString & calendar,\
2800                                                          const StdString & units, \
2801                                                          const StdString & time_origin, \
2802                                                          const StdString & time_bounds, \
2803                                                          const StdString & standard_name, \
2804                                                          const StdString & long_name)", << msg);
[498]2805         }
[219]2806      }
[488]2807
[219]2808      //---------------------------------------------------------------
2809
2810      void CNc4DataOutput::writeAxisAttributes(const StdString & axis_name,
2811                                               const StdString & axis,
2812                                               const StdString & standard_name,
2813                                               const StdString & long_name,
2814                                               const StdString & units,
2815                                               const StdString & nav_model)
2816      {
[498]2817         try
2818         {
[613]2819          if (!axis.empty())
2820            SuperClassWriter::addAttribute("axis"       , axis         , &axis_name);
2821
[498]2822          SuperClassWriter::addAttribute("standard_name", standard_name, &axis_name);
2823          SuperClassWriter::addAttribute("long_name"    , long_name    , &axis_name);
2824          SuperClassWriter::addAttribute("units"        , units        , &axis_name);
[973]2825//          SuperClassWriter::addAttribute("nav_model"    , nav_model    , &axis_name);
[498]2826         }
2827         catch (CNetCdfException& e)
2828         {
2829           StdString msg("On writing Axis Attribute: ");
2830           msg.append("In the context : ");
2831           CContext* context = CContext::getCurrent() ;
2832           msg.append(context->getId()); msg.append("\n");
2833           msg.append(e.what());
2834           ERROR("CNc4DataOutput::writeAxisAttributes(const StdString & axis_name, \
[613]2835                                                      const StdString & axis, \
2836                                                      const StdString & standard_name, \
2837                                                      const StdString & long_name, \
2838                                                      const StdString & units, \
2839                                                      const StdString & nav_model)", << msg);
[498]2840         }
[219]2841      }
2842
2843      //---------------------------------------------------------------
[488]2844
[219]2845      void CNc4DataOutput::writeLocalAttributes
2846         (int ibegin, int ni, int jbegin, int nj, StdString domid)
2847      {
[498]2848        try
2849        {
[318]2850         SuperClassWriter::addAttribute(StdString("ibegin").append(domid), ibegin);
2851         SuperClassWriter::addAttribute(StdString("ni"    ).append(domid), ni);
2852         SuperClassWriter::addAttribute(StdString("jbegin").append(domid), jbegin);
2853         SuperClassWriter::addAttribute(StdString("nj"    ).append(domid), nj);
[498]2854        }
2855        catch (CNetCdfException& e)
2856        {
2857           StdString msg("On writing Local Attributes: ");
2858           msg.append("In the context : ");
2859           CContext* context = CContext::getCurrent() ;
2860           msg.append(context->getId()); msg.append("\n");
2861           msg.append(e.what());
2862           ERROR("CNc4DataOutput::writeLocalAttributes \
2863                  (int ibegin, int ni, int jbegin, int nj, StdString domid)", << msg);
2864        }
2865
[219]2866      }
2867
[628]2868      void CNc4DataOutput::writeLocalAttributes_IOIPSL(const StdString& dimXid, const StdString& dimYid,
2869                                                       int ibegin, int ni, int jbegin, int nj, int ni_glo, int nj_glo, int rank, int size)
[391]2870      {
2871         CArray<int,1> array(2) ;
2872
[498]2873         try
2874         {
2875           SuperClassWriter::addAttribute("DOMAIN_number_total",size ) ;
2876           SuperClassWriter::addAttribute("DOMAIN_number", rank) ;
[629]2877           array = SuperClassWriter::getDimension(dimXid) + 1, SuperClassWriter::getDimension(dimYid) + 1;
[498]2878           SuperClassWriter::addAttribute("DOMAIN_dimensions_ids",array) ;
2879           array=ni_glo,nj_glo ;
2880           SuperClassWriter::addAttribute("DOMAIN_size_global", array) ;
2881           array=ni,nj ;
2882           SuperClassWriter::addAttribute("DOMAIN_size_local", array) ;
[819]2883           array=ibegin+1,jbegin+1 ;
[498]2884           SuperClassWriter::addAttribute("DOMAIN_position_first", array) ;
[819]2885           array=ibegin+ni-1+1,jbegin+nj-1+1 ;
[498]2886           SuperClassWriter::addAttribute("DOMAIN_position_last",array) ;
2887           array=0,0 ;
2888           SuperClassWriter::addAttribute("DOMAIN_halo_size_start", array) ;
2889           SuperClassWriter::addAttribute("DOMAIN_halo_size_end", array);
2890           SuperClassWriter::addAttribute("DOMAIN_type",string("box")) ;
2891  /*
2892           SuperClassWriter::addAttribute("DOMAIN_DIM_N001",string("x")) ;
2893           SuperClassWriter::addAttribute("DOMAIN_DIM_N002",string("y")) ;
2894           SuperClassWriter::addAttribute("DOMAIN_DIM_N003",string("axis_A")) ;
2895           SuperClassWriter::addAttribute("DOMAIN_DIM_N004",string("time_counter")) ;
2896  */
2897         }
2898         catch (CNetCdfException& e)
2899         {
[628]2900           StdString msg("On writing Local Attributes IOIPSL \n");
[498]2901           msg.append("In the context : ");
2902           CContext* context = CContext::getCurrent() ;
2903           msg.append(context->getId()); msg.append("\n");
2904           msg.append(e.what());
2905           ERROR("CNc4DataOutput::writeLocalAttributes_IOIPSL \
2906                  (int ibegin, int ni, int jbegin, int nj, int ni_glo, int nj_glo, int rank, int size)", << msg);
2907         }
[391]2908      }
[219]2909      //---------------------------------------------------------------
2910
2911      void CNc4DataOutput:: writeFileAttributes(const StdString & name,
2912                                                const StdString & description,
2913                                                const StdString & conventions,
2914                                                const StdString & production,
2915                                                const StdString & timeStamp)
2916      {
[498]2917         try
2918         {
2919           SuperClassWriter::addAttribute("name"       , name);
2920           SuperClassWriter::addAttribute("description", description);
[613]2921           SuperClassWriter::addAttribute("title"      , description);
2922           SuperClassWriter::addAttribute("Conventions", conventions);
[1158]2923           // SuperClassWriter::addAttribute("production" , production);
2924
2925           StdString timeStampStr ;
2926           if (file->time_stamp_name.isEmpty()) timeStampStr="timeStamp" ;
2927           else timeStampStr=file->time_stamp_name ;
2928           SuperClassWriter::addAttribute(timeStampStr, timeStamp);
2929
2930           StdString uuidName ;
2931           if (file->uuid_name.isEmpty()) uuidName="uuid" ;
2932           else uuidName=file->uuid_name ;
2933
2934           if (file->uuid_format.isEmpty()) SuperClassWriter::addAttribute(uuidName, getUuidStr());
2935           else SuperClassWriter::addAttribute(uuidName, getUuidStr(file->uuid_format));
2936         
[498]2937         }
2938         catch (CNetCdfException& e)
2939         {
2940           StdString msg("On writing File Attributes \n ");
2941           msg.append("In the context : ");
2942           CContext* context = CContext::getCurrent() ;
2943           msg.append(context->getId()); msg.append("\n");
2944           msg.append(e.what());
2945           ERROR("CNc4DataOutput:: writeFileAttributes(const StdString & name, \
2946                                                const StdString & description, \
2947                                                const StdString & conventions, \
2948                                                const StdString & production, \
2949                                                const StdString & timeStamp)", << msg);
2950         }
[219]2951      }
2952
2953      //---------------------------------------------------------------
2954
2955      void CNc4DataOutput::writeMaskAttributes(const StdString & mask_name,
2956                                               int data_dim,
2957                                               int data_ni,
2958                                               int data_nj,
2959                                               int data_ibegin,
2960                                               int data_jbegin)
2961      {
[498]2962         try
2963         {
2964           SuperClassWriter::addAttribute("data_dim"   , data_dim   , &mask_name);
2965           SuperClassWriter::addAttribute("data_ni"    , data_ni    , &mask_name);
2966           SuperClassWriter::addAttribute("data_nj"    , data_nj    , &mask_name);
2967           SuperClassWriter::addAttribute("data_ibegin", data_ibegin, &mask_name);
2968           SuperClassWriter::addAttribute("data_jbegin", data_jbegin, &mask_name);
2969         }
2970         catch (CNetCdfException& e)
2971         {
2972           StdString msg("On writing Mask Attributes \n ");
2973           msg.append("In the context : ");
2974           CContext* context = CContext::getCurrent() ;
2975           msg.append(context->getId()); msg.append("\n");
2976           msg.append(e.what());
2977           ERROR("CNc4DataOutput::writeMaskAttributes(const StdString & mask_name, \
2978                                               int data_dim, \
2979                                               int data_ni, \
2980                                               int data_nj, \
2981                                               int data_ibegin, \
2982                                               int data_jbegin)", << msg);
2983         }
[219]2984      }
2985
2986      ///--------------------------------------------------------------
2987
[1158]2988      StdSize CNc4DataOutput::getRecordFromTime(Time time, double factorUnit)
[707]2989      {
2990        std::map<Time, StdSize>::const_iterator it = timeToRecordCache.find(time);
2991        if (it == timeToRecordCache.end())
2992        {
[802]2993          StdString timeAxisBoundsId(getTimeCounterName() + "_bounds");
[1158]2994          if (!SuperClassWriter::varExist(timeAxisBoundsId)) timeAxisBoundsId = "time_centered_bounds";
2995          if (!SuperClassWriter::varExist(timeAxisBoundsId)) timeAxisBoundsId = "time_instant_bounds";
[707]2996
2997          CArray<double,2> timeAxisBounds;
[1158]2998          std::vector<StdSize> dimSize(SuperClassWriter::getDimensions(timeAxisBoundsId)) ;
2999         
[707]3000          StdSize record = 0;
3001          double dtime(time);
[1158]3002          for (int n = dimSize[0] - 1; n >= 0; n--)
[707]3003          {
[1158]3004            SuperClassWriter::getTimeAxisBounds(timeAxisBounds, timeAxisBoundsId, isCollective, n);
3005            timeAxisBounds*=factorUnit ;
3006            if (timeAxisBounds(1, 0) < dtime)
[707]3007            {
3008              record = n + 1;
3009              break;
3010            }
3011          }
3012          it = timeToRecordCache.insert(std::make_pair(time, record)).first;
3013        }
3014        return it->second;
3015      }
[774]3016
3017      ///--------------------------------------------------------------
3018
3019      bool CNc4DataOutput::isWrittenDomain(const std::string& domainName) const
3020      {
3021        return (this->writtenDomains.find(domainName) != this->writtenDomains.end());
3022      }
3023
3024      bool CNc4DataOutput::isWrittenCompressedDomain(const std::string& domainName) const
3025      {
3026        return (this->writtenCompressedDomains.find(domainName) != this->writtenCompressedDomains.end());
3027      }
3028
3029      bool CNc4DataOutput::isWrittenAxis(const std::string& axisName) const
3030      {
3031        return (this->writtenAxis.find(axisName) != this->writtenAxis.end());
3032      }
3033
3034      bool CNc4DataOutput::isWrittenCompressedAxis(const std::string& axisName) const
3035      {
3036        return (this->writtenCompressedAxis.find(axisName) != this->writtenCompressedAxis.end());
3037      }
3038
[887]3039      bool CNc4DataOutput::isWrittenScalar(const std::string& scalarName) const
3040      {
3041        return (this->writtenScalar.find(scalarName) != this->writtenScalar.end());
3042      }
3043
[774]3044      void CNc4DataOutput::setWrittenDomain(const std::string& domainName)
3045      {
3046        this->writtenDomains.insert(domainName);
3047      }
3048
3049      void CNc4DataOutput::setWrittenCompressedDomain(const std::string& domainName)
3050      {
3051        this->writtenCompressedDomains.insert(domainName);
3052      }
3053
3054      void CNc4DataOutput::setWrittenAxis(const std::string& axisName)
3055      {
3056        this->writtenAxis.insert(axisName);
3057      }
3058
3059      void CNc4DataOutput::setWrittenCompressedAxis(const std::string& axisName)
3060      {
3061        this->writtenCompressedAxis.insert(axisName);
3062      }
[887]3063
3064      void CNc4DataOutput::setWrittenScalar(const std::string& scalarName)
3065      {
3066        this->writtenScalar.insert(scalarName);
3067      }
[335]3068} // namespace xios
Note: See TracBrowser for help on using the repository browser.