BackgroundMesh2.h 13.1 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/******************************************************************************
 *
 * Extension of AMDiS - Adaptive multidimensional simulations
 *
 * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.
 * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis
 *
 * Authors: Simon Praetorius et al.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *
 * See also license.opensource.txt in the distribution.
 * 
 ******************************************************************************/
17

18
19
20

#ifndef EXTENSIONS_BACKGROUND_MESH2_H
#define EXTENSIONS_BACKGROUND_MESH2_H
21
22
23
24

#include "AMDiS.h"
#include "Tools.h"

25
#ifndef USE_EXPERIMENTAL
26
#define USE_EXPERIMENTAL
27
#endif
28
29
30
31
32
33
34

namespace experimental {

typedef WorldVector<double> PointType_;
typedef boost::tuple<const MacroElement*, int, unsigned long> ElInfoDataType; // data to recover elInfo
typedef std::pair<ElInfoDataType, PointType_> DataType_;

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// PointType ... type of coordinate vectors, e.g. WorldVector<double> in AMDiS
// DataType .... use DataType_ to look for ElInfos near coordinates

/** \brief Background-mesh structure for finding elements
  * Can be used to find k nearest elements to a given point. It uses a one
  * level background-mesh to look for a box where the point lies inside and
  * compares the distance to all element centers in the box, respective with the
  * elements in the surrounding boxes.
  * The elements to look for are stores as DataType-objects, e.g. tuples of 
  * MacroElement*, refinementPath and refinementPathLength. This makes it 
  * possible to create a new ElInfo object from the mesh.
  * 
  * To use this class call ElementBox<P,D>::provideBackgroundMesh(feSpace) with 
  * feSpace a FiniteElemSpace holding the mesh with all elements you want to look for.
  * The template-arguments correspond to coordinate-vector type P and D a type
  * in wich the elInfo is stored. Use PointType_ and DataType_ as defaults.
  * Or add an individual fillBox method that adds all the elements in the 
  * form of DataType to the box by calling addData for each element.
  **/
template<typename PointType=PointType_, typename DataType=DataType_>
55
56
struct ElementBox {

57
58
59
60
61
62
  /** \brief Constructor for BackgroundMesh 
   * Mesh is enclosed in default box [-1,1]^2.
   * 
   * \param DOW_ dimension of world
   * \param N_ vector containing number of boxes per dimension [Nx,Ny,Nz]
   **/
63
64
65
66
67
68
69
70
  ElementBox(int DOW_, std::vector<int> N_)
  : DOW(DOW_), N(N_), boxFilled(false)
  {
    min_corner.set(-1.0);
    max_corner.set(1.0);
    init();
  }
  
71
72
73
74
75
76
77
78
  /** \brief Constructor for BackgroundMesh 
   * Mesh is enclosed in a box given by the user.
   * 
   * \param DOW_ dimension of world
   * \param min_corner_ lower-left[-front] corner of enclosing box
   * \param max_corner_ upper-right[-back] corner of enclosing box
   * \param N_ vector containing number of boxes per dimension [Nx,Ny,Nz]
   **/
79
80
81
82
83
84
85
86
87
  ElementBox(int DOW_, PointType min_corner_, PointType max_corner_, std::vector<int> N_)
  : DOW(DOW_), 
    min_corner(min_corner_),
    max_corner(max_corner_),
    N(N_), boxFilled(false)
  {
    init();
  }
    
88
89
    
  /// add all elements of mesh corresponding to the feSpace to the background-mesh
90
91
  void fillBox(const FiniteElemSpace* feSpace);  
  
92
93
  
  /// delete and clear all boxes
94
95
96
97
98
99
  void clearBox()
  {
    boxData.clear();
  }
  
  
100
  /// calculate boxSize
101
102
103
104
105
106
107
108
109
110
  int getMaxBoxSize()
  {
    size_t maxSize = 0;
    for (size_t i = 0; i < boxData.size(); i++) {
      maxSize = std::max(maxSize, boxData[i].size());
    }
    return maxSize;
  }
  
  
111
  /// test of point x lies in current box
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
  bool inBox(PointType& x)
  {
    for (size_t i = 0; i < DOW; i++)
      if (min_corner[i] > x[i] || max_corner[i] < x[i])
	return false;
    return true;
  }
  
