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

Last change on this file since 790 was 790, checked in by rlacroix, 8 years ago

Add a new field attribute grid_path to allow chaining spatial transformations.

Intermediate grids must be separated by comma and the source/destination grids must not be listed.

  • 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: 34.0 KB
Line 
1#include "field.hpp"
2
3#include "attribute_template.hpp"
4#include "object_template.hpp"
5#include "group_template.hpp"
6
7#include "node_type.hpp"
8#include "calendar_util.hpp"
9#include "message.hpp"
10#include "xios_spl.hpp"
11#include "type.hpp"
12#include "timer.hpp"
13#include "context_client.hpp"
14#include "context_server.hpp"
15#include <set>
16#include "garbage_collector.hpp"
17#include "source_filter.hpp"
18#include "store_filter.hpp"
19#include "file_writer_filter.hpp"
20#include "pass_through_filter.hpp"
21#include "filter_expr_node.hpp"
22#include "lex_parser.hpp"
23#include "temporal_filter.hpp"
24#include "spatial_transform_filter.hpp"
25
26namespace xios{
27
28   /// ////////////////////// Définitions ////////////////////// ///
29
30   CField::CField(void)
31      : CObjectTemplate<CField>(), CFieldAttributes()
32      , grid(), file()
33      , written(false)
34      , nstep(0), nstepMax(0)
35      , hasOutputFile(false)
36      , domAxisIds_("", ""), areAllReferenceSolved(false)
37      , useCompressedOutput(false)
38      , isReadDataRequestPending(false)
39   { setVirtualVariableGroup(); }
40
41   CField::CField(const StdString& id)
42      : CObjectTemplate<CField>(id), CFieldAttributes()
43      , grid(), file()
44      , written(false)
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    lastDataRequestedFromServer = context->getCalendar()->getCurrentDate();
260    isReadDataRequestPending = true;
261
262    CEventClient event(getType(), EVENT_ID_READ_DATA);
263    if (client->isServerLeader())
264    {
265      CMessage msg;
266      msg << getId();
267      const std::list<int>& ranks = client->getRanksServerLeader();
268      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
269        event.push(*itRank, 1, msg);
270      client->sendEvent(event);
271    }
272    else client->sendEvent(event);
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(StdSize nstep /*= 0*/)
445   {
446      this->nstep = nstep;
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 (instantDataFilter != NULL);
459   }
460
461   //----------------------------------------------------------------
462
463   bool CField::wasWritten() const
464   {
465     return written;
466   }
467
468   void CField::setWritten()
469   {
470     written = true;
471   }
472
473   //----------------------------------------------------------------
474
475   bool CField::getUseCompressedOutput() const
476   {
477     return useCompressedOutput;
478   }
479
480   void CField::setUseCompressedOutput()
481   {
482     useCompressedOutput = true;
483   }
484
485   //----------------------------------------------------------------
486
487   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
488   {
489     return instantDataFilter;
490   }
491
492   //----------------------------------------------------------------
493
494   void CField::solveAllReferenceEnabledField(bool doSending2Sever)
495   {
496     CContext* context = CContext::getCurrent();
497     if (!areAllReferenceSolved)
498     {
499        areAllReferenceSolved = true;
500
501        if (context->hasClient)
502        {
503          solveRefInheritance(true);
504          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
505        }
506        else if (context->hasServer)
507          solveServerOperation();
508
509        solveGridReference();
510     }
511     if (context->hasClient)
512     {
513       solveGenerateGrid();
514     }
515
516     solveGridDomainAxisRef(doSending2Sever);
517
518     if (context->hasClient)
519     {
520       solveTransformedGrid();
521     }
522
523     solveCheckMaskIndex(doSending2Sever);
524   }
525
526   std::map<int, StdSize> CField::getGridAttributesBufferSize()
527   {
528     return grid->getAttributesBufferSize();
529   }
530
531   std::map<int, StdSize> CField::getGridDataBufferSize()
532   {
533     return grid->getDataBufferSize(getId());
534   }
535
536   //----------------------------------------------------------------
537
538   void CField::solveServerOperation(void)
539   {
540      CContext* context = CContext::getCurrent();
541
542      if (!context->hasServer || !hasOutputFile) return;
543
544      if (freq_op.isEmpty())
545        freq_op.setValue(TimeStep);
546
547      if (freq_offset.isEmpty())
548        freq_offset.setValue(NoneDu);
549
550      freq_operation_srv = file->output_freq.getValue();
551      freq_write_srv     = file->output_freq.getValue();
552
553      lastlast_Write_srv = context->getCalendar()->getInitDate();
554      last_Write_srv     = context->getCalendar()->getInitDate();
555      last_operation_srv = context->getCalendar()->getInitDate();
556
557      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
558      last_operation_srv     = last_operation_srv - toffset;
559
560      if (operation.isEmpty())
561        ERROR("void CField::solveServerOperation(void)",
562              << "An operation must be defined for field \"" << getId() << "\".");
563
564      boost::shared_ptr<func::CFunctor> functor;
565      CArray<double, 1> dummyData;
566
567#define DECLARE_FUNCTOR(MType, mtype) \
568      if (operation.getValue().compare(#mtype) == 0) \
569      { \
570        functor.reset(new func::C##MType(dummyData)); \
571      }
572
573#include "functor_type.conf"
574
575      if (!functor)
576        ERROR("void CField::solveServerOperation(void)",
577              << "\"" << operation << "\" is not a valid operation.");
578
579      operationTimeType = functor->timeType();
580   }
581
582   //----------------------------------------------------------------
583
584   /*!
585    * Constructs the graph filter for the field, enabling or not the data output.
586    * This method should not be called more than once with enableOutput equal to true.
587    *
588    * \param gc the garbage collector to use when building the filter graph
589    * \param enableOutput must be true when the field data is to be
590    *                     read by the client or/and written to a file
591    */
592   void CField::buildFilterGraph(CGarbageCollector& gc, bool enableOutput)
593   {
594     if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
595
596     // Start by building a filter which can provide the field's instant data
597     if (!instantDataFilter)
598     {
599       // Check if we have an expression to parse
600       if (!content.empty())
601       {
602         boost::scoped_ptr<IFilterExprNode> expr(parseExpr(content + '\0'));
603         instantDataFilter = expr->reduce(gc, *this);
604       }
605       // Check if we have a reference on another field
606       else if (!field_ref.isEmpty())
607         instantDataFilter = getFieldReference(gc);
608       // Check if the data is to be read from a file
609       else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
610         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
611                                                                                                     freq_offset.isEmpty() ? NoneDu : freq_offset));
612       else // The data might be passed from the model
613         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
614     }
615
616     // If the field data is to be read by the client or/and written to a file
617     if (enableOutput && !storeFilter && !fileWriterFilter)
618     {
619       if (!read_access.isEmpty() && read_access)
620       {
621         storeFilter = boost::shared_ptr<CStoreFilter>(new CStoreFilter(gc, CContext::getCurrent(), grid));
622         instantDataFilter->connectOutput(storeFilter, 0);
623       }
624
625       if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
626       {
627         fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
628         getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
629       }
630     }
631   }
632
633   /*!
634    * Returns the filter needed to handle the field reference.
635    * This method should only be called when building the filter graph corresponding to the field.
636    *
637    * \param gc the garbage collector to use
638    * \return the output pin corresponding to the field reference
639    */
640   boost::shared_ptr<COutputPin> CField::getFieldReference(CGarbageCollector& gc)
641   {
642     if (instantDataFilter || field_ref.isEmpty())
643       ERROR("COutputPin* CField::getFieldReference(CGarbageCollector& gc)",
644             "Impossible to get the field reference for a field which has already been parsed or which does not have a field_ref.");
645
646     CField* fieldRef = CField::get(field_ref);
647     fieldRef->buildFilterGraph(gc, false);
648
649     std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters;
650     // Check if a spatial transformation is needed
651     if (grid && grid != fieldRef->grid)
652       filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid);
653     else
654       filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
655
656     fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
657
658     return filters.second;
659   }
660
661   /*!
662    * Returns the filter needed to handle a self reference in the field's expression.
663    * If the needed filter does not exist, it is created, otherwise it is reused.
664    * This method should only be called when building the filter graph corresponding
665    * to the field's expression.
666    *
667    * \param gc the garbage collector to use
668    * \return the output pin corresponding to a self reference
669    */
670   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
671   {
672     if (instantDataFilter || content.empty())
673       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
674             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
675
676     if (!selfReferenceFilter)
677     {
678       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
679       {
680         if (!serverSourceFilter)
681           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
682                                                                                   freq_offset.isEmpty() ? NoneDu : freq_offset));
683
684         selfReferenceFilter = serverSourceFilter;
685       }
686       else if (!field_ref.isEmpty())
687         selfReferenceFilter = getFieldReference(gc);
688       else
689       {
690         if (!clientSourceFilter)
691           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
692
693         selfReferenceFilter = clientSourceFilter;
694       }
695     }
696
697     return selfReferenceFilter;
698   }
699
700   /*!
701    * Returns the temporal filter corresponding to the field's temporal operation
702    * for the specified operation frequency. The filter is created if it does not
703    * exist, otherwise it is reused.
704    *
705    * \param gc the garbage collector to use
706    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
707    * \return the output pin corresponding to the requested temporal filter
708    */
709   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
710   {
711     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
712
713     if (it == temporalDataFilters.end())
714     {
715       if (operation.isEmpty())
716         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
717               << "An operation must be defined for field \"" << getId() << "\".");
718
719       if (freq_op.isEmpty())
720         freq_op.setValue(TimeStep);
721       if (freq_offset.isEmpty())
722         freq_offset.setValue(NoneDu);
723
724       const bool ignoreMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
725
726       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
727                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
728                                                                             freq_op, freq_offset, outFreq,
729                                                                             ignoreMissingValue, ignoreMissingValue ? default_value : 0.0));
730       instantDataFilter->connectOutput(temporalFilter, 0);
731
732       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
733     }
734
735     return it->second;
736   }
737
738   //----------------------------------------------------------------
739/*
740   void CField::fromBinary(StdIStream& is)
741   {
742      SuperClass::fromBinary(is);
743#define CLEAR_ATT(name_)\
744      SuperClassAttribute::operator[](#name_)->reset()
745
746         CLEAR_ATT(domain_ref);
747         CLEAR_ATT(axis_ref);
748#undef CLEAR_ATT
749
750   }
751*/
752   //----------------------------------------------------------------
753
754   void CField::solveGridReference(void)
755   {
756      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty())
757      {
758        ERROR("CField::solveGridReference(void)",
759              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
760      }
761      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty()))
762      {
763        ERROR("CField::solveGridReference(void)",
764              << "Field '" << getFieldOutputName() << "' has both a grid and a domain/axis." << std::endl
765              << "Please define either 'grid_ref' or 'domain_ref'/'axis_ref'.");
766      }
767
768      if (grid_ref.isEmpty())
769      {
770        std::vector<CDomain*> vecDom;
771        std::vector<CAxis*> vecAxis;
772
773        if (!domain_ref.isEmpty())
774        {
775          if (CDomain::has(domain_ref))
776            vecDom.push_back(CDomain::get(domain_ref));
777          else
778            ERROR("CField::solveGridReference(void)",
779                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
780        }
781
782        if (!axis_ref.isEmpty())
783        {
784          if (CAxis::has(axis_ref))
785            vecAxis.push_back(CAxis::get(axis_ref));
786          else
787            ERROR("CField::solveGridReference(void)",
788                  << "Invalid reference to axis '" << axis_ref.getValue() << "'.");
789        }
790
791        // Warning: the gridId shouldn't be set as the grid_ref since it could be inherited
792        StdString gridId = CGrid::generateId(vecDom, vecAxis);
793        if (CGrid::has(gridId))
794          this->grid = CGrid::get(gridId);
795        else
796          this->grid = CGrid::createGrid(gridId, vecDom, vecAxis);
797      }
798      else
799      {
800        if (CGrid::has(grid_ref))
801          this->grid = CGrid::get(grid_ref);
802        else
803          ERROR("CField::solveGridReference(void)",
804                << "Invalid reference to grid '" << grid_ref.getValue() << "'.");
805      }
806   }
807
808   void CField::solveGridDomainAxisRef(bool checkAtt)
809   {
810     grid->solveDomainAxisRef(checkAtt);
811   }
812
813   void CField::solveCheckMaskIndex(bool doSendingIndex)
814   {
815     grid->checkMaskIndex(doSendingIndex);
816   }
817
818   void CField::solveTransformedGrid()
819   {
820     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
821     {
822       std::vector<CGrid*> grids;
823       // Source grid
824       grids.push_back(getDirectFieldReference()->grid);
825       // Intermediate grids
826       if (!grid_path.isEmpty())
827       {
828         std::string gridId;
829         size_t start = 0, end;
830
831         do
832         {
833           end = grid_path.getValue().find(',', start);
834           if (end != std::string::npos)
835           {
836             gridId = grid_path.getValue().substr(start, end - start);
837             start = end + 1;
838           }
839           else
840             gridId = grid_path.getValue().substr(start);
841
842           if (!CGrid::has(gridId))
843             ERROR("void CField::solveTransformedGrid()",
844                   << "Invalid grid_path, the grid '" << gridId << "' does not exist.");
845
846           grids.push_back(CGrid::get(gridId));
847         }
848         while (end != std::string::npos);
849       }
850       // Destination grid
851       grids.push_back(grid);
852
853       for (size_t i = 0, count = grids.size() - 1; i < count; ++i)
854       {
855         CGrid *gridSrc  = grids[i];
856         CGrid *gridDest = grids[i + 1];
857         if (!gridDest->isTransformed())
858           gridDest->transformGrid(gridSrc);
859       }
860     }
861   }
862
863   void CField::solveGenerateGrid()
864   {
865     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
866       grid->completeGrid(getDirectFieldReference()->grid);
867     else
868       grid->completeGrid();
869   }
870
871   void CField::solveGridDomainAxisBaseRef()
872   {
873     grid->solveDomainAxisRef(false);
874     grid->solveDomainAxisBaseRef();
875   }
876
877   ///-------------------------------------------------------------------
878
879   template <>
880   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
881   {
882      if (this->group_ref.isEmpty()) return;
883      StdString gref = this->group_ref.getValue();
884
885      if (!CFieldGroup::has(gref))
886         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
887               << "[ gref = " << gref << "]"
888               << " invalid group name !");
889
890      CFieldGroup* group = CFieldGroup::get(gref);
891      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
892
893      std::vector<CField*> allChildren  = group->getAllChildren();
894      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
895
896      for (; it != end; it++)
897      {
898         CField* child = *it;
899         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
900
901      }
902   }
903
904   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
905   {
906     map<int, CArray<double,1> >::iterator it;
907     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
908   }
909
910   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
911   {
912     map<int, CArray<double,1> >::iterator it;
913     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
914   }
915
916   void CField::outputField(CArray<double,3>& fieldOut)
917   {
918      map<int, CArray<double,1> >::iterator it;
919      for (it = data_srv.begin(); it != data_srv.end(); it++)
920      {
921        grid->outputField(it->first, it->second, fieldOut.dataFirst());
922      }
923   }
924
925   void CField::outputField(CArray<double,2>& fieldOut)
926   {
927      map<int, CArray<double,1> >::iterator it;
928      for(it=data_srv.begin();it!=data_srv.end();it++)
929      {
930         grid->outputField(it->first, it->second, fieldOut.dataFirst());
931      }
932   }
933
934   void CField::outputField(CArray<double,1>& fieldOut)
935   {
936      map<int, CArray<double,1> >::iterator it;
937
938      for (it = data_srv.begin(); it != data_srv.end(); it++)
939      {
940         grid->outputField(it->first, it->second, fieldOut.dataFirst());
941      }
942   }
943
944   void CField::inputField(CArray<double,3>& fieldOut)
945   {
946      map<int, CArray<double,1> >::iterator it;
947      for (it = data_srv.begin(); it != data_srv.end(); it++)
948      {
949        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
950      }
951   }
952
953   void CField::inputField(CArray<double,2>& fieldOut)
954   {
955      map<int, CArray<double,1> >::iterator it;
956      for(it = data_srv.begin(); it != data_srv.end(); it++)
957      {
958         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
959      }
960   }
961
962   void CField::inputField(CArray<double,1>& fieldOut)
963   {
964      map<int, CArray<double,1> >::iterator it;
965      for (it = data_srv.begin(); it != data_srv.end(); it++)
966      {
967         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
968      }
969   }
970
971   void CField::outputCompressedField(CArray<double,1>& fieldOut)
972   {
973      map<int, CArray<double,1> >::iterator it;
974
975      for (it = data_srv.begin(); it != data_srv.end(); it++)
976      {
977         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
978      }
979   }
980
981   ///-------------------------------------------------------------------
982
983   void CField::parse(xml::CXMLNode& node)
984   {
985      SuperClass::parse(node);
986      if (!node.getContent(this->content))
987      {
988        if (node.goToChildElement())
989        {
990          do
991          {
992            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
993          } while (node.goToNextElement());
994          node.goToParentElement();
995        }
996      }
997    }
998
999   /*!
1000     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
1001   of a field. In some cases, only domain exists but axis doesn't
1002   \return pair of Domain and Axis id
1003   */
1004   const std::pair<StdString,StdString>& CField::getRefDomainAxisIds()
1005   {
1006     CGrid* cgPtr = getRelGrid();
1007     if (NULL != cgPtr)
1008     {
1009       std::vector<StdString>::iterator it;
1010       if (!domain_ref.isEmpty())
1011       {
1012         std::vector<StdString> domainList = cgPtr->getDomainList();
1013         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
1014         if (domainList.end() != it) domAxisIds_.first = *it;
1015       }
1016
1017       if (!axis_ref.isEmpty())
1018       {
1019         std::vector<StdString> axisList = cgPtr->getAxisList();
1020         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
1021         if (axisList.end() != it) domAxisIds_.second = *it;
1022       }
1023     }
1024     return (domAxisIds_);
1025   }
1026
1027   CVariable* CField::addVariable(const string& id)
1028   {
1029     return vVariableGroup->createChild(id);
1030   }
1031
1032   CVariableGroup* CField::addVariableGroup(const string& id)
1033   {
1034     return vVariableGroup->createChildGroup(id);
1035   }
1036
1037   void CField::sendAddAllVariables()
1038   {
1039     if (!getAllVariables().empty())
1040     {
1041       // Firstly, it's necessary to add virtual variable group
1042       sendAddVariableGroup(getVirtualVariableGroup()->getId());
1043
1044       // Okie, now we can add to this variable group
1045       std::vector<CVariable*> allVar = getAllVariables();
1046       std::vector<CVariable*>::const_iterator it = allVar.begin();
1047       std::vector<CVariable*>::const_iterator itE = allVar.end();
1048
1049       for (; it != itE; ++it)
1050       {
1051         this->sendAddVariable((*it)->getId());
1052         (*it)->sendAllAttributesToServer();
1053         (*it)->sendValue();
1054       }
1055     }
1056   }
1057
1058   void CField::sendAddVariable(const string& id)
1059   {
1060    CContext* context = CContext::getCurrent();
1061
1062    if (!context->hasServer)
1063    {
1064       CContextClient* client = context->client;
1065
1066       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
1067       if (client->isServerLeader())
1068       {
1069         CMessage msg;
1070         msg << this->getId();
1071         msg << id;
1072         const std::list<int>& ranks = client->getRanksServerLeader();
1073         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1074           event.push(*itRank,1,msg);
1075         client->sendEvent(event);
1076       }
1077       else client->sendEvent(event);
1078    }
1079   }
1080
1081   void CField::sendAddVariableGroup(const string& id)
1082   {
1083    CContext* context = CContext::getCurrent();
1084    if (!context->hasServer)
1085    {
1086       CContextClient* client = context->client;
1087
1088       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
1089       if (client->isServerLeader())
1090       {
1091         CMessage msg;
1092         msg << this->getId();
1093         msg << id;
1094         const std::list<int>& ranks = client->getRanksServerLeader();
1095         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1096           event.push(*itRank,1,msg);
1097         client->sendEvent(event);
1098       }
1099       else client->sendEvent(event);
1100    }
1101   }
1102
1103   void CField::recvAddVariable(CEventServer& event)
1104   {
1105
1106      CBufferIn* buffer = event.subEvents.begin()->buffer;
1107      string id;
1108      *buffer >> id;
1109      get(id)->recvAddVariable(*buffer);
1110   }
1111
1112   void CField::recvAddVariable(CBufferIn& buffer)
1113   {
1114      string id;
1115      buffer >> id;
1116      addVariable(id);
1117   }
1118
1119   void CField::recvAddVariableGroup(CEventServer& event)
1120   {
1121
1122      CBufferIn* buffer = event.subEvents.begin()->buffer;
1123      string id;
1124      *buffer >> id;
1125      get(id)->recvAddVariableGroup(*buffer);
1126   }
1127
1128   void CField::recvAddVariableGroup(CBufferIn& buffer)
1129   {
1130      string id;
1131      buffer >> id;
1132      addVariableGroup(id);
1133   }
1134
1135   DEFINE_REF_FUNC(Field,field)
1136} // namespace xios
Note: See TracBrowser for help on using the repository browser.