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

Last change on this file since 779 was 775, checked in by mhnguyen, 9 years ago

Implementing the reading of attributes of an axis from a file

+) 3d grid can be read directly from a file
+) Clean some redundant codes
+) Add new attribute declaration that allows to output only desired attributes

Test
+) On Curie
+) test_remap passes and result is correct

  • 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.9 KB
RevLine 
[219]1#include "field.hpp"
2
[352]3#include "attribute_template.hpp"
4#include "object_template.hpp"
5#include "group_template.hpp"
[219]6
7#include "node_type.hpp"
8#include "calendar_util.hpp"
[352]9#include "message.hpp"
[591]10#include "xios_spl.hpp"
[352]11#include "type.hpp"
[638]12#include "timer.hpp"
[352]13#include "context_client.hpp"
[586]14#include "context_server.hpp"
[459]15#include <set>
[640]16#include "garbage_collector.hpp"
17#include "source_filter.hpp"
18#include "store_filter.hpp"
19#include "file_writer_filter.hpp"
[641]20#include "pass_through_filter.hpp"
[642]21#include "filter_expr_node.hpp"
22#include "lex_parser.hpp"
[643]23#include "temporal_filter.hpp"
[644]24#include "spatial_transform_filter.hpp"
[219]25
[335]26namespace xios{
[509]27
[219]28   /// ////////////////////// Définitions ////////////////////// ///
29
30   CField::CField(void)
31      : CObjectTemplate<CField>(), CFieldAttributes()
32      , grid(), file()
[707]33      , written(false)
[645]34      , nstep(0), nstepMax(0)
35      , hasOutputFile(false)
36      , domAxisIds_("", ""), areAllReferenceSolved(false)
[676]37      , useCompressedOutput(false)
[598]38      , isReadDataRequestPending(false)
[640]39   { setVirtualVariableGroup(); }
[219]40
[562]41   CField::CField(const StdString& id)
[219]42      : CObjectTemplate<CField>(id), CFieldAttributes()
43      , grid(), file()
[707]44      , written(false)
[645]45      , nstep(0), nstepMax(0)
46      , hasOutputFile(false)
47      , domAxisIds_("", ""), areAllReferenceSolved(false)
[676]48      , useCompressedOutput(false)
[598]49      , isReadDataRequestPending(false)
[562]50   { setVirtualVariableGroup(); }
[219]51
52   CField::~CField(void)
[645]53   {}
[509]54
[472]55  //----------------------------------------------------------------
56
57   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
[509]58   {
59      this->vVariableGroup = newVVariableGroup;
[472]60   }
[509]61
[472]62   void CField::setVirtualVariableGroup(void)
63   {
64      this->setVirtualVariableGroup(CVariableGroup::create());
65   }
[509]66
[472]67   CVariableGroup* CField::getVirtualVariableGroup(void) const
68   {
[562]69      return this->vVariableGroup;
[472]70   }
71
[509]72
[472]73   std::vector<CVariable*> CField::getAllVariables(void) const
74   {
[562]75      return this->vVariableGroup->getAllChildren();
[472]76   }
[509]77
[562]78   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
[472]79   {
[562]80      SuperClassAttribute::setAttributes(parent, apply);
[472]81      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
82   }
[219]83
[645]84  //----------------------------------------------------------------
[509]85
[598]86  bool CField::dispatchEvent(CEventServer& event)
[300]87  {
[562]88    if (SuperClass::dispatchEvent(event)) return true;
[300]89    else
90    {
91      switch(event.type)
92      {
93        case EVENT_ID_UPDATE_DATA :
[562]94          recvUpdateData(event);
95          return true;
96          break;
[472]97
[598]98        case EVENT_ID_READ_DATA :
99          recvReadDataRequest(event);
100          return true;
101          break;
[509]102
[598]103        case EVENT_ID_READ_DATA_READY :
104          recvReadDataReady(event);
105          return true;
106          break;
[509]107
[598]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
[300]118        default :
[562]119          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
120          return false;
[300]121      }
122    }
123  }
[509]124
[638]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
[650]134    map<int, CArray<int,1> >::iterator it;
[638]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          {
[650]144            int rank = it->first;
145            CArray<int,1>& index = it->second;
[638]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      {
[650]163        int rank = it->first;
164        CArray<int,1>& index = it->second;
[638]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    }
[687]177
[638]178    CTimer::get("XIOS Send Data").suspend();
179  }
180
[300]181  void CField::recvUpdateData(CEventServer& event)
182  {
[562]183    vector<int> ranks;
184    vector<CBufferIn*> buffers;
[509]185
[562]186    list<CEventServer::SSubEvent>::iterator it;
187    string fieldId;
[219]188
[562]189    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
[300]190    {
[562]191      int rank = it->rank;
192      CBufferIn* buffer = it->buffer;
193      *buffer >> fieldId;
194      ranks.push_back(rank);
195      buffers.push_back(buffer);
[300]196    }
[562]197    get(fieldId)->recvUpdateData(ranks,buffers);
[300]198  }
[509]199
[300]200  void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
201  {
202    if (data_srv.empty())
203    {
[650]204      for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
[300]205      {
[562]206        int rank = it->first;
[651]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]))));
[300]209      }
210    }
211
[562]212    CContext* context = CContext::getCurrent();
213    const CDate& currDate = context->getCalendar()->getCurrentDate();
[651]214    const CDate opeDate      = last_operation_srv + freq_operation_srv;
215    const CDate writeDate    = last_Write_srv     + freq_write_srv;
[300]216
217    if (opeDate <= currDate)
218    {
[562]219      for (int n = 0; n < ranks.size(); n++)
[300]220      {
[562]221        CArray<double,1> data_tmp;
222        *buffers[n] >> data_tmp;
223        (*foperation_srv[ranks[n]])(data_tmp);
[300]224      }
[651]225      last_operation_srv = currDate;
[300]226    }
[509]227
[300]228    if (writeDate < (currDate + freq_operation_srv))
229    {
[562]230      for (int n = 0; n < ranks.size(); n++)
[300]231      {
232        this->foperation_srv[ranks[n]]->final();
233      }
[509]234
[651]235      last_Write_srv = writeDate;
[562]236      writeField();
[651]237      lastlast_Write_srv = last_Write_srv;
[300]238    }
239  }
[509]240
[300]241  void CField::writeField(void)
242  {
[562]243    if (!getRelFile()->allDomainEmpty)
[586]244    {
[599]245      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
[379]246      {
247        getRelFile()->checkFile();
248        this->incrementNStep();
249        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
250      }
[586]251    }
[300]252  }
[562]253
[598]254  void CField::sendReadDataRequest(void)
255  {
256    CContext* context = CContext::getCurrent();
257    CContextClient* client = context->client;
258
[708]259    lastDataRequestedFromServer = context->getCalendar()->getCurrentDate();
260    isReadDataRequestPending = true;
261
[598]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
[599]307    bool hasData = readField();
[598]308
[651]309    map<int, CArray<double,1> >::iterator it;
[598]310    for (it = data_srv.begin(); it != data_srv.end(); it++)
311    {
312      msgs.push_back(CMessage());
313      CMessage& msg = msgs.back();
[599]314      msg << getId();
315      if (hasData)
[651]316        msg << getNStep() - 1 << it->second;
[599]317      else
[603]318        msg << size_t(-1);
[598]319      event.push(it->first, grid->nbSenders[it->first], msg);
320    }
321    client->sendEvent(event);
[599]322  }
[598]323
[599]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        {
[650]332          for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
[651]333            data_srv.insert(std::make_pair(it->first, CArray<double,1>(it->second.numElements())));
[599]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;
[598]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;
[640]375    std::map<int, CArray<double,1> > data;
376
[645]377    bool isEOF = false;
378
[598]379    for (int i = 0; i < ranks.size(); i++)
380    {
381      int rank = ranks[i];
[599]382      *buffers[i] >> record;
[603]383      isEOF = (record == size_t(-1));
[598]384
[599]385      if (!isEOF)
[640]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
[598]396    isReadDataRequestPending = false;
397  }
398
[219]399   //----------------------------------------------------------------
400
[347]401   void CField::setRelFile(CFile* _file)
[509]402   {
[459]403      this->file = _file;
[562]404      hasOutputFile = true;
[219]405   }
406
407   //----------------------------------------------------------------
408
[562]409   StdString CField::GetName(void)    { return StdString("field"); }
410   StdString CField::GetDefName(void) { return CField::GetName(); }
411   ENodeType CField::GetType(void)    { return eField; }
[219]412
413   //----------------------------------------------------------------
414
[347]415   CGrid* CField::getRelGrid(void) const
[509]416   {
[562]417      return this->grid;
[219]418   }
419
420   //----------------------------------------------------------------
421
[347]422   CFile* CField::getRelFile(void) const
[509]423   {
[562]424      return this->file;
[219]425   }
[509]426
[266]427   StdSize CField::getNStep(void) const
428   {
[562]429      return this->nstep;
[266]430   }
[509]431
[645]432   func::CFunctor::ETimeType CField::getOperationTimeType() const
433   {
434     return operationTimeType;
435   }
436
437   //----------------------------------------------------------------
438
[266]439   void CField::incrementNStep(void)
440   {
441      this->nstep++;
442   }
[509]443
[707]444   void CField::resetNStep(StdSize nstep /*= 0*/)
[321]445   {
[707]446      this->nstep = nstep;
[321]447   }
[219]448
[599]449   void CField::resetNStepMax(void)
450   {
451      this->nstepMax = 0;
452   }
453
[219]454   //----------------------------------------------------------------
455
[310]456   bool CField::isActive(void) const
[509]457   {
[767]458      return (instantDataFilter != NULL);
[310]459   }
[562]460
[219]461   //----------------------------------------------------------------
[509]462
[707]463   bool CField::wasWritten() const
464   {
465     return written;
466   }
467
468   void CField::setWritten()
469   {
470     written = true;
471   }
472
473   //----------------------------------------------------------------
474
[676]475   bool CField::getUseCompressedOutput() const
476   {
477     return useCompressedOutput;
478   }
479
480   void CField::setUseCompressedOutput()
481   {
482     useCompressedOutput = true;
483   }
484
485   //----------------------------------------------------------------
486
[641]487   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
488   {
489     return instantDataFilter;
490   }
491
492   //----------------------------------------------------------------
493
[509]494   void CField::solveAllReferenceEnabledField(bool doSending2Sever)
[459]495   {
[509]496     CContext* context = CContext::getCurrent();
497     if (!areAllReferenceSolved)
498     {
499        areAllReferenceSolved = true;
[644]500
[510]501        if (context->hasClient)
[509]502        {
503          solveRefInheritance(true);
[644]504          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
[509]505        }
[645]506        else if (context->hasServer)
507          solveServerOperation();
[478]508
[509]509        solveGridReference();
510     }
[687]511     if (context->hasClient)
512     {
513       solveGenerateGrid();
514     }
515
[509]516     solveGridDomainAxisRef(doSending2Sever);
[687]517
[619]518     if (context->hasClient)
519     {
520       solveTransformedGrid();
521     }
[687]522
[623]523     solveCheckMaskIndex(doSending2Sever);
[509]524   }
525
[731]526   std::map<int, StdSize> CField::getGridAttributesBufferSize()
[509]527   {
[731]528     return grid->getAttributesBufferSize();
[509]529   }
530
[731]531   std::map<int, StdSize> CField::getGridDataBufferSize()
532   {
533     return grid->getDataBufferSize(getId());
534   }
535
[219]536   //----------------------------------------------------------------
537
[645]538   void CField::solveServerOperation(void)
[219]539   {
[640]540      CContext* context = CContext::getCurrent();
[509]541
[640]542      if (!context->hasServer || !hasOutputFile) return;
543
[645]544      if (freq_op.isEmpty())
545        freq_op.setValue(TimeStep);
[509]546
[538]547      if (freq_offset.isEmpty())
548        freq_offset.setValue(NoneDu);
[219]549
[645]550      freq_operation_srv = file->output_freq.getValue();
551      freq_write_srv     = file->output_freq.getValue();
[509]552
[651]553      lastlast_Write_srv = context->getCalendar()->getInitDate();
554      last_Write_srv     = context->getCalendar()->getInitDate();
555      last_operation_srv = context->getCalendar()->getInitDate();
[509]556
[645]557      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
[651]558      last_operation_srv     = last_operation_srv - toffset;
[509]559
[645]560      if (operation.isEmpty())
561        ERROR("void CField::solveServerOperation(void)",
562              << "An operation must be defined for field \"" << getId() << "\".");
[509]563
[645]564      boost::shared_ptr<func::CFunctor> functor;
565      CArray<double, 1> dummyData;
[598]566
[562]567#define DECLARE_FUNCTOR(MType, mtype) \
[645]568      if (operation.getValue().compare(#mtype) == 0) \
[470]569      { \
[645]570        functor.reset(new func::C##MType(dummyData)); \
571      }
[509]572
[219]573#include "functor_type.conf"
[509]574
[645]575      if (!functor)
576        ERROR("void CField::solveServerOperation(void)",
577              << "\"" << operation << "\" is not a valid operation.");
578
579      operationTimeType = functor->timeType();
[219]580   }
[509]581
[219]582   //----------------------------------------------------------------
[640]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   {
[641]594     if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
595
[640]596     // Start by building a filter which can provide the field's instant data
597     if (!instantDataFilter)
598     {
[642]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       }
[641]605       // Check if we have a reference on another field
[642]606       else if (!field_ref.isEmpty())
[737]607         instantDataFilter = getFieldReference(gc);
[640]608       // Check if the data is to be read from a file
[641]609       else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
[756]610         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
611                                                                                                     freq_offset.isEmpty() ? NoneDu : freq_offset));
[640]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     {
[741]619       if (!read_access.isEmpty() && read_access)
[640]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));
[643]628         getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
[640]629       }
630     }
631   }
632
[642]633   /*!
[737]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
[746]651     if (grid && grid != fieldRef->grid)
[737]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.
[642]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
[737]676     if (!selfReferenceFilter)
677     {
[741]678       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
679       {
680         if (!serverSourceFilter)
[758]681           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
682                                                                                   freq_offset.isEmpty() ? NoneDu : freq_offset));
[741]683
684         selfReferenceFilter = serverSourceFilter;
685       }
686       else if (!field_ref.isEmpty())
[737]687         selfReferenceFilter = getFieldReference(gc);
688       else
689       {
690         if (!clientSourceFilter)
691           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
[642]692
[737]693         selfReferenceFilter = clientSourceFilter;
694       }
695     }
696
697     return selfReferenceFilter;
[642]698   }
699
[643]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
[640]738   //----------------------------------------------------------------
[369]739/*
[562]740   void CField::fromBinary(StdIStream& is)
[219]741   {
742      SuperClass::fromBinary(is);
743#define CLEAR_ATT(name_)\
[369]744      SuperClassAttribute::operator[](#name_)->reset()
[219]745
746         CLEAR_ATT(domain_ref);
747         CLEAR_ATT(axis_ref);
748#undef CLEAR_ATT
749
750   }
[369]751*/
[219]752   //----------------------------------------------------------------
753
754   void CField::solveGridReference(void)
755   {
[742]756      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty())
757      {
758        ERROR("CField::solveGridReference(void)",
[770]759              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
[742]760      }
[744]761      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty()))
[219]762      {
[744]763        ERROR("CField::solveGridReference(void)",
[770]764              << "Field '" << getFieldOutputName() << "' has both a grid and a domain/axis." << std::endl
[744]765              << "Please define either 'grid_ref' or 'domain_ref'/'axis_ref'.");
[219]766      }
767
[744]768      if (grid_ref.isEmpty())
[219]769      {
[744]770        std::vector<CDomain*> vecDom;
771        std::vector<CAxis*> vecAxis;
[742]772
[744]773        if (!domain_ref.isEmpty())
774        {
775          if (CDomain::has(domain_ref))
776            vecDom.push_back(CDomain::get(domain_ref));
777          else
[219]778            ERROR("CField::solveGridReference(void)",
[744]779                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
780        }
[219]781
[744]782        if (!axis_ref.isEmpty())
[742]783        {
[744]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() << "'.");
[742]789        }
[744]790
[745]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);
[219]797      }
[586]798      else
799      {
[744]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() << "'.");
[586]805      }
[509]806   }
[459]807
[509]808   void CField::solveGridDomainAxisRef(bool checkAtt)
809   {
810     grid->solveDomainAxisRef(checkAtt);
[219]811   }
812
[509]813   void CField::solveCheckMaskIndex(bool doSendingIndex)
814   {
815     grid->checkMaskIndex(doSendingIndex);
816   }
[219]817
[619]818   void CField::solveTransformedGrid()
819   {
[746]820     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[644]821       grid->transformGrid(getDirectFieldReference()->grid);
[619]822   }
823
[687]824   void CField::solveGenerateGrid()
825   {
[746]826     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[687]827       grid->completeGrid(getDirectFieldReference()->grid);
[775]828     else
829       grid->completeGrid();
[687]830   }
831
[775]832   void CField::solveGridDomainAxisBaseRef()
833   {
834     grid->solveDomainAxisRef(false);
835     grid->solveDomainAxisBaseRef();
836   }
837
[219]838   ///-------------------------------------------------------------------
839
840   template <>
[562]841   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
[219]842   {
843      if (this->group_ref.isEmpty()) return;
844      StdString gref = this->group_ref.getValue();
845
[346]846      if (!CFieldGroup::has(gref))
[219]847         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
848               << "[ gref = " << gref << "]"
849               << " invalid group name !");
850
[347]851      CFieldGroup* group = CFieldGroup::get(gref);
852      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
[219]853
[347]854      std::vector<CField*> allChildren  = group->getAllChildren();
[562]855      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
[509]856
[219]857      for (; it != end; it++)
858      {
[347]859         CField* child = *it;
[562]860         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
[509]861
[219]862      }
863   }
[509]864
[464]865   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
866   {
[651]867     map<int, CArray<double,1> >::iterator it;
868     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
[464]869   }
[509]870
[599]871   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
872   {
[651]873     map<int, CArray<double,1> >::iterator it;
874     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
[599]875   }
876
[369]877   void CField::outputField(CArray<double,3>& fieldOut)
[300]878   {
[651]879      map<int, CArray<double,1> >::iterator it;
[562]880      for (it = data_srv.begin(); it != data_srv.end(); it++)
[551]881      {
[651]882        grid->outputField(it->first, it->second, fieldOut.dataFirst());
[551]883      }
[300]884   }
[509]885
[369]886   void CField::outputField(CArray<double,2>& fieldOut)
[300]887   {
[651]888      map<int, CArray<double,1> >::iterator it;
[567]889      for(it=data_srv.begin();it!=data_srv.end();it++)
890      {
[676]891         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[567]892      }
893   }
[219]894
[567]895   void CField::outputField(CArray<double,1>& fieldOut)
896   {
[651]897      map<int, CArray<double,1> >::iterator it;
[567]898
[562]899      for (it = data_srv.begin(); it != data_srv.end(); it++)
[300]900      {
[676]901         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[300]902      }
903   }
[551]904
[599]905   void CField::inputField(CArray<double,3>& fieldOut)
906   {
[651]907      map<int, CArray<double,1> >::iterator it;
[599]908      for (it = data_srv.begin(); it != data_srv.end(); it++)
909      {
[651]910        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]911      }
912   }
913
914   void CField::inputField(CArray<double,2>& fieldOut)
915   {
[651]916      map<int, CArray<double,1> >::iterator it;
[599]917      for(it = data_srv.begin(); it != data_srv.end(); it++)
918      {
[651]919         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]920      }
921   }
922
923   void CField::inputField(CArray<double,1>& fieldOut)
924   {
[651]925      map<int, CArray<double,1> >::iterator it;
[599]926      for (it = data_srv.begin(); it != data_srv.end(); it++)
927      {
[651]928         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]929      }
930   }
931
[676]932   void CField::outputCompressedField(CArray<double,1>& fieldOut)
933   {
934      map<int, CArray<double,1> >::iterator it;
935
936      for (it = data_srv.begin(); it != data_srv.end(); it++)
937      {
938         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
939      }
940   }
941
[219]942   ///-------------------------------------------------------------------
943
[562]944   void CField::parse(xml::CXMLNode& node)
[459]945   {
946      SuperClass::parse(node);
[562]947      if (!node.getContent(this->content))
[472]948      {
[476]949        if (node.goToChildElement())
[472]950        {
[476]951          do
952          {
[562]953            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
954          } while (node.goToNextElement());
[476]955          node.goToParentElement();
956        }
[472]957      }
[459]958    }
[509]959
960   /*!
961     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
962   of a field. In some cases, only domain exists but axis doesn't
963   \return pair of Domain and Axis id
964   */
[569]965   const std::pair<StdString,StdString>& CField::getRefDomainAxisIds()
966   {
967     CGrid* cgPtr = getRelGrid();
968     if (NULL != cgPtr)
969     {
970       std::vector<StdString>::iterator it;
971       if (!domain_ref.isEmpty())
972       {
973         std::vector<StdString> domainList = cgPtr->getDomainList();
974         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
975         if (domainList.end() != it) domAxisIds_.first = *it;
976       }
[472]977
[569]978       if (!axis_ref.isEmpty())
979       {
980         std::vector<StdString> axisList = cgPtr->getAxisList();
981         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
982         if (axisList.end() != it) domAxisIds_.second = *it;
983       }
984     }
985     return (domAxisIds_);
986   }
987
[472]988   CVariable* CField::addVariable(const string& id)
989   {
[562]990     return vVariableGroup->createChild(id);
[472]991   }
992
993   CVariableGroup* CField::addVariableGroup(const string& id)
994   {
[562]995     return vVariableGroup->createChildGroup(id);
[472]996   }
997
[509]998   void CField::sendAddAllVariables()
999   {
1000     if (!getAllVariables().empty())
1001     {
1002       // Firstly, it's necessary to add virtual variable group
1003       sendAddVariableGroup(getVirtualVariableGroup()->getId());
1004
1005       // Okie, now we can add to this variable group
1006       std::vector<CVariable*> allVar = getAllVariables();
1007       std::vector<CVariable*>::const_iterator it = allVar.begin();
1008       std::vector<CVariable*>::const_iterator itE = allVar.end();
1009
1010       for (; it != itE; ++it)
1011       {
1012         this->sendAddVariable((*it)->getId());
1013         (*it)->sendAllAttributesToServer();
1014         (*it)->sendValue();
1015       }
1016     }
1017   }
1018
[472]1019   void CField::sendAddVariable(const string& id)
1020   {
[562]1021    CContext* context = CContext::getCurrent();
[509]1022
[562]1023    if (!context->hasServer)
[472]1024    {
[562]1025       CContextClient* client = context->client;
[472]1026
[562]1027       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
[472]1028       if (client->isServerLeader())
1029       {
[562]1030         CMessage msg;
1031         msg << this->getId();
1032         msg << id;
[595]1033         const std::list<int>& ranks = client->getRanksServerLeader();
1034         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1035           event.push(*itRank,1,msg);
[562]1036         client->sendEvent(event);
[472]1037       }
[562]1038       else client->sendEvent(event);
[472]1039    }
1040   }
[509]1041
[472]1042   void CField::sendAddVariableGroup(const string& id)
1043   {
[562]1044    CContext* context = CContext::getCurrent();
1045    if (!context->hasServer)
[472]1046    {
[562]1047       CContextClient* client = context->client;
[472]1048
[562]1049       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
[472]1050       if (client->isServerLeader())
1051       {
[562]1052         CMessage msg;
1053         msg << this->getId();
1054         msg << id;
[595]1055         const std::list<int>& ranks = client->getRanksServerLeader();
1056         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1057           event.push(*itRank,1,msg);
[562]1058         client->sendEvent(event);
[472]1059       }
[562]1060       else client->sendEvent(event);
[472]1061    }
1062   }
[509]1063
[472]1064   void CField::recvAddVariable(CEventServer& event)
1065   {
[509]1066
[562]1067      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1068      string id;
[562]1069      *buffer >> id;
1070      get(id)->recvAddVariable(*buffer);
[472]1071   }
[509]1072
[472]1073   void CField::recvAddVariable(CBufferIn& buffer)
1074   {
[562]1075      string id;
1076      buffer >> id;
1077      addVariable(id);
[472]1078   }
1079
1080   void CField::recvAddVariableGroup(CEventServer& event)
1081   {
[509]1082
[562]1083      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1084      string id;
[562]1085      *buffer >> id;
1086      get(id)->recvAddVariableGroup(*buffer);
[472]1087   }
[509]1088
[472]1089   void CField::recvAddVariableGroup(CBufferIn& buffer)
1090   {
[562]1091      string id;
1092      buffer >> id;
1093      addVariableGroup(id);
[472]1094   }
1095
[540]1096   DEFINE_REF_FUNC(Field,field)
[335]1097} // namespace xios
Note: See TracBrowser for help on using the repository browser.