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

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

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

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