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

Last change on this file since 990 was 990, checked in by mhnguyen, 7 years ago

Adding new attributes for fields: cell_methods and cell_methods_mode

cell_methods defines the string appearing in cell_methods meta data of a field
cell_methods_mode specifies modes to write out cell_methods. This attribute is only taken place if only if cell_methods is not empty()
+) overwrite: cell_methods string replaces default value of cell_methods meta data (Also default behavior if only cell_methods is defined)
+) prefix: concatenate cell_methods string as prefix of cell_methods meta data
+) suffix: concatenate cell_methods string as suffix of cell_methods meta data
+) none: do nothing

Test
+) On Curie
+) Work

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