Salome HOME
merge conflict
[modules/med.git] / src / medtool / src / INTERP_KERNEL / Interpolation3D.txx
1 // Copyright (C) 2007-2015  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License, or (at your option) any later version.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // Author : Anthony Geay (CEA/DEN)
20
21 #ifndef __INTERPOLATION3D_TXX__
22 #define __INTERPOLATION3D_TXX__
23
24 #include "Interpolation3D.hxx"
25 #include "Interpolation.txx"
26 #include "MeshElement.txx"
27 #include "TransformedTriangle.hxx"
28 #include "PolyhedronIntersectorP0P0.txx"
29 #include "PointLocator3DIntersectorP0P0.txx"
30 #include "PolyhedronIntersectorP0P1.txx"
31 #include "PointLocator3DIntersectorP0P1.txx"
32 #include "PolyhedronIntersectorP1P0.txx"
33 #include "PolyhedronIntersectorP1P0Bary.txx"
34 #include "PointLocator3DIntersectorP1P0.txx"
35 #include "PolyhedronIntersectorP1P1.txx"
36 #include "PointLocator3DIntersectorP1P1.txx"
37 #include "Barycentric3DIntersectorP1P1.txx"
38 #include "Log.hxx"
39 // If defined, use recursion to traverse the binary search tree, else use the BBTree class
40 //#define USE_RECURSIVE_BBOX_FILTER
41
42 #ifdef USE_RECURSIVE_BBOX_FILTER
43 #include "MeshRegion.txx"
44 #include "RegionNode.hxx"
45 #include <stack>
46
47 #else // use BBTree class
48
49 #include "BBTree.txx"
50
51 #endif
52
53 namespace INTERP_KERNEL
54 {
55   /**
56    * Calculates the matrix of volumes of intersection between the elements of srcMesh and the elements of targetMesh.
57    * The calculation is done in two steps. First a filtering process reduces the number of pairs of elements for which the
58    * calculation must be carried out by eliminating pairs that do not intersect based on their bounding boxes. Then, the 
59    * volume of intersection is calculated by an object of type Intersector3D for the remaining pairs, and entered into the
60    * intersection matrix. 
61    * 
62    * The matrix is partially sparse : it is a vector of maps of integer - double pairs. 
63    * It can also be an INTERP_KERNEL::Matrix object.
64    * The length of the vector is equal to the number of target elements - for each target element there is a map, regardless
65    * of whether the element intersects any source elements or not. But in the maps there are only entries for those source elements
66    * which have a non-zero intersection volume with the target element. The vector has indices running from 
67    * 0 to (nb target elements - 1), meaning that the map for target element i is stored at index i - 1. In the maps, however,
68    * the indexing is more natural : the intersection volume of the target element i with source element j is found at matrix[i-1][j].
69    * 
70
71    * @param srcMesh     3-dimensional source mesh
72    * @param targetMesh  3-dimesional target mesh, containing only tetraedra
73    * @param result      matrix in which the result is stored 
74    *
75    */
76   template<class MyMeshType, class MatrixType>
77   int Interpolation3D::interpolateMeshes(const MyMeshType& srcMesh, const MyMeshType& targetMesh, MatrixType& result, const std::string& method)
78   {
79     typedef typename MyMeshType::MyConnType ConnType;
80     // create MeshElement objects corresponding to each element of the two meshes
81     const unsigned long numSrcElems = srcMesh.getNumberOfElements();
82     const unsigned long numTargetElems = targetMesh.getNumberOfElements();
83
84     LOG(2, "Source mesh has " << numSrcElems << " elements and target mesh has " << numTargetElems << " elements ");
85
86     std::vector<MeshElement<ConnType>*> srcElems(numSrcElems);
87     std::vector<MeshElement<ConnType>*> targetElems(numTargetElems);
88
89     std::map<MeshElement<ConnType>*, int> indices;
90
91     for(unsigned long i = 0 ; i < numSrcElems ; ++i)
92       srcElems[i] = new MeshElement<ConnType>(i, srcMesh);       
93
94     for(unsigned long i = 0 ; i < numTargetElems ; ++i)
95       targetElems[i] = new MeshElement<ConnType>(i, targetMesh);
96
97     Intersector3D<MyMeshType,MatrixType>* intersector=0;
98     std::string methC = InterpolationOptions::filterInterpolationMethod(method);
99     if(methC=="P0P0")
100       {
101         switch(InterpolationOptions::getIntersectionType())
102           {
103           case Triangulation:
104             intersector=new PolyhedronIntersectorP0P0<MyMeshType,MatrixType>(targetMesh, srcMesh, getSplittingPolicy());
105             break;
106           case PointLocator:
107             intersector=new PointLocator3DIntersectorP0P0<MyMeshType,MatrixType>(targetMesh, srcMesh, getPrecision());
108             break;
109           default:
110             throw INTERP_KERNEL::Exception("Invalid 3D intersection type for P0P0 interp specified : must be Triangle or PointLocator.");
111           }
112       }
113     else if(methC=="P0P1")
114       {
115         switch(InterpolationOptions::getIntersectionType())
116           {
117           case Triangulation:
118             intersector=new PolyhedronIntersectorP0P1<MyMeshType,MatrixType>(targetMesh, srcMesh, getSplittingPolicy());
119             break;
120           case PointLocator:
121             intersector=new PointLocator3DIntersectorP0P1<MyMeshType,MatrixType>(targetMesh, srcMesh, getPrecision());
122             break;
123           default:
124             throw INTERP_KERNEL::Exception("Invalid 3D intersection type for P0P1 interp specified : must be Triangle or PointLocator.");
125           }
126       }
127     else if(methC=="P1P0")
128       {
129         switch(InterpolationOptions::getIntersectionType())
130           {
131           case Triangulation:
132             intersector=new PolyhedronIntersectorP1P0<MyMeshType,MatrixType>(targetMesh, srcMesh, getSplittingPolicy());
133             break;
134           case PointLocator:
135             intersector=new PointLocator3DIntersectorP1P0<MyMeshType,MatrixType>(targetMesh, srcMesh, getPrecision());
136             break;
137           case Barycentric:
138             intersector=new PolyhedronIntersectorP1P0Bary<MyMeshType,MatrixType>(targetMesh, srcMesh, getSplittingPolicy());
139             break;
140           default:
141             throw INTERP_KERNEL::Exception("Invalid 3D intersection type for P1P0 interp specified : must be Triangle, PointLocator or Barycentric.");
142           }
143       }
144     else if(methC=="P1P1")
145       {
146         switch(InterpolationOptions::getIntersectionType())
147           {
148           case Triangulation:
149             intersector=new PolyhedronIntersectorP1P1<MyMeshType,MatrixType>(targetMesh, srcMesh, getSplittingPolicy());
150             break;
151           case PointLocator:
152             intersector=new PointLocator3DIntersectorP1P1<MyMeshType,MatrixType>(targetMesh, srcMesh, getPrecision());
153             break;
154           case Barycentric:
155             intersector=new Barycentric3DIntersectorP1P1<MyMeshType,MatrixType>(targetMesh, srcMesh, getPrecision());
156             break;
157           default:
158             throw INTERP_KERNEL::Exception("Invalid 3D intersection type for P1P1 interp specified : must be Triangle or PointLocator.");
159           }
160       }
161     else
162       throw Exception("Invalid method choosed must be in \"P0P0\", \"P0P1\", \"P1P0\" or \"P1P1\".");
163     // create empty maps for all source elements
164     result.resize(intersector->getNumberOfRowsOfResMatrix());
165
166 #ifdef USE_RECURSIVE_BBOX_FILTER
167
168     /*
169      * Performs a depth-first search over srcMesh, using bounding boxes to recursively eliminate the elements of targetMesh
170      * which cannot intersect smaller and smaller regions of srcMesh. At each level, each region is divided in two, forming
171      * a binary search tree with leaves consisting of only one element of the source mesh together with the elements of the
172      * target mesh that can intersect it. The recursion is implemented with a stack of RegionNodes, each one containing a 
173      * source region and a target region. Each region has an associated bounding box and a vector of pointers to the elements 
174      * that belong to it. Each MeshElement contains a bounding box and the global number of the corresponding element in the mesh.
175      */
176
177     // create initial RegionNode and fill up its source region with all the source mesh elements and
178     // its target region with all the target mesh elements whose bounding box
179     // intersects that of the source region
180
181     RegionNode<ConnType>* firstNode = new RegionNode<ConnType>();
182
183     MeshRegion<ConnType>& srcRegion = firstNode->getSrcRegion();
184
185     for(unsigned long i = 0 ; i < numSrcElems ; ++i)
186       {
187         srcRegion.addElement(srcElems[i], srcMesh);
188       }
189
190     MeshRegion<ConnType>& targetRegion = firstNode->getTargetRegion();
191
192     for(unsigned long i = 0 ; i < numTargetElems ; ++i)
193       {
194         if(!srcRegion.isDisjointWithElementBoundingBox( *(targetElems[i]) ))
195           {
196             targetRegion.addElement(targetElems[i], targetMesh);
197           }
198       }
199
200     // Using a stack, descend recursively, creating at each step two new RegionNodes having as source region the left and
201     // right part of the source region of the current node (created using MeshRegion::split()) and as target region all the 
202     // elements of the target mesh whose bounding box intersects the corresponding part
203     // Continue until the source region contains only one element, at which point the intersection volumes are
204     // calculated with all the remaining target mesh elements and stored in the matrix if they are non-zero.
205
206     std::stack< RegionNode<ConnType>* > nodes;
207     nodes.push(firstNode);
208
209     while(!nodes.empty())
210       {
211         RegionNode<ConnType>* currNode = nodes.top();
212         nodes.pop();
213         LOG(4, "Popping node ");
214
215         if(currNode->getTargetRegion().getNumberOfElements() == 1)
216           {
217             // calculate volumes
218             LOG(4, " - One element");
219
220             MeshElement<ConnType>* targetElement = *(currNode->getTargetRegion().getBeginElements());
221             std::vector<ConnType> intersectElems;
222             for(typename std::vector< MeshElement<ConnType>* >::const_iterator iter = currNode->getSrcRegion().getBeginElements();iter != currNode->getSrcRegion().getEndElements();++iter)
223               intersectElems.push_back((*iter)->getIndex());
224             intersector->intersectCells(targetElement->getIndex(),intersectElems,result);
225           }
226         else // recursion 
227           {
228
229             LOG(4, " - Recursion");
230
231             RegionNode<ConnType>* leftNode = new RegionNode<ConnType>();
232             RegionNode<ConnType>* rightNode = new RegionNode<ConnType>();
233
234             // split current source region
235             //} decide on axis
236             static BoundingBox::BoxCoord axis = BoundingBox::XMAX;
237
238             currNode->getTargetRegion().split(leftNode->getTargetRegion(), rightNode->getTargetRegion(), axis, targetMesh);
239
240             LOG(5, "After split, left target region has " << leftNode->getTargetRegion().getNumberOfElements()
241                 << " elements and right target region has " << rightNode->getTargetRegion().getNumberOfElements() 
242                 << " elements");
243
244             // ugly hack to avoid problem with enum which does not start at 0
245             // I guess I ought to implement ++ for it instead ...
246             // Anyway, it basically chooses the next axis, cyclically
247             axis = (axis != BoundingBox::ZMAX) ? static_cast<BoundingBox::BoxCoord>(axis + 1) : BoundingBox::XMAX;
248
249             // add source elements of current node that overlap the target regions of the new nodes
250             LOG(5, " -- Adding source elements");
251             int numLeftElements = 0;
252             int numRightElements = 0;
253             for(typename std::vector<MeshElement<ConnType>*>::const_iterator iter = currNode->getSrcRegion().getBeginElements() ; 
254                 iter != currNode->getSrcRegion().getEndElements() ; ++iter)
255               {
256                 LOG(6, " --- New target node");
257
258                 if(!leftNode->getTargetRegion().isDisjointWithElementBoundingBox(**iter))
259                   {
260                     leftNode->getSrcRegion().addElement(*iter, srcMesh);
261                     ++numLeftElements;
262                   }
263
264                 if(!rightNode->getTargetRegion().isDisjointWithElementBoundingBox(**iter))
265                   {
266                     rightNode->getSrcRegion().addElement(*iter, srcMesh);
267                     ++numRightElements;
268                   }
269
270               }
271
272             LOG(5, "Left src region has " << numLeftElements << " elements and right src region has " 
273                 << numRightElements << " elements");
274
275             // push new nodes on stack
276             if(numLeftElements != 0)
277               {
278                 nodes.push(leftNode);
279               }
280             else
281               {
282                 delete leftNode;
283               }
284
285             if(numRightElements != 0)
286               {
287                 nodes.push(rightNode);
288               }
289             else
290               {
291                 delete rightNode;
292               }
293           }
294
295         // all nodes are deleted here
296         delete currNode;
297
298         LOG(4, "Next iteration. Nodes left : " << nodes.size());
299       }
300
301 #else // Use BBTree
302
303       // create BBTree structure
304       // - get bounding boxes
305     double* bboxes = new double[6 * numSrcElems];
306     int* srcElemIdx = new int[numSrcElems];
307     for(unsigned long i = 0; i < numSrcElems ; ++i)
308       {
309         // get source bboxes in right order
310         const BoundingBox* box = srcElems[i]->getBoundingBox();
311         bboxes[6*i+0] = box->getCoordinate(BoundingBox::XMIN);
312         bboxes[6*i+1] = box->getCoordinate(BoundingBox::XMAX);
313         bboxes[6*i+2] = box->getCoordinate(BoundingBox::YMIN);
314         bboxes[6*i+3] = box->getCoordinate(BoundingBox::YMAX);
315         bboxes[6*i+4] = box->getCoordinate(BoundingBox::ZMIN);
316         bboxes[6*i+5] = box->getCoordinate(BoundingBox::ZMAX);
317
318         // source indices have to begin with zero for BBox, I think
319         srcElemIdx[i] = srcElems[i]->getIndex();
320       }
321
322     BBTree<3,ConnType> tree(bboxes, srcElemIdx, 0, numSrcElems);
323
324     // for each target element, get source elements with which to calculate intersection
325     // - calculate intersection by calling intersectCells
326     for(unsigned long i = 0; i < numTargetElems; ++i)
327       {
328         const BoundingBox* box = targetElems[i]->getBoundingBox();
329         const int targetIdx = targetElems[i]->getIndex();
330
331         // get target bbox in right order
332         double targetBox[6];
333         targetBox[0] = box->getCoordinate(BoundingBox::XMIN);
334         targetBox[1] = box->getCoordinate(BoundingBox::XMAX);
335         targetBox[2] = box->getCoordinate(BoundingBox::YMIN);
336         targetBox[3] = box->getCoordinate(BoundingBox::YMAX);
337         targetBox[4] = box->getCoordinate(BoundingBox::ZMIN);
338         targetBox[5] = box->getCoordinate(BoundingBox::ZMAX);
339
340         std::vector<ConnType> intersectElems;
341
342         tree.getIntersectingElems(targetBox, intersectElems);
343
344         if ( !intersectElems.empty() )
345           intersector->intersectCells(targetIdx,intersectElems,result);
346       }
347
348     delete [] bboxes;
349     delete [] srcElemIdx;
350
351 #endif
352     // free allocated memory
353     int ret=intersector->getNumberOfColsOfResMatrix();
354
355     delete intersector;
356
357     for(unsigned long i = 0 ; i < numSrcElems ; ++i)
358       {
359         delete srcElems[i];
360       }
361     for(unsigned long i = 0 ; i < numTargetElems ; ++i)
362       {
363         delete targetElems[i];
364       }
365     return ret;
366
367   }
368 }
369
370 #endif