source: XIOS/dev/branch_openmp/src/transformation/domain_algorithm_interpolate.cpp @ 1482

Last change on this file since 1482 was 1482, checked in by yushan, 6 years ago

Branch EP merged with Dev_cmip6 @r1481

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