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