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

Last change on this file since 1132 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
RevLine 
[219]1#include "field.hpp"
2
[352]3#include "attribute_template.hpp"
4#include "object_template.hpp"
5#include "group_template.hpp"
[219]6
7#include "node_type.hpp"
8#include "calendar_util.hpp"
[352]9#include "message.hpp"
[591]10#include "xios_spl.hpp"
[352]11#include "type.hpp"
[638]12#include "timer.hpp"
[352]13#include "context_client.hpp"
[586]14#include "context_server.hpp"
[459]15#include <set>
[640]16#include "garbage_collector.hpp"
17#include "source_filter.hpp"
18#include "store_filter.hpp"
19#include "file_writer_filter.hpp"
[641]20#include "pass_through_filter.hpp"
[642]21#include "filter_expr_node.hpp"
22#include "lex_parser.hpp"
[643]23#include "temporal_filter.hpp"
[644]24#include "spatial_transform_filter.hpp"
[1025]25#include "file_server_writer_filter.hpp"
[219]26
[335]27namespace xios{
[509]28
[219]29   /// ////////////////////// Définitions ////////////////////// ///
30
31   CField::CField(void)
32      : CObjectTemplate<CField>(), CFieldAttributes()
33      , grid(), file()
[707]34      , written(false)
[645]35      , nstep(0), nstepMax(0)
36      , hasOutputFile(false)
[1129]37      , domAxisScalarIds_(vector<StdString>(3,""))
38      , areAllReferenceSolved(false), isReferenceSolved(false), isReferenceSolvedAndTransformed(false)
[676]39      , useCompressedOutput(false)
[1021]40      , wasDataAlreadyReceivedFromServer(false)
[957]41   { setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group")); }
[219]42
[562]43   CField::CField(const StdString& id)
[219]44      : CObjectTemplate<CField>(id), CFieldAttributes()
45      , grid(), file()
[707]46      , written(false)
[645]47      , nstep(0), nstepMax(0)
48      , hasOutputFile(false)
[1129]49      , domAxisScalarIds_(vector<StdString>(3,""))
50      , areAllReferenceSolved(false), isReferenceSolved(false), isReferenceSolvedAndTransformed(false)
[676]51      , useCompressedOutput(false)
[1021]52      , wasDataAlreadyReceivedFromServer(false)
[957]53   { setVirtualVariableGroup(CVariableGroup::create(getId() + "_virtual_variable_group")); }
[219]54
55   CField::~CField(void)
[645]56   {}
[509]57
[472]58  //----------------------------------------------------------------
59
60   void CField::setVirtualVariableGroup(CVariableGroup* newVVariableGroup)
[509]61   {
62      this->vVariableGroup = newVVariableGroup;
[472]63   }
[509]64
[472]65   CVariableGroup* CField::getVirtualVariableGroup(void) const
66   {
[562]67      return this->vVariableGroup;
[472]68   }
69
70   std::vector<CVariable*> CField::getAllVariables(void) const
71   {
[562]72      return this->vVariableGroup->getAllChildren();
[472]73   }
[509]74
[562]75   void CField::solveDescInheritance(bool apply, const CAttributeMap* const parent)
[472]76   {
[562]77      SuperClassAttribute::setAttributes(parent, apply);
[472]78      this->getVirtualVariableGroup()->solveDescInheritance(apply, NULL);
79   }
[219]80
[645]81  //----------------------------------------------------------------
[509]82
[598]83  bool CField::dispatchEvent(CEventServer& event)
[300]84  {
[562]85    if (SuperClass::dispatchEvent(event)) return true;
[300]86    else
87    {
88      switch(event.type)
89      {
90        case EVENT_ID_UPDATE_DATA :
[562]91          recvUpdateData(event);
92          return true;
93          break;
[472]94
[598]95        case EVENT_ID_READ_DATA :
96          recvReadDataRequest(event);
97          return true;
98          break;
[509]99
[598]100        case EVENT_ID_READ_DATA_READY :
101          recvReadDataReady(event);
102          return true;
103          break;
[509]104
[598]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
[300]115        default :
[562]116          ERROR("bool CField::dispatchEvent(CEventServer& event)", << "Unknown Event");
117          return false;
[300]118      }
119    }
120  }
[509]121
[638]122  void CField::sendUpdateData(const CArray<double,1>& data)
123  {
124    CTimer::get("XIOS Send Data").resume();
125
126    CContext* context = CContext::getCurrent();
[983]127//    CContextClient* client = context->client;
[1030]128    // int nbSrvPools = (context->hasServer) ? context->clientPrimServer.size() : 1;
[1099]129    // int nbSrvPools = (context->hasServer) ? (context->hasClient ? context->clientPrimServer.size() : 0) : 1;
130    // for (int i = 0; i < nbSrvPools; ++i)
131    // {
[1054]132      CContextClient* client = (!context->hasServer) ? context->client : this->file->getContextClient();
[638]133
[1009]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;
[1099]176          event.push(rank, grid->nbSenders[0][rank], list_msg.back());
[1009]177        }
178        client->sendEvent(event);
179      }
[1099]180    // }
[1009]181
182    CTimer::get("XIOS Send Data").suspend();
183  }
184
[1099]185  // void CField::sendUpdateData(const CArray<double,1>& data, CContextClient* client)
186  // {
187  //   CTimer::get("XIOS Send Data").resume();
[1009]188
[1099]189  //   CEventClient event(getType(), EVENT_ID_UPDATE_DATA);
[638]190
[1099]191  //   map<int, CArray<int,1> >::iterator it;
192  //   list<CMessage> list_msg;
193  //   list<CArray<double,1> > list_data;
[638]194
[1099]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;
[638]203
[1099]204  //           list_msg.push_back(CMessage());
205  //           list_data.push_back(CArray<double,1>(index.numElements()));
[638]206
[1099]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));
[638]209
[1099]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;
[638]223
[1099]224  //       list_msg.push_back(CMessage());
225  //       list_data.push_back(CArray<double,1>(index.numElements()));
[638]226
[1099]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));
[638]229
[1099]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
[300]238  void CField::recvUpdateData(CEventServer& event)
239  {
[1025]240    std::map<int,CBufferIn*> rankBuffers;
[509]241
[562]242    list<CEventServer::SSubEvent>::iterator it;
243    string fieldId;
[219]244
[562]245    for (it = event.subEvents.begin(); it != event.subEvents.end(); ++it)
[300]246    {
[562]247      int rank = it->rank;
248      CBufferIn* buffer = it->buffer;
249      *buffer >> fieldId;
[1025]250      rankBuffers[rank] = buffer;
[300]251    }
[1025]252    get(fieldId)->recvUpdateData(rankBuffers);
[300]253  }
[509]254
[1025]255  void  CField::recvUpdateData(std::map<int,CBufferIn*>& rankBuffers)
[300]256  {
[983]257    CContext* context = CContext::getCurrent();
258
[1025]259    size_t sizeData = 0;
260    if (0 == recvDataSrv.numElements())
[1129]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      // }
[1025]268
[1129]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
[1025]275      // Gather all data from different clients
[1129]276      // recvDataSrv.resize(sizeData);
277      recvDataSrv.resize(storeClient.numElements());
[1025]278      recvFoperationSrv = boost::shared_ptr<func::CFunctor>(new func::CInstant(recvDataSrv));
[300]279    }
280
[1025]281    CArray<double,1> recv_data_tmp(recvDataSrv.numElements());
[1099]282    // sizeData = 0;
[562]283    const CDate& currDate = context->getCalendar()->getCurrentDate();
[1099]284    const CDate opeDate   = last_operation_srv +freq_op + freq_operation_srv - freq_op;
[300]285
286    if (opeDate <= currDate)
287    {
[1129]288       for (map<int, CArray<size_t, 1> >::iterator it = grid->outLocalIndexStoreOnClient.begin(); it != grid->outLocalIndexStoreOnClient.end(); ++it)
289      {
[1099]290        CArray<double,1> tmp;
291        CArray<size_t,1>& indexTmp = it->second;
[1025]292        *(rankBuffers[it->first]) >> tmp;
[1099]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();     
[300]299      }
[1129]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      // }
[300]313    }
[509]314
[1025]315    this->setData(recv_data_tmp);
316  }
[509]317
[1025]318  void CField::writeUpdateData(const CArray<double,1>& data)
319  {
320    CContext* context = CContext::getCurrent();
[983]321
[1025]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)
[983]327    {
[1025]328      (*recvFoperationSrv)(data);
329      last_operation_srv = currDate;
[1009]330//        sendUpdateData(fieldData);
331        // Redirecting data to the correct secondary server
[1025]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]);
[983]335    }
[1025]336
337    if (writeDate < (currDate + freq_operation_srv))
[983]338    {
[1025]339      recvFoperationSrv->final();
340      last_Write_srv = writeDate;
[1129]341      grid->computeWrittenIndex();
[562]342      writeField();
[1025]343      lastlast_Write_srv = last_Write_srv;
[300]344    }
[1025]345  }
346 
347//   void  CField::recvUpdateData(vector<int>& ranks, vector<CBufferIn*>& buffers)
348//   {
349//     CContext* context = CContext::getCurrent();
[983]350
[1025]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//     }
[983]360
[1025]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;
[509]364
[1025]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
[300]412  void CField::writeField(void)
413  {
[562]414    if (!getRelFile()->allDomainEmpty)
[586]415    {
[599]416      if (grid->doGridHaveDataToWrite() || getRelFile()->type == CFile::type_attr::one_file)
[379]417      {
418        getRelFile()->checkFile();
419        this->incrementNStep();
420        getRelFile()->getDataOutput()->writeFieldData(CField::get(this));
421      }
[586]422    }
[300]423  }
[562]424
[1021]425  void CField::sendReadDataRequest(const CDate& tsDataRequested)
[598]426  {
427    CContext* context = CContext::getCurrent();
[1071]428//    CContextClient* client = context->client;
429    CContextClient* client = (!context->hasServer) ? context->client : this->file->getContextClient();
[598]430
[1071]431
[1021]432    lastDataRequestedFromServer = tsDataRequested;
[708]433
[598]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
[1021]455    bool dataRequested = false;
456    while (currentDate >= lastDataRequestedFromServer)
[850]457    {
[1021]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 ;
[873]462
[1021]463      sendReadDataRequest(lastDataRequestedFromServer + file->output_freq);
464
465      dataRequested = true;
[850]466    }
[1021]467    return dataRequested;
[598]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
[599]486    bool hasData = readField();
[598]487
[651]488    map<int, CArray<double,1> >::iterator it;
[1021]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())
[598]502    {
[1021]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       }
[598]543    }
[1021]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);
[1099]555        event.push(it->first, grid->nbSenders[0][it->first], msg);
[1021]556      }
557      client->sendEvent(event);
558    }
[599]559  }
[598]560
[599]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        {
[650]569          for (map<int, CArray<size_t, 1> >::iterator it = grid->outIndexFromClient.begin(); it != grid->outIndexFromClient.end(); ++it)
[651]570            data_srv.insert(std::make_pair(it->first, CArray<double,1>(it->second.numElements())));
[599]571        }
572
573        getRelFile()->checkFile();
574        if (!nstepMax)
575        {
576          nstepMax = getRelFile()->getDataInput()->getFieldNbRecords(CField::get(this));
577        }
[873]578
[850]579        this->incrementNStep();
[599]580
[850]581
582
583        if (getNStep() > nstepMax && (getRelFile()->cyclic.isEmpty() || !getRelFile()->cyclic) )
[599]584          return false;
585
586        getRelFile()->getDataInput()->readFieldData(CField::get(this));
587      }
588    }
589
590    return true;
[598]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();
[959]613    int record;
[640]614    std::map<int, CArray<double,1> > data;
615
[645]616    bool isEOF = false;
617
[598]618    for (int i = 0; i < ranks.size(); i++)
619    {
620      int rank = ranks[i];
[599]621      *buffers[i] >> record;
[959]622      isEOF = (record == int(-1));
[598]623
[599]624      if (!isEOF)
[640]625        *buffers[i] >> data[rank];
626      else
627        break;
628    }
629
[1021]630    if (wasDataAlreadyReceivedFromServer)
631      lastDataReceivedFromServer = lastDataReceivedFromServer + file->output_freq;
632    else
633    {
634      lastDataReceivedFromServer = context->getCalendar()->getInitDate();
635      wasDataAlreadyReceivedFromServer = true;
636    }
637
[640]638    if (isEOF)
[1021]639      serverSourceFilter->signalEndOfStream(lastDataReceivedFromServer);
[640]640    else
[1021]641      serverSourceFilter->streamDataFromServer(lastDataReceivedFromServer, data);
[598]642  }
643
[219]644   //----------------------------------------------------------------
645
[347]646   void CField::setRelFile(CFile* _file)
[509]647   {
[459]648      this->file = _file;
[562]649      hasOutputFile = true;
[219]650   }
651
652   //----------------------------------------------------------------
653
[562]654   StdString CField::GetName(void)    { return StdString("field"); }
655   StdString CField::GetDefName(void) { return CField::GetName(); }
656   ENodeType CField::GetType(void)    { return eField; }
[219]657
658   //----------------------------------------------------------------
659
[347]660   CGrid* CField::getRelGrid(void) const
[509]661   {
[562]662      return this->grid;
[219]663   }
664
665   //----------------------------------------------------------------
666
[347]667   CFile* CField::getRelFile(void) const
[509]668   {
[562]669      return this->file;
[219]670   }
[509]671
[952]672   int CField::getNStep(void) const
[266]673   {
[562]674      return this->nstep;
[266]675   }
[509]676
[645]677   func::CFunctor::ETimeType CField::getOperationTimeType() const
678   {
679     return operationTimeType;
680   }
681
682   //----------------------------------------------------------------
683
[266]684   void CField::incrementNStep(void)
685   {
686      this->nstep++;
687   }
[509]688
[952]689   void CField::resetNStep(int nstep /*= 0*/)
[321]690   {
[707]691      this->nstep = nstep;
[321]692   }
[219]693
[599]694   void CField::resetNStepMax(void)
695   {
696      this->nstepMax = 0;
697   }
698
[219]699   //----------------------------------------------------------------
700
[310]701   bool CField::isActive(void) const
[509]702   {
[767]703      return (instantDataFilter != NULL);
[310]704   }
[562]705
[219]706   //----------------------------------------------------------------
[509]707
[707]708   bool CField::wasWritten() const
709   {
710     return written;
711   }
712
713   void CField::setWritten()
714   {
715     written = true;
716   }
717
718   //----------------------------------------------------------------
719
[676]720   bool CField::getUseCompressedOutput() const
721   {
722     return useCompressedOutput;
723   }
724
725   void CField::setUseCompressedOutput()
726   {
727     useCompressedOutput = true;
728   }
729
730   //----------------------------------------------------------------
731
[641]732   boost::shared_ptr<COutputPin> CField::getInstantDataFilter()
733   {
734     return instantDataFilter;
735   }
736
737   //----------------------------------------------------------------
738
[823]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();
[983]746     if (context->hasClient && !context->hasServer)
747//     if (context->hasClient)
[687]748     {
[823]749       if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
750       {
751         grid->addTransGridSource(getDirectFieldReference()->grid);
752       }
[687]753     }
[823]754   }
[687]755
[823]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();
[983]762     if (context->hasClient && !context->hasServer)
763//     if (context->hasClient)
[823]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;
[687]772
[823]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   }
[1025]838   
[1129]839   /*!
840     Solve reference of all enabled fields even the source fields .
841     In this step, we do transformations.
842   */
843   void CField::solveAllEnabledFieldsAndTransform()
[1025]844   {
845     CContext* context = CContext::getCurrent();
846     bool hasClient = context->hasClient;
847     bool hasServer = context->hasServer;
[823]848
[1129]849     if (!isReferenceSolvedAndTransformed)
[1025]850     {
[1129]851        isReferenceSolvedAndTransformed = true;
[1025]852
853        if (hasClient && !hasServer)
854        {
855          solveRefInheritance(true);
[1129]856          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllEnabledFieldsAndTransform();
[1025]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     
[823]921   void CField::solveAllReferenceEnabledField(bool doSending2Server)
922   {
923     CContext* context = CContext::getCurrent();
924     solveOnlyReferenceEnabledField(doSending2Server);
925
926     if (!areAllReferenceSolved)
927     {
928        areAllReferenceSolved = true;
929
[1025]930       // if (context->hasClient)
[983]931        if (context->hasClient && !context->hasServer)
[823]932        {
933          solveRefInheritance(true);
934          if (hasDirectFieldReference()) getDirectFieldReference()->solveAllReferenceEnabledField(false);
935        }
[1025]936       else if (context->hasServer)
937        // if (context->hasServer && !context->hasClient)
[823]938          solveServerOperation();
939
940        solveGridReference();
941     }
942
943     solveGridDomainAxisRef(doSending2Server);
944
[1021]945     if (context->hasClient && !context->hasServer)
[619]946     {
947       solveTransformedGrid();
948     }
[687]949
[823]950     solveCheckMaskIndex(doSending2Server);
[509]951   }
952
[731]953   std::map<int, StdSize> CField::getGridAttributesBufferSize()
[509]954   {
[731]955     return grid->getAttributesBufferSize();
[509]956   }
957
[1099]958   std::vector<std::map<int, StdSize> > CField::getGridDataBufferSize()
[731]959   {
960     return grid->getDataBufferSize(getId());
961   }
962
[219]963   //----------------------------------------------------------------
964
[645]965   void CField::solveServerOperation(void)
[219]966   {
[640]967      CContext* context = CContext::getCurrent();
[509]968
[640]969      if (!context->hasServer || !hasOutputFile) return;
970
[645]971      if (freq_op.isEmpty())
972        freq_op.setValue(TimeStep);
[509]973
[538]974      if (freq_offset.isEmpty())
975        freq_offset.setValue(NoneDu);
[219]976
[645]977      freq_operation_srv = file->output_freq.getValue();
978      freq_write_srv     = file->output_freq.getValue();
[509]979
[651]980      lastlast_Write_srv = context->getCalendar()->getInitDate();
981      last_Write_srv     = context->getCalendar()->getInitDate();
982      last_operation_srv = context->getCalendar()->getInitDate();
[509]983
[645]984      const CDuration toffset = freq_operation_srv - freq_offset.getValue() - context->getCalendar()->getTimeStep();
[651]985      last_operation_srv     = last_operation_srv - toffset;
[509]986
[645]987      if (operation.isEmpty())
988        ERROR("void CField::solveServerOperation(void)",
989              << "An operation must be defined for field \"" << getId() << "\".");
[509]990
[645]991      boost::shared_ptr<func::CFunctor> functor;
992      CArray<double, 1> dummyData;
[598]993
[562]994#define DECLARE_FUNCTOR(MType, mtype) \
[645]995      if (operation.getValue().compare(#mtype) == 0) \
[470]996      { \
[645]997        functor.reset(new func::C##MType(dummyData)); \
998      }
[509]999
[219]1000#include "functor_type.conf"
[509]1001
[645]1002      if (!functor)
1003        ERROR("void CField::solveServerOperation(void)",
1004              << "\"" << operation << "\" is not a valid operation.");
1005
1006      operationTimeType = functor->timeType();
[219]1007   }
[509]1008
[219]1009   //----------------------------------------------------------------
[640]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   {
[1025]1021     // if (!areAllReferenceSolved) solveAllReferenceEnabledField(false);
[1129]1022    if (!isReferenceSolvedAndTransformed) solveAllEnabledFieldsAndTransform();
[1025]1023     CContext* context = CContext::getCurrent();
1024     bool hasWriterServer = context->hasServer && !context->hasClient;
1025     bool hasIntermediateServer = context->hasServer && context->hasClient;
[641]1026
[1025]1027     if (hasWriterServer)
[640]1028     {
[1025]1029        if (!instantDataFilter)
[1027]1030          instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
[1025]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)
[1027]1045         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
[1025]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
[1021]1063       if (hasExpression())
[1025]1064         {
[1021]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;
[1025]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)
[1021]1090         instantDataFilter = serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid,
1091                                                                                                     freq_offset.isEmpty() ? NoneDu : freq_offset,
1092                                                                                                     true));
[1025]1093         else // The data might be passed from the model
[1021]1094         instantDataFilter = clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
[1025]1095       }
[640]1096
[1025]1097       // If the field data is to be read by the client or/and written to a file
1098       if (enableOutput && !storeFilter && !fileWriterFilter)
[640]1099       {
[1025]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         }
[640]1105
[1025]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         }
[640]1111       }
1112     }
1113   }
1114
[1021]1115
[642]1116   /*!
[737]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    */
[1021]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.");
[737]1128
[1021]1129       CField* fieldRef = CField::get(field_ref);
1130       fieldRef->buildFilterGraph(gc, false);
[737]1131
[1021]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));
[873]1141
[1021]1142       fieldRef->getInstantDataFilter()->connectOutput(filters.first, 0);
[737]1143
[1021]1144       return filters.second;
1145     }
[737]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.
[642]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   {
[1021]1158     if (instantDataFilter || !hasExpression())
[642]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
[737]1162     if (!selfReferenceFilter)
1163     {
[741]1164       if (file && !file->mode.isEmpty() && file->mode == CFile::mode_attr::read)
1165       {
1166         if (!serverSourceFilter)
[1021]1167           serverSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid,
1168                                                                                   freq_offset.isEmpty() ? NoneDu : freq_offset,
1169                                                                                   true));
[741]1170         selfReferenceFilter = serverSourceFilter;
1171       }
1172       else if (!field_ref.isEmpty())
[1021]1173       {
1174         CField* fieldRef = CField::get(field_ref);
1175         fieldRef->buildFilterGraph(gc, false);
1176         selfReferenceFilter = fieldRef->getInstantDataFilter();
1177       }
[737]1178       else
1179       {
1180         if (!clientSourceFilter)
[1021]1181           clientSourceFilter = boost::shared_ptr<CSourceFilter>(new CSourceFilter(gc, grid));
[642]1182
[737]1183         selfReferenceFilter = clientSourceFilter;
1184       }
1185     }
1186
1187     return selfReferenceFilter;
[642]1188   }
1189
[643]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
[640]1228   //----------------------------------------------------------------
[369]1229/*
[562]1230   void CField::fromBinary(StdIStream& is)
[219]1231   {
1232      SuperClass::fromBinary(is);
1233#define CLEAR_ATT(name_)\
[369]1234      SuperClassAttribute::operator[](#name_)->reset()
[219]1235
1236         CLEAR_ATT(domain_ref);
1237         CLEAR_ATT(axis_ref);
1238#undef CLEAR_ATT
1239
1240   }
[369]1241*/
[219]1242   //----------------------------------------------------------------
1243
1244   void CField::solveGridReference(void)
1245   {
[887]1246      if (grid_ref.isEmpty() && domain_ref.isEmpty() && axis_ref.isEmpty() && scalar_ref.isEmpty())
[742]1247      {
1248        ERROR("CField::solveGridReference(void)",
[770]1249              << "A grid must be defined for field '" << getFieldOutputName() << "' .");
[742]1250      }
[887]1251      else if (!grid_ref.isEmpty() && (!domain_ref.isEmpty() || !axis_ref.isEmpty() || !scalar_ref.isEmpty()))
[219]1252      {
[744]1253        ERROR("CField::solveGridReference(void)",
[887]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'.");
[219]1256      }
1257
[744]1258      if (grid_ref.isEmpty())
[219]1259      {
[744]1260        std::vector<CDomain*> vecDom;
1261        std::vector<CAxis*> vecAxis;
[887]1262        std::vector<CScalar*> vecScalar;
[894]1263        std::vector<int> axisDomainOrderTmp;
1264       
[744]1265        if (!domain_ref.isEmpty())
1266        {
[823]1267          StdString tmp = domain_ref.getValue();
[744]1268          if (CDomain::has(domain_ref))
[894]1269          {
[744]1270            vecDom.push_back(CDomain::get(domain_ref));
[894]1271            axisDomainOrderTmp.push_back(2);
1272          }
[744]1273          else
[219]1274            ERROR("CField::solveGridReference(void)",
[744]1275                  << "Invalid reference to domain '" << domain_ref.getValue() << "'.");
1276        }
[219]1277
[744]1278        if (!axis_ref.isEmpty())
[742]1279        {
[744]1280          if (CAxis::has(axis_ref))
[894]1281          {
[744]1282            vecAxis.push_back(CAxis::get(axis_ref));
[894]1283            axisDomainOrderTmp.push_back(1);
1284          }
[744]1285          else
1286            ERROR("CField::solveGridReference(void)",
1287                  << "Invalid reference to axis '" << axis_ref.getValue() << "'.");
[742]1288        }
[744]1289
[887]1290        if (!scalar_ref.isEmpty())
1291        {
1292          if (CScalar::has(scalar_ref))
[894]1293          {
[887]1294            vecScalar.push_back(CScalar::get(scalar_ref));
[894]1295            axisDomainOrderTmp.push_back(0);
1296          }
[887]1297          else
1298            ERROR("CField::solveGridReference(void)",
1299                  << "Invalid reference to scalar '" << scalar_ref.getValue() << "'.");
1300        }
[894]1301       
1302        CArray<int,1> axisDomainOrder(axisDomainOrderTmp.size());
1303        for (int idx = 0; idx < axisDomainOrderTmp.size(); ++idx)
1304        {
1305          axisDomainOrder(idx) = axisDomainOrderTmp[idx];
1306        }
[887]1307
[745]1308        // Warning: the gridId shouldn't be set as the grid_ref since it could be inherited
[894]1309        StdString gridId = CGrid::generateId(vecDom, vecAxis, vecScalar,axisDomainOrder);
[745]1310        if (CGrid::has(gridId))
1311          this->grid = CGrid::get(gridId);
1312        else
[894]1313          this->grid = CGrid::createGrid(gridId, vecDom, vecAxis, vecScalar,axisDomainOrder);
[219]1314      }
[586]1315      else
1316      {
[744]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() << "'.");
[586]1322      }
[509]1323   }
[459]1324
[509]1325   void CField::solveGridDomainAxisRef(bool checkAtt)
1326   {
1327     grid->solveDomainAxisRef(checkAtt);
[219]1328   }
1329
[509]1330   void CField::solveCheckMaskIndex(bool doSendingIndex)
1331   {
1332     grid->checkMaskIndex(doSendingIndex);
1333   }
[219]1334
[619]1335   void CField::solveTransformedGrid()
1336   {
[746]1337     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[790]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     }
[934]1378     else if (grid && grid->hasTransform() && !grid->isTransformed())
1379     {
[1021]1380       // Temporarily deactivate the self-transformation of grid
1381       //grid->transformGrid(grid);
[934]1382     }
[619]1383   }
1384
[687]1385   void CField::solveGenerateGrid()
1386   {
[746]1387     if (grid && !grid->isTransformed() && hasDirectFieldReference() && grid != getDirectFieldReference()->grid)
[687]1388       grid->completeGrid(getDirectFieldReference()->grid);
[775]1389     else
1390       grid->completeGrid();
[687]1391   }
1392
[775]1393   void CField::solveGridDomainAxisBaseRef()
1394   {
1395     grid->solveDomainAxisRef(false);
1396     grid->solveDomainAxisBaseRef();
1397   }
1398
[219]1399   ///-------------------------------------------------------------------
1400
1401   template <>
[562]1402   void CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)
[219]1403   {
1404      if (this->group_ref.isEmpty()) return;
1405      StdString gref = this->group_ref.getValue();
1406
[346]1407      if (!CFieldGroup::has(gref))
[219]1408         ERROR("CGroupTemplate<CField, CFieldGroup, CFieldAttributes>::solveRefInheritance(void)",
1409               << "[ gref = " << gref << "]"
1410               << " invalid group name !");
1411
[347]1412      CFieldGroup* group = CFieldGroup::get(gref);
1413      CFieldGroup* owner = CFieldGroup::get(boost::polymorphic_downcast<CFieldGroup*>(this));
[219]1414
[347]1415      std::vector<CField*> allChildren  = group->getAllChildren();
[562]1416      std::vector<CField*>::iterator it = allChildren.begin(), end = allChildren.end();
[509]1417
[219]1418      for (; it != end; it++)
1419      {
[347]1420         CField* child = *it;
[562]1421         if (child->hasId()) owner->createChild()->field_ref.setValue(child->getId());
[509]1422
[219]1423      }
1424   }
[509]1425
[464]1426   void CField::scaleFactorAddOffset(double scaleFactor, double addOffset)
1427   {
[651]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;
[464]1430   }
[509]1431
[599]1432   void CField::invertScaleFactorAddOffset(double scaleFactor, double addOffset)
1433   {
[651]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;
[599]1436   }
1437
[369]1438   void CField::outputField(CArray<double,3>& fieldOut)
[300]1439   {
[651]1440      map<int, CArray<double,1> >::iterator it;
[562]1441      for (it = data_srv.begin(); it != data_srv.end(); it++)
[551]1442      {
[651]1443        grid->outputField(it->first, it->second, fieldOut.dataFirst());
[551]1444      }
[300]1445   }
[509]1446
[369]1447   void CField::outputField(CArray<double,2>& fieldOut)
[300]1448   {
[651]1449      map<int, CArray<double,1> >::iterator it;
[567]1450      for(it=data_srv.begin();it!=data_srv.end();it++)
1451      {
[676]1452         grid->outputField(it->first, it->second, fieldOut.dataFirst());
[567]1453      }
1454   }
[219]1455
[567]1456   void CField::outputField(CArray<double,1>& fieldOut)
1457   {
[1129]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
[1025]1467      // for (it = data_srv.begin(); it != data_srv.end(); it++)
1468      // {
1469      //    grid->outputField(it->first, it->second, fieldOut.dataFirst());
1470      // }
[1099]1471    // grid->outputField(recvDataSrv, fieldOut);
[300]1472   }
[551]1473
[599]1474   void CField::inputField(CArray<double,3>& fieldOut)
1475   {
[651]1476      map<int, CArray<double,1> >::iterator it;
[599]1477      for (it = data_srv.begin(); it != data_srv.end(); it++)
1478      {
[651]1479        grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1480      }
1481   }
1482
1483   void CField::inputField(CArray<double,2>& fieldOut)
1484   {
[651]1485      map<int, CArray<double,1> >::iterator it;
[599]1486      for(it = data_srv.begin(); it != data_srv.end(); it++)
1487      {
[651]1488         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1489      }
1490   }
1491
1492   void CField::inputField(CArray<double,1>& fieldOut)
1493   {
[651]1494      map<int, CArray<double,1> >::iterator it;
[599]1495      for (it = data_srv.begin(); it != data_srv.end(); it++)
1496      {
[651]1497         grid->inputField(it->first, fieldOut.dataFirst(), it->second);
[599]1498      }
1499   }
1500
[676]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
[219]1511   ///-------------------------------------------------------------------
1512
[562]1513   void CField::parse(xml::CXMLNode& node)
[459]1514   {
1515      SuperClass::parse(node);
[562]1516      if (!node.getContent(this->content))
[472]1517      {
[476]1518        if (node.goToChildElement())
[472]1519        {
[476]1520          do
1521          {
[562]1522            if (node.getElementName() == "variable" || node.getElementName() == "variable_group") this->getVirtualVariableGroup()->parseChild(node);
1523          } while (node.goToNextElement());
[476]1524          node.goToParentElement();
1525        }
[472]1526      }
[459]1527    }
[509]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   */
[887]1534   const std::vector<StdString>& CField::getRefDomainAxisIds()
[569]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());
[887]1544         if (domainList.end() != it) domAxisScalarIds_[0] = *it;
[569]1545       }
[472]1546
[569]1547       if (!axis_ref.isEmpty())
1548       {
1549         std::vector<StdString> axisList = cgPtr->getAxisList();
1550         it = std::find(axisList.begin(), axisList.end(), axis_ref.getValue());
[887]1551         if (axisList.end() != it) domAxisScalarIds_[1] = *it;
[569]1552       }
[887]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       }
[569]1560     }
[887]1561     return (domAxisScalarIds_);
[569]1562   }
1563
[472]1564   CVariable* CField::addVariable(const string& id)
1565   {
[562]1566     return vVariableGroup->createChild(id);
[472]1567   }
1568
1569   CVariableGroup* CField::addVariableGroup(const string& id)
1570   {
[562]1571     return vVariableGroup->createChildGroup(id);
[472]1572   }
1573
[509]1574   void CField::sendAddAllVariables()
1575   {
[957]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)
[509]1581     {
[957]1582       this->sendAddVariable((*it)->getId());
1583       (*it)->sendAllAttributesToServer();
1584       (*it)->sendValue();
[509]1585     }
1586   }
1587
[1021]1588   void CField::sendAddAllVariables(CContextClient* client)
[1009]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     {
[1021]1596       this->sendAddVariable((*it)->getId(), client);
1597       (*it)->sendAllAttributesToServer(client);
1598       (*it)->sendValue(client);
[1009]1599     }
1600   }
1601
[472]1602   void CField::sendAddVariable(const string& id)
1603   {
[987]1604      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE);
1605    // CContext* context = CContext::getCurrent();
[509]1606
[987]1607    // if (!context->hasServer)
1608    // {
1609    //    CContextClient* client = context->client;
[472]1610
[987]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    // }
[472]1624   }
[509]1625
[1021]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
[472]1650   void CField::sendAddVariableGroup(const string& id)
1651   {
[987]1652      sendAddItem(id, (int)EVENT_ID_ADD_VARIABLE_GROUP);
1653    // CContext* context = CContext::getCurrent();
1654    // if (!context->hasServer)
1655    // {
1656    //    CContextClient* client = context->client;
[472]1657
[987]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    // }
[472]1671   }
[509]1672
[472]1673   void CField::recvAddVariable(CEventServer& event)
1674   {
[509]1675
[562]1676      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1677      string id;
[562]1678      *buffer >> id;
1679      get(id)->recvAddVariable(*buffer);
[472]1680   }
[509]1681
[472]1682   void CField::recvAddVariable(CBufferIn& buffer)
1683   {
[562]1684      string id;
1685      buffer >> id;
1686      addVariable(id);
[472]1687   }
1688
1689   void CField::recvAddVariableGroup(CEventServer& event)
1690   {
[509]1691
[562]1692      CBufferIn* buffer = event.subEvents.begin()->buffer;
[472]1693      string id;
[562]1694      *buffer >> id;
1695      get(id)->recvAddVariableGroup(*buffer);
[472]1696   }
[509]1697
[472]1698   void CField::recvAddVariableGroup(CBufferIn& buffer)
1699   {
[562]1700      string id;
1701      buffer >> id;
1702      addVariableGroup(id);
[472]1703   }
1704
[1021]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
[540]1726   DEFINE_REF_FUNC(Field,field)
[335]1727} // namespace xios
Note: See TracBrowser for help on using the repository browser.