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

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

Adding new transformation: Compute_connectivity_domain

Test
+) On Curie
+) Test passes

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