source: XIOS/dev/XIOS_DEV_CMIP6/src/io/nc4_data_output.cpp @ 1451

Last change on this file since 1451 was 1446, checked in by oabramkina, 6 years ago

Adding a scalar to the coordinate list of a variable only if the scalar has value or label defined.

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