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

Last change on this file since 1415 was 1415, checked in by ymipsl, 6 years ago

2 fixs :

  • for curvilinear grids, associated coordinates are wrong if using default lon_name et lat_name value
  • add domain_id 2 times for boundaries name

YM

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