source: XIOS/dev/branch_yushan_merged/src/io/nc4_data_output.cpp @ 1138

Last change on this file since 1138 was 1138, checked in by yushan, 7 years ago

test_remap back to work. No thread for now

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