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

Last change on this file since 2385 was 2385, checked in by jderouillat, 2 years ago

Move in a new method of CLocalView the management of a without redundancy full view connector (used in hash computation of elements)

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