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

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

Bugfix on writing of an axis introduced in r1430.

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