source: XIOS/dev/dev_ym/XIOS_COUPLING/src/io/nc4_data_output.cpp @ 1882

Last change on this file since 1882 was 1882, checked in by ymipsl, 4 years ago

Xios coupling branch
Refactor and simplify file writer filter management on server side.

YM

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