source: XIOS/dev/dev_olga/src/node/field.cpp @ 987

Last change on this file since 987 was 987, checked in by mhnguyen, 7 years ago

First working version.
There are more things to do with it

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