source: XIOS/trunk/src/io/nc4_data_output.cpp @ 2200

Last change on this file since 2200 was 2200, checked in by ymipsl, 3 years ago

Bugs fix for UGRID convention output

  • global indexation was not taking into account
  • coherence problem in connectivity for node, edge and face mesh
  • add UGRID testcase based on sphere cube

YM

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