  /**
   * 
   * Ny=2
   * ^----------------
   * | 4 | 5 | 6 | 7 |
   * ----+---+---+----
   * | 0 | 1 | 2 | 3 |
   * -----------------> Nx=4
   **/
  
  int getBox(PointType& x)
  {
    std::vector<int> idx(DOW);
    for (size_t i = 0; i < DOW; i++)
      idx[i] = static_cast<int>(floor((x[i]-min_corner[i])*N[i]/(max_corner[i]-min_corner[i])));
    return idx2nr(idx);
  }
  
  
139
140
141
  /// return ElInfo* created from DataType data nearest to x.
  /// Template specialization for DataType=DataType_ and
  /// PointType=PointType_ provided.
142
143
144
  bool getNearestElInfo(PointType &x, ElInfo*& minElInfo);
  
  
145
146
  /// get object of type DataType nearest to given coordinate x,
  /// where data can be used to create an ElInfo from the mesh.
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
  bool getNearestData(PointType& x, DataType& data)
  {
    if (!inBox(x))
      return false;
    
    int nr = getBox(x);
    if (boxData[nr].size() == 0) {
      std::vector<DataType> datas;
      getNearestData(x, datas, 1);
      data = datas[0];
      return true;
    }
    std::vector<double> distances;
    typename std::vector<DataType>::iterator dataIter;
    for (dataIter = boxData[nr].begin(); dataIter != boxData[nr].end(); dataIter++) {
      distances.push_back(norm(x - (*dataIter).second));
    }
    double minDist = 1.e15;
    size_t minIdx = 0;
    vector_operations::getMin(distances, minDist, minIdx);
    data = boxData[nr][minIdx];
    return true;
  }
  
171
172
173
  
  /// get nData objects of type DataType nearest to given coordinate x,
  /// where data can be used to create an ElInfo from the mesh.
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
  bool getNearestData(PointType& x, std::vector<DataType>& data, int nData)
  {
    if (!inBox(x))
      return false;
    
    std::set<int> nrs; nrs.insert(getBox(x));
    double boxBoundaryDist = getBoxBoundaryDist(*(nrs.begin()), x);
    std::vector<int> visited;
    std::vector<int>::iterator visitedIter;
    std::set<int>::iterator nrIter;
    int level = 0;
    for (int level = 0; data.size() < nData && nrs.size() > 0; level++) {
      for (nrIter = nrs.begin(); nrIter != nrs.end(); nrIter++) {
	data.insert(data.end(), boxData[*nrIter].begin(), boxData[*nrIter].end());
      }
      visited.insert(visited.end(), nrs.begin(), nrs.end());
      
      std::vector<double> distances;
      if (data.size() > 0) {
	// 1.) bestimme Abstand zu x 
	for (size_t i = 0; i < data.size(); i++) {
	  distances.push_back(norm(x - data[i].second));
	}
	// 2.) sortiere Paare aus dist und data
	compare0<double, DataType> comp;
	vector_operations::sort(distances, data, comp);
      }
      
      // 3.) wenn noch nicht genügend Punkte, dann umgebende Boxen mit durchsuchen
      if (data.size() < nData 
	|| (level == 0 && distances[std::min(nData,static_cast<int>(distances.size()))-1] > boxBoundaryDist))
      {
	std::set<int> surrounding_nrs;
	getSurroundingBoxes(nrs, surrounding_nrs);
	swap (nrs, surrounding_nrs);
      }
      
      for (visitedIter = visited.begin(); visitedIter != visited.end(); visitedIter++)
	nrs.erase(*visitedIter);
    }
    data.resize(nData);
    return true;
  }

