source: XIOS/dev/dev_olga/src/io/nc4_data_output.cpp @ 1054

Last change on this file since 1054 was 1054, checked in by oabramkina, 7 years ago

dev: intermediate commit.

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