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

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

Adding a check on existence of dimension str_len.

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