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

Last change on this file since 1046 was 1046, checked in by ymipsl, 7 years ago
  • Add 2 new file attributes to parameter timestamp : time_stamp_name and time_stamp_format.

Default value :
time_stamp_name="timestamp"
time_stamp_format="%Y-%b-%d %H:%M:%S %Z"

  • timestamp is now given in UTC time

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