source: XIOS/trunk/src/io/nc4_data_output.cpp @ 1559

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

Replacing axis zoom by axis extract.
Zoom private attributes are gone for good.

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