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

Last change on this file since 854 was 854, checked in by ymipsl, 8 years ago

Correct bug in output using freq_op != 1ts and Gregorian calendar.

YM

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