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

Last change on this file since 823 was 823, checked in by mhnguyen, 8 years ago

Implementing grid destination clone in case of two grid source

+) Clone attributes of grid destination as well as its transformation
+) Clean some redundant codes

Test
+) All tests pass

  • 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: 38.2 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)
[823]36      , domAxisIds_("", ""), areAllReferenceSolved(false), isReferenceSolved(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)
[823]47      , domAxisIds_("", ""), areAllReferenceSolved(false), isReferenceSolved(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
[823]494   void CField::solveOnlyReferenceEnabledField(bool doSending2Server)
[459]495   {
[509]496     CContext* context = CContext::getCurrent();
[823]497     if (!isReferenceSolved)
[509]498     {
[823]499        isReferenceSolved = true;
[644]500
[510]501        if (context->hasClient)
[509]502        {
503          solveRefInheritance(true);
[823]504          if (hasDirectFieldReference()) getDirectFieldReference()->solveOnlyReferenceEnabledField(false);
[509]505        }
[645]506        else if (context->hasServer)
507          solveServerOperation();
[478]508
[509]509        solveGridReference();
[823]510
511       if (context->hasClient)
512       {
513         solveGenerateGrid();
514         buildGridTransformationGraph();
515       }
[509]516     }
[823]517   }
518
519   /*!
520     Build up graph of grids which plays role of destination and source in grid transformation
521     This function should be called before \func solveGridReference()
522   */
523   void CField::buildGridTransformationGraph()
524   {
525     CContext* context = CContext::getCurrent();
[687]526     if (context->hasClient)
527     {
[823]528       if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
529       {
530         grid->addTransGridSource(getDirectFieldReference()->grid);
531       }
[687]532     }
[823]533   }
[687]534
[823]535   /*!
536     Generate a new grid destination if there are more than one grid source pointing to a same grid destination
537   */
538   void CField::generateNewTransformationGridDest()
539   {
540     CContext* context = CContext::getCurrent();
541     if (context->hasClient)
542     {
543       std::map<CGrid*,std::pair<bool,StdString> >& gridSrcMap = grid->getTransGridSource();
544       if (1 < gridSrcMap.size())
545       {
546         // Search for grid source
547         CGrid* gridSrc = grid;
548         CField* currField = this;
549         std::vector<CField*> hieraField;
[687]550
[823]551         while (currField->hasDirectFieldReference() && (gridSrc == grid))
552         {
553           hieraField.push_back(currField);
554           CField* tmp = currField->getDirectFieldReference();
555           currField = tmp;
556           gridSrc = currField->grid;
557         }
558
559         if (gridSrcMap.end() != gridSrcMap.find(gridSrc))
560         {
561           CGrid* gridTmp;
562           std::pair<bool,StdString> newGridDest = gridSrcMap[gridSrc];
563           if (newGridDest.first)
564           {
565             StdString newIdGridDest = newGridDest.second;
566             if (!CGrid::has(newIdGridDest))
567             {
568                ERROR("CGrid* CGrid::generateNewTransformationGridDest()",
569                  << " Something wrong happened! Grid whose id " << newIdGridDest
570                  << "should exist ");
571             }
572             gridTmp = CGrid::get(newIdGridDest);
573           }
574           else
575           {
576             StdString newIdGridDest = CGrid::generateId(gridSrc, grid);
577             gridTmp = CGrid::cloneGrid(newIdGridDest, grid);
578
579             (gridSrcMap[gridSrc]).first = true;
580             (gridSrcMap[gridSrc]).second = newIdGridDest;
581           }
582
583           // Update all descendants
584           for (std::vector<CField*>::iterator it = hieraField.begin(); it != hieraField.end(); ++it)
585           {
586             (*it)->grid = gridTmp;
587             (*it)->updateRef((*it)->grid);
588           }
589         }
590       }
591     }
592   }
593
594   void CField::updateRef(CGrid* grid)
595   {
596     if (!grid_ref.isEmpty()) grid_ref.setValue(grid->getId());
597     else
598     {
599       std::vector<CAxis*> axisTmp = grid->getAxis();
600       std::vector<CDomain*> domainTmp = grid->getDomains();
601       if ((1<axisTmp.size()) || (1<domainTmp.size()))
602         ERROR("void CField::updateRef(CGrid* grid)",
603           << "More than one domain or axis is available for domain_ref/axis_ref of field " << this->getId());
604
605       if ((!domain_ref.isEmpty()) && (domainTmp.empty()))
606         ERROR("void CField::updateRef(CGrid* grid)",
607           << "Incoherent between available domain and domain_ref of field " << this->getId());
608       if ((!axis_ref.isEmpty()) && (axisTmp.empty()))
609         ERROR("void CField::updateRef(CGrid* grid)",
610           << "Incoherent between available axis and axis_ref of field " << this->getId());
611
612       if (!domain_ref.isEmpty()) domain_ref.setValue(domainTmp[0]->getId());
613       if (!axis_ref.isEmpty()) axis_ref.setValue(axisTmp[0]->getId());
614     }
615   }
616
617   void CField::solveAllReferenceEnabledField(bool doSending2Server)
618   {
619     CContext* context = CContext::getCurrent();
620     solveOnlyReferenceEnabledField(doSending2Server);
621
622     if (!areAllReferenceSolved)
623     {
624        areAllReferenceSolved = true;
625
626        if (context->hasClient)
627        {
628          solveRefInheritance(true);
629          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
630        }
631        else if (context->hasServer)
632          solveServerOperation();
633
634        solveGridReference();
635     }
636
637     solveGridDomainAxisRef(doSending2Server);
638
[619]639     if (context->hasClient)
640     {
641       solveTransformedGrid();
642     }
[687]643
[823]644     solveCheckMaskIndex(doSending2Server);
[509]645   }
646
[731]647   std::map<int, StdSize> CField::getGridAttributesBufferSize()
[509]648   {
[731]649     return grid->getAttributesBufferSize();
[509]650   }
651
[731]652   std::map<int, StdSize> CField::getGridDataBufferSize()
653   {
654     return grid->getDataBufferSize(getId());
655   }
656
[219]657   //----------------------------------------------------------------
658
[645]659   void CField::solveServerOperation(void)
[219]660   {
[640]661      CContext* context = CContext::getCurrent();
[509]662
[640]663      if (!context->hasServer || !hasOutputFile) return;
664
[645]665      if (freq_op.isEmpty())
666        freq_op.setValue(TimeStep);
[509]667
[538]668      if (freq_offset.isEmpty())
669        freq_offset.setValue(NoneDu);
[219]670
[645]671      freq_operation_srv = file->output_freq.getValue();
672      freq_write_srv     = file->output_freq.getValue();
[509]673
[651]674      lastlast_Write_srv = context->getCalendar()->getInitDate();
675      last_Write_srv     = context->getCalendar()->getInitDate();
676      last_operation_srv = context->getCalendar()->getInitDate();
[509]677
[645]678      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
[651]679      last_operation_srv     = last_operation_srv - toffset;
[509]680
[645]681      if (operation.isEmpty())
682        ERROR("void CField::solveServerOperation(void)",
683              << "An operation must be defined for field \"" << getId() << "\".");
[509]684
[645]685      boost::shared_ptr<func::CFunctor> functor;
686      CArray<double, 1> dummyData;
[598]687
[562]688#define DECLARE_FUNCTOR(MType, mtype) \
[645]689      if (operation.getValue().compare(#mtype) == 0) \
[470]690      { \
[645]691        functor.reset(new func::C##MType(dummyData)); \
692      }
[509]693
[219]694#include "functor_type.conf"
[509]695
[645]696      if (!functor)
697        ERROR("void CField::solveServerOperation(void)",
698              << "\"" << operation << "\" is not a valid operation.");
699
700      operationTimeType = functor->timeType();
[219]701   }
[509]702
[219]703   //----------------------------------------------------------------
[640]704
705   /*!
706    * Constructs the graph filter for the field, enabling or not the data output.
707    * This method should not be called more than once with enableOutput equal to true.
708    *
709    * \param gc the garbage collector to use when building the filter graph
710    * \param enableOutput must be true when the field data is to be
711    *                     read by the client or/and written to a file
712    */
713   void CField::buildFilterGraph(CGarbageCollector& gc, bool enableOutput)
714   {
[641]715     if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
716
[640]717     // Start by building a filter which can provide the field's instant data
718     if (!instantDataFilter)
719     {
[642]720       // Check if we have an expression to parse
721       if (!content.empty())
722       {
723         boost::scoped_ptr<IFilterExprNode> expr(parseExpr(content + '\0'));
724         instantDataFilter = expr->reduce(gc, *this);
725       }
[641]726       // Check if we have a reference on another field
[642]727       else if (!field_ref.isEmpty())
[737]728         instantDataFilter = getFieldReference(gc);
[640]729       // Check if the data is to be read from a file
[641]730       else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
[756]731         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
732                                                                                                     freq_offset.isEmpty() ? NoneDu : freq_offset));
[640]733       else // The data might be passed from the model
734         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
735     }
736
737     // If the field data is to be read by the client or/and written to a file
738     if (enableOutput && !storeFilter && !fileWriterFilter)
739     {
[741]740       if (!read_access.isEmpty() && read_access)
[640]741       {
742         storeFilter = boost::shared_ptr<CStoreFilter>(new CStoreFilter(gc, CContext::getCurrent(), grid));
743         instantDataFilter->connectOutput(storeFilter, 0);
744       }
745
746       if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
747       {
748         fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
[643]749         getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
[640]750       }
751     }
752   }
753
[642]754   /*!
[737]755    * Returns the filter needed to handle the field reference.
756    * This method should only be called when building the filter graph corresponding to the field.
757    *
758    * \param gc the garbage collector to use
759    * \return the output pin corresponding to the field reference
760    */
761   boost::shared_ptr<COutputPin> CField::getFieldReference(CGarbageCollector& gc)
762   {
763     if (instantDataFilter || field_ref.isEmpty())
764       ERROR("COutputPin* CField::getFieldReference(CGarbageCollector& gc)",
765             "Impossible to get the field reference for a field which has already been parsed or which does not have a field_ref.");
766
767     CField* fieldRef = CField::get(field_ref);
768     fieldRef->buildFilterGraph(gc, false);
769
770     std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters;
771     // Check if a spatial transformation is needed
[746]772     if (grid && grid != fieldRef->grid)
[737]773       filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid);
774     else
775       filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
776
777     fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
778
779     return filters.second;
780   }
781
782   /*!
783    * Returns the filter needed to handle a self reference in the field's expression.
784    * If the needed filter does not exist, it is created, otherwise it is reused.
[642]785    * This method should only be called when building the filter graph corresponding
786    * to the field's expression.
787    *
788    * \param gc the garbage collector to use
789    * \return the output pin corresponding to a self reference
790    */
791   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
792   {
793     if (instantDataFilter || content.empty())
794       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
795             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
796
[737]797     if (!selfReferenceFilter)
798     {
[741]799       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
800       {
801         if (!serverSourceFilter)
[758]802           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
803                                                                                   freq_offset.isEmpty() ? NoneDu : freq_offset));
[741]804
805         selfReferenceFilter = serverSourceFilter;
806       }
807       else if (!field_ref.isEmpty())
[737]808         selfReferenceFilter = getFieldReference(gc);
809       else
810       {
811         if (!clientSourceFilter)
812           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
[642]813
[737]814         selfReferenceFilter = clientSourceFilter;
815       }
816     }
817
818     return selfReferenceFilter;
[642]819   }
820
[643]821   /*!
822    * Returns the temporal filter corresponding to the field's temporal operation
823    * for the specified operation frequency. The filter is created if it does not
824    * exist, otherwise it is reused.
825    *
826    * \param gc the garbage collector to use
827    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
828    * \return the output pin corresponding to the requested temporal filter
829    */
830   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
831   {
832     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
833
834     if (it == temporalDataFilters.end())
835     {
836       if (operation.isEmpty())
837         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
838               << "An operation must be defined for field \"" << getId() << "\".");
839
840       if (freq_op.isEmpty())
841         freq_op.setValue(TimeStep);
842       if (freq_offset.isEmpty())
843         freq_offset.setValue(NoneDu);
844
845       const bool ignoreMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
846
847       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
848                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
849                                                                             freq_op, freq_offset, outFreq,
850                                                                             ignoreMissingValue, ignoreMissingValue ? default_value : 0.0));
851       instantDataFilter->connectOutput(temporalFilter, 0);
852
853       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
854     }
855
856     return it->second;
857   }
858
[640]859   //----------------------------------------------------------------
[369]860/*
[562]861   void CField::fromBinary(StdIStream& is)
[219]862   {
863      SuperClass::fromBinary(is);
864#define CLEAR_ATT(name_)\
[369]865      SuperClassAttribute::operator[](#name_)->reset()
[219]866
867         CLEAR_ATT(domain_ref);
868         CLEAR_ATT(axis_ref);
869#undef CLEAR_ATT
870
871   }
[369]872*/
[219]873   //----------------------------------------------------------------
874
875   void CField::solveGridReference(void)
876   {
[742]877      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty())
878      {
879        ERROR("CField::solveGridReference(void)",
[770]880              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
[742]881      }
[744]882      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty()))
[219]883      {
[744]884        ERROR("CField::solveGridReference(void)",
[770]885              << "Field '" << getFieldOutputName() << "' has both a grid and a domain/axis." << std::endl
[744]886              << "Please define either 'grid_ref' or 'domain_ref'/'axis_ref'.");
[219]887      }
888
[744]889      if (grid_ref.isEmpty())
[219]890      {
[744]891        std::vector<CDomain*> vecDom;
892        std::vector<CAxis*> vecAxis;
[742]893
[744]894        if (!domain_ref.isEmpty())
895        {
[823]896          StdString tmp = domain_ref.getValue();
[744]897          if (CDomain::has(domain_ref))
898            vecDom.push_back(CDomain::get(domain_ref));
899          else
[219]900            ERROR("CField::solveGridReference(void)",
[744]901                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
902        }
[219]903
[744]904        if (!axis_ref.isEmpty())
[742]905        {
[744]906          if (CAxis::has(axis_ref))
907            vecAxis.push_back(CAxis::get(axis_ref));
908          else
909            ERROR("CField::solveGridReference(void)",
910                  << "Invalid reference to axis '" << axis_ref.getValue() << "'.");
[742]911        }
[744]912
[745]913        // Warning: the gridId shouldn't be set as the grid_ref since it could be inherited
914        StdString gridId = CGrid::generateId(vecDom, vecAxis);
915        if (CGrid::has(gridId))
916          this->grid = CGrid::get(gridId);
917        else
918          this->grid = CGrid::createGrid(gridId, vecDom, vecAxis);
[219]919      }
[586]920      else
921      {
[744]922        if (CGrid::has(grid_ref))
923          this->grid = CGrid::get(grid_ref);
924        else
925          ERROR("CField::solveGridReference(void)",
926                << "Invalid reference to grid '" << grid_ref.getValue() << "'.");
[586]927      }
[509]928   }
[459]929
[509]930   void CField::solveGridDomainAxisRef(bool checkAtt)
931   {
932     grid->solveDomainAxisRef(checkAtt);
[219]933   }
934
[509]935   void CField::solveCheckMaskIndex(bool doSendingIndex)
936   {
937     grid->checkMaskIndex(doSendingIndex);
938   }
[219]939
[619]940   void CField::solveTransformedGrid()
941   {
[746]942     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[790]943     {
944       std::vector<CGrid*> grids;
945       // Source grid
946       grids.push_back(getDirectFieldReference()->grid);
947       // Intermediate grids
948       if (!grid_path.isEmpty())
949       {
950         std::string gridId;
951         size_t start = 0, end;
952
953         do
954         {
955           end = grid_path.getValue().find(',', start);
956           if (end != std::string::npos)
957           {
958             gridId = grid_path.getValue().substr(start, end - start);
959             start = end + 1;
960           }
961           else
962             gridId = grid_path.getValue().substr(start);
963
964           if (!CGrid::has(gridId))
965             ERROR("void CField::solveTransformedGrid()",
966                   << "Invalid grid_path, the grid '" << gridId << "' does not exist.");
967
968           grids.push_back(CGrid::get(gridId));
969         }
970         while (end != std::string::npos);
971       }
972       // Destination grid
973       grids.push_back(grid);
974
975       for (size_t i = 0, count = grids.size() - 1; i < count; ++i)
976       {
977         CGrid *gridSrc  = grids[i];
978         CGrid *gridDest = grids[i + 1];
979         if (!gridDest->isTransformed())
980           gridDest->transformGrid(gridSrc);
981       }
982     }
[619]983   }
984
[687]985   void CField::solveGenerateGrid()
986   {
[746]987     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[687]988       grid->completeGrid(getDirectFieldReference()->grid);
[775]989     else
990       grid->completeGrid();
[687]991   }
992
[775]993   void CField::solveGridDomainAxisBaseRef()
994   {
995     grid->solveDomainAxisRef(false);
996     grid->solveDomainAxisBaseRef();
997   }
998
[219]999   ///-------------------------------------------------------------------
1000
1001   template <>
[562]1002   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
[219]1003   {
1004      if (this->group_ref.isEmpty()) return;
1005      StdString gref = this->group_ref.getValue();
1006
[346]1007      if (!CFieldGroup::has(gref))
[219]1008         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
1009               << "[ gref = " << gref << "]"
1010               << " invalid group name !");
1011
[347]1012      CFieldGroup* group = CFieldGroup::get(gref);
1013      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
[219]1014
[347]1015      std::vector<CField*> allChildren  = group->getAllChildren();
[562]1016      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
[509]1017
[219]1018      for (; it != end; it++)
1019      {
[347]1020         CField* child = *it;
[562]1021         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
[509]1022
[219]1023      }
1024   }
[509]1025
[464]1026   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
1027   {
[651]1028     map<int, CArray<double,1> >::iterator it;
1029     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
[464]1030   }
[509]1031
[599]1032   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
1033   {
[651]1034     map<int, CArray<double,1> >::iterator it;
1035     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
[599]1036   }
1037
[369]1038   void CField::outputField(CArray<double,3>& fieldOut)
[300]1039   {
[651]1040      map<int, CArray<double,1> >::iterator it;
[562]1041      for (it = data_srv.begin(); it != data_srv.end(); it++)
[551]1042      {
[651]1043        grid->outputField(it->first, it->second, fieldOut.dataFirst());
[551]1044      }
[300]1045   }
[509]1046
[369]1047   void CField::outputField(CArray<double,2>& fieldOut)
[300]1048   {
[651]1049      map<int, CArray<double,1> >::iterator it;
[567]1050      for(it=data_srv.begin();it!=data_srv.end();it++)
1051      {
[676]1052         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[567]1053      }
1054   }
[219]1055
[567]1056   void CField::outputField(CArray<double,1>& fieldOut)
1057   {
[651]1058      map<int, CArray<double,1> >::iterator it;
[567]1059
[562]1060      for (it = data_srv.begin(); it != data_srv.end(); it++)
[300]1061      {
[676]1062         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[300]1063      }
1064   }
[551]1065
[599]1066   void CField::inputField(CArray<double,3>& fieldOut)
1067   {
[651]1068      map<int, CArray<double,1> >::iterator it;
[599]1069      for (it = data_srv.begin(); it != data_srv.end(); it++)
1070      {
[651]1071        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1072      }
1073   }
1074
1075   void CField::inputField(CArray<double,2>& fieldOut)
1076   {
[651]1077      map<int, CArray<double,1> >::iterator it;
[599]1078      for(it = data_srv.begin(); it != data_srv.end(); it++)
1079      {
[651]1080         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1081      }
1082   }
1083
1084   void CField::inputField(CArray<double,1>& fieldOut)
1085   {
[651]1086      map<int, CArray<double,1> >::iterator it;
[599]1087      for (it = data_srv.begin(); it != data_srv.end(); it++)
1088      {
[651]1089         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1090      }
1091   }
1092
[676]1093   void CField::outputCompressedField(CArray<double,1>& fieldOut)
1094   {
1095      map<int, CArray<double,1> >::iterator it;
1096
1097      for (it = data_srv.begin(); it != data_srv.end(); it++)
1098      {
1099         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
1100      }
1101   }
1102
[219]1103   ///-------------------------------------------------------------------
1104
[562]1105   void CField::parse(xml::CXMLNode& node)
[459]1106   {
1107      SuperClass::parse(node);
[562]1108      if (!node.getContent(this->content))
[472]1109      {
[476]1110        if (node.goToChildElement())
[472]1111        {
[476]1112          do
1113          {
[562]1114            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
1115          } while (node.goToNextElement());
[476]1116          node.goToParentElement();
1117        }
[472]1118      }
[459]1119    }
[509]1120
1121   /*!
1122     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
1123   of a field. In some cases, only domain exists but axis doesn't
1124   \return pair of Domain and Axis id
1125   */
[569]1126   const std::pair<StdString,StdString>& CField::getRefDomainAxisIds()
1127   {
1128     CGrid* cgPtr = getRelGrid();
1129     if (NULL != cgPtr)
1130     {
1131       std::vector<StdString>::iterator it;
1132       if (!domain_ref.isEmpty())
1133       {
1134         std::vector<StdString> domainList = cgPtr->getDomainList();
1135         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
1136         if (domainList.end() != it) domAxisIds_.first = *it;
1137       }
[472]1138
[569]1139       if (!axis_ref.isEmpty())
1140       {
1141         std::vector<StdString> axisList = cgPtr->getAxisList();
1142         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
1143         if (axisList.end() != it) domAxisIds_.second = *it;
1144       }
1145     }
1146     return (domAxisIds_);
1147   }
1148
[472]1149   CVariable* CField::addVariable(const string& id)
1150   {
[562]1151     return vVariableGroup->createChild(id);
[472]1152   }
1153
1154   CVariableGroup* CField::addVariableGroup(const string& id)
1155   {
[562]1156     return vVariableGroup->createChildGroup(id);
[472]1157   }
1158
[509]1159   void CField::sendAddAllVariables()
1160   {
1161     if (!getAllVariables().empty())
1162     {
1163       // Firstly, it's necessary to add virtual variable group
1164       sendAddVariableGroup(getVirtualVariableGroup()->getId());
1165
1166       // Okie, now we can add to this variable group
1167       std::vector<CVariable*> allVar = getAllVariables();
1168       std::vector<CVariable*>::const_iterator it = allVar.begin();
1169       std::vector<CVariable*>::const_iterator itE = allVar.end();
1170
1171       for (; it != itE; ++it)
1172       {
1173         this->sendAddVariable((*it)->getId());
1174         (*it)->sendAllAttributesToServer();
1175         (*it)->sendValue();
1176       }
1177     }
1178   }
1179
[472]1180   void CField::sendAddVariable(const string& id)
1181   {
[562]1182    CContext* context = CContext::getCurrent();
[509]1183
[562]1184    if (!context->hasServer)
[472]1185    {
[562]1186       CContextClient* client = context->client;
[472]1187
[562]1188       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
[472]1189       if (client->isServerLeader())
1190       {
[562]1191         CMessage msg;
1192         msg << this->getId();
1193         msg << id;
[595]1194         const std::list<int>& ranks = client->getRanksServerLeader();
1195         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1196           event.push(*itRank,1,msg);
[562]1197         client->sendEvent(event);
[472]1198       }
[562]1199       else client->sendEvent(event);
[472]1200    }
1201   }
[509]1202
[472]1203   void CField::sendAddVariableGroup(const string& id)
1204   {
[562]1205    CContext* context = CContext::getCurrent();
1206    if (!context->hasServer)
[472]1207    {
[562]1208       CContextClient* client = context->client;
[472]1209
[562]1210       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
[472]1211       if (client->isServerLeader())
1212       {
[562]1213         CMessage msg;
1214         msg << this->getId();
1215         msg << id;
[595]1216         const std::list<int>& ranks = client->getRanksServerLeader();
1217         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1218           event.push(*itRank,1,msg);
[562]1219         client->sendEvent(event);
[472]1220       }
[562]1221       else client->sendEvent(event);
[472]1222    }
1223   }
[509]1224
[472]1225   void CField::recvAddVariable(CEventServer& event)
1226   {
[509]1227
[562]1228      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1229      string id;
[562]1230      *buffer >> id;
1231      get(id)->recvAddVariable(*buffer);
[472]1232   }
[509]1233
[472]1234   void CField::recvAddVariable(CBufferIn& buffer)
1235   {
[562]1236      string id;
1237      buffer >> id;
1238      addVariable(id);
[472]1239   }
1240
1241   void CField::recvAddVariableGroup(CEventServer& event)
1242   {
[509]1243
[562]1244      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1245      string id;
[562]1246      *buffer >> id;
1247      get(id)->recvAddVariableGroup(*buffer);
[472]1248   }
[509]1249
[472]1250   void CField::recvAddVariableGroup(CBufferIn& buffer)
1251   {
[562]1252      string id;
1253      buffer >> id;
1254      addVariableGroup(id);
[472]1255   }
1256
[540]1257   DEFINE_REF_FUNC(Field,field)
[335]1258} // namespace xios
Note: See TracBrowser for help on using the repository browser.