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

Last change on this file since 952 was 952, checked in by ymipsl, 8 years ago
  • Attribut record_offset accept now negative value.
  • Field are not output in files until nstep > 0.

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: 40.1 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(); }
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(); }
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   int 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(int 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     {
783       double defaultValue = 0.0;
784       if (!default_value.isEmpty()) defaultValue = this->default_value;
785       filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid, defaultValue);
786     }
787
788     else
789       filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
790
791     fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
792
793     return filters.second;
794   }
795
796   /*!
797    * Returns the filter needed to handle a self reference in the field's expression.
798    * If the needed filter does not exist, it is created, otherwise it is reused.
799    * This method should only be called when building the filter graph corresponding
800    * to the field's expression.
801    *
802    * \param gc the garbage collector to use
803    * \return the output pin corresponding to a self reference
804    */
805   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
806   {
807     if (instantDataFilter || content.empty())
808       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
809             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
810
811     if (!selfReferenceFilter)
812     {
813       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
814       {
815         if (!serverSourceFilter)
816           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid,
817                                                                                   freq_offset.isEmpty() ? NoneDu : freq_offset));
818
819         selfReferenceFilter = serverSourceFilter;
820       }
821       else if (!field_ref.isEmpty())
822         selfReferenceFilter = getFieldReference(gc);
823       else
824       {
825         if (!clientSourceFilter)
826           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
827
828         selfReferenceFilter = clientSourceFilter;
829       }
830     }
831
832     return selfReferenceFilter;
833   }
834
835   /*!
836    * Returns the temporal filter corresponding to the field's temporal operation
837    * for the specified operation frequency. The filter is created if it does not
838    * exist, otherwise it is reused.
839    *
840    * \param gc the garbage collector to use
841    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
842    * \return the output pin corresponding to the requested temporal filter
843    */
844   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
845   {
846     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
847
848     if (it == temporalDataFilters.end())
849     {
850       if (operation.isEmpty())
851         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
852               << "An operation must be defined for field \"" << getId() << "\".");
853
854       if (freq_op.isEmpty())
855         freq_op.setValue(TimeStep);
856       if (freq_offset.isEmpty())
857         freq_offset.setValue(NoneDu);
858
859       const bool ignoreMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
860
861       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
862                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
863                                                                             freq_op, freq_offset, outFreq,
864                                                                             ignoreMissingValue, ignoreMissingValue ? default_value : 0.0));
865       instantDataFilter->connectOutput(temporalFilter, 0);
866
867       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
868     }
869
870     return it->second;
871   }
872
873   //----------------------------------------------------------------
874/*
875   void CField::fromBinary(StdIStream& is)
876   {
877      SuperClass::fromBinary(is);
878#define CLEAR_ATT(name_)\
879      SuperClassAttribute::operator[](#name_)->reset()
880
881         CLEAR_ATT(domain_ref);
882         CLEAR_ATT(axis_ref);
883#undef CLEAR_ATT
884
885   }
886*/
887   //----------------------------------------------------------------
888
889   void CField::solveGridReference(void)
890   {
891      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty() && scalar_ref.isEmpty())
892      {
893        ERROR("CField::solveGridReference(void)",
894              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
895      }
896      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty() || !scalar_ref.isEmpty()))
897      {
898        ERROR("CField::solveGridReference(void)",
899              << "Field '" << getFieldOutputName() << "' has both a grid and a domain/axis/scalar." << std::endl
900              << "Please define either 'grid_ref' or 'domain_ref'/'axis_ref'/'scalar_ref'.");
901      }
902
903      if (grid_ref.isEmpty())
904      {
905        std::vector<CDomain*> vecDom;
906        std::vector<CAxis*> vecAxis;
907        std::vector<CScalar*> vecScalar;
908        std::vector<int> axisDomainOrderTmp;
909       
910        if (!domain_ref.isEmpty())
911        {
912          StdString tmp = domain_ref.getValue();
913          if (CDomain::has(domain_ref))
914          {
915            vecDom.push_back(CDomain::get(domain_ref));
916            axisDomainOrderTmp.push_back(2);
917          }
918          else
919            ERROR("CField::solveGridReference(void)",
920                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
921        }
922
923        if (!axis_ref.isEmpty())
924        {
925          if (CAxis::has(axis_ref))
926          {
927            vecAxis.push_back(CAxis::get(axis_ref));
928            axisDomainOrderTmp.push_back(1);
929          }
930          else
931            ERROR("CField::solveGridReference(void)",
932                  << "Invalid reference to axis '" << axis_ref.getValue() << "'.");
933        }
934
935        if (!scalar_ref.isEmpty())
936        {
937          if (CScalar::has(scalar_ref))
938          {
939            vecScalar.push_back(CScalar::get(scalar_ref));
940            axisDomainOrderTmp.push_back(0);
941          }
942          else
943            ERROR("CField::solveGridReference(void)",
944                  << "Invalid reference to scalar '" << scalar_ref.getValue() << "'.");
945        }
946       
947        CArray<int,1> axisDomainOrder(axisDomainOrderTmp.size());
948        for (int idx = 0; idx < axisDomainOrderTmp.size(); ++idx)
949        {
950          axisDomainOrder(idx) = axisDomainOrderTmp[idx];
951        }
952
953        // Warning: the gridId shouldn't be set as the grid_ref since it could be inherited
954        StdString gridId = CGrid::generateId(vecDom, vecAxis, vecScalar,axisDomainOrder);
955        if (CGrid::has(gridId))
956          this->grid = CGrid::get(gridId);
957        else
958          this->grid = CGrid::createGrid(gridId, vecDom, vecAxis, vecScalar,axisDomainOrder);
959      }
960      else
961      {
962        if (CGrid::has(grid_ref))
963          this->grid = CGrid::get(grid_ref);
964        else
965          ERROR("CField::solveGridReference(void)",
966                << "Invalid reference to grid '" << grid_ref.getValue() << "'.");
967      }
968   }
969
970   void CField::solveGridDomainAxisRef(bool checkAtt)
971   {
972     grid->solveDomainAxisRef(checkAtt);
973   }
974
975   void CField::solveCheckMaskIndex(bool doSendingIndex)
976   {
977     grid->checkMaskIndex(doSendingIndex);
978   }
979
980   void CField::solveTransformedGrid()
981   {
982     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
983     {
984       std::vector<CGrid*> grids;
985       // Source grid
986       grids.push_back(getDirectFieldReference()->grid);
987       // Intermediate grids
988       if (!grid_path.isEmpty())
989       {
990         std::string gridId;
991         size_t start = 0, end;
992
993         do
994         {
995           end = grid_path.getValue().find(',', start);
996           if (end != std::string::npos)
997           {
998             gridId = grid_path.getValue().substr(start, end - start);
999             start = end + 1;
1000           }
1001           else
1002             gridId = grid_path.getValue().substr(start);
1003
1004           if (!CGrid::has(gridId))
1005             ERROR("void CField::solveTransformedGrid()",
1006                   << "Invalid grid_path, the grid '" << gridId << "' does not exist.");
1007
1008           grids.push_back(CGrid::get(gridId));
1009         }
1010         while (end != std::string::npos);
1011       }
1012       // Destination grid
1013       grids.push_back(grid);
1014
1015       for (size_t i = 0, count = grids.size() - 1; i < count; ++i)
1016       {
1017         CGrid *gridSrc  = grids[i];
1018         CGrid *gridDest = grids[i + 1];
1019         if (!gridDest->isTransformed())
1020           gridDest->transformGrid(gridSrc);
1021       }
1022     }
1023     else if (grid && grid->hasTransform() && !grid->isTransformed())
1024     {
1025       grid->transformGrid(grid);
1026     }
1027   }
1028
1029   void CField::solveGenerateGrid()
1030   {
1031     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
1032       grid->completeGrid(getDirectFieldReference()->grid);
1033     else
1034       grid->completeGrid();
1035   }
1036
1037   void CField::solveGridDomainAxisBaseRef()
1038   {
1039     grid->solveDomainAxisRef(false);
1040     grid->solveDomainAxisBaseRef();
1041   }
1042
1043   ///-------------------------------------------------------------------
1044
1045   template <>
1046   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
1047   {
1048      if (this->group_ref.isEmpty()) return;
1049      StdString gref = this->group_ref.getValue();
1050
1051      if (!CFieldGroup::has(gref))
1052         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
1053               << "[ gref = " << gref << "]"
1054               << " invalid group name !");
1055
1056      CFieldGroup* group = CFieldGroup::get(gref);
1057      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
1058
1059      std::vector<CField*> allChildren  = group->getAllChildren();
1060      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
1061
1062      for (; it != end; it++)
1063      {
1064         CField* child = *it;
1065         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
1066
1067      }
1068   }
1069
1070   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
1071   {
1072     map<int, CArray<double,1> >::iterator it;
1073     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
1074   }
1075
1076   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
1077   {
1078     map<int, CArray<double,1> >::iterator it;
1079     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
1080   }
1081
1082   void CField::outputField(CArray<double,3>& fieldOut)
1083   {
1084      map<int, CArray<double,1> >::iterator it;
1085      for (it = data_srv.begin(); it != data_srv.end(); it++)
1086      {
1087        grid->outputField(it->first, it->second, fieldOut.dataFirst());
1088      }
1089   }
1090
1091   void CField::outputField(CArray<double,2>& fieldOut)
1092   {
1093      map<int, CArray<double,1> >::iterator it;
1094      for(it=data_srv.begin();it!=data_srv.end();it++)
1095      {
1096         grid->outputField(it->first, it->second, fieldOut.dataFirst());
1097      }
1098   }
1099
1100   void CField::outputField(CArray<double,1>& fieldOut)
1101   {
1102      map<int, CArray<double,1> >::iterator it;
1103
1104      for (it = data_srv.begin(); it != data_srv.end(); it++)
1105      {
1106         grid->outputField(it->first, it->second, fieldOut.dataFirst());
1107      }
1108   }
1109
1110   void CField::inputField(CArray<double,3>& fieldOut)
1111   {
1112      map<int, CArray<double,1> >::iterator it;
1113      for (it = data_srv.begin(); it != data_srv.end(); it++)
1114      {
1115        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
1116      }
1117   }
1118
1119   void CField::inputField(CArray<double,2>& fieldOut)
1120   {
1121      map<int, CArray<double,1> >::iterator it;
1122      for(it = data_srv.begin(); it != data_srv.end(); it++)
1123      {
1124         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
1125      }
1126   }
1127
1128   void CField::inputField(CArray<double,1>& fieldOut)
1129   {
1130      map<int, CArray<double,1> >::iterator it;
1131      for (it = data_srv.begin(); it != data_srv.end(); it++)
1132      {
1133         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
1134      }
1135   }
1136
1137   void CField::outputCompressedField(CArray<double,1>& fieldOut)
1138   {
1139      map<int, CArray<double,1> >::iterator it;
1140
1141      for (it = data_srv.begin(); it != data_srv.end(); it++)
1142      {
1143         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
1144      }
1145   }
1146
1147   ///-------------------------------------------------------------------
1148
1149   void CField::parse(xml::CXMLNode& node)
1150   {
1151      SuperClass::parse(node);
1152      if (!node.getContent(this->content))
1153      {
1154        if (node.goToChildElement())
1155        {
1156          do
1157          {
1158            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
1159          } while (node.goToNextElement());
1160          node.goToParentElement();
1161        }
1162      }
1163    }
1164
1165   /*!
1166     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
1167   of a field. In some cases, only domain exists but axis doesn't
1168   \return pair of Domain and Axis id
1169   */
1170   const std::vector<StdString>& CField::getRefDomainAxisIds()
1171   {
1172     CGrid* cgPtr = getRelGrid();
1173     if (NULL != cgPtr)
1174     {
1175       std::vector<StdString>::iterator it;
1176       if (!domain_ref.isEmpty())
1177       {
1178         std::vector<StdString> domainList = cgPtr->getDomainList();
1179         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
1180         if (domainList.end() != it) domAxisScalarIds_[0] = *it;
1181       }
1182
1183       if (!axis_ref.isEmpty())
1184       {
1185         std::vector<StdString> axisList = cgPtr->getAxisList();
1186         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
1187         if (axisList.end() != it) domAxisScalarIds_[1] = *it;
1188       }
1189
1190       if (!scalar_ref.isEmpty())
1191       {
1192         std::vector<StdString> scalarList = cgPtr->getScalarList();
1193         it = std::find(scalarList.begin(), scalarList.end(), scalar_ref.getValue());
1194         if (scalarList.end() != it) domAxisScalarIds_[2] = *it;
1195       }
1196     }
1197     return (domAxisScalarIds_);
1198   }
1199
1200   CVariable* CField::addVariable(const string& id)
1201   {
1202     return vVariableGroup->createChild(id);
1203   }
1204
1205   CVariableGroup* CField::addVariableGroup(const string& id)
1206   {
1207     return vVariableGroup->createChildGroup(id);
1208   }
1209
1210   void CField::sendAddAllVariables()
1211   {
1212     if (!getAllVariables().empty())
1213     {
1214       // Firstly, it's necessary to add virtual variable group
1215       sendAddVariableGroup(getVirtualVariableGroup()->getId());
1216
1217       // Okie, now we can add to this variable group
1218       std::vector<CVariable*> allVar = getAllVariables();
1219       std::vector<CVariable*>::const_iterator it = allVar.begin();
1220       std::vector<CVariable*>::const_iterator itE = allVar.end();
1221
1222       for (; it != itE; ++it)
1223       {
1224         this->sendAddVariable((*it)->getId());
1225         (*it)->sendAllAttributesToServer();
1226         (*it)->sendValue();
1227       }
1228     }
1229   }
1230
1231   void CField::sendAddVariable(const string& id)
1232   {
1233    CContext* context = CContext::getCurrent();
1234
1235    if (!context->hasServer)
1236    {
1237       CContextClient* client = context->client;
1238
1239       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
1240       if (client->isServerLeader())
1241       {
1242         CMessage msg;
1243         msg << this->getId();
1244         msg << id;
1245         const std::list<int>& ranks = client->getRanksServerLeader();
1246         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1247           event.push(*itRank,1,msg);
1248         client->sendEvent(event);
1249       }
1250       else client->sendEvent(event);
1251    }
1252   }
1253
1254   void CField::sendAddVariableGroup(const string& id)
1255   {
1256    CContext* context = CContext::getCurrent();
1257    if (!context->hasServer)
1258    {
1259       CContextClient* client = context->client;
1260
1261       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
1262       if (client->isServerLeader())
1263       {
1264         CMessage msg;
1265         msg << this->getId();
1266         msg << id;
1267         const std::list<int>& ranks = client->getRanksServerLeader();
1268         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1269           event.push(*itRank,1,msg);
1270         client->sendEvent(event);
1271       }
1272       else client->sendEvent(event);
1273    }
1274   }
1275
1276   void CField::recvAddVariable(CEventServer& event)
1277   {
1278
1279      CBufferIn* buffer = event.subEvents.begin()->buffer;
1280      string id;
1281      *buffer >> id;
1282      get(id)->recvAddVariable(*buffer);
1283   }
1284
1285   void CField::recvAddVariable(CBufferIn& buffer)
1286   {
1287      string id;
1288      buffer >> id;
1289      addVariable(id);
1290   }
1291
1292   void CField::recvAddVariableGroup(CEventServer& event)
1293   {
1294
1295      CBufferIn* buffer = event.subEvents.begin()->buffer;
1296      string id;
1297      *buffer >> id;
1298      get(id)->recvAddVariableGroup(*buffer);
1299   }
1300
1301   void CField::recvAddVariableGroup(CBufferIn& buffer)
1302   {
1303      string id;
1304      buffer >> id;
1305      addVariableGroup(id);
1306   }
1307
1308   DEFINE_REF_FUNC(Field,field)
1309} // namespace xios
Note: See TracBrowser for help on using the repository browser.