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

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

Updating 2-level server

+) Make some changes in the way data rebuilt on each level of server
+) Make some changes in the order of functions call during close context to make sure that each server receives the global indexes before calculating index to send to next level
+) Modify some functions to make sure data sent to the correct server pool

Test
+) On Curie
+) Only test_client

  • 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: 53.8 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#include "file_server_writer_filter.hpp"
26
27namespace xios{
28
29   /// ////////////////////// Définitions ////////////////////// ///
30
31   CField::CField(void)
32      : CObjectTemplate<CField>(), CFieldAttributes()
33      , grid(), file()
34      , written(false)
35      , nstep(0), nstepMax(0)
36      , hasOutputFile(false)
37      , domAxisScalarIds_(vector<StdString>(3,"")), areAllReferenceSolved(false), isReferenceSolved(false)
38      , useCompressedOutput(false)
39      , wasDataAlreadyReceivedFromServer(false)
40   { setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group")); }
41
42   CField::CField(const StdString& id)
43      : CObjectTemplate<CField>(id), CFieldAttributes()
44      , grid(), file()
45      , written(false)
46      , nstep(0), nstepMax(0)
47      , hasOutputFile(false)
48      , domAxisScalarIds_(vector<StdString>(3,"")), areAllReferenceSolved(false), isReferenceSolved(false)
49      , useCompressedOutput(false)
50      , wasDataAlreadyReceivedFromServer(false)
51   { setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group")); }
52
53   CField::~CField(void)
54   {}
55
56  //----------------------------------------------------------------
57
58   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
59   {
60      this->vVariableGroup = newVVariableGroup;
61   }
62
63   CVariableGroup* CField::getVirtualVariableGroup(void) const
64   {
65      return this->vVariableGroup;
66   }
67
68   std::vector<CVariable*> CField::getAllVariables(void) const
69   {
70      return this->vVariableGroup->getAllChildren();
71   }
72
73   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
74   {
75      SuperClassAttribute::setAttributes(parent, apply);
76      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
77   }
78
79  //----------------------------------------------------------------
80
81  bool CField::dispatchEvent(CEventServer& event)
82  {
83    if (SuperClass::dispatchEvent(event)) return true;
84    else
85    {
86      switch(event.type)
87      {
88        case EVENT_ID_UPDATE_DATA :
89          recvUpdateData(event);
90          return true;
91          break;
92
93        case EVENT_ID_READ_DATA :
94          recvReadDataRequest(event);
95          return true;
96          break;
97
98        case EVENT_ID_READ_DATA_READY :
99          recvReadDataReady(event);
100          return true;
101          break;
102
103        case EVENT_ID_ADD_VARIABLE :
104          recvAddVariable(event);
105          return true;
106          break;
107
108        case EVENT_ID_ADD_VARIABLE_GROUP :
109          recvAddVariableGroup(event);
110          return true;
111          break;
112
113        default :
114          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
115          return false;
116      }
117    }
118  }
119
120  void CField::sendUpdateData(const CArray<double,1>& data)
121  {
122    CTimer::get("XIOS Send Data").resume();
123
124    CContext* context = CContext::getCurrent();
125//    CContextClient* client = context->client;
126    // int nbSrvPools = (context->hasServer) ? context->clientPrimServer.size() : 1;
127    // int nbSrvPools = (context->hasServer) ? (context->hasClient ? context->clientPrimServer.size() : 0) : 1;
128    // for (int i = 0; i < nbSrvPools; ++i)
129    // {
130      CContextClient* client = (!context->hasServer) ? context->client : this->file->getContextClient();
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 (client->isServerLeader())
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         }
158         else client->sendEvent(event);
159      }
160      else
161      {
162        for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
163        {
164          int rank = it->first;
165          CArray<int,1>& index = it->second;
166
167          list_msg.push_back(CMessage());
168          list_data.push_back(CArray<double,1>(index.numElements()));
169
170          CArray<double,1>& data_tmp = list_data.back();
171          for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
172
173          list_msg.back() << getId() << data_tmp;
174          event.push(rank, grid->nbSenders[0][rank], list_msg.back());
175        }
176        client->sendEvent(event);
177      }
178    // }
179
180    CTimer::get("XIOS Send Data").suspend();
181  }
182
183  // void CField::sendUpdateData(const CArray<double,1>& data, CContextClient* client)
184  // {
185  //   CTimer::get("XIOS Send Data").resume();
186
187  //   CEventClient event(getType(), EVENT_ID_UPDATE_DATA);
188
189  //   map<int, CArray<int,1> >::iterator it;
190  //   list<CMessage> list_msg;
191  //   list<CArray<double,1> > list_data;
192
193  //   if (!grid->doGridHaveDataDistributed())
194  //   {
195  //      if (client->isServerLeader())
196  //      {
197  //         for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
198  //         {
199  //           int rank = it->first;
200  //           CArray<int,1>& index = it->second;
201
202  //           list_msg.push_back(CMessage());
203  //           list_data.push_back(CArray<double,1>(index.numElements()));
204
205  //           CArray<double,1>& data_tmp = list_data.back();
206  //           for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
207
208  //           list_msg.back() << getId() << data_tmp;
209  //           event.push(rank, 1, list_msg.back());
210  //         }
211  //         client->sendEvent(event);
212  //      }
213  //      else client->sendEvent(event);
214  //   }
215  //   else
216  //   {
217  //     for (it = grid->storeIndex_toSrv.begin(); it != grid->storeIndex_toSrv.end(); it++)
218  //     {
219  //       int rank = it->first;
220  //       CArray<int,1>& index = it->second;
221
222  //       list_msg.push_back(CMessage());
223  //       list_data.push_back(CArray<double,1>(index.numElements()));
224
225  //       CArray<double,1>& data_tmp = list_data.back();
226  //       for (int n = 0; n < data_tmp.numElements(); n++) data_tmp(n) = data(index(n));
227
228  //       list_msg.back() << getId() << data_tmp;
229  //       event.push(rank, grid->nbSenders[rank], list_msg.back());
230  //     }
231  //     client->sendEvent(event);
232  //   }
233  //   CTimer::get("XIOS Send Data").suspend();
234  // }
235
236  void CField::recvUpdateData(CEventServer& event)
237  {
238    std::map<int,CBufferIn*> rankBuffers;
239
240    list<CEventServer::SSubEvent>::iterator it;
241    string fieldId;
242
243    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
244    {
245      int rank = it->rank;
246      CBufferIn* buffer = it->buffer;
247      *buffer >> fieldId;
248      rankBuffers[rank] = buffer;
249    }
250    get(fieldId)->recvUpdateData(rankBuffers);
251  }
252
253  void  CField::recvUpdateData(std::map<int,CBufferIn*>& rankBuffers)
254  {
255    CContext* context = CContext::getCurrent();
256
257    size_t sizeData = 0;
258    if (0 == recvDataSrv.numElements())
259    {     
260      for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
261      {
262        sizeData += it->second.numElements();
263        data_srv.insert(std::make_pair(it->first, CArray<double,1>(it->second.numElements())));
264      }
265
266      // Gather all data from different clients
267      recvDataSrv.resize(sizeData);
268      recvFoperationSrv = boost::shared_ptr<func::CFunctor>(new func::CInstant(recvDataSrv));
269    }
270
271    CArray<double,1> recv_data_tmp(recvDataSrv.numElements());
272    // sizeData = 0;
273    const CDate& currDate = context->getCalendar()->getCurrentDate();
274    const CDate opeDate   = last_operation_srv +freq_op + freq_operation_srv - freq_op;
275
276    if (opeDate <= currDate)
277    {
278      for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
279      {       
280        CArray<double,1> tmp;
281        CArray<size_t,1>& indexTmp = it->second;
282        *(rankBuffers[it->first]) >> tmp;
283        for (int idx = 0; idx < indexTmp.numElements(); ++idx)
284        {
285          recv_data_tmp(indexTmp(idx)) = tmp(idx);
286        }
287        // recv_data_tmp(Range(sizeData,sizeData+it->second.numElements()-1)) = tmp; 
288        // sizeData += it->second.numElements();     
289      }
290    }
291
292    this->setData(recv_data_tmp);
293  }
294
295  void CField::writeUpdateData(const CArray<double,1>& data)
296  {
297    CContext* context = CContext::getCurrent();
298
299    const CDate& currDate = context->getCalendar()->getCurrentDate();
300    const CDate opeDate      = last_operation_srv +freq_op + freq_operation_srv - freq_op;
301    const CDate writeDate    = last_Write_srv     + freq_write_srv;
302
303    if (opeDate <= currDate)
304    {
305      (*recvFoperationSrv)(data);
306      last_operation_srv = currDate;
307//        sendUpdateData(fieldData);
308        // Redirecting data to the correct secondary server
309        //int fileIdx = std::find(context->enabledFiles.begin(), context->enabledFiles.end(), this->file) - context->enabledFiles.begin();
310        //int srvId = fileIdx % context->clientPrimServer.size();
311        //sendUpdateData(fieldData, context->clientPrimServer[srvId]);
312    }
313
314    if (writeDate < (currDate + freq_operation_srv))
315    {
316      recvFoperationSrv->final();
317      last_Write_srv = writeDate;
318      writeField();
319      lastlast_Write_srv = last_Write_srv;
320    }
321  }
322 
323//   void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
324//   {
325//     CContext* context = CContext::getCurrent();
326
327//     if (data_srv.empty())
328//     {
329//       for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
330//       {
331//         int rank = it->first;
332//         data_srv.insert(std::make_pair(rank, CArray<double,1>(it->second.numElements())));
333//         foperation_srv.insert(pair<int,boost::shared_ptr<func::CFunctor> >(rank,boost::shared_ptr<func::CFunctor>(new func::CInstant(data_srv[rank]))));
334//       }
335//     }
336
337//     const CDate& currDate = context->getCalendar()->getCurrentDate();
338//     const CDate opeDate      = last_operation_srv +freq_op + freq_operation_srv - freq_op;
339//     const CDate writeDate    = last_Write_srv     + freq_write_srv;
340
341//     if (opeDate <= currDate)
342//     {
343//       for (int n = 0; n < ranks.size(); n++)
344//       {
345//         CArray<double,1> data_tmp;
346//         *buffers[n] >> data_tmp;
347//         (*foperation_srv[ranks[n]])(data_tmp);
348//       }
349//       last_operation_srv = currDate;
350//     }
351
352//     if (writeDate < (currDate + freq_operation_srv))
353//     {
354//       for (int n = 0; n < ranks.size(); n++)
355//       {
356//         this->foperation_srv[ranks[n]]->final();
357//       }
358
359//       last_Write_srv = writeDate;
360//     }
361
362//     if (context->hasClient && context->hasServer)
363//     {
364//       size_t writtenSize;
365// //      if (field->getUseCompressedOutput())
366// //        writtenSize = grid->getNumberWrittenIndexes();
367// //      else
368//         writtenSize = grid->getWrittenDataSize();
369
370//       CArray<double,1> fieldData(writtenSize);
371// //      if (!field->default_value.isEmpty()) fieldData = field->default_value;
372
373// //      if (field->getUseCompressedOutput())
374// //        field->outputCompressedField(fieldData);
375// //      else
376//         this->outputField(fieldData);
377//       sendUpdateData(fieldData);
378//     }
379//     if (!context->hasClient && context->hasServer)
380//     {
381//       writeField();
382//     }
383
384//     lastlast_Write_srv = last_Write_srv;
385
386//   }
387
388  void CField::writeField(void)
389  {
390    if (!getRelFile()->allDomainEmpty)
391    {
392      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
393      {
394        getRelFile()->checkFile();
395        this->incrementNStep();
396        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
397      }
398    }
399  }
400
401  void CField::sendReadDataRequest(const CDate& tsDataRequested)
402  {
403    CContext* context = CContext::getCurrent();
404//    CContextClient* client = context->client;
405    CContextClient* client = (!context->hasServer) ? context->client : this->file->getContextClient();
406
407
408    lastDataRequestedFromServer = tsDataRequested;
409
410    CEventClient event(getType(), EVENT_ID_READ_DATA);
411    if (client->isServerLeader())
412    {
413      CMessage msg;
414      msg << getId();
415      const std::list<int>& ranks = client->getRanksServerLeader();
416      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
417        event.push(*itRank, 1, msg);
418      client->sendEvent(event);
419    }
420    else client->sendEvent(event);
421  }
422
423  /*!
424  Send request new data read from file if need be, that is the current data is out-of-date.
425  \return true if and only if some data was requested
426  */
427  bool CField::sendReadDataRequestIfNeeded(void)
428  {
429    const CDate& currentDate = CContext::getCurrent()->getCalendar()->getCurrentDate();
430
431    bool dataRequested = false;
432    while (currentDate >= lastDataRequestedFromServer)
433    {
434      info(20) << "currentDate : " << currentDate << endl ;
435      info(20) << "lastDataRequestedFromServer : " << lastDataRequestedFromServer << endl ;
436      info(20) << "file->output_freq.getValue() : " << file->output_freq.getValue() << endl ;
437      info(20) << "lastDataRequestedFromServer + file->output_freq.getValue() : " << lastDataRequestedFromServer + file->output_freq << endl ;
438
439      sendReadDataRequest(lastDataRequestedFromServer + file->output_freq);
440
441      dataRequested = true;
442    }
443    return dataRequested;
444  }
445
446  void CField::recvReadDataRequest(CEventServer& event)
447  {
448    CBufferIn* buffer = event.subEvents.begin()->buffer;
449    StdString fieldId;
450    *buffer >> fieldId;
451    get(fieldId)->recvReadDataRequest();
452  }
453
454  void CField::recvReadDataRequest(void)
455  {
456    CContext* context = CContext::getCurrent();
457    CContextClient* client = context->client;
458
459    CEventClient event(getType(), EVENT_ID_READ_DATA_READY);
460    std::list<CMessage> msgs;
461
462    bool hasData = readField();
463
464    map<int, CArray<double,1> >::iterator it;
465//    for (it = data_srv.begin(); it != data_srv.end(); it++)
466//    {
467//      msgs.push_back(CMessage());
468//      CMessage& msg = msgs.back();
469//      msg << getId();
470//      if (hasData)
471//        msg << getNStep() - 1 << it->second;
472//      else
473//        msg << int(-1);
474//      event.push(it->first, grid->nbSenders[it->first], msg);
475//    }
476//    client->sendEvent(event);
477    if (!grid->doGridHaveDataDistributed())
478    {
479       if (client->isServerLeader())
480       {
481          if (!data_srv.empty())
482          {
483            it = data_srv.begin();
484            const std::list<int>& ranks = client->getRanksServerLeader();
485            for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
486            {
487              msgs.push_back(CMessage());
488              CMessage& msg = msgs.back();
489              msg << getId();
490              if (hasData)
491                msg << getNStep() - 1 << it->second;
492              else
493                msg << int(-1);
494              event.push(*itRank, 1, msg);
495            }
496          }
497          client->sendEvent(event);
498       }
499       else
500       {
501          // if (!data_srv.empty())
502          // {
503          //   it = data_srv.begin();
504          //   const std::list<int>& ranks = client->getRanksServerNotLeader();
505          //   for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
506          //   {
507          //     msgs.push_back(CMessage());
508          //     CMessage& msg = msgs.back();
509          //     msg << getId();
510          //     if (hasData)
511          //       msg << getNStep() - 1 << it->second;
512          //     else
513          //       msg << int(-1);
514          //     event.push(*itRank, 1, msg);
515          //   }
516          // }
517          client->sendEvent(event);
518       }
519    }
520    else
521    {
522      for (it = data_srv.begin(); it != data_srv.end(); it++)
523      {
524        msgs.push_back(CMessage());
525        CMessage& msg = msgs.back();
526        msg << getId();
527        if (hasData)
528          msg << getNStep() - 1 << it->second;
529        else
530          msg << int(-1);
531        event.push(it->first, grid->nbSenders[0][it->first], msg);
532      }
533      client->sendEvent(event);
534    }
535  }
536
537  bool CField::readField(void)
538  {
539    if (!getRelFile()->allDomainEmpty)
540    {
541      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
542      {
543        if (data_srv.empty())
544        {
545          for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
546            data_srv.insert(std::make_pair(it->first, CArray<double,1>(it->second.numElements())));
547        }
548
549        getRelFile()->checkFile();
550        if (!nstepMax)
551        {
552          nstepMax = getRelFile()->getDataInput()->getFieldNbRecords(CField::get(this));
553        }
554
555        this->incrementNStep();
556
557
558
559        if (getNStep() > nstepMax && (getRelFile()->cyclic.isEmpty() || !getRelFile()->cyclic) )
560          return false;
561
562        getRelFile()->getDataInput()->readFieldData(CField::get(this));
563      }
564    }
565
566    return true;
567  }
568
569  void CField::recvReadDataReady(CEventServer& event)
570  {
571    string fieldId;
572    vector<int> ranks;
573    vector<CBufferIn*> buffers;
574
575    list<CEventServer::SSubEvent>::iterator it;
576    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
577    {
578      ranks.push_back(it->rank);
579      CBufferIn* buffer = it->buffer;
580      *buffer >> fieldId;
581      buffers.push_back(buffer);
582    }
583    get(fieldId)->recvReadDataReady(ranks, buffers);
584  }
585
586  void CField::recvReadDataReady(vector<int> ranks, vector<CBufferIn*> buffers)
587  {
588    CContext* context = CContext::getCurrent();
589    int record;
590    std::map<int, CArray<double,1> > data;
591
592    bool isEOF = false;
593
594    for (int i = 0; i < ranks.size(); i++)
595    {
596      int rank = ranks[i];
597      *buffers[i] >> record;
598      isEOF = (record == int(-1));
599
600      if (!isEOF)
601        *buffers[i] >> data[rank];
602      else
603        break;
604    }
605
606    if (wasDataAlreadyReceivedFromServer)
607      lastDataReceivedFromServer = lastDataReceivedFromServer + file->output_freq;
608    else
609    {
610      lastDataReceivedFromServer = context->getCalendar()->getInitDate();
611      wasDataAlreadyReceivedFromServer = true;
612    }
613
614    if (isEOF)
615      serverSourceFilter->signalEndOfStream(lastDataReceivedFromServer);
616    else
617      serverSourceFilter->streamDataFromServer(lastDataReceivedFromServer, data);
618  }
619
620   //----------------------------------------------------------------
621
622   void CField::setRelFile(CFile* _file)
623   {
624      this->file = _file;
625      hasOutputFile = true;
626   }
627
628   //----------------------------------------------------------------
629
630   StdString CField::GetName(void)    { return StdString("field"); }
631   StdString CField::GetDefName(void) { return CField::GetName(); }
632   ENodeType CField::GetType(void)    { return eField; }
633
634   //----------------------------------------------------------------
635
636   CGrid* CField::getRelGrid(void) const
637   {
638      return this->grid;
639   }
640
641   //----------------------------------------------------------------
642
643   CFile* CField::getRelFile(void) const
644   {
645      return this->file;
646   }
647
648   int CField::getNStep(void) const
649   {
650      return this->nstep;
651   }
652
653   func::CFunctor::ETimeType CField::getOperationTimeType() const
654   {
655     return operationTimeType;
656   }
657
658   //----------------------------------------------------------------
659
660   void CField::incrementNStep(void)
661   {
662      this->nstep++;
663   }
664
665   void CField::resetNStep(int nstep /*= 0*/)
666   {
667      this->nstep = nstep;
668   }
669
670   void CField::resetNStepMax(void)
671   {
672      this->nstepMax = 0;
673   }
674
675   //----------------------------------------------------------------
676
677   bool CField::isActive(void) const
678   {
679      return (instantDataFilter != NULL);
680   }
681
682   //----------------------------------------------------------------
683
684   bool CField::wasWritten() const
685   {
686     return written;
687   }
688
689   void CField::setWritten()
690   {
691     written = true;
692   }
693
694   //----------------------------------------------------------------
695
696   bool CField::getUseCompressedOutput() const
697   {
698     return useCompressedOutput;
699   }
700
701   void CField::setUseCompressedOutput()
702   {
703     useCompressedOutput = true;
704   }
705
706   //----------------------------------------------------------------
707
708   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
709   {
710     return instantDataFilter;
711   }
712
713   //----------------------------------------------------------------
714
715   /*!
716     Build up graph of grids which plays role of destination and source in grid transformation
717     This function should be called before \func solveGridReference()
718   */
719   void CField::buildGridTransformationGraph()
720   {
721     CContext* context = CContext::getCurrent();
722     if (context->hasClient && !context->hasServer)
723//     if (context->hasClient)
724     {
725       if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
726       {
727         grid->addTransGridSource(getDirectFieldReference()->grid);
728       }
729     }
730   }
731
732   /*!
733     Generate a new grid destination if there are more than one grid source pointing to a same grid destination
734   */
735   void CField::generateNewTransformationGridDest()
736   {
737     CContext* context = CContext::getCurrent();
738     if (context->hasClient && !context->hasServer)
739//     if (context->hasClient)
740     {
741       std::map<CGrid*,std::pair<bool,StdString> >& gridSrcMap = grid->getTransGridSource();
742       if (1 < gridSrcMap.size())
743       {
744         // Search for grid source
745         CGrid* gridSrc = grid;
746         CField* currField = this;
747         std::vector<CField*> hieraField;
748
749         while (currField->hasDirectFieldReference() && (gridSrc == grid))
750         {
751           hieraField.push_back(currField);
752           CField* tmp = currField->getDirectFieldReference();
753           currField = tmp;
754           gridSrc = currField->grid;
755         }
756
757         if (gridSrcMap.end() != gridSrcMap.find(gridSrc))
758         {
759           CGrid* gridTmp;
760           std::pair<bool,StdString> newGridDest = gridSrcMap[gridSrc];
761           if (newGridDest.first)
762           {
763             StdString newIdGridDest = newGridDest.second;
764             if (!CGrid::has(newIdGridDest))
765             {
766                ERROR("CGrid* CGrid::generateNewTransformationGridDest()",
767                  << " Something wrong happened! Grid whose id " << newIdGridDest
768                  << "should exist ");
769             }
770             gridTmp = CGrid::get(newIdGridDest);
771           }
772           else
773           {
774             StdString newIdGridDest = CGrid::generateId(gridSrc, grid);
775             gridTmp = CGrid::cloneGrid(newIdGridDest, grid);
776
777             (gridSrcMap[gridSrc]).first = true;
778             (gridSrcMap[gridSrc]).second = newIdGridDest;
779           }
780
781           // Update all descendants
782           for (std::vector<CField*>::iterator it = hieraField.begin(); it != hieraField.end(); ++it)
783           {
784             (*it)->grid = gridTmp;
785             (*it)->updateRef((*it)->grid);
786           }
787         }
788       }
789     }
790   }
791
792   void CField::updateRef(CGrid* grid)
793   {
794     if (!grid_ref.isEmpty()) grid_ref.setValue(grid->getId());
795     else
796     {
797       std::vector<CAxis*> axisTmp = grid->getAxis();
798       std::vector<CDomain*> domainTmp = grid->getDomains();
799       if ((1<axisTmp.size()) || (1<domainTmp.size()))
800         ERROR("void CField::updateRef(CGrid* grid)",
801           << "More than one domain or axis is available for domain_ref/axis_ref of field " << this->getId());
802
803       if ((!domain_ref.isEmpty()) && (domainTmp.empty()))
804         ERROR("void CField::updateRef(CGrid* grid)",
805           << "Incoherent between available domain and domain_ref of field " << this->getId());
806       if ((!axis_ref.isEmpty()) && (axisTmp.empty()))
807         ERROR("void CField::updateRef(CGrid* grid)",
808           << "Incoherent between available axis and axis_ref of field " << this->getId());
809
810       if (!domain_ref.isEmpty()) domain_ref.setValue(domainTmp[0]->getId());
811       if (!axis_ref.isEmpty()) axis_ref.setValue(axisTmp[0]->getId());
812     }
813   }
814   
815   void CField::solveAllEnabledFields()
816   {
817     CContext* context = CContext::getCurrent();
818     bool hasClient = context->hasClient;
819     bool hasServer = context->hasServer;
820
821     if (!isReferenceSolved)
822     {
823        isReferenceSolved = true;
824
825        if (hasClient && !hasServer)
826        {
827          solveRefInheritance(true);
828          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllEnabledFields();
829        }
830
831        if (hasServer)
832          solveServerOperation();
833
834        solveGridReference();
835
836        if (hasClient && !hasServer)
837       {
838         solveGenerateGrid();
839         buildGridTransformationGraph();
840       }
841
842       solveGridDomainAxisRef(false);
843
844       if (hasClient && !hasServer)
845       {
846         solveTransformedGrid();
847       }
848
849       solveGridDomainAxisRef(false);
850     }
851   }
852
853   void CField::checkGridOfEnabledFields()
854   {
855      solveCheckMaskIndex(false);
856   }
857
858   void CField::sendGridOfEnabledFields()
859   {
860      solveGridDomainAxisRef(true);
861      solveCheckMaskIndex(true);
862   }
863
864
865    void CField::solveOnlyReferenceEnabledField(bool doSending2Server)
866   {
867     CContext* context = CContext::getCurrent();
868     if (!isReferenceSolved)
869     {
870        isReferenceSolved = true;
871
872        if (context->hasClient && !context->hasServer)
873//        if (context->hasClient)
874        {
875          solveRefInheritance(true);
876          if (hasDirectFieldReference()) getDirectFieldReference()->solveOnlyReferenceEnabledField(false);
877        }
878//        else if (context->hasServer)
879        if (context->hasServer)
880          solveServerOperation();
881
882        solveGridReference();
883
884        if (context->hasClient && !context->hasServer)
885//       if (context->hasClient)
886       {
887         solveGenerateGrid();
888         buildGridTransformationGraph();
889       }
890     }
891   }
892     
893   void CField::solveAllReferenceEnabledField(bool doSending2Server)
894   {
895     CContext* context = CContext::getCurrent();
896     solveOnlyReferenceEnabledField(doSending2Server);
897
898     if (!areAllReferenceSolved)
899     {
900        areAllReferenceSolved = true;
901
902       // if (context->hasClient)
903        if (context->hasClient && !context->hasServer)
904        {
905          solveRefInheritance(true);
906          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
907        }
908       else if (context->hasServer)
909        // if (context->hasServer && !context->hasClient)
910          solveServerOperation();
911
912        solveGridReference();
913     }
914
915     solveGridDomainAxisRef(doSending2Server);
916
917     if (context->hasClient && !context->hasServer)
918     {
919       solveTransformedGrid();
920     }
921
922     solveCheckMaskIndex(doSending2Server);
923   }
924
925   std::map<int, StdSize> CField::getGridAttributesBufferSize()
926   {
927     return grid->getAttributesBufferSize();
928   }
929
930   std::vector<std::map<int, StdSize> > CField::getGridDataBufferSize()
931   {
932     return grid->getDataBufferSize(getId());
933   }
934
935   //----------------------------------------------------------------
936
937   void CField::solveServerOperation(void)
938   {
939      CContext* context = CContext::getCurrent();
940
941      if (!context->hasServer || !hasOutputFile) return;
942
943      if (freq_op.isEmpty())
944        freq_op.setValue(TimeStep);
945
946      if (freq_offset.isEmpty())
947        freq_offset.setValue(NoneDu);
948
949      freq_operation_srv = file->output_freq.getValue();
950      freq_write_srv     = file->output_freq.getValue();
951
952      lastlast_Write_srv = context->getCalendar()->getInitDate();
953      last_Write_srv     = context->getCalendar()->getInitDate();
954      last_operation_srv = context->getCalendar()->getInitDate();
955
956      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
957      last_operation_srv     = last_operation_srv - toffset;
958
959      if (operation.isEmpty())
960        ERROR("void CField::solveServerOperation(void)",
961              << "An operation must be defined for field \"" << getId() << "\".");
962
963      boost::shared_ptr<func::CFunctor> functor;
964      CArray<double, 1> dummyData;
965
966#define DECLARE_FUNCTOR(MType, mtype) \
967      if (operation.getValue().compare(#mtype) == 0) \
968      { \
969        functor.reset(new func::C##MType(dummyData)); \
970      }
971
972#include "functor_type.conf"
973
974      if (!functor)
975        ERROR("void CField::solveServerOperation(void)",
976              << "\"" << operation << "\" is not a valid operation.");
977
978      operationTimeType = functor->timeType();
979   }
980
981   //----------------------------------------------------------------
982
983   /*!
984    * Constructs the graph filter for the field, enabling or not the data output.
985    * This method should not be called more than once with enableOutput equal to true.
986    *
987    * \param gc the garbage collector to use when building the filter graph
988    * \param enableOutput must be true when the field data is to be
989    *                     read by the client or/and written to a file
990    */
991   void CField::buildFilterGraph(CGarbageCollector& gc, bool enableOutput)
992   {
993     // if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
994    if (!isReferenceSolved) solveAllEnabledFields();
995     CContext* context = CContext::getCurrent();
996     bool hasWriterServer = context->hasServer && !context->hasClient;
997     bool hasIntermediateServer = context->hasServer && context->hasClient;
998
999     if (hasWriterServer)
1000     {
1001        if (!instantDataFilter)
1002          instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
1003
1004             // If the field data is to be read by the client or/and written to a file
1005       if (enableOutput && !storeFilter && !fileWriterFilter)
1006       {
1007         if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
1008         {
1009           fileServerWriterFilter = boost::shared_ptr<CFileServerWriterFilter>(new CFileServerWriterFilter(gc, this));
1010           instantDataFilter->connectOutput(fileServerWriterFilter, 0);
1011         }
1012       }
1013     }
1014     else if (hasIntermediateServer)
1015     {
1016       if (!instantDataFilter)
1017         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
1018
1019             // If the field data is to be read by the client or/and written to a file
1020       if (enableOutput && !storeFilter && !fileWriterFilter)
1021       {
1022         if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
1023         {
1024           fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
1025           instantDataFilter->connectOutput(fileWriterFilter, 0);
1026         }
1027       }
1028     }
1029     else
1030     {
1031       // Start by building a filter which can provide the field's instant data
1032       if (!instantDataFilter)
1033       {
1034         // Check if we have an expression to parse
1035       if (hasExpression())
1036         {
1037         boost::scoped_ptr<IFilterExprNode> expr(parseExpr(getExpression() + '\0'));
1038         boost::shared_ptr<COutputPin> filter = expr->reduce(gc, *this);
1039
1040         // Check if a spatial transformation is needed
1041         if (!field_ref.isEmpty())
1042         {
1043           CGrid* gridRef = CField::get(field_ref)->grid;
1044
1045           if (grid && grid != gridRef && grid->hasTransform())
1046           {
1047             double defaultValue = !default_value.isEmpty() ? default_value : 0.0;
1048             std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters = CSpatialTransformFilter::buildFilterGraph(gc, gridRef, grid, defaultValue);
1049
1050             filter->connectOutput(filters.first, 0);
1051             filter = filters.second;
1052           }
1053         }
1054
1055         instantDataFilter = filter;
1056         }
1057         // Check if we have a reference on another field
1058         else if (!field_ref.isEmpty())
1059           instantDataFilter = getFieldReference(gc);
1060         // Check if the data is to be read from a file
1061         else if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
1062         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid,
1063                                                                                                     freq_offset.isEmpty() ? NoneDu : freq_offset,
1064                                                                                                     true));
1065         else // The data might be passed from the model
1066         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
1067       }
1068
1069       // If the field data is to be read by the client or/and written to a file
1070       if (enableOutput && !storeFilter && !fileWriterFilter)
1071       {
1072         if (!read_access.isEmpty() && read_access)
1073         {
1074           storeFilter = boost::shared_ptr<CStoreFilter>(new CStoreFilter(gc, CContext::getCurrent(), grid));
1075           instantDataFilter->connectOutput(storeFilter, 0);
1076         }
1077
1078         if (file && (file->mode.isEmpty() || file->mode == CFile::mode_attr::write))
1079         {
1080           fileWriterFilter = boost::shared_ptr<CFileWriterFilter>(new CFileWriterFilter(gc, this));
1081           getTemporalDataFilter(gc, file->output_freq)->connectOutput(fileWriterFilter, 0);
1082         }
1083       }
1084     }
1085   }
1086
1087
1088   /*!
1089    * Returns the filter needed to handle the field reference.
1090    * This method should only be called when building the filter graph corresponding to the field.
1091    *
1092    * \param gc the garbage collector to use
1093    * \return the output pin corresponding to the field reference
1094    */
1095     boost::shared_ptr<COutputPin> CField::getFieldReference(CGarbageCollector& gc)
1096     {
1097       if (instantDataFilter || field_ref.isEmpty())
1098         ERROR("COutputPin* CField::getFieldReference(CGarbageCollector& gc)",
1099               "Impossible to get the field reference for a field which has already been parsed or which does not have a field_ref.");
1100
1101       CField* fieldRef = CField::get(field_ref);
1102       fieldRef->buildFilterGraph(gc, false);
1103
1104       std::pair<boost::shared_ptr<CFilter>, boost::shared_ptr<CFilter> > filters;
1105       // Check if a spatial transformation is needed
1106       if (grid && grid != fieldRef->grid && grid->hasTransform())
1107       {
1108         double defaultValue = !default_value.isEmpty() ? default_value : 0.0;
1109         filters = CSpatialTransformFilter::buildFilterGraph(gc, fieldRef->grid, grid, defaultValue);
1110       }
1111       else
1112         filters.first = filters.second = boost::shared_ptr<CFilter>(new CPassThroughFilter(gc));
1113
1114       fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
1115
1116       return filters.second;
1117     }
1118
1119   /*!
1120    * Returns the filter needed to handle a self reference in the field's expression.
1121    * If the needed filter does not exist, it is created, otherwise it is reused.
1122    * This method should only be called when building the filter graph corresponding
1123    * to the field's expression.
1124    *
1125    * \param gc the garbage collector to use
1126    * \return the output pin corresponding to a self reference
1127    */
1128   boost::shared_ptr<COutputPin> CField::getSelfReference(CGarbageCollector& gc)
1129   {
1130     if (instantDataFilter || !hasExpression())
1131       ERROR("COutputPin* CField::getSelfReference(CGarbageCollector& gc)",
1132             "Impossible to add a self reference to a field which has already been parsed or which does not have an expression.");
1133
1134     if (!selfReferenceFilter)
1135     {
1136       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
1137       {
1138         if (!serverSourceFilter)
1139           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid,
1140                                                                                   freq_offset.isEmpty() ? NoneDu : freq_offset,
1141                                                                                   true));
1142         selfReferenceFilter = serverSourceFilter;
1143       }
1144       else if (!field_ref.isEmpty())
1145       {
1146         CField* fieldRef = CField::get(field_ref);
1147         fieldRef->buildFilterGraph(gc, false);
1148         selfReferenceFilter = fieldRef->getInstantDataFilter();
1149       }
1150       else
1151       {
1152         if (!clientSourceFilter)
1153           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
1154
1155         selfReferenceFilter = clientSourceFilter;
1156       }
1157     }
1158
1159     return selfReferenceFilter;
1160   }
1161
1162   /*!
1163    * Returns the temporal filter corresponding to the field's temporal operation
1164    * for the specified operation frequency. The filter is created if it does not
1165    * exist, otherwise it is reused.
1166    *
1167    * \param gc the garbage collector to use
1168    * \param outFreq the operation frequency, i.e. the frequency at which the output data will be computed
1169    * \return the output pin corresponding to the requested temporal filter
1170    */
1171   boost::shared_ptr<COutputPin> CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)
1172   {
1173     std::map<CDuration, boost::shared_ptr<COutputPin> >::iterator it = temporalDataFilters.find(outFreq);
1174
1175     if (it == temporalDataFilters.end())
1176     {
1177       if (operation.isEmpty())
1178         ERROR("void CField::getTemporalDataFilter(CGarbageCollector& gc, CDuration outFreq)",
1179               << "An operation must be defined for field \"" << getId() << "\".");
1180
1181       if (freq_op.isEmpty())
1182         freq_op.setValue(TimeStep);
1183       if (freq_offset.isEmpty())
1184         freq_offset.setValue(NoneDu);
1185
1186       const bool ignoreMissingValue = (!detect_missing_value.isEmpty() && !default_value.isEmpty() && detect_missing_value == true);
1187
1188       boost::shared_ptr<CTemporalFilter> temporalFilter(new CTemporalFilter(gc, operation,
1189                                                                             CContext::getCurrent()->getCalendar()->getInitDate(),
1190                                                                             freq_op, freq_offset, outFreq,
1191                                                                             ignoreMissingValue, ignoreMissingValue ? default_value : 0.0));
1192       instantDataFilter->connectOutput(temporalFilter, 0);
1193
1194       it = temporalDataFilters.insert(std::make_pair(outFreq, temporalFilter)).first;
1195     }
1196
1197     return it->second;
1198   }
1199
1200   //----------------------------------------------------------------
1201/*
1202   void CField::fromBinary(StdIStream& is)
1203   {
1204      SuperClass::fromBinary(is);
1205#define CLEAR_ATT(name_)\
1206      SuperClassAttribute::operator[](#name_)->reset()
1207
1208         CLEAR_ATT(domain_ref);
1209         CLEAR_ATT(axis_ref);
1210#undef CLEAR_ATT
1211
1212   }
1213*/
1214   //----------------------------------------------------------------
1215
1216   void CField::solveGridReference(void)
1217   {
1218      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty() && scalar_ref.isEmpty())
1219      {
1220        ERROR("CField::solveGridReference(void)",
1221              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
1222      }
1223      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty() || !scalar_ref.isEmpty()))
1224      {
1225        ERROR("CField::solveGridReference(void)",
1226              << "Field '" << getFieldOutputName() << "' has both a grid and a domain/axis/scalar." << std::endl
1227              << "Please define either 'grid_ref' or 'domain_ref'/'axis_ref'/'scalar_ref'.");
1228      }
1229
1230      if (grid_ref.isEmpty())
1231      {
1232        std::vector<CDomain*> vecDom;
1233        std::vector<CAxis*> vecAxis;
1234        std::vector<CScalar*> vecScalar;
1235        std::vector<int> axisDomainOrderTmp;
1236       
1237        if (!domain_ref.isEmpty())
1238        {
1239          StdString tmp = domain_ref.getValue();
1240          if (CDomain::has(domain_ref))
1241          {
1242            vecDom.push_back(CDomain::get(domain_ref));
1243            axisDomainOrderTmp.push_back(2);
1244          }
1245          else
1246            ERROR("CField::solveGridReference(void)",
1247                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
1248        }
1249
1250        if (!axis_ref.isEmpty())
1251        {
1252          if (CAxis::has(axis_ref))
1253          {
1254            vecAxis.push_back(CAxis::get(axis_ref));
1255            axisDomainOrderTmp.push_back(1);
1256          }
1257          else
1258            ERROR("CField::solveGridReference(void)",
1259                  << "Invalid reference to axis '" << axis_ref.getValue() << "'.");
1260        }
1261
1262        if (!scalar_ref.isEmpty())
1263        {
1264          if (CScalar::has(scalar_ref))
1265          {
1266            vecScalar.push_back(CScalar::get(scalar_ref));
1267            axisDomainOrderTmp.push_back(0);
1268          }
1269          else
1270            ERROR("CField::solveGridReference(void)",
1271                  << "Invalid reference to scalar '" << scalar_ref.getValue() << "'.");
1272        }
1273       
1274        CArray<int,1> axisDomainOrder(axisDomainOrderTmp.size());
1275        for (int idx = 0; idx < axisDomainOrderTmp.size(); ++idx)
1276        {
1277          axisDomainOrder(idx) = axisDomainOrderTmp[idx];
1278        }
1279
1280        // Warning: the gridId shouldn't be set as the grid_ref since it could be inherited
1281        StdString gridId = CGrid::generateId(vecDom, vecAxis, vecScalar,axisDomainOrder);
1282        if (CGrid::has(gridId))
1283          this->grid = CGrid::get(gridId);
1284        else
1285          this->grid = CGrid::createGrid(gridId, vecDom, vecAxis, vecScalar,axisDomainOrder);
1286      }
1287      else
1288      {
1289        if (CGrid::has(grid_ref))
1290          this->grid = CGrid::get(grid_ref);
1291        else
1292          ERROR("CField::solveGridReference(void)",
1293                << "Invalid reference to grid '" << grid_ref.getValue() << "'.");
1294      }
1295   }
1296
1297   void CField::solveGridDomainAxisRef(bool checkAtt)
1298   {
1299     grid->solveDomainAxisRef(checkAtt);
1300   }
1301
1302   void CField::solveCheckMaskIndex(bool doSendingIndex)
1303   {
1304     grid->checkMaskIndex(doSendingIndex);
1305   }
1306
1307   void CField::solveTransformedGrid()
1308   {
1309     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
1310     {
1311       std::vector<CGrid*> grids;
1312       // Source grid
1313       grids.push_back(getDirectFieldReference()->grid);
1314       // Intermediate grids
1315       if (!grid_path.isEmpty())
1316       {
1317         std::string gridId;
1318         size_t start = 0, end;
1319
1320         do
1321         {
1322           end = grid_path.getValue().find(',', start);
1323           if (end != std::string::npos)
1324           {
1325             gridId = grid_path.getValue().substr(start, end - start);
1326             start = end + 1;
1327           }
1328           else
1329             gridId = grid_path.getValue().substr(start);
1330
1331           if (!CGrid::has(gridId))
1332             ERROR("void CField::solveTransformedGrid()",
1333                   << "Invalid grid_path, the grid '" << gridId << "' does not exist.");
1334
1335           grids.push_back(CGrid::get(gridId));
1336         }
1337         while (end != std::string::npos);
1338       }
1339       // Destination grid
1340       grids.push_back(grid);
1341
1342       for (size_t i = 0, count = grids.size() - 1; i < count; ++i)
1343       {
1344         CGrid *gridSrc  = grids[i];
1345         CGrid *gridDest = grids[i + 1];
1346         if (!gridDest->isTransformed())
1347           gridDest->transformGrid(gridSrc);
1348       }
1349     }
1350     else if (grid && grid->hasTransform() && !grid->isTransformed())
1351     {
1352       // Temporarily deactivate the self-transformation of grid
1353       //grid->transformGrid(grid);
1354     }
1355   }
1356
1357   void CField::solveGenerateGrid()
1358   {
1359     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
1360       grid->completeGrid(getDirectFieldReference()->grid);
1361     else
1362       grid->completeGrid();
1363   }
1364
1365   void CField::solveGridDomainAxisBaseRef()
1366   {
1367     grid->solveDomainAxisRef(false);
1368     grid->solveDomainAxisBaseRef();
1369   }
1370
1371   ///-------------------------------------------------------------------
1372
1373   template <>
1374   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
1375   {
1376      if (this->group_ref.isEmpty()) return;
1377      StdString gref = this->group_ref.getValue();
1378
1379      if (!CFieldGroup::has(gref))
1380         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
1381               << "[ gref = " << gref << "]"
1382               << " invalid group name !");
1383
1384      CFieldGroup* group = CFieldGroup::get(gref);
1385      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
1386
1387      std::vector<CField*> allChildren  = group->getAllChildren();
1388      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
1389
1390      for (; it != end; it++)
1391      {
1392         CField* child = *it;
1393         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
1394
1395      }
1396   }
1397
1398   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
1399   {
1400     map<int, CArray<double,1> >::iterator it;
1401     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = (it->second - addOffset) / scaleFactor;
1402   }
1403
1404   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
1405   {
1406     map<int, CArray<double,1> >::iterator it;
1407     for (it = data_srv.begin(); it != data_srv.end(); it++) it->second = it->second * scaleFactor + addOffset;
1408   }
1409
1410   void CField::outputField(CArray<double,3>& fieldOut)
1411   {
1412      map<int, CArray<double,1> >::iterator it;
1413      for (it = data_srv.begin(); it != data_srv.end(); it++)
1414      {
1415        grid->outputField(it->first, it->second, fieldOut.dataFirst());
1416      }
1417   }
1418
1419   void CField::outputField(CArray<double,2>& fieldOut)
1420   {
1421      map<int, CArray<double,1> >::iterator it;
1422      for(it=data_srv.begin();it!=data_srv.end();it++)
1423      {
1424         grid->outputField(it->first, it->second, fieldOut.dataFirst());
1425      }
1426   }
1427
1428   void CField::outputField(CArray<double,1>& fieldOut)
1429   {
1430      map<int, CArray<double,1> >::iterator it;
1431     
1432      fieldOut = recvDataSrv;
1433     
1434      // for (it = data_srv.begin(); it != data_srv.end(); it++)
1435      // {
1436      //    grid->outputField(it->first, it->second, fieldOut.dataFirst());
1437      // }
1438    // grid->outputField(recvDataSrv, fieldOut);
1439   }
1440
1441   void CField::inputField(CArray<double,3>& fieldOut)
1442   {
1443      map<int, CArray<double,1> >::iterator it;
1444      for (it = data_srv.begin(); it != data_srv.end(); it++)
1445      {
1446        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
1447      }
1448   }
1449
1450   void CField::inputField(CArray<double,2>& fieldOut)
1451   {
1452      map<int, CArray<double,1> >::iterator it;
1453      for(it = data_srv.begin(); it != data_srv.end(); it++)
1454      {
1455         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
1456      }
1457   }
1458
1459   void CField::inputField(CArray<double,1>& fieldOut)
1460   {
1461      map<int, CArray<double,1> >::iterator it;
1462      for (it = data_srv.begin(); it != data_srv.end(); it++)
1463      {
1464         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
1465      }
1466   }
1467
1468   void CField::outputCompressedField(CArray<double,1>& fieldOut)
1469   {
1470      map<int, CArray<double,1> >::iterator it;
1471
1472      for (it = data_srv.begin(); it != data_srv.end(); it++)
1473      {
1474         grid->outputCompressedField(it->first, it->second, fieldOut.dataFirst());
1475      }
1476   }
1477
1478   ///-------------------------------------------------------------------
1479
1480   void CField::parse(xml::CXMLNode& node)
1481   {
1482      SuperClass::parse(node);
1483      if (!node.getContent(this->content))
1484      {
1485        if (node.goToChildElement())
1486        {
1487          do
1488          {
1489            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
1490          } while (node.goToNextElement());
1491          node.goToParentElement();
1492        }
1493      }
1494    }
1495
1496   /*!
1497     This function retrieves Id of corresponding domain_ref and axis_ref (if any)
1498   of a field. In some cases, only domain exists but axis doesn't
1499   \return pair of Domain and Axis id
1500   */
1501   const std::vector<StdString>& CField::getRefDomainAxisIds()
1502   {
1503     CGrid* cgPtr = getRelGrid();
1504     if (NULL != cgPtr)
1505     {
1506       std::vector<StdString>::iterator it;
1507       if (!domain_ref.isEmpty())
1508       {
1509         std::vector<StdString> domainList = cgPtr->getDomainList();
1510         it = std::find(domainList.begin(), domainList.end(), domain_ref.getValue());
1511         if (domainList.end() != it) domAxisScalarIds_[0] = *it;
1512       }
1513
1514       if (!axis_ref.isEmpty())
1515       {
1516         std::vector<StdString> axisList = cgPtr->getAxisList();
1517         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
1518         if (axisList.end() != it) domAxisScalarIds_[1] = *it;
1519       }
1520
1521       if (!scalar_ref.isEmpty())
1522       {
1523         std::vector<StdString> scalarList = cgPtr->getScalarList();
1524         it = std::find(scalarList.begin(), scalarList.end(), scalar_ref.getValue());
1525         if (scalarList.end() != it) domAxisScalarIds_[2] = *it;
1526       }
1527     }
1528     return (domAxisScalarIds_);
1529   }
1530
1531   CVariable* CField::addVariable(const string& id)
1532   {
1533     return vVariableGroup->createChild(id);
1534   }
1535
1536   CVariableGroup* CField::addVariableGroup(const string& id)
1537   {
1538     return vVariableGroup->createChildGroup(id);
1539   }
1540
1541   void CField::sendAddAllVariables()
1542   {
1543     std::vector<CVariable*> allVar = getAllVariables();
1544     std::vector<CVariable*>::const_iterator it = allVar.begin();
1545     std::vector<CVariable*>::const_iterator itE = allVar.end();
1546
1547     for (; it != itE; ++it)
1548     {
1549       this->sendAddVariable((*it)->getId());
1550       (*it)->sendAllAttributesToServer();
1551       (*it)->sendValue();
1552     }
1553   }
1554
1555   void CField::sendAddAllVariables(CContextClient* client)
1556   {
1557     std::vector<CVariable*> allVar = getAllVariables();
1558     std::vector<CVariable*>::const_iterator it = allVar.begin();
1559     std::vector<CVariable*>::const_iterator itE = allVar.end();
1560
1561     for (; it != itE; ++it)
1562     {
1563       this->sendAddVariable((*it)->getId(), client);
1564       (*it)->sendAllAttributesToServer(client);
1565       (*it)->sendValue(client);
1566     }
1567   }
1568
1569   void CField::sendAddVariable(const string& id)
1570   {
1571      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE);
1572    // CContext* context = CContext::getCurrent();
1573
1574    // if (!context->hasServer)
1575    // {
1576    //    CContextClient* client = context->client;
1577
1578    //    CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
1579    //    if (client->isServerLeader())
1580    //    {
1581    //      CMessage msg;
1582    //      msg << this->getId();
1583    //      msg << id;
1584    //      const std::list<int>& ranks = client->getRanksServerLeader();
1585    //      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1586    //        event.push(*itRank,1,msg);
1587    //      client->sendEvent(event);
1588    //    }
1589    //    else client->sendEvent(event);
1590    // }
1591   }
1592
1593   void CField::sendAddVariable(const string& id, CContextClient* client)
1594   {
1595      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE, client);
1596    // CContext* context = CContext::getCurrent();
1597
1598    // if (!context->hasServer)
1599    // {
1600    //    CContextClient* client = context->client;
1601
1602    //    CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE);
1603    //    if (client->isServerLeader())
1604    //    {
1605    //      CMessage msg;
1606    //      msg << this->getId();
1607    //      msg << id;
1608    //      const std::list<int>& ranks = client->getRanksServerLeader();
1609    //      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1610    //        event.push(*itRank,1,msg);
1611    //      client->sendEvent(event);
1612    //    }
1613    //    else client->sendEvent(event);
1614    // }
1615   }
1616
1617   void CField::sendAddVariableGroup(const string& id)
1618   {
1619      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE_GROUP);
1620    // CContext* context = CContext::getCurrent();
1621    // if (!context->hasServer)
1622    // {
1623    //    CContextClient* client = context->client;
1624
1625    //    CEventClient event(this->getType(),EVENT_ID_ADD_VARIABLE_GROUP);
1626    //    if (client->isServerLeader())
1627    //    {
1628    //      CMessage msg;
1629    //      msg << this->getId();
1630    //      msg << id;
1631    //      const std::list<int>& ranks = client->getRanksServerLeader();
1632    //      for (std::list<int>::const_iterator itRank = ranks.begin(), itRankEnd = ranks.end(); itRank != itRankEnd; ++itRank)
1633    //        event.push(*itRank,1,msg);
1634    //      client->sendEvent(event);
1635    //    }
1636    //    else client->sendEvent(event);
1637    // }
1638   }
1639
1640   void CField::recvAddVariable(CEventServer& event)
1641   {
1642
1643      CBufferIn* buffer = event.subEvents.begin()->buffer;
1644      string id;
1645      *buffer >> id;
1646      get(id)->recvAddVariable(*buffer);
1647   }
1648
1649   void CField::recvAddVariable(CBufferIn& buffer)
1650   {
1651      string id;
1652      buffer >> id;
1653      addVariable(id);
1654   }
1655
1656   void CField::recvAddVariableGroup(CEventServer& event)
1657   {
1658
1659      CBufferIn* buffer = event.subEvents.begin()->buffer;
1660      string id;
1661      *buffer >> id;
1662      get(id)->recvAddVariableGroup(*buffer);
1663   }
1664
1665   void CField::recvAddVariableGroup(CBufferIn& buffer)
1666   {
1667      string id;
1668      buffer >> id;
1669      addVariableGroup(id);
1670   }
1671
1672   /*!
1673    * Returns string arithmetic expression associated to the field.
1674    * \return if content is defined return content string, otherwise, if "expr" attribute is defined, return expr string.
1675    */
1676   const string& CField::getExpression(void)
1677   {
1678     if (!expr.isEmpty() && content.empty())
1679     {
1680       content = expr;
1681       expr.reset();
1682     }
1683
1684     return content;
1685   }
1686
1687   bool CField::hasExpression(void) const
1688   {
1689     return (!expr.isEmpty() || !content.empty());
1690   }
1691
1692
1693   DEFINE_REF_FUNC(Field,field)
1694} // namespace xios
Note: See TracBrowser for help on using the repository browser.