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

Last change on this file since 2200 was 2200, checked in by ymipsl, 3 years ago

Bugs fix for UGRID convention output

  • global indexation was not taking into account
  • coherence problem in connectivity for node, edge and face mesh
  • add UGRID testcase based on sphere cube

YM

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