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

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

Reactivating a grid self-transformation (the case when a field has no reference to another field and there is a transformation defined on its grid).

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