source: XIOS/dev/branch_yushan_merged/src/transformation/domain_algorithm_interpolate.cpp @ 1205

Last change on this file since 1205 was 1205, checked in by yushan, 7 years ago

branch merged with trunk @1200

File size: 32.0 KB
Line 
1/*!
2   \file domain_algorithm_interpolate_from_file.cpp
3   \author Ha NGUYEN
4   \since 09 Jul 2015
5   \date 15 Sep 2015
6
7   \brief Algorithm for interpolation on a domain.
8 */
9#include "domain_algorithm_interpolate.hpp"
10#include <boost/unordered_map.hpp>
11#include "context.hpp"
12#include "context_client.hpp"
13#include "distribution_client.hpp"
14#include "client_server_mapping_distributed.hpp"
15#include "netcdf.hpp"
16#include "mapper.hpp"
17#include "mpi_tag.hpp"
18#include "domain.hpp"
19#include "grid_transformation_factory_impl.hpp"
20#include "interpolate_domain.hpp"
21#include "grid.hpp"
22
23namespace xios {
24CGenericAlgorithmTransformation* CDomainAlgorithmInterpolate::create(CGrid* gridDst, CGrid* gridSrc,
25                                                                     CTransformation<CDomain>* transformation,
26                                                                     int elementPositionInGrid,
27                                                                     std::map<int, int>& elementPositionInGridSrc2ScalarPosition,
28                                                                     std::map<int, int>& elementPositionInGridSrc2AxisPosition,
29                                                                     std::map<int, int>& elementPositionInGridSrc2DomainPosition,
30                                                                     std::map<int, int>& elementPositionInGridDst2ScalarPosition,
31                                                                     std::map<int, int>& elementPositionInGridDst2AxisPosition,
32                                                                     std::map<int, int>& elementPositionInGridDst2DomainPosition)
33{
34  std::vector<CDomain*> domainListDestP = gridDst->getDomains();
35  std::vector<CDomain*> domainListSrcP  = gridSrc->getDomains();
36
37  CInterpolateDomain* interpolateDomain = dynamic_cast<CInterpolateDomain*> (transformation);
38  int domainDstIndex = elementPositionInGridDst2DomainPosition[elementPositionInGrid];
39  int domainSrcIndex = elementPositionInGridSrc2DomainPosition[elementPositionInGrid];
40
41  return (new CDomainAlgorithmInterpolate(domainListDestP[domainDstIndex], domainListSrcP[domainSrcIndex], interpolateDomain));
42}
43
44bool CDomainAlgorithmInterpolate::registerTrans()
45{
46  CGridTransformationFactory<CDomain>::registerTransformation(TRANS_INTERPOLATE_DOMAIN, create);
47}
48
49CDomainAlgorithmInterpolate::CDomainAlgorithmInterpolate(CDomain* domainDestination, CDomain* domainSource, CInterpolateDomain* interpDomain)
50: CDomainAlgorithmTransformation(domainDestination, domainSource), interpDomain_(interpDomain), writeToFile_(false), readFromFile_(false)
51{
52  CContext* context = CContext::getCurrent();
53  interpDomain_->checkValid(domainSource);
54  fileToReadWrite_ = "xios_interpolation_weights_";
55
56  if (interpDomain_->weight_filename.isEmpty())
57  {
58    fileToReadWrite_ += context->getId() + "_" + 
59                    domainSource->getDomainOutputName() + "_" + 
60                    domainDestination->getDomainOutputName() + ".nc";   
61  }
62  else 
63    fileToReadWrite_ = interpDomain_->weight_filename;
64
65  ifstream f(fileToReadWrite_.c_str()); 
66  switch (interpDomain_->mode)
67  {
68    case CInterpolateDomain::mode_attr::read:
69      readFromFile_ = true;     
70      break;
71    case CInterpolateDomain::mode_attr::compute:
72      readFromFile_ = false;
73      break;
74    case CInterpolateDomain::mode_attr::read_or_compute:     
75      if (!f.good())
76        readFromFile_ = false;
77      else
78        readFromFile_ = true;
79      break;
80    default:
81      break;
82  } 
83
84  writeToFile_ = interpDomain_->write_weight; 
85   
86}
87
88/*!
89  Compute remap with integrated remap calculation module
90*/
91void CDomainAlgorithmInterpolate::computeRemap()
92{
93  using namespace sphereRemap;
94
95  CContext* context = CContext::getCurrent();
96  CContextClient* client=context->client;
97  int clientRank = client->clientRank;
98  int i, j, k, idx;
99  std::vector<double> srcPole(3,0), dstPole(3,0);
100  int orderInterp = interpDomain_->order.getValue();
101  bool renormalize ;
102  bool quantity ;
103
104  if (interpDomain_->renormalize.isEmpty()) renormalize=true;
105  else renormalize = interpDomain_->renormalize;
106
107  if (interpDomain_->quantity.isEmpty()) quantity=false;
108  else quantity = interpDomain_->quantity;
109
110  const double poleValue = 90.0;
111  const int constNVertex = 4; // Value by default number of vertex for rectangular domain
112  int nVertexSrc, nVertexDest;
113  nVertexSrc = nVertexDest = constNVertex;
114
115  // First of all, try to retrieve the boundary values of domain source and domain destination
116  int localDomainSrcSize = domainSrc_->i_index.numElements();
117  int niSrc = domainSrc_->ni.getValue(), njSrc = domainSrc_->nj.getValue();
118  bool hasBoundSrc = domainSrc_->hasBounds;
119  if (hasBoundSrc) nVertexSrc = domainSrc_->nvertex.getValue();
120  CArray<double,2> boundsLonSrc(nVertexSrc,localDomainSrcSize);
121  CArray<double,2> boundsLatSrc(nVertexSrc,localDomainSrcSize);
122
123  if (domainSrc_->hasPole) srcPole[2] = 1;
124  if (hasBoundSrc)  // Suppose that domain source is curvilinear or unstructured
125  {
126    if (!domainSrc_->bounds_lon_2d.isEmpty())
127    {
128      for (j = 0; j < njSrc; ++j)
129        for (i = 0; i < niSrc; ++i)
130        {
131          k=j*niSrc+i;
132          for(int n=0;n<nVertexSrc;++n)
133          {
134            boundsLonSrc(n,k) = domainSrc_->bounds_lon_2d(n,i,j);
135            boundsLatSrc(n,k) = domainSrc_->bounds_lat_2d(n,i,j);
136          }
137        }
138    }
139    else
140    {
141      boundsLonSrc = domainSrc_->bounds_lon_1d;
142      boundsLatSrc = domainSrc_->bounds_lat_1d;
143    }
144  }
145  else // if domain source is rectilinear, not do anything now
146  {
147    CArray<double,1> lon_g ;
148    CArray<double,1> lat_g ;
149
150    if (!domainSrc_->lonvalue_1d.isEmpty() && !domainSrc_->latvalue_1d.isEmpty())
151    {
152      domainSrc_->AllgatherRectilinearLonLat(domainSrc_->lonvalue_1d,domainSrc_->latvalue_1d, lon_g,lat_g) ;
153    }
154    else if (! domainSrc_->latvalue_rectilinear_read_from_file.isEmpty() && ! domainSrc_->lonvalue_rectilinear_read_from_file.isEmpty() )
155    {
156      lat_g=domainSrc_->latvalue_rectilinear_read_from_file ;
157      lon_g=domainSrc_->lonvalue_rectilinear_read_from_file ;
158    }
159    else if (!domainSrc_->lon_start.isEmpty() && !domainSrc_->lon_end.isEmpty() &&
160             !domainSrc_->lat_start.isEmpty() && !domainSrc_->lat_end.isEmpty())
161    {
162      double step=(domainSrc_->lon_end-domainSrc_->lon_start)/domainSrc_->ni_glo ;
163      for (int i=0; i<domainSrc_->ni_glo; ++i) lon_g(i)=domainSrc_->lon_start+i*step ;
164      step=(domainSrc_->lat_end-domainSrc_->lat_start)/domainSrc_->nj_glo ;
165      for (int i=0; i<domainSrc_->ni_glo; ++i) lat_g(i)=domainSrc_->lat_start+i*step ;
166    }
167    else ERROR("void CDomainAlgorithmInterpolate::computeRemap()",<<"Cannot compute bounds for rectilinear domain") ;
168
169    nVertexSrc = constNVertex;
170    domainSrc_->fillInRectilinearBoundLonLat(lon_g,lat_g, boundsLonSrc, boundsLatSrc);
171  }
172
173  std::map<int,std::vector<std::pair<int,double> > > interpMapValueNorthPole;
174  std::map<int,std::vector<std::pair<int,double> > > interpMapValueSouthPole;
175
176  int localDomainDestSize = domainDest_->i_index.numElements();
177  int niDest = domainDest_->ni.getValue(), njDest = domainDest_->nj.getValue();
178  bool hasBoundDest = domainDest_->hasBounds;
179  if (hasBoundDest) nVertexDest = domainDest_->nvertex.getValue();
180  CArray<double,2> boundsLonDest(nVertexDest,localDomainDestSize);
181  CArray<double,2> boundsLatDest(nVertexDest,localDomainDestSize);
182
183  if (domainDest_->hasPole) dstPole[2] = 1;
184  if (hasBoundDest)
185  {
186    if (!domainDest_->bounds_lon_2d.isEmpty())
187    {
188      for (j = 0; j < njDest; ++j)
189        for (i = 0; i < niDest; ++i)
190        {
191          k=j*niDest+i;
192          for(int n=0;n<nVertexDest;++n)
193          {
194            boundsLonDest(n,k) = domainDest_->bounds_lon_2d(n,i,j);
195            boundsLatDest(n,k) = domainDest_->bounds_lat_2d(n,i,j);
196          }
197        }
198    }
199    else
200    {
201      boundsLonDest = domainDest_->bounds_lon_1d;
202      boundsLatDest = domainDest_->bounds_lat_1d;
203    }
204  }
205  else
206  {
207    bool isNorthPole = false;
208    bool isSouthPole = false;
209
210    CArray<double,1> lon_g ;
211    CArray<double,1> lat_g ;
212
213    if (!domainDest_->lonvalue_1d.isEmpty() && !domainDest_->latvalue_1d.isEmpty())
214    {
215      domainDest_->AllgatherRectilinearLonLat(domainDest_->lonvalue_1d,domainDest_->latvalue_1d, lon_g,lat_g) ;
216    }
217    else if (! domainDest_->latvalue_rectilinear_read_from_file.isEmpty() && ! domainDest_->lonvalue_rectilinear_read_from_file.isEmpty() )
218    {
219      lat_g=domainDest_->latvalue_rectilinear_read_from_file ;
220      lon_g=domainDest_->lonvalue_rectilinear_read_from_file ;
221    }
222    else if (!domainDest_->lon_start.isEmpty() && !domainDest_->lon_end.isEmpty() &&
223             !domainDest_->lat_start.isEmpty() && !domainDest_->lat_end.isEmpty())
224    {
225      double step=(domainDest_->lon_end-domainDest_->lon_start)/domainDest_->ni_glo ;
226      for(int i=0; i<domainDest_->ni_glo; ++i) lon_g(i)=domainDest_->lon_start+i*step ;
227      step=(domainDest_->lat_end-domainDest_->lat_start)/domainDest_->nj_glo ;
228      for(int i=0; i<domainDest_->ni_glo; ++i) lat_g(i)=domainDest_->lat_start+i*step ;
229    }
230    else ERROR("void CDomainAlgorithmInterpolate::computeRemap()",<<"Cannot compute bounds for rectilinear domain") ;
231   
232    if (std::abs(poleValue - std::abs(lat_g(0))) < NumTraits<double>::epsilon()) isNorthPole = true;
233    if (std::abs(poleValue - std::abs(lat_g(domainDest_->nj_glo-1))) < NumTraits<double>::epsilon()) isSouthPole = true;
234
235
236
237
238    if (isNorthPole && (0 == domainDest_->jbegin.getValue()))
239    {
240      int ibegin = domainDest_->ibegin.getValue();
241      for (i = 0; i < niDest; ++i)
242      {
243        interpMapValueNorthPole[i+ibegin];
244      }
245    }
246
247    if (isSouthPole && (domainDest_->nj_glo.getValue() == (domainDest_->jbegin.getValue() + njDest)))
248    {
249      int ibegin = domainDest_->ibegin.getValue();
250      int njGlo = domainDest_->nj_glo.getValue();
251      int niGlo = domainDest_->ni_glo.getValue();
252      for (i = 0; i < niDest; ++i)
253      {
254        k = (njGlo - 1)*niGlo + i + ibegin;
255        interpMapValueSouthPole[k];
256      }
257    }
258
259    // Ok, fill in boundary values for rectangular domain
260    nVertexDest = constNVertex;
261    domainDest_->fillInRectilinearBoundLonLat(lon_g,lat_g, boundsLonDest, boundsLatDest);
262  }
263
264
265
266  // Ok, now use mapper to calculate
267  int nSrcLocal = domainSrc_->i_index.numElements();
268  int nDstLocal = domainDest_->i_index.numElements();
269  long int * globalSrc = new long int [nSrcLocal];
270  long int * globalDst = new long int [nDstLocal];
271
272  long int globalIndex;
273  int i_ind, j_ind;
274  for (int idx = 0; idx < nSrcLocal; ++idx)
275  {
276    i_ind=domainSrc_->i_index(idx) ;
277    j_ind=domainSrc_->j_index(idx) ;
278
279    globalIndex = i_ind + j_ind * domainSrc_->ni_glo;
280    globalSrc[idx] = globalIndex;
281  }
282
283  for (int idx = 0; idx < nDstLocal; ++idx)
284  {
285    i_ind=domainDest_->i_index(idx) ;
286    j_ind=domainDest_->j_index(idx) ;
287
288    globalIndex = i_ind + j_ind * domainDest_->ni_glo;
289    globalDst[idx] = globalIndex;
290  }
291
292
293  // Calculate weight index
294  Mapper mapper(client->intraComm);
295  mapper.setVerbosity(PROGRESS) ;
296
297     
298  // supress masked data for the source
299  int nSrcLocalUnmasked = 0 ;
300  for (int idx=0 ; idx < nSrcLocal; idx++) if (domainSrc_->localMask(idx)) ++nSrcLocalUnmasked ;
301
302
303  CArray<double,2> boundsLonSrcUnmasked(nVertexSrc,nSrcLocalUnmasked);
304  CArray<double,2> boundsLatSrcUnmasked(nVertexSrc,nSrcLocalUnmasked);
305  long int * globalSrcUnmasked = new long int [nSrcLocalUnmasked];
306
307  nSrcLocalUnmasked=0 ;
308  for (int idx=0 ; idx < nSrcLocal; idx++)
309  {
310    if (domainSrc_->localMask(idx))
311    {
312      for(int n=0;n<nVertexSrc;++n)
313      {
314        boundsLonSrcUnmasked(n,nSrcLocalUnmasked) = boundsLonSrc(n,idx) ;
315        boundsLatSrcUnmasked(n,nSrcLocalUnmasked) = boundsLatSrc(n,idx) ;
316      }
317      globalSrcUnmasked[nSrcLocalUnmasked]=globalSrc[idx] ;
318      ++nSrcLocalUnmasked ;
319    }
320  }
321
322
323  int nDstLocalUnmasked = 0 ;
324  for (int idx=0 ; idx < nDstLocal; idx++) if (domainDest_->localMask(idx)) ++nDstLocalUnmasked ;
325
326  CArray<double,2> boundsLonDestUnmasked(nVertexDest,nDstLocalUnmasked);
327  CArray<double,2> boundsLatDestUnmasked(nVertexDest,nDstLocalUnmasked);
328  long int * globalDstUnmasked = new long int [nDstLocalUnmasked];
329
330  nDstLocalUnmasked=0 ;
331  for (int idx=0 ; idx < nDstLocal; idx++)
332  {
333    if (domainDest_->localMask(idx))
334    {
335      for(int n=0;n<nVertexDest;++n)
336      {
337        boundsLonDestUnmasked(n,nDstLocalUnmasked) = boundsLonDest(n,idx) ;
338        boundsLatDestUnmasked(n,nDstLocalUnmasked) = boundsLatDest(n,idx) ;
339      }
340      globalDstUnmasked[nDstLocalUnmasked]=globalDst[idx] ;
341      ++nDstLocalUnmasked ;
342    }
343  }
344
345  mapper.setSourceMesh(boundsLonSrcUnmasked.dataFirst(), boundsLatSrcUnmasked.dataFirst(), nVertexSrc, nSrcLocalUnmasked, &srcPole[0], globalSrcUnmasked);
346  mapper.setTargetMesh(boundsLonDestUnmasked.dataFirst(), boundsLatDestUnmasked.dataFirst(), nVertexDest, nDstLocalUnmasked, &dstPole[0], globalDstUnmasked);
347
348  std::vector<double> timings = mapper.computeWeights(orderInterp,renormalize,quantity);
349
350  std::map<int,std::vector<std::pair<int,double> > > interpMapValue;
351  std::map<int,std::vector<std::pair<int,double> > >::const_iterator iteNorthPole = interpMapValueNorthPole.end(),
352                                                                     iteSouthPole = interpMapValueSouthPole.end();
353  for (int idx = 0;  idx < mapper.nWeights; ++idx)
354  {
355    interpMapValue[mapper.targetWeightId[idx]].push_back(make_pair(mapper.sourceWeightId[idx],mapper.remapMatrix[idx]));
356    if (iteNorthPole != interpMapValueNorthPole.find(mapper.targetWeightId[idx]))
357    {
358      interpMapValueNorthPole[mapper.targetWeightId[idx]].push_back(make_pair(mapper.sourceWeightId[idx],mapper.remapMatrix[idx]));
359    }
360
361    if (iteSouthPole != interpMapValueSouthPole.find(mapper.targetWeightId[idx]))
362    {
363      interpMapValueSouthPole[mapper.targetWeightId[idx]].push_back(make_pair(mapper.sourceWeightId[idx],mapper.remapMatrix[idx]));
364    }
365  }
366  int niGloDst = domainDest_->ni_glo.getValue();
367  processPole(interpMapValueNorthPole, niGloDst);
368  processPole(interpMapValueSouthPole, niGloDst);
369
370  if (!interpMapValueNorthPole.empty())
371  {
372     std::map<int,std::vector<std::pair<int,double> > >::iterator itNorthPole = interpMapValueNorthPole.begin();
373     for (; itNorthPole != iteNorthPole; ++itNorthPole)
374     {
375       if (!(itNorthPole->second.empty()))
376        itNorthPole->second.swap(interpMapValue[itNorthPole->first]);
377     }
378  }
379
380  if (!interpMapValueSouthPole.empty())
381  {
382     std::map<int,std::vector<std::pair<int,double> > >::iterator itSouthPole = interpMapValueSouthPole.begin();
383     for (; itSouthPole != iteSouthPole; ++itSouthPole)
384     {
385       if (!(itSouthPole->second.empty()))
386        itSouthPole->second.swap(interpMapValue[itSouthPole->first]);
387     }
388  }
389
390  if (writeToFile_ && !readFromFile_) writeRemapInfo(interpMapValue);
391//  exchangeRemapInfo(interpMapValue);
392  convertRemapInfo(interpMapValue) ;
393
394  delete [] globalSrc;
395  delete [] globalSrcUnmasked;
396  delete [] globalDst;
397  delete [] globalDstUnmasked;
398
399}
400
401void CDomainAlgorithmInterpolate::processPole(std::map<int,std::vector<std::pair<int,double> > >& interMapValuePole,
402                                              int nbGlobalPointOnPole)
403{
404  CContext* context = CContext::getCurrent();
405  CContextClient* client=context->client;
406  int split_key;
407  ep_lib::MPI_Comm_rank(client->intraComm, &split_key);
408
409  ep_lib::MPI_Comm poleComme(MPI_COMM_NULL);
410  ep_lib::MPI_Comm_split(client->intraComm, interMapValuePole.empty() ? 9 : 1, split_key, &poleComme);
411  if (MPI_COMM_NULL != poleComme)
412  {
413    int nbClientPole;
414    ep_lib::MPI_Comm_size(poleComme, &nbClientPole);
415
416    std::map<int,std::vector<std::pair<int,double> > >::iterator itePole = interMapValuePole.end(), itPole,
417                                                                 itbPole = interMapValuePole.begin();
418
419    int nbWeight = 0;
420    for (itPole = itbPole; itPole != itePole; ++itPole)
421       nbWeight += itPole->second.size();
422
423    std::vector<int> recvCount(nbClientPole,0);
424    std::vector<int> displ(nbClientPole,0);
425    ep_lib::MPI_Allgather(&nbWeight,1,MPI_INT,&recvCount[0],1,MPI_INT,poleComme) ;
426
427    displ[0]=0;
428    for(int n=1;n<nbClientPole;++n) displ[n]=displ[n-1]+recvCount[n-1] ;
429    int recvSize=displ[nbClientPole-1]+recvCount[nbClientPole-1] ;
430   
431
432    std::vector<int> sendSourceIndexBuff(nbWeight);
433    std::vector<double> sendSourceWeightBuff(nbWeight);
434    int k = 0;
435    for (itPole = itbPole; itPole != itePole; ++itPole)
436    {
437      for (int idx = 0; idx < itPole->second.size(); ++idx)
438      {
439        sendSourceIndexBuff[k] = (itPole->second)[idx].first;
440        sendSourceWeightBuff[k] = (itPole->second)[idx].second;
441        ++k;
442      }
443    }
444
445    std::vector<int> recvSourceIndexBuff(recvSize);
446    std::vector<double> recvSourceWeightBuff(recvSize);
447
448    // Gather all index and weight for pole
449    ep_lib::MPI_Allgatherv(&sendSourceIndexBuff[0],nbWeight,MPI_INT,&recvSourceIndexBuff[0],&recvCount[0],&displ[0],MPI_INT,poleComme);
450    ep_lib::MPI_Allgatherv(&sendSourceWeightBuff[0],nbWeight,MPI_DOUBLE,&recvSourceWeightBuff[0],&recvCount[0],&displ[0],MPI_DOUBLE,poleComme);
451
452    std::map<int,double> recvTemp;
453    for (int idx = 0; idx < recvSize; ++idx)
454    {
455      if (recvTemp.end() != recvTemp.find(recvSourceIndexBuff[idx]))
456        recvTemp[recvSourceIndexBuff[idx]] += recvSourceWeightBuff[idx]/nbGlobalPointOnPole;
457      else
458        recvTemp[recvSourceIndexBuff[idx]] = 0.0;
459    }
460
461    std::map<int,double>::const_iterator itRecvTemp, itbRecvTemp = recvTemp.begin(), iteRecvTemp = recvTemp.end();
462
463    for (itPole = itbPole; itPole != itePole; ++itPole)
464    {
465      itPole->second.clear();
466      for (itRecvTemp = itbRecvTemp; itRecvTemp != iteRecvTemp; ++itRecvTemp)
467          itPole->second.push_back(make_pair(itRecvTemp->first, itRecvTemp->second));
468    }
469  }
470
471}
472
473/*!
474  Compute the index mapping between domain on grid source and one on grid destination
475*/
476void CDomainAlgorithmInterpolate::computeIndexSourceMapping_(const std::vector<CArray<double,1>* >& dataAuxInputs)
477{
478  if (readFromFile_ && !writeToFile_) 
479    readRemapInfo();
480  else
481  {
482    computeRemap(); 
483  }
484}
485
486void CDomainAlgorithmInterpolate::writeRemapInfo(std::map<int,std::vector<std::pair<int,double> > >& interpMapValue)
487{ 
488  writeInterpolationInfo(fileToReadWrite_, interpMapValue);
489}
490
491void CDomainAlgorithmInterpolate::readRemapInfo()
492{ 
493  std::map<int,std::vector<std::pair<int,double> > > interpMapValue;
494  readInterpolationInfo(fileToReadWrite_, interpMapValue);
495
496  exchangeRemapInfo(interpMapValue);
497}
498
499void CDomainAlgorithmInterpolate::convertRemapInfo(std::map<int,std::vector<std::pair<int,double> > >& interpMapValue)
500{
501  CContext* context = CContext::getCurrent();
502  CContextClient* client=context->client;
503  int clientRank = client->clientRank;
504
505  this->transformationMapping_.resize(1);
506  this->transformationWeight_.resize(1);
507
508  TransformationIndexMap& transMap = this->transformationMapping_[0];
509  TransformationWeightMap& transWeight = this->transformationWeight_[0];
510
511  std::map<int,std::vector<std::pair<int,double> > >::const_iterator itb = interpMapValue.begin(), it,
512                                                                     ite = interpMapValue.end();
513 
514  for (it = itb; it != ite; ++it)
515  {   
516    const std::vector<std::pair<int,double> >& tmp = it->second;
517    for (int i = 0; i < tmp.size(); ++i)
518    {
519      transMap[it->first].push_back(tmp[i].first);
520      transWeight[it->first].push_back(tmp[i].second);
521    }     
522  }     
523}
524
525/*!
526  Read remap information from file then distribute it among clients
527*/
528void CDomainAlgorithmInterpolate::exchangeRemapInfo(std::map<int,std::vector<std::pair<int,double> > >& interpMapValue)
529{
530  CContext* context = CContext::getCurrent();
531  CContextClient* client=context->client;
532  int clientRank = client->clientRank;
533
534  this->transformationMapping_.resize(1);
535  this->transformationWeight_.resize(1);
536
537  TransformationIndexMap& transMap = this->transformationMapping_[0];
538  TransformationWeightMap& transWeight = this->transformationWeight_[0];
539
540  boost::unordered_map<size_t,int> globalIndexOfDomainDest;
541  int ni = domainDest_->ni.getValue();
542  int nj = domainDest_->nj.getValue();
543  int ni_glo = domainDest_->ni_glo.getValue();
544  size_t globalIndex;
545  int nIndexSize = domainDest_->i_index.numElements(), i_ind, j_ind;
546  for (int idx = 0; idx < nIndexSize; ++idx)
547  {
548    i_ind=domainDest_->i_index(idx) ;
549    j_ind=domainDest_->j_index(idx) ;
550
551    globalIndex = i_ind + j_ind * ni_glo;
552    globalIndexOfDomainDest[globalIndex] = clientRank;
553  }
554
555  CClientServerMappingDistributed domainIndexClientClientMapping(globalIndexOfDomainDest,
556                                                                 client->intraComm,
557                                                                 true);
558  CArray<size_t,1> globalIndexInterp(interpMapValue.size());
559  std::map<int,std::vector<std::pair<int,double> > >::const_iterator itb = interpMapValue.begin(), it,
560                                                                     ite = interpMapValue.end();
561  size_t globalIndexCount = 0;
562  for (it = itb; it != ite; ++it)
563  {
564    globalIndexInterp(globalIndexCount) = it->first;
565    ++globalIndexCount;
566  }
567
568  domainIndexClientClientMapping.computeServerIndexMapping(globalIndexInterp);
569  const CClientServerMapping::GlobalIndexMap& globalIndexInterpSendToClient = domainIndexClientClientMapping.getGlobalIndexOnServer();
570
571  //Inform each client number of index they will receive
572  int nbClient = client->clientSize;
573  int* sendBuff = new int[nbClient];
574  int* recvBuff = new int[nbClient];
575  for (int i = 0; i < nbClient; ++i)
576  {
577    sendBuff[i] = 0;
578    recvBuff[i] = 0;
579  }
580  int sendBuffSize = 0;
581  CClientServerMapping::GlobalIndexMap::const_iterator itbMap = globalIndexInterpSendToClient.begin(), itMap,
582                                                       iteMap = globalIndexInterpSendToClient.end();
583  for (itMap = itbMap; itMap != iteMap; ++itMap)
584  {
585    const std::vector<size_t>& tmp = itMap->second;
586    int sizeIndex = 0, mapSize = (itMap->second).size();
587    for (int idx = 0; idx < mapSize; ++idx)
588    {
589//      sizeIndex += interpMapValue.at((itMap->second)[idx]).size();
590      sizeIndex += (interpMapValue[(int)(itMap->second)[idx]]).size();
591    }
592    sendBuff[itMap->first] = sizeIndex;
593    sendBuffSize += sizeIndex;
594  }
595
596
597  ep_lib::MPI_Allreduce(sendBuff, recvBuff, nbClient, MPI_INT, MPI_SUM, client->intraComm);
598
599  int* sendIndexDestBuff = new int [sendBuffSize];
600  int* sendIndexSrcBuff  = new int [sendBuffSize];
601  double* sendWeightBuff = new double [sendBuffSize];
602
603  std::vector<ep_lib::MPI_Request> sendRequest;
604
605  int sendOffSet = 0, l = 0;
606  for (itMap = itbMap; itMap != iteMap; ++itMap)
607  {
608    const std::vector<size_t>& indexToSend = itMap->second;
609    int mapSize = indexToSend.size();
610    int k = 0;
611    for (int idx = 0; idx < mapSize; ++idx)
612    {
613      std::vector<std::pair<int,double> >& interpMap = interpMapValue[(int)indexToSend[idx]]; //interpMapValue.at(indexToSend[idx]);
614      for (int i = 0; i < interpMap.size(); ++i)
615      {
616        sendIndexDestBuff[l] = indexToSend[idx];
617        sendIndexSrcBuff[l]  = interpMap[i].first;
618        sendWeightBuff[l]    = interpMap[i].second;
619        ++k;
620        ++l;
621      }
622    }
623
624    sendRequest.push_back(ep_lib::MPI_Request());
625    ep_lib::MPI_Isend(sendIndexDestBuff + sendOffSet,
626             k,
627             MPI_INT,
628             itMap->first,
629             MPI_DOMAIN_INTERPOLATION_DEST_INDEX,
630             client->intraComm,
631             &sendRequest.back());
632    sendRequest.push_back(ep_lib::MPI_Request());
633    ep_lib::MPI_Isend(sendIndexSrcBuff + sendOffSet,
634             k,
635             MPI_INT,
636             itMap->first,
637             MPI_DOMAIN_INTERPOLATION_SRC_INDEX,
638             client->intraComm,
639             &sendRequest.back());
640    sendRequest.push_back(ep_lib::MPI_Request());
641    ep_lib::MPI_Isend(sendWeightBuff + sendOffSet,
642             k,
643             MPI_DOUBLE,
644             itMap->first,
645             MPI_DOMAIN_INTERPOLATION_WEIGHT,
646             client->intraComm,
647             &sendRequest.back());
648    sendOffSet += k;
649  }
650
651  int recvBuffSize = recvBuff[clientRank];
652  int* recvIndexDestBuff = new int [recvBuffSize];
653  int* recvIndexSrcBuff  = new int [recvBuffSize];
654  double* recvWeightBuff = new double [recvBuffSize];
655  int receivedSize = 0;
656  int clientSrcRank;
657  while (receivedSize < recvBuffSize)
658  {
659    ep_lib::MPI_Status recvStatus;
660    ep_lib::MPI_Recv((recvIndexDestBuff + receivedSize),
661             recvBuffSize,
662             MPI_INT,
663             MPI_ANY_SOURCE,
664             MPI_DOMAIN_INTERPOLATION_DEST_INDEX,
665             client->intraComm,
666             &recvStatus);
667
668    int countBuff = 0;
669    ep_lib::MPI_Get_count(&recvStatus, MPI_INT, &countBuff);
670    #ifdef _usingMPI
671    clientSrcRank = recvStatus.MPI_SOURCE;
672    #elif _usingEP
673    clientSrcRank = recvStatus.ep_src;
674    #endif
675    ep_lib::MPI_Recv((recvIndexSrcBuff + receivedSize),
676             recvBuffSize,
677             MPI_INT,
678             clientSrcRank,
679             MPI_DOMAIN_INTERPOLATION_SRC_INDEX,
680             client->intraComm,
681             &recvStatus);
682
683    ep_lib::MPI_Recv((recvWeightBuff + receivedSize),
684             recvBuffSize,
685             MPI_DOUBLE,
686             clientSrcRank,
687             MPI_DOMAIN_INTERPOLATION_WEIGHT,
688             client->intraComm,
689             &recvStatus);
690
691    for (int idx = 0; idx < countBuff; ++idx)
692    {
693      transMap[*(recvIndexDestBuff + receivedSize + idx)].push_back(*(recvIndexSrcBuff + receivedSize + idx));
694      transWeight[*(recvIndexDestBuff + receivedSize + idx)].push_back(*(recvWeightBuff + receivedSize + idx));
695    }
696    receivedSize += countBuff;
697  }
698
699  std::vector<ep_lib::MPI_Status> requestStatus(sendRequest.size());
700  ep_lib::MPI_Status stat_ignore;
701  ep_lib::MPI_Waitall(sendRequest.size(), &sendRequest[0], &stat_ignore);
702
703  delete [] sendIndexDestBuff;
704  delete [] sendIndexSrcBuff;
705  delete [] sendWeightBuff;
706  delete [] recvIndexDestBuff;
707  delete [] recvIndexSrcBuff;
708  delete [] recvWeightBuff;
709  delete [] sendBuff;
710  delete [] recvBuff;
711}
712 
713/*! Redefined some functions of CONetCDF4 to make use of them */
714CDomainAlgorithmInterpolate::WriteNetCdf::WriteNetCdf(const StdString& filename, const MPI_Comm comm)
715  : CNc4DataOutput(NULL, filename, false, false, true, comm, false, true) {}
716int CDomainAlgorithmInterpolate::WriteNetCdf::addDimensionWrite(const StdString& name, 
717                                                                const StdSize size)
718{
719  return CONetCDF4::addDimension(name, size); 
720}
721
722int CDomainAlgorithmInterpolate::WriteNetCdf::addVariableWrite(const StdString& name, nc_type type,
723                                                               const std::vector<StdString>& dim)
724{
725  return CONetCDF4::addVariable(name, type, dim);
726}
727
728void CDomainAlgorithmInterpolate::WriteNetCdf::endDefinition()
729{
730  CONetCDF4::definition_end();
731}
732
733void CDomainAlgorithmInterpolate::WriteNetCdf::writeDataIndex(const CArray<int,1>& data, const StdString& name,
734                                                              bool collective, StdSize record,
735                                                              const std::vector<StdSize>* start,
736                                                              const std::vector<StdSize>* count)
737{
738  CONetCDF4::writeData<int,1>(data, name, collective, record, start, count);
739}
740
741void CDomainAlgorithmInterpolate::WriteNetCdf::writeDataIndex(const CArray<double,1>& data, const StdString& name,
742                                                              bool collective, StdSize record,
743                                                              const std::vector<StdSize>* start,
744                                                              const std::vector<StdSize>* count)
745{
746  CONetCDF4::writeData<double,1>(data, name, collective, record, start, count);
747}
748
749/*
750   Write interpolation weights into a file
751   \param [in] filename name of output file
752   \param interpMapValue mapping of global index of domain destination and domain source as well as the corresponding weight
753*/
754void CDomainAlgorithmInterpolate::writeInterpolationInfo(std::string& filename,
755                                                         std::map<int,std::vector<std::pair<int,double> > >& interpMapValue)
756{
757  CContext* context = CContext::getCurrent();
758  CContextClient* client=context->client;
759
760  size_t n_src = domainSrc_->ni_glo * domainSrc_->nj_glo;
761  size_t n_dst = domainDest_->ni_glo * domainDest_->nj_glo;
762
763  long localNbWeight = 0;
764  long globalNbWeight;
765  long startIndex;
766  typedef std::map<int,std::vector<std::pair<int,double> > > IndexRemap;
767  IndexRemap::iterator itb = interpMapValue.begin(), it,
768                       ite = interpMapValue.end();
769  for (it = itb; it!=ite; ++it)
770  {
771    localNbWeight += (it->second).size();
772  }
773
774  CArray<int,1> src_idx(localNbWeight);
775  CArray<int,1> dst_idx(localNbWeight);
776  CArray<double,1> weights(localNbWeight);
777
778  int index = 0;
779  for (it = itb; it !=ite; ++it)
780  {
781    std::vector<std::pair<int,double> >& tmp = it->second;
782    for (int idx = 0; idx < tmp.size(); ++idx)
783    {
784      dst_idx(index) = it->first + 1;
785      src_idx(index) = tmp[idx].first + 1;
786      weights(index) = tmp[idx].second;
787      ++index;
788    }   
789  }
790
791  ep_lib::MPI_Allreduce(&localNbWeight, &globalNbWeight, 1, MPI_LONG, MPI_SUM, client->intraComm);
792  ep_lib::MPI_Scan(&localNbWeight, &startIndex, 1, MPI_LONG, MPI_SUM, client->intraComm);
793 
794  if (0 == globalNbWeight)
795  {
796    info << "There is no interpolation weights calculated between "
797         << "domain source: " << domainSrc_->getDomainOutputName()
798         << " and domain destination: " << domainDest_->getDomainOutputName()
799         << std::endl;
800    return;
801  }
802
803  std::vector<StdSize> start(1, startIndex - localNbWeight);
804  std::vector<StdSize> count(1, localNbWeight);
805
806  WriteNetCdf netCdfWriter(filename, static_cast<MPI_Comm>(client->intraComm.mpi_comm));
807
808  // Define some dimensions
809  netCdfWriter.addDimensionWrite("n_src", n_src);
810  netCdfWriter.addDimensionWrite("n_dst", n_dst);
811  netCdfWriter.addDimensionWrite("n_weight", globalNbWeight);
812 
813  std::vector<StdString> dims(1,"n_weight");
814
815  // Add some variables
816  netCdfWriter.addVariableWrite("src_idx", NC_INT, dims);
817  netCdfWriter.addVariableWrite("dst_idx", NC_INT, dims);
818  netCdfWriter.addVariableWrite("weight", NC_DOUBLE, dims);
819
820  // End of definition
821  netCdfWriter.endDefinition();
822
823  // // Write variables
824  if (0 != localNbWeight)
825  {
826    netCdfWriter.writeDataIndex(src_idx, "src_idx", false, 0, &start, &count);
827    netCdfWriter.writeDataIndex(dst_idx, "dst_idx", false, 0, &start, &count);
828    netCdfWriter.writeDataIndex(weights, "weight", false, 0, &start, &count);
829  }
830
831  netCdfWriter.closeFile();
832}
833
834/*!
835  Read interpolation information from a file
836  \param [in] filename interpolation file
837  \param [in/out] interpMapValue Mapping between (global) index of domain on grid destination and
838         corresponding global index of domain and associated weight value on grid source
839*/
840void CDomainAlgorithmInterpolate::readInterpolationInfo(std::string& filename,
841                                                        std::map<int,std::vector<std::pair<int,double> > >& interpMapValue)
842{
843  int ncid ;
844  int weightDimId ;
845  size_t nbWeightGlo ;
846
847  CContext* context = CContext::getCurrent();
848  CContextClient* client=context->client;
849  int clientRank = client->clientRank;
850  int clientSize = client->clientSize;
851
852  nc_open(filename.c_str(),NC_NOWRITE, &ncid) ;
853  nc_inq_dimid(ncid,"n_weight",&weightDimId) ;
854  nc_inq_dimlen(ncid,weightDimId,&nbWeightGlo) ;
855
856  size_t nbWeight ;
857  size_t start ;
858  size_t div = nbWeightGlo/clientSize ;
859  size_t mod = nbWeightGlo%clientSize ;
860  if (clientRank < mod)
861  {
862    nbWeight=div+1 ;
863    start=clientRank*(div+1) ;
864  }
865  else
866  {
867    nbWeight=div ;
868    start= mod * (div+1) + (clientRank-mod) * div ;
869  }
870
871  double* weight=new double[nbWeight] ;
872  int weightId ;
873  nc_inq_varid (ncid, "weight", &weightId) ;
874  nc_get_vara_double(ncid, weightId, &start, &nbWeight, weight) ;
875
876  long* srcIndex=new long[nbWeight] ;
877  int srcIndexId ;
878  nc_inq_varid (ncid, "src_idx", &srcIndexId) ;
879  nc_get_vara_long(ncid, srcIndexId, &start, &nbWeight, srcIndex) ;
880
881  long* dstIndex=new long[nbWeight] ;
882  int dstIndexId ;
883  nc_inq_varid (ncid, "dst_idx", &dstIndexId) ;
884  nc_get_vara_long(ncid, dstIndexId, &start, &nbWeight, dstIndex) ;
885
886  for(size_t ind=0; ind<nbWeight;++ind)
887    interpMapValue[dstIndex[ind]-1].push_back(make_pair(srcIndex[ind]-1,weight[ind]));
888}
889
890}
Note: See TracBrowser for help on using the repository browser.