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

Last change on this file since 1199 was 1186, checked in by rlacroix, 7 years ago

Fix: Ensure "detect_missing_value" is always applied.

Missing values are know handled as expected for input fields (both from file or from model).

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