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

Last change on this file since 572 was 569, checked in by mhnguyen, 9 years ago

Correct some bugs on discovering server index and do some code cleanings

+) Add some checking functions to make sure mpi_isend and mpi_irecv work correctly
+) Add comments to code
+) Remove some redundant code and comments

Test
+) On Curie
+) The new functions are tested in test_new_features.f90. Test_client and test_complete work like before
+) Test cases:

  • 3 dimension grid with: 1 domain, 1 axis
  • 3 dimension grid with: 3 axis
  • Attached and connected

+) All pass and results are correct

TODO:
+) Fix zoom bug with grid composed of only one axis

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