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

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

Cleanup: Remove now deprecated code.

  • 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: 30.7 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      , refObject(), baseRefObject()
33      , grid(), file()
34      , nstep(0), nstepMax(0)
35      , hasOutputFile(false)
36      , domAxisIds_("", ""), areAllReferenceSolved(false)
37      , isReadDataRequestPending(false)
38   { setVirtualVariableGroup(); }
39
40   CField::CField(const StdString& id)
41      : CObjectTemplate<CField>(id), CFieldAttributes()
42      , refObject(), baseRefObject()
43      , grid(), file()
44      , nstep(0), nstepMax(0)
45      , hasOutputFile(false)
46      , domAxisIds_("", ""), areAllReferenceSolved(false)
47      , isReadDataRequestPending(false)
48   { setVirtualVariableGroup(); }
49
50   CField::~CField(void)
51   {}
52
53  //----------------------------------------------------------------
54
55   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
56   {
57      this->vVariableGroup = newVVariableGroup;
58   }
59
60   void CField::setVirtualVariableGroup(void)
61   {
62      this->setVirtualVariableGroup(CVariableGroup::create());
63   }
64
65   CVariableGroup* CField::getVirtualVariableGroup(void) const
66   {
67      return this->vVariableGroup;
68   }
69
70
71   std::vector<CVariable*> CField::getAllVariables(void) const
72   {
73      return this->vVariableGroup->getAllChildren();
74   }
75
76   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
77   {
78      SuperClassAttribute::setAttributes(parent, apply);
79      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
80   }
81
82  //----------------------------------------------------------------
83
84  bool CField::dispatchEvent(CEventServer& event)
85  {
86    if (SuperClass::dispatchEvent(event)) return true;
87    else
88    {
89      switch(event.type)
90      {
91        case EVENT_ID_UPDATE_DATA :
92          recvUpdateData(event);
93          return true;
94          break;
95
96        case EVENT_ID_READ_DATA :
97          recvReadDataRequest(event);
98          return true;
99          break;
100
101        case EVENT_ID_READ_DATA_READY :
102          recvReadDataReady(event);
103          return true;
104          break;
105
106        case EVENT_ID_ADD_VARIABLE :
107          recvAddVariable(event);
108          return true;
109          break;
110
111        case EVENT_ID_ADD_VARIABLE_GROUP :
112          recvAddVariableGroup(event);
113          return true;
114          break;
115
116        default :
117          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
118          return false;
119      }
120    }
121  }
122
123  void CField::sendUpdateData(const CArray<double,1>& data)
124  {
125    CTimer::get("XIOS Send Data").resume();
126
127    CContext* context = CContext::getCurrent();
128    CContextClient* client = context->client;
129
130    CEventClient event(getType(), EVENT_ID_UPDATE_DATA);
131
132    map<int, CArray<int,1>* >::iterator it;
133    list<CMessage> list_msg;
134    list<CArray<double,1> > list_data;
135
136    if (!grid->doGridHaveDataDistributed())
137    {
138       if (0 == client->clientRank)
139       {
140          for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
141          {
142            int rank = (*it).first;
143            CArray<int,1>& index = *(it->second);
144
145            list_msg.push_back(CMessage());
146            list_data.push_back(CArray<double,1>(index.numElements()));
147
148            CArray<double,1>& data_tmp = list_data.back();
149            for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
150
151            list_msg.back() << getId() << data_tmp;
152            event.push(rank, 1, list_msg.back());
153          }
154          client->sendEvent(event);
155       } else client->sendEvent(event);
156    }
157    else
158    {
159      for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
160      {
161        int rank = (*it).first;
162        CArray<int,1>& index = *(it->second);
163
164        list_msg.push_back(CMessage());
165        list_data.push_back(CArray<double,1>(index.numElements()));
166
167        CArray<double,1>& data_tmp = list_data.back();
168        for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
169
170        list_msg.back() << getId() << data_tmp;
171        event.push(rank, grid->nbSenders[rank], list_msg.back());
172      }
173      client->sendEvent(event);
174    }
175   
176    CTimer::get("XIOS Send Data").suspend();
177  }
178
179  void CField::recvUpdateData(CEventServer& event)
180  {
181    vector<int> ranks;
182    vector<CBufferIn*> buffers;
183
184    list<CEventServer::SSubEvent>::iterator it;
185    string fieldId;
186
187    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
188    {
189      int rank = it->rank;
190      CBufferIn* buffer = it->buffer;
191      *buffer >> fieldId;
192      ranks.push_back(rank);
193      buffers.push_back(buffer);
194    }
195    get(fieldId)->recvUpdateData(ranks,buffers);
196  }
197
198  void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
199  {
200    if (data_srv.empty())
201    {
202      for (map<int, CArray<size_t, 1>* >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
203      {
204        int rank = it->first;
205        CArray<double,1> data_tmp(it->second->numElements());
206        data_srv.insert( pair<int, CArray<double,1>* >(rank, new CArray<double,1>(data_tmp)));
207        foperation_srv.insert(pair<int,boost::shared_ptr<func::CFunctor> >(rank,boost::shared_ptr<func::CFunctor>(new func::CInstant(*data_srv[rank]))));
208      }
209    }
210
211    CContext* context = CContext::getCurrent();
212    const CDate& currDate = context->getCalendar()->getCurrentDate();
213    const CDate opeDate      = *last_operation_srv + freq_operation_srv;
214    const CDate writeDate    = *last_Write_srv     + freq_write_srv;
215
216    if (opeDate <= currDate)
217    {
218      for (int n = 0; n < ranks.size(); n++)
219      {
220        CArray<double,1> data_tmp;
221        *buffers[n] >> data_tmp;
222        (*foperation_srv[ranks[n]])(data_tmp);
223      }
224      *last_operation_srv = currDate;
225    }
226
227    if (writeDate < (currDate + freq_operation_srv))
228    {
229      for (int n = 0; n < ranks.size(); n++)
230      {
231        this->foperation_srv[ranks[n]]->final();
232      }
233
234      *last_Write_srv = writeDate;
235      writeField();
236      *lastlast_Write_srv = *last_Write_srv;
237    }
238  }
239
240  void CField::writeField(void)
241  {
242    if (!getRelFile()->allDomainEmpty)
243    {
244      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
245      {
246        getRelFile()->checkFile();
247        this->incrementNStep();
248        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
249      }
250    }
251  }
252
253  void CField::sendReadDataRequest(void)
254  {
255    CContext* context = CContext::getCurrent();
256    CContextClient* client = context->client;
257
258    CEventClient event(getType(), EVENT_ID_READ_DATA);
259    if (client->isServerLeader())
260    {
261      CMessage msg;
262      msg << getId();
263      const std::list<int>& ranks = client->getRanksServerLeader();
264      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
265        event.push(*itRank, 1, msg);
266      client->sendEvent(event);
267    }
268    else client->sendEvent(event);
269
270    lastDataRequestedFromServer = context->getCalendar()->getCurrentDate();
271    isReadDataRequestPending = true;
272  }
273
274  /*!
275  Send request new data read from file if need be, that is the current data is out-of-date.
276  \return true if and only if some data was requested
277  */
278  bool CField::sendReadDataRequestIfNeeded(void)
279  {
280    const CDate& currentDate = CContext::getCurrent()->getCalendar()->getCurrentDate();
281
282    bool requestData = (currentDate >= lastDataRequestedFromServer + file->output_freq.getValue());
283
284    if (requestData)
285      sendReadDataRequest();
286
287    return requestData;
288  }
289
290  void CField::recvReadDataRequest(CEventServer& event)
291  {
292    CBufferIn* buffer = event.subEvents.begin()->buffer;
293    StdString fieldId;
294    *buffer >> fieldId;
295    get(fieldId)->recvReadDataRequest();
296  }
297
298  void CField::recvReadDataRequest(void)
299  {
300    CContext* context = CContext::getCurrent();
301    CContextClient* client = context->client;
302
303    CEventClient event(getType(), EVENT_ID_READ_DATA_READY);
304    std::list<CMessage> msgs;
305
306    bool hasData = readField();
307
308    map<int, CArray<double,1>* >::iterator it;
309    for (it = data_srv.begin(); it != data_srv.end(); it++)
310    {
311      msgs.push_back(CMessage());
312      CMessage& msg = msgs.back();
313      msg << getId();
314      if (hasData)
315        msg << getNStep() - 1 << *it->second;
316      else
317        msg << size_t(-1);
318      event.push(it->first, grid->nbSenders[it->first], msg);
319    }
320    client->sendEvent(event);
321  }
322
323  bool CField::readField(void)
324  {
325    if (!getRelFile()->allDomainEmpty)
326    {
327      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
328      {
329        if (data_srv.empty())
330        {
331          for (map<int, CArray<size_t, 1>* >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
332            data_srv.insert(pair<int, CArray<double,1>*>(it->first, new CArray<double,1>(it->second->numElements())));
333        }
334
335        getRelFile()->checkFile();
336        this->incrementNStep();
337
338        if (!nstepMax)
339        {
340          nstepMax = getRelFile()->getDataInput()->getFieldNbRecords(CField::get(this));
341        }
342
343        if (getNStep() > nstepMax)
344          return false;
345
346        getRelFile()->getDataInput()->readFieldData(CField::get(this));
347      }
348    }
349
350    return true;
351  }
352
353  void CField::recvReadDataReady(CEventServer& event)
354  {
355    string fieldId;
356    vector<int> ranks;
357    vector<CBufferIn*> buffers;
358
359    list<CEventServer::SSubEvent>::iterator it;
360    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
361    {
362      ranks.push_back(it->rank);
363      CBufferIn* buffer = it->buffer;
364      *buffer >> fieldId;
365      buffers.push_back(buffer);
366    }
367    get(fieldId)->recvReadDataReady(ranks, buffers);
368  }
369
370  void CField::recvReadDataReady(vector<int> ranks, vector<CBufferIn*> buffers)
371  {
372    CContext* context = CContext::getCurrent();
373    StdSize record;
374    std::map<int, CArray<double,1> > data;
375
376    bool isEOF = false;
377
378    for (int i = 0; i < ranks.size(); i++)
379    {
380      int rank = ranks[i];
381      *buffers[i] >> record;
382      isEOF = (record == size_t(-1));
383
384      if (!isEOF)
385        *buffers[i] >> data[rank];
386      else
387        break;
388    }
389
390    if (isEOF)
391      serverSourceFilter->signalEndOfStream(lastDataRequestedFromServer);
392    else
393      serverSourceFilter->streamDataFromServer(lastDataRequestedFromServer, data);
394
395    isReadDataRequestPending = false;
396  }
397
398   //----------------------------------------------------------------
399
400   void CField::setRelFile(CFile* _file)
401   {
402      this->file = _file;
403      hasOutputFile = true;
404   }
405
406   //----------------------------------------------------------------
407
408   StdString CField::GetName(void)    { return StdString("field"); }
409   StdString CField::GetDefName(void) { return CField::GetName(); }
410   ENodeType CField::GetType(void)    { return eField; }
411
412   //----------------------------------------------------------------
413
414   CGrid* CField::getRelGrid(void) const
415   {
416      return this->grid;
417   }
418
419   //----------------------------------------------------------------
420
421   CFile* CField::getRelFile(void) const
422   {
423      return this->file;
424   }
425
426   StdSize CField::getNStep(void) const
427   {
428      return this->nstep;
429   }
430
431   func::CFunctor::ETimeType CField::getOperationTimeType() const
432   {
433     return operationTimeType;
434   }
435
436   //----------------------------------------------------------------
437
438   void CField::incrementNStep(void)
439   {
440      this->nstep++;
441   }
442
443   void CField::resetNStep(void)
444   {
445      this->nstep = 0;
446   }
447
448   void CField::resetNStepMax(void)
449   {
450      this->nstepMax = 0;
451   }
452
453   //----------------------------------------------------------------
454
455   bool CField::isActive(void) const
456   {
457      return !this->refObject.empty();
458   }
459
460   //----------------------------------------------------------------
461
462   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
463   {
464     return instantDataFilter;
465   }
466
467   //----------------------------------------------------------------
468
469   void CField::solveAllReferenceEnabledField(bool doSending2Sever)
470   {
471     CContext* context = CContext::getCurrent();
472     if (!areAllReferenceSolved)
473     {
474        areAllReferenceSolved = true;
475
476        if (context->hasClient)
477        {
478          solveRefInheritance(true);
479          solveBaseReference();
480          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
481        }
482        else if (context->hasServer)
483          solveServerOperation();
484
485        solveGridReference();
486
487        lastDataRequestedFromServer.setRelCalendar(*context->getCalendar());
488     }
489     solveGridDomainAxisRef(doSending2Sever);
490     if (context->hasClient)
491     {
492       solveTransformedGrid();
493     }
494     solveCheckMaskIndex(doSending2Sever);
495   }
496
497   std::map<int, StdSize> CField::getGridDataSize()
498   {
499     return grid->getConnectedServerDataSize();
500   }
501
502   //----------------------------------------------------------------
503
504   void CField::solveServerOperation(void)
505   {
506      CContext* context = CContext::getCurrent();
507
508      if (!context->hasServer || !hasOutputFile) return;
509
510      if (freq_op.isEmpty())
511        freq_op.setValue(TimeStep);
512
513      if (freq_offset.isEmpty())
514        freq_offset.setValue(NoneDu);
515
516      freq_operation_srv = file->output_freq.getValue();
517      freq_write_srv     = file->output_freq.getValue();
518
519      lastlast_Write_srv = boost::shared_ptr<CDate>(new CDate(context->getCalendar()->getInitDate()));
520      last_Write_srv     = boost::shared_ptr<CDate>(new CDate(context->getCalendar()->getInitDate()));
521      last_operation_srv = boost::shared_ptr<CDate>(new CDate(context->getCalendar()->getInitDate()));
522
523      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
524      *last_operation_srv     = *last_operation_srv - toffset;
525
526      if (operation.isEmpty())
527        ERROR("void CField::solveServerOperation(void)",
528              << "An operation must be defined for field \"" << getId() << "\".");
529
530      boost::shared_ptr<func::CFunctor> functor;
531      CArray<double, 1> dummyData;
532
533#define DECLARE_FUNCTOR(MType, mtype) \
534      if (operation.getValue().compare(#mtype) == 0) \
535      { \
536        functor.reset(new func::C##MType(dummyData)); \
537      }
538
539#include "functor_type.conf"
540
541      if (!functor)
542        ERROR("void CField::solveServerOperation(void)",
543              << "\"" << operation << "\" is not a valid operation.");
544
545      operationTimeType = functor->timeType();
546   }
547
548   //----------------------------------------------------------------
549
550   /*!
551    * Constructs the graph filter for the field, enabling or not the data output.
552    * This method should not be called more than once with enableOutput equal to true.
553    *
554    * \param gc the garbage collector to use when building the filter graph
555    * \param enableOutput must be true when the field data is to be
556    *                     read by the client or/and written to a file
557    */
558   void CField::buildFilterGraph(CGarbageCollector& gc, bool enableOutput)
559   {
560     if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
561
562     // Start by building a filter which can provide the field's instant data
563     if (!instantDataFilter)
564     {
565       // Check if we have an expression to parse
566       if (!content.empty())
567       {
568         boost::scoped_ptr<IFilterExprNode> expr(parseExpr(content + '\0'));
569         instantDataFilter = expr->reduce(gc, *this);
570       }
571       // Check if we have a reference on another field
572       else if (!field_ref.isEmpty())
573       {
574         CField* fieldRef = CField::get(field_ref);
575         fieldRef->buildFilterGraph(gc, false);
576
577         std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters;
578         // Check if a spatial transformation is needed
579         if (!grid_ref.isEmpty() && !fieldRef->grid_ref.isEmpty() && grid_ref.getValue() != fieldRef->grid_ref.getValue())
580           filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid);
581         else
582           filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
583
584         fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
585         instantDataFilter = filters.second;
586       }
587       // Check if the data is to be read from a file
588       else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
589         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
590       else // The data might be passed from the model
591         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
592     }
593
594     // If the field data is to be read by the client or/and written to a file
595     if (enableOutput && !storeFilter && !fileWriterFilter)
596     {
597       if (!read_access.isEmpty() && read_access.getValue())
598       {
599         storeFilter = boost::shared_ptr<CStoreFilter>(new CStoreFilter(gc, CContext::getCurrent(), grid));
600         instantDataFilter->connectOutput(storeFilter, 0);
601       }
602
603       if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
604       {
605         fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
606         getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
607       }
608     }
609   }
610
611   /*!
612    * Returns the source filter to handle a self reference in the field's expression.
613    * If the needed source filter does not exist, it is created, otherwise it is reused.
614    * This method should only be called when building the filter graph corresponding
615    * to the field's expression.
616    *
617    * \param gc the garbage collector to use
618    * \return the output pin corresponding to a self reference
619    */
620   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
621   {
622     if (instantDataFilter || content.empty())
623       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
624             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
625
626     if (!clientSourceFilter)
627       clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
628
629     return clientSourceFilter;
630   }
631
632   /*!
633    * Returns the temporal filter corresponding to the field's temporal operation
634    * for the specified operation frequency. The filter is created if it does not
635    * exist, otherwise it is reused.
636    *
637    * \param gc the garbage collector to use
638    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
639    * \return the output pin corresponding to the requested temporal filter
640    */
641   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
642   {
643     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
644
645     if (it == temporalDataFilters.end())
646     {
647       if (operation.isEmpty())
648         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
649               << "An operation must be defined for field \"" << getId() << "\".");
650
651       if (freq_op.isEmpty())
652         freq_op.setValue(TimeStep);
653       if (freq_offset.isEmpty())
654         freq_offset.setValue(NoneDu);
655
656       const bool ignoreMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
657
658       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
659                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
660                                                                             freq_op, freq_offset, outFreq,
661                                                                             ignoreMissingValue, ignoreMissingValue ? default_value : 0.0));
662       instantDataFilter->connectOutput(temporalFilter, 0);
663
664       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
665     }
666
667     return it->second;
668   }
669
670   //----------------------------------------------------------------
671/*
672   void CField::fromBinary(StdIStream& is)
673   {
674      SuperClass::fromBinary(is);
675#define CLEAR_ATT(name_)\
676      SuperClassAttribute::operator[](#name_)->reset()
677
678         CLEAR_ATT(domain_ref);
679         CLEAR_ATT(axis_ref);
680#undef CLEAR_ATT
681
682   }
683*/
684   //----------------------------------------------------------------
685
686   void CField::solveGridReference(void)
687   {
688      CDomain* domain;
689      CAxis* axis;
690      std::vector<CDomain*> vecDom;
691      std::vector<CAxis*> vecAxis;
692      std::vector<std::string> domList, axisList;
693
694      if (!domain_ref.isEmpty())
695      {
696         if (CDomain::has(domain_ref.getValue()))
697         {
698           domain = CDomain::get(domain_ref.getValue());
699           vecDom.push_back(domain);
700         }
701         else
702            ERROR("CField::solveGridReference(void)",
703                  << "Reference to the domain \'"
704                  << domain_ref.getValue() << "\' is wrong");
705      }
706
707      if (!axis_ref.isEmpty())
708      {
709         if (CAxis::has(axis_ref.getValue()))
710         {
711           axis = CAxis::get(axis_ref.getValue());
712           vecAxis.push_back(axis);
713         }
714         else
715            ERROR("CField::solveGridReference(void)",
716                  << "Reference to the axis \'"
717                  << axis_ref.getValue() <<"\' is wrong");
718      }
719
720      if (!grid_ref.isEmpty())
721      {
722         if (CGrid::has(grid_ref.getValue()))
723         {
724           this->grid = CGrid::get(grid_ref.getValue());
725           domList = grid->getDomainList();
726           axisList = grid->getAxisList();
727           if (domList.empty() && axisList.empty())
728           {
729             this->grid = CGrid::createGrid(vecDom, vecAxis);
730           }
731         }
732         else
733            ERROR("CField::solveGridReference(void)",
734                  << "Reference to the grid \'"
735                  << grid_ref.getValue() << "\' is wrong");
736      }
737      else
738      {
739         this->grid = CGrid::createGrid(vecDom, vecAxis);
740      }
741
742      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty())
743      {
744            ERROR("CField::solveGridReference(void)",
745                  << "At least one dimension must be defined for this field.");
746      }
747   }
748
749   void CField::solveGridDomainAxisRef(bool checkAtt)
750   {
751     grid->solveDomainAxisRef(checkAtt);
752   }
753
754   void CField::solveCheckMaskIndex(bool doSendingIndex)
755   {
756     grid->checkMaskIndex(doSendingIndex);
757   }
758
759   void CField::solveTransformedGrid()
760   {
761     if (!grid_ref.isEmpty() && hasDirectFieldReference() && !getDirectFieldReference()->grid_ref.isEmpty()
762         && grid_ref.getValue() != getDirectFieldReference()->grid_ref.getValue() && !grid->isTransformed())
763       grid->transformGrid(getDirectFieldReference()->grid);
764   }
765
766   ///-------------------------------------------------------------------
767
768   template <>
769   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
770   {
771      if (this->group_ref.isEmpty()) return;
772      StdString gref = this->group_ref.getValue();
773
774      if (!CFieldGroup::has(gref))
775         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
776               << "[ gref = " << gref << "]"
777               << " invalid group name !");
778
779      CFieldGroup* group = CFieldGroup::get(gref);
780      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
781
782      std::vector<CField*> allChildren  = group->getAllChildren();
783      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
784
785      for (; it != end; it++)
786      {
787         CField* child = *it;
788         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
789
790      }
791   }
792
793   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
794   {
795     map<int, CArray<double,1>* >::iterator it;
796     for (it = data_srv.begin(); it != data_srv.end(); it++) *it->second = (*it->second - addOffset) / scaleFactor;
797   }
798
799   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
800   {
801     map<int, CArray<double,1>* >::iterator it;
802     for (it = data_srv.begin(); it != data_srv.end(); it++) *it->second = *it->second * scaleFactor + addOffset;
803   }
804
805   void CField::outputField(CArray<double,3>& fieldOut)
806   {
807      map<int, CArray<double,1>* >::iterator it;
808      for (it = data_srv.begin(); it != data_srv.end(); it++)
809      {
810        grid->outputField(it->first,*it->second, fieldOut.dataFirst());
811      }
812   }
813
814   void CField::outputField(CArray<double,2>& fieldOut)
815   {
816      map<int, CArray<double,1>* >::iterator it;
817      for(it=data_srv.begin();it!=data_srv.end();it++)
818      {
819         grid->outputField(it->first,*it->second, fieldOut.dataFirst()) ;
820      }
821   }
822
823   void CField::outputField(CArray<double,1>& fieldOut)
824   {
825      map<int, CArray<double,1>* >::iterator it;
826
827      for (it = data_srv.begin(); it != data_srv.end(); it++)
828      {
829         grid->outputField(it->first,*it->second, fieldOut.dataFirst()) ;
830      }
831   }
832
833   void CField::inputField(CArray<double,3>& fieldOut)
834   {
835      map<int, CArray<double,1>*>::iterator it;
836      for (it = data_srv.begin(); it != data_srv.end(); it++)
837      {
838        grid->inputField(it->first, fieldOut.dataFirst(), *it->second);
839      }
840   }
841
842   void CField::inputField(CArray<double,2>& fieldOut)
843   {
844      map<int, CArray<double,1>*>::iterator it;
845      for(it = data_srv.begin(); it != data_srv.end(); it++)
846      {
847         grid->inputField(it->first, fieldOut.dataFirst(), *it->second);
848      }
849   }
850
851   void CField::inputField(CArray<double,1>& fieldOut)
852   {
853      map<int, CArray<double,1>*>::iterator it;
854      for (it = data_srv.begin(); it != data_srv.end(); it++)
855      {
856         grid->inputField(it->first, fieldOut.dataFirst(), *it->second);
857      }
858   }
859
860   ///-------------------------------------------------------------------
861
862   void CField::parse(xml::CXMLNode& node)
863   {
864      SuperClass::parse(node);
865      if (!node.getContent(this->content))
866      {
867        if (node.goToChildElement())
868        {
869          do
870          {
871            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
872          } while (node.goToNextElement());
873          node.goToParentElement();
874        }
875      }
876    }
877
878   /*!
879     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
880   of a field. In some cases, only domain exists but axis doesn't
881   \return pair of Domain and Axis id
882   */
883   const std::pair<StdString,StdString>& CField::getRefDomainAxisIds()
884   {
885     CGrid* cgPtr = getRelGrid();
886     if (NULL != cgPtr)
887     {
888       std::vector<StdString>::iterator it;
889       if (!domain_ref.isEmpty())
890       {
891         std::vector<StdString> domainList = cgPtr->getDomainList();
892         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
893         if (domainList.end() != it) domAxisIds_.first = *it;
894       }
895
896       if (!axis_ref.isEmpty())
897       {
898         std::vector<StdString> axisList = cgPtr->getAxisList();
899         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
900         if (axisList.end() != it) domAxisIds_.second = *it;
901       }
902     }
903     return (domAxisIds_);
904   }
905
906   CVariable* CField::addVariable(const string& id)
907   {
908     return vVariableGroup->createChild(id);
909   }
910
911   CVariableGroup* CField::addVariableGroup(const string& id)
912   {
913     return vVariableGroup->createChildGroup(id);
914   }
915
916   void CField::sendAddAllVariables()
917   {
918     if (!getAllVariables().empty())
919     {
920       // Firstly, it's necessary to add virtual variable group
921       sendAddVariableGroup(getVirtualVariableGroup()->getId());
922
923       // Okie, now we can add to this variable group
924       std::vector<CVariable*> allVar = getAllVariables();
925       std::vector<CVariable*>::const_iterator it = allVar.begin();
926       std::vector<CVariable*>::const_iterator itE = allVar.end();
927
928       for (; it != itE; ++it)
929       {
930         this->sendAddVariable((*it)->getId());
931         (*it)->sendAllAttributesToServer();
932         (*it)->sendValue();
933       }
934     }
935   }
936
937   void CField::sendAddVariable(const string& id)
938   {
939    CContext* context = CContext::getCurrent();
940
941    if (!context->hasServer)
942    {
943       CContextClient* client = context->client;
944
945       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
946       if (client->isServerLeader())
947       {
948         CMessage msg;
949         msg << this->getId();
950         msg << id;
951         const std::list<int>& ranks = client->getRanksServerLeader();
952         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
953           event.push(*itRank,1,msg);
954         client->sendEvent(event);
955       }
956       else client->sendEvent(event);
957    }
958   }
959
960   void CField::sendAddVariableGroup(const string& id)
961   {
962    CContext* context = CContext::getCurrent();
963    if (!context->hasServer)
964    {
965       CContextClient* client = context->client;
966
967       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
968       if (client->isServerLeader())
969       {
970         CMessage msg;
971         msg << this->getId();
972         msg << id;
973         const std::list<int>& ranks = client->getRanksServerLeader();
974         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
975           event.push(*itRank,1,msg);
976         client->sendEvent(event);
977       }
978       else client->sendEvent(event);
979    }
980   }
981
982   void CField::recvAddVariable(CEventServer& event)
983   {
984
985      CBufferIn* buffer = event.subEvents.begin()->buffer;
986      string id;
987      *buffer >> id;
988      get(id)->recvAddVariable(*buffer);
989   }
990
991   void CField::recvAddVariable(CBufferIn& buffer)
992   {
993      string id;
994      buffer >> id;
995      addVariable(id);
996   }
997
998   void CField::recvAddVariableGroup(CEventServer& event)
999   {
1000
1001      CBufferIn* buffer = event.subEvents.begin()->buffer;
1002      string id;
1003      *buffer >> id;
1004      get(id)->recvAddVariableGroup(*buffer);
1005   }
1006
1007   void CField::recvAddVariableGroup(CBufferIn& buffer)
1008   {
1009      string id;
1010      buffer >> id;
1011      addVariableGroup(id);
1012   }
1013
1014   DEFINE_REF_FUNC(Field,field)
1015} // namespace xios
Note: See TracBrowser for help on using the repository browser.