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

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

Correcting a bug in case if default_value is given as 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: 128.7 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.append(appendDomid);
118             dimYid     = latName.append(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.append(appendDomid);
215                     latid = latName.append(appendDomid);
216                     break ;
217                   case CDomain::type_attr::rectilinear :
218                     lonid = lonName.append(appendDomid);
219                     latid = latName.append(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.append(appendDomid);
358                       latid = latName.append(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.append(appendDomid);
367                       latid = latName.append(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.append(appendDomid);
1045                 latid = latName.append(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.append(appendDomid);
1099                 latid = latName.append(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++) axis_value(i) = axis->value(indexToWrite(i));
1288            CArray<double,2> axis_bounds;
1289            CArray<string,1> axis_label;
1290            if (!axis->label.isEmpty())
1291            {
1292              axis_label.resize(indexToWrite.numElements());
1293              for (int i = 0; i < nbWritten; i++) axis_label(i) = axis->label(indexToWrite(i));
1294            }
1295
1296            switch (SuperClass::type)
1297            {
1298              case MULTI_FILE:
1299              {
1300                if (axis->label.isEmpty())
1301                  SuperClassWriter::writeData(axis_value, axisid, isCollective, 0);
1302
1303                if (!axis->bounds.isEmpty() && axis->label.isEmpty())
1304                {
1305                    axis_bounds.resize(2, indexToWrite.numElements());
1306                    for (int i = 0; i < nbWritten; ++i)
1307                    {
1308                      axis_bounds(0, i) = axis->bounds(0, int(indexToWrite(i)));
1309                      axis_bounds(1, i) = axis->bounds(1, int(indexToWrite(i)));
1310                    }
1311
1312                        SuperClassWriter::writeData(axis_bounds, axisBoundsId, isCollective, 0);
1313                }
1314
1315                // Need to check after
1316                if (!axis->label.isEmpty()) 
1317                  SuperClassWriter::writeData(axis_label, axisid, isCollective, 0);
1318 
1319                SuperClassWriter::definition_start();
1320                break;
1321              }
1322              case ONE_FILE:
1323              {
1324                std::vector<StdSize> start(1), startBounds(2) ;
1325                std::vector<StdSize> count(1), countBounds(2) ;
1326                start[0] = startBounds[0] = zoom_begin - axis->global_zoom_begin;
1327                count[0] = countBounds[0] = zoom_count; // zoom_size
1328                startBounds[1] = 0;
1329                countBounds[1] = 2;
1330
1331                if (axis->label.isEmpty())
1332                  SuperClassWriter::writeData(axis_value, axisid, isCollective, 0, &start, &count);
1333
1334                if (!axis->bounds.isEmpty() && axis->label.isEmpty())
1335                {
1336                  axis_bounds.resize(2, indexToWrite.numElements());
1337                  for (int i = 0; i < nbWritten; ++i)
1338                  {
1339                    axis_bounds(0, i) = axis->bounds(0, int(indexToWrite(i)));
1340                    axis_bounds(1, i) = axis->bounds(1, int(indexToWrite(i)));
1341                  }
1342                  SuperClassWriter::writeData(axis_bounds, axisBoundsId, isCollective, 0, &startBounds, &countBounds);
1343                }
1344
1345                // Need to check after
1346                if (!axis->label.isEmpty())
1347                {
1348                  std::vector<StdSize> startLabel(2), countLabel(2);
1349                  startLabel[0] = start[0]; startLabel[1] = 0;
1350                  countLabel[0] = count[0]; countLabel[1] = stringArrayLen;
1351                  SuperClassWriter::writeData(axis_label, axisid, isCollective, 0, &startLabel, &countLabel);
1352                }
1353
1354                SuperClassWriter::definition_start();
1355
1356                break;
1357              }
1358              default :
1359                ERROR("CNc4DataOutput::writeAxis_(CAxis* axis)",
1360                      << "[ type = " << SuperClass::type << "]"
1361                      << " not implemented yet !");
1362            }
1363          }
1364        }
1365        catch (CNetCdfException& e)
1366        {
1367          StdString msg("On writing the axis : ");
1368          msg.append(axisid); msg.append("\n");
1369          msg.append("In the context : ");
1370          CContext* context = CContext::getCurrent() ;
1371          msg.append(context->getId()); msg.append("\n");
1372          msg.append(e.what());
1373          ERROR("CNc4DataOutput::writeAxis_(CAxis* axis)", << msg);
1374        }
1375        axis->addRelFile(this->filename);
1376     }
1377
1378      void CNc4DataOutput::writeScalar_(CScalar* scalar)
1379      {
1380        if (scalar->IsWritten(this->filename)) return;
1381        scalar->checkAttributes();
1382        int scalarSize = 1;
1383
1384        StdString scalaId = scalar->getScalarOutputName();
1385        if (isWrittenAxis(scalaId)) return ;
1386        else setWrittenAxis(scalaId);
1387
1388        nc_type typePrec ;
1389        if (scalar->prec.isEmpty()) typePrec =  NC_FLOAT ;
1390        else if (scalar->prec==4)  typePrec =  NC_FLOAT ;
1391        else if (scalar->prec==8)   typePrec =  NC_DOUBLE ;
1392
1393       
1394        try
1395        {
1396          if (!scalar->value.isEmpty())
1397          {
1398//            dims.push_back(scalaId);
1399            std::vector<StdString> dims;
1400            SuperClassWriter::addVariable(scalaId, typePrec, dims);
1401
1402            if (!scalar->name.isEmpty())
1403              SuperClassWriter::addAttribute("name", scalar->name.getValue(), &scalaId);
1404
1405            if (!scalar->standard_name.isEmpty())
1406              SuperClassWriter::addAttribute("standard_name", scalar->standard_name.getValue(), &scalaId);
1407
1408            if (!scalar->long_name.isEmpty())
1409              SuperClassWriter::addAttribute("long_name", scalar->long_name.getValue(), &scalaId);
1410
1411            if (!scalar->unit.isEmpty())
1412              SuperClassWriter::addAttribute("units", scalar->unit.getValue(), &scalaId);
1413
1414            SuperClassWriter::definition_end();
1415
1416            switch (SuperClass::type)
1417            {
1418              case MULTI_FILE:
1419              {
1420                CArray<double,1> scalarValue(scalarSize);
1421                scalarValue(0) = scalar->value;
1422                SuperClassWriter::writeData(scalarValue, scalaId, isCollective, 0);
1423                SuperClassWriter::definition_start();
1424
1425                break;
1426              }
1427              case ONE_FILE:
1428              {
1429                CArray<double,1> scalarValue(scalarSize);
1430                scalarValue(0) = scalar->value;
1431
1432                std::vector<StdSize> start(1);
1433                std::vector<StdSize> count(1);
1434                start[0] = 0;
1435                count[0] = 1;
1436                SuperClassWriter::writeData(scalarValue, scalaId, isCollective, 0, &start, &count);
1437                SuperClassWriter::definition_start();
1438
1439                break;
1440              }
1441              default :
1442                ERROR("CNc4DataOutput::writeAxis_(CAxis* scalar)",
1443                      << "[ type = " << SuperClass::type << "]"
1444                      << " not implemented yet !");
1445            }
1446          }
1447        }
1448        catch (CNetCdfException& e)
1449        {
1450          StdString msg("On writing the scalar : ");
1451          msg.append(scalaId); msg.append("\n");
1452          msg.append("In the context : ");
1453          CContext* context = CContext::getCurrent() ;
1454          msg.append(context->getId()); msg.append("\n");
1455          msg.append(e.what());
1456          ERROR("CNc4DataOutput::writeScalar_(CScalar* scalar)", << msg);
1457        }
1458        scalar->addRelFile(this->filename);
1459     }
1460
1461     //--------------------------------------------------------------
1462
1463     void CNc4DataOutput::writeGridCompressed_(CGrid* grid)
1464     {
1465       if (grid->isScalarGrid() || grid->isWrittenCompressed(this->filename)) return;
1466
1467       try
1468       {
1469         CArray<int,1> axisDomainOrder = grid->axis_domain_order;
1470         std::vector<StdString> domainList = grid->getDomainList();
1471         std::vector<StdString> axisList   = grid->getAxisList();
1472         std::vector<StdString> scalarList = grid->getScalarList();
1473         int numElement = axisDomainOrder.numElements(), idxDomain = 0, idxAxis = 0, idxScalar = 0;
1474
1475         std::vector<StdString> dims;
1476
1477         if (grid->isCompressible())
1478         {
1479           StdString varId = grid->getId() + "_points";
1480
1481           int nbIndexes = (SuperClass::type == MULTI_FILE) ? grid->getNumberWrittenIndexes() : grid->getTotalNumberWrittenIndexes();
1482           SuperClassWriter::addDimension(varId, nbIndexes);
1483
1484           dims.push_back(varId);
1485           SuperClassWriter::addVariable(varId, NC_INT, dims);
1486
1487           StdOStringStream compress;
1488           for (int i = numElement - 1; i >= 0; --i)
1489           {
1490             if (2 == axisDomainOrder(i))
1491             {
1492               CDomain* domain = CDomain::get(domainList[domainList.size() - idxDomain - 1]);
1493               StdString domId = domain->getDomainOutputName();
1494               StdString appendDomId  = singleDomain ? "" : "_" + domId;
1495
1496               switch (domain->type)
1497               {
1498                 case CDomain::type_attr::curvilinear:
1499                   compress << "y" << appendDomId << " x" << appendDomId;
1500                   break;
1501                 case CDomain::type_attr::rectilinear:
1502                   compress << "lat" << appendDomId << " lon" << appendDomId;
1503                   break;
1504                 case CDomain::type_attr::unstructured:
1505                   compress << "cell" << appendDomId;
1506                   break;
1507               }
1508               ++idxDomain;
1509             }
1510             else if (1 == axisDomainOrder(i))
1511             {
1512               CAxis* axis = CAxis::get(axisList[axisList.size() - idxAxis - 1]);
1513               compress << axis->getAxisOutputName();
1514               ++idxAxis;
1515             }
1516             else
1517             {
1518               CScalar* scalar = CScalar::get(scalarList[scalarList.size() - idxScalar - 1]);
1519               compress << scalar->getScalarOutputName();
1520               ++idxScalar;
1521             }
1522
1523             if (i != 0) compress << ' ';
1524           }
1525           SuperClassWriter::addAttribute("compress", compress.str(), &varId);         
1526
1527           CArray<int, 1> indexes(grid->getNumberWrittenIndexes());
1528           indexes = grid->localIndexToWriteOnServer;
1529
1530           switch (SuperClass::type)
1531           {
1532             case (MULTI_FILE):
1533             {
1534               SuperClassWriter::writeData(indexes, varId, isCollective, 0);
1535               break;
1536             }
1537             case (ONE_FILE):
1538             {
1539               if (grid->doGridHaveDataDistributed())
1540                 grid->getDistributionServer()->computeGlobalIndex(indexes);
1541
1542               std::vector<StdSize> start, count;
1543               start.push_back(grid->getOffsetWrittenIndexes());
1544               count.push_back(grid->getNumberWrittenIndexes());
1545
1546               SuperClassWriter::writeData(indexes, varId, isCollective, 0, &start, &count);
1547               break;
1548             }
1549           }
1550         }
1551         else
1552         {
1553           for (int i = 0; i < numElement; ++i)
1554           {
1555             StdString varId, compress;
1556             CArray<int, 1> indexes;
1557             bool isDistributed;
1558             StdSize nbIndexes, totalNbIndexes, offset;
1559             int firstGlobalIndex;
1560
1561             if (2 == axisDomainOrder(i))
1562             {
1563               CDomain* domain = CDomain::get(domainList[idxDomain]);
1564               StdString domId = domain->getDomainOutputName();
1565
1566               if (!domain->isCompressible()
1567                    || domain->type == CDomain::type_attr::unstructured
1568                    || domain->isWrittenCompressed(this->filename)
1569                    || isWrittenCompressedDomain(domId))
1570                 continue;
1571
1572               StdString appendDomId  = singleDomain ? "" : "_" + domId;
1573
1574               varId = domId + "_points";
1575               switch (domain->type)
1576               {
1577                 case CDomain::type_attr::curvilinear:
1578                   compress = "y" + appendDomId + " x" + appendDomId;
1579                   break;
1580                 case CDomain::type_attr::rectilinear:
1581                   compress = "lat" + appendDomId + " lon" + appendDomId;
1582                   break;
1583               }
1584
1585               // indexes.resize(domain->compressedIndexToWriteOnServer[comm_file].numElements());
1586               // indexes = domain->compressedIndexToWriteOnServer[com_file];
1587               indexes.resize(domain->getCompressedIndexToWriteOnServer(comm_file).numElements());
1588               indexes = domain->getCompressedIndexToWriteOnServer(comm_file);
1589
1590               isDistributed = domain->isDistributed();
1591               nbIndexes = domain->getNumberWrittenIndexes(comm_file);
1592               totalNbIndexes = domain->getTotalNumberWrittenIndexes(comm_file);
1593               offset = domain->getOffsetWrittenIndexes(comm_file);
1594               firstGlobalIndex = domain->ibegin + domain->jbegin * domain->ni_glo;
1595
1596               domain->addRelFileCompressed(this->filename);
1597               setWrittenCompressedDomain(domId);
1598               ++idxDomain;
1599             }
1600             else if (1 == axisDomainOrder(i))
1601             {
1602               CAxis* axis = CAxis::get(axisList[idxAxis]);
1603               StdString axisId = axis->getAxisOutputName();
1604
1605               if (!axis->isCompressible()
1606                    || axis->isWrittenCompressed(this->filename)
1607                    || isWrittenCompressedAxis(axisId))
1608                 continue;
1609
1610               varId = axisId + "_points";
1611               compress = axisId;
1612
1613               // indexes.resize(axis->compressedIndexToWriteOnServer.numElements());
1614               // indexes = axis->compressedIndexToWriteOnServer;
1615
1616               indexes.resize(axis->getCompressedIndexToWriteOnServer(comm_file).numElements());
1617               indexes = axis->getCompressedIndexToWriteOnServer(comm_file);
1618
1619               isDistributed = axis->isDistributed();
1620               nbIndexes = axis->getNumberWrittenIndexes(comm_file);
1621               totalNbIndexes = axis->getTotalNumberWrittenIndexes(comm_file);
1622               offset = axis->getOffsetWrittenIndexes(comm_file);
1623               firstGlobalIndex = axis->begin;
1624
1625               axis->addRelFileCompressed(this->filename);
1626               setWrittenCompressedAxis(axisId);
1627               ++idxAxis;
1628             }
1629             else
1630             {
1631             }
1632
1633             if (!varId.empty())
1634             {
1635               SuperClassWriter::addDimension(varId, (SuperClass::type == MULTI_FILE) ? nbIndexes : totalNbIndexes);
1636
1637               dims.clear();
1638               dims.push_back(varId);
1639               SuperClassWriter::addVariable(varId, NC_INT, dims);
1640
1641               SuperClassWriter::addAttribute("compress", compress, &varId);
1642
1643               switch (SuperClass::type)
1644               {
1645                 case (MULTI_FILE):
1646                 {
1647                   indexes -= firstGlobalIndex;
1648                   SuperClassWriter::writeData(indexes, varId, isCollective, 0);
1649                   break;
1650                 }
1651                 case (ONE_FILE):
1652                 {
1653                   std::vector<StdSize> start, count;
1654                   start.push_back(offset);
1655                   count.push_back(nbIndexes);
1656
1657                   SuperClassWriter::writeData(indexes, varId, isCollective, 0, &start, &count);
1658                   break;
1659                 }
1660               }
1661             }
1662            }
1663         }
1664
1665         grid->addRelFileCompressed(this->filename);
1666       }
1667       catch (CNetCdfException& e)
1668       {
1669         StdString msg("On writing compressed grid : ");
1670         msg.append(grid->getId()); msg.append("\n");
1671         msg.append("In the context : ");
1672         CContext* context = CContext::getCurrent();
1673         msg.append(context->getId()); msg.append("\n");
1674         msg.append(e.what());
1675         ERROR("CNc4DataOutput::writeGridCompressed_(CGrid* grid)", << msg);
1676       }
1677     }
1678
1679     //--------------------------------------------------------------
1680
1681     void CNc4DataOutput::writeTimeDimension_(void)
1682     {
1683       try
1684       {
1685        SuperClassWriter::addDimension(getTimeCounterName());
1686       }
1687       catch (CNetCdfException& e)
1688       {
1689         StdString msg("On writing time dimension : time_couter\n");
1690         msg.append("In the context : ");
1691         CContext* context = CContext::getCurrent() ;
1692         msg.append(context->getId()); msg.append("\n");
1693         msg.append(e.what());
1694         ERROR("CNc4DataOutput::writeTimeDimension_(void)", << msg);
1695       }
1696     }
1697
1698      //--------------------------------------------------------------
1699
1700      void CNc4DataOutput::writeField_(CField* field)
1701      {
1702        CContext* context = CContext::getCurrent() ;
1703        CContextServer* server=context->server ;
1704
1705        std::vector<StdString> dims, coodinates;
1706        CGrid* grid = field->grid;
1707        if (!grid->doGridHaveDataToWrite())
1708          if (SuperClass::type==MULTI_FILE) return ;
1709
1710        CArray<int,1> axisDomainOrder = grid->axis_domain_order;
1711        int numElement = axisDomainOrder.numElements(), idxDomain = 0, idxAxis = 0, idxScalar = 0;
1712        std::vector<StdString> domainList = grid->getDomainList();
1713        std::vector<StdString> axisList   = grid->getAxisList();
1714        std::vector<StdString> scalarList = grid->getScalarList();       
1715
1716        StdString timeid  = getTimeCounterName();
1717        StdString dimXid,dimYid;
1718        std::deque<StdString> dimIdList, dimCoordList;
1719        bool hasArea = false;
1720        StdString cellMeasures = "area:";
1721        bool compressedOutput = !field->indexed_output.isEmpty() && field->indexed_output;
1722
1723        for (int i = 0; i < numElement; ++i)
1724        {
1725          if (2 == axisDomainOrder(i))
1726          {
1727            CDomain* domain = CDomain::get(domainList[idxDomain]);
1728            StdString domId = domain->getDomainOutputName();
1729            StdString appendDomId  = singleDomain ? "" : "_" + domId ;
1730            StdString lonName,latName ;
1731
1732            if (domain->lon_name.isEmpty()) lonName = "lon";
1733            else lonName = domain->lon_name;
1734
1735            if (domain->lat_name.isEmpty()) latName = "lat";
1736            else latName = domain->lat_name;
1737       
1738            if (compressedOutput && domain->isCompressible() && domain->type != CDomain::type_attr::unstructured)
1739            {
1740              dimIdList.push_back(domId + "_points");
1741              field->setUseCompressedOutput();
1742            }
1743
1744            switch (domain->type)
1745            {
1746              case CDomain::type_attr::curvilinear:
1747                if (!compressedOutput || !domain->isCompressible())
1748                {
1749                  dimXid     = StdString("x").append(appendDomId);
1750                  dimIdList.push_back(dimXid);
1751                  dimYid     = StdString("y").append(appendDomId);
1752                  dimIdList.push_back(dimYid);
1753                }
1754                dimCoordList.push_back(lonName.append(appendDomId));
1755                dimCoordList.push_back(latName.append(appendDomId));
1756              break ;
1757              case CDomain::type_attr::rectilinear:
1758                if (!compressedOutput || !domain->isCompressible())
1759                {
1760                  dimXid     = lonName.append(appendDomId);
1761                  dimIdList.push_back(dimXid);
1762                  dimYid     = latName.append(appendDomId);
1763                  dimIdList.push_back(dimYid);
1764                }
1765              break ;
1766              case CDomain::type_attr::unstructured:
1767              {
1768                if (SuperClassWriter::useCFConvention)
1769                {
1770                  dimXid     = StdString("cell").append(appendDomId);
1771                  dimIdList.push_back(dimXid);
1772                  dimCoordList.push_back(lonName.append(appendDomId));
1773                  dimCoordList.push_back(latName.append(appendDomId));
1774                }
1775                else
1776                {
1777                  StdString domainName = domain->name;
1778                  if (domain->nvertex == 1)
1779                  {
1780                    dimXid     = "n" + domainName + "_node";
1781                    dimIdList.push_back(dimXid);
1782                    dimCoordList.push_back(StdString(domainName + "_node_x"));
1783                    dimCoordList.push_back(StdString(domainName + "_node_y"));
1784                  }
1785                  else if (domain->nvertex == 2)
1786                  {
1787                    dimXid     = "n" + domainName + "_edge";
1788                    dimIdList.push_back(dimXid);
1789                    dimCoordList.push_back(StdString(domainName + "_edge_x"));
1790                    dimCoordList.push_back(StdString(domainName + "_edge_y"));
1791                  }
1792                  else
1793                  {
1794                    dimXid     = "n" + domainName + "_face";
1795                    dimIdList.push_back(dimXid);
1796                    dimCoordList.push_back(StdString(domainName + "_face_x"));
1797                    dimCoordList.push_back(StdString(domainName + "_face_y"));
1798                  }
1799                }  // ugrid convention
1800              }  // case unstructured domain
1801            }
1802
1803            if (domain->hasArea)
1804            {
1805              hasArea = true;
1806              cellMeasures += " area" + appendDomId;
1807            }
1808            ++idxDomain;
1809          }
1810          else if (1 == axisDomainOrder(i))
1811          {
1812            CAxis* axis = CAxis::get(axisList[idxAxis]);
1813            StdString axisId = axis->getAxisOutputName();
1814
1815            if (compressedOutput && axis->isCompressible())
1816            {
1817              dimIdList.push_back(axisId + "_points");
1818              field->setUseCompressedOutput();
1819            }
1820            else
1821              dimIdList.push_back(axisId);
1822
1823            dimCoordList.push_back(axisId);
1824            ++idxAxis;
1825          }
1826          else // scalar
1827          {
1828             /* Do nothing here */
1829          }
1830        }
1831
1832        StdString fieldid = field->getFieldOutputName();
1833
1834        nc_type type ;
1835        if (field->prec.isEmpty()) type =  NC_FLOAT ;
1836        else
1837        {
1838          if (field->prec==2) type = NC_SHORT ;
1839          else if (field->prec==4)  type =  NC_FLOAT ;
1840          else if (field->prec==8)   type =  NC_DOUBLE ;
1841        }
1842
1843        bool wtime   = !(!field->operation.isEmpty() && field->getOperationTimeType() == func::CFunctor::once);
1844
1845        if (wtime)
1846        {
1847          if (field->hasTimeInstant && hasTimeInstant) coodinates.push_back(string("time_instant"));
1848          else if (field->hasTimeCentered && hasTimeCentered)  coodinates.push_back(string("time_centered"));
1849          dims.push_back(timeid);
1850        }
1851
1852        if (compressedOutput && grid->isCompressible())
1853        {
1854          dims.push_back(grid->getId() + "_points");
1855          field->setUseCompressedOutput();
1856        }
1857        else
1858        {
1859          while (!dimIdList.empty())
1860          {
1861            dims.push_back(dimIdList.back());
1862            dimIdList.pop_back();
1863          }
1864        }
1865
1866        while (!dimCoordList.empty())
1867        {
1868          coodinates.push_back(dimCoordList.back());
1869          dimCoordList.pop_back();
1870        }
1871
1872        try
1873        {
1874           SuperClassWriter::addVariable(fieldid, type, dims);
1875
1876           if (!field->standard_name.isEmpty())
1877              SuperClassWriter::addAttribute
1878                 ("standard_name",  field->standard_name.getValue(), &fieldid);
1879
1880           if (!field->long_name.isEmpty())
1881              SuperClassWriter::addAttribute
1882                 ("long_name", field->long_name.getValue(), &fieldid);
1883
1884           if (!field->unit.isEmpty())
1885              SuperClassWriter::addAttribute
1886                 ("units", field->unit.getValue(), &fieldid);
1887
1888           // Ugrid field attributes "mesh" and "location"
1889           if (!SuperClassWriter::useCFConvention)
1890           {
1891            if (!domainList.empty())
1892            {
1893              CDomain* domain = CDomain::get(domainList[0]); // Suppose that we have only domain
1894              StdString mesh = domain->name;
1895              SuperClassWriter::addAttribute("mesh", mesh, &fieldid);
1896              StdString location;
1897              if (domain->nvertex == 1)
1898                location = "node";
1899              else if (domain->nvertex == 2)
1900                location = "edge";
1901              else if (domain->nvertex > 2)
1902                location = "face";
1903              SuperClassWriter::addAttribute("location", location, &fieldid);
1904            }
1905
1906           }
1907
1908           if (!field->valid_min.isEmpty())
1909              SuperClassWriter::addAttribute
1910                 ("valid_min", field->valid_min.getValue(), &fieldid);
1911
1912           if (!field->valid_max.isEmpty())
1913              SuperClassWriter::addAttribute
1914                 ("valid_max", field->valid_max.getValue(), &fieldid);
1915
1916            if (!field->scale_factor.isEmpty())
1917              SuperClassWriter::addAttribute
1918                 ("scale_factor", field->scale_factor.getValue(), &fieldid);
1919
1920             if (!field->add_offset.isEmpty())
1921              SuperClassWriter::addAttribute
1922                 ("add_offset", field->add_offset.getValue(), &fieldid);
1923
1924           SuperClassWriter::addAttribute
1925                 ("online_operation", field->operation.getValue(), &fieldid);
1926
1927          // write child variables as attributes
1928
1929
1930           bool alreadyAddCellMethod = false;
1931           StdString cellMethodsPrefix(""), cellMethodsSuffix("");
1932           if (!field->cell_methods.isEmpty())
1933           {
1934              StdString cellMethodString = field->cell_methods;
1935              if (field->cell_methods_mode.isEmpty() ||
1936                 (CField::cell_methods_mode_attr::overwrite == field->cell_methods_mode))
1937              {
1938                SuperClassWriter::addAttribute("cell_methods", cellMethodString, &fieldid);
1939                alreadyAddCellMethod = true;
1940              }
1941              else
1942              {
1943                switch (field->cell_methods_mode)
1944                {
1945                  case (CField::cell_methods_mode_attr::prefix):
1946                    cellMethodsPrefix = cellMethodString;
1947                    cellMethodsPrefix += " ";
1948                    break;
1949                  case (CField::cell_methods_mode_attr::suffix):
1950                    cellMethodsSuffix = " ";
1951                    cellMethodsSuffix += cellMethodString;
1952                    break;
1953                  case (CField::cell_methods_mode_attr::none):
1954                    break;
1955                  default:
1956                    break;
1957                }
1958              }
1959           }
1960
1961
1962           if (wtime)
1963           {
1964              CDuration freqOp = field->freq_op.getValue();
1965              freqOp.solveTimeStep(*context->calendar);
1966              StdString freqOpStr = freqOp.toStringUDUnits();
1967              SuperClassWriter::addAttribute("interval_operation", freqOpStr, &fieldid);
1968
1969              CDuration freqOut = field->getRelFile()->output_freq.getValue();
1970              freqOut.solveTimeStep(*context->calendar);
1971              SuperClassWriter::addAttribute("interval_write", freqOut.toStringUDUnits(), &fieldid);
1972
1973              StdString cellMethods(cellMethodsPrefix + "time: ");
1974              if (field->operation.getValue() == "instant") cellMethods += "point";
1975              else if (field->operation.getValue() == "average") cellMethods += "mean";
1976              else if (field->operation.getValue() == "accumulate") cellMethods += "sum";
1977              else cellMethods += field->operation;
1978              if (freqOp.resolve(*context->calendar) != freqOut.resolve(*context->calendar))
1979                cellMethods += " (interval: " + freqOpStr + ")";
1980              cellMethods += cellMethodsSuffix;
1981              if (!alreadyAddCellMethod)
1982                SuperClassWriter::addAttribute("cell_methods", cellMethods, &fieldid);
1983           }
1984
1985           if (hasArea)
1986             SuperClassWriter::addAttribute("cell_measures", cellMeasures, &fieldid);
1987
1988           if (!field->default_value.isEmpty())
1989           {
1990              double default_value = field->default_value.getValue();
1991              short sdefault_value = (short)default_value;
1992              float fdefault_value = (float)default_value;
1993              if (type == NC_DOUBLE)
1994                 SuperClassWriter::setDefaultValue(fieldid, &default_value);
1995              else if (type == NC_SHORT)
1996                  SuperClassWriter::setDefaultValue(fieldid, &sdefault_value);
1997              else
1998                 SuperClassWriter::setDefaultValue(fieldid, &fdefault_value);
1999           }
2000           else
2001              SuperClassWriter::setDefaultValue(fieldid, (double*)NULL);
2002
2003            if (field->compression_level.isEmpty())
2004              field->compression_level = field->file->compression_level.isEmpty() ? 0 : field->file->compression_level;
2005            SuperClassWriter::setCompressionLevel(fieldid, field->compression_level);
2006
2007           {  // Ecriture des coordonnes
2008
2009              StdString coordstr; //boost::algorithm::join(coodinates, " ")
2010              std::vector<StdString>::iterator
2011                 itc = coodinates.begin(), endc = coodinates.end();
2012
2013              for (; itc!= endc; itc++)
2014              {
2015                 StdString & coord = *itc;
2016                 if (itc+1 != endc)
2017                       coordstr.append(coord).append(" ");
2018                 else  coordstr.append(coord);
2019              }
2020
2021              SuperClassWriter::addAttribute("coordinates", coordstr, &fieldid);
2022
2023           }
2024
2025           vector<CVariable*> listVars = field->getAllVariables() ;
2026           for (vector<CVariable*>::iterator it = listVars.begin() ;it != listVars.end(); it++) writeAttribute_(*it, fieldid) ;
2027
2028         }
2029         catch (CNetCdfException& e)
2030         {
2031           StdString msg("On writing field : ");
2032           msg.append(fieldid); msg.append("\n");
2033           msg.append("In the context : ");
2034           msg.append(context->getId()); msg.append("\n");
2035           msg.append(e.what());
2036           ERROR("CNc4DataOutput::writeField_(CField* field)", << msg);
2037         }
2038      } // writeField_()
2039
2040      //--------------------------------------------------------------
2041
2042      void CNc4DataOutput::writeFile_ (CFile* file)
2043      {
2044         StdString filename = file->getFileOutputName();
2045         StdString description = (!file->description.isEmpty())
2046                               ? file->description.getValue()
2047                               : StdString("Created by xios");
2048
2049         singleDomain = (file->nbDomains == 1);
2050
2051         StdString conv_str ;
2052         if (file->convention_str.isEmpty())
2053         {
2054            if (SuperClassWriter::useCFConvention) conv_str="CF-1.6" ;
2055            else conv_str="UGRID" ;
2056         }
2057         else conv_str=file->convention_str ;
2058           
2059         try
2060         {
2061           if (!appendMode) this->writeFileAttributes(filename, description,
2062                                                      conv_str,
2063                                                      StdString("An IPSL model"),
2064                                                      this->getTimeStamp());
2065
2066           if (!appendMode)
2067             SuperClassWriter::addDimension("axis_nbounds", 2);
2068         }
2069         catch (CNetCdfException& e)
2070         {
2071           StdString msg("On writing file : ");
2072           msg.append(filename); msg.append("\n");
2073           msg.append("In the context : ");
2074           CContext* context = CContext::getCurrent() ;
2075           msg.append(context->getId()); msg.append("\n");
2076           msg.append(e.what());
2077           ERROR("CNc4DataOutput::writeFile_ (CFile* file)", << msg);
2078         }
2079      }
2080
2081      void CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)
2082      {
2083        StdString name = var->getVariableOutputName();
2084
2085        try
2086        {
2087          if (var->type.getValue() == CVariable::type_attr::t_int || var->type.getValue() == CVariable::type_attr::t_int32)
2088            addAttribute(name, var->getData<int>(), &fieldId);
2089          else if (var->type.getValue() == CVariable::type_attr::t_int16)
2090            addAttribute(name, var->getData<short int>(), &fieldId);
2091          else if (var->type.getValue() == CVariable::type_attr::t_float)
2092            addAttribute(name, var->getData<float>(), &fieldId);
2093          else if (var->type.getValue() == CVariable::type_attr::t_double)
2094            addAttribute(name, var->getData<double>(), &fieldId);
2095          else if (var->type.getValue() == CVariable::type_attr::t_string)
2096            addAttribute(name, var->getData<string>(), &fieldId);
2097          else
2098            ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)",
2099                  << "Unsupported variable of type " << var->type.getStringValue());
2100        }
2101       catch (CNetCdfException& e)
2102       {
2103         StdString msg("On writing attributes of variable with name : ");
2104         msg.append(name); msg.append("in the field "); msg.append(fieldId); msg.append("\n");
2105         msg.append("In the context : ");
2106         CContext* context = CContext::getCurrent() ;
2107         msg.append(context->getId()); msg.append("\n");
2108         msg.append(e.what());
2109         ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var, const string& fieldId)", << msg);
2110       }
2111     }
2112
2113     void CNc4DataOutput::writeAttribute_ (CVariable* var)
2114     {
2115        StdString name = var->getVariableOutputName();
2116
2117        try
2118        {
2119          if (var->type.getValue() == CVariable::type_attr::t_int || var->type.getValue() == CVariable::type_attr::t_int32)
2120            addAttribute(name, var->getData<int>());
2121          else if (var->type.getValue() == CVariable::type_attr::t_int16)
2122            addAttribute(name, var->getData<short int>());
2123          else if (var->type.getValue() == CVariable::type_attr::t_float)
2124            addAttribute(name, var->getData<float>());
2125          else if (var->type.getValue() == CVariable::type_attr::t_double)
2126            addAttribute(name, var->getData<double>());
2127          else if (var->type.getValue() == CVariable::type_attr::t_string)
2128            addAttribute(name, var->getData<string>());
2129          else
2130            ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var)",
2131                  << "Unsupported variable of type " << var->type.getStringValue());
2132        }
2133       catch (CNetCdfException& e)
2134       {
2135         StdString msg("On writing attributes of variable with name : ");
2136         msg.append(name); msg.append("\n");
2137         msg.append("In the context : ");
2138         CContext* context = CContext::getCurrent() ;
2139         msg.append(context->getId()); msg.append("\n");
2140         msg.append(e.what());
2141         ERROR("CNc4DataOutput::writeAttribute_ (CVariable* var)", << msg);
2142       }
2143     }
2144
2145      void CNc4DataOutput::syncFile_ (void)
2146      {
2147        try
2148        {
2149          SuperClassWriter::sync() ;
2150        }
2151        catch (CNetCdfException& e)
2152        {
2153         StdString msg("On synchronizing the write among processes");
2154         msg.append("In the context : ");
2155         CContext* context = CContext::getCurrent() ;
2156         msg.append(context->getId()); msg.append("\n");
2157         msg.append(e.what());
2158         ERROR("CNc4DataOutput::syncFile_ (void)", << msg);
2159        }
2160      }
2161
2162      void CNc4DataOutput::closeFile_ (void)
2163      {
2164        try
2165        {
2166          SuperClassWriter::close() ;
2167        }
2168        catch (CNetCdfException& e)
2169        {
2170         StdString msg("On closing file");
2171         msg.append("In the context : ");
2172         CContext* context = CContext::getCurrent() ;
2173         msg.append(context->getId()); msg.append("\n");
2174         msg.append(e.what());
2175         ERROR("CNc4DataOutput::syncFile_ (void)", << msg);
2176        }
2177
2178      }
2179
2180      //---------------------------------------------------------------
2181
2182      StdString CNc4DataOutput::getTimeStamp(void) const
2183      {
2184         const int buffer_size = 100;
2185         time_t rawtime;
2186         struct tm * timeinfo = NULL;
2187         char buffer [buffer_size];
2188         StdString formatStr;
2189         if (file->time_stamp_format.isEmpty()) formatStr="%Y-%b-%d %H:%M:%S %Z" ;
2190         else formatStr=file->time_stamp_format;
2191
2192//         time ( &rawtime );
2193//         timeinfo = localtime ( &rawtime );
2194         time ( &rawtime );
2195         timeinfo = gmtime ( &rawtime );
2196         strftime (buffer, buffer_size, formatStr.c_str(), timeinfo);
2197
2198         return (StdString(buffer));
2199      }
2200
2201      //---------------------------------------------------------------
2202
2203      void CNc4DataOutput::writeFieldData_ (CField*  field)
2204      {
2205        CContext* context = CContext::getCurrent();
2206        CContextServer* server = context->server;
2207        CGrid* grid = field->grid;
2208
2209        if (field->getNStep()<1) 
2210        {
2211          return;
2212        }
2213       
2214        if (!grid->doGridHaveDataToWrite())
2215          if (SuperClass::type == MULTI_FILE || !isCollective)
2216          {
2217            return;
2218          }
2219
2220        StdString fieldid = field->getFieldOutputName();
2221
2222        StdOStringStream oss;
2223        string timeAxisId;
2224        if (field->hasTimeInstant) timeAxisId = "time_instant";
2225        else if (field->hasTimeCentered) timeAxisId = "time_centered";
2226
2227        StdString timeBoundId = getTimeCounterName() + "_bounds";
2228
2229        StdString timeAxisBoundId;
2230        if (field->hasTimeInstant) timeAxisBoundId = "time_instant_bounds";
2231        else if (field->hasTimeCentered) timeAxisBoundId = "time_centered_bounds";
2232
2233        if (!field->wasWritten())
2234        {
2235          if (appendMode && field->file->record_offset.isEmpty() && 
2236              field->getOperationTimeType() != func::CFunctor::once)
2237          {
2238            double factorUnit;
2239            if (!field->file->time_units.isEmpty() && field->file->time_units==CFile::time_units_attr::days)
2240            factorUnit=context->getCalendar()->getDayLengthInSeconds() ;
2241            else factorUnit=1 ;
2242            field->resetNStep(getRecordFromTime(field->last_Write_srv,factorUnit) + 1);
2243          }
2244
2245          field->setWritten();
2246        }
2247
2248
2249        CArray<double,1> time_data(1);
2250        CArray<double,1> time_data_bound(2);
2251        CArray<double,1> time_counter(1);
2252        CArray<double,1> time_counter_bound(2);
2253
2254        bool wtime = (field->getOperationTimeType() != func::CFunctor::once);
2255        bool wtimeCounter =false ;
2256        bool wtimeData =false ;
2257       
2258
2259        if (wtime)
2260        {
2261          Time lastWrite = field->last_Write_srv;
2262          Time lastLastWrite = field->lastlast_Write_srv;
2263
2264         
2265          if (field->hasTimeInstant)
2266          {
2267            time_data(0) = time_data_bound(1) = lastWrite;
2268            time_data_bound(0) = time_data_bound(1) = lastWrite;
2269            if (timeCounterType==instant)
2270            {
2271              time_counter(0) = time_data(0);
2272              time_counter_bound(0) = time_data_bound(0);
2273              time_counter_bound(1) = time_data_bound(1);
2274              wtimeCounter=true ;
2275            }
2276            if (hasTimeInstant) wtimeData=true ;
2277          }
2278          else if (field->hasTimeCentered)
2279          {
2280            time_data(0) = (lastWrite + lastLastWrite) / 2;
2281            time_data_bound(0) = lastLastWrite;
2282            time_data_bound(1) = lastWrite;
2283            if (timeCounterType==centered)
2284            {
2285              time_counter(0) = time_data(0) ;
2286              time_counter_bound(0) = time_data_bound(0) ;
2287              time_counter_bound(1) = time_data_bound(1) ;
2288              wtimeCounter=true ;
2289            }
2290            if (hasTimeCentered) wtimeData=true ;
2291          }
2292
2293          if (timeCounterType==record)
2294          {
2295            time_counter(0) = field->getNStep() - 1;
2296            time_counter_bound(0) = time_counter_bound(1) = field->getNStep() - 1;
2297            wtimeCounter=true ;
2298          }
2299
2300          if (!field->file->time_units.isEmpty() && field->file->time_units==CFile::time_units_attr::days)
2301          {
2302            double secByDay=context->getCalendar()->getDayLengthInSeconds() ;
2303            time_data/=secByDay;
2304            time_data_bound/=secByDay;
2305            time_counter/=secByDay;
2306            time_counter_bound/=secByDay;
2307          }
2308        }
2309
2310         bool isRoot = (server->intraCommRank == 0);
2311
2312         if (!field->scale_factor.isEmpty() || !field->add_offset.isEmpty())
2313         {
2314           double scaleFactor = 1.0;
2315           double addOffset = 0.0;
2316           if (!field->scale_factor.isEmpty()) scaleFactor = field->scale_factor;
2317           if (!field->add_offset.isEmpty()) addOffset = field->add_offset;
2318           field->scaleFactorAddOffset(scaleFactor, addOffset);
2319         }
2320
2321         try
2322         {
2323           size_t writtenSize;
2324           if (field->getUseCompressedOutput())
2325             writtenSize = grid->getNumberWrittenIndexes();
2326           else
2327             writtenSize = grid->getWrittenDataSize();
2328
2329           CArray<double,1> fieldData(writtenSize);
2330           if (!field->default_value.isEmpty()) fieldData = field->default_value;
2331
2332           if (field->getUseCompressedOutput())
2333             field->outputCompressedField(fieldData);
2334           else
2335             field->outputField(fieldData);
2336
2337           if (!field->prec.isEmpty() && field->prec == 2) fieldData = round(fieldData);
2338
2339           switch (SuperClass::type)
2340           {
2341              case (MULTI_FILE) :
2342              {
2343                 CTimer::get("Files : writing data").resume();
2344                 SuperClassWriter::writeData(fieldData, fieldid, isCollective, field->getNStep() - 1);
2345                 CTimer::get("Files : writing data").suspend();
2346                 if (wtime)
2347                 {
2348                   CTimer::get("Files : writing time axis").resume();
2349                   if ( wtimeData)
2350                   {
2351//                     SuperClassWriter::writeData(time_data, timeAxisId, isCollective, field->getNStep() - 1);
2352//                     SuperClassWriter::writeData(time_data_bound, timeAxisBoundId, isCollective, field->getNStep() - 1);
2353                       SuperClassWriter::writeTimeAxisData(time_data, timeAxisId, isCollective, field->getNStep() - 1, isRoot);
2354                       SuperClassWriter::writeTimeAxisDataBounds(time_data_bound, timeAxisBoundId, isCollective, field->getNStep() - 1, isRoot);
2355                  }
2356                   if (wtimeCounter)
2357                   {
2358//                     SuperClassWriter::writeData(time_counter, getTimeCounterName(), isCollective, field->getNStep() - 1);
2359//                     if (timeCounterType!=record) SuperClassWriter::writeData(time_counter_bound, timeBoundId, isCollective, field->getNStep() - 1);
2360                     SuperClassWriter::writeTimeAxisData(time_counter, getTimeCounterName(), isCollective, field->getNStep() - 1,isRoot);
2361                     if (timeCounterType!=record) SuperClassWriter::writeTimeAxisDataBounds(time_counter_bound, timeBoundId, isCollective, field->getNStep() - 1, isRoot);
2362                   }
2363                   CTimer::get("Files : writing time axis").suspend();
2364                 }
2365                 break;
2366              }
2367              case (ONE_FILE) :
2368              {
2369                const std::vector<int>& nZoomBeginGlobal = grid->getDistributionServer()->getZoomBeginGlobal();
2370                const std::vector<int>& nZoomBeginServer = grid->getDistributionServer()->getZoomBeginServer();
2371                const std::vector<int>& nZoomSizeServer  = grid->getDistributionServer()->getZoomSizeServer();
2372
2373                std::vector<StdSize> start, count;
2374
2375                if (field->getUseCompressedOutput())
2376                {
2377                  if (grid->isCompressible())
2378                  {
2379                    start.push_back(grid->getOffsetWrittenIndexes());
2380                    count.push_back(grid->getNumberWrittenIndexes());
2381                  }
2382                  else
2383                  {
2384                    CArray<int,1> axisDomainOrder = grid->axis_domain_order;
2385                    std::vector<StdString> domainList = grid->getDomainList();
2386                    std::vector<StdString> axisList   = grid->getAxisList();
2387                    int numElement = axisDomainOrder.numElements();
2388                    int idxDomain = domainList.size() - 1, idxAxis = axisList.size() - 1;
2389                    int idx = nZoomBeginGlobal.size() - 1;
2390
2391                    start.reserve(nZoomBeginGlobal.size());
2392                    count.reserve(nZoomBeginGlobal.size());
2393
2394
2395                    for (int i = numElement - 1; i >= 0; --i)
2396                    {
2397                      if (2 == axisDomainOrder(i))
2398                      {
2399                        CDomain* domain = CDomain::get(domainList[idxDomain]);
2400
2401                        if (domain->isCompressible())
2402                        {
2403                          start.push_back(domain->getOffsetWrittenIndexes(comm_file));
2404                          count.push_back(domain->getNumberWrittenIndexes(comm_file));
2405                          idx -= 2;
2406                        }
2407                        else
2408                        {
2409                          if ((domain->type) != CDomain::type_attr::unstructured)
2410                          {
2411                            start.push_back(nZoomBeginServer[idx] - nZoomBeginGlobal[idx]);
2412                            count.push_back(nZoomSizeServer[idx]);
2413                          }
2414                          --idx;
2415                          start.push_back(nZoomBeginServer[idx] - nZoomBeginGlobal[idx]);
2416                          count.push_back(nZoomSizeServer[idx]);
2417                          --idx;
2418                        }
2419                        --idxDomain;
2420                      }
2421                      else if (1 == axisDomainOrder(i))
2422                      {
2423                        CAxis* axis = CAxis::get(axisList[idxAxis]);
2424
2425                        if (axis->isCompressible())
2426                        {
2427                          start.push_back(axis->getOffsetWrittenIndexes(comm_file));
2428                          count.push_back(axis->getNumberWrittenIndexes(comm_file));
2429                        }
2430                        else
2431                        {
2432                          start.push_back(nZoomBeginServer[idx] - nZoomBeginGlobal[idx]);
2433                          count.push_back(nZoomSizeServer[idx]);
2434                        }
2435
2436                        --idxAxis;
2437                        --idx;
2438                      }
2439                    }
2440                  }
2441                }
2442                else
2443                {
2444                  CArray<int,1> axisDomainOrder = grid->axis_domain_order;
2445                  std::vector<StdString> domainList = grid->getDomainList();
2446                  std::vector<StdString> axisList   = grid->getAxisList();
2447                  int numElement = axisDomainOrder.numElements();
2448                  int idxDomain = domainList.size() - 1, idxAxis = axisList.size() - 1;
2449                  int idx = domainList.size() * 2 + axisList.size() - 1;// nZoomBeginGlobal.size() - 1;
2450
2451                  start.reserve(nZoomBeginGlobal.size());
2452                  count.reserve(nZoomBeginGlobal.size());
2453
2454                  for (int i = numElement - 1; i >= 0; --i)
2455                  {
2456                    if (2 == axisDomainOrder(i))
2457                    {
2458                      CDomain* domain = CDomain::get(domainList[idxDomain]);
2459                      if ((domain->type) != CDomain::type_attr::unstructured)
2460                      {
2461                        start.push_back(domain->zoom_jbegin - domain->global_zoom_jbegin);
2462                        count.push_back(domain->zoom_nj);
2463                      }
2464                      --idx ;
2465
2466                        start.push_back(domain->zoom_ibegin - domain->global_zoom_ibegin);
2467                        count.push_back(domain->zoom_ni);
2468                      --idx ;
2469                      --idxDomain;
2470                    }
2471                    else if (1 == axisDomainOrder(i))
2472                    {
2473                        CAxis* axis = CAxis::get(axisList[idxAxis]);
2474                        start.push_back(axis->zoom_begin - axis->global_zoom_begin);
2475                        count.push_back(axis->zoom_n);
2476                      --idx;
2477                      --idxAxis;
2478                    }
2479                    else
2480                    {
2481                      if (1 == axisDomainOrder.numElements())
2482                      {
2483                        start.push_back(0);
2484                        count.push_back(1);
2485                      }
2486                      --idx;
2487                    }
2488                  }
2489                }
2490
2491
2492                CTimer::get("Files : writing data").resume();
2493                SuperClassWriter::writeData(fieldData, fieldid, isCollective, field->getNStep() - 1, &start, &count);
2494                CTimer::get("Files : writing data").suspend();
2495
2496                 if (wtime)
2497                 {
2498                   CTimer::get("Files : writing time axis").resume();
2499                   if ( wtimeData)
2500                   {
2501//                     SuperClassWriter::writeData(time_data, timeAxisId, isCollective, field->getNStep() - 1);
2502//                     SuperClassWriter::writeData(time_data_bound, timeAxisBoundId, isCollective, field->getNStep() - 1);
2503                     SuperClassWriter::writeTimeAxisData(time_data, timeAxisId, isCollective, field->getNStep() - 1, isRoot);
2504                     SuperClassWriter::writeTimeAxisDataBounds(time_data_bound, timeAxisBoundId, isCollective, field->getNStep() - 1, isRoot);
2505                   }
2506                   if (wtimeCounter)
2507                   {
2508//                     SuperClassWriter::writeData(time_counter, getTimeCounterName(), isCollective, field->getNStep() - 1);
2509//                     if (timeCounterType!=record) SuperClassWriter::writeData(time_counter_bound, timeBoundId, isCollective, field->getNStep() - 1);
2510                     SuperClassWriter::writeTimeAxisData(time_counter, getTimeCounterName(), isCollective, field->getNStep() - 1,isRoot);
2511                     if (timeCounterType!=record) SuperClassWriter::writeTimeAxisDataBounds(time_counter_bound, timeBoundId, isCollective, field->getNStep() - 1, isRoot);
2512
2513                   }
2514                   CTimer::get("Files : writing time axis").suspend(); 
2515                 }
2516
2517                break;
2518              }
2519            }
2520         }
2521         catch (CNetCdfException& e)
2522         {
2523           StdString msg("On writing field data: ");
2524           msg.append(fieldid); msg.append("\n");
2525           msg.append("In the context : ");
2526           msg.append(context->getId()); msg.append("\n");
2527           msg.append(e.what());
2528           ERROR("CNc4DataOutput::writeFieldData_ (CField*  field)", << msg);
2529         }
2530      }
2531
2532      //---------------------------------------------------------------
2533
2534      void CNc4DataOutput::writeTimeAxis_
2535                  (CField*    field,
2536                   const boost::shared_ptr<CCalendar> cal)
2537      {
2538         StdOStringStream oss;
2539         bool createInstantAxis=false ;
2540         bool createCenteredAxis=false ;
2541         bool createTimeCounterAxis=false ;
2542         
2543         if (field->getOperationTimeType() == func::CFunctor::once) return ;
2544
2545
2546         StdString axisId ;
2547         StdString axisBoundId;
2548         StdString timeid(getTimeCounterName());
2549         StdString timeBoundId("axis_nbounds");
2550
2551         StdString strTimeUnits ;
2552         if (!field->file->time_units.isEmpty() && field->file->time_units==CFile::time_units_attr::days) strTimeUnits="days since " ;
2553         else  strTimeUnits="seconds since " ;
2554 
2555         if (field->getOperationTimeType() == func::CFunctor::instant) field->hasTimeInstant = true;
2556         if (field->getOperationTimeType() == func::CFunctor::centered) field->hasTimeCentered = true;
2557
2558
2559         if (field->file->time_counter.isEmpty())
2560         {
2561           if (timeCounterType==none) createTimeCounterAxis=true ;
2562           if (field->hasTimeCentered)
2563           {
2564             timeCounterType=centered ;
2565             if (!hasTimeCentered) createCenteredAxis=true ;
2566           }
2567           if (field->hasTimeInstant)
2568           {
2569             if (timeCounterType==none) timeCounterType=instant ;
2570             if (!hasTimeInstant) createInstantAxis=true ;
2571           }
2572         }
2573         else if (field->file->time_counter==CFile::time_counter_attr::instant)
2574         {
2575           if (field->hasTimeCentered)
2576           {
2577             if (!hasTimeCentered) createCenteredAxis=true ;
2578           }
2579           if (field->hasTimeInstant)
2580           {
2581             if (timeCounterType==none) createTimeCounterAxis=true ;
2582             timeCounterType=instant ;
2583             if (!hasTimeInstant) createInstantAxis=true ;
2584           }
2585         }
2586         else if (field->file->time_counter==CFile::time_counter_attr::centered)
2587         {
2588           if (field->hasTimeCentered)
2589           {
2590             if (timeCounterType==none) createTimeCounterAxis=true ;
2591             timeCounterType=centered ;
2592             if (!hasTimeCentered) createCenteredAxis=true ;
2593           }
2594           if (field->hasTimeInstant)
2595           {
2596             if (!hasTimeInstant) createInstantAxis=true ;
2597           }
2598         }
2599         else if (field->file->time_counter==CFile::time_counter_attr::instant_exclusive)
2600         {
2601           if (field->hasTimeCentered)
2602           {
2603             if (!hasTimeCentered) createCenteredAxis=true ;
2604           }
2605           if (field->hasTimeInstant)
2606           {
2607             if (timeCounterType==none) createTimeCounterAxis=true ;
2608             timeCounterType=instant ;
2609           }
2610         }
2611         else if (field->file->time_counter==CFile::time_counter_attr::centered_exclusive)
2612         {
2613           if (field->hasTimeCentered)
2614           {
2615             if (timeCounterType==none) createTimeCounterAxis=true ;
2616             timeCounterType=centered ;
2617           }
2618           if (field->hasTimeInstant)
2619           {
2620             if (!hasTimeInstant) createInstantAxis=true ;
2621           }
2622         }
2623         else if (field->file->time_counter==CFile::time_counter_attr::exclusive)
2624         {
2625           if (field->hasTimeCentered)
2626           {
2627             if (timeCounterType==none) createTimeCounterAxis=true ;
2628             if (timeCounterType==instant) createInstantAxis=true ;
2629             timeCounterType=centered ;
2630           }
2631           if (field->hasTimeInstant)
2632           {
2633             if (timeCounterType==none)
2634             {
2635               createTimeCounterAxis=true ;
2636               timeCounterType=instant ;
2637             }
2638             if (timeCounterType==centered)
2639             {
2640               if (!hasTimeInstant) createInstantAxis=true ;
2641             }
2642           }
2643         }
2644         else if (field->file->time_counter==CFile::time_counter_attr::none)
2645         {
2646           if (field->hasTimeCentered)
2647           {
2648             if (!hasTimeCentered) createCenteredAxis=true ;
2649           }
2650           if (field->hasTimeInstant)
2651           {
2652             if (!hasTimeInstant) createInstantAxis=true ;
2653           }
2654         }
2655         else if (field->file->time_counter==CFile::time_counter_attr::record)
2656         {
2657           if (timeCounterType==none) createTimeCounterAxis=true ;
2658           timeCounterType=record ;
2659           if (field->hasTimeCentered)
2660           {
2661             if (!hasTimeCentered) createCenteredAxis=true ;
2662           }
2663           if (field->hasTimeInstant)
2664           {
2665             if (!hasTimeInstant) createInstantAxis=true ;
2666           }
2667         }
2668         
2669         if (createInstantAxis)
2670         {
2671           axisId="time_instant" ;
2672           axisBoundId="time_instant_bounds";
2673           hasTimeInstant=true ;
2674         }
2675
2676         if (createCenteredAxis)
2677         {
2678           axisId="time_centered" ;
2679           axisBoundId="time_centered_bounds";
2680           hasTimeCentered=true ;
2681         }
2682
2683         
2684         try
2685         {
2686            std::vector<StdString> dims;
2687           
2688            if (createInstantAxis || createCenteredAxis)
2689            {
2690              // Adding time_instant or time_centered
2691              dims.push_back(timeid);
2692              if (!SuperClassWriter::varExist(axisId))
2693              {
2694                SuperClassWriter::addVariable(axisId, NC_DOUBLE, dims);
2695
2696                CDate timeOrigin=cal->getTimeOrigin() ;
2697                StdOStringStream oss2;
2698                StdString strInitdate=oss2.str() ;
2699                StdString strTimeOrigin=timeOrigin.toString() ;
2700                this->writeTimeAxisAttributes(axisId, cal->getType(),strTimeUnits+strTimeOrigin,
2701                                              strTimeOrigin, axisBoundId);
2702             }
2703
2704             // Adding time_instant_bounds or time_centered_bounds variables
2705             if (!SuperClassWriter::varExist(axisBoundId))
2706             {
2707                dims.clear() ;
2708                dims.push_back(timeid);
2709                dims.push_back(timeBoundId);
2710                SuperClassWriter::addVariable(axisBoundId, NC_DOUBLE, dims);
2711             }
2712           }
2713
2714           if (createTimeCounterAxis)
2715           {
2716             // Adding time_counter
2717             axisId = getTimeCounterName();
2718             axisBoundId = getTimeCounterName() + "_bounds";
2719             dims.clear();
2720             dims.push_back(timeid);
2721             if (!SuperClassWriter::varExist(axisId))
2722             {
2723                SuperClassWriter::addVariable(axisId, NC_DOUBLE, dims);
2724                SuperClassWriter::addAttribute("axis", string("T"), &axisId);
2725
2726                if (field->file->time_counter.isEmpty() || 
2727                   (field->file->time_counter != CFile::time_counter_attr::record))
2728                {
2729                  CDate timeOrigin = cal->getTimeOrigin();
2730                  StdString strTimeOrigin = timeOrigin.toString();
2731
2732                  this->writeTimeAxisAttributes(axisId, cal->getType(),
2733                                                strTimeUnits+strTimeOrigin,
2734                                                strTimeOrigin, axisBoundId);
2735                }
2736             }
2737
2738             // Adding time_counter_bound dimension
2739             if (field->file->time_counter.isEmpty() || (field->file->time_counter != CFile::time_counter_attr::record))
2740             {
2741                if (!SuperClassWriter::varExist(axisBoundId))
2742                {
2743                  dims.clear();
2744                  dims.push_back(timeid);
2745                  dims.push_back(timeBoundId);
2746                  SuperClassWriter::addVariable(axisBoundId, NC_DOUBLE, dims);
2747                }
2748             }
2749           }
2750         }
2751         catch (CNetCdfException& e)
2752         {
2753           StdString msg("On writing time axis data: ");
2754           msg.append("In the context : ");
2755           CContext* context = CContext::getCurrent() ;
2756           msg.append(context->getId()); msg.append("\n");
2757           msg.append(e.what());
2758           ERROR("CNc4DataOutput::writeTimeAxis_ (CField*    field, \
2759                  const boost::shared_ptr<CCalendar> cal)", << msg);
2760         }
2761      }
2762
2763      //---------------------------------------------------------------
2764
2765      void CNc4DataOutput::writeTimeAxisAttributes(const StdString & axis_name,
2766                                                   const StdString & calendar,
2767                                                   const StdString & units,
2768                                                   const StdString & time_origin,
2769                                                   const StdString & time_bounds,
2770                                                   const StdString & standard_name,
2771                                                   const StdString & long_name)
2772      {
2773         try
2774         {
2775           SuperClassWriter::addAttribute("standard_name", standard_name, &axis_name);
2776           SuperClassWriter::addAttribute("long_name",     long_name    , &axis_name);
2777           SuperClassWriter::addAttribute("calendar",      calendar     , &axis_name);
2778           SuperClassWriter::addAttribute("units",         units        , &axis_name);
2779           SuperClassWriter::addAttribute("time_origin",   time_origin  , &axis_name);
2780           SuperClassWriter::addAttribute("bounds",        time_bounds  , &axis_name);
2781         }
2782         catch (CNetCdfException& e)
2783         {
2784           StdString msg("On writing time axis Attribute: ");
2785           msg.append("In the context : ");
2786           CContext* context = CContext::getCurrent() ;
2787           msg.append(context->getId()); msg.append("\n");
2788           msg.append(e.what());
2789           ERROR("CNc4DataOutput::writeTimeAxisAttributes(const StdString & axis_name, \
2790                                                          const StdString & calendar,\
2791                                                          const StdString & units, \
2792                                                          const StdString & time_origin, \
2793                                                          const StdString & time_bounds, \
2794                                                          const StdString & standard_name, \
2795                                                          const StdString & long_name)", << msg);
2796         }
2797      }
2798
2799      //---------------------------------------------------------------
2800
2801      void CNc4DataOutput::writeAxisAttributes(const StdString & axis_name,
2802                                               const StdString & axis,
2803                                               const StdString & standard_name,
2804                                               const StdString & long_name,
2805                                               const StdString & units,
2806                                               const StdString & nav_model)
2807      {
2808         try
2809         {
2810          if (!axis.empty())
2811            SuperClassWriter::addAttribute("axis"       , axis         , &axis_name);
2812
2813          SuperClassWriter::addAttribute("standard_name", standard_name, &axis_name);
2814          SuperClassWriter::addAttribute("long_name"    , long_name    , &axis_name);
2815          SuperClassWriter::addAttribute("units"        , units        , &axis_name);
2816//          SuperClassWriter::addAttribute("nav_model"    , nav_model    , &axis_name);
2817         }
2818         catch (CNetCdfException& e)
2819         {
2820           StdString msg("On writing Axis Attribute: ");
2821           msg.append("In the context : ");
2822           CContext* context = CContext::getCurrent() ;
2823           msg.append(context->getId()); msg.append("\n");
2824           msg.append(e.what());
2825           ERROR("CNc4DataOutput::writeAxisAttributes(const StdString & axis_name, \
2826                                                      const StdString & axis, \
2827                                                      const StdString & standard_name, \
2828                                                      const StdString & long_name, \
2829                                                      const StdString & units, \
2830                                                      const StdString & nav_model)", << msg);
2831         }
2832      }
2833
2834      //---------------------------------------------------------------
2835
2836      void CNc4DataOutput::writeLocalAttributes
2837         (int ibegin, int ni, int jbegin, int nj, StdString domid)
2838      {
2839        try
2840        {
2841         SuperClassWriter::addAttribute(StdString("ibegin").append(domid), ibegin);
2842         SuperClassWriter::addAttribute(StdString("ni"    ).append(domid), ni);
2843         SuperClassWriter::addAttribute(StdString("jbegin").append(domid), jbegin);
2844         SuperClassWriter::addAttribute(StdString("nj"    ).append(domid), nj);
2845        }
2846        catch (CNetCdfException& e)
2847        {
2848           StdString msg("On writing Local Attributes: ");
2849           msg.append("In the context : ");
2850           CContext* context = CContext::getCurrent() ;
2851           msg.append(context->getId()); msg.append("\n");
2852           msg.append(e.what());
2853           ERROR("CNc4DataOutput::writeLocalAttributes \
2854                  (int ibegin, int ni, int jbegin, int nj, StdString domid)", << msg);
2855        }
2856
2857      }
2858
2859      void CNc4DataOutput::writeLocalAttributes_IOIPSL(const StdString& dimXid, const StdString& dimYid,
2860                                                       int ibegin, int ni, int jbegin, int nj, int ni_glo, int nj_glo, int rank, int size)
2861      {
2862         CArray<int,1> array(2) ;
2863
2864         try
2865         {
2866           SuperClassWriter::addAttribute("DOMAIN_number_total",size ) ;
2867           SuperClassWriter::addAttribute("DOMAIN_number", rank) ;
2868           array = SuperClassWriter::getDimension(dimXid) + 1, SuperClassWriter::getDimension(dimYid) + 1;
2869           SuperClassWriter::addAttribute("DOMAIN_dimensions_ids",array) ;
2870           array=ni_glo,nj_glo ;
2871           SuperClassWriter::addAttribute("DOMAIN_size_global", array) ;
2872           array=ni,nj ;
2873           SuperClassWriter::addAttribute("DOMAIN_size_local", array) ;
2874           array=ibegin+1,jbegin+1 ;
2875           SuperClassWriter::addAttribute("DOMAIN_position_first", array) ;
2876           array=ibegin+ni-1+1,jbegin+nj-1+1 ;
2877           SuperClassWriter::addAttribute("DOMAIN_position_last",array) ;
2878           array=0,0 ;
2879           SuperClassWriter::addAttribute("DOMAIN_halo_size_start", array) ;
2880           SuperClassWriter::addAttribute("DOMAIN_halo_size_end", array);
2881           SuperClassWriter::addAttribute("DOMAIN_type",string("box")) ;
2882  /*
2883           SuperClassWriter::addAttribute("DOMAIN_DIM_N001",string("x")) ;
2884           SuperClassWriter::addAttribute("DOMAIN_DIM_N002",string("y")) ;
2885           SuperClassWriter::addAttribute("DOMAIN_DIM_N003",string("axis_A")) ;
2886           SuperClassWriter::addAttribute("DOMAIN_DIM_N004",string("time_counter")) ;
2887  */
2888         }
2889         catch (CNetCdfException& e)
2890         {
2891           StdString msg("On writing Local Attributes IOIPSL \n");
2892           msg.append("In the context : ");
2893           CContext* context = CContext::getCurrent() ;
2894           msg.append(context->getId()); msg.append("\n");
2895           msg.append(e.what());
2896           ERROR("CNc4DataOutput::writeLocalAttributes_IOIPSL \
2897                  (int ibegin, int ni, int jbegin, int nj, int ni_glo, int nj_glo, int rank, int size)", << msg);
2898         }
2899      }
2900      //---------------------------------------------------------------
2901
2902      void CNc4DataOutput:: writeFileAttributes(const StdString & name,
2903                                                const StdString & description,
2904                                                const StdString & conventions,
2905                                                const StdString & production,
2906                                                const StdString & timeStamp)
2907      {
2908         try
2909         {
2910           SuperClassWriter::addAttribute("name"       , name);
2911           SuperClassWriter::addAttribute("description", description);
2912           SuperClassWriter::addAttribute("title"      , description);
2913           SuperClassWriter::addAttribute("Conventions", conventions);
2914           // SuperClassWriter::addAttribute("production" , production);
2915
2916           StdString timeStampStr ;
2917           if (file->time_stamp_name.isEmpty()) timeStampStr="timeStamp" ;
2918           else timeStampStr=file->time_stamp_name ;
2919           SuperClassWriter::addAttribute(timeStampStr, timeStamp);
2920
2921           StdString uuidName ;
2922           if (file->uuid_name.isEmpty()) uuidName="uuid" ;
2923           else uuidName=file->uuid_name ;
2924
2925           if (file->uuid_format.isEmpty()) SuperClassWriter::addAttribute(uuidName, getUuidStr());
2926           else SuperClassWriter::addAttribute(uuidName, getUuidStr(file->uuid_format));
2927         
2928         }
2929         catch (CNetCdfException& e)
2930         {
2931           StdString msg("On writing File Attributes \n ");
2932           msg.append("In the context : ");
2933           CContext* context = CContext::getCurrent() ;
2934           msg.append(context->getId()); msg.append("\n");
2935           msg.append(e.what());
2936           ERROR("CNc4DataOutput:: writeFileAttributes(const StdString & name, \
2937                                                const StdString & description, \
2938                                                const StdString & conventions, \
2939                                                const StdString & production, \
2940                                                const StdString & timeStamp)", << msg);
2941         }
2942      }
2943
2944      //---------------------------------------------------------------
2945
2946      void CNc4DataOutput::writeMaskAttributes(const StdString & mask_name,
2947                                               int data_dim,
2948                                               int data_ni,
2949                                               int data_nj,
2950                                               int data_ibegin,
2951                                               int data_jbegin)
2952      {
2953         try
2954         {
2955           SuperClassWriter::addAttribute("data_dim"   , data_dim   , &mask_name);
2956           SuperClassWriter::addAttribute("data_ni"    , data_ni    , &mask_name);
2957           SuperClassWriter::addAttribute("data_nj"    , data_nj    , &mask_name);
2958           SuperClassWriter::addAttribute("data_ibegin", data_ibegin, &mask_name);
2959           SuperClassWriter::addAttribute("data_jbegin", data_jbegin, &mask_name);
2960         }
2961         catch (CNetCdfException& e)
2962         {
2963           StdString msg("On writing Mask Attributes \n ");
2964           msg.append("In the context : ");
2965           CContext* context = CContext::getCurrent() ;
2966           msg.append(context->getId()); msg.append("\n");
2967           msg.append(e.what());
2968           ERROR("CNc4DataOutput::writeMaskAttributes(const StdString & mask_name, \
2969                                               int data_dim, \
2970                                               int data_ni, \
2971                                               int data_nj, \
2972                                               int data_ibegin, \
2973                                               int data_jbegin)", << msg);
2974         }
2975      }
2976
2977      ///--------------------------------------------------------------
2978
2979      StdSize CNc4DataOutput::getRecordFromTime(Time time, double factorUnit)
2980      {
2981        std::map<Time, StdSize>::const_iterator it = timeToRecordCache.find(time);
2982        if (it == timeToRecordCache.end())
2983        {
2984          StdString timeAxisBoundsId(getTimeCounterName() + "_bounds");
2985          if (!SuperClassWriter::varExist(timeAxisBoundsId)) timeAxisBoundsId = "time_centered_bounds";
2986          if (!SuperClassWriter::varExist(timeAxisBoundsId)) timeAxisBoundsId = "time_instant_bounds";
2987
2988          CArray<double,2> timeAxisBounds;
2989          std::vector<StdSize> dimSize(SuperClassWriter::getDimensions(timeAxisBoundsId)) ;
2990         
2991          StdSize record = 0;
2992          double dtime(time);
2993          for (int n = dimSize[0] - 1; n >= 0; n--)
2994          {
2995            SuperClassWriter::getTimeAxisBounds(timeAxisBounds, timeAxisBoundsId, isCollective, n);
2996            timeAxisBounds*=factorUnit ;
2997            if (timeAxisBounds(1, 0) < dtime)
2998            {
2999              record = n + 1;
3000              break;
3001            }
3002          }
3003          it = timeToRecordCache.insert(std::make_pair(time, record)).first;
3004        }
3005        return it->second;
3006      }
3007
3008      ///--------------------------------------------------------------
3009
3010      bool CNc4DataOutput::isWrittenDomain(const std::string& domainName) const
3011      {
3012        return (this->writtenDomains.find(domainName) != this->writtenDomains.end());
3013      }
3014
3015      bool CNc4DataOutput::isWrittenCompressedDomain(const std::string& domainName) const
3016      {
3017        return (this->writtenCompressedDomains.find(domainName) != this->writtenCompressedDomains.end());
3018      }
3019
3020      bool CNc4DataOutput::isWrittenAxis(const std::string& axisName) const
3021      {
3022        return (this->writtenAxis.find(axisName) != this->writtenAxis.end());
3023      }
3024
3025      bool CNc4DataOutput::isWrittenCompressedAxis(const std::string& axisName) const
3026      {
3027        return (this->writtenCompressedAxis.find(axisName) != this->writtenCompressedAxis.end());
3028      }
3029
3030      bool CNc4DataOutput::isWrittenScalar(const std::string& scalarName) const
3031      {
3032        return (this->writtenScalar.find(scalarName) != this->writtenScalar.end());
3033      }
3034
3035      void CNc4DataOutput::setWrittenDomain(const std::string& domainName)
3036      {
3037        this->writtenDomains.insert(domainName);
3038      }
3039
3040      void CNc4DataOutput::setWrittenCompressedDomain(const std::string& domainName)
3041      {
3042        this->writtenCompressedDomains.insert(domainName);
3043      }
3044
3045      void CNc4DataOutput::setWrittenAxis(const std::string& axisName)
3046      {
3047        this->writtenAxis.insert(axisName);
3048      }
3049
3050      void CNc4DataOutput::setWrittenCompressedAxis(const std::string& axisName)
3051      {
3052        this->writtenCompressedAxis.insert(axisName);
3053      }
3054
3055      void CNc4DataOutput::setWrittenScalar(const std::string& scalarName)
3056      {
3057        this->writtenScalar.insert(scalarName);
3058      }
3059} // namespace xios
Note: See TracBrowser for help on using the repository browser.