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

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

Ticket 106: Reading a scalar from file

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

Test
+) On Curie
+) OK

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