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

Last change on this file since 2628 was 2628, checked in by jderouillat, 7 weeks ago

New timers integration/reporting

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