source: XIOS/dev/branch_openmp/src/io/nc4_data_output.cpp @ 1460

Last change on this file since 1460 was 1460, checked in by yushan, 6 years ago

branch_openmp merged with XIOS_DEV_CMIP6@1459

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