source: XIOS/dev/branch_yushan_merged/src/node/field.cpp @ 1205

Last change on this file since 1205 was 1205, checked in by yushan, 7 years ago

branch merged with trunk @1200

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