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

Last change on this file since 566 was 562, checked in by rlacroix, 9 years ago

Fix incorrect output values when using a field_ref or the @ operator on a field computed from an operation.

The computed values were never transmitted from the source field to the destination field.

  • 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
File size: 32.3 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 "xmlioserver_spl.hpp"
11#include "type.hpp"
12#include "context_client.hpp"
13#include <set>
14
15namespace xios{
16
17   /// ////////////////////// Définitions ////////////////////// ///
18
19   CField::CField(void)
20      : CObjectTemplate<CField>(), CFieldAttributes()
21      , refObject(), baseRefObject()
22      , grid(), file()
23      , freq_operation(), freq_write()
24      , nstep(0)
25      , last_Write(), last_operation()
26      , foperation(), hasInstantData(false), hasExpression(false)
27      , active(false) , hasOutputFile(false),hasFieldOut(false), slotUpdateDate(NULL)
28      , processed(false), domAxisIds_("", ""), areAllReferenceSolved(false), areAllExpressionBuilt(false)
29      { setVirtualVariableGroup(); }
30
31   CField::CField(const StdString& id)
32      : CObjectTemplate<CField>(id), CFieldAttributes()
33      , refObject(), baseRefObject()
34      , grid(), file()
35      , freq_operation(), freq_write()
36      , nstep(0)
37      , last_Write(), last_operation()
38      , foperation(), hasInstantData(false), hasExpression(false)
39      , active(false), hasOutputFile(false), hasFieldOut(false), slotUpdateDate(NULL)
40      , processed(false), domAxisIds_("", ""), areAllReferenceSolved(false), areAllExpressionBuilt(false)
41   { setVirtualVariableGroup(); }
42
43   CField::~CField(void)
44   {
45//      this->grid.reset();
46//      this->file.reset();
47      this->foperation.reset();
48      if (hasExpression) delete expression;
49      if (slotUpdateDate != NULL) delete slotUpdateDate;
50
51   }
52
53
54  //----------------------------------------------------------------
55
56   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
57   {
58      this->vVariableGroup = newVVariableGroup;
59   }
60
61   void CField::setVirtualVariableGroup(void)
62   {
63      this->setVirtualVariableGroup(CVariableGroup::create());
64   }
65
66   CVariableGroup* CField::getVirtualVariableGroup(void) const
67   {
68      return this->vVariableGroup;
69   }
70
71
72   std::vector<CVariable*> CField::getAllVariables(void) const
73   {
74      return this->vVariableGroup->getAllChildren();
75   }
76
77   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
78   {
79      SuperClassAttribute::setAttributes(parent, apply);
80      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
81   }
82   //----------------------------------------------------------------
83   //----------------------------------------------------------------
84
85   bool CField::updateDataServer
86      (const CDate& currDate,
87       const std::deque< CArray<double, 1>* > storedClient)
88   {
89      const CDate opeDate      = *last_operation + freq_operation;
90      const CDate writeDate    = *last_Write     + freq_write;
91
92      if (opeDate <= currDate)
93      {
94         if (this->data.numElements() != this->grid->storeIndex[0]->numElements())
95         {
96            this->data.resize(this->grid->storeIndex[0]->numElements());
97         }
98         CArray<double,1> input(data.numElements());
99         this->grid->inputFieldServer(storedClient, input);
100         (*this->foperation)(input);
101         *last_operation = currDate;
102      }
103      if (writeDate < (currDate + freq_operation))
104      {
105         this->foperation->final();
106         this->incrementNStep();
107         *last_Write = writeDate;
108         return true;
109      }
110      return false;
111   }
112
113   bool CField::dispatchEvent(CEventServer& event)
114  {
115
116    if (SuperClass::dispatchEvent(event)) return true;
117    else
118    {
119      switch(event.type)
120      {
121        case EVENT_ID_UPDATE_DATA :
122          recvUpdateData(event);
123          return true;
124          break;
125
126            case EVENT_ID_ADD_VARIABLE :
127             recvAddVariable(event);
128             return true;
129             break;
130
131           case EVENT_ID_ADD_VARIABLE_GROUP :
132             recvAddVariableGroup(event);
133             return true;
134             break;
135
136        default :
137          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
138          return false;
139      }
140    }
141  }
142
143  void CField::sendUpdateData(void)
144  {
145    CContext* context = CContext::getCurrent();
146    CContextClient* client = context->client;
147
148    CEventClient event(getType(),EVENT_ID_UPDATE_DATA);
149
150    map<int,CArray<int, 1>* >::iterator it;
151    list<shared_ptr<CMessage> > list_msg;
152    list< CArray<double,1>* > list_data;
153
154     for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
155    {
156      int rank = (*it).first;
157      CArray<int,1>& index = *(it->second);
158      CArray<double,1> data_tmp(index.numElements());
159      for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
160      list_msg.push_back(shared_ptr<CMessage>(new CMessage));
161      list_data.push_back(new CArray<double,1>(data_tmp));
162      *list_msg.back() << getId() << *list_data.back();
163      event.push(rank,grid->nbSenders[rank],*list_msg.back());
164    }
165    client->sendEvent(event);
166
167    for (list< CArray<double,1>* >::iterator it = list_data.begin(); it != list_data.end(); it++) delete *it;
168  }
169
170  void CField::recvUpdateData(CEventServer& event)
171  {
172    vector<int> ranks;
173    vector<CBufferIn*> buffers;
174
175    list<CEventServer::SSubEvent>::iterator it;
176    string fieldId;
177
178    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
179    {
180      int rank = it->rank;
181      CBufferIn* buffer = it->buffer;
182      *buffer >> fieldId;
183      ranks.push_back(rank);
184      buffers.push_back(buffer);
185    }
186    get(fieldId)->recvUpdateData(ranks,buffers);
187  }
188
189  void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
190  {
191
192    if (data_srv.empty())
193    {
194//      for (map<int, CArray<int, 1>* >::iterator it = grid->out_i_fromClient.begin(); it != grid->out_i_fromClient.end(); it++)
195      for (map<int, CArray<size_t, 1>* >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
196      {
197        int rank = it->first;
198        CArray<double,1> data_tmp(it->second->numElements());
199        data_srv.insert( pair<int, CArray<double,1>* >(rank, new CArray<double,1>(data_tmp)));
200        foperation_srv.insert(pair<int,boost::shared_ptr<func::CFunctor> >(rank,boost::shared_ptr<func::CFunctor>(new func::CInstant(*data_srv[rank]))));
201      }
202    }
203
204    CContext* context = CContext::getCurrent();
205    const CDate& currDate = context->getCalendar()->getCurrentDate();
206    const CDate opeDate      = *last_operation_srv + freq_operation_srv;
207    const CDate writeDate    = *last_Write_srv     + freq_write_srv;
208
209    if (opeDate <= currDate)
210    {
211      for (int n = 0; n < ranks.size(); n++)
212      {
213        CArray<double,1> data_tmp;
214        *buffers[n] >> data_tmp;
215        (*foperation_srv[ranks[n]])(data_tmp);
216      }
217      *last_operation_srv = currDate;
218    }
219
220    if (writeDate < (currDate + freq_operation_srv))
221    {
222      for (int n = 0; n < ranks.size(); n++)
223      {
224        this->foperation_srv[ranks[n]]->final();
225      }
226
227      *last_Write_srv = writeDate;
228      writeField();
229      *lastlast_Write_srv = *last_Write_srv;
230    }
231  }
232
233  void CField::writeField(void)
234  {
235    if (!getRelFile()->allDomainEmpty)
236      if (!grid->domain->isEmpty() || getRelFile()->type == CFile::type_attr::one_file)
237      {
238        getRelFile()->checkFile();
239        this->incrementNStep();
240        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
241      }
242  }
243
244   //----------------------------------------------------------------
245
246   void CField::setRelFile(CFile* _file)
247   {
248      this->file = _file;
249      hasOutputFile = true;
250   }
251
252   //----------------------------------------------------------------
253
254   StdString CField::GetName(void)    { return StdString("field"); }
255   StdString CField::GetDefName(void) { return CField::GetName(); }
256   ENodeType CField::GetType(void)    { return eField; }
257
258   //----------------------------------------------------------------
259
260   CGrid* CField::getRelGrid(void) const
261   {
262      return this->grid;
263   }
264
265   //----------------------------------------------------------------
266
267   CFile* CField::getRelFile(void) const
268   {
269      return this->file;
270   }
271
272   StdSize CField::getNStep(void) const
273   {
274      return this->nstep;
275   }
276
277   void CField::incrementNStep(void)
278   {
279      this->nstep++;
280   }
281
282   void CField::resetNStep(void)
283   {
284      this->nstep = 0;
285   }
286
287   //----------------------------------------------------------------
288
289   const CDuration& CField::getFreqOperation(void) const
290   {
291      return this->freq_operation;
292   }
293
294   //----------------------------------------------------------------
295
296   const CDuration& CField::getFreqWrite(void) const
297   {
298      return this->freq_write;
299   }
300
301   //----------------------------------------------------------------
302
303   boost::shared_ptr<func::CFunctor> CField::getFieldOperation(void) const
304   {
305      return this->foperation;
306   }
307
308   bool CField::isActive(void) const
309   {
310      return !this->refObject.empty();
311   }
312
313   //----------------------------------------------------------------
314
315   CArray<double, 1> CField::getData(void) const
316   {
317      return(this->data);
318   }
319
320   //----------------------------------------------------------------
321
322   boost::shared_ptr<CDate> CField::getLastWriteDate(void) const
323   {
324      return(this->last_Write);
325   }
326
327   //----------------------------------------------------------------
328
329   boost::shared_ptr<CDate> CField::getLastOperationDate(void) const
330   {
331      return(this->last_operation);
332   }
333
334   //----------------------------------------------------------------
335
336//   void CField::processEnabledField(void)
337//   {
338//      if (!processed)
339//      {
340//        processed = true;
341//        solveRefInheritance(true);
342//        solveBaseReference();
343//        solveOperation();
344//        solveGridReference();
345//
346//        if (hasDirectFieldReference()) baseRefObject->processEnabledField();
347//        buildExpression();
348//        active = true;
349//      }
350//    }
351
352   void CField::solveAllReferenceEnabledField(bool doSending2Sever)
353   {
354     CContext* context = CContext::getCurrent();
355     if (!areAllReferenceSolved)
356     {
357        areAllReferenceSolved = true;
358        if (context->hasClient)
359        {
360          solveRefInheritance(true);
361          solveBaseReference();
362        }
363
364        solveOperation();
365        solveGridReference();
366     }
367     solveGridDomainAxisRef(doSending2Sever);
368     solveCheckMaskIndex(doSending2Sever);
369   }
370
371   std::map<int, StdSize> CField::getGridDataSize()
372   {
373     return grid->getConnectedServerDataSize();
374   }
375
376   void CField::buildAllExpressionEnabledField()
377   {
378     if (!areAllReferenceSolved) solveAllReferenceEnabledField(true);
379     if (!areAllExpressionBuilt)
380     {
381       areAllExpressionBuilt = true;
382//       solveCheckMaskIndex(true);
383//       solveCheckMaskIndex();
384       if (hasDirectFieldReference()) baseRefObject->buildAllExpressionEnabledField();
385       buildExpression();
386       active = true;
387     }
388   }
389
390   //----------------------------------------------------------------
391
392   void  CField::solveOperation(void)
393   {
394      using namespace func;
395
396      if (!hasOutputFile && !hasFieldOut) return;
397
398      StdString id;
399      if (hasId()) id = getId();
400      else if (!name.isEmpty()) id = name;
401      else if (hasDirectFieldReference()) id = baseRefObject->getId();
402
403      CContext* context = CContext::getCurrent();
404
405      if (freq_op.isEmpty()) freq_op.setValue(TimeStep);
406
407      if (operation.isEmpty())
408      {
409         ERROR("CField::solveOperation(void)",
410               << "[ id = " << id << "]"
411               << "Impossible to define an operation for this field !");
412      }
413
414      if (freq_offset.isEmpty())
415        freq_offset.setValue(NoneDu);
416
417//      if (CXIOSManager::GetStatus() == CXIOSManager::LOC_SERVER)
418      if (context->hasServer)
419      {
420         if (hasOutputFile)
421         {
422           this->freq_operation_srv = this->file->output_freq.getValue();
423           this->freq_write_srv = this->file->output_freq.getValue();
424         }
425         this->lastlast_Write_srv = boost::shared_ptr<CDate>
426                        (new CDate(context->getCalendar()->getInitDate()));
427         this->last_Write_srv     = boost::shared_ptr<CDate>
428                        (new CDate(context->getCalendar()->getInitDate()));
429         this->last_operation_srv = boost::shared_ptr<CDate>
430                        (new CDate(context->getCalendar()->getInitDate()));
431//         this->foperation_srv     =
432//             boost::shared_ptr<func::CFunctor>(new CInstant(this->data_srv));
433
434         if (hasOutputFile)
435         {
436           const CDuration toffset = this->freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
437           *this->last_operation_srv   = *this->last_operation_srv - toffset;
438         }
439      }
440
441//      if (context->hasClient)
442//      {
443         this->freq_operation = freq_op.getValue();
444         if (hasOutputFile) this->freq_write = this->file->output_freq.getValue();
445         if (hasFieldOut)
446         {
447           this->freq_write = this->fieldOut->freq_op.getValue();
448         }
449         this->last_Write     = boost::shared_ptr<CDate>
450                        (new CDate(context->getCalendar()->getInitDate()));
451         this->last_operation = boost::shared_ptr<CDate>
452                        (new CDate(context->getCalendar()->getInitDate()));
453
454         const CDuration toffset = this->freq_operation - freq_offset.getValue() - context->getCalendar()->getTimeStep();
455         *this->last_operation   = *this->last_operation - toffset;
456
457        if (operation.get() == "once") isOnceOperation = true;
458        else isOnceOperation = false;
459        isFirstOperation = true;
460
461#define DECLARE_FUNCTOR(MType, mtype) \
462   if (operation.getValue().compare(#mtype) == 0) \
463   { \
464      if (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true) \
465      { \
466        boost::shared_ptr<func::CFunctor> foperation_(new C##MType(this->data,default_value)); \
467        this->foperation = foperation_; \
468      } \
469      else \
470      { \
471        boost::shared_ptr<func::CFunctor> foperation_(new C##MType(this->data)); \
472        this->foperation = foperation_; \
473      } \
474      return; \
475   }
476
477#include "functor_type.conf"
478
479         ERROR("CField::solveOperation(void)",
480               << "[ operation = " << operation.getValue() << "]"
481               << "The operation is not defined !");
482//      }
483   }
484
485   //----------------------------------------------------------------
486/*
487   void CField::fromBinary(StdIStream& is)
488   {
489      SuperClass::fromBinary(is);
490#define CLEAR_ATT(name_)\
491      SuperClassAttribute::operator[](#name_)->reset()
492
493         CLEAR_ATT(domain_ref);
494         CLEAR_ATT(axis_ref);
495#undef CLEAR_ATT
496
497   }
498*/
499   //----------------------------------------------------------------
500
501   void CField::solveGridReference(void)
502   {
503      CDomain* domain;
504      CAxis* axis;
505      std::vector<CDomain*> vecDom;
506      std::vector<CAxis*> vecAxis;
507      std::vector<std::string> domList, axisList;
508
509      if (!domain_ref.isEmpty())
510      {
511         if (CDomain::has(domain_ref.getValue()))
512         {
513           domain = CDomain::get(domain_ref.getValue());
514           vecDom.push_back(domain);
515         }
516         else
517            ERROR("CField::solveGridReference(void)",
518                  << "Reference to the domain \'"
519                  << domain_ref.getValue() << "\' is wrong");
520      }
521
522      if (!axis_ref.isEmpty())
523      {
524         if (CAxis::has(axis_ref.getValue()))
525         {
526           axis = CAxis::get(axis_ref.getValue());
527           vecAxis.push_back(axis);
528         }
529         else
530            ERROR("CField::solveGridReference(void)",
531                  << "Reference to the axis \'"
532                  << axis_ref.getValue() <<"\' is wrong");
533      }
534
535      if (!grid_ref.isEmpty())
536      {
537         if (CGrid::has(grid_ref.getValue()))
538         {
539           this->grid = CGrid::get(grid_ref.getValue());
540           domList = grid->getDomainList();
541           axisList = grid->getAxisList();
542         }
543         else
544            ERROR("CField::solveGridReference(void)",
545                  << "Reference to the grid \'"
546                  << grid_ref.getValue() << "\' is wrong");
547      }
548
549      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty())
550      {
551            ERROR("CField::solveGridReference(void)",
552                  << "At least one dimension must be defined for this field.");
553      }
554
555//     if (!grid_ref.isEmpty())
556//     {
557//       domain = grid->domain;
558//       axis = grid->axis;
559//     }
560
561//     CType<string> goodDomain;
562//     CType<string> goodAxis;
563//     if (!grid_ref.isEmpty())
564//     {
565//       if (!grid->domain_ref.isEmpty()) goodDomain = grid->domain_ref;
566//       if (!grid->axis_ref.isEmpty()) goodAxis = grid->axis_ref;
567//     }
568//     if (!domain_ref.isEmpty()) goodDomain = domain_ref;
569//     if (!axis_ref.isEmpty()) goodAxis = axis_ref;
570
571//     CArray<std::string,1> domListTmp = grid->domainList.getValue();
572//     CArray<std::string,1> axisListTmp = grid->axisList.getValue();
573
574     if (domList.empty() && axisList.empty())
575     {
576       this->grid = CGrid::createGrid(vecDom, vecAxis);
577     }
578
579//     std::string goodDomain = domListTmp[0];
580//     std::string goodAxis = axisListTmp[0];
581
582//     if (goodDomain.isEmpty())
583//     if (goodDomain.empty())
584//     {
585//       ERROR("CField::solveGridReference(void)", << "The horizontal domain for this field is not defined");
586//     }
587//     else
588//     {
589//       if (CDomain::has(goodDomain)) domain = CDomain::get(goodDomain);
590//       else ERROR("CField::solveGridReference(void)",<< "Reference to the domain \'"
591//                  << goodDomain << "\' is wrong");
592////                << goodDomain.get() << "\' is wrong");
593//     }
594//
595////     if (!goodAxis.isEmpty())
596//     if (!goodAxis.empty())
597//     {
598//       if (CAxis::has(goodAxis))  axis = CAxis::get(goodAxis);
599//       else  ERROR("CField::solveGridReference(void)", << "Reference to the axis \'"
600//                   << goodAxis <<"\' is wrong");
601//                   << goodAxis.get() <<"\' is wrong");
602//     }
603
604//     bool nothingToDo = false;
605//
606//     if (!grid_ref.isEmpty())
607//     {
608//       if (!grid->domain_ref.isEmpty() && goodDomain.get() == grid->domain_ref.get())
609//         if (goodAxis.isEmpty()) nothingToDo = true;
610//         else if (!grid->axis_ref.isEmpty())
611//                 if (grid->axis_ref.get() == goodAxis.get()) nothingToDo = true;
612//     }
613//
614//     nothingToDo = true;
615//     if (!nothingToDo)
616//     {
617//       if (!goodAxis.isEmpty())
618//       {
619//         this->grid = CGrid::createGrid(domain, axis);
620//         this->grid_ref.setValue(this->grid->getId());
621//       }
622//       else
623//       {
624//         this->grid = CGrid::createGrid(domain);
625//         this->grid_ref.setValue(this->grid->getId());
626//       }
627//     }
628
629//     grid->solveReference();
630//     grid->solveDomainAxisRef();
631//     grid->checkMaskIndex();
632   }
633
634   void CField::solveGridDomainAxisRef(bool checkAtt)
635   {
636     grid->solveDomainAxisRef(checkAtt);
637   }
638
639   void CField::solveCheckMaskIndex(bool doSendingIndex)
640   {
641     grid->checkMaskIndex(doSendingIndex);
642   }
643
644   ///-------------------------------------------------------------------
645
646   template <>
647   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
648   {
649      if (this->group_ref.isEmpty()) return;
650      StdString gref = this->group_ref.getValue();
651
652      if (!CFieldGroup::has(gref))
653         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
654               << "[ gref = " << gref << "]"
655               << " invalid group name !");
656
657      CFieldGroup* group = CFieldGroup::get(gref);
658      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
659
660      std::vector<CField*> allChildren  = group->getAllChildren();
661      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
662
663      for (; it != end; it++)
664      {
665         CField* child = *it;
666         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
667
668      }
669   }
670
671   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
672   {
673     map<int, CArray<double,1>* >::iterator it;
674     for (it = data_srv.begin(); it != data_srv.end(); it++) *it->second = (*it->second - addOffset) / scaleFactor;
675   }
676
677   void CField::outputField(CArray<double,3>& fieldOut)
678   {
679      map<int, CArray<double,1>* >::iterator it;
680      for (it = data_srv.begin(); it != data_srv.end(); it++)
681      {
682        grid->outputField(it->first,*it->second, fieldOut.dataFirst());
683      }
684
685//         grid->outputField(it->first,*it->second, fieldOut.);
686   }
687
688   void CField::outputField(CArray<double,2>& fieldOut)
689   {
690      map<int, CArray<double,1>* >::iterator it;
691
692      for (it = data_srv.begin(); it != data_srv.end(); it++)
693      {
694         grid->outputField(it->first, *it->second, fieldOut);
695      }
696   }
697
698   ///-------------------------------------------------------------------
699
700   void CField::parse(xml::CXMLNode& node)
701   {
702      SuperClass::parse(node);
703      if (!node.getContent(this->content))
704      {
705        if (node.goToChildElement())
706        {
707          do
708          {
709            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
710          } while (node.goToNextElement());
711          node.goToParentElement();
712        }
713      }
714    }
715
716  CArray<double,1>* CField::getInstantData(void)
717  {
718    if (!hasInstantData)
719    {
720      instantData.resize(grid->storeIndex_client.numElements());
721      hasInstantData = true;
722    }
723    return &instantData;
724  }
725
726  void CField::addDependency(CField* field, int slotId)
727  {
728    fieldDependency.push_back(pair<CField*,int>(field,slotId));
729  }
730
731  void CField::buildExpression(void)
732  {
733    if (content.size() > 0)
734    {
735      CSimpleNodeExpr* simpleExpr = parseExpr(content+'\0');
736      expression = CFieldNode::newNode(simpleExpr);
737      delete simpleExpr;
738      set<string> instantFieldIds;
739      map<string,CField*> associatedInstantFieldIds;
740      expression->getInstantFieldIds(instantFieldIds);
741      for (set<string>::iterator it = instantFieldIds.begin(); it != instantFieldIds.end(); ++it)
742      {
743        if (*it != "this")
744        {
745          if (CField::has(*it))
746          {
747            CField* field = CField::get(*it);
748//            field->processEnabledField();
749            field->buildAllExpressionEnabledField();
750            associatedInstantFieldIds[*it] = field;
751          }
752          else  ERROR("void CField::buildExpression(void)", << " Field " << *it << " does not exist");
753        }
754      }
755
756      set<string> averageFieldIds;
757      map<string,CField*> associatedAverageFieldIds;
758
759      expression->getAverageFieldIds(averageFieldIds);
760      for (set<string>::iterator it = averageFieldIds.begin(); it != averageFieldIds.end(); ++it)
761      {
762        if (CField::has(*it))
763        {
764           CFieldGroup* root = CFieldGroup::get("field_definition");
765           CField* averageField = root->createChild();
766           CField* instantField = root->createChild();
767           averageField->field_ref = *it;
768           averageField->hasFieldOut = true;
769           averageField->fieldOut = instantField;
770           instantField->freq_op = freq_op;
771//           averageField-> processEnabledField();
772           averageField->buildAllExpressionEnabledField();
773           instantField->SuperClassAttribute::setAttributes(averageField, true);
774           instantField->field_ref.reset();
775           instantField->operation.reset();
776
777//           instantField-> processEnabledField();
778           instantField->buildAllExpressionEnabledField();
779           associatedAverageFieldIds[*it] = instantField;
780        }
781        else ERROR("void CField::buildExpression(void)", << " Field " << *it << " does not exist");
782      }
783
784      expression->reduce(this,associatedInstantFieldIds,associatedAverageFieldIds);
785
786      slots.resize(instantFieldIds.size() + averageFieldIds.size());
787      resetSlots();
788      int slotId = 0;
789      set<CField*> fields;
790      expression->getFields(fields);
791      for (set<CField*>::iterator it = fields.begin(); it != fields.end(); ++it, ++slotId) (*it)->addDependency(this,slotId);
792      hasExpression = true;
793    }
794  }
795
796  void CField::resetSlots(void)
797  {
798    for (vector<bool>::iterator it = slots.begin(); it != slots.end(); ++it) *it = false;
799  }
800
801  bool CField::slotsFull(void)
802  {
803    bool ret = true;
804    for (vector<bool>::iterator it = slots.begin(); it != slots.end(); ++it) ret &= *it;
805    return ret;
806  }
807
808  void CField::setSlot(int slotId)
809  {
810    CContext* context = CContext::getCurrent();
811    const CDate& currDate = context->getCalendar()->getCurrentDate();
812    if (slotUpdateDate == NULL || currDate != *slotUpdateDate)
813    {
814      resetSlots();
815      if (slotUpdateDate == NULL) slotUpdateDate = new CDate(currDate);
816      else *slotUpdateDate = currDate;
817    }
818    slots[slotId] = true;
819    if (slotsFull())
820    {
821      CArray<double,1> expr(expression->compute());
822
823      if (hasInstantData)
824      {
825        instantData = expr;
826        for (list< pair<CField *,int> >::iterator it = fieldDependency.begin(); it != fieldDependency.end(); ++it)
827          if (it->first != this) it->first->setSlot(it->second);
828      }
829
830      if (hasOutputFile) updateDataFromExpression(expr);
831
832      const std::vector<CField*>& refField = getAllReference();
833      for (std::vector<CField*>::const_iterator it = refField.begin(); it != refField.end(); it++)
834      {
835        if (!(*it)->hasExpression)
836          (*it)->setDataFromExpression(expr);
837      }
838    }
839  }
840
841   /*!
842     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
843   of a field. In some cases, only domain exists but axis doesn't
844   \return pair of Domain and Axis id
845   */
846   const std::pair<StdString,StdString>& CField::getDomainAxisIds()
847   {
848     CGrid* cgPtr = getRelGrid();
849     if (NULL != cgPtr)
850     {
851       if (NULL != cgPtr->getRelDomain()) domAxisIds_.first = cgPtr->getRelDomain()->getId();
852       if (NULL != cgPtr->getRelAxis()) domAxisIds_.second = cgPtr->getRelAxis()->getId();
853     }
854
855     return domAxisIds_;
856   }
857
858   CVariable* CField::addVariable(const string& id)
859   {
860     return vVariableGroup->createChild(id);
861   }
862
863   CVariableGroup* CField::addVariableGroup(const string& id)
864   {
865     return vVariableGroup->createChildGroup(id);
866   }
867
868   void CField::sendAddAllVariables()
869   {
870     if (!getAllVariables().empty())
871     {
872       // Firstly, it's necessary to add virtual variable group
873       sendAddVariableGroup(getVirtualVariableGroup()->getId());
874
875       // Okie, now we can add to this variable group
876       std::vector<CVariable*> allVar = getAllVariables();
877       std::vector<CVariable*>::const_iterator it = allVar.begin();
878       std::vector<CVariable*>::const_iterator itE = allVar.end();
879
880       for (; it != itE; ++it)
881       {
882         this->sendAddVariable((*it)->getId());
883         (*it)->sendAllAttributesToServer();
884         (*it)->sendValue();
885       }
886     }
887   }
888
889   void CField::sendAddVariable(const string& id)
890   {
891    CContext* context = CContext::getCurrent();
892
893    if (!context->hasServer)
894    {
895       CContextClient* client = context->client;
896
897       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
898       if (client->isServerLeader())
899       {
900         CMessage msg;
901         msg << this->getId();
902         msg << id;
903         event.push(client->getServerLeader(),1,msg);
904         client->sendEvent(event);
905       }
906       else client->sendEvent(event);
907    }
908   }
909
910   void CField::sendAddVariableGroup(const string& id)
911   {
912    CContext* context = CContext::getCurrent();
913    if (!context->hasServer)
914    {
915       CContextClient* client = context->client;
916
917       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
918       if (client->isServerLeader())
919       {
920         CMessage msg;
921         msg << this->getId();
922         msg << id;
923         event.push(client->getServerLeader(),1,msg);
924         client->sendEvent(event);
925       }
926       else client->sendEvent(event);
927    }
928   }
929
930   void CField::recvAddVariable(CEventServer& event)
931   {
932
933      CBufferIn* buffer = event.subEvents.begin()->buffer;
934      string id;
935      *buffer >> id;
936      get(id)->recvAddVariable(*buffer);
937   }
938
939   void CField::recvAddVariable(CBufferIn& buffer)
940   {
941      string id;
942      buffer >> id;
943      addVariable(id);
944   }
945
946   void CField::recvAddVariableGroup(CEventServer& event)
947   {
948
949      CBufferIn* buffer = event.subEvents.begin()->buffer;
950      string id;
951      *buffer >> id;
952      get(id)->recvAddVariableGroup(*buffer);
953   }
954
955   void CField::recvAddVariableGroup(CBufferIn& buffer)
956   {
957      string id;
958      buffer >> id;
959      addVariableGroup(id);
960   }
961
962   DEFINE_REF_FUNC(Field,field)
963
964//  void CField::addReference(CField* field)
965//  {
966//    refObject.push_back(field);
967//  }
968//
969//   //----------------------------------------------------------------
970//
971//   bool CField::hasDirectFieldReference(void) const
972//   {
973//     return !this->field_ref.isEmpty();
974//   }
975//
976//   //----------------------------------------------------------------
977//
978//   const StdString& CField::getBaseFieldId(void) const
979//   {
980//      return this->getBaseFieldReference()->getId();
981//   }
982//
983//   //----------------------------------------------------------------
984//
985//   /*!
986//   \brief Get pointer to direct field to which the current field refers.
987//   */
988//   CField* CField::getDirectFieldReference(void) const
989//   {
990//      if (this->field_ref.isEmpty())
991//         return this->getBaseFieldReference();
992//
993//      if (!CField::has(this->field_ref.getValue()))
994//         ERROR("CField::getDirectFieldReference(void)",
995//               << "[ ref_name = " << this->field_ref.getValue() << "]"
996//               << " invalid field name !");
997//
998//      return CField::get(this->field_ref.getValue());
999//   }
1000//
1001//   //----------------------------------------------------------------
1002//
1003//   CField* CField::getBaseFieldReference(void) const
1004//   {
1005//      return baseRefObject;
1006//   }
1007//
1008//   //----------------------------------------------------------------
1009//
1010//   const std::vector<CField*>& CField::getAllReference(void) const
1011//   {
1012//      return refObject;
1013//   }
1014//
1015//   /*!
1016//   \brief Searching for all reference of a field
1017//   If a field refers to (an)other field(s), we will search for all its referenced parents.
1018//   Moreover, if any father, direct or indirect (e.g: two levels up), has non-empty attributes,
1019//   all its attributes will be added to the current field
1020//   \param [in] apply Flag to specify whether current field uses attributes of its father
1021//               in case the attribute is empty (true) or its attributes are replaced by ones of its father (false)
1022//   */
1023//   void CField::solveRefInheritance(bool apply)
1024//   {
1025//      std::set<CField *> sset;
1026//      CField* refer_sptr;
1027//      CField* refer_ptr = this;
1028//
1029//      while (refer_ptr->hasDirectFieldReference())
1030//      {
1031//         refer_sptr = refer_ptr->getDirectFieldReference();
1032//         refer_ptr  = refer_sptr;
1033//
1034//         if(sset.end() != sset.find(refer_ptr))
1035//         {
1036//            DEBUG (<< "Circular dependency stopped for field object on "
1037//                   << "\"" + refer_ptr->getId() + "\" !");
1038//            break;
1039//         }
1040//
1041//         SuperClassAttribute::setAttributes(refer_ptr, apply);
1042//         sset.insert(refer_ptr);
1043//      }
1044//   }
1045//
1046//   /*!
1047//   \brief Only on SERVER side. Remove all field_ref from current field
1048//   On creating a new field on server side, redundant "field_ref" is still kept in the attribute list
1049//   of the current field. This function removes this from current field
1050//   */
1051//   void CField::removeRefInheritance()
1052//   {
1053//     if (this->field_ref.isEmpty()) return;
1054//     this->clearAttribute("field_ref");
1055//   }
1056//
1057//   void CField::solveBaseReference(void)
1058//   {
1059//      std::set<CField *> sset;
1060//      CField* refer_sptr;
1061//      CField* refer_ptr = this;
1062//
1063//      if (this->hasDirectFieldReference())  baseRefObject = getDirectFieldReference();
1064//      else  baseRefObject = CField::get(this);
1065//
1066//      while (refer_ptr->hasDirectFieldReference())
1067//      {
1068//         refer_sptr = refer_ptr->getDirectFieldReference();
1069//         refer_ptr  = refer_sptr;
1070//
1071//         if(sset.end() != sset.find(refer_ptr))
1072//         {
1073//            DEBUG (<< "Circular dependency stopped for field object on "
1074//                   << "\"" + refer_ptr->getId() + "\" !");
1075//            break;
1076//         }
1077//
1078//         sset.insert(refer_ptr);
1079//      }
1080//
1081//      if (hasDirectFieldReference()) baseRefObject->addReference(this);
1082//   }
1083} // namespace xios
Note: See TracBrowser for help on using the repository browser.