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
Line 
1#include "nc4_data_output.hpp"
2
3#include "attribute_template.hpp"
4#include "group_template.hpp"
5
6#include "file.hpp"
7#include "calendar.hpp"
8#include "context.hpp"
9#include "context_server.hpp"
10#include "netCdfException.hpp"
11#include "exception.hpp"
12#include "timer.hpp"
13#include "uuid.hpp"
14namespace xios
15{
16      /// ////////////////////// Dfinitions ////////////////////// ///
17      CNc4DataOutput::CNc4DataOutput
18         (CFile* file, const StdString & filename, bool exist)
19            : SuperClass()
20            , SuperClassWriter(filename, exist)
21            , filename(filename)
22            , file(file),hasTimeInstant(false),hasTimeCentered(false), timeCounterType(none), relElements_()
23      {
24        SuperClass::type = MULTI_FILE;
25        compressionLevel= file->compression_level.isEmpty() ? 0 :file->compression_level ;
26      }
27
28      CNc4DataOutput::CNc4DataOutput
29         (CFile* file, const StdString & filename, bool exist, bool useClassicFormat, bool useCFConvention,
30          MPI_Comm comm_file, bool multifile, bool isCollective, const StdString& timeCounterName)
31            : SuperClass()
32            , SuperClassWriter(filename, exist, useClassicFormat, useCFConvention, &comm_file, multifile, timeCounterName)
33            , comm_file(comm_file)
34            , filename(filename)
35            , isCollective(isCollective)
36            , file(file),hasTimeInstant(false),hasTimeCentered(false), timeCounterType(none), relElements_()
37      {
38        SuperClass::type = (multifile) ? MULTI_FILE : ONE_FILE;
39        if (file==NULL) compressionLevel = 0 ;
40        else compressionLevel= file->compression_level.isEmpty() ? 0 :file->compression_level ;
41      }
42
43      CNc4DataOutput::~CNc4DataOutput(void)
44    { /* Ne rien faire de plus */ }
45
46      ///--------------------------------------------------------------
47
48      const StdString & CNc4DataOutput::getFileName(void) const
49      {
50         return (this->filename);
51      }
52
53      //---------------------------------------------------------------
54
55      void CNc4DataOutput::writeDomain_(CDomain* domain)
56      TRY
57      {
58        StdString lonName,latName ;
59
60        if (domain->type == CDomain::type_attr::unstructured)
61        {
62          if (SuperClassWriter::useCFConvention)
63            writeUnstructuredDomain(domain) ;
64          else
65            writeUnstructuredDomainUgrid(domain) ;
66          return ;
67        }
68
69         CContext* context = CContext::getCurrent() ;
70         if (domain->IsWritten(this->filename)) return;
71         domain->checkAttributes();
72
73         if (domain->isEmpty())
74           if (SuperClass::type==MULTI_FILE) return;
75
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         {
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;
83           // Compute a without redundancy element FULL view to enable a consistent hash computation
84           domain->getLocalView(CElementView::FULL)->createWithoutRedundancyFullViewConnector( globalSize, comm_file, gridTransformConnector, globalIndex );
85           int localSize = globalIndex.numElements();
86           
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();
99           if ( !relDomains_.count ( defaultNameKey ) )
100           {
101             // if defaultNameKey not in the map, write the element such as it is defined
102             relDomains_.insert( make_pair( defaultNameKey, make_pair(globalHash, domain) ) );
103           }
104           else // look if a hash associated this key is equal
105           {
106             bool elementIsInMap(false);
107             auto defaultNameKeyElements = relDomains_.equal_range( defaultNameKey );
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
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;
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();
125               relDomains_.insert( make_pair( defaultNameKey, make_pair(globalHash, domain) ) ) ;         
126             }
127           }
128         }
129
130         
131         std::vector<StdString> dim0, dim1;
132         StdString domid = domain->getDomainOutputName();
133         StdString appendDomid  = (singleDomain) ? "" : "_"+domid ;
134         if (isWrittenDomain(domid)) return ;
135         else setWrittenDomain(domid);
136       
137         int nvertex = (domain->nvertex.isEmpty()) ? 0 : domain->nvertex;
138
139
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         
147         bool isRegularDomain = (domain->type == CDomain::type_attr::rectilinear);
148         switch (domain->type)
149         {
150           case CDomain::type_attr::curvilinear :
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
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
164             break ;
165
166           case CDomain::type_attr::rectilinear :
167
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             }
175             else lonName = domain->lon_name;
176
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             }
184             else latName = domain->lat_name;
185             
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;
191             break;
192         }
193
194         StdString dimVertId = StdString("nvertex").append(appendDomid);
195
196         string lonid,latid,bounds_lonid,bounds_latid ;
197         string areaId = "area" + appendDomid;
198
199         try
200         {
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);
209                     lonid = lonName+appendDomid;
210                     latid = latName+appendDomid;
211                     break ;
212                   case CDomain::type_attr::rectilinear :
213                     lonid = lonName+appendDomid;
214                     latid = latName+appendDomid;
215                     dim0.push_back(dimYid);
216                     dim1.push_back(dimXid);
217                     break;
218                 }
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;
223
224                 SuperClassWriter::addDimension(dimXid, domain->ni);
225                 SuperClassWriter::addDimension(dimYid, domain->nj);
226
227                 if (domain->hasBounds)
228                   SuperClassWriter::addDimension(dimVertId, domain->nvertex);
229
230                 if (context->intraCommSize_ > 1)
231                 {
232                   this->writeLocalAttributes(domain->ibegin,
233                                              domain->ni,
234                                              domain->jbegin,
235                                              domain->nj,
236                                              appendDomid);
237
238                   if (singleDomain)
239                    this->writeLocalAttributes_IOIPSL(dimXid, dimYid,
240                                                      domain->ibegin,
241                                                      domain->ni,
242                                                      domain->jbegin,
243                                                      domain->nj,
244                                                      domain->ni_glo,domain->nj_glo,
245                                                      context->intraCommRank_,context->intraCommSize_);
246                 }
247
248                 if (domain->hasLonLat)
249                 {
250                   switch (domain->type)
251                   {
252                     case CDomain::type_attr::curvilinear :
253                       SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
254                       SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
255                       break ;
256                      case CDomain::type_attr::rectilinear :
257                        SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
258                        SuperClassWriter::addVariable(lonid, typePrec, dim1, compressionLevel);
259                        break ;
260                   }
261
262                   this->writeAxisAttributes(lonid, isRegularDomain ? "X" : "", "longitude", "Longitude", "degrees_east", domid);
263                   this->writeAxisAttributes(latid, isRegularDomain ? "Y" : "", "latitude", "Latitude", "degrees_north", domid);
264
265                   if (domain->hasBounds)
266                   {
267                     SuperClassWriter::addAttribute("bounds", bounds_lonid, &lonid);
268                     SuperClassWriter::addAttribute("bounds", bounds_latid, &latid);
269
270                     dim0.clear();
271                     dim0.push_back(dimYid);
272                     dim0.push_back(dimXid);
273                     dim0.push_back(dimVertId);
274                     SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
275                     SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
276                   }
277                 }
278
279                 dim0.clear();
280                 dim0.push_back(dimYid);
281                 dim0.push_back(dimXid);
282
283                 if (domain->hasArea)
284                 {
285                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
286                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
287                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
288                 }
289
290                 SuperClassWriter::definition_end();
291
292                 if (domain->hasLonLat)
293                 {
294                   switch (domain->type)
295                   {
296                     case CDomain::type_attr::curvilinear :                       
297                       SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0);
298                       SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0);
299                       break;
300                     case CDomain::type_attr::rectilinear :
301                       CArray<double,1> lat = domain->latvalue(Range(fromStart,toEnd,domain->ni)) ;
302                       SuperClassWriter::writeData(CArray<double,1>(lat.copy()), latid, isCollective, 0);
303                       CArray<double,1> lon = domain->lonvalue(Range(0,domain->ni-1)) ;
304                       SuperClassWriter::writeData(CArray<double,1>(lon.copy()), lonid, isCollective, 0);
305                       break;
306                   }
307
308                   if (domain->hasBounds)
309                   {
310                     SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0);
311                     SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0);
312                   }
313                 }
314
315                 if (domain->hasArea)
316                 {
317                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0);                   
318                 }
319
320                 SuperClassWriter::definition_start();
321
322                 break;
323              }
324              case (ONE_FILE) :
325              {
326                SuperClassWriter::addDimension(dimXid, domain->ni_glo);
327                SuperClassWriter::addDimension(dimYid, domain->nj_glo);
328
329                 if (domain->hasBounds)
330                   SuperClassWriter::addDimension(dimVertId, domain->nvertex);
331
332                 if (domain->hasLonLat)
333                 {
334                   switch (domain->type)
335                   {
336                     case CDomain::type_attr::curvilinear :
337                       dim0.push_back(dimYid); dim0.push_back(dimXid);
338                       lonid = lonName+appendDomid;
339                       latid = latName+appendDomid;
340                       SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
341                       SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
342                       break;
343
344                     case CDomain::type_attr::rectilinear :
345                       dim0.push_back(dimYid);
346                       dim1.push_back(dimXid);
347                       lonid = lonName+appendDomid;
348                       latid = latName+appendDomid;
349                       SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
350                       SuperClassWriter::addVariable(lonid, typePrec, dim1, compressionLevel);
351                       break;
352                   }
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;
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();
369                     dim0.push_back(dimYid);
370                     dim0.push_back(dimXid);
371                     dim0.push_back(dimVertId);
372                     SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
373                     SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
374                   }
375                 }
376
377                 if (domain->hasArea)
378                 {
379                   dim0.clear();
380                   dim0.push_back(dimYid); dim0.push_back(dimXid);
381                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
382                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
383                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
384                   dim0.clear();
385                 }
386
387                 SuperClassWriter::definition_end();
388
389                 switch (domain->type)
390                 {
391                   case CDomain::type_attr::curvilinear :
392                   {
393                     std::vector<StdSize> start(2) ;
394                     std::vector<StdSize> count(2) ;
395                     start[1]=domain->ibegin;
396                     start[0]=domain->jbegin;
397                     count[1]=domain->ni ; count[0]=domain->nj ;
398
399                     if (domain->hasLonLat)
400                     {
401                       SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0,&start,&count);
402                       SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0,&start,&count);
403                     }
404                     break;
405                   }
406                   case CDomain::type_attr::rectilinear :
407                   {
408                     if (domain->hasLonLat)
409                     {
410                       std::vector<StdSize> start(1) ;
411                       std::vector<StdSize> count(1) ;
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);
417
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);
422                     }
423                     break;
424                   }
425                 }
426
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;
439                     start[1] = domain->ibegin;
440                     start[0] = domain->jbegin;
441                     count[2] = domain->nvertex;
442                     count[1] = domain->ni;
443                     count[0] = domain->nj;
444                   }
445                 
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);
448                 }
449
450                 if (domain->hasArea)
451                 {
452                   std::vector<StdSize> start(2);
453                   std::vector<StdSize> count(2);
454
455                   start[1] = domain->ibegin;
456                   start[0] = domain->jbegin;
457                   count[1] = domain->ni;
458                   count[0] = domain->nj;
459                   
460                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0, &start, &count);
461                 }
462
463                 SuperClassWriter::definition_start();
464                 break;
465              }
466              default :
467                 ERROR("CNc4DataOutput::writeDomain(domain)",
468                       << "[ type = " << SuperClass::type << "]"
469                       << " not implemented yet !");
470           }
471         }
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
482         domain->addRelFile(this->filename);
483      }
484      CATCH
485
486    //--------------------------------------------------------------
487
488    void CNc4DataOutput::writeUnstructuredDomainUgrid(CDomain* domain)
489    {
490      CContext* context = CContext::getCurrent() ;
491
492      if (domain->IsWritten(this->filename)) return;
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
501      domain->checkAttributes();
502      if (domain->isEmpty())
503        if (SuperClass::type==MULTI_FILE) return ;
504
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
510      std::vector<StdString> dim0;
511      StdString domainName = domain->name;
512      domain->assignMesh(domainName, domain->nvertex);
513      domain->mesh->createMeshEpsilon(context->intraComm_, domain->lonvalue, domain->latvalue, domain->bounds_lonvalue, domain->bounds_latvalue);
514
515      StdString node_x = domainName + "_node_x";
516      StdString node_y = domainName + "_node_y";
517
518      StdString edge_x = domainName + "_edge_x";
519      StdString edge_y = domainName + "_edge_y";
520      StdString edge_nodes = domainName + "_edge_nodes";
521
522      StdString face_x = domainName + "_face_x";
523      StdString face_y = domainName + "_face_y";
524      StdString face_nodes = domainName + "_face_nodes";
525      StdString face_edges = domainName + "_face_edges";
526      StdString edge_faces = domainName + "_edge_face_links";
527      StdString face_faces = domainName + "_face_links";
528
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";
534
535      if (!SuperClassWriter::dimExist(dimTwo)) SuperClassWriter::addDimension(dimTwo, 2);
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);
542
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              {
554                SuperClassWriter::addDimension(dimNode, domain->ni_glo);
555                dim0.clear();
556                dim0.push_back(dimNode);
557                SuperClassWriter::addVariable(node_x, typePrec, dim0, compressionLevel);
558                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &node_x);
559                SuperClassWriter::addAttribute("long_name", StdString("Longitude of mesh nodes."), &node_x);
560                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &node_x);
561                SuperClassWriter::addVariable(node_y, typePrec, dim0, compressionLevel);
562                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &node_y);
563                SuperClassWriter::addAttribute("long_name", StdString("Latitude of mesh nodes."), &node_y);
564                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &node_y);
565              }
566            } // domain->nvertex == 1
567
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              {
573                SuperClassWriter::addDimension(dimNode, domain->mesh->nbNodesGlo);
574                dim0.clear();
575                dim0.push_back(dimNode);
576                SuperClassWriter::addVariable(node_x, typePrec, dim0, compressionLevel);
577                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &node_x);
578                SuperClassWriter::addAttribute("long_name", StdString("Longitude of mesh nodes."), &node_x);
579                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &node_x);
580                SuperClassWriter::addVariable(node_y, typePrec, dim0, compressionLevel);
581                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &node_y);
582                SuperClassWriter::addAttribute("long_name", StdString("Latitude of mesh nodes."), &node_y);
583                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &node_y);
584              }
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);
590              SuperClassWriter::addVariable(edge_x, typePrec, dim0, compressionLevel);
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);
594              SuperClassWriter::addVariable(edge_y, typePrec, dim0, compressionLevel);
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);
601              SuperClassWriter::addVariable(edge_nodes, NC_INT, dim0, compressionLevel);
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);
605            } // domain->nvertex == 2
606
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              {
613                SuperClassWriter::addDimension(dimNode, domain->mesh->nbNodesGlo);
614                dim0.clear();
615                dim0.push_back(dimNode);
616                SuperClassWriter::addVariable(node_x, typePrec, dim0, compressionLevel);
617                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &node_x);
618                SuperClassWriter::addAttribute("long_name", StdString("Longitude of mesh nodes."), &node_x);
619                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &node_x);
620                SuperClassWriter::addVariable(node_y, typePrec, dim0, compressionLevel);
621                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &node_y);
622                SuperClassWriter::addAttribute("long_name", StdString("Latitude of mesh nodes."), &node_y);
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);
629                SuperClassWriter::addDimension(dimEdge, domain->mesh->nbEdgesGlo);
630                dim0.clear();
631                dim0.push_back(dimEdge);
632                SuperClassWriter::addVariable(edge_x, typePrec, dim0, compressionLevel);
633                SuperClassWriter::addAttribute("standard_name", StdString("longitude"), &edge_x);
634                SuperClassWriter::addAttribute("long_name", StdString("Characteristic longitude of mesh edges."), &edge_x);
635                SuperClassWriter::addAttribute("units", StdString("degrees_east"), &edge_x);
636                SuperClassWriter::addVariable(edge_y, typePrec, dim0, compressionLevel);
637                SuperClassWriter::addAttribute("standard_name", StdString("latitude"), &edge_y);
638                SuperClassWriter::addAttribute("long_name", StdString("Characteristic latitude of mesh edges."), &edge_y);
639                SuperClassWriter::addAttribute("units", StdString("degrees_north"), &edge_y);
640                dim0.clear();
641                dim0.push_back(dimEdge);
642                dim0.push_back(dimTwo);
643                SuperClassWriter::addVariable(edge_nodes, NC_INT, dim0, compressionLevel);
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              }
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);
654              SuperClassWriter::addVariable(face_x, typePrec, dim0, compressionLevel);
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);
658              SuperClassWriter::addVariable(face_y, typePrec, dim0, compressionLevel);
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);
665              SuperClassWriter::addVariable(face_nodes, NC_INT, dim0, compressionLevel);
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);
672              SuperClassWriter::addVariable(face_edges, NC_INT, dim0, compressionLevel);
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);
676              SuperClassWriter::addAttribute("_FillValue", 999999, &face_edges);
677              dim0.clear();
678              dim0.push_back(dimEdge);
679              dim0.push_back(dimTwo);
680              SuperClassWriter::addVariable(edge_faces, NC_INT, dim0, compressionLevel);
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);
689              SuperClassWriter::addVariable(face_faces, NC_INT, dim0, compressionLevel);
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);
693              SuperClassWriter::addAttribute("_FillValue", 999999, &face_faces);
694              SuperClassWriter::addAttribute("flag_values", -1, &face_faces);
695              SuperClassWriter::addAttribute("flag_meanings", StdString("out_of_mesh"), &face_faces);
696            } // domain->nvertex > 2
697
698            SuperClassWriter::definition_end();
699
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) ;
712
713            if (domain->nvertex == 1)
714            {
715              if (domain->isEmpty())
716               {
717                 startNodes[0]=0 ;
718                 countNodes[0]=0 ;
719               }
720               else
721               {
722                 startNodes[0] = domain->ibegin;
723                 countNodes[0] = domain->ni ;
724               }
725
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;
741
742               }
743               else
744               {
745                 startEdges[0] = domain->ibegin;
746                 countEdges[0] = domain->ni;
747                 startNodes[0] = domain->mesh->node_start;
748                 countNodes[0] = domain->mesh->node_count;
749                 startEdgeNodes[0] = domain->ibegin;
750                 startEdgeNodes[1] = 0;
751                 countEdgeNodes[0] = domain->ni;
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            }
760            else
761            {
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               {
781                 startFaces[0] = domain->ibegin;
782                 countFaces[0] = domain->ni ;
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;
795                 startFaceConctv[0] = domain->ibegin;
796                 startFaceConctv[1] = 0;
797                 countFaceConctv[0] = domain->ni;
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            }
812            SuperClassWriter::definition_start();
813
814            break;
815          } // ONE_FILE
816
817          case (MULTI_FILE) :
818          {
819            ERROR("CNc4DataOutput::writeDomain(domain)",
820            << "[ type = multiple_file ]"
821            << " is not yet implemented for UGRID files !");
822            break;
823          }
824
825          default :
826          ERROR("CNc4DataOutput::writeDomain(domain)",
827          << "[ type = " << SuperClass::type << "]"
828          << " not implemented yet !");
829          } // switch
830        } // try
831
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());
839          ERROR("CNc4DataOutput::writeUnstructuredDomainUgrid(CDomain* domain)", << msg);
840        }
841
842  domain->addRelFile(this->filename);
843  }
844
845    //--------------------------------------------------------------
846
847    void CNc4DataOutput::writeUnstructuredDomain(CDomain* domain)
848      {
849         CContext* context = CContext::getCurrent() ;
850
851         if (domain->IsWritten(this->filename)) return;
852         domain->checkAttributes();
853
854         if (domain->isEmpty())
855           if (SuperClass::type==MULTI_FILE) return ;
856
857         std::vector<StdString> dim0, dim1;
858         StdString domid = domain->getDomainOutputName();
859         if (isWrittenDomain(domid)) return ;
860         else setWrittenDomain(domid);
861
862         StdString appendDomid  = (singleDomain) ? "" : "_"+domid ;
863
864         StdString lonName,latName, cellName ;
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
871         if (!domain->dim_i_name.isEmpty()) cellName=domain->dim_i_name;
872         else cellName="cell";
873         StdString dimXid = cellName+appendDomid;
874         StdString dimVertId = StdString("nvertex").append(appendDomid);
875
876         string lonid,latid,bounds_lonid,bounds_latid ;
877         string areaId = "area" + appendDomid;
878
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
884         int nvertex = (domain->nvertex.isEmpty()) ? 0 : domain->nvertex;
885
886         try
887         {
888           switch (SuperClass::type)
889           {
890              case (MULTI_FILE) :
891              {
892                 dim0.push_back(dimXid);
893                 SuperClassWriter::addDimension(dimXid, domain->ni);
894
895                 lonid = lonName+appendDomid;
896                 latid = latName+appendDomid;
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
902                 if (domain->hasLonLat)
903                 {
904                   SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
905                   SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
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                 }
912                 dim0.clear();
913                 if (domain->hasBounds)
914                 {
915                   dim0.push_back(dimXid);
916                   dim0.push_back(dimVertId);
917                   SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
918                   SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
919                 }
920
921                 dim0.clear();
922                 dim0.push_back(dimXid);
923                 if (domain->hasArea)
924                 {
925                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
926                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
927                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
928                 }
929
930                 SuperClassWriter::definition_end();
931
932                 if (domain->hasLonLat)
933                 {
934                   SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0);
935                   SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0);
936                   if (domain->hasBounds)
937                   {
938                     SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0);
939                     SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0);
940                   }
941                 }
942
943                 if (domain->hasArea)
944                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0);
945
946                 SuperClassWriter::definition_start();
947                 break ;
948              }
949
950              case (ONE_FILE) :
951              {
952                 lonid = lonName+appendDomid;
953                 latid = latName+appendDomid;
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;
958
959                 dim0.push_back(dimXid);
960                 SuperClassWriter::addDimension(dimXid, domain->ni_glo);
961                 if (domain->hasLonLat)
962                 {
963                   SuperClassWriter::addVariable(latid, typePrec, dim0, compressionLevel);
964                   SuperClassWriter::addVariable(lonid, typePrec, dim0, compressionLevel);
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);
970                   if (domain->hasBounds) SuperClassWriter::addDimension(dimVertId, nvertex);
971                 }
972                 dim0.clear();
973
974                 if (domain->hasBounds)
975                 {
976                   dim0.push_back(dimXid);
977                   dim0.push_back(dimVertId);
978                   SuperClassWriter::addVariable(bounds_lonid, typePrec, dim0, compressionLevel);
979                   SuperClassWriter::addVariable(bounds_latid, typePrec, dim0, compressionLevel);
980                 }
981
982                 if (domain->hasArea)
983                 {
984                   dim0.clear();
985                   dim0.push_back(dimXid);
986                   SuperClassWriter::addVariable(areaId, typePrec, dim0, compressionLevel);
987                   SuperClassWriter::addAttribute("standard_name", StdString("cell_area"), &areaId);
988                   SuperClassWriter::addAttribute("units", StdString("m2"), &areaId);
989                 }
990
991                 SuperClassWriter::definition_end();
992
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 ;
1000                   countBounds[1]=nvertex ;
1001                   startBounds[0]=0 ;
1002                   countBounds[0]=0 ;
1003                 }
1004                 else
1005                 {
1006                   start[0]=domain->ibegin;
1007                   count[0]=domain->ni;
1008                   startBounds[0]=domain->ibegin;
1009                   startBounds[1]=0 ;
1010                   countBounds[0]=domain->ni;
1011                   countBounds[1]=nvertex ;
1012                 }
1013
1014                 if (domain->hasLonLat)
1015                 {
1016                   SuperClassWriter::writeData(domain->latvalue, latid, isCollective, 0,&start,&count);
1017                   SuperClassWriter::writeData(domain->lonvalue, lonid, isCollective, 0,&start,&count);
1018                   if (domain->hasBounds)
1019                   {
1020                     SuperClassWriter::writeData(domain->bounds_lonvalue, bounds_lonid, isCollective, 0,&startBounds,&countBounds);
1021                     SuperClassWriter::writeData(domain->bounds_latvalue, bounds_latid, isCollective, 0,&startBounds,&countBounds);
1022                   }
1023                 }
1024
1025                 if (domain->hasArea)
1026                   SuperClassWriter::writeData(domain->areavalue, areaId, isCollective, 0, &start, &count);
1027
1028                 SuperClassWriter::definition_start();
1029
1030                 break;
1031              }
1032              default :
1033                 ERROR("CNc4DataOutput::writeDomain(domain)",
1034                       << "[ type = " << SuperClass::type << "]"
1035                       << " not implemented yet !");
1036           }
1037         }
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         }
1047         domain->addRelFile(this->filename);
1048      }
1049      //--------------------------------------------------------------
1050
1051      void CNc4DataOutput::writeAxis_(CAxis* axis)
1052      {
1053        if (axis->IsWritten(this->filename)) return;
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        {
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();
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
1103        axis->checkAttributes();
1104
1105        int size  = (MULTI_FILE == SuperClass::type) ? axis->n.getValue()
1106                                                          : axis->n_glo.getValue();
1107
1108        if ((0 == axis->n) && (MULTI_FILE == SuperClass::type)) return;
1109
1110        std::vector<StdString> dims;
1111        StdString axisid = axis->getAxisOutputName();
1112        StdString axisDim, axisBoundsId;
1113        if (isWrittenAxis(axisid)) return ;
1114        else setWrittenAxis(axisid);
1115
1116        nc_type typePrec ;
1117        if (axis->prec.isEmpty()) typePrec =  NC_FLOAT ;
1118        else if (axis->prec==4)   typePrec =  NC_FLOAT ;
1119        else if (axis->prec==8)   typePrec =  NC_DOUBLE ;
1120         
1121        if (!axis->label.isEmpty()) typePrec = NC_CHAR ;
1122        string strId="str_len" ;
1123        try
1124        {
1125          if (axis->dim_name.isEmpty()) axisDim = axisid;
1126          else axisDim=axis->dim_name.getValue();
1127          SuperClassWriter::addDimension(axisDim, size);
1128          dims.push_back(axisDim);
1129
1130          if (!axis->label.isEmpty() && !SuperClassWriter::dimExist(strId)) SuperClassWriter::addDimension(strId, stringArrayLen);
1131
1132          if (axis->hasValue || !axis->label.isEmpty())
1133          {
1134            if (!axis->label.isEmpty()) dims.push_back(strId);
1135
1136            SuperClassWriter::addVariable(axisid, typePrec, dims, compressionLevel);
1137
1138            if (!axis->name.isEmpty())
1139              SuperClassWriter::addAttribute("name", axis->name.getValue(), &axisid);
1140
1141            if (!axis->standard_name.isEmpty())
1142              SuperClassWriter::addAttribute("standard_name", axis->standard_name.getValue(), &axisid);
1143
1144            if (!axis->long_name.isEmpty())
1145              SuperClassWriter::addAttribute("long_name", axis->long_name.getValue(), &axisid);
1146
1147            if (!axis->unit.isEmpty())
1148              SuperClassWriter::addAttribute("units", axis->unit.getValue(), &axisid);
1149
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
1169            if (!axis->positive.isEmpty())
1170            {
1171              SuperClassWriter::addAttribute("positive",
1172                                             (axis->positive == CAxis::positive_attr::up) ? string("up") : string("down"),
1173                                             &axisid);
1174            }
1175
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             
1182            axisBoundsId = (axis->bounds_name.isEmpty()) ? axisid + "_bounds" : axis->bounds_name;
1183            if (!axis->bounds.isEmpty() && axis->label.isEmpty())
1184            {
1185              dims.push_back("axis_nbounds");
1186              SuperClassWriter::addVariable(axisBoundsId, typePrec, dims, compressionLevel);
1187              SuperClassWriter::addAttribute("bounds", axisBoundsId, &axisid);
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
1195              if (!axis->formula_bounds.isEmpty())
1196                SuperClassWriter::addAttribute("formula", axis->formula_bounds.getValue(), &axisBoundsId);
1197
1198              if (!axis->formula_term_bounds.isEmpty())
1199                SuperClassWriter::addAttribute("formula_term", axis->formula_term_bounds.getValue(), &axisBoundsId);
1200            }
1201          }
1202
1203          SuperClassWriter::definition_end();
1204         
1205          switch (SuperClass::type)
1206          {
1207            case MULTI_FILE:
1208            {
1209              if (axis->label.isEmpty())
1210              {
1211                if (!axis->value.isEmpty())
1212                  SuperClassWriter::writeData(axis->value, axisid, isCollective, 0);
1213
1214                if (!axis->bounds.isEmpty())
1215                  SuperClassWriter::writeData(axis->bounds, axisBoundsId, isCollective, 0);
1216              }
1217              else
1218                SuperClassWriter::writeData(axis->label, axisid, isCollective, 0);
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) ;
1227              start[0] = startBounds[0] = axis->begin;
1228              count[0] = countBounds[0] = axis->n;
1229              startBounds[1] = 0;
1230              countBounds[1] = 2;
1231
1232              if (axis->label.isEmpty())
1233              {
1234                if (!axis->value.isEmpty())
1235                  SuperClassWriter::writeData(axis->value, axisid, isCollective, 0, &start, &count);
1236
1237                if (!axis->bounds.isEmpty())
1238                  SuperClassWriter::writeData(axis->bounds, axisBoundsId, isCollective, 0, &startBounds, &countBounds);
1239              }
1240              else
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;
1245                SuperClassWriter::writeData(axis->label, axisid, isCollective, 0, &startLabel, &countLabel);
1246              }
1247
1248              SuperClassWriter::definition_start();
1249
1250              break;
1251            }
1252            default :
1253              ERROR("CNc4DataOutput::writeAxis_(CAxis* axis)",
1254                    << "[ type = " << SuperClass::type << "]"
1255                    << " not implemented yet !");
1256          }
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        }
1268        axis->addRelFile(this->filename);
1269     }
1270
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();
1278        StdString boundsId;
1279        if (isWrittenAxis(scalaId)) return ;
1280        else setWrittenAxis(scalaId);
1281
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
1287        if (!scalar->label.isEmpty()) typePrec = NC_CHAR ;
1288        string strId="str_len" ;
1289
1290        try
1291        {
1292          if (!scalar->label.isEmpty() && !SuperClassWriter::dimExist(strId)) SuperClassWriter::addDimension(strId, stringArrayLen);
1293
1294          if (!scalar->value.isEmpty() || !scalar->label.isEmpty())
1295          {
1296            std::vector<StdString> dims;
1297            StdString scalarDim = scalaId;
1298
1299            if (!scalar->label.isEmpty()) dims.push_back(strId);
1300
1301            SuperClassWriter::addVariable(scalaId, typePrec, dims);
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
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
1334            if (!scalar->positive.isEmpty())
1335            {
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            {
1343              dims.clear();
1344              dims.push_back("axis_nbounds");
1345              boundsId = (scalar->bounds_name.isEmpty()) ? (scalaId + "_bounds") : scalar->bounds_name.getValue();
1346              SuperClassWriter::addVariable(boundsId, typePrec, dims);
1347              SuperClassWriter::addAttribute("bounds", boundsId, &scalaId);
1348            }
1349
1350            SuperClassWriter::definition_end();
1351
1352            switch (SuperClass::type)
1353            {
1354              case MULTI_FILE:
1355              {
1356                CArray<double,1> scalarValue(scalarSize);
1357                CArray<string,1> scalarLabel(scalarSize);
1358                CArray<double,1> scalarBounds(scalarSize*2);
1359
1360                if (!scalar->value.isEmpty() && scalar->label.isEmpty())
1361                {
1362                  scalarValue(0) = scalar->value;
1363                  SuperClassWriter::writeData(scalarValue, scalaId, isCollective, 0);
1364                }
1365
1366                if (!scalar->bounds.isEmpty() && scalar->label.isEmpty())
1367                {
1368                  scalarBounds(0) = scalar->bounds(0);
1369                  scalarBounds(1) = scalar->bounds(1);
1370                  SuperClassWriter::writeData(scalarBounds, boundsId, isCollective, 0);
1371                }
1372
1373                if (!scalar->label.isEmpty())
1374                {
1375                  scalarLabel(0) = scalar->label;
1376                  SuperClassWriter::writeData(scalarLabel, scalaId, isCollective, 0);
1377                }
1378
1379                SuperClassWriter::definition_start();
1380
1381                break;
1382              }
1383              case ONE_FILE:
1384              {
1385                CArray<double,1> scalarValue(scalarSize);
1386                CArray<string,1> scalarLabel(scalarSize);
1387                CArray<double,1> scalarBounds(scalarSize*2);
1388
1389                std::vector<StdSize> start(1);
1390                std::vector<StdSize> count(1);
1391                start[0] = 0;
1392                count[0] = 1;
1393                if (!scalar->value.isEmpty() && scalar->label.isEmpty())
1394                {
1395                  scalarValue(0) = scalar->value;
1396                  SuperClassWriter::writeData(scalarValue, scalaId, isCollective, 0, &start, &count);
1397                }
1398                if (!scalar->bounds.isEmpty() && scalar->label.isEmpty())
1399                {
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);
1404                }
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
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
1436     //--------------------------------------------------------------
1437
1438     void CNc4DataOutput::writeGridCompressed_(CGrid* grid)
1439     {
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) ;
1460
1461          std::vector<StdString> dims;
1462
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();
1475
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 ?
1483
1484              string lonName,latName ;
1485
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;
1492
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;
1501
1502              varId = domId + "_points";
1503              compress = latName + appendDomId + " " + lonName + appendDomId;
1504     
1505              shared_ptr<CLocalView> workflowView = domain->getLocalView(CElementView::WORKFLOW) ;
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              }
1520
1521              firstGlobalIndex = domain->ibegin + domain->jbegin * domain->ni_glo;
1522
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();
1531
1532              if (!axis->isCompressible()
1533                  || axis->isWrittenCompressed(this->filename)
1534                  || isWrittenCompressedAxis(axisId))
1535                continue;
1536
1537              varId = axisId + "_points";
1538              compress = axisId;
1539
1540              shared_ptr<CLocalView> workflowView = axis->getLocalView(CElementView::WORKFLOW) ;
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            }
1565
1566            if (!varId.empty())
1567            {
1568              SuperClassWriter::addDimension(varId, (SuperClass::type == MULTI_FILE) ? nbIndexes : totalNbIndexes);
1569
1570              dims.clear();
1571              dims.push_back(varId);
1572              SuperClassWriter::addVariable(varId, NC_UINT64, dims);
1573
1574              SuperClassWriter::addAttribute("compress", compress, &varId);
1575
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);
1589
1590                  SuperClassWriter::writeData(indexes, varId, isCollective, 0, &start, &count);
1591                  break;
1592                }
1593              }
1594            }
1595          }
1596
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      }
1610
1611     //--------------------------------------------------------------
1612
1613     void CNc4DataOutput::writeTimeDimension_(void)
1614     {
1615       try
1616       {
1617        SuperClassWriter::addDimension(getTimeCounterName());
1618       }
1619       catch (CNetCdfException& e)
1620       {
1621         StdString msg("On writing time dimension : time_couter\n");
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       }
1628     }
1629
1630      //--------------------------------------------------------------
1631
1632      void CNc4DataOutput::writeField_(CField* field)
1633      {
1634        CContext* context = CContext::getCurrent() ;
1635
1636        std::vector<StdString> dims, coodinates;
1637        CGrid* grid = field->getGrid();
1638        if (!grid->doGridHaveDataToWrite())
1639          if (SuperClass::type==MULTI_FILE) return ;
1640
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();       
1646
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;
1653
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 ;
1661            StdString lonName,latName ;
1662            StdString dimIname,dimJname ;
1663
1664            if (domain->lon_name.isEmpty())
1665            { 
1666              if (domain->type==CDomain::type_attr::curvilinear) lonName = "nav_lon";
1667              else lonName = "lon";
1668            }
1669            else lonName = domain->lon_name;
1670
1671            if (domain->lat_name.isEmpty())
1672            {
1673              if (domain->type==CDomain::type_attr::curvilinear) latName = "nav_lat";
1674              else latName = "lat";
1675            }
1676            else latName = domain->lat_name;
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;
1692       
1693            if (compressedOutput && domain->isCompressible() && domain->type != CDomain::type_attr::unstructured)
1694            {
1695              dimIdList.push_back(domId + "_points");
1696              field->setUseCompressedOutput();
1697            }
1698
1699            switch (domain->type)
1700            {
1701              case CDomain::type_attr::curvilinear:
1702                if (!compressedOutput || !domain->isCompressible())
1703                {
1704                  dimXid=dimIname+appendDomId;
1705                  dimYid=dimJname+appendDomId;
1706                  dimIdList.push_back(dimXid);
1707                  dimIdList.push_back(dimYid);
1708                }
1709                dimCoordList.push_back(lonName+appendDomId);
1710                dimCoordList.push_back(latName+appendDomId);
1711              break ;
1712              case CDomain::type_attr::rectilinear:
1713                if (!compressedOutput || !domain->isCompressible())
1714                {
1715                  dimXid     = dimIname+appendDomId;
1716                  dimYid     = dimJname+appendDomId;
1717                  dimIdList.push_back(dimXid);
1718                  dimIdList.push_back(dimYid);
1719                }
1720                if (lonName != dimIname)  dimCoordList.push_back(lonName+appendDomId);
1721                if (latName != dimJname)  dimCoordList.push_back(latName+appendDomId);
1722
1723              break ;
1724              case CDomain::type_attr::unstructured:
1725              {
1726                if (SuperClassWriter::useCFConvention)
1727                {
1728                  dimXid     = dimIname + appendDomId;
1729                  dimIdList.push_back(dimXid);
1730                  dimCoordList.push_back(lonName+appendDomId);
1731                  dimCoordList.push_back(latName+appendDomId);
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
1759            }
1760
1761            if (domain->hasArea)
1762            {
1763              hasArea = true;
1764              cellMeasures += " area" + appendDomId;
1765            }
1766            ++idxDomain;
1767          }
1768          else if (1 == axisDomainOrder(i))
1769          {
1770            CAxis* axis = CAxis::get(axisList[idxAxis]);
1771            StdString axisId = axis->getAxisOutputName();
1772            StdString axisDim;
1773
1774            if (axis->dim_name.isEmpty()) axisDim = axisId;
1775            else axisDim=axis->dim_name.getValue();
1776
1777            if (compressedOutput && axis->isCompressible())
1778            {
1779              dimIdList.push_back(axisDim + "_points");
1780              field->setUseCompressedOutput();
1781            }
1782            else
1783              dimIdList.push_back(axisDim);
1784
1785            if (axisDim != axisId) dimCoordList.push_back(axisId);
1786            ++idxAxis;
1787          }
1788          else
1789          {
1790            CScalar* scalar = CScalar::get(scalarList[idxScalar]);
1791            StdString scalarId = scalar->getScalarOutputName();
1792            if (!scalar->value.isEmpty() || !scalar->label.isEmpty())
1793              dimCoordList.push_back(scalarId);
1794            ++idxScalar;
1795          }
1796        }
1797
1798        StdString fieldid = field->getFieldOutputName();
1799
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        }
1808
1809        bool wtime   = !(!field->operation.isEmpty() && field->getOperationTimeType() == func::CFunctor::once);
1810
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        }
1817
1818        while (!dimIdList.empty())
1819        {
1820          dims.push_back(dimIdList.back());
1821          dimIdList.pop_back();
1822        }
1823
1824        while (!dimCoordList.empty())
1825        {
1826          coodinates.push_back(dimCoordList.back());
1827          dimCoordList.pop_back();
1828        }
1829
1830        try
1831        {
1832           SuperClassWriter::addVariable(fieldid, type, dims);
1833
1834           if (!field->standard_name.isEmpty())
1835              SuperClassWriter::addAttribute
1836                 ("standard_name",  field->standard_name.getValue(), &fieldid);
1837
1838           if (!field->long_name.isEmpty())
1839              SuperClassWriter::addAttribute
1840                 ("long_name", field->long_name.getValue(), &fieldid);
1841
1842           if (!field->unit.isEmpty())
1843              SuperClassWriter::addAttribute
1844                 ("units", field->unit.getValue(), &fieldid);
1845
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())
1867              SuperClassWriter::addAttribute
1868                 ("valid_min", field->valid_min.getValue(), &fieldid);
1869
1870           if (!field->valid_max.isEmpty())
1871              SuperClassWriter::addAttribute
1872                 ("valid_max", field->valid_max.getValue(), &fieldid);
1873
1874            if (!field->scale_factor.isEmpty())
1875              SuperClassWriter::addAttribute
1876                 ("scale_factor", field->scale_factor.getValue(), &fieldid);
1877
1878             if (!field->add_offset.isEmpty())
1879              SuperClassWriter::addAttribute
1880                 ("add_offset", field->add_offset.getValue(), &fieldid);
1881
1882           SuperClassWriter::addAttribute
1883                 ("online_operation", field->operation.getValue(), &fieldid);
1884
1885          // write child variables as attributes
1886
1887
1888           bool alreadyAddCellMethod = false;
1889           StdString cellMethodsPrefix(""), cellMethodsSuffix("");
1890           if (!field->cell_methods.isEmpty())
1891           {
1892              StdString cellMethodString = field->cell_methods;
1893              if (field->cell_methods_mode.isEmpty() ||
1894                 (CField::cell_methods_mode_attr::overwrite == field->cell_methods_mode))
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              }
1917           }
1918
1919
1920           if (wtime)
1921           {
1922              CDuration freqOp = field->freq_op.getValue();
1923              freqOp.solveTimeStep(*context->calendar);
1924              StdString freqOpStr = freqOp.toStringUDUnits();
1925              SuperClassWriter::addAttribute("interval_operation", freqOpStr, &fieldid);
1926
1927              CDuration freqOut = field->getRelFile()->output_freq.getValue();
1928              freqOut.solveTimeStep(*context->calendar);
1929              SuperClassWriter::addAttribute("interval_write", freqOut.toStringUDUnits(), &fieldid);
1930
1931              StdString cellMethods(cellMethodsPrefix + "time: ");
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;
1936              if (freqOp.resolve(*context->calendar) != freqOut.resolve(*context->calendar))
1937                cellMethods += " (interval: " + freqOpStr + ")";
1938              cellMethods += cellMethodsSuffix;
1939              if (!alreadyAddCellMethod)
1940                SuperClassWriter::addAttribute("cell_methods", cellMethods, &fieldid);
1941           }
1942
1943           if (hasArea)
1944             SuperClassWriter::addAttribute("cell_measures", cellMeasures, &fieldid);
1945
1946           if (!field->default_value.isEmpty())
1947           {
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             }
1963           }
1964           else
1965              SuperClassWriter::setDefaultValue(fieldid, (double*)NULL);
1966
1967            if (field->compression_level.isEmpty())
1968              field->compression_level = field->getRelFile()->compression_level.isEmpty() ? 0 : field->getRelFile()->compression_level;
1969            SuperClassWriter::setCompressionLevel(fieldid, field->compression_level);
1970
1971           {  // Ecriture des coordonnes
1972
1973              StdString coordstr; //boost::algorithm::join(coodinates, " ")
1974              std::vector<StdString>::iterator
1975                 itc = coodinates.begin(), endc = coodinates.end();
1976
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              }
1984
1985              SuperClassWriter::addAttribute("coordinates", coordstr, &fieldid);
1986
1987           }
1988
1989           vector<CVariable*> listVars = field->getAllVariables() ;
1990           for (vector<CVariable*>::iterator it = listVars.begin() ;it != listVars.end(); it++) writeAttribute_(*it, fieldid) ;
1991
1992         }
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         }
2002      } // writeField_()
2003
2004      //--------------------------------------------------------------
2005
2006      void CNc4DataOutput::writeFile_ (CFile* file)
2007      {
2008         StdString filename = file->getFileOutputName();
2009         StdString description = (!file->description.isEmpty())
2010                               ? file->description.getValue()
2011                               : StdString("Created by xios");
2012
2013         singleDomain = (file->nbDomains == 1);
2014
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           
2023         try
2024         {
2025           if (!appendMode) this->writeFileAttributes(filename, description,
2026                                                      conv_str,
2027                                                      StdString("An IPSL model"),
2028                                                      this->getTimeStamp());
2029
2030           if (!appendMode)
2031             SuperClassWriter::addDimension("axis_nbounds", 2);
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         }
2043      }
2044
2045      void CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)
2046      {
2047        StdString name = var->getVariableOutputName();
2048
2049        try
2050        {
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());
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       }
2075     }
2076
2077     void CNc4DataOutput::writeAttribute_ (CVariable* var)
2078     {
2079        StdString name = var->getVariableOutputName();
2080
2081        try
2082        {
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());
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       }
2107     }
2108
2109      void CNc4DataOutput::syncFile_ (void)
2110      {
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        }
2124      }
2125
2126      void CNc4DataOutput::closeFile_ (void)
2127      {
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
2142      }
2143
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];
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;
2155
2156//         time ( &rawtime );
2157//         timeinfo = localtime ( &rawtime );
2158         time ( &rawtime );
2159         timeinfo = gmtime ( &rawtime );
2160         strftime (buffer, buffer_size, formatStr.c_str(), timeinfo);
2161
2162         return (StdString(buffer));
2163      }
2164
2165      //---------------------------------------------------------------
2166
2167      int CNc4DataOutput::writeFieldData_ (CField*  field, const CArray<double,1>& data, const CDate& lastWrite,
2168                                           const CDate& currentWrite, int nstep)
2169      {
2170        CContext* context = CContext::getCurrent();
2171        CGrid* grid = field->getGrid();
2172       
2173        if (nstep<1) 
2174        {
2175          return nstep;
2176        }
2177       
2178        if (!grid->doGridHaveDataToWrite())
2179          if (SuperClass::type == MULTI_FILE || !isCollective)
2180          {
2181            return nstep;
2182          }
2183
2184        StdString fieldid = field->getFieldOutputName();
2185
2186        StdOStringStream oss;
2187        string timeAxisId;
2188        if (field->hasTimeInstant) timeAxisId = "time_instant";
2189        else if (field->hasTimeCentered) timeAxisId = "time_centered";
2190
2191        StdString timeBoundId = getTimeCounterName() + "_bounds";
2192
2193        StdString timeAxisBoundId;
2194        if (field->hasTimeInstant) timeAxisBoundId = "time_instant_bounds";
2195        else if (field->hasTimeCentered) timeAxisBoundId = "time_centered_bounds";
2196
2197        if (!field->wasWritten())
2198        {
2199          if (appendMode && field->getRelFile()->record_offset.isEmpty() && 
2200              field->getOperationTimeType() != func::CFunctor::once)
2201          {
2202            double factorUnit;
2203            if (!field->getRelFile()->time_units.isEmpty() && field->getRelFile()->time_units==CFile::time_units_attr::days)
2204            factorUnit=context->getCalendar()->getDayLengthInSeconds() ;
2205            else factorUnit=1 ;
2206            nstep = getRecordFromTime(currentWrite,factorUnit) + 1;
2207          }
2208
2209          field->setWritten();
2210        }
2211
2212
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);
2219        bool wtimeCounter =false ;
2220        bool wtimeData =false ;
2221       
2222
2223        if (wtime)
2224        {
2225         
2226          if (field->hasTimeInstant)
2227          {
2228            time_data(0) = time_data_bound(1) = (Time) lastWrite;
2229            time_data_bound(0) = time_data_bound(1) = (Time) currentWrite;
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)
2240          {
2241            time_data(0) = ((Time)currentWrite + (Time)lastWrite) / 2;
2242            time_data_bound(0) = (Time)lastWrite;
2243            time_data_bound(1) = (Time)currentWrite;
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 ;
2252          }
2253
2254          if (timeCounterType==record)
2255          {
2256            time_counter(0) = nstep - 1;
2257            time_counter_bound(0) = time_counter_bound(1) = nstep - 1;
2258            wtimeCounter=true ;
2259          }
2260
2261          if (!field->getRelFile()->time_units.isEmpty() && field->getRelFile()->time_units==CFile::time_units_attr::days)
2262          {
2263            double secByDay=context->getCalendar()->getDayLengthInSeconds() ;
2264            time_data/=secByDay;
2265            time_data_bound/=secByDay;
2266            time_counter/=secByDay;
2267            time_counter_bound/=secByDay;
2268          }
2269        }
2270
2271         bool isRoot = (context->intraCommRank_ == 0);
2272
2273         try
2274         {
2275           switch (SuperClass::type)
2276           {
2277              case (MULTI_FILE) :
2278              {
2279                 CTimer::get("Files : writing data").resume();
2280                 SuperClassWriter::writeData(data, fieldid, isCollective, nstep - 1);
2281                 CTimer::get("Files : writing data").suspend();
2282                 if (wtime)
2283                 {
2284                   CTimer::get("Files : writing time axis").resume();
2285                   if ( wtimeData)
2286                   {
2287                       SuperClassWriter::writeTimeAxisData(time_data, timeAxisId, isCollective, nstep - 1, isRoot);
2288                       SuperClassWriter::writeTimeAxisDataBounds(time_data_bound, timeAxisBoundId, isCollective, nstep - 1, isRoot);
2289                  }
2290                   if (wtimeCounter)
2291                   {
2292                     SuperClassWriter::writeTimeAxisData(time_counter, getTimeCounterName(), isCollective, nstep - 1,isRoot);
2293                     if (timeCounterType!=record) SuperClassWriter::writeTimeAxisDataBounds(time_counter_bound, timeBoundId, isCollective, nstep - 1, isRoot);
2294                   }
2295                   CTimer::get("Files : writing time axis").suspend();
2296                 }
2297                 break;
2298              }
2299              case (ONE_FILE) :
2300              {
2301
2302                std::vector<StdSize> start, count;
2303
2304                if (field->getUseCompressedOutput())
2305                {
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 ;
2313
2314                  MPI_Comm_rank(comm_file,&commRank) ;
2315
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))
2322                    {
2323                      CDomain* domain = CDomain::get(domainList[idxDomain]);
2324
2325                      if (domain->isCompressible())
2326                      {
2327                        size_t offset ;
2328                        size_t nbIndexes = domain->getLocalView(CElementView::WORKFLOW)->getSize() ;
2329                        if (domain->isDistributed())
2330                        {
2331                          MPI_Exscan(&nbIndexes, &offset, 1, MPI_SIZE_T, MPI_SUM, comm_file) ;
2332                          if (commRank==0) offset=0 ;
2333                        }
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)
2343                        {
2344                          start.push_back(domain->jbegin);
2345                          count.push_back(domain->nj);
2346                        }
2347                        --idx;
2348                        start.push_back(domain->ibegin);
2349                        count.push_back(domain->ni);
2350                        --idx;
2351                      }
2352                      --idxDomain;
2353                    }
2354                    else if (1 == axisDomainOrder(i))
2355                    {
2356                      CAxis* axis = CAxis::get(axisList[idxAxis]);
2357
2358                      if (axis->isCompressible())
2359                      {
2360                        size_t offset ;
2361                        size_t nbIndexes = axis->getLocalView(CElementView::WORKFLOW)->getSize() ;
2362                        if (axis->isDistributed())
2363                        {
2364                          MPI_Exscan(&nbIndexes, &offset, 1, MPI_SIZE_T, MPI_SUM, comm_file) ;
2365                          if (commRank==0) offset=0 ;
2366                        }
2367                        else offset=0 ;
2368
2369                        start.push_back(offset);
2370                        count.push_back(nbIndexes);
2371                      }
2372                      else
2373                      {
2374                        start.push_back(axis->begin);
2375                        count.push_back(axis->n);
2376                      }
2377                      --idxAxis;
2378                      --idx;
2379                    }
2380                  }
2381                }
2382                else
2383                {
2384                  CArray<int,1> axisDomainOrder = grid->axis_domain_order;
2385                  std::vector<StdString> domainList = grid->getDomainList();
2386                  std::vector<StdString> axisList   = grid->getAxisList();
2387                  std::vector<StdString> scalarList  = grid->getScalarList() ;
2388                  int numElement = axisDomainOrder.numElements();
2389                  int idxDomain = domainList.size() - 1, idxAxis = axisList.size() - 1;
2390                  int idx = domainList.size() * 2 + axisList.size() - 1;
2391
2392                  start.reserve(idx+1);
2393                  count.reserve(idx+1);
2394
2395                  for (int i = numElement - 1; i >= 0; --i)
2396                  {
2397                    if (2 == axisDomainOrder(i))
2398                    {
2399                      CDomain* domain = CDomain::get(domainList[idxDomain]);
2400                      if ((domain->type) != CDomain::type_attr::unstructured)
2401                      {
2402                        start.push_back(domain->jbegin);
2403                        count.push_back(domain->nj);
2404                      }
2405                      --idx ;
2406
2407                        start.push_back(domain->ibegin);
2408                        count.push_back(domain->ni);
2409                      --idx ;
2410                      --idxDomain;
2411                    }
2412                    else if (1 == axisDomainOrder(i))
2413                    {
2414                        CAxis* axis = CAxis::get(axisList[idxAxis]);
2415                        start.push_back(axis->begin);
2416                        count.push_back(axis->n);
2417                      --idx;
2418                      --idxAxis;
2419                    }
2420                    else
2421                    {
2422                      if (1 == axisDomainOrder.numElements())
2423                      {
2424                        CScalar* scalar = CScalar::get(scalarList[scalarList.size()-1]);
2425                        start.push_back(0);
2426                        count.push_back(scalar->n);
2427                      }
2428                      --idx;
2429                    }
2430                  }
2431                }
2432
2433
2434                CTimer::get("Files : writing data").resume();
2435                SuperClassWriter::writeData(data, fieldid, isCollective, nstep - 1, &start, &count);
2436                CTimer::get("Files : writing data").suspend();
2437
2438                 if (wtime)
2439                 {
2440                   CTimer::get("Files : writing time axis").resume();
2441                   if ( wtimeData)
2442                   {
2443                     SuperClassWriter::writeTimeAxisData(time_data, timeAxisId, isCollective, nstep - 1, isRoot);
2444                     SuperClassWriter::writeTimeAxisDataBounds(time_data_bound, timeAxisBoundId, isCollective, nstep - 1, isRoot);
2445                   }
2446                   if (wtimeCounter)
2447                   {
2448                     SuperClassWriter::writeTimeAxisData(time_counter, getTimeCounterName(), isCollective, nstep - 1,isRoot);
2449                     if (timeCounterType!=record) SuperClassWriter::writeTimeAxisDataBounds(time_counter_bound, timeBoundId, isCollective, nstep - 1, isRoot);
2450
2451                   }
2452                   CTimer::get("Files : writing time axis").suspend(); 
2453                 }
2454
2455                break;
2456              }
2457            }
2458            return nstep ;
2459         }
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());
2467           ERROR("CNc4DataOutput::writeFieldData_ (CField*  field)", << msg);
2468         }
2469      }
2470
2471      //---------------------------------------------------------------
2472
2473      void CNc4DataOutput::writeTimeAxis_
2474                  (CField*    field,
2475                   const std::shared_ptr<CCalendar> cal)
2476      {
2477         StdOStringStream oss;
2478         bool createInstantAxis=false ;
2479         bool createCenteredAxis=false ;
2480         bool createTimeCounterAxis=false ;
2481         
2482         if (field->getOperationTimeType() == func::CFunctor::once) return ;
2483
2484
2485         StdString axisId ;
2486         StdString axisBoundId;
2487         StdString timeid(getTimeCounterName());
2488         StdString timeBoundId("axis_nbounds");
2489
2490         StdString strTimeUnits ;
2491         if (!field->getRelFile()->time_units.isEmpty() && field->getRelFile()->time_units==CFile::time_units_attr::days) strTimeUnits="days since " ;
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
2498         if (field->getRelFile()->time_counter.isEmpty())
2499         {
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           }
2511         }
2512         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::instant)
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         }
2525         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::centered)
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         }
2538         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::instant_exclusive)
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         }
2550         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::centered_exclusive)
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         }
2562         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::exclusive)
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         }
2583         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::none)
2584         {
2585           if (field->hasTimeCentered)
2586           {
2587             if (!hasTimeCentered) createCenteredAxis=true ;
2588           }
2589           if (field->hasTimeInstant)
2590           {
2591             if (!hasTimeInstant) createInstantAxis=true ;
2592           }
2593         }
2594         else if (field->getRelFile()->time_counter==CFile::time_counter_attr::record)
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         }
2614
2615         if (createCenteredAxis)
2616         {
2617           axisId="time_centered" ;
2618           axisBoundId="time_centered_bounds";
2619           hasTimeCentered=true ;
2620         }
2621
2622         
2623         try
2624         {
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);
2634
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             }
2642
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             }
2651           }
2652
2653           if (createTimeCounterAxis)
2654           {
2655             // Adding time_counter
2656             axisId = getTimeCounterName();
2657             axisBoundId = getTimeCounterName() + "_bounds";
2658             dims.clear();
2659             dims.push_back(timeid);
2660             if (!SuperClassWriter::varExist(axisId))
2661             {
2662                SuperClassWriter::addVariable(axisId, NC_DOUBLE, dims);
2663                SuperClassWriter::addAttribute("axis", string("T"), &axisId);
2664
2665                if (field->getRelFile()->time_counter.isEmpty() || 
2666                   (field->getRelFile()->time_counter != CFile::time_counter_attr::record))
2667                {
2668                  CDate timeOrigin = cal->getTimeOrigin();
2669                  StdString strTimeOrigin = timeOrigin.toString();
2670
2671                  this->writeTimeAxisAttributes(axisId, cal->getType(),
2672                                                strTimeUnits+strTimeOrigin,
2673                                                strTimeOrigin, axisBoundId);
2674                }
2675             }
2676
2677             // Adding time_counter_bound dimension
2678             if (field->getRelFile()->time_counter.isEmpty() || (field->getRelFile()->time_counter != CFile::time_counter_attr::record))
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             }
2688           }
2689         }
2690         catch (CNetCdfException& e)
2691         {
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, \
2698                  const std::shared_ptr<CCalendar> cal)", << msg);
2699         }
2700      }
2701
2702      //---------------------------------------------------------------
2703
2704      void CNc4DataOutput::writeTimeAxisAttributes(const StdString & axis_name,
2705                                                   const StdString & calendar,
2706                                                   const StdString & units,
2707                                                   const StdString & time_origin,
2708                                                   const StdString & time_bounds,
2709                                                   const StdString & standard_name,
2710                                                   const StdString & long_name)
2711      {
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, \
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);
2735         }
2736      }
2737
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      {
2747         try
2748         {
2749          if (!axis.empty())
2750            SuperClassWriter::addAttribute("axis"       , axis         , &axis_name);
2751
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);
2755//          SuperClassWriter::addAttribute("nav_model"    , nav_model    , &axis_name);
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, \
2765                                                      const StdString & axis, \
2766                                                      const StdString & standard_name, \
2767                                                      const StdString & long_name, \
2768                                                      const StdString & units, \
2769                                                      const StdString & nav_model)", << msg);
2770         }
2771      }
2772
2773      //---------------------------------------------------------------
2774
2775      void CNc4DataOutput::writeLocalAttributes
2776         (int ibegin, int ni, int jbegin, int nj, StdString domid)
2777      {
2778        try
2779        {
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);
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
2796      }
2797
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)
2800      {
2801         CArray<int,1> array(2) ;
2802
2803         try
2804         {
2805           SuperClassWriter::addAttribute("DOMAIN_number_total",size ) ;
2806           SuperClassWriter::addAttribute("DOMAIN_number", rank) ;
2807           array = SuperClassWriter::getDimension(dimXid) + 1, SuperClassWriter::getDimension(dimYid) + 1;
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) ;
2813           array=ibegin+1,jbegin+1 ;
2814           SuperClassWriter::addAttribute("DOMAIN_position_first", array) ;
2815           array=ibegin+ni-1+1,jbegin+nj-1+1 ;
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         {
2830           StdString msg("On writing Local Attributes IOIPSL \n");
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         }
2838      }
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      {
2847         try
2848         {
2849           SuperClassWriter::addAttribute("name"       , name);
2850           SuperClassWriter::addAttribute("description", description);
2851           SuperClassWriter::addAttribute("title"      , description);
2852           SuperClassWriter::addAttribute("Conventions", conventions);
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         
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         }
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      {
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         }
2914      }
2915
2916      ///--------------------------------------------------------------
2917
2918      StdSize CNc4DataOutput::getRecordFromTime(Time time, double factorUnit)
2919      {
2920        std::map<Time, StdSize>::const_iterator it = timeToRecordCache.find(time);
2921        if (it == timeToRecordCache.end())
2922        {
2923          StdString timeAxisBoundsId(getTimeCounterName() + "_bounds");
2924          if (!SuperClassWriter::varExist(timeAxisBoundsId)) timeAxisBoundsId = "time_centered_bounds";
2925          if (!SuperClassWriter::varExist(timeAxisBoundsId)) timeAxisBoundsId = "time_instant_bounds";
2926
2927          CArray<double,2> timeAxisBounds;
2928          std::vector<StdSize> dimSize(SuperClassWriter::getDimensions(timeAxisBoundsId)) ;
2929         
2930          StdSize record = 0;
2931          double dtime(time);
2932          for (int n = dimSize[0] - 1; n >= 0; n--)
2933          {
2934            SuperClassWriter::getTimeAxisBounds(timeAxisBounds, timeAxisBoundsId, isCollective, n);
2935            timeAxisBounds*=factorUnit ;
2936            if (timeAxisBounds(1, 0) < dtime)
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      }
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
2969      bool CNc4DataOutput::isWrittenScalar(const std::string& scalarName) const
2970      {
2971        return (this->writtenScalar.find(scalarName) != this->writtenScalar.end());
2972      }
2973
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      }
2993
2994      void CNc4DataOutput::setWrittenScalar(const std::string& scalarName)
2995      {
2996        this->writtenScalar.insert(scalarName);
2997      }
2998} // namespace xios
Note: See TracBrowser for help on using the repository browser.