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

Last change on this file since 708 was 708, checked in by rlacroix, 9 years ago

Fix reading files in attached mode.

  • 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: 31.6 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      , refObject(), baseRefObject()
33      , grid(), file()
34      , written(false)
35      , nstep(0), nstepMax(0)
36      , hasOutputFile(false)
37      , domAxisIds_("", ""), areAllReferenceSolved(false)
38      , useCompressedOutput(false)
39      , isReadDataRequestPending(false)
40   { setVirtualVariableGroup(); }
41
42   CField::CField(const StdString& id)
43      : CObjectTemplate<CField>(id), CFieldAttributes()
44      , refObject(), baseRefObject()
45      , grid(), file()
46      , written(false)
47      , nstep(0), nstepMax(0)
48      , hasOutputFile(false)
49      , domAxisIds_("", ""), areAllReferenceSolved(false)
50      , useCompressedOutput(false)
51      , isReadDataRequestPending(false)
52   { setVirtualVariableGroup(); }
53
54   CField::~CField(void)
55   {}
56
57  //----------------------------------------------------------------
58
59   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
60   {
61      this->vVariableGroup = newVVariableGroup;
62   }
63
64   void CField::setVirtualVariableGroup(void)
65   {
66      this->setVirtualVariableGroup(CVariableGroup::create());
67   }
68
69   CVariableGroup* CField::getVirtualVariableGroup(void) const
70   {
71      return this->vVariableGroup;
72   }
73
74
75   std::vector<CVariable*> CField::getAllVariables(void) const
76   {
77      return this->vVariableGroup->getAllChildren();
78   }
79
80   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
81   {
82      SuperClassAttribute::setAttributes(parent, apply);
83      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
84   }
85
86  //----------------------------------------------------------------
87
88  bool CField::dispatchEvent(CEventServer& event)
89  {
90    if (SuperClass::dispatchEvent(event)) return true;
91    else
92    {
93      switch(event.type)
94      {
95        case EVENT_ID_UPDATE_DATA :
96          recvUpdateData(event);
97          return true;
98          break;
99
100        case EVENT_ID_READ_DATA :
101          recvReadDataRequest(event);
102          return true;
103          break;
104
105        case EVENT_ID_READ_DATA_READY :
106          recvReadDataReady(event);
107          return true;
108          break;
109
110        case EVENT_ID_ADD_VARIABLE :
111          recvAddVariable(event);
112          return true;
113          break;
114
115        case EVENT_ID_ADD_VARIABLE_GROUP :
116          recvAddVariableGroup(event);
117          return true;
118          break;
119
120        default :
121          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
122          return false;
123      }
124    }
125  }
126
127  void CField::sendUpdateData(const CArray<double,1>& data)
128  {
129    CTimer::get("XIOS Send Data").resume();
130
131    CContext* context = CContext::getCurrent();
132    CContextClient* client = context->client;
133
134    CEventClient event(getType(), EVENT_ID_UPDATE_DATA);
135
136    map<int, CArray<int,1> >::iterator it;
137    list<CMessage> list_msg;
138    list<CArray<double,1> > list_data;
139
140    if (!grid->doGridHaveDataDistributed())
141    {
142       if (0 == client->clientRank)
143       {
144          for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
145          {
146            int rank = it->first;
147            CArray<int,1>& index = it->second;
148
149            list_msg.push_back(CMessage());
150            list_data.push_back(CArray<double,1>(index.numElements()));
151
152            CArray<double,1>& data_tmp = list_data.back();
153            for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
154
155            list_msg.back() << getId() << data_tmp;
156            event.push(rank, 1, list_msg.back());
157          }
158          client->sendEvent(event);
159       } else client->sendEvent(event);
160    }
161    else
162    {
163      for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
164      {
165        int rank = it->first;
166        CArray<int,1>& index = it->second;
167
168        list_msg.push_back(CMessage());
169        list_data.push_back(CArray<double,1>(index.numElements()));
170
171        CArray<double,1>& data_tmp = list_data.back();
172        for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
173
174        list_msg.back() << getId() << data_tmp;
175        event.push(rank, grid->nbSenders[rank], list_msg.back());
176      }
177      client->sendEvent(event);
178    }
179
180    CTimer::get("XIOS Send Data").suspend();
181  }
182
183  void CField::recvUpdateData(CEventServer& event)
184  {
185    vector<int> ranks;
186    vector<CBufferIn*> buffers;
187
188    list<CEventServer::SSubEvent>::iterator it;
189    string fieldId;
190
191    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
192    {
193      int rank = it->rank;
194      CBufferIn* buffer = it->buffer;
195      *buffer >> fieldId;
196      ranks.push_back(rank);
197      buffers.push_back(buffer);
198    }
199    get(fieldId)->recvUpdateData(ranks,buffers);
200  }
201
202  void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
203  {
204    if (data_srv.empty())
205    {
206      for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
207      {
208        int rank = it->first;
209        data_srv.insert(std::make_pair(rank, CArray<double,1>(it->second.numElements())));
210        foperation_srv.insert(pair<int,boost::shared_ptr<func::CFunctor> >(rank,boost::shared_ptr<func::CFunctor>(new func::CInstant(data_srv[rank]))));
211      }
212    }
213
214    CContext* context = CContext::getCurrent();
215    const CDate& currDate = context->getCalendar()->getCurrentDate();
216    const CDate opeDate      = last_operation_srv + freq_operation_srv;
217    const CDate writeDate    = last_Write_srv     + freq_write_srv;
218
219    if (opeDate <= currDate)
220    {
221      for (int n = 0; n < ranks.size(); n++)
222      {
223        CArray<double,1> data_tmp;
224        *buffers[n] >> data_tmp;
225        (*foperation_srv[ranks[n]])(data_tmp);
226      }
227      last_operation_srv = currDate;
228    }
229
230    if (writeDate < (currDate + freq_operation_srv))
231    {
232      for (int n = 0; n < ranks.size(); n++)
233      {
234        this->foperation_srv[ranks[n]]->final();
235      }
236
237      last_Write_srv = writeDate;
238      writeField();
239      lastlast_Write_srv = last_Write_srv;
240    }
241  }
242
243  void CField::writeField(void)
244  {
245    if (!getRelFile()->allDomainEmpty)
246    {
247      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
248      {
249        getRelFile()->checkFile();
250        this->incrementNStep();
251        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
252      }
253    }
254  }
255
256  void CField::sendReadDataRequest(void)
257  {
258    CContext* context = CContext::getCurrent();
259    CContextClient* client = context->client;
260
261    lastDataRequestedFromServer = context->getCalendar()->getCurrentDate();
262    isReadDataRequestPending = true;
263
264    CEventClient event(getType(), EVENT_ID_READ_DATA);
265    if (client->isServerLeader())
266    {
267      CMessage msg;
268      msg << getId();
269      const std::list<int>& ranks = client->getRanksServerLeader();
270      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
271        event.push(*itRank, 1, msg);
272      client->sendEvent(event);
273    }
274    else client->sendEvent(event);
275  }
276
277  /*!
278  Send request new data read from file if need be, that is the current data is out-of-date.
279  \return true if and only if some data was requested
280  */
281  bool CField::sendReadDataRequestIfNeeded(void)
282  {
283    const CDate& currentDate = CContext::getCurrent()->getCalendar()->getCurrentDate();
284
285    bool requestData = (currentDate >= lastDataRequestedFromServer + file->output_freq.getValue());
286
287    if (requestData)
288      sendReadDataRequest();
289
290    return requestData;
291  }
292
293  void CField::recvReadDataRequest(CEventServer& event)
294  {
295    CBufferIn* buffer = event.subEvents.begin()->buffer;
296    StdString fieldId;
297    *buffer >> fieldId;
298    get(fieldId)->recvReadDataRequest();
299  }
300
301  void CField::recvReadDataRequest(void)
302  {
303    CContext* context = CContext::getCurrent();
304    CContextClient* client = context->client;
305
306    CEventClient event(getType(), EVENT_ID_READ_DATA_READY);
307    std::list<CMessage> msgs;
308
309    bool hasData = readField();
310
311    map<int, CArray<double,1> >::iterator it;
312    for (it = data_srv.begin(); it != data_srv.end(); it++)
313    {
314      msgs.push_back(CMessage());
315      CMessage& msg = msgs.back();
316      msg << getId();
317      if (hasData)
318        msg << getNStep() - 1 << it->second;
319      else
320        msg << size_t(-1);
321      event.push(it->first, grid->nbSenders[it->first], msg);
322    }
323    client->sendEvent(event);
324  }
325
326  bool CField::readField(void)
327  {
328    if (!getRelFile()->allDomainEmpty)
329    {
330      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
331      {
332        if (data_srv.empty())
333        {
334          for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
335            data_srv.insert(std::make_pair(it->first, CArray<double,1>(it->second.numElements())));
336        }
337
338        getRelFile()->checkFile();
339        this->incrementNStep();
340
341        if (!nstepMax)
342        {
343          nstepMax = getRelFile()->getDataInput()->getFieldNbRecords(CField::get(this));
344        }
345
346        if (getNStep() > nstepMax)
347          return false;
348
349        getRelFile()->getDataInput()->readFieldData(CField::get(this));
350      }
351    }
352
353    return true;
354  }
355
356  void CField::recvReadDataReady(CEventServer& event)
357  {
358    string fieldId;
359    vector<int> ranks;
360    vector<CBufferIn*> buffers;
361
362    list<CEventServer::SSubEvent>::iterator it;
363    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
364    {
365      ranks.push_back(it->rank);
366      CBufferIn* buffer = it->buffer;
367      *buffer >> fieldId;
368      buffers.push_back(buffer);
369    }
370    get(fieldId)->recvReadDataReady(ranks, buffers);
371  }
372
373  void CField::recvReadDataReady(vector<int> ranks, vector<CBufferIn*> buffers)
374  {
375    CContext* context = CContext::getCurrent();
376    StdSize record;
377    std::map<int, CArray<double,1> > data;
378
379    bool isEOF = false;
380
381    for (int i = 0; i < ranks.size(); i++)
382    {
383      int rank = ranks[i];
384      *buffers[i] >> record;
385      isEOF = (record == size_t(-1));
386
387      if (!isEOF)
388        *buffers[i] >> data[rank];
389      else
390        break;
391    }
392
393    if (isEOF)
394      serverSourceFilter->signalEndOfStream(lastDataRequestedFromServer);
395    else
396      serverSourceFilter->streamDataFromServer(lastDataRequestedFromServer, data);
397
398    isReadDataRequestPending = false;
399  }
400
401   //----------------------------------------------------------------
402
403   void CField::setRelFile(CFile* _file)
404   {
405      this->file = _file;
406      hasOutputFile = true;
407   }
408
409   //----------------------------------------------------------------
410
411   StdString CField::GetName(void)    { return StdString("field"); }
412   StdString CField::GetDefName(void) { return CField::GetName(); }
413   ENodeType CField::GetType(void)    { return eField; }
414
415   //----------------------------------------------------------------
416
417   CGrid* CField::getRelGrid(void) const
418   {
419      return this->grid;
420   }
421
422   //----------------------------------------------------------------
423
424   CFile* CField::getRelFile(void) const
425   {
426      return this->file;
427   }
428
429   StdSize CField::getNStep(void) const
430   {
431      return this->nstep;
432   }
433
434   func::CFunctor::ETimeType CField::getOperationTimeType() const
435   {
436     return operationTimeType;
437   }
438
439   //----------------------------------------------------------------
440
441   void CField::incrementNStep(void)
442   {
443      this->nstep++;
444   }
445
446   void CField::resetNStep(StdSize nstep /*= 0*/)
447   {
448      this->nstep = nstep;
449   }
450
451   void CField::resetNStepMax(void)
452   {
453      this->nstepMax = 0;
454   }
455
456   //----------------------------------------------------------------
457
458   bool CField::isActive(void) const
459   {
460      return !this->refObject.empty();
461   }
462
463   //----------------------------------------------------------------
464
465   bool CField::wasWritten() const
466   {
467     return written;
468   }
469
470   void CField::setWritten()
471   {
472     written = true;
473   }
474
475   //----------------------------------------------------------------
476
477   bool CField::getUseCompressedOutput() const
478   {
479     return useCompressedOutput;
480   }
481
482   void CField::setUseCompressedOutput()
483   {
484     useCompressedOutput = true;
485   }
486
487   //----------------------------------------------------------------
488
489   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
490   {
491     return instantDataFilter;
492   }
493
494   //----------------------------------------------------------------
495
496   void CField::solveAllReferenceEnabledField(bool doSending2Sever)
497   {
498     CContext* context = CContext::getCurrent();
499     if (!areAllReferenceSolved)
500     {
501        areAllReferenceSolved = true;
502
503        if (context->hasClient)
504        {
505          solveRefInheritance(true);
506          solveBaseReference();
507          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
508        }
509        else if (context->hasServer)
510          solveServerOperation();
511
512        solveGridReference();
513     }
514     if (context->hasClient)
515     {
516       solveGenerateGrid();
517     }
518
519     solveGridDomainAxisRef(doSending2Sever);
520
521     if (context->hasClient)
522     {
523       solveTransformedGrid();
524     }
525
526     solveCheckMaskIndex(doSending2Sever);
527   }
528
529   std::map<int, StdSize> CField::getGridDataSize()
530   {
531     return grid->getConnectedServerDataSize();
532   }
533
534   //----------------------------------------------------------------
535
536   void CField::solveServerOperation(void)
537   {
538      CContext* context = CContext::getCurrent();
539
540      if (!context->hasServer || !hasOutputFile) return;
541
542      if (freq_op.isEmpty())
543        freq_op.setValue(TimeStep);
544
545      if (freq_offset.isEmpty())
546        freq_offset.setValue(NoneDu);
547
548      freq_operation_srv = file->output_freq.getValue();
549      freq_write_srv     = file->output_freq.getValue();
550
551      lastlast_Write_srv = context->getCalendar()->getInitDate();
552      last_Write_srv     = context->getCalendar()->getInitDate();
553      last_operation_srv = context->getCalendar()->getInitDate();
554
555      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
556      last_operation_srv     = last_operation_srv - toffset;
557
558      if (operation.isEmpty())
559        ERROR("void CField::solveServerOperation(void)",
560              << "An operation must be defined for field \"" << getId() << "\".");
561
562      boost::shared_ptr<func::CFunctor> functor;
563      CArray<double, 1> dummyData;
564
565#define DECLARE_FUNCTOR(MType, mtype) \
566      if (operation.getValue().compare(#mtype) == 0) \
567      { \
568        functor.reset(new func::C##MType(dummyData)); \
569      }
570
571#include "functor_type.conf"
572
573      if (!functor)
574        ERROR("void CField::solveServerOperation(void)",
575              << "\"" << operation << "\" is not a valid operation.");
576
577      operationTimeType = functor->timeType();
578   }
579
580   //----------------------------------------------------------------
581
582   /*!
583    * Constructs the graph filter for the field, enabling or not the data output.
584    * This method should not be called more than once with enableOutput equal to true.
585    *
586    * \param gc the garbage collector to use when building the filter graph
587    * \param enableOutput must be true when the field data is to be
588    *                     read by the client or/and written to a file
589    */
590   void CField::buildFilterGraph(CGarbageCollector& gc, bool enableOutput)
591   {
592     if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
593
594     // Start by building a filter which can provide the field's instant data
595     if (!instantDataFilter)
596     {
597       // Check if we have an expression to parse
598       if (!content.empty())
599       {
600         boost::scoped_ptr<IFilterExprNode> expr(parseExpr(content + '\0'));
601         instantDataFilter = expr->reduce(gc, *this);
602       }
603       // Check if we have a reference on another field
604       else if (!field_ref.isEmpty())
605       {
606         CField* fieldRef = CField::get(field_ref);
607         fieldRef->buildFilterGraph(gc, false);
608
609         std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters;
610         // Check if a spatial transformation is needed
611         if (!grid_ref.isEmpty() && !fieldRef->grid_ref.isEmpty() && grid_ref.getValue() != fieldRef->grid_ref.getValue())
612           filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid);
613         else
614           filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
615
616         fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
617         instantDataFilter = filters.second;
618       }
619       // Check if the data is to be read from a file
620       else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
621         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
622       else // The data might be passed from the model
623         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
624     }
625
626     // If the field data is to be read by the client or/and written to a file
627     if (enableOutput && !storeFilter && !fileWriterFilter)
628     {
629       if (!read_access.isEmpty() && read_access.getValue())
630       {
631         storeFilter = boost::shared_ptr<CStoreFilter>(new CStoreFilter(gc, CContext::getCurrent(), grid));
632         instantDataFilter->connectOutput(storeFilter, 0);
633       }
634
635       if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
636       {
637         fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
638         getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
639       }
640     }
641   }
642
643   /*!
644    * Returns the source filter to handle a self reference in the field's expression.
645    * If the needed source filter does not exist, it is created, otherwise it is reused.
646    * This method should only be called when building the filter graph corresponding
647    * to the field's expression.
648    *
649    * \param gc the garbage collector to use
650    * \return the output pin corresponding to a self reference
651    */
652   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
653   {
654     if (instantDataFilter || content.empty())
655       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
656             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
657
658     if (!clientSourceFilter)
659       clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(grid));
660
661     return clientSourceFilter;
662   }
663
664   /*!
665    * Returns the temporal filter corresponding to the field's temporal operation
666    * for the specified operation frequency. The filter is created if it does not
667    * exist, otherwise it is reused.
668    *
669    * \param gc the garbage collector to use
670    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
671    * \return the output pin corresponding to the requested temporal filter
672    */
673   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
674   {
675     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
676
677     if (it == temporalDataFilters.end())
678     {
679       if (operation.isEmpty())
680         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
681               << "An operation must be defined for field \"" << getId() << "\".");
682
683       if (freq_op.isEmpty())
684         freq_op.setValue(TimeStep);
685       if (freq_offset.isEmpty())
686         freq_offset.setValue(NoneDu);
687
688       const bool ignoreMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
689
690       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
691                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
692                                                                             freq_op, freq_offset, outFreq,
693                                                                             ignoreMissingValue, ignoreMissingValue ? default_value : 0.0));
694       instantDataFilter->connectOutput(temporalFilter, 0);
695
696       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
697     }
698
699     return it->second;
700   }
701
702   //----------------------------------------------------------------
703/*
704   void CField::fromBinary(StdIStream& is)
705   {
706      SuperClass::fromBinary(is);
707#define CLEAR_ATT(name_)\
708      SuperClassAttribute::operator[](#name_)->reset()
709
710         CLEAR_ATT(domain_ref);
711         CLEAR_ATT(axis_ref);
712#undef CLEAR_ATT
713
714   }
715*/
716   //----------------------------------------------------------------
717
718   void CField::solveGridReference(void)
719   {
720      CDomain* domain;
721      CAxis* axis;
722      std::vector<CDomain*> vecDom;
723      std::vector<CAxis*> vecAxis;
724      std::vector<std::string> domList, axisList;
725
726      if (!domain_ref.isEmpty())
727      {
728         if (CDomain::has(domain_ref.getValue()))
729         {
730           domain = CDomain::get(domain_ref.getValue());
731           vecDom.push_back(domain);
732         }
733         else
734            ERROR("CField::solveGridReference(void)",
735                  << "Reference to the domain \'"
736                  << domain_ref.getValue() << "\' is wrong");
737      }
738
739      if (!axis_ref.isEmpty())
740      {
741         if (CAxis::has(axis_ref.getValue()))
742         {
743           axis = CAxis::get(axis_ref.getValue());
744           vecAxis.push_back(axis);
745         }
746         else
747            ERROR("CField::solveGridReference(void)",
748                  << "Reference to the axis \'"
749                  << axis_ref.getValue() <<"\' is wrong");
750      }
751
752      if (!grid_ref.isEmpty())
753      {
754         if (CGrid::has(grid_ref.getValue()))
755         {
756           this->grid = CGrid::get(grid_ref.getValue());
757           domList = grid->getDomainList();
758           axisList = grid->getAxisList();
759           if (domList.empty() && axisList.empty())
760           {
761             this->grid = CGrid::createGrid(vecDom, vecAxis);
762           }
763         }
764         else
765            ERROR("CField::solveGridReference(void)",
766                  << "Reference to the grid \'"
767                  << grid_ref.getValue() << "\' is wrong");
768      }
769      else
770      {
771         this->grid = CGrid::createGrid(vecDom, vecAxis);
772      }
773
774      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty())
775      {
776            ERROR("CField::solveGridReference(void)",
777                  << "At least one dimension must be defined for this field.");
778      }
779   }
780
781   void CField::solveGridDomainAxisRef(bool checkAtt)
782   {
783     grid->solveDomainAxisRef(checkAtt);
784   }
785
786   void CField::solveCheckMaskIndex(bool doSendingIndex)
787   {
788     grid->checkMaskIndex(doSendingIndex);
789   }
790
791   void CField::solveTransformedGrid()
792   {
793     if (!grid_ref.isEmpty() && hasDirectFieldReference() && !getDirectFieldReference()->grid_ref.isEmpty()
794         && grid_ref.getValue() != getDirectFieldReference()->grid_ref.getValue() && !grid->isTransformed())
795       grid->transformGrid(getDirectFieldReference()->grid);
796   }
797
798   void CField::solveGenerateGrid()
799   {
800     if (!grid_ref.isEmpty() && hasDirectFieldReference() && !getDirectFieldReference()->grid_ref.isEmpty()
801         && grid_ref.getValue() != getDirectFieldReference()->grid_ref.getValue() && !grid->isTransformed())
802       grid->completeGrid(getDirectFieldReference()->grid);
803   }
804
805   ///-------------------------------------------------------------------
806
807   template <>
808   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
809   {
810      if (this->group_ref.isEmpty()) return;
811      StdString gref = this->group_ref.getValue();
812
813      if (!CFieldGroup::has(gref))
814         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
815               << "[ gref = " << gref << "]"
816               << " invalid group name !");
817
818      CFieldGroup* group = CFieldGroup::get(gref);
819      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
820
821      std::vector<CField*> allChildren  = group->getAllChildren();
822      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
823
824      for (; it != end; it++)
825      {
826         CField* child = *it;
827         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
828
829      }
830   }
831
832   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
833   {
834     map<int, CArray<double,1> >::iterator it;
835     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
836   }
837
838   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
839   {
840     map<int, CArray<double,1> >::iterator it;
841     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
842   }
843
844   void CField::outputField(CArray<double,3>& fieldOut)
845   {
846      map<int, CArray<double,1> >::iterator it;
847      for (it = data_srv.begin(); it != data_srv.end(); it++)
848      {
849        grid->outputField(it->first, it->second, fieldOut.dataFirst());
850      }
851   }
852
853   void CField::outputField(CArray<double,2>& fieldOut)
854   {
855      map<int, CArray<double,1> >::iterator it;
856      for(it=data_srv.begin();it!=data_srv.end();it++)
857      {
858         grid->outputField(it->first, it->second, fieldOut.dataFirst());
859      }
860   }
861
862   void CField::outputField(CArray<double,1>& fieldOut)
863   {
864      map<int, CArray<double,1> >::iterator it;
865
866      for (it = data_srv.begin(); it != data_srv.end(); it++)
867      {
868         grid->outputField(it->first, it->second, fieldOut.dataFirst());
869      }
870   }
871
872   void CField::inputField(CArray<double,3>& fieldOut)
873   {
874      map<int, CArray<double,1> >::iterator it;
875      for (it = data_srv.begin(); it != data_srv.end(); it++)
876      {
877        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
878      }
879   }
880
881   void CField::inputField(CArray<double,2>& fieldOut)
882   {
883      map<int, CArray<double,1> >::iterator it;
884      for(it = data_srv.begin(); it != data_srv.end(); it++)
885      {
886         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
887      }
888   }
889
890   void CField::inputField(CArray<double,1>& fieldOut)
891   {
892      map<int, CArray<double,1> >::iterator it;
893      for (it = data_srv.begin(); it != data_srv.end(); it++)
894      {
895         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
896      }
897   }
898
899   void CField::outputCompressedField(CArray<double,1>& fieldOut)
900   {
901      map<int, CArray<double,1> >::iterator it;
902
903      for (it = data_srv.begin(); it != data_srv.end(); it++)
904      {
905         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
906      }
907   }
908
909   ///-------------------------------------------------------------------
910
911   void CField::parse(xml::CXMLNode& node)
912   {
913      SuperClass::parse(node);
914      if (!node.getContent(this->content))
915      {
916        if (node.goToChildElement())
917        {
918          do
919          {
920            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
921          } while (node.goToNextElement());
922          node.goToParentElement();
923        }
924      }
925    }
926
927   /*!
928     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
929   of a field. In some cases, only domain exists but axis doesn't
930   \return pair of Domain and Axis id
931   */
932   const std::pair<StdString,StdString>& CField::getRefDomainAxisIds()
933   {
934     CGrid* cgPtr = getRelGrid();
935     if (NULL != cgPtr)
936     {
937       std::vector<StdString>::iterator it;
938       if (!domain_ref.isEmpty())
939       {
940         std::vector<StdString> domainList = cgPtr->getDomainList();
941         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
942         if (domainList.end() != it) domAxisIds_.first = *it;
943       }
944
945       if (!axis_ref.isEmpty())
946       {
947         std::vector<StdString> axisList = cgPtr->getAxisList();
948         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
949         if (axisList.end() != it) domAxisIds_.second = *it;
950       }
951     }
952     return (domAxisIds_);
953   }
954
955   CVariable* CField::addVariable(const string& id)
956   {
957     return vVariableGroup->createChild(id);
958   }
959
960   CVariableGroup* CField::addVariableGroup(const string& id)
961   {
962     return vVariableGroup->createChildGroup(id);
963   }
964
965   void CField::sendAddAllVariables()
966   {
967     if (!getAllVariables().empty())
968     {
969       // Firstly, it's necessary to add virtual variable group
970       sendAddVariableGroup(getVirtualVariableGroup()->getId());
971
972       // Okie, now we can add to this variable group
973       std::vector<CVariable*> allVar = getAllVariables();
974       std::vector<CVariable*>::const_iterator it = allVar.begin();
975       std::vector<CVariable*>::const_iterator itE = allVar.end();
976
977       for (; it != itE; ++it)
978       {
979         this->sendAddVariable((*it)->getId());
980         (*it)->sendAllAttributesToServer();
981         (*it)->sendValue();
982       }
983     }
984   }
985
986   void CField::sendAddVariable(const string& id)
987   {
988    CContext* context = CContext::getCurrent();
989
990    if (!context->hasServer)
991    {
992       CContextClient* client = context->client;
993
994       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
995       if (client->isServerLeader())
996       {
997         CMessage msg;
998         msg << this->getId();
999         msg << id;
1000         const std::list<int>& ranks = client->getRanksServerLeader();
1001         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1002           event.push(*itRank,1,msg);
1003         client->sendEvent(event);
1004       }
1005       else client->sendEvent(event);
1006    }
1007   }
1008
1009   void CField::sendAddVariableGroup(const string& id)
1010   {
1011    CContext* context = CContext::getCurrent();
1012    if (!context->hasServer)
1013    {
1014       CContextClient* client = context->client;
1015
1016       CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
1017       if (client->isServerLeader())
1018       {
1019         CMessage msg;
1020         msg << this->getId();
1021         msg << id;
1022         const std::list<int>& ranks = client->getRanksServerLeader();
1023         for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1024           event.push(*itRank,1,msg);
1025         client->sendEvent(event);
1026       }
1027       else client->sendEvent(event);
1028    }
1029   }
1030
1031   void CField::recvAddVariable(CEventServer& event)
1032   {
1033
1034      CBufferIn* buffer = event.subEvents.begin()->buffer;
1035      string id;
1036      *buffer >> id;
1037      get(id)->recvAddVariable(*buffer);
1038   }
1039
1040   void CField::recvAddVariable(CBufferIn& buffer)
1041   {
1042      string id;
1043      buffer >> id;
1044      addVariable(id);
1045   }
1046
1047   void CField::recvAddVariableGroup(CEventServer& event)
1048   {
1049
1050      CBufferIn* buffer = event.subEvents.begin()->buffer;
1051      string id;
1052      *buffer >> id;
1053      get(id)->recvAddVariableGroup(*buffer);
1054   }
1055
1056   void CField::recvAddVariableGroup(CBufferIn& buffer)
1057   {
1058      string id;
1059      buffer >> id;
1060      addVariableGroup(id);
1061   }
1062
1063   DEFINE_REF_FUNC(Field,field)
1064} // namespace xios
Note: See TracBrowser for help on using the repository browser.