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

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

Support freq_offset for fields in files in read mode.

In theory the first record of a file being read is available at timestep 0, this allows to delay the availability of the data to a later timestep.

Use a temporary solution for now until this can be properly integrated in a temporal filter.

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