source: XIOS/dev/dev_olga/src/node/file.cpp @ 1132

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

Correcting a minor bug on writting unstructured grid

+) Correct the mapping between received data and written data.
+) Clean some redundant codes

Test
+) On Curie
+) Writing on unstructured grid works correctly

  • 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
File size: 36.3 KB
RevLine 
[219]1#include "file.hpp"
2
[352]3#include "attribute_template.hpp"
4#include "object_template.hpp"
5#include "group_template.hpp"
[219]6#include "object_factory.hpp"
[300]7#include "context.hpp"
8#include "context_server.hpp"
9#include "nc4_data_output.hpp"
[599]10#include "nc4_data_input.hpp"
[318]11#include "calendar_util.hpp"
12#include "date.hpp"
[352]13#include "message.hpp"
14#include "type.hpp"
[591]15#include "xios_spl.hpp"
[382]16#include "mpi.hpp"
[219]17
[335]18namespace xios {
[509]19
[878]20   /// ////////////////////// Dfinitions ////////////////////// ///
[219]21
22   CFile::CFile(void)
23      : CObjectTemplate<CFile>(), CFileAttributes()
[379]24      , vFieldGroup(), data_out(), enabledFields(), fileComm(MPI_COMM_NULL)
[775]25      , allDomainEmpty(false), isOpen(false)
[509]26   {
[957]27     setVirtualFieldGroup(CFieldGroup::create(getId() + "_virtual_field_group"));
28     setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group"));
[472]29   }
[219]30
31   CFile::CFile(const StdString & id)
32      : CObjectTemplate<CFile>(id), CFileAttributes()
[379]33      , vFieldGroup(), data_out(), enabledFields(), fileComm(MPI_COMM_NULL)
[775]34      , allDomainEmpty(false), isOpen(false)
[509]35    {
[957]36      setVirtualFieldGroup(CFieldGroup::create(getId() + "_virtual_field_group"));
37      setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group"));
[472]38    }
[219]39
40   CFile::~CFile(void)
41   { /* Ne rien faire de plus */ }
42
43   ///---------------------------------------------------------------
[509]44  //! Get name of file
[219]45   StdString CFile::GetName(void)   { return (StdString("file")); }
46   StdString CFile::GetDefName(void){ return (CFile::GetName()); }
47   ENodeType CFile::GetType(void)   { return (eFile); }
48
49   //----------------------------------------------------------------
[773]50
51   const StdString& CFile::getFileOutputName(void) const
52   {
53     return name.isEmpty() ? getId() : name;
54   }
55
56   //----------------------------------------------------------------
[509]57   /*!
[599]58   \brief Get data writer object.
[509]59   Each enabled file in xml represents a physical netcdf file.
[599]60   This function allows to access the data writer object.
61   \return data writer object.
[509]62   */
[337]63   boost::shared_ptr<CDataOutput> CFile::getDataOutput(void) const
[219]64   {
[599]65      return data_out;
[219]66   }
67
[509]68   /*!
[599]69   \brief Get data reader object.
70   Each enabled file in xml represents a physical netcdf file.
71   This function allows to access the data reader object.
72   \return data reader object.
73   */
74   boost::shared_ptr<CDataInput> CFile::getDataInput(void) const
75   {
76      return data_in;
77   }
78
79   /*!
[509]80   \brief Get virtual field group
81      In each file, there always exists a field group which is the ancestor of all
82   fields in the file. This is considered be virtual because it is created automatically during
83   file initialization and it normally doesn't appear on xml file
84   \return Pointer to field group
85   */
[347]86   CFieldGroup* CFile::getVirtualFieldGroup(void) const
[219]87   {
88      return (this->vFieldGroup);
89   }
90
[509]91   /*!
92   \brief Get virtual variable group
93      In each file, there always exists a variable group which is the ancestor of all
94   variable in the file. This is considered be virtual because it is created automatically during
95   file initialization and it normally doesn't appear on xml file
96   \return Pointer to variable group
97   */
[472]98   CVariableGroup* CFile::getVirtualVariableGroup(void) const
99   {
100      return (this->vVariableGroup);
101   }
102
[509]103   //! Get all fields of a file
[347]104   std::vector<CField*> CFile::getAllFields(void) const
[219]105   {
106      return (this->vFieldGroup->getAllChildren());
107   }
[509]108
109   //! Get all variables of a file
[472]110   std::vector<CVariable*> CFile::getAllVariables(void) const
111   {
112      return (this->vVariableGroup->getAllChildren());
113   }
[219]114
115   //----------------------------------------------------------------
[509]116   /*!
117   \brief Get all enabled fields of file
118      A field is considered to be enabled if it fullfil these conditions: it is enabled, inside a enabled file
119   and its own level is not larger than file output level.
120   \param [in] default_outputlevel default value output level of file
121   \param [in] default_level default value level of field
122   \param [in] default_enabled flag determine by default if field is enabled
123   \return Vector of pointers of enabled fields
124   */
125   std::vector<CField*> CFile::getEnabledFields(int default_outputlevel,
[347]126                                                int default_level,
127                                                bool default_enabled)
[219]128   {
129      if (!this->enabledFields.empty())
130         return (this->enabledFields);
131
132      const int _outputlevel =
133         (!output_level.isEmpty()) ? output_level.getValue() : default_outputlevel;
[347]134      std::vector<CField*>::iterator it;
[219]135      this->enabledFields = this->getAllFields();
136
[347]137      std::vector<CField*> newEnabledFields;
[509]138
[651]139      for ( it = this->enabledFields.begin(); it != this->enabledFields.end(); it++ )
[219]140      {
[878]141         if (!(*it)->enabled.isEmpty()) // Si l'attribut 'enabled' est dfini ...
[219]142         {
[300]143            if (! (*it)->enabled.getValue()) continue;
144//            { it--; this->enabledFields.erase(it+1); continue; }
[219]145         }
[878]146         else // Si l'attribut 'enabled' n'est pas dfini ...
[219]147         {
[651]148            if (!default_enabled) continue;
[300]149//            { it--; this->enabledFields.erase(it+1); continue; }
[219]150         }
151
[878]152         if (!(*it)->level.isEmpty()) // Si l'attribut 'level' est dfini ...
[219]153         {
[651]154            if ((*it)->level.getValue() > _outputlevel) continue;
[300]155//            { it--; this->enabledFields.erase(it+1); continue; }
[219]156         }
[878]157         else // Si l'attribut 'level' n'est pas dfini ...
[219]158         {
[651]159            if (default_level > _outputlevel) continue;
[300]160//            { it--; this->enabledFields.erase(it+1); continue; }
[219]161         }
[509]162
[651]163//         CField* field_tmp=(*it).get();
164//         shared_ptr<CField> sptfield=*it;
165//         field_tmp->refObject.push_back(sptfield);
166         newEnabledFields.push_back(*it);
[286]167         // Le champ est finalement actif, on y ajoute sa propre reference.
[459]168//         (*it)->refObject.push_back(*it);
[878]169         // Le champ est finalement actif, on y ajoute la rfrence au champ de base.
[346]170         (*it)->setRelFile(CFile::get(this));
[219]171      }
[651]172      enabledFields = newEnabledFields;
[219]173
174      return (this->enabledFields);
175   }
176
177   //----------------------------------------------------------------
[509]178   //! Change virtual field group to a new one
[347]179   void CFile::setVirtualFieldGroup(CFieldGroup* newVFieldGroup)
[509]180   {
181      this->vFieldGroup = newVFieldGroup;
[219]182   }
183
[509]184   //! Change virtual variable group to new one
[472]185   void CFile::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
[509]186   {
187      this->vVariableGroup = newVVariableGroup;
[472]188   }
189
[219]190   //----------------------------------------------------------------
[318]191   bool CFile::isSyncTime(void)
192   {
[651]193     CContext* context = CContext::getCurrent();
194     const CDate& currentDate = context->calendar->getCurrentDate();
[538]195     if (!sync_freq.isEmpty())
[318]196     {
[651]197       if (lastSync + sync_freq.getValue() < currentDate)
[318]198       {
[651]199         lastSync = currentDate;
200         return true;
[318]201        }
202      }
[651]203      return false;
[318]204    }
[509]205
206   //! Initialize a file in order to write into it
[321]207   void CFile::initFile(void)
208   {
[651]209      CContext* context = CContext::getCurrent();
210      const CDate& currentDate = context->calendar->getCurrentDate();
211      CContextServer* server = context->server;
[509]212
[651]213      lastSync  = currentDate;
214      lastSplit = currentDate;
[702]215      if (!split_freq.isEmpty())
216      {
217        if (context->registryIn->foundKey("splitStart") && context->registryIn->foundKey("splitEnd"))
218        {
219          CDate savedSplitStart(*context->getCalendar()), savedSplitEnd(*context->getCalendar());
220          context->registryIn->getKey("splitStart", savedSplitStart);
221          context->registryIn->getKey("splitEnd",   savedSplitEnd);
222
223          if (savedSplitStart <= lastSplit && lastSplit <= savedSplitEnd)
224            lastSplit = savedSplitStart;
225        }
226      }
[651]227      isOpen = false;
[379]228
[651]229      allDomainEmpty = true;
[567]230
[952]231//      if (!record_offset.isEmpty() && record_offset < 0)
232//        ERROR("void CFile::initFile(void)",
233//              "Invalid 'record_offset', this attribute cannot be negative.");
234      const int recordOffset = record_offset.isEmpty() ? 0 : record_offset;
[757]235
[1009]236//      set<CAxis*> setAxis;
237//      set<CDomain*> setDomains;
238      set<StdString> setAxis;
239      set<StdString> setDomains;
[379]240
241      std::vector<CField*>::iterator it, end = this->enabledFields.end();
[609]242      for (it = this->enabledFields.begin(); it != end; it++)
[379]243      {
244         CField* field = *it;
[609]245         allDomainEmpty &= !field->grid->doGridHaveDataToWrite();
246         std::vector<CAxis*> vecAxis = field->grid->getAxis();
247         for (size_t i = 0; i < vecAxis.size(); ++i)
[1009]248           setAxis.insert(vecAxis[i]->getAxisOutputName());
249//            setAxis.insert(vecAxis[i]);
[609]250         std::vector<CDomain*> vecDomains = field->grid->getDomains();
251         for (size_t i = 0; i < vecDomains.size(); ++i)
[1009]252           setDomains.insert(vecDomains[i]->getDomainOutputName());
253//            setDomains.insert(vecDomains[i]);
[757]254
255         field->resetNStep(recordOffset);
[379]256      }
[609]257      nbAxis = setAxis.size();
258      nbDomains = setDomains.size();
[379]259
[509]260      // create sub communicator for file
[651]261      int color = allDomainEmpty ? 0 : 1;
262      MPI_Comm_split(server->intraComm, color, server->intraCommRank, &fileComm);
263      if (allDomainEmpty) MPI_Comm_free(&fileComm);
[692]264
265      if (time_counter.isEmpty()) time_counter.setValue(time_counter_attr::centered);
[802]266      if (time_counter_name.isEmpty()) time_counter_name = "time_counter";
[321]267    }
[509]268
269    //! Verify state of a file
[321]270    void CFile::checkFile(void)
271    {
[1054]272      CContext* context = CContext::getCurrent();
273      // Done by classical server or secondary server
274      if (!CXios::usingServer2 || (CXios::usingServer2 && !context->hasClient))
[599]275      {
[1054]276        if (mode.isEmpty() || mode.getValue() == mode_attr::write)
277        {
278          if (!isOpen) createHeader();
279          checkSync();
280        }
281        else
282        {
283          if (!isOpen) openInReadMode();
284        }
285        checkSplit();
[599]286      }
[321]287    }
[509]288
289    /*!
290    \brief Verify if synchronisation should be done
291        If syn option is enabled, syn frequence and current time will be used to
292    calculate the moment to syn file(s)
293    \return True if it is the moment to synchronize file, otherwise false
294    */
[321]295   bool CFile::checkSync(void)
296   {
[651]297     CContext* context = CContext::getCurrent();
298     const CDate& currentDate = context->calendar->getCurrentDate();
[538]299     if (!sync_freq.isEmpty())
[321]300     {
[651]301       if (lastSync + sync_freq.getValue() <= currentDate)
[321]302       {
[651]303         lastSync = currentDate;
304         data_out->syncFile();
305         return true;
[321]306        }
307      }
[651]308      return false;
[321]309    }
[509]310
311    /*!
312    \brief Verify if splitting should be done
313        If split option is enabled, split frequence and current time will be used to
314    calculate the moment to split file
315    \return True if it is the moment to split file, otherwise false
316    */
[321]317    bool CFile::checkSplit(void)
318    {
[651]319      CContext* context = CContext::getCurrent();
320      const CDate& currentDate = context->calendar->getCurrentDate();
[538]321      if (!split_freq.isEmpty())
[321]322      {
[651]323        if (currentDate > lastSplit + split_freq.getValue())
[321]324        {
[651]325          lastSplit = lastSplit + split_freq.getValue();
[347]326          std::vector<CField*>::iterator it, end = this->enabledFields.end();
[599]327          for (it = this->enabledFields.begin(); it != end; it++)
328          {
329            (*it)->resetNStep();
330            (*it)->resetNStepMax();
331          }
332          if (mode.isEmpty() || mode.getValue() == mode_attr::write)
[651]333            createHeader();
[599]334          else
335            openInReadMode();
[651]336          return true;
[321]337        }
338      }
[651]339      return false;
[321]340    }
[509]341
342   /*!
343   \brief Create header of netcdf file
344   There are some information to fill in header of each netcdf.
345   */
[300]346   void CFile::createHeader(void)
[219]347   {
[651]348      CContext* context = CContext::getCurrent();
349      CContextServer* server = context->server;
[509]350
[379]351      if (!allDomainEmpty)
[219]352      {
[773]353         StdString filename = getFileOutputName();
[875]354         if (!name_suffix.isEmpty()) filename+=name_suffix.getValue();
355
356// determine splitting format in the file name  : firstPart%start_date%middlePart%end_date%lastPart
357
358         std::string strStartDate="%start_date%" ;
359         std::string strEndDate="%end_date%" ;
360
361         std::string firstPart ;
362         std::string middlePart ;
363         std::string lastPart ;
364         size_t pos1, pos2 ;
365         bool hasStartDate=false ;
[920]366         bool hasEndDate=false ;
367         bool hasSplit = (!split_freq.isEmpty());
[875]368                 
369         pos1=filename.find(strStartDate) ;
370         if (pos1!=std::string::npos)
371         {
372           firstPart=filename.substr(0,pos1) ;
373           pos1+=strStartDate.size() ;
374           hasStartDate=true ;
375         }
376         else pos1=0 ;
377
378         pos2=filename.find(strEndDate,pos1) ;
379         if (pos2!=std::string::npos)
380         {
381           middlePart=filename.substr(pos1,pos2-pos1) ;
382           pos2+=strEndDate.size() ;
383           lastPart=filename.substr(pos2,filename.size()-pos2) ;
384           hasEndDate=true ;
385         }
386         else middlePart=filename.substr(pos1,filename.size()) ;
387
388         if (!hasStartDate && !hasEndDate)
389         {
390           hasStartDate=true ;
391           hasEndDate=true;
392           firstPart=middlePart ;
[920]393           if (hasSplit) firstPart +="_";
[875]394           middlePart="-" ;
395         }
[920]396   
[300]397         StdOStringStream oss;
[538]398
[431]399         if (!split_freq.isEmpty())
400         {
[702]401           CDate splitEnd = lastSplit + split_freq - 1 * Second;
402
[651]403           string splitFormat;
[431]404           if (split_freq_format.isEmpty())
405           {
[538]406             if (split_freq.getValue().second != 0) splitFormat = "%y%mo%d%h%mi%s";
407             else if (split_freq.getValue().minute != 0) splitFormat = "%y%mo%d%h%mi";
408             else if (split_freq.getValue().hour != 0) splitFormat = "%y%mo%d%h";
409             else if (split_freq.getValue().day != 0) splitFormat = "%y%mo%d";
410             else if (split_freq.getValue().month != 0) splitFormat = "%y%mo";
411             else splitFormat = "%y";
[431]412           }
[651]413           else splitFormat = split_freq_format;
[702]414
[875]415           oss << firstPart ;
416           if (hasStartDate) oss << lastSplit.getStr(splitFormat) ;
417           oss << middlePart ;
418           if (hasEndDate) oss << splitEnd.getStr(splitFormat);
419           oss << lastPart ;
[702]420
421           context->registryOut->setKey("splitStart", lastSplit);
422           context->registryOut->setKey("splitEnd",   splitEnd);
[431]423         }
[875]424         else oss<<firstPart<<lastPart ;
[509]425
[528]426        bool append = !this->append.isEmpty() && this->append.getValue();
[567]427
[517]428         bool useClassicFormat = !format.isEmpty() && format == format_attr::netcdf4_classic;
[878]429         bool useCFConvention = convention.isEmpty() || convention == convention_attr::CF;
[517]430
[651]431         bool multifile = true;
[300]432         if (!type.isEmpty())
433         {
[651]434           if (type == type_attr::one_file) multifile = false;
435           else if (type == type_attr::multiple_file) multifile = true;
[379]436
[509]437         }
[379]438#ifndef USING_NETCDF_PAR
439         if (!multifile)
440         {
[651]441            info(0) << "!!! Warning -> Using non parallel version of netcdf, switching in multiple_file mode for file : " << filename << " ..." << endl;
442            multifile = true;
[379]443          }
444#endif
[509]445         if (multifile)
[300]446         {
[651]447            int commSize, commRank;
448            MPI_Comm_size(fileComm, &commSize);
449            MPI_Comm_rank(fileComm, &commRank);
[509]450
451            if (server->intraCommSize > 1)
[375]452            {
[651]453              oss << "_" ;
454              int width=0; int n = commSize-1;
455              while (n != 0) { n = n / 10; width++;}
[509]456              if (!min_digits.isEmpty())
[651]457                if (width < min_digits) width = min_digits;
458              oss.width(width);
459              oss.fill('0');
460              oss << right << commRank;
[375]461            }
[300]462         }
463         oss << ".nc";
464
[526]465         bool isCollective = par_access.isEmpty() ||  par_access == par_access_attr::collective;
466
467         if (isOpen) data_out->closeFile();
468
[878]469        data_out = shared_ptr<CDataOutput>(new CNc4DataOutput(oss.str(), append, useClassicFormat, useCFConvention,
[802]470                                                              fileComm, multifile, isCollective, time_counter_name));
[528]471        isOpen = true;
[300]472
[528]473        data_out->writeFile(CFile::get(this));
474
475        // Do not recreate the file structure if opening an existing file
476        if (!data_out->IsInAppendMode())
477        {
478          std::vector<CField*>::iterator it, end = this->enabledFields.end();
479          for (it = this->enabledFields.begin(); it != end; it++)
480          {
[347]481            CField* field = *it;
[300]482            this->data_out->writeFieldGrid(field);
[528]483          }
484          this->data_out->writeTimeDimension();
[509]485
[528]486          for (it = this->enabledFields.begin(); it != end; it++)
487          {
[347]488            CField* field = *it;
[300]489            this->data_out->writeField(field);
[528]490          }
[509]491
[651]492          vector<CVariable*> listVars = getAllVariables();
[528]493          for (vector<CVariable*>::iterator it = listVars.begin(); it != listVars.end(); it++)
494            this->data_out->writeAttribute(*it);
[509]495
[528]496          this->data_out->definition_end();
497        }
[219]498      }
499   }
500
[599]501  /*!
502  \brief Open an existing NetCDF file in read-only mode
503  */
504  void CFile::openInReadMode(void)
505  {
506    CContext* context = CContext::getCurrent();
[651]507    CContextServer* server = context->server;
[599]508
509    if (!allDomainEmpty)
510    {
[773]511      StdString filename = getFileOutputName();
[599]512      StdOStringStream oss;
513      oss << filename;
514      if (!name_suffix.isEmpty()) oss << name_suffix.getValue();
515
516      if (!split_freq.isEmpty())
517      {
518        string splitFormat;
519        if (split_freq_format.isEmpty())
520        {
521          if (split_freq.getValue().second != 0) splitFormat = "%y%mo%d%h%mi%s";
522          else if (split_freq.getValue().minute != 0) splitFormat = "%y%mo%d%h%mi";
523          else if (split_freq.getValue().hour != 0) splitFormat = "%y%mo%d%h";
524          else if (split_freq.getValue().day != 0) splitFormat = "%y%mo%d";
525          else if (split_freq.getValue().month != 0) splitFormat = "%y%mo";
526          else splitFormat = "%y";
527        }
[651]528        else splitFormat = split_freq_format;
529        oss << "_" << lastSplit.getStr(splitFormat)
530        << "-" << (lastSplit + split_freq.getValue() - 1 * Second).getStr(splitFormat);
[599]531      }
532
533      bool multifile = true;
534      if (!type.isEmpty())
535      {
536        if (type == type_attr::one_file) multifile = false;
537        else if (type == type_attr::multiple_file) multifile = true;
538      }
539  #ifndef USING_NETCDF_PAR
540      if (!multifile)
541      {
542        info(0) << "!!! Warning -> Using non parallel version of netcdf, switching in multiple_file mode for file : " << filename << " ..." << endl;
543        multifile = true;
544      }
545  #endif
546      if (multifile)
547      {
548        int commSize, commRank;
549        MPI_Comm_size(fileComm, &commSize);
550        MPI_Comm_rank(fileComm, &commRank);
551
552        if (server->intraCommSize > 1)
553        {
[651]554          oss << "_";
[599]555          int width = 0, n = commSize - 1;
556          while (n != 0) { n = n / 10; width++; }
557          if (!min_digits.isEmpty() && width < min_digits)
558            width = min_digits;
559          oss.width(width);
560          oss.fill('0');
561          oss << right << commRank;
562        }
563      }
564      oss << ".nc";
565
566      bool isCollective = par_access.isEmpty() || par_access == par_access_attr::collective;
567
568      if (isOpen) data_out->closeFile();
[811]569      if (time_counter_name.isEmpty()) data_in = shared_ptr<CDataInput>(new CNc4DataInput(oss.str(), fileComm, multifile, isCollective));
570      else data_in = shared_ptr<CDataInput>(new CNc4DataInput(oss.str(), fileComm, multifile, isCollective, time_counter_name));
[599]571      isOpen = true;
572    }
573  }
574
[509]575   //! Close file
[286]576   void CFile::close(void)
577   {
[379]578     if (!allDomainEmpty)
[509]579       if (isOpen)
[321]580       {
[599]581         if (mode.isEmpty() || mode.getValue() == mode_attr::write)
582          this->data_out->closeFile();
583         else
584          this->data_in->closeFile();
[321]585       }
[651]586      if (fileComm != MPI_COMM_NULL) MPI_Comm_free(&fileComm);
[286]587   }
[219]588   //----------------------------------------------------------------
589
[775]590   void CFile::readAttributesOfEnabledFieldsInReadMode()
591   {
592     if (enabledFields.empty()) return;
593
594     // Just check file and try to open it
595     CContext* context = CContext::getCurrent();
596     CContextClient* client=context->client;
[1054]597//     CContextClient* client = (0 != context->clientPrimServer.size()) ? context->clientPrimServer[0] : context->client;
[775]598
[805]599     // It would probably be better to call initFile() somehow
[775]600     MPI_Comm_dup(client->intraComm, &fileComm);
[805]601     if (time_counter_name.isEmpty()) time_counter_name = "time_counter";
602
[775]603     checkFile();
[805]604
[775]605     for (int idx = 0; idx < enabledFields.size(); ++idx)
606     {
607        // First of all, find out which domain and axis associated with this field
608        enabledFields[idx]->solveGridReference();
609
610        // Read attributes of domain and axis from this file
611        this->data_in->readFieldAttributesMetaData(enabledFields[idx]);
612
613        // Now complete domain and axis associated with this field
614        enabledFields[idx]->solveGenerateGrid();
615
616        // Read necessary value from file
617        this->data_in->readFieldAttributesValues(enabledFields[idx]);
618
619        // Fill attributes for base reference
620        enabledFields[idx]->solveGridDomainAxisBaseRef();
621     }
622
623     // Now everything is ok, close it
624     close();
625   }
626
627
[509]628   /*!
629   \brief Parse xml file and write information into file object
630   \param [in] node xmld node corresponding in xml file
631   */
[219]632   void CFile::parse(xml::CXMLNode & node)
633   {
634      SuperClass::parse(node);
[509]635
[472]636      if (node.goToChildElement())
637      {
638        do
639        {
640           if (node.getElementName()=="field" || node.getElementName()=="field_group") this->getVirtualFieldGroup()->parseChild(node);
641           else if (node.getElementName()=="variable" || node.getElementName()=="variable_group") this->getVirtualVariableGroup()->parseChild(node);
[651]642        } while (node.goToNextElement());
[472]643        node.goToParentElement();
[219]644      }
[472]645
[219]646   }
647   //----------------------------------------------------------------
648
[509]649   /*!
650   \brief Represent a file in form of string with all its info
651   \return String
652   */
[219]653   StdString CFile::toString(void) const
654   {
655      StdOStringStream oss;
656
657      oss << "<" << CFile::GetName() << " ";
658      if (this->hasId())
659         oss << " id=\"" << this->getId() << "\" ";
660      oss << SuperClassAttribute::toString() << ">" << std::endl;
[347]661      if (this->getVirtualFieldGroup() != NULL)
[219]662         oss << *this->getVirtualFieldGroup() << std::endl;
663      oss << "</" << CFile::GetName() << " >";
664      return (oss.str());
665   }
666
667   //----------------------------------------------------------------
[509]668
669   /*!
670   \brief Find all inheritace among objects in a file.
671   \param [in] apply (true) write attributes of parent into ones of child if they are empty
672                     (false) write attributes of parent into a new container of child
673   \param [in] parent
674   */
[445]675   void CFile::solveDescInheritance(bool apply, const CAttributeMap * const parent)
[219]676   {
[445]677      SuperClassAttribute::setAttributes(parent,apply);
[509]678      this->getVirtualFieldGroup()->solveDescInheritance(apply, NULL);
[472]679      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
[219]680   }
681
682   //----------------------------------------------------------------
683
[509]684   /*!
685   \brief Resolve all reference of active fields.
686      In order to know exactly which data each active field has, a search for all its
687   reference to find its parents or/and its base reference object must be done. Moreover
688   during this search, there are some information that can only be sent to server AFTER
689   all information of active fields are created on server side, e.g: checking mask or index
690   \param [in] sendToServer: Send all info to server (true) or only a part of it (false)
691   */
[823]692   void CFile::solveOnlyRefOfEnabledFields(bool sendToServer)
693   {
694     int size = this->enabledFields.size();
695     for (int i = 0; i < size; ++i)
696     {
[1129]697       this->enabledFields[i]->solveOnlyReferenceEnabledField(sendToServer);
698       // this->enabledFields[i]->solveAllEnabledFields();
[823]699//       this->enabledFields[i]->buildGridTransformationGraph();
700     }
701   }
702
[1025]703   void CFile::checkGridOfEnabledFields()
704   { 
705     int size = this->enabledFields.size();
706     for (int i = 0; i < size; ++i)
707     {
708       this->enabledFields[i]->checkGridOfEnabledFields();
709     }
710   }
711
712   void CFile::sendGridOfEnabledFields()
713   { 
714     int size = this->enabledFields.size();
715     for (int i = 0; i < size; ++i)
716     {
717       this->enabledFields[i]->sendGridOfEnabledFields();
718     }
719   }
720
[823]721   void CFile::generateNewTransformationGridDest()
722   {
723     int size = this->enabledFields.size();
724     for (int i = 0; i < size; ++i)
725     {
726       this->enabledFields[i]->generateNewTransformationGridDest();
727     }
728   }
729
730   /*!
731   \brief Resolve all reference of active fields.
732      In order to know exactly which data each active field has, a search for all its
733   reference to find its parents or/and its base reference object must be done. Moreover
734   during this search, there are some information that can only be sent to server AFTER
735   all information of active fields are created on server side, e.g: checking mask or index
736   \param [in] sendToServer: Send all info to server (true) or only a part of it (false)
737   */
[1129]738   void CFile::solveAllRefOfEnabledFieldsAndTransform(bool sendToServer)
[459]739   {
[509]740     int size = this->enabledFields.size();
741     for (int i = 0; i < size; ++i)
742     {
[1129]743       // this->enabledFields[i]->solveAllReferenceEnabledField(sendToServer);
744      this->enabledFields[i]->solveAllEnabledFieldsAndTransform();
[509]745     }
[459]746   }
[509]747
748   /*!
[640]749    * Constructs the filter graph for each active field.
750    *
751    * \param gc the garbage collector to use when building the filter graph
752    */
753   void CFile::buildFilterGraphOfEnabledFields(CGarbageCollector& gc)
754   {
755     int size = this->enabledFields.size();
756     for (int i = 0; i < size; ++i)
757     {
758       this->enabledFields[i]->buildFilterGraph(gc, true);
759     }
760   }
761
762   /*!
[598]763     Prefetching the data for enabled fields read from file.
764   */
765   void CFile::prefetchEnabledReadModeFields(void)
766   {
767     if (mode.isEmpty() || mode.getValue() != mode_attr::read)
768       return;
769
770     int size = this->enabledFields.size();
771     for (int i = 0; i < size; ++i)
[1021]772       this->enabledFields[i]->sendReadDataRequest(CContext::getCurrent()->getCalendar()->getCurrentDate());
[598]773   }
774
775   /*!
776     Prefetching the data for enabled fields read from file whose data is out-of-date.
777   */
778   void CFile::prefetchEnabledReadModeFieldsIfNeeded(void)
779   {
780     if (mode.isEmpty() || mode.getValue() != mode_attr::read)
781       return;
782
783     int size = this->enabledFields.size();
784     for (int i = 0; i < size; ++i)
785       this->enabledFields[i]->sendReadDataRequestIfNeeded();
786   }
787
[445]788   void CFile::solveFieldRefInheritance(bool apply)
[219]789   {
[878]790      // Rsolution des hritages par rfrence de chacun des champs contenus dans le fichier.
[347]791      std::vector<CField*> allF = this->getAllFields();
[219]792      for (unsigned int i = 0; i < allF.size(); i++)
[445]793         allF[i]->solveRefInheritance(apply);
[219]794   }
795
796   //----------------------------------------------------------------
797
[509]798   /*!
799   \brief Add a field into file.
800      A field is added into file and it will be written out if the file is enabled and
801   level of this field is smaller than level_output. A new field won't be created if one
802   with id has already existed
803   \param [in] id String identity of new field
804   \return Pointer to added (or already existed) field
805   */
[347]806   CField* CFile::addField(const string& id)
[300]807   {
[651]808     return vFieldGroup->createChild(id);
[300]809   }
[219]810
[509]811   /*!
812   \brief Add a field group into file.
813      A field group is added into file and it will play a role as parents for fields.
814   A new field group won't be created if one with id has already existed
815   \param [in] id String identity of new field group
816   \return Pointer to added (or already existed) field group
817   */
[347]818   CFieldGroup* CFile::addFieldGroup(const string& id)
[300]819   {
[651]820     return vFieldGroup->createChildGroup(id);
[300]821   }
[509]822
823   /*!
824   \brief Add a variable into file.
825      A variable is added into file and if one with id has already existed, pointer to
826   it will be returned.
827      Variable as long as attributes are information container of file.
828   However, whereas attributes are "fixed" information, variables provides a more flexible way to user
829   to fill in (extra) information for a file.
830   \param [in] id String identity of new variable
831   \return Pointer to added (or already existed) variable
832   */
[472]833   CVariable* CFile::addVariable(const string& id)
834   {
[651]835     return vVariableGroup->createChild(id);
[472]836   }
837
[509]838   /*!
839   \brief Add a variable group into file.
840      A variable group is added into file and it will play a role as parents for variables.
841   A new variable group won't be created if one with id has already existed
842   \param [in] id String identity of new variable group
843   \return Pointer to added (or already existed) variable group
844   */
[472]845   CVariableGroup* CFile::addVariableGroup(const string& id)
846   {
[651]847     return vVariableGroup->createChildGroup(id);
[472]848   }
[509]849
[1021]850   void CFile::setContextClient(CContextClient* newContextClient)
851   {
852     client = newContextClient;
853   }
854
855   CContextClient* CFile::getContextClient()
856   {
857     return client;
858   }
859
[1071]860
[509]861   /*!
862   \brief Send a message to create a field on server side
863   \param[in] id String identity of field that will be created on server
864   */
[300]865   void CFile::sendAddField(const string& id)
866   {
[987]867      sendAddItem(id, EVENT_ID_ADD_FIELD);
[300]868   }
[509]869
[1021]870   void CFile::sendAddField(const string& id, CContextClient* client)
[1009]871   {
[1021]872      sendAddItem(id, EVENT_ID_ADD_FIELD, client);
[1009]873   }
874
[509]875   /*!
876   \brief Send a message to create a field group on server side
877   \param[in] id String identity of field group that will be created on server
878   */
[300]879   void CFile::sendAddFieldGroup(const string& id)
880   {
[987]881      sendAddItem(id, (int)EVENT_ID_ADD_FIELD_GROUP);
[300]882   }
[509]883
884   /*!
885   \brief Receive a message annoucing the creation of a field on server side
886   \param[in] event Received event
887   */
[300]888   void CFile::recvAddField(CEventServer& event)
889   {
[509]890
[651]891      CBufferIn* buffer = event.subEvents.begin()->buffer;
[300]892      string id;
[651]893      *buffer>>id;
894      get(id)->recvAddField(*buffer);
[300]895   }
[509]896
897   /*!
898   \brief Receive a message annoucing the creation of a field on server side
899   \param[in] buffer Buffer containing message
900   */
[300]901   void CFile::recvAddField(CBufferIn& buffer)
902   {
[651]903      string id;
904      buffer>>id;
905      addField(id);
[300]906   }
907
[509]908   /*!
909   \brief Receive a message annoucing the creation of a field group on server side
910   \param[in] event Received event
911   */
[300]912   void CFile::recvAddFieldGroup(CEventServer& event)
913   {
[509]914
[651]915      CBufferIn* buffer = event.subEvents.begin()->buffer;
[300]916      string id;
[651]917      *buffer>>id;
918      get(id)->recvAddFieldGroup(*buffer);
[300]919   }
[509]920
921   /*!
922   \brief Receive a message annoucing the creation of a field group on server side
923   \param[in] buffer Buffer containing message
924   */
[300]925   void CFile::recvAddFieldGroup(CBufferIn& buffer)
926   {
[651]927      string id;
928      buffer>>id;
929      addFieldGroup(id);
[300]930   }
931
[509]932   /*!
933   \brief Send messages to duplicate all variables on server side
934      Because each variable has also its attributes. So first thing to do is replicate
935   all these attributes on server side. Because variable can have a value, the second thing
936   is to duplicate this value on server, too.
937   */
938   void CFile::sendAddAllVariables()
939   {
[957]940     std::vector<CVariable*> allVar = getAllVariables();
941     std::vector<CVariable*>::const_iterator it = allVar.begin();
942     std::vector<CVariable*>::const_iterator itE = allVar.end();
943
944     for (; it != itE; ++it)
[509]945     {
[957]946       this->sendAddVariable((*it)->getId());
947       (*it)->sendAllAttributesToServer();
948       (*it)->sendValue();
[509]949     }
950   }
[472]951
[1021]952   void CFile::sendAddAllVariables(CContextClient* client)
[1009]953   {
954     std::vector<CVariable*> allVar = getAllVariables();
955     std::vector<CVariable*>::const_iterator it = allVar.begin();
956     std::vector<CVariable*>::const_iterator itE = allVar.end();
957
958     for (; it != itE; ++it)
959     {
[1021]960       this->sendAddVariable((*it)->getId(), client);
961       (*it)->sendAllAttributesToServer(client);
962       (*it)->sendValue(client);
[1009]963     }
964   }
965
[509]966   /*!
[1009]967   \brief Send a message to create a variable group on server side
968   \param[in] id String identity of variable group that will be created on server
969   */
970   void CFile::sendAddVariableGroup(const string& id)
971   {
972      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE_GROUP);
973   }
974
975   /*!
[1132]976   \brief Send a message to create a variable group on server side
977   \param[in] id String identity of variable group that will be created on server
978   \param [in] client client to which we will send this adding action
979   */
980   void CFile::sendAddVariableGroup(const string& id, CContextClient* client)
981   {
982      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE_GROUP, client);
983   }
984
985   /*!
[509]986   \brief Send a message to create a variable on server side
987      A variable always belongs to a variable group
988   \param[in] id String identity of variable that will be created on server
989   */
[472]990   void CFile::sendAddVariable(const string& id)
991   {
[987]992      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE);
[472]993   }
[509]994
[1132]995   /*
996     Send message to add a variable into a file within a certain client
997     \param [in] id String identity of a variable
998     \param [in] client client to which we will send this adding action
999   */
[1021]1000   void CFile::sendAddVariable(const string& id, CContextClient* client)
[472]1001   {
[1130]1002      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE, client);
[472]1003   }
[509]1004
1005   /*!
1006   \brief Receive a message annoucing the creation of a variable on server side
1007   \param[in] event Received event
1008   */
[472]1009   void CFile::recvAddVariable(CEventServer& event)
1010   {
[509]1011
[651]1012      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1013      string id;
[651]1014      *buffer>>id;
1015      get(id)->recvAddVariable(*buffer);
[472]1016   }
[509]1017
1018   /*!
1019   \brief Receive a message annoucing the creation of a variable on server side
1020   \param[in] buffer Buffer containing message
1021   */
[472]1022   void CFile::recvAddVariable(CBufferIn& buffer)
1023   {
[651]1024      string id;
1025      buffer>>id;
1026      addVariable(id);
[472]1027   }
1028
[509]1029   /*!
1030   \brief Receive a message annoucing the creation of a variable group on server side
1031   \param[in] event Received event
1032   */
[472]1033   void CFile::recvAddVariableGroup(CEventServer& event)
1034   {
[509]1035
[651]1036      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1037      string id;
[651]1038      *buffer>>id;
1039      get(id)->recvAddVariableGroup(*buffer);
[472]1040   }
[509]1041
1042   /*!
1043   \brief Receive a message annoucing the creation of a variable group on server side
1044   \param[in] buffer Buffer containing message
1045   */
[472]1046   void CFile::recvAddVariableGroup(CBufferIn& buffer)
1047   {
[651]1048      string id;
1049      buffer>>id;
1050      addVariableGroup(id);
[472]1051   }
1052
[509]1053   /*!
1054     \brief Sending all active (enabled) fields from client to server.
1055   Each field is identified uniquely by its string identity. Not only should we
1056   send the id to server but also we need to send ids of reference domain and reference axis.
1057   With these two id, it's easier to make reference to grid where all data should be written.
1058   Remark: This function must be called AFTER all active (enabled) files have been created on the server side
[1021]1059   */   void CFile::sendEnabledFields(CContextClient* client)
[1009]1060   {
1061     size_t size = this->enabledFields.size();
1062     for (size_t i = 0; i < size; ++i)
1063     {
1064       CField* field = this->enabledFields[i];
[1021]1065       this->sendAddField(field->getId(), client);
1066       field->sendAllAttributesToServer(client);
1067       field->sendAddAllVariables(client);
[1009]1068     }
1069   }
1070
[1021]1071
[509]1072   /*!
1073   \brief Dispatch event received from client
1074      Whenever a message is received in buffer of server, it will be processed depending on
1075   its event type. A new event type should be added in the switch list to make sure
1076   it processed on server side.
1077   \param [in] event: Received message
1078   */
[300]1079   bool CFile::dispatchEvent(CEventServer& event)
1080   {
[651]1081      if (SuperClass::dispatchEvent(event)) return true;
[300]1082      else
1083      {
1084        switch(event.type)
1085        {
1086           case EVENT_ID_ADD_FIELD :
[651]1087             recvAddField(event);
1088             return true;
1089             break;
[509]1090
[300]1091           case EVENT_ID_ADD_FIELD_GROUP :
[651]1092             recvAddFieldGroup(event);
1093             return true;
1094             break;
[509]1095
[472]1096            case EVENT_ID_ADD_VARIABLE :
[651]1097             recvAddVariable(event);
1098             return true;
1099             break;
[509]1100
[472]1101           case EVENT_ID_ADD_VARIABLE_GROUP :
[651]1102             recvAddVariableGroup(event);
1103             return true;
1104             break;
[300]1105           default :
[651]1106              ERROR("bool CFile::dispatchEvent(CEventServer& event)", << "Unknown Event");
1107           return false;
[300]1108        }
1109      }
1110   }
[509]1111
1112
1113
1114
[219]1115   ///---------------------------------------------------------------
1116
[335]1117} // namespace xios
Note: See TracBrowser for help on using the repository browser.