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

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

Cleaning up some redundant codes

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