source: XIOS/trunk/src/node/field.cpp @ 1387

Last change on this file since 1387 was 1387, checked in by oabramkina, 6 years ago

Fixing a bug in case of output_freq defined in months to avoid adding a month to the last day of a month.

  • 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: 49.5 KB
RevLine 
[219]1#include "field.hpp"
2
[352]3#include "attribute_template.hpp"
4#include "object_template.hpp"
5#include "group_template.hpp"
[219]6
7#include "node_type.hpp"
8#include "calendar_util.hpp"
[352]9#include "message.hpp"
[591]10#include "xios_spl.hpp"
[352]11#include "type.hpp"
[638]12#include "timer.hpp"
[352]13#include "context_client.hpp"
[586]14#include "context_server.hpp"
[459]15#include <set>
[640]16#include "garbage_collector.hpp"
17#include "source_filter.hpp"
18#include "store_filter.hpp"
19#include "file_writer_filter.hpp"
[641]20#include "pass_through_filter.hpp"
[642]21#include "filter_expr_node.hpp"
22#include "lex_parser.hpp"
[643]23#include "temporal_filter.hpp"
[644]24#include "spatial_transform_filter.hpp"
[219]25
[335]26namespace xios{
[509]27
[219]28   /// ////////////////////// Définitions ////////////////////// ///
29
30   CField::CField(void)
31      : CObjectTemplate<CField>(), CFieldAttributes()
32      , grid(), file()
[707]33      , written(false)
[645]34      , nstep(0), nstepMax(0)
35      , hasOutputFile(false)
[887]36      , domAxisScalarIds_(vector<StdString>(3,"")), areAllReferenceSolved(false), isReferenceSolved(false)
[676]37      , useCompressedOutput(false)
[989]38      , hasTimeInstant(false)
39      , hasTimeCentered(false)
[1318]40      , wasDataRequestedFromServer(false)
[1013]41      , wasDataAlreadyReceivedFromServer(false)
[1358]42      , mustAutoTrigger(false)
[1017]43      , isEOF(false)
[957]44   { setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group")); }
[219]45
[562]46   CField::CField(const StdString& id)
[219]47      : CObjectTemplate<CField>(id), CFieldAttributes()
48      , grid(), file()
[707]49      , written(false)
[645]50      , nstep(0), nstepMax(0)
51      , hasOutputFile(false)
[887]52      , domAxisScalarIds_(vector<StdString>(3,"")), areAllReferenceSolved(false), isReferenceSolved(false)
[676]53      , useCompressedOutput(false)
[989]54      , hasTimeInstant(false)
55      , hasTimeCentered(false)
[1318]56      , wasDataRequestedFromServer(false)
[1013]57      , wasDataAlreadyReceivedFromServer(false)
[1358]58      , mustAutoTrigger(false)
[1017]59      , isEOF(false)
[957]60   { setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group")); }
[219]61
62   CField::~CField(void)
[645]63   {}
[509]64
[472]65  //----------------------------------------------------------------
66
67   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
[509]68   {
69      this->vVariableGroup = newVVariableGroup;
[472]70   }
[509]71
[472]72   CVariableGroup* CField::getVirtualVariableGroup(void) const
73   {
[562]74      return this->vVariableGroup;
[472]75   }
76
77   std::vector<CVariable*> CField::getAllVariables(void) const
78   {
[562]79      return this->vVariableGroup->getAllChildren();
[472]80   }
[509]81
[562]82   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
[472]83   {
[562]84      SuperClassAttribute::setAttributes(parent, apply);
[472]85      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
86   }
[219]87
[645]88  //----------------------------------------------------------------
[509]89
[598]90  bool CField::dispatchEvent(CEventServer& event)
[300]91  {
[562]92    if (SuperClass::dispatchEvent(event)) return true;
[300]93    else
94    {
95      switch(event.type)
96      {
97        case EVENT_ID_UPDATE_DATA :
[562]98          recvUpdateData(event);
99          return true;
100          break;
[472]101
[598]102        case EVENT_ID_READ_DATA :
103          recvReadDataRequest(event);
104          return true;
105          break;
[509]106
[598]107        case EVENT_ID_READ_DATA_READY :
108          recvReadDataReady(event);
109          return true;
110          break;
[509]111
[598]112        case EVENT_ID_ADD_VARIABLE :
113          recvAddVariable(event);
114          return true;
115          break;
116
117        case EVENT_ID_ADD_VARIABLE_GROUP :
118          recvAddVariableGroup(event);
119          return true;
120          break;
121
[300]122        default :
[562]123          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
124          return false;
[300]125      }
126    }
127  }
[509]128
[638]129  void CField::sendUpdateData(const CArray<double,1>& data)
130  {
[1135]131    CTimer::get("Field : send data").resume();
[638]132
133    CContext* context = CContext::getCurrent();
134    CContextClient* client = context->client;
135
136    CEventClient event(getType(), EVENT_ID_UPDATE_DATA);
137
[650]138    map<int, CArray<int,1> >::iterator it;
[638]139    list<CMessage> list_msg;
140    list<CArray<double,1> > list_data;
141
142    if (!grid->doGridHaveDataDistributed())
143    {
[967]144       if (client->isServerLeader())
[638]145       {
146          for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
147          {
[650]148            int rank = it->first;
149            CArray<int,1>& index = it->second;
[638]150
151            list_msg.push_back(CMessage());
152            list_data.push_back(CArray<double,1>(index.numElements()));
153
154            CArray<double,1>& data_tmp = list_data.back();
155            for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
156
157            list_msg.back() << getId() << data_tmp;
158            event.push(rank, 1, list_msg.back());
159          }
160          client->sendEvent(event);
[967]161       } 
162       else client->sendEvent(event);
[638]163    }
164    else
165    {
166      for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
167      {
[650]168        int rank = it->first;
169        CArray<int,1>& index = it->second;
[638]170
171        list_msg.push_back(CMessage());
172        list_data.push_back(CArray<double,1>(index.numElements()));
173
174        CArray<double,1>& data_tmp = list_data.back();
175        for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
176
177        list_msg.back() << getId() << data_tmp;
178        event.push(rank, grid->nbSenders[rank], list_msg.back());
179      }
180      client->sendEvent(event);
181    }
[687]182
[1135]183    CTimer::get("Field : send data").suspend();
[638]184  }
185
[300]186  void CField::recvUpdateData(CEventServer& event)
187  {
[562]188    vector<int> ranks;
189    vector<CBufferIn*> buffers;
[509]190
[562]191    list<CEventServer::SSubEvent>::iterator it;
192    string fieldId;
[1135]193    CTimer::get("Field : recv data").resume();
[562]194    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
[300]195    {
[562]196      int rank = it->rank;
197      CBufferIn* buffer = it->buffer;
198      *buffer >> fieldId;
199      ranks.push_back(rank);
200      buffers.push_back(buffer);
[300]201    }
[562]202    get(fieldId)->recvUpdateData(ranks,buffers);
[1135]203    CTimer::get("Field : recv data").suspend();
[300]204  }
[509]205
[300]206  void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
207  {
208    if (data_srv.empty())
209    {
[650]210      for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
[300]211      {
[562]212        int rank = it->first;
[651]213        data_srv.insert(std::make_pair(rank, CArray<double,1>(it->second.numElements())));
214        foperation_srv.insert(pair<int,boost::shared_ptr<func::CFunctor> >(rank,boost::shared_ptr<func::CFunctor>(new func::CInstant(data_srv[rank]))));
[300]215      }
216    }
217
[562]218    CContext* context = CContext::getCurrent();
219    const CDate& currDate = context->getCalendar()->getCurrentDate();
[1387]220    const CDate opeDate      = (last_operation_srv + context->getCalendar()->getTimeStep()) +freq_op + freq_operation_srv - freq_op - context->getCalendar()->getTimeStep();
[651]221    const CDate writeDate    = last_Write_srv     + freq_write_srv;
[300]222
223    if (opeDate <= currDate)
224    {
[562]225      for (int n = 0; n < ranks.size(); n++)
[300]226      {
[562]227        CArray<double,1> data_tmp;
228        *buffers[n] >> data_tmp;
229        (*foperation_srv[ranks[n]])(data_tmp);
[300]230      }
[651]231      last_operation_srv = currDate;
[300]232    }
[509]233
[300]234    if (writeDate < (currDate + freq_operation_srv))
235    {
[562]236      for (int n = 0; n < ranks.size(); n++)
[300]237      {
238        this->foperation_srv[ranks[n]]->final();
239      }
[509]240
[651]241      last_Write_srv = writeDate;
[562]242      writeField();
[651]243      lastlast_Write_srv = last_Write_srv;
[300]244    }
245  }
[509]246
[300]247  void CField::writeField(void)
248  {
[562]249    if (!getRelFile()->allDomainEmpty)
[586]250    {
[599]251      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
[379]252      {
253        getRelFile()->checkFile();
254        this->incrementNStep();
255        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
256      }
[586]257    }
[300]258  }
[562]259
[1017]260  bool CField::sendReadDataRequest(const CDate& tsDataRequested)
[598]261  {
262    CContext* context = CContext::getCurrent();
263    CContextClient* client = context->client;
264
[1013]265    lastDataRequestedFromServer = tsDataRequested;
[708]266
[1318]267    // No need to send the request if we are sure that we are already at EOF
268    if (!isEOF || context->getCalendar()->getCurrentDate() <= dateEOF)
[598]269    {
[1017]270      CEventClient event(getType(), EVENT_ID_READ_DATA);
271      if (client->isServerLeader())
272      {
273        CMessage msg;
274        msg << getId();
275        const std::list<int>& ranks = client->getRanksServerLeader();
276        for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
277          event.push(*itRank, 1, msg);
278        client->sendEvent(event);
279      }
280      else client->sendEvent(event);
[598]281    }
[1017]282    else
283      serverSourceFilter->signalEndOfStream(tsDataRequested);
284
[1318]285    wasDataRequestedFromServer = true;
286
[1017]287    return !isEOF;
[598]288  }
289
290  /*!
291  Send request new data read from file if need be, that is the current data is out-of-date.
292  \return true if and only if some data was requested
293  */
294  bool CField::sendReadDataRequestIfNeeded(void)
295  {
296    const CDate& currentDate = CContext::getCurrent()->getCalendar()->getCurrentDate();
297
[1013]298    bool dataRequested = false;
[598]299
[1013]300    while (currentDate >= lastDataRequestedFromServer)
[850]301    {
[1013]302      info(20) << "currentDate : " << currentDate << endl ;
303      info(20) << "lastDataRequestedFromServer : " << lastDataRequestedFromServer << endl ;
304      info(20) << "file->output_freq.getValue() : " << file->output_freq.getValue() << endl ;
305      info(20) << "lastDataRequestedFromServer + file->output_freq.getValue() : " << lastDataRequestedFromServer + file->output_freq << endl ;
[873]306
[1017]307      dataRequested |= sendReadDataRequest(lastDataRequestedFromServer + file->output_freq);
[850]308    }
[598]309
[1013]310    return dataRequested;
[598]311  }
312
313  void CField::recvReadDataRequest(CEventServer& event)
314  {
315    CBufferIn* buffer = event.subEvents.begin()->buffer;
316    StdString fieldId;
317    *buffer >> fieldId;
318    get(fieldId)->recvReadDataRequest();
319  }
320
321  void CField::recvReadDataRequest(void)
322  {
323    CContext* context = CContext::getCurrent();
324    CContextClient* client = context->client;
325
326    CEventClient event(getType(), EVENT_ID_READ_DATA_READY);
327    std::list<CMessage> msgs;
328
[599]329    bool hasData = readField();
[598]330
[651]331    map<int, CArray<double,1> >::iterator it;
[988]332    if (!grid->doGridHaveDataDistributed())
[598]333    {
[988]334       if (client->isServerLeader())
335       {
336          if (!data_srv.empty())
337          {
338            it = data_srv.begin();
339            const std::list<int>& ranks = client->getRanksServerLeader();
340            for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
341            {
342              msgs.push_back(CMessage());
343              CMessage& msg = msgs.back();
344              msg << getId();
345              if (hasData)
346                msg << getNStep() - 1 << it->second;
347              else
348                msg << int(-1);
349              event.push(*itRank, 1, msg);
350            }
351          }
352          client->sendEvent(event);
353       } 
354       else 
355       {
356          // if (!data_srv.empty())
357          // {
358          //   it = data_srv.begin();
359          //   const std::list<int>& ranks = client->getRanksServerNotLeader();
360          //   for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
361          //   {
362          //     msgs.push_back(CMessage());
363          //     CMessage& msg = msgs.back();
364          //     msg << getId();
365          //     if (hasData)
366          //       msg << getNStep() - 1 << it->second;
367          //     else
368          //       msg << int(-1);
369          //     event.push(*itRank, 1, msg);
370          //   }
371          // }
372          client->sendEvent(event);
373       }
[598]374    }
[988]375    else
376    {
377      for (it = data_srv.begin(); it != data_srv.end(); it++)
378      {
379        msgs.push_back(CMessage());
380        CMessage& msg = msgs.back();
381        msg << getId();
382        if (hasData)
383          msg << getNStep() - 1 << it->second;
384        else
385          msg << int(-1);
386        event.push(it->first, grid->nbSenders[it->first], msg);
387      }
388      client->sendEvent(event);
389    }
[599]390  }
[598]391
[599]392  bool CField::readField(void)
393  {
394    if (!getRelFile()->allDomainEmpty)
395    {
396      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
397      {
398        if (data_srv.empty())
399        {
[650]400          for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
[651]401            data_srv.insert(std::make_pair(it->first, CArray<double,1>(it->second.numElements())));
[599]402        }
403
404        getRelFile()->checkFile();
405        if (!nstepMax)
406        {
407          nstepMax = getRelFile()->getDataInput()->getFieldNbRecords(CField::get(this));
408        }
[873]409
[850]410        this->incrementNStep();
[599]411
[850]412        if (getNStep() > nstepMax && (getRelFile()->cyclic.isEmpty() || !getRelFile()->cyclic) )
[599]413          return false;
414
415        getRelFile()->getDataInput()->readFieldData(CField::get(this));
416      }
417    }
418
419    return true;
[598]420  }
421
422  void CField::recvReadDataReady(CEventServer& event)
423  {
424    string fieldId;
425    vector<int> ranks;
426    vector<CBufferIn*> buffers;
427
428    list<CEventServer::SSubEvent>::iterator it;
429    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
430    {
431      ranks.push_back(it->rank);
432      CBufferIn* buffer = it->buffer;
433      *buffer >> fieldId;
434      buffers.push_back(buffer);
435    }
436    get(fieldId)->recvReadDataReady(ranks, buffers);
437  }
438
439  void CField::recvReadDataReady(vector<int> ranks, vector<CBufferIn*> buffers)
440  {
441    CContext* context = CContext::getCurrent();
[640]442    std::map<int, CArray<double,1> > data;
[1318]443    const bool wasEOF = isEOF;
[640]444
[598]445    for (int i = 0; i < ranks.size(); i++)
446    {
447      int rank = ranks[i];
[1318]448      int record;
[599]449      *buffers[i] >> record;
[959]450      isEOF = (record == int(-1));
[598]451
[599]452      if (!isEOF)
[640]453        *buffers[i] >> data[rank];
454      else
455        break;
456    }
457
[1013]458    if (wasDataAlreadyReceivedFromServer)
459      lastDataReceivedFromServer = lastDataReceivedFromServer + file->output_freq;
460    else
461    {
462      lastDataReceivedFromServer = context->getCalendar()->getInitDate();
463      wasDataAlreadyReceivedFromServer = true;
464    }
465
[640]466    if (isEOF)
[1318]467    {
468      if (!wasEOF)
469        dateEOF = lastDataReceivedFromServer;
470
[1013]471      serverSourceFilter->signalEndOfStream(lastDataReceivedFromServer);
[1318]472    }
[640]473    else
[1013]474      serverSourceFilter->streamDataFromServer(lastDataReceivedFromServer, data);
[598]475  }
476
[1318]477  void CField::checkForLateDataFromServer(void)
478  {
479    CContext* context = CContext::getCurrent();
480    const CDate& currentDate = context->getCalendar()->getCurrentDate();
481
482    // Check if data previously requested has been received as expected
[1358]483    if (wasDataRequestedFromServer && !isEOF)
[1318]484    {
485      CTimer timer("CField::checkForLateDataFromServer");
486
[1322]487      bool isDataLate;
488      do
[1318]489      {
[1322]490        const CDate nextDataDue = wasDataAlreadyReceivedFromServer ? (lastDataReceivedFromServer + file->output_freq) : context->getCalendar()->getInitDate();
[1358]491        isDataLate = (nextDataDue <= currentDate);
[1318]492
[1322]493        if (isDataLate)
494        {
495          timer.resume();
[1318]496
[1322]497          context->checkBuffersAndListen();
[1318]498
[1322]499          timer.suspend();
500        }
[1318]501      }
[1322]502      while (isDataLate && timer.getCumulatedTime() < CXios::recvFieldTimeout);
[1318]503
504      if (isDataLate)
505        ERROR("void CField::checkForLateDataFromServer(void)",
506              << "Late data at timestep = " << currentDate);
507    }
508  }
509
[1358]510  void CField::checkIfMustAutoTrigger(void)
511  {
512    mustAutoTrigger = serverSourceFilter ? serverSourceFilter->mustAutoTrigger() : false;
513  }
514
515  void CField::autoTriggerIfNeeded(void)
516  {
517    if (mustAutoTrigger)
518      serverSourceFilter->trigger(CContext::getCurrent()->getCalendar()->getCurrentDate());
519  }
520
[219]521   //----------------------------------------------------------------
522
[347]523   void CField::setRelFile(CFile* _file)
[509]524   {
[459]525      this->file = _file;
[562]526      hasOutputFile = true;
[219]527   }
528
529   //----------------------------------------------------------------
530
[562]531   StdString CField::GetName(void)    { return StdString("field"); }
532   StdString CField::GetDefName(void) { return CField::GetName(); }
533   ENodeType CField::GetType(void)    { return eField; }
[219]534
535   //----------------------------------------------------------------
536
[347]537   CGrid* CField::getRelGrid(void) const
[509]538   {
[562]539      return this->grid;
[219]540   }
541
542   //----------------------------------------------------------------
543
[347]544   CFile* CField::getRelFile(void) const
[509]545   {
[562]546      return this->file;
[219]547   }
[509]548
[952]549   int CField::getNStep(void) const
[266]550   {
[562]551      return this->nstep;
[266]552   }
[509]553
[645]554   func::CFunctor::ETimeType CField::getOperationTimeType() const
555   {
556     return operationTimeType;
557   }
558
559   //----------------------------------------------------------------
560
[266]561   void CField::incrementNStep(void)
562   {
563      this->nstep++;
564   }
[509]565
[952]566   void CField::resetNStep(int nstep /*= 0*/)
[321]567   {
[707]568      this->nstep = nstep;
[321]569   }
[219]570
[599]571   void CField::resetNStepMax(void)
572   {
573      this->nstepMax = 0;
574   }
575
[219]576   //----------------------------------------------------------------
577
[1119]578   bool CField::isActive(bool atCurrentTimestep /*= false*/) const
[509]579   {
[1120]580      if (clientSourceFilter)
581        return atCurrentTimestep ? clientSourceFilter->isDataExpected(CContext::getCurrent()->getCalendar()->getCurrentDate()) : true;
582      else if (storeFilter)
583        return true;
584      else if (instantDataFilter)
585        ERROR("bool CField::isActive(bool atCurrentTimestep)",
586              << "Impossible to check if field [ id = " << getId() << " ] is active as it cannot be used to receive nor send data.");
587
588      return false;
[310]589   }
[562]590
[219]591   //----------------------------------------------------------------
[509]592
[707]593   bool CField::wasWritten() const
594   {
595     return written;
596   }
597
598   void CField::setWritten()
599   {
600     written = true;
601   }
602
603   //----------------------------------------------------------------
604
[676]605   bool CField::getUseCompressedOutput() const
606   {
607     return useCompressedOutput;
608   }
609
610   void CField::setUseCompressedOutput()
611   {
612     useCompressedOutput = true;
613   }
614
615   //----------------------------------------------------------------
616
[641]617   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
618   {
619     return instantDataFilter;
620   }
621
622   //----------------------------------------------------------------
623
[823]624   void CField::solveOnlyReferenceEnabledField(bool doSending2Server)
[459]625   {
[509]626     CContext* context = CContext::getCurrent();
[823]627     if (!isReferenceSolved)
[509]628     {
[823]629        isReferenceSolved = true;
[644]630
[510]631        if (context->hasClient)
[509]632        {
633          solveRefInheritance(true);
[823]634          if (hasDirectFieldReference()) getDirectFieldReference()->solveOnlyReferenceEnabledField(false);
[509]635        }
[645]636        else if (context->hasServer)
637          solveServerOperation();
[478]638
[509]639        solveGridReference();
[823]640
641       if (context->hasClient)
642       {
643         solveGenerateGrid();
644         buildGridTransformationGraph();
645       }
[509]646     }
[823]647   }
648
649   /*!
650     Build up graph of grids which plays role of destination and source in grid transformation
651     This function should be called before \func solveGridReference()
652   */
653   void CField::buildGridTransformationGraph()
654   {
655     CContext* context = CContext::getCurrent();
[687]656     if (context->hasClient)
657     {
[823]658       if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
659       {
660         grid->addTransGridSource(getDirectFieldReference()->grid);
661       }
[687]662     }
[823]663   }
[687]664
[823]665   /*!
666     Generate a new grid destination if there are more than one grid source pointing to a same grid destination
667   */
668   void CField::generateNewTransformationGridDest()
669   {
670     CContext* context = CContext::getCurrent();
671     if (context->hasClient)
672     {
673       std::map<CGrid*,std::pair<bool,StdString> >& gridSrcMap = grid->getTransGridSource();
674       if (1 < gridSrcMap.size())
675       {
676         // Search for grid source
677         CGrid* gridSrc = grid;
678         CField* currField = this;
679         std::vector<CField*> hieraField;
[687]680
[823]681         while (currField->hasDirectFieldReference() && (gridSrc == grid))
682         {
683           hieraField.push_back(currField);
684           CField* tmp = currField->getDirectFieldReference();
685           currField = tmp;
686           gridSrc = currField->grid;
687         }
688
689         if (gridSrcMap.end() != gridSrcMap.find(gridSrc))
690         {
691           CGrid* gridTmp;
692           std::pair<bool,StdString> newGridDest = gridSrcMap[gridSrc];
693           if (newGridDest.first)
694           {
695             StdString newIdGridDest = newGridDest.second;
696             if (!CGrid::has(newIdGridDest))
697             {
698                ERROR("CGrid* CGrid::generateNewTransformationGridDest()",
699                  << " Something wrong happened! Grid whose id " << newIdGridDest
700                  << "should exist ");
701             }
702             gridTmp = CGrid::get(newIdGridDest);
703           }
704           else
705           {
706             StdString newIdGridDest = CGrid::generateId(gridSrc, grid);
707             gridTmp = CGrid::cloneGrid(newIdGridDest, grid);
708
709             (gridSrcMap[gridSrc]).first = true;
710             (gridSrcMap[gridSrc]).second = newIdGridDest;
711           }
712
713           // Update all descendants
714           for (std::vector<CField*>::iterator it = hieraField.begin(); it != hieraField.end(); ++it)
715           {
716             (*it)->grid = gridTmp;
717             (*it)->updateRef((*it)->grid);
718           }
719         }
720       }
721     }
722   }
723
724   void CField::updateRef(CGrid* grid)
725   {
726     if (!grid_ref.isEmpty()) grid_ref.setValue(grid->getId());
727     else
728     {
729       std::vector<CAxis*> axisTmp = grid->getAxis();
730       std::vector<CDomain*> domainTmp = grid->getDomains();
731       if ((1<axisTmp.size()) || (1<domainTmp.size()))
732         ERROR("void CField::updateRef(CGrid* grid)",
733           << "More than one domain or axis is available for domain_ref/axis_ref of field " << this->getId());
734
735       if ((!domain_ref.isEmpty()) && (domainTmp.empty()))
736         ERROR("void CField::updateRef(CGrid* grid)",
737           << "Incoherent between available domain and domain_ref of field " << this->getId());
738       if ((!axis_ref.isEmpty()) && (axisTmp.empty()))
739         ERROR("void CField::updateRef(CGrid* grid)",
740           << "Incoherent between available axis and axis_ref of field " << this->getId());
741
742       if (!domain_ref.isEmpty()) domain_ref.setValue(domainTmp[0]->getId());
743       if (!axis_ref.isEmpty()) axis_ref.setValue(axisTmp[0]->getId());
744     }
745   }
746
747   void CField::solveAllReferenceEnabledField(bool doSending2Server)
748   {
749     CContext* context = CContext::getCurrent();
750     solveOnlyReferenceEnabledField(doSending2Server);
751
752     if (!areAllReferenceSolved)
753     {
754        areAllReferenceSolved = true;
755
756        if (context->hasClient)
757        {
758          solveRefInheritance(true);
759          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
760        }
761        else if (context->hasServer)
762          solveServerOperation();
763
764        solveGridReference();
765     }
766
767     solveGridDomainAxisRef(doSending2Server);
768
[619]769     if (context->hasClient)
770     {
771       solveTransformedGrid();
772     }
[687]773
[823]774     solveCheckMaskIndex(doSending2Server);
[509]775   }
776
[731]777   std::map<int, StdSize> CField::getGridAttributesBufferSize()
[509]778   {
[731]779     return grid->getAttributesBufferSize();
[509]780   }
781
[731]782   std::map<int, StdSize> CField::getGridDataBufferSize()
783   {
784     return grid->getDataBufferSize(getId());
785   }
786
[219]787   //----------------------------------------------------------------
788
[645]789   void CField::solveServerOperation(void)
[219]790   {
[640]791      CContext* context = CContext::getCurrent();
[509]792
[640]793      if (!context->hasServer || !hasOutputFile) return;
794
[645]795      if (freq_op.isEmpty())
796        freq_op.setValue(TimeStep);
[509]797
[538]798      if (freq_offset.isEmpty())
799        freq_offset.setValue(NoneDu);
[219]800
[645]801      freq_operation_srv = file->output_freq.getValue();
802      freq_write_srv     = file->output_freq.getValue();
[509]803
[651]804      lastlast_Write_srv = context->getCalendar()->getInitDate();
805      last_Write_srv     = context->getCalendar()->getInitDate();
806      last_operation_srv = context->getCalendar()->getInitDate();
[509]807
[645]808      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
[651]809      last_operation_srv     = last_operation_srv - toffset;
[509]810
[645]811      if (operation.isEmpty())
812        ERROR("void CField::solveServerOperation(void)",
813              << "An operation must be defined for field \"" << getId() << "\".");
[509]814
[645]815      boost::shared_ptr<func::CFunctor> functor;
816      CArray<double, 1> dummyData;
[598]817
[562]818#define DECLARE_FUNCTOR(MType, mtype) \
[645]819      if (operation.getValue().compare(#mtype) == 0) \
[470]820      { \
[645]821        functor.reset(new func::C##MType(dummyData)); \
822      }
[509]823
[219]824#include "functor_type.conf"
[509]825
[645]826      if (!functor)
827        ERROR("void CField::solveServerOperation(void)",
828              << "\"" << operation << "\" is not a valid operation.");
829
830      operationTimeType = functor->timeType();
[219]831   }
[509]832
[219]833   //----------------------------------------------------------------
[640]834
835   /*!
836    * Constructs the graph filter for the field, enabling or not the data output.
837    * This method should not be called more than once with enableOutput equal to true.
838    *
839    * \param gc the garbage collector to use when building the filter graph
840    * \param enableOutput must be true when the field data is to be
841    *                     read by the client or/and written to a file
842    */
843   void CField::buildFilterGraph(CGarbageCollector& gc, bool enableOutput)
844   {
[641]845     if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
[1000]846
[1186]847     const bool detectMissingValues = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
848     const double defaultValue  = detectMissingValues ? default_value : (!default_value.isEmpty() ? default_value : 0.0);
849
[640]850     // Start by building a filter which can provide the field's instant data
851     if (!instantDataFilter)
852     {
[642]853       // Check if we have an expression to parse
[1000]854       if (hasExpression())
[642]855       {
[1000]856         boost::scoped_ptr<IFilterExprNode> expr(parseExpr(getExpression() + '\0'));
857         boost::shared_ptr<COutputPin> filter = expr->reduce(gc, *this);
858
859         // Check if a spatial transformation is needed
860         if (!field_ref.isEmpty())
[998]861         {
[1000]862           CGrid* gridRef = CField::get(field_ref)->grid;
863
864           if (grid && grid != gridRef && grid->hasTransform())
865           {
[1186]866             std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters = CSpatialTransformFilter::buildFilterGraph(gc, gridRef, grid, detectMissingValues, defaultValue);
[1000]867
868             filter->connectOutput(filters.first, 0);
869             filter = filters.second;
870           }
[998]871         }
[1000]872
873         instantDataFilter = filter;
874       }
875       // Check if we have a reference on another field
876       else if (!field_ref.isEmpty())
877         instantDataFilter = getFieldReference(gc);
[640]878       // Check if the data is to be read from a file
[641]879       else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
[1319]880       {
881         checkAttributes();
[1315]882         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid, freq_offset, true,
[1186]883                                                                                                     detectMissingValues, defaultValue));
[1319]884       }
[640]885       else // The data might be passed from the model
[1018]886       {
[1181]887          if (check_if_active.isEmpty()) check_if_active = false;
[1018]888          instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid, NoneDu, false,
[1186]889                                                                                                      detectMissingValues, defaultValue));
890       }
[640]891     }
892
893     // If the field data is to be read by the client or/and written to a file
894     if (enableOutput && !storeFilter && !fileWriterFilter)
895     {
[741]896       if (!read_access.isEmpty() && read_access)
[640]897       {
[1186]898         storeFilter = boost::shared_ptr<CStoreFilter>(new CStoreFilter(gc, CContext::getCurrent(), grid,
899                                                                        detectMissingValues, defaultValue));
[640]900         instantDataFilter->connectOutput(storeFilter, 0);
901       }
902
903       if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
904       {
905         fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
[643]906         getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
[640]907       }
908     }
909   }
910
[642]911   /*!
[737]912    * Returns the filter needed to handle the field reference.
913    * This method should only be called when building the filter graph corresponding to the field.
914    *
915    * \param gc the garbage collector to use
916    * \return the output pin corresponding to the field reference
917    */
[1000]918   boost::shared_ptr<COutputPin> CField::getFieldReference(CGarbageCollector& gc)
[737]919   {
920     if (instantDataFilter || field_ref.isEmpty())
921       ERROR("COutputPin* CField::getFieldReference(CGarbageCollector& gc)",
922             "Impossible to get the field reference for a field which has already been parsed or which does not have a field_ref.");
923
924     CField* fieldRef = CField::get(field_ref);
[1000]925     fieldRef->buildFilterGraph(gc, false);
[737]926
927     std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters;
928     // Check if a spatial transformation is needed
[824]929     if (grid && grid != fieldRef->grid && grid->hasTransform())
[1018]930     {       
931       bool hasMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
932       double defaultValue  = hasMissingValue ? default_value : (!default_value.isEmpty() ? default_value : 0.0);                               
933       filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid, hasMissingValue, defaultValue);
[873]934     }
[737]935     else
936       filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
937
[1000]938     fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
[737]939
940     return filters.second;
941   }
942
943   /*!
944    * Returns the filter needed to handle a self reference in the field's expression.
945    * If the needed filter does not exist, it is created, otherwise it is reused.
[642]946    * This method should only be called when building the filter graph corresponding
947    * to the field's expression.
948    *
949    * \param gc the garbage collector to use
950    * \return the output pin corresponding to a self reference
951    */
952   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
953   {
[1000]954     if (instantDataFilter || !hasExpression())
[642]955       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
956             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
957
[737]958     if (!selfReferenceFilter)
959     {
[1186]960       const bool detectMissingValues = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
961       const double defaultValue  = detectMissingValues ? default_value : (!default_value.isEmpty() ? default_value : 0.0);
962
[741]963       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
964       {
965         if (!serverSourceFilter)
[1319]966         {
967           checkAttributes();
[1315]968           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid, freq_offset, true,
[1186]969                                                                                   detectMissingValues, defaultValue));
[1319]970         }
[741]971
972         selfReferenceFilter = serverSourceFilter;
973       }
974       else if (!field_ref.isEmpty())
[998]975       {
976         CField* fieldRef = CField::get(field_ref);
977         fieldRef->buildFilterGraph(gc, false); 
978         selfReferenceFilter = fieldRef->getInstantDataFilter();
979       }
[737]980       else
981       {
982         if (!clientSourceFilter)
[1018]983         {
[1181]984           if (check_if_active.isEmpty()) check_if_active = false;
[1018]985           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid, NoneDu, false,
[1186]986                                                                                   detectMissingValues, defaultValue));
[1018]987         }
[642]988
[737]989         selfReferenceFilter = clientSourceFilter;
990       }
991     }
992
993     return selfReferenceFilter;
[642]994   }
995
[643]996   /*!
997    * Returns the temporal filter corresponding to the field's temporal operation
998    * for the specified operation frequency. The filter is created if it does not
999    * exist, otherwise it is reused.
1000    *
1001    * \param gc the garbage collector to use
1002    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
1003    * \return the output pin corresponding to the requested temporal filter
1004    */
1005   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
1006   {
1007     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
1008
1009     if (it == temporalDataFilters.end())
1010     {
1011       if (operation.isEmpty())
1012         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
1013               << "An operation must be defined for field \"" << getId() << "\".");
1014
[1315]1015       checkAttributes();
1016
[1186]1017       const bool detectMissingValues = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
[643]1018       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
1019                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
1020                                                                             freq_op, freq_offset, outFreq,
[1186]1021                                                                             detectMissingValues, detectMissingValues ? default_value : 0.0));
[643]1022       instantDataFilter->connectOutput(temporalFilter, 0);
1023
1024       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
1025     }
1026
1027     return it->second;
1028   }
1029
[998]1030  /*!
1031    * Returns the temporal filter corresponding to the field's temporal operation
[1000]1032    * for the specified operation frequency.
[998]1033    *
1034    * \param gc the garbage collector to use
1035    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
1036    * \return the output pin corresponding to the requested temporal filter
1037    */
1038   
1039   boost::shared_ptr<COutputPin> CField::getSelfTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
1040   {
1041     if (instantDataFilter || !hasExpression())
1042       ERROR("COutputPin* CField::getSelfTemporalDataFilter(CGarbageCollector& gc)",
1043             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
1044
1045     if (!selfReferenceFilter) getSelfReference(gc) ;
1046
1047     if (serverSourceFilter || clientSourceFilter)
1048     {
1049       if (operation.isEmpty())
1050         ERROR("void CField::getSelfTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
1051               << "An operation must be defined for field \"" << getId() << "\".");
1052
[1315]1053       checkAttributes();
1054
[1186]1055       const bool detectMissingValues = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
[998]1056       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
1057                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
1058                                                                             freq_op, freq_offset, outFreq,
[1186]1059                                                                             detectMissingValues, detectMissingValues ? default_value : 0.0));
[998]1060       selfReferenceFilter->connectOutput(temporalFilter, 0);
1061       return temporalFilter ;
1062     }
1063     else if (!field_ref.isEmpty())
1064     {
1065       CField* fieldRef = CField::get(field_ref);
1066       fieldRef->buildFilterGraph(gc, false); 
1067       return fieldRef->getTemporalDataFilter(gc, outFreq) ;
1068     }
1069  }
1070
[640]1071   //----------------------------------------------------------------
[369]1072/*
[562]1073   void CField::fromBinary(StdIStream& is)
[219]1074   {
1075      SuperClass::fromBinary(is);
1076#define CLEAR_ATT(name_)\
[369]1077      SuperClassAttribute::operator[](#name_)->reset()
[219]1078
1079         CLEAR_ATT(domain_ref);
1080         CLEAR_ATT(axis_ref);
1081#undef CLEAR_ATT
1082
1083   }
[369]1084*/
[219]1085   //----------------------------------------------------------------
1086
1087   void CField::solveGridReference(void)
1088   {
[887]1089      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty() && scalar_ref.isEmpty())
[742]1090      {
1091        ERROR("CField::solveGridReference(void)",
[770]1092              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
[742]1093      }
[887]1094      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty() || !scalar_ref.isEmpty()))
[219]1095      {
[744]1096        ERROR("CField::solveGridReference(void)",
[887]1097              << "Field '" << getFieldOutputName() << "' has both a grid and a domain/axis/scalar." << std::endl
1098              << "Please define either 'grid_ref' or 'domain_ref'/'axis_ref'/'scalar_ref'.");
[219]1099      }
1100
[744]1101      if (grid_ref.isEmpty())
[219]1102      {
[744]1103        std::vector<CDomain*> vecDom;
1104        std::vector<CAxis*> vecAxis;
[887]1105        std::vector<CScalar*> vecScalar;
[894]1106        std::vector<int> axisDomainOrderTmp;
1107       
[744]1108        if (!domain_ref.isEmpty())
1109        {
[823]1110          StdString tmp = domain_ref.getValue();
[744]1111          if (CDomain::has(domain_ref))
[894]1112          {
[744]1113            vecDom.push_back(CDomain::get(domain_ref));
[894]1114            axisDomainOrderTmp.push_back(2);
1115          }
[744]1116          else
[219]1117            ERROR("CField::solveGridReference(void)",
[744]1118                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
1119        }
[219]1120
[744]1121        if (!axis_ref.isEmpty())
[742]1122        {
[744]1123          if (CAxis::has(axis_ref))
[894]1124          {
[744]1125            vecAxis.push_back(CAxis::get(axis_ref));
[894]1126            axisDomainOrderTmp.push_back(1);
1127          }
[744]1128          else
1129            ERROR("CField::solveGridReference(void)",
1130                  << "Invalid reference to axis '" << axis_ref.getValue() << "'.");
[742]1131        }
[744]1132
[887]1133        if (!scalar_ref.isEmpty())
1134        {
1135          if (CScalar::has(scalar_ref))
[894]1136          {
[887]1137            vecScalar.push_back(CScalar::get(scalar_ref));
[894]1138            axisDomainOrderTmp.push_back(0);
1139          }
[887]1140          else
1141            ERROR("CField::solveGridReference(void)",
1142                  << "Invalid reference to scalar '" << scalar_ref.getValue() << "'.");
1143        }
[894]1144       
1145        CArray<int,1> axisDomainOrder(axisDomainOrderTmp.size());
1146        for (int idx = 0; idx < axisDomainOrderTmp.size(); ++idx)
1147        {
1148          axisDomainOrder(idx) = axisDomainOrderTmp[idx];
1149        }
[887]1150
[745]1151        // Warning: the gridId shouldn't be set as the grid_ref since it could be inherited
[894]1152        StdString gridId = CGrid::generateId(vecDom, vecAxis, vecScalar,axisDomainOrder);
[745]1153        if (CGrid::has(gridId))
1154          this->grid = CGrid::get(gridId);
1155        else
[894]1156          this->grid = CGrid::createGrid(gridId, vecDom, vecAxis, vecScalar,axisDomainOrder);
[219]1157      }
[586]1158      else
1159      {
[744]1160        if (CGrid::has(grid_ref))
1161          this->grid = CGrid::get(grid_ref);
1162        else
1163          ERROR("CField::solveGridReference(void)",
1164                << "Invalid reference to grid '" << grid_ref.getValue() << "'.");
[586]1165      }
[509]1166   }
[459]1167
[509]1168   void CField::solveGridDomainAxisRef(bool checkAtt)
1169   {
1170     grid->solveDomainAxisRef(checkAtt);
[219]1171   }
1172
[509]1173   void CField::solveCheckMaskIndex(bool doSendingIndex)
1174   {
1175     grid->checkMaskIndex(doSendingIndex);
1176   }
[219]1177
[619]1178   void CField::solveTransformedGrid()
1179   {
[746]1180     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[790]1181     {
1182       std::vector<CGrid*> grids;
1183       // Source grid
1184       grids.push_back(getDirectFieldReference()->grid);
1185       // Intermediate grids
1186       if (!grid_path.isEmpty())
1187       {
1188         std::string gridId;
1189         size_t start = 0, end;
1190
1191         do
1192         {
1193           end = grid_path.getValue().find(',', start);
1194           if (end != std::string::npos)
1195           {
1196             gridId = grid_path.getValue().substr(start, end - start);
1197             start = end + 1;
1198           }
1199           else
1200             gridId = grid_path.getValue().substr(start);
1201
1202           if (!CGrid::has(gridId))
1203             ERROR("void CField::solveTransformedGrid()",
1204                   << "Invalid grid_path, the grid '" << gridId << "' does not exist.");
1205
1206           grids.push_back(CGrid::get(gridId));
1207         }
1208         while (end != std::string::npos);
1209       }
1210       // Destination grid
1211       grids.push_back(grid);
1212
1213       for (size_t i = 0, count = grids.size() - 1; i < count; ++i)
1214       {
1215         CGrid *gridSrc  = grids[i];
1216         CGrid *gridDest = grids[i + 1];
1217         if (!gridDest->isTransformed())
1218           gridDest->transformGrid(gridSrc);
1219       }
1220     }
[934]1221     else if (grid && grid->hasTransform() && !grid->isTransformed())
1222     {
[1003]1223       // Temporarily deactivate the self-transformation of grid
[1326]1224       grid->transformGrid(grid);
[934]1225     }
[619]1226   }
1227
[687]1228   void CField::solveGenerateGrid()
1229   {
[746]1230     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[687]1231       grid->completeGrid(getDirectFieldReference()->grid);
[775]1232     else
1233       grid->completeGrid();
[687]1234   }
1235
[775]1236   void CField::solveGridDomainAxisBaseRef()
1237   {
1238     grid->solveDomainAxisRef(false);
1239     grid->solveDomainAxisBaseRef();
1240   }
1241
[219]1242   ///-------------------------------------------------------------------
1243
1244   template <>
[562]1245   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
[219]1246   {
1247      if (this->group_ref.isEmpty()) return;
1248      StdString gref = this->group_ref.getValue();
1249
[346]1250      if (!CFieldGroup::has(gref))
[219]1251         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
1252               << "[ gref = " << gref << "]"
1253               << " invalid group name !");
1254
[347]1255      CFieldGroup* group = CFieldGroup::get(gref);
1256      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
[219]1257
[347]1258      std::vector<CField*> allChildren  = group->getAllChildren();
[562]1259      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
[509]1260
[219]1261      for (; it != end; it++)
1262      {
[347]1263         CField* child = *it;
[562]1264         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
[509]1265
[219]1266      }
1267   }
[509]1268
[464]1269   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
1270   {
[651]1271     map<int, CArray<double,1> >::iterator it;
1272     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
[464]1273   }
[509]1274
[599]1275   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
1276   {
[651]1277     map<int, CArray<double,1> >::iterator it;
1278     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
[599]1279   }
1280
[369]1281   void CField::outputField(CArray<double,3>& fieldOut)
[300]1282   {
[651]1283      map<int, CArray<double,1> >::iterator it;
[562]1284      for (it = data_srv.begin(); it != data_srv.end(); it++)
[551]1285      {
[651]1286        grid->outputField(it->first, it->second, fieldOut.dataFirst());
[551]1287      }
[300]1288   }
[509]1289
[369]1290   void CField::outputField(CArray<double,2>& fieldOut)
[300]1291   {
[651]1292      map<int, CArray<double,1> >::iterator it;
[567]1293      for(it=data_srv.begin();it!=data_srv.end();it++)
1294      {
[676]1295         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[567]1296      }
1297   }
[219]1298
[567]1299   void CField::outputField(CArray<double,1>& fieldOut)
1300   {
[651]1301      map<int, CArray<double,1> >::iterator it;
[567]1302
[562]1303      for (it = data_srv.begin(); it != data_srv.end(); it++)
[300]1304      {
[676]1305         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[300]1306      }
1307   }
[551]1308
[599]1309   void CField::inputField(CArray<double,3>& fieldOut)
1310   {
[651]1311      map<int, CArray<double,1> >::iterator it;
[599]1312      for (it = data_srv.begin(); it != data_srv.end(); it++)
1313      {
[651]1314        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1315      }
1316   }
1317
1318   void CField::inputField(CArray<double,2>& fieldOut)
1319   {
[651]1320      map<int, CArray<double,1> >::iterator it;
[599]1321      for(it = data_srv.begin(); it != data_srv.end(); it++)
1322      {
[651]1323         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1324      }
1325   }
1326
1327   void CField::inputField(CArray<double,1>& fieldOut)
1328   {
[651]1329      map<int, CArray<double,1> >::iterator it;
[599]1330      for (it = data_srv.begin(); it != data_srv.end(); it++)
1331      {
[651]1332         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1333      }
1334   }
1335
[676]1336   void CField::outputCompressedField(CArray<double,1>& fieldOut)
1337   {
1338      map<int, CArray<double,1> >::iterator it;
1339
1340      for (it = data_srv.begin(); it != data_srv.end(); it++)
1341      {
1342         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
1343      }
1344   }
1345
[219]1346   ///-------------------------------------------------------------------
1347
[562]1348   void CField::parse(xml::CXMLNode& node)
[459]1349   {
1350      SuperClass::parse(node);
[562]1351      if (!node.getContent(this->content))
[472]1352      {
[476]1353        if (node.goToChildElement())
[472]1354        {
[476]1355          do
1356          {
[562]1357            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
1358          } while (node.goToNextElement());
[476]1359          node.goToParentElement();
1360        }
[472]1361      }
[459]1362    }
[509]1363
1364   /*!
1365     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
1366   of a field. In some cases, only domain exists but axis doesn't
1367   \return pair of Domain and Axis id
1368   */
[887]1369   const std::vector<StdString>& CField::getRefDomainAxisIds()
[569]1370   {
1371     CGrid* cgPtr = getRelGrid();
1372     if (NULL != cgPtr)
1373     {
1374       std::vector<StdString>::iterator it;
1375       if (!domain_ref.isEmpty())
1376       {
1377         std::vector<StdString> domainList = cgPtr->getDomainList();
1378         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
[887]1379         if (domainList.end() != it) domAxisScalarIds_[0] = *it;
[569]1380       }
[472]1381
[569]1382       if (!axis_ref.isEmpty())
1383       {
1384         std::vector<StdString> axisList = cgPtr->getAxisList();
1385         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
[887]1386         if (axisList.end() != it) domAxisScalarIds_[1] = *it;
[569]1387       }
[887]1388
1389       if (!scalar_ref.isEmpty())
1390       {
1391         std::vector<StdString> scalarList = cgPtr->getScalarList();
1392         it = std::find(scalarList.begin(), scalarList.end(), scalar_ref.getValue());
1393         if (scalarList.end() != it) domAxisScalarIds_[2] = *it;
1394       }
[569]1395     }
[887]1396     return (domAxisScalarIds_);
[569]1397   }
1398
[472]1399   CVariable* CField::addVariable(const string& id)
1400   {
[562]1401     return vVariableGroup->createChild(id);
[472]1402   }
1403
1404   CVariableGroup* CField::addVariableGroup(const string& id)
1405   {
[562]1406     return vVariableGroup->createChildGroup(id);
[472]1407   }
1408
[509]1409   void CField::sendAddAllVariables()
1410   {
[957]1411     std::vector<CVariable*> allVar = getAllVariables();
1412     std::vector<CVariable*>::const_iterator it = allVar.begin();
1413     std::vector<CVariable*>::const_iterator itE = allVar.end();
1414
1415     for (; it != itE; ++it)
[509]1416     {
[957]1417       this->sendAddVariable((*it)->getId());
1418       (*it)->sendAllAttributesToServer();
1419       (*it)->sendValue();
[509]1420     }
1421   }
1422
[472]1423   void CField::sendAddVariable(const string& id)
1424   {
[562]1425    CContext* context = CContext::getCurrent();
[509]1426
[562]1427    if (!context->hasServer)
[472]1428    {
[562]1429       CContextClient* client = context->client;
[472]1430
[562]1431       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
[472]1432       if (client->isServerLeader())
1433       {
[562]1434         CMessage msg;
1435         msg << this->getId();
1436         msg << id;
[595]1437         const std::list<int>& ranks = client->getRanksServerLeader();
1438         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1439           event.push(*itRank,1,msg);
[562]1440         client->sendEvent(event);
[472]1441       }
[562]1442       else client->sendEvent(event);
[472]1443    }
1444   }
[509]1445
[472]1446   void CField::sendAddVariableGroup(const string& id)
1447   {
[562]1448    CContext* context = CContext::getCurrent();
1449    if (!context->hasServer)
[472]1450    {
[562]1451       CContextClient* client = context->client;
[472]1452
[562]1453       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
[472]1454       if (client->isServerLeader())
1455       {
[562]1456         CMessage msg;
1457         msg << this->getId();
1458         msg << id;
[595]1459         const std::list<int>& ranks = client->getRanksServerLeader();
1460         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1461           event.push(*itRank,1,msg);
[562]1462         client->sendEvent(event);
[472]1463       }
[562]1464       else client->sendEvent(event);
[472]1465    }
1466   }
[509]1467
[472]1468   void CField::recvAddVariable(CEventServer& event)
1469   {
[509]1470
[562]1471      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1472      string id;
[562]1473      *buffer >> id;
1474      get(id)->recvAddVariable(*buffer);
[472]1475   }
[509]1476
[472]1477   void CField::recvAddVariable(CBufferIn& buffer)
1478   {
[562]1479      string id;
1480      buffer >> id;
1481      addVariable(id);
[472]1482   }
1483
1484   void CField::recvAddVariableGroup(CEventServer& event)
1485   {
[509]1486
[562]1487      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1488      string id;
[562]1489      *buffer >> id;
1490      get(id)->recvAddVariableGroup(*buffer);
[472]1491   }
[509]1492
[472]1493   void CField::recvAddVariableGroup(CBufferIn& buffer)
1494   {
[562]1495      string id;
1496      buffer >> id;
1497      addVariableGroup(id);
[472]1498   }
1499
[998]1500   /*!
[1286]1501    * Check on freq_off and freq_op attributes.
1502    */
1503   void CField::checkAttributes(void)
1504   {
[1315]1505     bool isFieldRead = file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read;
1506     if (isFieldRead && operation.getValue() != "instant")
1507       ERROR("void CField::checkAttributes(void)",
1508             << "Unsupported operation for field '" << getFieldOutputName() << "'." << std::endl
1509             << "Currently only \"instant\" is supported for fields read from file.")
1510
[1286]1511     if (freq_op.isEmpty())
1512     {
[1315]1513       if (operation.getValue() == "instant")
[1307]1514         freq_op.setValue(file->output_freq.getValue());
[1286]1515       else
[1307]1516         freq_op.setValue(TimeStep);
[1286]1517     }
[1307]1518     if (freq_offset.isEmpty())
[1315]1519       freq_offset.setValue(isFieldRead ? NoneDu : (freq_op.getValue() - TimeStep));
[1286]1520   }
1521
1522   /*!
[998]1523    * Returns string arithmetic expression associated to the field.
1524    * \return if content is defined return content string, otherwise, if "expr" attribute is defined, return expr string.
1525    */
[1000]1526   const string& CField::getExpression(void)
[998]1527   {
[1000]1528     if (!expr.isEmpty() && content.empty())
[998]1529     {
[1000]1530       content = expr;
1531       expr.reset();
[998]1532     }
[1000]1533
[998]1534     return content;
1535   }
[1000]1536
1537   bool CField::hasExpression(void) const
[998]1538   {
[1000]1539     return (!expr.isEmpty() || !content.empty());
1540   }
1541
[540]1542   DEFINE_REF_FUNC(Field,field)
[335]1543} // namespace xios
Note: See TracBrowser for help on using the repository browser.