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

Last change on this file since 689 was 687, checked in by mhnguyen, 9 years ago

Implementing auto-generate rectilinear domain

+) Add a new special transformation to generate (complete) rectilinear domain

Test
+) On Curie
+) test_new_feature passed

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