source: XIOS3/branches/xios-3.0-beta/src/io/nc4_data_output.cpp

Last change on this file was 2598, checked in by jderouillat, 7 months ago

Add a field attribute, conversion_by_NetCDF, to operate type conversion in XIOS, and not in NetCDF

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