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

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

Bugfix: avoiding unnecessary cast of default values to float or short int.

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