source: XIOS/dev/branch_yushan/src/node/field.cpp @ 1053

Last change on this file since 1053 was 1037, checked in by yushan, 7 years ago

initialize the branch

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