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

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

Add missing metadata in mesh when using ugrid convention writing :

  • face_edge_connectivity
  • edge_face_connectivity
  • face_face_connectivity

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