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

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

Updating two-level server.
Each client now can play the role of server: It can forward data to other clients or write data like a server.
Each client must combine all data received from other client(s) before forward them or write them on files

+) Correct some bugs of exchange data_index in domain and axis
+) Reorder some functions in context.cpp to make sure that all necessary attributes are available before computing index
+) Add the mapping index for client to write data.

Test
+) On Curie
+) test_client and test_complete
+) Mode:

  • Only one level: Correct
  • Two levels: Work if using ddt (bug)

+) Only zoom is tested but other transformations should work
+) No reading test

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