  /**
   * strategies:
   * 0 .. get nearest point to x and eval DOFVector at this DOF-index
   * 1 .. get n nearest points, calc weighted sum of data at these points
   * 2 .. get n nearest points, calc regression plane and eval at x
   * 3 .. get n nearest points, calc weighted regression plane and eval at x
   **/
  template<typename T>
  T evalAtPoint(DOFVector<T>& vec, PointType& x, int strategy = 0, int nrOfPoints = -1)
  {
    T value;
    switch (strategy) {
      case 0:
	value = evalAtPoint_simple(vec, x);
	break;   
      default:
	ERROR("ERROR: unknown strategy [%d]!\n",strategy);
	break;
    }
    return value;
  }

  
241
242
243
244
245
246
247
248
  /** \brief create background-mesh structure for given feSpace
   * Using fillBox() implementation to store element-information in the DataType_
   * format in the background-mesh structure. When a new background mesh is created
   * parameters about size are read from init-file:
   * - <c>backgroundMesh->N</c> reads to \ref N
   * - <c>backgroundMesh->min_corner</c> reads to \ref min_corner
   * - <c>backgroundMesh->max_corner</c> reads to \ref max_corner
   **/
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
  static ElementBox<PointType, DataType>* provideBackgroundMesh(const FiniteElemSpace* feSpace)
  {
    if (boxMap.find(feSpace) != boxMap.end()) {
      if (boxMap[feSpace].first != feSpace->getMesh()->getChangeIndex()) {
	boxMap[feSpace].second->clearBox();
	boxMap[feSpace].second->init();
	boxMap[feSpace].second->fillBox(feSpace);
	boxMap[feSpace].first = feSpace->getMesh()->getChangeIndex();
	std::cout<<"max box size = "<<boxMap[feSpace].second->getMaxBoxSize()<<"\n";   
      }
    } else {
      int N_const = 2;
      PointType min_corner_; min_corner_.set(-1.0);
      PointType max_corner_; max_corner_.set(1.0);
      Parameters::get("backgroundMesh->N", N_const);
      Parameters::get("backgroundMesh->min_corner", min_corner_);
      Parameters::get("backgroundMesh->max_corner", max_corner_);
      std::vector<int> N_(Global::getGeo(WORLD), N_const);
      ElementBox<PointType, DataType>* box = new ElementBox<PointType, DataType>(Global::getGeo(WORLD), min_corner_, max_corner_, N_);
      box->fillBox(feSpace);
      
      boxMap[feSpace] = std::make_pair(feSpace->getMesh()->getChangeIndex(), box);   
      std::cout<<"max box size = "<<boxMap[feSpace].second->getMaxBoxSize()<<"\n";   
    }
    
    return boxMap[feSpace].second;
  }
  
277
  /// clear background mesh
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
  static void delete_all()
  {
    typename std::map<const FiniteElemSpace*, std::pair<int, ElementBox<PointType, DataType>*> >::iterator boxIter;
    for (boxIter = boxMap.begin(); boxIter != boxMap.end(); boxIter++) {
      (*boxIter).second.second->clearBox();
      delete (*boxIter).second.second;
    }
    boxMap.clear();
  }
  
  void init()
  {
    int maxNr = 1.0;
    for (size_t i = 0; i < DOW; i++)
      maxNr *= N[i];
    boxData.resize(maxNr);
    
    std::cout<<"\n background mesh\n";
    std::cout<<"=================\n";
    std::cout<<"min_corner: "<<min_corner<<"\n";
    std::cout<<"max_corner: "<<max_corner<<"\n";
    std::cout<<"N: "<<N<<"\n\n";
    
    PointType tolerance; tolerance.set(2.0*DBL_TOL);
    min_corner -= tolerance;
    max_corner += tolerance;
  }
  
protected:
  
  template<typename T>
  T evalAtPoint_simple(DOFVector<T>& vec, PointType& x);
  
