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

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

Implementing grid destination clone in case of two grid source

+) Clone attributes of grid destination as well as its transformation
+) Clean some redundant codes

Test
+) All tests pass

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