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

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