  inline int idx2nr(std::vector<int>& idx)
  {
    int nr = idx.back();
    std::vector<int>::reverse_iterator iIter, nIter;
    for (iIter = idx.rbegin()+1, nIter = N.rbegin()+1; iIter < idx.rend(); iIter++,nIter++) {
      nr = *iIter + nr*(*nIter);
    }
    return nr;
  }
  
321
  inline void nr2idx(int nr, std::vector<int>& idx)
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
  {
    switch (DOW) {
      case 1:
	idx.resize(1);
	idx[0] = nr % N[0];
	break;
      case 2:
	idx.resize(2);
	idx[1] = nr / N[0];
	idx[0] = nr % N[0];
	break;
      case 3:
	idx.resize(3);
	idx[2] = nr / (N[1]*N[0]);
	nr = nr % (N[1]*N[0]);
	idx[1] = nr / N[0];
	idx[0] = nr % N[0];
	break;
      default:
	throw(std::runtime_error("DOW="+boost::lexical_cast<std::string>(DOW)+", nur die Version für DOW=1 verwendet!"));
	break;
    }
  }
  
346
  /// get indices of boxes surrounding the box with given nr
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
  void getSurroundingBoxes(int nr, std::set<int> &surrounding_nrs)
  {
    std::vector<int> idx;
    nr2idx(nr, idx); // --> idx
    
    for (size_t i = 0; i < DOW; i++) {
      std::vector<int> idx_i = idx;
      idx_i[i] = std::min(N[i]-1, idx_i[i]+1);
      surrounding_nrs.insert(idx2nr(idx_i));
      idx_i[i] = std::max(0, idx_i[i]-2);
      surrounding_nrs.insert(idx2nr(idx_i));
    }
    surrounding_nrs.erase(nr);
  }
  
362
363
  
  /// get indices of boxes surrounding the boxes with given set of nrs
364
365
366
367
368
369
370
371
372
373
  void getSurroundingBoxes(std::set<int> &nrs, std::set<int> &surrounding_nrs)
  {
    std::set<int>::iterator nrsIter;
    for (nrsIter = nrs.begin(); nrsIter != nrs.end(); nrsIter++)
      getSurroundingBoxes(*nrsIter, surrounding_nrs);
    
    for (nrsIter = nrs.begin(); nrsIter != nrs.end(); nrsIter++)
      surrounding_nrs.erase(*nrsIter);
  }  
  
374
  /// get minimal distance of box-boundaries to x
375
376
377
378
379
380
381
382
383
384
385
  double getBoxBoundaryDist(int nr, PointType& x)
  {
    std::vector<int> idx;
    nr2idx(nr, idx);
    PointType min_c, max_c;
    for (size_t i = 0; i < DOW; i++) {
      min_c[i] = min_corner[i] + (max_corner[i]-min_corner[i])*idx[i]/N[i];
      max_c[i] = min_corner[i] + (max_corner[i]-min_corner[i])*(idx[i]+1)/N[i];
    }
    double dist = 1.e15;
    for (int i = 0; i < DOW; i++)
386
      dist = std::min(dist, std::min(std::abs(max_c[i]-x[i]), std::abs(min_c[i]-x[i])));
387
388
389
    return dist;
  }
  
390
  /// add data to the background-mesh at point x
391
392
393
394
395
396
397
398
  void addData(PointType x, DataType data)
  {
    int nr = getBox(x);
    if (nr < 0 || nr >= boxData.size())
      throw(std::runtime_error("box-nr out of range: nr = "+boost::lexical_cast<std::string>(nr)+", boxSize = "+boost::lexical_cast<std::string>(boxData.size())));
    boxData[nr].push_back(data);
  }
  
399
  /// used by \ref provideBackgroundMesh
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
  static typename std::map<const FiniteElemSpace*, std::pair<int, ElementBox<PointType, DataType>*> > boxMap;

protected:

  int DOW;
  std::vector<int> N;
  bool boxFilled;

  PointType min_corner;
  PointType max_corner;
  
  std::vector<std::vector<DataType> > boxData;
};

template<typename PointType, typename DataType>
std::map<const FiniteElemSpace*, std::pair<int, ElementBox<PointType, DataType>*> > ElementBox<PointType, DataType>::boxMap;

} // end namespace tools

#include "BackgroundMesh2.hh"

421
#endif // EXTENSIONS_BACKGROUND_MESH2_H