source: XIOS2/trunk/src/io/nc4_data_output.cpp @ 2434

Last change on this file since 2434 was 2434, checked in by ymipsl, 19 months ago

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