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

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

Preperation for merge from trunk

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