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

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

Ticket 106: Reading a scalar from file

+) Add method to read scalar value
+) Modify the way to send/receive scalar (and non-distributed) data

Test
+) On Curie
+) OK

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