Salome HOME
Preparing skyline: now a RefCount object.
[tools/medcoupling.git] / src / MEDCoupling / MEDCouplingUMesh.cxx
1 // Copyright (C) 2007-2016  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 #include "MEDCouplingUMesh.hxx"
22 #include "MEDCouplingCMesh.hxx"
23 #include "MEDCoupling1GTUMesh.hxx"
24 #include "MEDCouplingFieldDouble.hxx"
25 #include "MEDCouplingSkyLineArray.hxx"
26 #include "CellModel.hxx"
27 #include "VolSurfUser.txx"
28 #include "InterpolationUtils.hxx"
29 #include "PointLocatorAlgos.txx"
30 #include "BBTree.txx"
31 #include "BBTreeDst.txx"
32 #include "SplitterTetra.hxx"
33 #include "DiameterCalculator.hxx"
34 #include "DirectedBoundingBox.hxx"
35 #include "InterpKernelMatrixTools.hxx"
36 #include "InterpKernelMeshQuality.hxx"
37 #include "InterpKernelCellSimplify.hxx"
38 #include "InterpKernelGeo2DEdgeArcCircle.hxx"
39 #include "InterpKernelAutoPtr.hxx"
40 #include "InterpKernelGeo2DNode.hxx"
41 #include "InterpKernelGeo2DEdgeLin.hxx"
42 #include "InterpKernelGeo2DEdgeArcCircle.hxx"
43 #include "InterpKernelGeo2DQuadraticPolygon.hxx"
44 #include "MEDCouplingUMesh_internal.hxx"
45
46 #include <sstream>
47 #include <fstream>
48 #include <numeric>
49 #include <cstring>
50 #include <limits>
51 #include <list>
52
53 using namespace MEDCoupling;
54
55 double MEDCouplingUMesh::EPS_FOR_POLYH_ORIENTATION=1.e-14;
56
57 /// @cond INTERNAL
58 const INTERP_KERNEL::NormalizedCellType MEDCouplingUMesh::MEDMEM_ORDER[N_MEDMEM_ORDER] = { INTERP_KERNEL::NORM_POINT1, INTERP_KERNEL::NORM_SEG2, INTERP_KERNEL::NORM_SEG3, INTERP_KERNEL::NORM_SEG4, INTERP_KERNEL::NORM_POLYL, INTERP_KERNEL::NORM_TRI3, INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6, INTERP_KERNEL::NORM_TRI7, INTERP_KERNEL::NORM_QUAD8, INTERP_KERNEL::NORM_QUAD9, INTERP_KERNEL::NORM_POLYGON, INTERP_KERNEL::NORM_QPOLYG, INTERP_KERNEL::NORM_TETRA4, INTERP_KERNEL::NORM_PYRA5, INTERP_KERNEL::NORM_PENTA6, INTERP_KERNEL::NORM_HEXA8, INTERP_KERNEL::NORM_HEXGP12, INTERP_KERNEL::NORM_TETRA10, INTERP_KERNEL::NORM_PYRA13, INTERP_KERNEL::NORM_PENTA15, INTERP_KERNEL::NORM_HEXA20, INTERP_KERNEL::NORM_HEXA27, INTERP_KERNEL::NORM_POLYHED };
59 const int MEDCouplingUMesh::MEDCOUPLING2VTKTYPETRADUCER[INTERP_KERNEL::NORM_MAXTYPE+1]={1,3,21,5,9,7,22,34,23,28,-1,-1,-1,-1,10,14,13,-1,12,-1,24,-1,16,27,-1,26,-1,29,-1,-1,25,42,36,4};
60 /// @endcond
61
62 MEDCouplingUMesh *MEDCouplingUMesh::New()
63 {
64   return new MEDCouplingUMesh;
65 }
66
67 MEDCouplingUMesh *MEDCouplingUMesh::New(const std::string& meshName, int meshDim)
68 {
69   MEDCouplingUMesh *ret=new MEDCouplingUMesh;
70   ret->setName(meshName);
71   ret->setMeshDimension(meshDim);
72   return ret;
73 }
74
75 /*!
76  * Returns a new MEDCouplingUMesh which is a full copy of \a this one. No data is shared
77  * between \a this and the new mesh.
78  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingMesh. The caller is to
79  *          delete this mesh using decrRef() as it is no more needed. 
80  */
81 MEDCouplingUMesh *MEDCouplingUMesh::deepCopy() const
82 {
83   return clone(true);
84 }
85
86
87 /*!
88  * Returns a new MEDCouplingUMesh which is a copy of \a this one.
89  *  \param [in] recDeepCpy - if \a true, the copy is deep, else all data arrays of \a
90  * this mesh are shared by the new mesh.
91  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingMesh. The caller is to
92  *          delete this mesh using decrRef() as it is no more needed. 
93  */
94 MEDCouplingUMesh *MEDCouplingUMesh::clone(bool recDeepCpy) const
95 {
96   return new MEDCouplingUMesh(*this,recDeepCpy);
97 }
98
99 /*!
100  * This method behaves mostly like MEDCouplingUMesh::deepCopy method, except that only nodal connectivity arrays are deeply copied.
101  * The coordinates are shared between \a this and the returned instance.
102  * 
103  * \return MEDCouplingUMesh * - A new object instance holding the copy of \a this (deep for connectivity, shallow for coordiantes)
104  * \sa MEDCouplingUMesh::deepCopy
105  */
106 MEDCouplingUMesh *MEDCouplingUMesh::deepCopyConnectivityOnly() const
107 {
108   checkConnectivityFullyDefined();
109   MCAuto<MEDCouplingUMesh> ret=clone(false);
110   MCAuto<DataArrayInt> c(getNodalConnectivity()->deepCopy()),ci(getNodalConnectivityIndex()->deepCopy());
111   ret->setConnectivity(c,ci);
112   return ret.retn();
113 }
114
115 void MEDCouplingUMesh::shallowCopyConnectivityFrom(const MEDCouplingPointSet *other)
116 {
117   if(!other)
118     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::shallowCopyConnectivityFrom : input pointer is null !");
119   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
120   if(!otherC)
121     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::shallowCopyConnectivityFrom : input pointer is not an MEDCouplingUMesh instance !");
122   MEDCouplingUMesh *otherC2=const_cast<MEDCouplingUMesh *>(otherC);//sorry :(
123   setConnectivity(otherC2->getNodalConnectivity(),otherC2->getNodalConnectivityIndex(),true);
124 }
125
126 std::size_t MEDCouplingUMesh::getHeapMemorySizeWithoutChildren() const
127 {
128   std::size_t ret(MEDCouplingPointSet::getHeapMemorySizeWithoutChildren());
129   return ret;
130 }
131
132 std::vector<const BigMemoryObject *> MEDCouplingUMesh::getDirectChildrenWithNull() const
133 {
134   std::vector<const BigMemoryObject *> ret(MEDCouplingPointSet::getDirectChildrenWithNull());
135   ret.push_back(_nodal_connec);
136   ret.push_back(_nodal_connec_index);
137   return ret;
138 }
139
140 void MEDCouplingUMesh::updateTime() const
141 {
142   MEDCouplingPointSet::updateTime();
143   if(_nodal_connec)
144     {
145       updateTimeWith(*_nodal_connec);
146     }
147   if(_nodal_connec_index)
148     {
149       updateTimeWith(*_nodal_connec_index);
150     }
151 }
152
153 MEDCouplingUMesh::MEDCouplingUMesh():_mesh_dim(-2),_nodal_connec(0),_nodal_connec_index(0)
154 {
155 }
156
157 /*!
158  * Checks if \a this mesh is well defined. If no exception is thrown by this method,
159  * then \a this mesh is most probably is writable, exchangeable and available for most
160  * of algorithms. When a mesh is constructed from scratch, it is a good habit to call
161  * this method to check that all is in order with \a this mesh.
162  *  \throw If the mesh dimension is not set.
163  *  \throw If the coordinates array is not set (if mesh dimension != -1 ).
164  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
165  *  \throw If the connectivity data array has more than one component.
166  *  \throw If the connectivity data array has a named component.
167  *  \throw If the connectivity index data array has more than one component.
168  *  \throw If the connectivity index data array has a named component.
169  */
170 void MEDCouplingUMesh::checkConsistencyLight() const
171 {
172   if(_mesh_dim<-1)
173     throw INTERP_KERNEL::Exception("No mesh dimension specified !");
174   if(_mesh_dim!=-1)
175     MEDCouplingPointSet::checkConsistencyLight();
176   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=_types.begin();iter!=_types.end();iter++)
177     {
178       if((int)INTERP_KERNEL::CellModel::GetCellModel(*iter).getDimension()!=_mesh_dim)
179         {
180           std::ostringstream message;
181           message << "Mesh invalid because dimension is " << _mesh_dim << " and there is presence of cell(s) with type " << (*iter);
182           throw INTERP_KERNEL::Exception(message.str().c_str());
183         }
184     }
185   if(_nodal_connec)
186     {
187       if(_nodal_connec->getNumberOfComponents()!=1)
188         throw INTERP_KERNEL::Exception("Nodal connectivity array is expected to be with number of components set to one !");
189       if(_nodal_connec->getInfoOnComponent(0)!="")
190         throw INTERP_KERNEL::Exception("Nodal connectivity array is expected to have no info on its single component !");
191     }
192   else
193     if(_mesh_dim!=-1)
194       throw INTERP_KERNEL::Exception("Nodal connectivity array is not defined !");
195   if(_nodal_connec_index)
196     {
197       if(_nodal_connec_index->getNumberOfComponents()!=1)
198         throw INTERP_KERNEL::Exception("Nodal connectivity index array is expected to be with number of components set to one !");
199       if(_nodal_connec_index->getInfoOnComponent(0)!="")
200         throw INTERP_KERNEL::Exception("Nodal connectivity index array is expected to have no info on its single component !");
201     }
202   else
203     if(_mesh_dim!=-1)
204       throw INTERP_KERNEL::Exception("Nodal connectivity index array is not defined !");
205 }
206
207 /*!
208  * Checks if \a this mesh is well defined. If no exception is thrown by this method,
209  * then \a this mesh is most probably is writable, exchangeable and available for all
210  * algorithms. <br> In addition to the checks performed by checkConsistencyLight(), this
211  * method thoroughly checks the nodal connectivity.
212  *  \param [in] eps - a not used parameter.
213  *  \throw If the mesh dimension is not set.
214  *  \throw If the coordinates array is not set (if mesh dimension != -1 ).
215  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
216  *  \throw If the connectivity data array has more than one component.
217  *  \throw If the connectivity data array has a named component.
218  *  \throw If the connectivity index data array has more than one component.
219  *  \throw If the connectivity index data array has a named component.
220  *  \throw If number of nodes defining an element does not correspond to the type of element.
221  *  \throw If the nodal connectivity includes an invalid node id.
222  */
223 void MEDCouplingUMesh::checkConsistency(double eps) const
224 {
225   checkConsistencyLight();
226   if(_mesh_dim==-1)
227     return ;
228   int meshDim=getMeshDimension();
229   int nbOfNodes=getNumberOfNodes();
230   int nbOfCells=getNumberOfCells();
231   const int *ptr=_nodal_connec->getConstPointer();
232   const int *ptrI=_nodal_connec_index->getConstPointer();
233   for(int i=0;i<nbOfCells;i++)
234     {
235       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)ptr[ptrI[i]]);
236       if((int)cm.getDimension()!=meshDim)
237         {
238           std::ostringstream oss;
239           oss << "MEDCouplingUMesh::checkConsistency : cell << #" << i<< " with type Type " << cm.getRepr() << " in 'this' whereas meshdim == " << meshDim << " !";
240           throw INTERP_KERNEL::Exception(oss.str());
241         }
242       int nbOfNodesInCell=ptrI[i+1]-ptrI[i]-1;
243       if(!cm.isDynamic())
244         if(nbOfNodesInCell!=(int)cm.getNumberOfNodes())
245           {
246             std::ostringstream oss;
247             oss << "MEDCouplingUMesh::checkConsistency : cell #" << i << " with static Type '" << cm.getRepr() << "' has " <<  cm.getNumberOfNodes();
248             oss << " nodes whereas in connectivity there is " << nbOfNodesInCell << " nodes ! Looks very bad !";
249             throw INTERP_KERNEL::Exception(oss.str());
250           }
251       if(cm.isQuadratic() && cm.isDynamic() && meshDim == 2)
252         if (nbOfNodesInCell % 2 || nbOfNodesInCell < 4)
253           {
254             std::ostringstream oss;
255             oss << "MEDCouplingUMesh::checkConsistency : cell #" << i << " with quadratic type '" << cm.getRepr() << "' has " <<  nbOfNodesInCell;
256             oss << " nodes. This should be even, and greater or equal than 4!! Looks very bad!";
257             throw INTERP_KERNEL::Exception(oss.str());
258           }
259       for(const int *w=ptr+ptrI[i]+1;w!=ptr+ptrI[i+1];w++)
260         {
261           int nodeId=*w;
262           if(nodeId>=0)
263             {
264               if(nodeId>=nbOfNodes)
265                 {
266                   std::ostringstream oss; oss << "Cell #" << i << " is built with node #" << nodeId << " whereas there are only " << nbOfNodes << " nodes in the mesh !";
267                   throw INTERP_KERNEL::Exception(oss.str());
268                 }
269             }
270           else if(nodeId<-1)
271             {
272               std::ostringstream oss; oss << "Cell #" << i << " is built with node #" << nodeId << " in connectivity ! sounds bad !";
273               throw INTERP_KERNEL::Exception(oss.str());
274             }
275           else
276             {
277               if((INTERP_KERNEL::NormalizedCellType)(ptr[ptrI[i]])!=INTERP_KERNEL::NORM_POLYHED)
278                 {
279                   std::ostringstream oss; oss << "Cell #" << i << " is built with node #-1 in connectivity ! sounds bad !";
280                   throw INTERP_KERNEL::Exception(oss.str());
281                 }
282             }
283         }
284     }
285 }
286
287 /*!
288  * Sets dimension of \a this mesh. The mesh dimension in general depends on types of
289  * elements contained in the mesh. For more info on the mesh dimension see
290  * \ref MEDCouplingUMeshPage.
291  *  \param [in] meshDim - a new mesh dimension.
292  *  \throw If \a meshDim is invalid. A valid range is <em> -1 <= meshDim <= 3</em>.
293  */
294 void MEDCouplingUMesh::setMeshDimension(int meshDim)
295 {
296   if(meshDim<-1 || meshDim>3)
297     throw INTERP_KERNEL::Exception("Invalid meshDim specified ! Must be greater or equal to -1 and lower or equal to 3 !");
298   _mesh_dim=meshDim;
299   declareAsNew();
300 }
301
302 /*!
303  * Allocates memory to store an estimation of the given number of cells. The closer is the estimation to the number of cells effectively inserted,
304  * the less will the library need to reallocate memory. If the number of cells to be inserted is not known simply put 0 to this parameter.
305  * If a nodal connectivity previouly existed before the call of this method, it will be reset.
306  *
307  *  \param [in] nbOfCells - estimation of the number of cell \a this mesh will contain.
308  *
309  *  \if ENABLE_EXAMPLES
310  *  \ref medcouplingcppexamplesUmeshStdBuild1 "Here is a C++ example".<br>
311  *  \ref medcouplingpyexamplesUmeshStdBuild1 "Here is a Python example".
312  *  \endif
313  */
314 void MEDCouplingUMesh::allocateCells(int nbOfCells)
315 {
316   if(nbOfCells<0)
317     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::allocateCells : the input number of cells should be >= 0 !");
318   if(_nodal_connec_index)
319     {
320       _nodal_connec_index->decrRef();
321     }
322   if(_nodal_connec)
323     {
324       _nodal_connec->decrRef();
325     }
326   _nodal_connec_index=DataArrayInt::New();
327   _nodal_connec_index->reserve(nbOfCells+1);
328   _nodal_connec_index->pushBackSilent(0);
329   _nodal_connec=DataArrayInt::New();
330   _nodal_connec->reserve(2*nbOfCells);
331   _types.clear();
332   declareAsNew();
333 }
334
335 /*!
336  * Appends a cell to the connectivity array. For deeper understanding what is
337  * happening see \ref MEDCouplingUMeshNodalConnectivity.
338  *  \param [in] type - type of cell to add.
339  *  \param [in] size - number of nodes constituting this cell.
340  *  \param [in] nodalConnOfCell - the connectivity of the cell to add.
341  * 
342  *  \if ENABLE_EXAMPLES
343  *  \ref medcouplingcppexamplesUmeshStdBuild1 "Here is a C++ example".<br>
344  *  \ref medcouplingpyexamplesUmeshStdBuild1 "Here is a Python example".
345  *  \endif
346  */
347 void MEDCouplingUMesh::insertNextCell(INTERP_KERNEL::NormalizedCellType type, int size, const int *nodalConnOfCell)
348 {
349   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
350   if(_nodal_connec_index==0)
351     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::insertNextCell : nodal connectivity not set ! invoke allocateCells before calling insertNextCell !");
352   if((int)cm.getDimension()==_mesh_dim)
353     {
354       if(!cm.isDynamic())
355         if(size!=(int)cm.getNumberOfNodes())
356           {
357             std::ostringstream oss; oss << "MEDCouplingUMesh::insertNextCell : Trying to push a " << cm.getRepr() << " cell with a size of " << size;
358             oss << " ! Expecting " << cm.getNumberOfNodes() << " !";
359             throw INTERP_KERNEL::Exception(oss.str());
360           }
361       int idx=_nodal_connec_index->back();
362       int val=idx+size+1;
363       _nodal_connec_index->pushBackSilent(val);
364       _nodal_connec->writeOnPlace(idx,type,nodalConnOfCell,size);
365       _types.insert(type);
366     }
367   else
368     {
369       std::ostringstream oss; oss << "MEDCouplingUMesh::insertNextCell : cell type " << cm.getRepr() << " has a dimension " << cm.getDimension();
370       oss << " whereas Mesh Dimension of current UMesh instance is set to " << _mesh_dim << " ! Please invoke \"setMeshDimension\" method before or invoke ";
371       oss << "\"MEDCouplingUMesh::New\" static method with 2 parameters name and meshDimension !";
372       throw INTERP_KERNEL::Exception(oss.str());
373     }
374 }
375
376 /*!
377  * Compacts data arrays to release unused memory. This method is to be called after
378  * finishing cell insertion using \a this->insertNextCell().
379  * 
380  *  \if ENABLE_EXAMPLES
381  *  \ref medcouplingcppexamplesUmeshStdBuild1 "Here is a C++ example".<br>
382  *  \ref medcouplingpyexamplesUmeshStdBuild1 "Here is a Python example".
383  *  \endif
384  */
385 void MEDCouplingUMesh::finishInsertingCells()
386 {
387   _nodal_connec->pack();
388   _nodal_connec_index->pack();
389   _nodal_connec->declareAsNew();
390   _nodal_connec_index->declareAsNew();
391   updateTime();
392 }
393
394 /*!
395  * Entry point for iteration over cells of this. Warning the returned cell iterator should be deallocated.
396  * Useful for python users.
397  */
398 MEDCouplingUMeshCellIterator *MEDCouplingUMesh::cellIterator()
399 {
400   return new MEDCouplingUMeshCellIterator(this);
401 }
402
403 /*!
404  * Entry point for iteration over cells groups geo types per geotypes. Warning the returned cell iterator should be deallocated.
405  * If \a this is not so that that cells are grouped by geo types this method will throw an exception.
406  * In this case MEDCouplingUMesh::sortCellsInMEDFileFrmt or MEDCouplingUMesh::rearrange2ConsecutiveCellTypes methods for example can be called before invoking this method.
407  * Useful for python users.
408  */
409 MEDCouplingUMeshCellByTypeEntry *MEDCouplingUMesh::cellsByType()
410 {
411   if(!checkConsecutiveCellTypes())
412     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::cellsByType : this mesh is not sorted by type !");
413   return new MEDCouplingUMeshCellByTypeEntry(this);
414 }
415
416 /*!
417  * Returns a set of all cell types available in \a this mesh.
418  * \return std::set<INTERP_KERNEL::NormalizedCellType> - the set of cell types.
419  * \warning this method does not throw any exception even if \a this is not defined.
420  * \sa MEDCouplingUMesh::getAllGeoTypesSorted
421  */
422 std::set<INTERP_KERNEL::NormalizedCellType> MEDCouplingUMesh::getAllGeoTypes() const
423 {
424   return _types;
425 }
426
427 /*!
428  * This method returns the sorted list of geometric types in \a this.
429  * Sorted means in the same order than the cells in \a this. A single entry in return vector means the maximal chunk of consecutive cells in \a this
430  * having the same geometric type. So a same geometric type can appear more than once if the cells are not sorted per geometric type.
431  *
432  * \throw if connectivity in \a this is not correctly defined.
433  *  
434  * \sa MEDCouplingMesh::getAllGeoTypes
435  */
436 std::vector<INTERP_KERNEL::NormalizedCellType> MEDCouplingUMesh::getAllGeoTypesSorted() const
437 {
438   std::vector<INTERP_KERNEL::NormalizedCellType> ret;
439   checkConnectivityFullyDefined();
440   int nbOfCells(getNumberOfCells());
441   if(nbOfCells==0)
442     return ret;
443   if(getNodalConnectivityArrayLen()<1)
444     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAllGeoTypesSorted : the connectivity in this seems invalid !");
445   const int *c(_nodal_connec->begin()),*ci(_nodal_connec_index->begin());
446   ret.push_back((INTERP_KERNEL::NormalizedCellType)c[*ci++]);
447   for(int i=1;i<nbOfCells;i++,ci++)
448     if(ret.back()!=((INTERP_KERNEL::NormalizedCellType)c[*ci]))
449       ret.push_back((INTERP_KERNEL::NormalizedCellType)c[*ci]);
450   return ret;
451 }
452
453 /*!
454  * This method is a method that compares \a this and \a other.
455  * This method compares \b all attributes, even names and component names.
456  */
457 bool MEDCouplingUMesh::isEqualIfNotWhy(const MEDCouplingMesh *other, double prec, std::string& reason) const
458 {
459   if(!other)
460     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::isEqualIfNotWhy : input other pointer is null !");
461   std::ostringstream oss; oss.precision(15);
462   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
463   if(!otherC)
464     {
465       reason="mesh given in input is not castable in MEDCouplingUMesh !";
466       return false;
467     }
468   if(!MEDCouplingPointSet::isEqualIfNotWhy(other,prec,reason))
469     return false;
470   if(_mesh_dim!=otherC->_mesh_dim)
471     {
472       oss << "umesh dimension mismatch : this mesh dimension=" << _mesh_dim << " other mesh dimension=" <<  otherC->_mesh_dim;
473       reason=oss.str();
474       return false;
475     }
476   if(_types!=otherC->_types)
477     {
478       oss << "umesh geometric type mismatch :\nThis geometric types are :";
479       for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=_types.begin();iter!=_types.end();iter++)
480         { const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(*iter); oss << cm.getRepr() << ", "; }
481       oss << "\nOther geometric types are :";
482       for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=otherC->_types.begin();iter!=otherC->_types.end();iter++)
483         { const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(*iter); oss << cm.getRepr() << ", "; }
484       reason=oss.str();
485       return false;
486     }
487   if(_nodal_connec!=0 || otherC->_nodal_connec!=0)
488     if(_nodal_connec==0 || otherC->_nodal_connec==0)
489       {
490         reason="Only one UMesh between the two this and other has its nodal connectivity DataArrayInt defined !";
491         return false;
492       }
493   if(_nodal_connec!=otherC->_nodal_connec)
494     if(!_nodal_connec->isEqualIfNotWhy(*otherC->_nodal_connec,reason))
495       {
496         reason.insert(0,"Nodal connectivity DataArrayInt differ : ");
497         return false;
498       }
499   if(_nodal_connec_index!=0 || otherC->_nodal_connec_index!=0)
500     if(_nodal_connec_index==0 || otherC->_nodal_connec_index==0)
501       {
502         reason="Only one UMesh between the two this and other has its nodal connectivity index DataArrayInt defined !";
503         return false;
504       }
505   if(_nodal_connec_index!=otherC->_nodal_connec_index)
506     if(!_nodal_connec_index->isEqualIfNotWhy(*otherC->_nodal_connec_index,reason))
507       {
508         reason.insert(0,"Nodal connectivity index DataArrayInt differ : ");
509         return false;
510       }
511   return true;
512 }
513
514 /*!
515  * Checks if data arrays of this mesh (node coordinates, nodal
516  * connectivity of cells, etc) of two meshes are same. Textual data like name etc. are
517  * not considered.
518  *  \param [in] other - the mesh to compare with.
519  *  \param [in] prec - precision value used to compare node coordinates.
520  *  \return bool - \a true if the two meshes are same.
521  */
522 bool MEDCouplingUMesh::isEqualWithoutConsideringStr(const MEDCouplingMesh *other, double prec) const
523 {
524   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
525   if(!otherC)
526     return false;
527   if(!MEDCouplingPointSet::isEqualWithoutConsideringStr(other,prec))
528     return false;
529   if(_mesh_dim!=otherC->_mesh_dim)
530     return false;
531   if(_types!=otherC->_types)
532     return false;
533   if(_nodal_connec!=0 || otherC->_nodal_connec!=0)
534     if(_nodal_connec==0 || otherC->_nodal_connec==0)
535       return false;
536   if(_nodal_connec!=otherC->_nodal_connec)
537     if(!_nodal_connec->isEqualWithoutConsideringStr(*otherC->_nodal_connec))
538       return false;
539   if(_nodal_connec_index!=0 || otherC->_nodal_connec_index!=0)
540     if(_nodal_connec_index==0 || otherC->_nodal_connec_index==0)
541       return false;
542   if(_nodal_connec_index!=otherC->_nodal_connec_index)
543     if(!_nodal_connec_index->isEqualWithoutConsideringStr(*otherC->_nodal_connec_index))
544       return false;
545   return true;
546 }
547
548 /*!
549  * Checks if \a this and \a other meshes are geometrically equivalent with high
550  * probability, else an exception is thrown. The meshes are considered equivalent if
551  * (1) meshes contain the same number of nodes and the same number of elements of the
552  * same types (2) three cells of the two meshes (first, last and middle) are based
553  * on coincident nodes (with a specified precision).
554  *  \param [in] other - the mesh to compare with.
555  *  \param [in] prec - the precision used to compare nodes of the two meshes.
556  *  \throw If the two meshes do not match.
557  */
558 void MEDCouplingUMesh::checkFastEquivalWith(const MEDCouplingMesh *other, double prec) const
559 {
560   MEDCouplingPointSet::checkFastEquivalWith(other,prec);
561   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
562   if(!otherC)
563     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkFastEquivalWith : Two meshes are not not unstructured !"); 
564 }
565
566 /*!
567  * Returns the reverse nodal connectivity. The reverse nodal connectivity enumerates
568  * cells each node belongs to.
569  * \warning For speed reasons, this method does not check if node ids in the nodal
570  *          connectivity correspond to the size of node coordinates array.
571  * \param [in,out] revNodal - an array holding ids of cells sharing each node.
572  * \param [in,out] revNodalIndx - an array, of length \a this->getNumberOfNodes() + 1,
573  *        dividing cell ids in \a revNodal into groups each referring to one
574  *        node. Its every element (except the last one) is an index pointing to the
575  *         first id of a group of cells. For example cells sharing the node #1 are 
576  *        described by following range of indices: 
577  *        [ \a revNodalIndx[1], \a revNodalIndx[2] ) and the cell ids are
578  *        \a revNodal[ \a revNodalIndx[1] ], \a revNodal[ \a revNodalIndx[1] + 1], ...
579  *        Number of cells sharing the *i*-th node is
580  *        \a revNodalIndx[ *i*+1 ] - \a revNodalIndx[ *i* ].
581  * \throw If the coordinates array is not set.
582  * \throw If the nodal connectivity of cells is not defined.
583  * 
584  * \if ENABLE_EXAMPLES
585  * \ref cpp_mcumesh_getReverseNodalConnectivity "Here is a C++ example".<br>
586  * \ref  py_mcumesh_getReverseNodalConnectivity "Here is a Python example".
587  * \endif
588  */
589 void MEDCouplingUMesh::getReverseNodalConnectivity(DataArrayInt *revNodal, DataArrayInt *revNodalIndx) const
590 {
591   checkFullyDefined();
592   int nbOfNodes=getNumberOfNodes();
593   int *revNodalIndxPtr=(int *)malloc((nbOfNodes+1)*sizeof(int));
594   revNodalIndx->useArray(revNodalIndxPtr,true,C_DEALLOC,nbOfNodes+1,1);
595   std::fill(revNodalIndxPtr,revNodalIndxPtr+nbOfNodes+1,0);
596   const int *conn=_nodal_connec->getConstPointer();
597   const int *connIndex=_nodal_connec_index->getConstPointer();
598   int nbOfCells=getNumberOfCells();
599   int nbOfEltsInRevNodal=0;
600   for(int eltId=0;eltId<nbOfCells;eltId++)
601     {
602       const int *strtNdlConnOfCurCell=conn+connIndex[eltId]+1;
603       const int *endNdlConnOfCurCell=conn+connIndex[eltId+1];
604       for(const int *iter=strtNdlConnOfCurCell;iter!=endNdlConnOfCurCell;iter++)
605         if(*iter>=0)//for polyhedrons
606           {
607             nbOfEltsInRevNodal++;
608             revNodalIndxPtr[(*iter)+1]++;
609           }
610     }
611   std::transform(revNodalIndxPtr+1,revNodalIndxPtr+nbOfNodes+1,revNodalIndxPtr,revNodalIndxPtr+1,std::plus<int>());
612   int *revNodalPtr=(int *)malloc((nbOfEltsInRevNodal)*sizeof(int));
613   revNodal->useArray(revNodalPtr,true,C_DEALLOC,nbOfEltsInRevNodal,1);
614   std::fill(revNodalPtr,revNodalPtr+nbOfEltsInRevNodal,-1);
615   for(int eltId=0;eltId<nbOfCells;eltId++)
616     {
617       const int *strtNdlConnOfCurCell=conn+connIndex[eltId]+1;
618       const int *endNdlConnOfCurCell=conn+connIndex[eltId+1];
619       for(const int *iter=strtNdlConnOfCurCell;iter!=endNdlConnOfCurCell;iter++)
620         if(*iter>=0)//for polyhedrons
621           *std::find_if(revNodalPtr+revNodalIndxPtr[*iter],revNodalPtr+revNodalIndxPtr[*iter+1],std::bind2nd(std::equal_to<int>(),-1))=eltId;
622     }
623 }
624
625 /*!
626  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
627  * this->getMeshDimension(), that bound cells of \a this mesh. In addition arrays
628  * describing correspondence between cells of \a this and the result meshes are
629  * returned. The arrays \a desc and \a descIndx (\ref numbering-indirect) describe the descending connectivity,
630  * i.e. enumerate cells of the result mesh bounding each cell of \a this mesh. The
631  * arrays \a revDesc and \a revDescIndx (\ref numbering-indirect) describe the reverse descending connectivity,
632  * i.e. enumerate cells of  \a this mesh bounded by each cell of the result mesh. 
633  * \warning For speed reasons, this method does not check if node ids in the nodal
634  *          connectivity correspond to the size of node coordinates array.
635  * \warning Cells of the result mesh are \b not sorted by geometric type, hence,
636  *          to write this mesh to the MED file, its cells must be sorted using
637  *          sortCellsInMEDFileFrmt().
638  *  \param [in,out] desc - the array containing cell ids of the result mesh bounding
639  *         each cell of \a this mesh.
640  *  \param [in,out] descIndx - the array, of length \a this->getNumberOfCells() + 1,
641  *        dividing cell ids in \a desc into groups each referring to one
642  *        cell of \a this mesh. Its every element (except the last one) is an index
643  *        pointing to the first id of a group of cells. For example cells of the
644  *        result mesh bounding the cell #1 of \a this mesh are described by following
645  *        range of indices:
646  *        [ \a descIndx[1], \a descIndx[2] ) and the cell ids are
647  *        \a desc[ \a descIndx[1] ], \a desc[ \a descIndx[1] + 1], ...
648  *        Number of cells of the result mesh sharing the *i*-th cell of \a this mesh is
649  *        \a descIndx[ *i*+1 ] - \a descIndx[ *i* ].
650  *  \param [in,out] revDesc - the array containing cell ids of \a this mesh bounded
651  *         by each cell of the result mesh.
652  *  \param [in,out] revDescIndx - the array, of length one more than number of cells
653  *        in the result mesh,
654  *        dividing cell ids in \a revDesc into groups each referring to one
655  *        cell of the result mesh the same way as \a descIndx divides \a desc.
656  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is to
657  *        delete this mesh using decrRef() as it is no more needed.
658  *  \throw If the coordinates array is not set.
659  *  \throw If the nodal connectivity of cells is node defined.
660  *  \throw If \a desc == NULL || \a descIndx == NULL || \a revDesc == NULL || \a
661  *         revDescIndx == NULL.
662  * 
663  *  \if ENABLE_EXAMPLES
664  *  \ref cpp_mcumesh_buildDescendingConnectivity "Here is a C++ example".<br>
665  *  \ref  py_mcumesh_buildDescendingConnectivity "Here is a Python example".
666  *  \endif
667  * \sa buildDescendingConnectivity2()
668  */
669 MEDCouplingUMesh *MEDCouplingUMesh::buildDescendingConnectivity(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
670 {
671   return buildDescendingConnectivityGen<MinusOneSonsGenerator>(desc,descIndx,revDesc,revDescIndx,MEDCouplingFastNbrer);
672 }
673
674 /*!
675  * \a this has to have a mesh dimension equal to 3. If it is not the case an INTERP_KERNEL::Exception will be thrown.
676  * This behaves exactly as MEDCouplingUMesh::buildDescendingConnectivity does except that this method compute directly the transition from mesh dimension 3 to sub edges (dimension 1)
677  * in one shot. That is to say that this method is equivalent to 2 successive calls to MEDCouplingUMesh::buildDescendingConnectivity.
678  * This method returns 4 arrays and a mesh as MEDCouplingUMesh::buildDescendingConnectivity does.
679  * \sa MEDCouplingUMesh::buildDescendingConnectivity
680  */
681 MEDCouplingUMesh *MEDCouplingUMesh::explode3DMeshTo1D(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
682 {
683   checkFullyDefined();
684   if(getMeshDimension()!=3)
685     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::explode3DMeshTo1D : This has to have a mesh dimension to 3 !");
686   return buildDescendingConnectivityGen<MinusTwoSonsGenerator>(desc,descIndx,revDesc,revDescIndx,MEDCouplingFastNbrer);
687 }
688
689 /*!
690  * This method computes the micro edges constituting each cell in \a this. Micro edge is an edge for non quadratic cells. Micro edge is an half edge for quadratic cells.
691  * This method works for both meshes with mesh dimenstion equal to 2 or 3. Dynamical cells are not supported (polygons, polyhedrons...)
692  * 
693  * \sa explode3DMeshTo1D, buildDescendingConnectiviy
694  */
695 MEDCouplingUMesh *MEDCouplingUMesh::explodeMeshIntoMicroEdges(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
696 {
697    checkFullyDefined();
698    switch(getMeshDimension())
699      {
700      case 2:
701        return buildDescendingConnectivityGen<MicroEdgesGenerator2D>(desc,descIndx,revDesc,revDescIndx,MEDCouplingFastNbrer);
702      case 3:
703        return buildDescendingConnectivityGen<MicroEdgesGenerator2D>(desc,descIndx,revDesc,revDescIndx,MEDCouplingFastNbrer);
704      default:
705        throw INTERP_KERNEL::Exception("MEDCouplingUMesh::explodeMeshIntoMicroEdges : Only 2D and 3D supported !");
706      }
707 }
708
709 /*!
710  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
711  * this->getMeshDimension(), that bound cells of \a this mesh. In
712  * addition arrays describing correspondence between cells of \a this and the result
713  * meshes are returned. The arrays \a desc and \a descIndx (\ref numbering-indirect) describe the descending
714  * connectivity, i.e. enumerate cells of the result mesh bounding each cell of \a this
715  *  mesh. This method differs from buildDescendingConnectivity() in that apart
716  * from cell ids, \a desc returns mutual orientation of cells in \a this and the
717  * result meshes. So a positive id means that order of nodes in corresponding cells
718  * of two meshes is same, and a negative id means a reverse order of nodes. Since a
719  * cell with id #0 can't be negative, the array \a desc returns ids in FORTRAN mode,
720  * i.e. cell ids are one-based.
721  * Arrays \a revDesc and \a revDescIndx (\ref numbering-indirect) describe the reverse descending connectivity,
722  * i.e. enumerate cells of  \a this mesh bounded by each cell of the result mesh. 
723  * \warning For speed reasons, this method does not check if node ids in the nodal
724  *          connectivity correspond to the size of node coordinates array.
725  * \warning Cells of the result mesh are \b not sorted by geometric type, hence,
726  *          to write this mesh to the MED file, its cells must be sorted using
727  *          sortCellsInMEDFileFrmt().
728  *  \param [in,out] desc - the array containing cell ids of the result mesh bounding
729  *         each cell of \a this mesh.
730  *  \param [in,out] descIndx - the array, of length \a this->getNumberOfCells() + 1,
731  *        dividing cell ids in \a desc into groups each referring to one
732  *        cell of \a this mesh. Its every element (except the last one) is an index
733  *        pointing to the first id of a group of cells. For example cells of the
734  *        result mesh bounding the cell #1 of \a this mesh are described by following
735  *        range of indices:
736  *        [ \a descIndx[1], \a descIndx[2] ) and the cell ids are
737  *        \a desc[ \a descIndx[1] ], \a desc[ \a descIndx[1] + 1], ...
738  *        Number of cells of the result mesh sharing the *i*-th cell of \a this mesh is
739  *        \a descIndx[ *i*+1 ] - \a descIndx[ *i* ].
740  *  \param [in,out] revDesc - the array containing cell ids of \a this mesh bounded
741  *         by each cell of the result mesh.
742  *  \param [in,out] revDescIndx - the array, of length one more than number of cells
743  *        in the result mesh,
744  *        dividing cell ids in \a revDesc into groups each referring to one
745  *        cell of the result mesh the same way as \a descIndx divides \a desc.
746  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. This result mesh
747  *        shares the node coordinates array with \a this mesh. The caller is to
748  *        delete this mesh using decrRef() as it is no more needed.
749  *  \throw If the coordinates array is not set.
750  *  \throw If the nodal connectivity of cells is node defined.
751  *  \throw If \a desc == NULL || \a descIndx == NULL || \a revDesc == NULL || \a
752  *         revDescIndx == NULL.
753  * 
754  *  \if ENABLE_EXAMPLES
755  *  \ref cpp_mcumesh_buildDescendingConnectivity2 "Here is a C++ example".<br>
756  *  \ref  py_mcumesh_buildDescendingConnectivity2 "Here is a Python example".
757  *  \endif
758  * \sa buildDescendingConnectivity()
759  */
760 MEDCouplingUMesh *MEDCouplingUMesh::buildDescendingConnectivity2(DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *revDesc, DataArrayInt *revDescIndx) const
761 {
762   return buildDescendingConnectivityGen<MinusOneSonsGenerator>(desc,descIndx,revDesc,revDescIndx,MEDCouplingOrientationSensitiveNbrer);
763 }
764
765 /*!
766  * \b WARNING this method do the assumption that connectivity lies on the coordinates set.
767  * For speed reasons no check of this will be done. This method calls
768  * MEDCouplingUMesh::buildDescendingConnectivity to compute the result.
769  * This method lists cell by cell in \b this which are its neighbors. To compute the result
770  * only connectivities are considered.
771  * The neighbor cells of cell having id 'cellId' are neighbors[neighborsIndx[cellId]:neighborsIndx[cellId+1]].
772  * The format of return is hence \ref numbering-indirect.
773  *
774  * \param [out] neighbors is an array storing all the neighbors of all cells in \b this. This array is newly
775  * allocated and should be dealt by the caller. \b neighborsIndx 2nd output
776  * parameter allows to select the right part in this array (\ref numbering-indirect). The number of tuples
777  * is equal to the last values in \b neighborsIndx.
778  * \param [out] neighborsIndx is an array of size this->getNumberOfCells()+1 newly allocated and should be
779  * dealt by the caller. This arrays allow to use the first output parameter \b neighbors (\ref numbering-indirect).
780  */
781 void MEDCouplingUMesh::computeNeighborsOfCells(DataArrayInt *&neighbors, DataArrayInt *&neighborsIndx) const
782 {
783   MCAuto<DataArrayInt> desc=DataArrayInt::New();
784   MCAuto<DataArrayInt> descIndx=DataArrayInt::New();
785   MCAuto<DataArrayInt> revDesc=DataArrayInt::New();
786   MCAuto<DataArrayInt> revDescIndx=DataArrayInt::New();
787   MCAuto<MEDCouplingUMesh> meshDM1=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
788   meshDM1=0;
789   ComputeNeighborsOfCellsAdv(desc,descIndx,revDesc,revDescIndx,neighbors,neighborsIndx);
790 }
791
792 void MEDCouplingUMesh::computeCellNeighborhoodFromNodesOne(const DataArrayInt *nodeNeigh, const DataArrayInt *nodeNeighI, MCAuto<DataArrayInt>& cellNeigh, MCAuto<DataArrayInt>& cellNeighIndex) const
793 {
794   if(!nodeNeigh || !nodeNeighI)
795     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::computeCellNeighborhoodFromNodesOne : null pointer !");
796   checkConsistencyLight();
797   nodeNeigh->checkAllocated(); nodeNeighI->checkAllocated();
798   nodeNeigh->checkNbOfComps(1,"MEDCouplingUMesh::computeCellNeighborhoodFromNodesOne : node neigh");
799   nodeNeighI->checkNbOfComps(1,"MEDCouplingUMesh::computeCellNeighborhoodFromNodesOne : node neigh index");
800   nodeNeighI->checkNbOfTuples(1+getNumberOfNodes(),"MEDCouplingUMesh::computeCellNeighborhoodFromNodesOne : invalid length");
801   int nbCells(getNumberOfCells());
802   const int *c(_nodal_connec->begin()),*ci(_nodal_connec_index->begin()),*ne(nodeNeigh->begin()),*nei(nodeNeighI->begin());
803   cellNeigh=DataArrayInt::New(); cellNeigh->alloc(0,1); cellNeighIndex=DataArrayInt::New(); cellNeighIndex->alloc(1,1); cellNeighIndex->setIJ(0,0,0);
804   for(int i=0;i<nbCells;i++)
805     {
806       std::set<int> s;
807       for(const int *it=c+ci[i]+1;it!=c+ci[i+1];it++)
808         if(*it>=0)
809           s.insert(ne+nei[*it],ne+nei[*it+1]);
810       s.erase(i);
811       cellNeigh->insertAtTheEnd(s.begin(),s.end());
812       cellNeighIndex->pushBackSilent(cellNeigh->getNumberOfTuples());
813     }
814 }
815
816 /*!
817  * This method is called by MEDCouplingUMesh::computeNeighborsOfCells. This methods performs the algorithm
818  * of MEDCouplingUMesh::computeNeighborsOfCells.
819  * This method is useful for users that want to reduce along a criterion the set of neighbours cell. This is
820  * typically the case to extract a set a neighbours,
821  * excluding a set of meshdim-1 cells in input descending connectivity.
822  * Typically \b desc, \b descIndx, \b revDesc and \b revDescIndx (\ref numbering-indirect) input params are
823  * the result of MEDCouplingUMesh::buildDescendingConnectivity.
824  * This method lists cell by cell in \b this which are its neighbors. To compute the result only connectivities
825  * are considered.
826  * The neighbor cells of cell having id 'cellId' are neighbors[neighborsIndx[cellId]:neighborsIndx[cellId+1]].
827  *
828  * \param [in] desc descending connectivity array.
829  * \param [in] descIndx descending connectivity index array used to walk through \b desc (\ref numbering-indirect).
830  * \param [in] revDesc reverse descending connectivity array.
831  * \param [in] revDescIndx reverse descending connectivity index array used to walk through \b revDesc (\ref numbering-indirect).
832  * \param [out] neighbors is an array storing all the neighbors of all cells in \b this. This array is newly allocated and should be dealt by the caller. \b neighborsIndx 2nd output
833  *                        parameter allows to select the right part in this array. The number of tuples is equal to the last values in \b neighborsIndx.
834  * \param [out] neighborsIndx is an array of size this->getNumberOfCells()+1 newly allocated and should be dealt by the caller. This arrays allow to use the first output parameter \b neighbors.
835  */
836 void MEDCouplingUMesh::ComputeNeighborsOfCellsAdv(const DataArrayInt *desc, const DataArrayInt *descIndx, const DataArrayInt *revDesc, const DataArrayInt *revDescIndx,
837                                                   DataArrayInt *&neighbors, DataArrayInt *&neighborsIndx)
838 {
839   if(!desc || !descIndx || !revDesc || !revDescIndx)
840     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeNeighborsOfCellsAdv some input array is empty !");
841   const int *descPtr=desc->getConstPointer();
842   const int *descIPtr=descIndx->getConstPointer();
843   const int *revDescPtr=revDesc->getConstPointer();
844   const int *revDescIPtr=revDescIndx->getConstPointer();
845   //
846   int nbCells=descIndx->getNumberOfTuples()-1;
847   MCAuto<DataArrayInt> out0=DataArrayInt::New();
848   MCAuto<DataArrayInt> out1=DataArrayInt::New(); out1->alloc(nbCells+1,1);
849   int *out1Ptr=out1->getPointer();
850   *out1Ptr++=0;
851   out0->reserve(desc->getNumberOfTuples());
852   for(int i=0;i<nbCells;i++,descIPtr++,out1Ptr++)
853     {
854       for(const int *w1=descPtr+descIPtr[0];w1!=descPtr+descIPtr[1];w1++)
855         {
856           std::set<int> s(revDescPtr+revDescIPtr[*w1],revDescPtr+revDescIPtr[(*w1)+1]);
857           s.erase(i);
858           out0->insertAtTheEnd(s.begin(),s.end());
859         }
860       *out1Ptr=out0->getNumberOfTuples();
861     }
862   neighbors=out0.retn();
863   neighborsIndx=out1.retn();
864 }
865
866 /*!
867  * \b WARNING this method do the assumption that connectivity lies on the coordinates set.
868  * For speed reasons no check of this will be done. This method calls
869  * MEDCouplingUMesh::buildDescendingConnectivity to compute the result.
870  * This method lists node by node in \b this which are its neighbors. To compute the result
871  * only connectivities are considered.
872  * The neighbor nodes of node having id 'nodeId' are neighbors[neighborsIndx[cellId]:neighborsIndx[cellId+1]].
873  *
874  * \param [out] neighbors is an array storing all the neighbors of all nodes in \b this. This array
875  * is newly allocated and should be dealt by the caller. \b neighborsIndx 2nd output
876  * parameter allows to select the right part in this array (\ref numbering-indirect).
877  * The number of tuples is equal to the last values in \b neighborsIndx.
878  * \param [out] neighborsIdx is an array of size this->getNumberOfCells()+1 newly allocated and should
879  * be dealt by the caller. This arrays allow to use the first output parameter \b neighbors.
880  */
881 void MEDCouplingUMesh::computeNeighborsOfNodes(DataArrayInt *&neighbors, DataArrayInt *&neighborsIdx) const
882 {
883   checkFullyDefined();
884   int mdim(getMeshDimension()),nbNodes(getNumberOfNodes());
885   MCAuto<DataArrayInt> desc(DataArrayInt::New()),descIndx(DataArrayInt::New()),revDesc(DataArrayInt::New()),revDescIndx(DataArrayInt::New());
886   MCAuto<MEDCouplingUMesh> mesh1D;
887   switch(mdim)
888   {
889     case 3:
890       {
891         mesh1D=explode3DMeshTo1D(desc,descIndx,revDesc,revDescIndx);
892         break;
893       }
894     case 2:
895       {
896         mesh1D=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
897         break;
898       }
899     case 1:
900       {
901         mesh1D=const_cast<MEDCouplingUMesh *>(this);
902         mesh1D->incrRef();
903         break;
904       }
905     default:
906       {
907         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::computeNeighborsOfNodes : Mesh dimension supported are [3,2,1] !");
908       }
909   }
910   desc=DataArrayInt::New(); descIndx=DataArrayInt::New(); revDesc=0; revDescIndx=0;
911   mesh1D->getReverseNodalConnectivity(desc,descIndx);
912   MCAuto<DataArrayInt> ret0(DataArrayInt::New());
913   ret0->alloc(desc->getNumberOfTuples(),1);
914   int *r0Pt(ret0->getPointer());
915   const int *c1DPtr(mesh1D->getNodalConnectivity()->begin()),*rn(desc->begin()),*rni(descIndx->begin());
916   for(int i=0;i<nbNodes;i++,rni++)
917     {
918       for(const int *oneDCellIt=rn+rni[0];oneDCellIt!=rn+rni[1];oneDCellIt++)
919         *r0Pt++=c1DPtr[3*(*oneDCellIt)+1]==i?c1DPtr[3*(*oneDCellIt)+2]:c1DPtr[3*(*oneDCellIt)+1];
920     }
921   neighbors=ret0.retn();
922   neighborsIdx=descIndx.retn();
923 }
924
925 /*!
926  * Converts specified cells to either polygons (if \a this is a 2D mesh) or
927  * polyhedrons (if \a this is a 3D mesh). The cells to convert are specified by an
928  * array of cell ids. Pay attention that after conversion all algorithms work slower
929  * with \a this mesh than before conversion. <br> If an exception is thrown during the
930  * conversion due presence of invalid ids in the array of cells to convert, as a
931  * result \a this mesh contains some already converted elements. In this case the 2D
932  * mesh remains valid but 3D mesh becomes \b inconsistent!
933  *  \warning This method can significantly modify the order of geometric types in \a this,
934  *          hence, to write this mesh to the MED file, its cells must be sorted using
935  *          sortCellsInMEDFileFrmt().
936  *  \param [in] cellIdsToConvertBg - the array holding ids of cells to convert.
937  *  \param [in] cellIdsToConvertEnd - a pointer to the last-plus-one-th element of \a
938  *         cellIdsToConvertBg.
939  *  \throw If the coordinates array is not set.
940  *  \throw If the nodal connectivity of cells is node defined.
941  *  \throw If dimension of \a this mesh is not either 2 or 3.
942  *
943  *  \if ENABLE_EXAMPLES
944  *  \ref cpp_mcumesh_convertToPolyTypes "Here is a C++ example".<br>
945  *  \ref  py_mcumesh_convertToPolyTypes "Here is a Python example".
946  *  \endif
947  */
948 void MEDCouplingUMesh::convertToPolyTypes(const int *cellIdsToConvertBg, const int *cellIdsToConvertEnd)
949 {
950   checkFullyDefined();
951   int dim=getMeshDimension();
952   if(dim<2 || dim>3)
953     throw INTERP_KERNEL::Exception("Invalid mesh dimension : must be 2 or 3 !");
954   int nbOfCells(getNumberOfCells());
955   if(dim==2)
956     {
957       const int *connIndex=_nodal_connec_index->getConstPointer();
958       int *conn=_nodal_connec->getPointer();
959       for(const int *iter=cellIdsToConvertBg;iter!=cellIdsToConvertEnd;iter++)
960         {
961           if(*iter>=0 && *iter<nbOfCells)
962             {
963               const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*iter]]);
964               if(!cm.isQuadratic())
965                 conn[connIndex[*iter]]=INTERP_KERNEL::NORM_POLYGON;
966               else
967                 conn[connIndex[*iter]]=INTERP_KERNEL::NORM_QPOLYG;
968             }
969           else
970             {
971               std::ostringstream oss; oss << "MEDCouplingUMesh::convertToPolyTypes : On rank #" << std::distance(cellIdsToConvertBg,iter) << " value is " << *iter << " which is not";
972               oss << " in range [0," << nbOfCells << ") !";
973               throw INTERP_KERNEL::Exception(oss.str());
974             }
975         }
976     }
977   else
978     {
979       int *connIndex(_nodal_connec_index->getPointer());
980       const int *connOld(_nodal_connec->getConstPointer());
981       MCAuto<DataArrayInt> connNew(DataArrayInt::New()),connNewI(DataArrayInt::New()); connNew->alloc(0,1); connNewI->alloc(1,1); connNewI->setIJ(0,0,0);
982       std::vector<bool> toBeDone(nbOfCells,false);
983       for(const int *iter=cellIdsToConvertBg;iter!=cellIdsToConvertEnd;iter++)
984         {
985           if(*iter>=0 && *iter<nbOfCells)
986             toBeDone[*iter]=true;
987           else
988             {
989               std::ostringstream oss; oss << "MEDCouplingUMesh::convertToPolyTypes : On rank #" << std::distance(cellIdsToConvertBg,iter) << " value is " << *iter << " which is not";
990               oss << " in range [0," << nbOfCells << ") !";
991               throw INTERP_KERNEL::Exception(oss.str());
992             }
993         }
994       for(int cellId=0;cellId<nbOfCells;cellId++)
995         {
996           int pos(connIndex[cellId]),posP1(connIndex[cellId+1]);
997           int lgthOld(posP1-pos-1);
998           if(toBeDone[cellId])
999             {
1000               const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)connOld[pos]);
1001               unsigned nbOfFaces(cm.getNumberOfSons2(connOld+pos+1,lgthOld));
1002               int *tmp(new int[nbOfFaces*lgthOld+1]);
1003               int *work=tmp; *work++=INTERP_KERNEL::NORM_POLYHED;
1004               for(unsigned j=0;j<nbOfFaces;j++)
1005                 {
1006                   INTERP_KERNEL::NormalizedCellType type;
1007                   unsigned offset=cm.fillSonCellNodalConnectivity2(j,connOld+pos+1,lgthOld,work,type);
1008                   work+=offset;
1009                   *work++=-1;
1010                 }
1011               std::size_t newLgth(std::distance(tmp,work)-1);//-1 for last -1
1012               connNew->pushBackValsSilent(tmp,tmp+newLgth);
1013               connNewI->pushBackSilent(connNewI->back()+(int)newLgth);
1014               delete [] tmp;
1015             }
1016           else
1017             {
1018               connNew->pushBackValsSilent(connOld+pos,connOld+posP1);
1019               connNewI->pushBackSilent(connNewI->back()+posP1-pos);
1020             }
1021         }
1022       setConnectivity(connNew,connNewI,false);//false because computeTypes called just behind.
1023     }
1024   computeTypes();
1025 }
1026
1027 /*!
1028  * Converts all cells to either polygons (if \a this is a 2D mesh) or
1029  * polyhedrons (if \a this is a 3D mesh).
1030  *  \warning As this method is purely for user-friendliness and no optimization is
1031  *          done to avoid construction of a useless vector, this method can be costly
1032  *          in memory.
1033  *  \throw If the coordinates array is not set.
1034  *  \throw If the nodal connectivity of cells is node defined.
1035  *  \throw If dimension of \a this mesh is not either 2 or 3.
1036  */
1037 void MEDCouplingUMesh::convertAllToPoly()
1038 {
1039   int nbOfCells=getNumberOfCells();
1040   std::vector<int> cellIds(nbOfCells);
1041   for(int i=0;i<nbOfCells;i++)
1042     cellIds[i]=i;
1043   convertToPolyTypes(&cellIds[0],&cellIds[0]+cellIds.size());
1044 }
1045
1046 /*!
1047  * Fixes nodal connectivity of invalid cells of type NORM_POLYHED. This method
1048  * expects that all NORM_POLYHED cells have connectivity similar to that of prismatic
1049  * volumes like NORM_HEXA8, NORM_PENTA6 etc., i.e. the first half of nodes describes a
1050  * base facet of the volume and the second half of nodes describes an opposite facet
1051  * having the same number of nodes as the base one. This method converts such
1052  * connectivity to a valid polyhedral format where connectivity of each facet is
1053  * explicitly described and connectivity of facets are separated by -1. If \a this mesh
1054  * contains a NORM_POLYHED cell with a valid connectivity, or an invalid connectivity is
1055  * not as expected, an exception is thrown and the mesh remains unchanged. Care of
1056  * a correct orientation of the first facet of a polyhedron, else orientation of a
1057  * corrected cell is reverse.<br>
1058  * This method is useful to build an extruded unstructured mesh with polyhedrons as
1059  * it releases the user from boring description of polyhedra connectivity in the valid
1060  * format.
1061  *  \throw If \a this->getMeshDimension() != 3.
1062  *  \throw If \a this->getSpaceDimension() != 3.
1063  *  \throw If the nodal connectivity of cells is not defined.
1064  *  \throw If the coordinates array is not set.
1065  *  \throw If \a this mesh contains polyhedrons with the valid connectivity.
1066  *  \throw If \a this mesh contains polyhedrons with odd number of nodes.
1067  *
1068  *  \if ENABLE_EXAMPLES
1069  *  \ref cpp_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a C++ example".<br>
1070  *  \ref  py_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a Python example".
1071  *  \endif
1072  */
1073 void MEDCouplingUMesh::convertExtrudedPolyhedra()
1074 {
1075   checkFullyDefined();
1076   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
1077     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertExtrudedPolyhedra works on umeshes with meshdim equal to 3 and spaceDim equal to 3 too!");
1078   int nbOfCells=getNumberOfCells();
1079   MCAuto<DataArrayInt> newCi=DataArrayInt::New();
1080   newCi->alloc(nbOfCells+1,1);
1081   int *newci=newCi->getPointer();
1082   const int *ci=_nodal_connec_index->getConstPointer();
1083   const int *c=_nodal_connec->getConstPointer();
1084   newci[0]=0;
1085   for(int i=0;i<nbOfCells;i++)
1086     {
1087       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)c[ci[i]];
1088       if(type==INTERP_KERNEL::NORM_POLYHED)
1089         {
1090           if(std::count(c+ci[i]+1,c+ci[i+1],-1)!=0)
1091             {
1092               std::ostringstream oss; oss << "MEDCouplingUMesh::convertExtrudedPolyhedra : cell # " << i << " is a polhedron BUT it has NOT exactly 1 face !";
1093               throw INTERP_KERNEL::Exception(oss.str());
1094             }
1095           std::size_t n2=std::distance(c+ci[i]+1,c+ci[i+1]);
1096           if(n2%2!=0)
1097             {
1098               std::ostringstream oss; oss << "MEDCouplingUMesh::convertExtrudedPolyhedra : cell # " << i << " is a polhedron with 1 face but there is a mismatch of number of nodes in face should be even !";
1099               throw INTERP_KERNEL::Exception(oss.str());
1100             }
1101           int n1=(int)(n2/2);
1102           newci[i+1]=7*n1+2+newci[i];//6*n1 (nodal length) + n1+2 (number of faces) - 1 (number of '-1' separator is equal to number of faces -1) + 1 (for cell type)
1103         }
1104       else
1105         newci[i+1]=(ci[i+1]-ci[i])+newci[i];
1106     }
1107   MCAuto<DataArrayInt> newC=DataArrayInt::New();
1108   newC->alloc(newci[nbOfCells],1);
1109   int *newc=newC->getPointer();
1110   for(int i=0;i<nbOfCells;i++)
1111     {
1112       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)c[ci[i]];
1113       if(type==INTERP_KERNEL::NORM_POLYHED)
1114         {
1115           std::size_t n1=std::distance(c+ci[i]+1,c+ci[i+1])/2;
1116           newc=std::copy(c+ci[i],c+ci[i]+n1+1,newc);
1117           *newc++=-1;
1118           for(std::size_t j=0;j<n1;j++)
1119             {
1120               newc[j]=c[ci[i]+1+n1+(n1-j)%n1];
1121               newc[n1+5*j]=-1;
1122               newc[n1+5*j+1]=c[ci[i]+1+j];
1123               newc[n1+5*j+2]=c[ci[i]+1+j+n1];
1124               newc[n1+5*j+3]=c[ci[i]+1+(j+1)%n1+n1];
1125               newc[n1+5*j+4]=c[ci[i]+1+(j+1)%n1];
1126             }
1127           newc+=n1*6;
1128         }
1129       else
1130         newc=std::copy(c+ci[i],c+ci[i+1],newc);
1131     }
1132   _nodal_connec_index->decrRef(); _nodal_connec_index=newCi.retn();
1133   _nodal_connec->decrRef(); _nodal_connec=newC.retn();
1134 }
1135
1136
1137 /*!
1138  * Converts all polygons (if \a this is a 2D mesh) or polyhedrons (if \a this is a 3D
1139  * mesh) to cells of classical types. This method is opposite to convertToPolyTypes().
1140  * \warning Cells of the result mesh are \b not sorted by geometric type, hence,
1141  *          to write this mesh to the MED file, its cells must be sorted using
1142  *          sortCellsInMEDFileFrmt().
1143  * \warning Cells (and most notably polyhedrons) must be correctly oriented for this to work
1144  *          properly. See orientCorrectlyPolyhedrons() and arePolyhedronsNotCorrectlyOriented().
1145  * \return \c true if at least one cell has been converted, \c false else. In the
1146  *         last case the nodal connectivity remains unchanged.
1147  * \throw If the coordinates array is not set.
1148  * \throw If the nodal connectivity of cells is not defined.
1149  * \throw If \a this->getMeshDimension() < 0.
1150  */
1151 bool MEDCouplingUMesh::unPolyze()
1152 {
1153   checkFullyDefined();
1154   int mdim=getMeshDimension();
1155   if(mdim<0)
1156     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::unPolyze works on umeshes with meshdim equals to 0, 1 2 or 3 !");
1157   if(mdim<=1)
1158     return false;
1159   int nbOfCells=getNumberOfCells();
1160   if(nbOfCells<1)
1161     return false;
1162   int initMeshLgth=getNodalConnectivityArrayLen();
1163   int *conn=_nodal_connec->getPointer();
1164   int *index=_nodal_connec_index->getPointer();
1165   int posOfCurCell=0;
1166   int newPos=0;
1167   int lgthOfCurCell;
1168   bool ret=false;
1169   for(int i=0;i<nbOfCells;i++)
1170     {
1171       lgthOfCurCell=index[i+1]-posOfCurCell;
1172       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[posOfCurCell];
1173       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
1174       INTERP_KERNEL::NormalizedCellType newType=INTERP_KERNEL::NORM_ERROR;
1175       int newLgth;
1176       if(cm.isDynamic())
1177         {
1178           switch(cm.getDimension())
1179           {
1180             case 2:
1181               {
1182                 INTERP_KERNEL::AutoPtr<int> tmp=new int[lgthOfCurCell-1];
1183                 std::copy(conn+posOfCurCell+1,conn+posOfCurCell+lgthOfCurCell,(int *)tmp);
1184                 newType=INTERP_KERNEL::CellSimplify::tryToUnPoly2D(cm.isQuadratic(),tmp,lgthOfCurCell-1,conn+newPos+1,newLgth);
1185                 break;
1186               }
1187             case 3:
1188               {
1189                 int nbOfFaces,lgthOfPolyhConn;
1190                 INTERP_KERNEL::AutoPtr<int> zipFullReprOfPolyh=INTERP_KERNEL::CellSimplify::getFullPolyh3DCell(type,conn+posOfCurCell+1,lgthOfCurCell-1,nbOfFaces,lgthOfPolyhConn);
1191                 newType=INTERP_KERNEL::CellSimplify::tryToUnPoly3D(zipFullReprOfPolyh,nbOfFaces,lgthOfPolyhConn,conn+newPos+1,newLgth);
1192                 break;
1193               }
1194             case 1:
1195               {
1196                 newType=(lgthOfCurCell==3)?INTERP_KERNEL::NORM_SEG2:INTERP_KERNEL::NORM_POLYL;
1197                 break;
1198               }
1199           }
1200           ret=ret || (newType!=type);
1201           conn[newPos]=newType;
1202           newPos+=newLgth+1;
1203           posOfCurCell=index[i+1];
1204           index[i+1]=newPos;
1205         }
1206       else
1207         {
1208           std::copy(conn+posOfCurCell,conn+posOfCurCell+lgthOfCurCell,conn+newPos);
1209           newPos+=lgthOfCurCell;
1210           posOfCurCell+=lgthOfCurCell;
1211           index[i+1]=newPos;
1212         }
1213     }
1214   if(newPos!=initMeshLgth)
1215     _nodal_connec->reAlloc(newPos);
1216   if(ret)
1217     computeTypes();
1218   return ret;
1219 }
1220
1221 /*!
1222  * This method expects that spaceDimension is equal to 3 and meshDimension equal to 3.
1223  * This method performs operation only on polyhedrons in \b this. If no polyhedrons exists in \b this, \b this remains unchanged.
1224  * This method allows to merge if any coplanar 3DSurf cells that may appear in some polyhedrons cells. 
1225  *
1226  * \param [in] eps is a relative precision that allows to establish if some 3D plane are coplanar or not. This epsilon is used to recenter around origin to have maximal 
1227  *             precision.
1228  */
1229 void MEDCouplingUMesh::simplifyPolyhedra(double eps)
1230 {
1231   checkFullyDefined();
1232   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
1233     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplifyPolyhedra : works on meshdimension 3 and spaceDimension 3 !");
1234   MCAuto<DataArrayDouble> coords=getCoords()->deepCopy();
1235   coords->recenterForMaxPrecision(eps);
1236   //
1237   int nbOfCells=getNumberOfCells();
1238   const int *conn=_nodal_connec->getConstPointer();
1239   const int *index=_nodal_connec_index->getConstPointer();
1240   MCAuto<DataArrayInt> connINew=DataArrayInt::New();
1241   connINew->alloc(nbOfCells+1,1);
1242   int *connINewPtr=connINew->getPointer(); *connINewPtr++=0;
1243   MCAuto<DataArrayInt> connNew=DataArrayInt::New(); connNew->alloc(0,1);
1244   bool changed=false;
1245   for(int i=0;i<nbOfCells;i++,connINewPtr++)
1246     {
1247       if(conn[index[i]]==(int)INTERP_KERNEL::NORM_POLYHED)
1248         {
1249           SimplifyPolyhedronCell(eps,coords,conn+index[i],conn+index[i+1],connNew);
1250           changed=true;
1251         }
1252       else
1253         connNew->insertAtTheEnd(conn+index[i],conn+index[i+1]);
1254       *connINewPtr=connNew->getNumberOfTuples();
1255     }
1256   if(changed)
1257     setConnectivity(connNew,connINew,false);
1258 }
1259
1260 /*!
1261  * This method returns all node ids used in the connectivity of \b this. The data array returned has to be dealt by the caller.
1262  * The returned node ids are sorted ascendingly. This method is close to MEDCouplingUMesh::getNodeIdsInUse except
1263  * the format of the returned DataArrayInt instance.
1264  * 
1265  * \return a newly allocated DataArrayInt sorted ascendingly of fetched node ids.
1266  * \sa MEDCouplingUMesh::getNodeIdsInUse, areAllNodesFetched
1267  */
1268 DataArrayInt *MEDCouplingUMesh::computeFetchedNodeIds() const
1269 {
1270   checkConnectivityFullyDefined();
1271   const int *maxEltPt(std::max_element(_nodal_connec->begin(),_nodal_connec->end()));
1272   int maxElt(maxEltPt==_nodal_connec->end()?0:std::abs(*maxEltPt)+1);
1273   std::vector<bool> retS(maxElt,false);
1274   computeNodeIdsAlg(retS);
1275   return DataArrayInt::BuildListOfSwitchedOn(retS);
1276 }
1277
1278 /*!
1279  * \param [in,out] nodeIdsInUse an array of size typically equal to nbOfNodes.
1280  * \sa MEDCouplingUMesh::getNodeIdsInUse, areAllNodesFetched
1281  */
1282 void MEDCouplingUMesh::computeNodeIdsAlg(std::vector<bool>& nodeIdsInUse) const
1283 {
1284   int nbOfNodes((int)nodeIdsInUse.size()),nbOfCells(getNumberOfCells());
1285   const int *connIndex(_nodal_connec_index->getConstPointer()),*conn(_nodal_connec->getConstPointer());
1286   for(int i=0;i<nbOfCells;i++)
1287     for(int j=connIndex[i]+1;j<connIndex[i+1];j++)
1288       if(conn[j]>=0)
1289         {
1290           if(conn[j]<nbOfNodes)
1291             nodeIdsInUse[conn[j]]=true;
1292           else
1293             {
1294               std::ostringstream oss; oss << "MEDCouplingUMesh::computeNodeIdsAlg : In cell #" << i  << " presence of node id " <<  conn[j] << " not in [0," << nbOfNodes << ") !";
1295               throw INTERP_KERNEL::Exception(oss.str());
1296             }
1297         }
1298 }
1299
1300 /// @cond INTERNAL
1301
1302 struct MEDCouplingAccVisit
1303 {
1304   MEDCouplingAccVisit():_new_nb_of_nodes(0) { }
1305   int operator()(int val) { if(val!=-1) return _new_nb_of_nodes++; else return -1; }
1306   int _new_nb_of_nodes;
1307 };
1308
1309 /// @endcond
1310
1311 /*!
1312  * Finds nodes not used in any cell and returns an array giving a new id to every node
1313  * by excluding the unused nodes, for which the array holds -1. The result array is
1314  * a mapping in "Old to New" mode. 
1315  *  \param [out] nbrOfNodesInUse - number of node ids present in the nodal connectivity.
1316  *  \return DataArrayInt * - a new instance of DataArrayInt. Its length is \a
1317  *          this->getNumberOfNodes(). It holds for each node of \a this mesh either -1
1318  *          if the node is unused or a new id else. The caller is to delete this
1319  *          array using decrRef() as it is no more needed.  
1320  *  \throw If the coordinates array is not set.
1321  *  \throw If the nodal connectivity of cells is not defined.
1322  *  \throw If the nodal connectivity includes an invalid id.
1323  *
1324  *  \if ENABLE_EXAMPLES
1325  *  \ref cpp_mcumesh_getNodeIdsInUse "Here is a C++ example".<br>
1326  *  \ref  py_mcumesh_getNodeIdsInUse "Here is a Python example".
1327  *  \endif
1328  * \sa computeFetchedNodeIds, computeNodeIdsAlg()
1329  */
1330 DataArrayInt *MEDCouplingUMesh::getNodeIdsInUse(int& nbrOfNodesInUse) const
1331 {
1332   nbrOfNodesInUse=-1;
1333   int nbOfNodes(getNumberOfNodes());
1334   MCAuto<DataArrayInt> ret=DataArrayInt::New();
1335   ret->alloc(nbOfNodes,1);
1336   int *traducer=ret->getPointer();
1337   std::fill(traducer,traducer+nbOfNodes,-1);
1338   int nbOfCells=getNumberOfCells();
1339   const int *connIndex=_nodal_connec_index->getConstPointer();
1340   const int *conn=_nodal_connec->getConstPointer();
1341   for(int i=0;i<nbOfCells;i++)
1342     for(int j=connIndex[i]+1;j<connIndex[i+1];j++)
1343       if(conn[j]>=0)
1344         {
1345           if(conn[j]<nbOfNodes)
1346             traducer[conn[j]]=1;
1347           else
1348             {
1349               std::ostringstream oss; oss << "MEDCouplingUMesh::getNodeIdsInUse : In cell #" << i  << " presence of node id " <<  conn[j] << " not in [0," << nbOfNodes << ") !";
1350               throw INTERP_KERNEL::Exception(oss.str());
1351             }
1352         }
1353   nbrOfNodesInUse=(int)std::count(traducer,traducer+nbOfNodes,1);
1354   std::transform(traducer,traducer+nbOfNodes,traducer,MEDCouplingAccVisit());
1355   return ret.retn();
1356 }
1357
1358 /*!
1359  * This method returns a newly allocated array containing this->getNumberOfCells() tuples and 1 component.
1360  * For each cell in \b this the number of nodes constituting cell is computed.
1361  * For each polyhedron cell, the sum of the number of nodes of each face constituting polyhedron cell is returned.
1362  * So for pohyhedrons some nodes can be counted several times in the returned result.
1363  * 
1364  * \return a newly allocated array
1365  * \sa MEDCouplingUMesh::computeEffectiveNbOfNodesPerCell
1366  */
1367 DataArrayInt *MEDCouplingUMesh::computeNbOfNodesPerCell() const
1368 {
1369   checkConnectivityFullyDefined();
1370   int nbOfCells=getNumberOfCells();
1371   MCAuto<DataArrayInt> ret=DataArrayInt::New();
1372   ret->alloc(nbOfCells,1);
1373   int *retPtr=ret->getPointer();
1374   const int *conn=getNodalConnectivity()->getConstPointer();
1375   const int *connI=getNodalConnectivityIndex()->getConstPointer();
1376   for(int i=0;i<nbOfCells;i++,retPtr++)
1377     {
1378       if(conn[connI[i]]!=(int)INTERP_KERNEL::NORM_POLYHED)
1379         *retPtr=connI[i+1]-connI[i]-1;
1380       else
1381         *retPtr=connI[i+1]-connI[i]-1-std::count(conn+connI[i]+1,conn+connI[i+1],-1);
1382     }
1383   return ret.retn();
1384 }
1385
1386 /*!
1387  * This method computes effective number of nodes per cell. That is to say nodes appearing several times in nodal connectivity of a cell,
1388  * will be counted only once here whereas it will be counted several times in MEDCouplingUMesh::computeNbOfNodesPerCell method.
1389  *
1390  * \return DataArrayInt * - new object to be deallocated by the caller.
1391  * \sa MEDCouplingUMesh::computeNbOfNodesPerCell
1392  */
1393 DataArrayInt *MEDCouplingUMesh::computeEffectiveNbOfNodesPerCell() const
1394 {
1395   checkConnectivityFullyDefined();
1396   int nbOfCells=getNumberOfCells();
1397   MCAuto<DataArrayInt> ret=DataArrayInt::New();
1398   ret->alloc(nbOfCells,1);
1399   int *retPtr=ret->getPointer();
1400   const int *conn=getNodalConnectivity()->getConstPointer();
1401   const int *connI=getNodalConnectivityIndex()->getConstPointer();
1402   for(int i=0;i<nbOfCells;i++,retPtr++)
1403     {
1404       std::set<int> s(conn+connI[i]+1,conn+connI[i+1]);
1405       if(conn[connI[i]]!=(int)INTERP_KERNEL::NORM_POLYHED)
1406         *retPtr=(int)s.size();
1407       else
1408         {
1409           s.erase(-1);
1410           *retPtr=(int)s.size();
1411         }
1412     }
1413   return ret.retn();
1414 }
1415
1416 /*!
1417  * This method returns a newly allocated array containing this->getNumberOfCells() tuples and 1 component.
1418  * For each cell in \b this the number of faces constituting (entity of dimension this->getMeshDimension()-1) cell is computed.
1419  * 
1420  * \return a newly allocated array
1421  */
1422 DataArrayInt *MEDCouplingUMesh::computeNbOfFacesPerCell() const
1423 {
1424   checkConnectivityFullyDefined();
1425   int nbOfCells=getNumberOfCells();
1426   MCAuto<DataArrayInt> ret=DataArrayInt::New();
1427   ret->alloc(nbOfCells,1);
1428   int *retPtr=ret->getPointer();
1429   const int *conn=getNodalConnectivity()->getConstPointer();
1430   const int *connI=getNodalConnectivityIndex()->getConstPointer();
1431   for(int i=0;i<nbOfCells;i++,retPtr++,connI++)
1432     {
1433       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*connI]);
1434       *retPtr=cm.getNumberOfSons2(conn+connI[0]+1,connI[1]-connI[0]-1);
1435     }
1436   return ret.retn();
1437 }
1438
1439 /*!
1440  * Removes unused nodes (the node coordinates array is shorten) and returns an array
1441  * mapping between new and old node ids in "Old to New" mode. -1 values in the returned
1442  * array mean that the corresponding old node is no more used. 
1443  *  \return DataArrayInt * - a new instance of DataArrayInt of length \a
1444  *           this->getNumberOfNodes() before call of this method. The caller is to
1445  *           delete this array using decrRef() as it is no more needed. 
1446  *  \throw If the coordinates array is not set.
1447  *  \throw If the nodal connectivity of cells is not defined.
1448  *  \throw If the nodal connectivity includes an invalid id.
1449  *  \sa areAllNodesFetched
1450  *
1451  *  \if ENABLE_EXAMPLES
1452  *  \ref cpp_mcumesh_zipCoordsTraducer "Here is a C++ example".<br>
1453  *  \ref  py_mcumesh_zipCoordsTraducer "Here is a Python example".
1454  *  \endif
1455  */
1456 DataArrayInt *MEDCouplingUMesh::zipCoordsTraducer()
1457 {
1458   return MEDCouplingPointSet::zipCoordsTraducer();
1459 }
1460
1461 /*!
1462  * This method stands if 'cell1' and 'cell2' are equals regarding 'compType' policy.
1463  * The semantic of 'compType' is specified in MEDCouplingPointSet::zipConnectivityTraducer method.
1464  */
1465 int MEDCouplingUMesh::AreCellsEqual(const int *conn, const int *connI, int cell1, int cell2, int compType)
1466 {
1467   switch(compType)
1468   {
1469     case 0:
1470       return AreCellsEqualPolicy0(conn,connI,cell1,cell2);
1471     case 1:
1472       return AreCellsEqualPolicy1(conn,connI,cell1,cell2);
1473     case 2:
1474       return AreCellsEqualPolicy2(conn,connI,cell1,cell2);
1475     case 3:
1476       return AreCellsEqualPolicy2NoType(conn,connI,cell1,cell2);
1477     case 7:
1478       return AreCellsEqualPolicy7(conn,connI,cell1,cell2);
1479   }
1480   throw INTERP_KERNEL::Exception("Unknown comparison asked ! Must be in 0,1,2,3 or 7.");
1481 }
1482
1483 /*!
1484  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 0.
1485  */
1486 int MEDCouplingUMesh::AreCellsEqualPolicy0(const int *conn, const int *connI, int cell1, int cell2)
1487 {
1488   if(connI[cell1+1]-connI[cell1]==connI[cell2+1]-connI[cell2])
1489     return std::equal(conn+connI[cell1]+1,conn+connI[cell1+1],conn+connI[cell2]+1)?1:0;
1490   return 0;
1491 }
1492
1493 /*!
1494  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 1.
1495  */
1496 int MEDCouplingUMesh::AreCellsEqualPolicy1(const int *conn, const int *connI, int cell1, int cell2)
1497 {
1498   int sz=connI[cell1+1]-connI[cell1];
1499   if(sz==connI[cell2+1]-connI[cell2])
1500     {
1501       if(conn[connI[cell1]]==conn[connI[cell2]])
1502         {
1503           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[cell1]]);
1504           unsigned dim=cm.getDimension();
1505           if(dim!=3)
1506             {
1507               if(dim!=1)
1508                 {
1509                   int sz1=2*(sz-1);
1510                   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz1];
1511                   int *work=std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],(int *)tmp);
1512                   std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],work);
1513                   work=std::search((int *)tmp,(int *)tmp+sz1,conn+connI[cell2]+1,conn+connI[cell2+1]);
1514                   return work!=tmp+sz1?1:0;
1515                 }
1516               else
1517                 return std::equal(conn+connI[cell1]+1,conn+connI[cell1+1],conn+connI[cell2]+1)?1:0;//case of SEG2 and SEG3
1518             }
1519           else
1520             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AreCellsEqualPolicy1 : not implemented yet for meshdim == 3 !");
1521         }
1522     }
1523   return 0;
1524 }
1525
1526 /*!
1527  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 2.
1528  */
1529 int MEDCouplingUMesh::AreCellsEqualPolicy2(const int *conn, const int *connI, int cell1, int cell2)
1530 {
1531   if(connI[cell1+1]-connI[cell1]==connI[cell2+1]-connI[cell2])
1532     {
1533       if(conn[connI[cell1]]==conn[connI[cell2]])
1534         {
1535           std::set<int> s1(conn+connI[cell1]+1,conn+connI[cell1+1]);
1536           std::set<int> s2(conn+connI[cell2]+1,conn+connI[cell2+1]);
1537           return s1==s2?1:0;
1538         }
1539     }
1540   return 0;
1541 }
1542
1543 /*!
1544  * This method is less restrictive than AreCellsEqualPolicy2. Here the geometric type is absolutely not taken into account !
1545  */
1546 int MEDCouplingUMesh::AreCellsEqualPolicy2NoType(const int *conn, const int *connI, int cell1, int cell2)
1547 {
1548   if(connI[cell1+1]-connI[cell1]==connI[cell2+1]-connI[cell2])
1549     {
1550       std::set<int> s1(conn+connI[cell1]+1,conn+connI[cell1+1]);
1551       std::set<int> s2(conn+connI[cell2]+1,conn+connI[cell2+1]);
1552       return s1==s2?1:0;
1553     }
1554   return 0;
1555 }
1556
1557 /*!
1558  * This method is the last step of the MEDCouplingPointSet::zipConnectivityTraducer with policy 7.
1559  */
1560 int MEDCouplingUMesh::AreCellsEqualPolicy7(const int *conn, const int *connI, int cell1, int cell2)
1561 {
1562   int sz=connI[cell1+1]-connI[cell1];
1563   if(sz==connI[cell2+1]-connI[cell2])
1564     {
1565       if(conn[connI[cell1]]==conn[connI[cell2]])
1566         {
1567           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[cell1]]);
1568           unsigned dim=cm.getDimension();
1569           if(dim!=3)
1570             {
1571               if(dim!=1)
1572                 {
1573                   int sz1=2*(sz-1);
1574                   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz1];
1575                   int *work=std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],(int *)tmp);
1576                   std::copy(conn+connI[cell1]+1,conn+connI[cell1+1],work);
1577                   work=std::search((int *)tmp,(int *)tmp+sz1,conn+connI[cell2]+1,conn+connI[cell2+1]);
1578                   if(work!=tmp+sz1)
1579                     return 1;
1580                   else
1581                     {
1582                       std::reverse_iterator<int *> it1((int *)tmp+sz1);
1583                       std::reverse_iterator<int *> it2((int *)tmp);
1584                       if(std::search(it1,it2,conn+connI[cell2]+1,conn+connI[cell2+1])!=it2)
1585                         return 2;
1586                       else
1587                         return 0;
1588                     }
1589
1590                   return work!=tmp+sz1?1:0;
1591                 }
1592               else
1593                 {//case of SEG2 and SEG3
1594                   if(std::equal(conn+connI[cell1]+1,conn+connI[cell1+1],conn+connI[cell2]+1))
1595                     return 1;
1596                   if(!cm.isQuadratic())
1597                     {
1598                       std::reverse_iterator<const int *> it1(conn+connI[cell1+1]);
1599                       std::reverse_iterator<const int *> it2(conn+connI[cell1]+1);
1600                       if(std::equal(it1,it2,conn+connI[cell2]+1))
1601                         return 2;
1602                       return 0;
1603                     }
1604                   else
1605                     {
1606                       if(conn[connI[cell1]+1]==conn[connI[cell2]+2] && conn[connI[cell1]+2]==conn[connI[cell2]+1] && conn[connI[cell1]+3]==conn[connI[cell2]+3])
1607                         return 2;
1608                       return 0;
1609                     }
1610                 }
1611             }
1612           else
1613             throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AreCellsEqualPolicy7 : not implemented yet for meshdim == 3 !");
1614         }
1615     }
1616   return 0;
1617 }
1618
1619
1620 /*!
1621  * This method find cells that are equal (regarding \a compType) in \a this. The comparison is specified
1622  * by \a compType.
1623  * This method keeps the coordiantes of \a this. This method is time consuming.
1624  *
1625  * \param [in] compType input specifying the technique used to compare cells each other.
1626  *   - 0 : exactly. A cell is detected to be the same if and only if the connectivity is exactly the same without permutation and types same too. This is the strongest policy.
1627  *   - 1 : permutation same orientation. cell1 and cell2 are considered equal if the connectivity of cell2 can be deduced by those of cell1 by direct permutation (with exactly the same orientation)
1628  * and their type equal. For 1D mesh the policy 1 is equivalent to 0.
1629  *   - 2 : nodal. cell1 and cell2 are equal if and only if cell1 and cell2 have same type and have the same nodes constituting connectivity. This is the laziest policy. This policy
1630  * can be used for users not sensitive to orientation of cell
1631  * \param [in] startCellId specifies the cellId starting from which the equality computation will be carried out. By default it is 0, which it means that all cells in \a this will be scanned.
1632  * \param [out] commonCellsArr common cells ids (\ref numbering-indirect)
1633  * \param [out] commonCellsIArr common cells ids (\ref numbering-indirect)
1634  * \return the correspondance array old to new in a newly allocated array.
1635  * 
1636  */
1637 void MEDCouplingUMesh::findCommonCells(int compType, int startCellId, DataArrayInt *& commonCellsArr, DataArrayInt *& commonCellsIArr) const
1638 {
1639   MCAuto<DataArrayInt> revNodal=DataArrayInt::New(),revNodalI=DataArrayInt::New();
1640   getReverseNodalConnectivity(revNodal,revNodalI);
1641   FindCommonCellsAlg(compType,startCellId,_nodal_connec,_nodal_connec_index,revNodal,revNodalI,commonCellsArr,commonCellsIArr);
1642 }
1643
1644 void MEDCouplingUMesh::FindCommonCellsAlg(int compType, int startCellId, const DataArrayInt *nodal, const DataArrayInt *nodalI, const DataArrayInt *revNodal, const DataArrayInt *revNodalI,
1645                                           DataArrayInt *& commonCellsArr, DataArrayInt *& commonCellsIArr)
1646 {
1647   MCAuto<DataArrayInt> commonCells=DataArrayInt::New(),commonCellsI=DataArrayInt::New(); commonCells->alloc(0,1);
1648   int nbOfCells=nodalI->getNumberOfTuples()-1;
1649   commonCellsI->reserve(1); commonCellsI->pushBackSilent(0);
1650   const int *revNodalPtr=revNodal->getConstPointer(),*revNodalIPtr=revNodalI->getConstPointer();
1651   const int *connPtr=nodal->getConstPointer(),*connIPtr=nodalI->getConstPointer();
1652   std::vector<bool> isFetched(nbOfCells,false);
1653   if(startCellId==0)
1654     {
1655       for(int i=0;i<nbOfCells;i++)
1656         {
1657           if(!isFetched[i])
1658             {
1659               const int *connOfNode=std::find_if(connPtr+connIPtr[i]+1,connPtr+connIPtr[i+1],std::bind2nd(std::not_equal_to<int>(),-1));
1660               std::vector<int> v,v2;
1661               if(connOfNode!=connPtr+connIPtr[i+1])
1662                 {
1663                   const int *locRevNodal=std::find(revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1],i);
1664                   v2.insert(v2.end(),locRevNodal,revNodalPtr+revNodalIPtr[*connOfNode+1]);
1665                   connOfNode++;
1666                 }
1667               for(;connOfNode!=connPtr+connIPtr[i+1] && v2.size()>1;connOfNode++)
1668                 if(*connOfNode>=0)
1669                   {
1670                     v=v2;
1671                     const int *locRevNodal=std::find(revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1],i);
1672                     std::vector<int>::iterator it=std::set_intersection(v.begin(),v.end(),locRevNodal,revNodalPtr+revNodalIPtr[*connOfNode+1],v2.begin());
1673                     v2.resize(std::distance(v2.begin(),it));
1674                   }
1675               if(v2.size()>1)
1676                 {
1677                   if(AreCellsEqualInPool(v2,compType,connPtr,connIPtr,commonCells))
1678                     {
1679                       int pos=commonCellsI->back();
1680                       commonCellsI->pushBackSilent(commonCells->getNumberOfTuples());
1681                       for(const int *it=commonCells->begin()+pos;it!=commonCells->end();it++)
1682                         isFetched[*it]=true;
1683                     }
1684                 }
1685             }
1686         }
1687     }
1688   else
1689     {
1690       for(int i=startCellId;i<nbOfCells;i++)
1691         {
1692           if(!isFetched[i])
1693             {
1694               const int *connOfNode=std::find_if(connPtr+connIPtr[i]+1,connPtr+connIPtr[i+1],std::bind2nd(std::not_equal_to<int>(),-1));
1695               std::vector<int> v,v2;
1696               if(connOfNode!=connPtr+connIPtr[i+1])
1697                 {
1698                   v2.insert(v2.end(),revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1]);
1699                   connOfNode++;
1700                 }
1701               for(;connOfNode!=connPtr+connIPtr[i+1] && v2.size()>1;connOfNode++)
1702                 if(*connOfNode>=0)
1703                   {
1704                     v=v2;
1705                     std::vector<int>::iterator it=std::set_intersection(v.begin(),v.end(),revNodalPtr+revNodalIPtr[*connOfNode],revNodalPtr+revNodalIPtr[*connOfNode+1],v2.begin());
1706                     v2.resize(std::distance(v2.begin(),it));
1707                   }
1708               if(v2.size()>1)
1709                 {
1710                   if(AreCellsEqualInPool(v2,compType,connPtr,connIPtr,commonCells))
1711                     {
1712                       int pos=commonCellsI->back();
1713                       commonCellsI->pushBackSilent(commonCells->getNumberOfTuples());
1714                       for(const int *it=commonCells->begin()+pos;it!=commonCells->end();it++)
1715                         isFetched[*it]=true;
1716                     }
1717                 }
1718             }
1719         }
1720     }
1721   commonCellsArr=commonCells.retn();
1722   commonCellsIArr=commonCellsI.retn();
1723 }
1724
1725 /*!
1726  * Checks if \a this mesh includes all cells of an \a other mesh, and returns an array
1727  * giving for each cell of the \a other an id of a cell in \a this mesh. A value larger
1728  * than \a this->getNumberOfCells() in the returned array means that there is no
1729  * corresponding cell in \a this mesh.
1730  * It is expected that \a this and \a other meshes share the same node coordinates
1731  * array, if it is not so an exception is thrown. 
1732  *  \param [in] other - the mesh to compare with.
1733  *  \param [in] compType - specifies a cell comparison technique. For meaning of its
1734  *         valid values [0,1,2], see zipConnectivityTraducer().
1735  *  \param [out] arr - a new instance of DataArrayInt returning correspondence
1736  *         between cells of the two meshes. It contains \a other->getNumberOfCells()
1737  *         values. The caller is to delete this array using
1738  *         decrRef() as it is no more needed.
1739  *  \return bool - \c true if all cells of \a other mesh are present in the \a this
1740  *         mesh.
1741  *
1742  *  \if ENABLE_EXAMPLES
1743  *  \ref cpp_mcumesh_areCellsIncludedIn "Here is a C++ example".<br>
1744  *  \ref  py_mcumesh_areCellsIncludedIn "Here is a Python example".
1745  *  \endif
1746  *  \sa checkDeepEquivalOnSameNodesWith()
1747  *  \sa checkGeoEquivalWith()
1748  */
1749 bool MEDCouplingUMesh::areCellsIncludedIn(const MEDCouplingUMesh *other, int compType, DataArrayInt *& arr) const
1750 {
1751   MCAuto<MEDCouplingUMesh> mesh=MergeUMeshesOnSameCoords(this,other);
1752   int nbOfCells=getNumberOfCells();
1753   static const int possibleCompType[]={0,1,2};
1754   if(std::find(possibleCompType,possibleCompType+sizeof(possibleCompType)/sizeof(int),compType)==possibleCompType+sizeof(possibleCompType)/sizeof(int))
1755     {
1756       std::ostringstream oss; oss << "MEDCouplingUMesh::areCellsIncludedIn : only following policies are possible : ";
1757       std::copy(possibleCompType,possibleCompType+sizeof(possibleCompType)/sizeof(int),std::ostream_iterator<int>(oss," "));
1758       oss << " !";
1759       throw INTERP_KERNEL::Exception(oss.str());
1760     }
1761   MCAuto<DataArrayInt> o2n=mesh->zipConnectivityTraducer(compType,nbOfCells);
1762   arr=o2n->subArray(nbOfCells);
1763   arr->setName(other->getName());
1764   int tmp;
1765   if(other->getNumberOfCells()==0)
1766     return true;
1767   return arr->getMaxValue(tmp)<nbOfCells;
1768 }
1769
1770 /*!
1771  * This method makes the assumption that \a this and \a other share the same coords. If not an exception will be thrown !
1772  * This method tries to determine if \b other is fully included in \b this.
1773  * The main difference is that this method is not expected to throw exception.
1774  * This method has two outputs :
1775  *
1776  * \param other other mesh
1777  * \param arr is an output parameter that returns a \b newly created instance. This array is of size 'other->getNumberOfCells()'.
1778  * \return If \a other is fully included in 'this 'true is returned. If not false is returned.
1779  */
1780 bool MEDCouplingUMesh::areCellsIncludedInPolicy7(const MEDCouplingUMesh *other, DataArrayInt *& arr) const
1781 {
1782   MCAuto<MEDCouplingUMesh> mesh=MergeUMeshesOnSameCoords(this,other);
1783   DataArrayInt *commonCells=0,*commonCellsI=0;
1784   int thisNbCells=getNumberOfCells();
1785   mesh->findCommonCells(7,thisNbCells,commonCells,commonCellsI);
1786   MCAuto<DataArrayInt> commonCellsTmp(commonCells),commonCellsITmp(commonCellsI);
1787   const int *commonCellsPtr=commonCells->getConstPointer(),*commonCellsIPtr=commonCellsI->getConstPointer();
1788   int otherNbCells=other->getNumberOfCells();
1789   MCAuto<DataArrayInt> arr2=DataArrayInt::New();
1790   arr2->alloc(otherNbCells,1);
1791   arr2->fillWithZero();
1792   int *arr2Ptr=arr2->getPointer();
1793   int nbOfCommon=commonCellsI->getNumberOfTuples()-1;
1794   for(int i=0;i<nbOfCommon;i++)
1795     {
1796       int start=commonCellsPtr[commonCellsIPtr[i]];
1797       if(start<thisNbCells)
1798         {
1799           for(int j=commonCellsIPtr[i]+1;j!=commonCellsIPtr[i+1];j++)
1800             {
1801               int sig=commonCellsPtr[j]>0?1:-1;
1802               int val=std::abs(commonCellsPtr[j])-1;
1803               if(val>=thisNbCells)
1804                 arr2Ptr[val-thisNbCells]=sig*(start+1);
1805             }
1806         }
1807     }
1808   arr2->setName(other->getName());
1809   if(arr2->presenceOfValue(0))
1810     return false;
1811   arr=arr2.retn();
1812   return true;
1813 }
1814
1815 MEDCouplingUMesh *MEDCouplingUMesh::mergeMyselfWithOnSameCoords(const MEDCouplingPointSet *other) const
1816 {
1817   if(!other)
1818     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::mergeMyselfWithOnSameCoords : input other is null !");
1819   const MEDCouplingUMesh *otherC=dynamic_cast<const MEDCouplingUMesh *>(other);
1820   if(!otherC)
1821     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::mergeMyselfWithOnSameCoords : the input other mesh is not of type unstructured !");
1822   std::vector<const MEDCouplingUMesh *> ms(2);
1823   ms[0]=this;
1824   ms[1]=otherC;
1825   return MergeUMeshesOnSameCoords(ms);
1826 }
1827
1828 /*!
1829  * Build a sub part of \b this lying or not on the same coordinates than \b this (regarding value of \b keepCoords).
1830  * By default coordinates are kept. This method is close to MEDCouplingUMesh::buildPartOfMySelf except that here input
1831  * cellIds is not given explicitely but by a range python like.
1832  * 
1833  * \param start
1834  * \param end
1835  * \param step
1836  * \param keepCoords that specifies if you want or not to keep coords as this or zip it (see MEDCoupling::MEDCouplingUMesh::zipCoords). If true zipCoords is \b NOT called, if false, zipCoords is called.
1837  * \return a newly allocated
1838  * 
1839  * \warning This method modifies can generate an unstructured mesh whose cells are not sorted by geometric type order.
1840  * In view of the MED file writing, a renumbering of cells of returned unstructured mesh (using MEDCouplingUMesh::sortCellsInMEDFileFrmt) should be necessary.
1841  */
1842 MEDCouplingUMesh *MEDCouplingUMesh::buildPartOfMySelfSlice(int start, int end, int step, bool keepCoords) const
1843 {
1844   if(getMeshDimension()!=-1)
1845     return static_cast<MEDCouplingUMesh *>(MEDCouplingPointSet::buildPartOfMySelfSlice(start,end,step,keepCoords));
1846   else
1847     {
1848       int newNbOfCells=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::buildPartOfMySelfSlice for -1 dimension mesh ");
1849       if(newNbOfCells!=1)
1850         throw INTERP_KERNEL::Exception("-1D mesh has only one cell !");
1851       if(start!=0)
1852         throw INTERP_KERNEL::Exception("-1D mesh has only one cell : 0 !");
1853       incrRef();
1854       return const_cast<MEDCouplingUMesh *>(this);
1855     }
1856 }
1857
1858 /*!
1859  * Creates a new MEDCouplingUMesh containing specified cells of \a this mesh.
1860  * The result mesh shares or not the node coordinates array with \a this mesh depending
1861  * on \a keepCoords parameter.
1862  *  \warning Cells of the result mesh can be \b not sorted by geometric type, hence,
1863  *           to write this mesh to the MED file, its cells must be sorted using
1864  *           sortCellsInMEDFileFrmt().
1865  *  \param [in] begin - an array of cell ids to include to the new mesh.
1866  *  \param [in] end - a pointer to last-plus-one-th element of \a begin.
1867  *  \param [in] keepCoords - if \c true, the result mesh shares the node coordinates
1868  *         array of \a this mesh, else "free" nodes are removed from the result mesh
1869  *         by calling zipCoords().
1870  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is
1871  *         to delete this mesh using decrRef() as it is no more needed. 
1872  *  \throw If the coordinates array is not set.
1873  *  \throw If the nodal connectivity of cells is not defined.
1874  *  \throw If any cell id in the array \a begin is not valid.
1875  *
1876  *  \if ENABLE_EXAMPLES
1877  *  \ref cpp_mcumesh_buildPartOfMySelf "Here is a C++ example".<br>
1878  *  \ref  py_mcumesh_buildPartOfMySelf "Here is a Python example".
1879  *  \endif
1880  */
1881 MEDCouplingUMesh *MEDCouplingUMesh::buildPartOfMySelf(const int *begin, const int *end, bool keepCoords) const
1882 {
1883   if(getMeshDimension()!=-1)
1884     return static_cast<MEDCouplingUMesh *>(MEDCouplingPointSet::buildPartOfMySelf(begin,end,keepCoords));
1885   else
1886     {
1887       if(end-begin!=1)
1888         throw INTERP_KERNEL::Exception("-1D mesh has only one cell !");
1889       if(begin[0]!=0)
1890         throw INTERP_KERNEL::Exception("-1D mesh has only one cell : 0 !");
1891       incrRef();
1892       return const_cast<MEDCouplingUMesh *>(this);
1893     }
1894 }
1895
1896 /*!
1897  * This method operates only on nodal connectivity on \b this. Coordinates of \b this is completely ignored here.
1898  *
1899  * This method allows to partially modify some cells in \b this (whose list is specified by [ \b cellIdsBg, \b cellIdsEnd ) ) with cells coming in \b otherOnSameCoordsThanThis.
1900  * Size of [ \b cellIdsBg, \b cellIdsEnd ) ) must be equal to the number of cells of otherOnSameCoordsThanThis.
1901  * The number of cells of \b this will remain the same with this method.
1902  *
1903  * \param [in] cellIdsBg begin of cell ids (included) of cells in this to assign
1904  * \param [in] cellIdsEnd end of cell ids (excluded) of cells in this to assign
1905  * \param [in] otherOnSameCoordsThanThis an another mesh with same meshdimension than \b this with exactly the same number of cells than cell ids list in [\b cellIdsBg, \b cellIdsEnd ).
1906  *             Coordinate pointer of \b this and those of \b otherOnSameCoordsThanThis must be the same
1907  */
1908 void MEDCouplingUMesh::setPartOfMySelf(const int *cellIdsBg, const int *cellIdsEnd, const MEDCouplingUMesh& otherOnSameCoordsThanThis)
1909 {
1910   checkConnectivityFullyDefined();
1911   otherOnSameCoordsThanThis.checkConnectivityFullyDefined();
1912   if(getCoords()!=otherOnSameCoordsThanThis.getCoords())
1913     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::setPartOfMySelf : coordinates pointer are not the same ! Invoke setCoords or call tryToShareSameCoords method !");
1914   if(getMeshDimension()!=otherOnSameCoordsThanThis.getMeshDimension())
1915     {
1916       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf : Mismatch of meshdimensions ! this is equal to " << getMeshDimension();
1917       oss << ", whereas other mesh dimension is set equal to " << otherOnSameCoordsThanThis.getMeshDimension() << " !";
1918       throw INTERP_KERNEL::Exception(oss.str());
1919     }
1920   int nbOfCellsToModify=(int)std::distance(cellIdsBg,cellIdsEnd);
1921   if(nbOfCellsToModify!=otherOnSameCoordsThanThis.getNumberOfCells())
1922     {
1923       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf : cells ids length (" <<  nbOfCellsToModify << ") do not match the number of cells of other mesh (" << otherOnSameCoordsThanThis.getNumberOfCells() << ") !";
1924       throw INTERP_KERNEL::Exception(oss.str());
1925     }
1926   int nbOfCells=getNumberOfCells();
1927   bool easyAssign=true;
1928   const int *connI=_nodal_connec_index->getConstPointer();
1929   const int *connIOther=otherOnSameCoordsThanThis._nodal_connec_index->getConstPointer();
1930   for(const int *it=cellIdsBg;it!=cellIdsEnd && easyAssign;it++,connIOther++)
1931     {
1932       if(*it>=0 && *it<nbOfCells)
1933         {
1934           easyAssign=(connIOther[1]-connIOther[0])==(connI[*it+1]-connI[*it]);
1935         }
1936       else
1937         {
1938           std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelf : On pos #" << std::distance(cellIdsBg,it) << " id is equal to " << *it << " which is not in [0," << nbOfCells << ") !";
1939           throw INTERP_KERNEL::Exception(oss.str());
1940         }
1941     }
1942   if(easyAssign)
1943     {
1944       MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx(cellIdsBg,cellIdsEnd,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index);
1945       computeTypes();
1946     }
1947   else
1948     {
1949       DataArrayInt *arrOut=0,*arrIOut=0;
1950       MEDCouplingUMesh::SetPartOfIndexedArrays(cellIdsBg,cellIdsEnd,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index,
1951                                                arrOut,arrIOut);
1952       MCAuto<DataArrayInt> arrOutAuto(arrOut),arrIOutAuto(arrIOut);
1953       setConnectivity(arrOut,arrIOut,true);
1954     }
1955 }
1956
1957 void MEDCouplingUMesh::setPartOfMySelfSlice(int start, int end, int step, const MEDCouplingUMesh& otherOnSameCoordsThanThis)
1958 {
1959   checkConnectivityFullyDefined();
1960   otherOnSameCoordsThanThis.checkConnectivityFullyDefined();
1961   if(getCoords()!=otherOnSameCoordsThanThis.getCoords())
1962     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::setPartOfMySelfSlice : coordinates pointer are not the same ! Invoke setCoords or call tryToShareSameCoords method !");
1963   if(getMeshDimension()!=otherOnSameCoordsThanThis.getMeshDimension())
1964     {
1965       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelfSlice : Mismatch of meshdimensions ! this is equal to " << getMeshDimension();
1966       oss << ", whereas other mesh dimension is set equal to " << otherOnSameCoordsThanThis.getMeshDimension() << " !";
1967       throw INTERP_KERNEL::Exception(oss.str());
1968     }
1969   int nbOfCellsToModify=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::setPartOfMySelfSlice : ");
1970   if(nbOfCellsToModify!=otherOnSameCoordsThanThis.getNumberOfCells())
1971     {
1972       std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelfSlice : cells ids length (" <<  nbOfCellsToModify << ") do not match the number of cells of other mesh (" << otherOnSameCoordsThanThis.getNumberOfCells() << ") !";
1973       throw INTERP_KERNEL::Exception(oss.str());
1974     }
1975   int nbOfCells=getNumberOfCells();
1976   bool easyAssign=true;
1977   const int *connI=_nodal_connec_index->getConstPointer();
1978   const int *connIOther=otherOnSameCoordsThanThis._nodal_connec_index->getConstPointer();
1979   int it=start;
1980   for(int i=0;i<nbOfCellsToModify && easyAssign;i++,it+=step,connIOther++)
1981     {
1982       if(it>=0 && it<nbOfCells)
1983         {
1984           easyAssign=(connIOther[1]-connIOther[0])==(connI[it+1]-connI[it]);
1985         }
1986       else
1987         {
1988           std::ostringstream oss; oss << "MEDCouplingUMesh::setPartOfMySelfSlice : On pos #" << i << " id is equal to " << it << " which is not in [0," << nbOfCells << ") !";
1989           throw INTERP_KERNEL::Exception(oss.str());
1990         }
1991     }
1992   if(easyAssign)
1993     {
1994       MEDCouplingUMesh::SetPartOfIndexedArraysSameIdxSlice(start,end,step,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index);
1995       computeTypes();
1996     }
1997   else
1998     {
1999       DataArrayInt *arrOut=0,*arrIOut=0;
2000       MEDCouplingUMesh::SetPartOfIndexedArraysSlice(start,end,step,_nodal_connec,_nodal_connec_index,otherOnSameCoordsThanThis._nodal_connec,otherOnSameCoordsThanThis._nodal_connec_index,
2001                                                 arrOut,arrIOut);
2002       MCAuto<DataArrayInt> arrOutAuto(arrOut),arrIOutAuto(arrIOut);
2003       setConnectivity(arrOut,arrIOut,true);
2004     }
2005 }                      
2006
2007
2008 /*!
2009  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
2010  * this->getMeshDimension(), that bound some cells of \a this mesh.
2011  * The cells of lower dimension to include to the result mesh are selected basing on
2012  * specified node ids and the value of \a fullyIn parameter. If \a fullyIn ==\c true, a
2013  * cell is copied if its all nodes are in the array \a begin of node ids. If \a fullyIn
2014  * ==\c false, a cell is copied if any its node is in the array of node ids. The
2015  * created mesh shares the node coordinates array with \a this mesh. 
2016  *  \param [in] begin - the array of node ids.
2017  *  \param [in] end - a pointer to the (last+1)-th element of \a begin.
2018  *  \param [in] fullyIn - if \c true, then cells whose all nodes are in the
2019  *         array \a begin are added, else cells whose any node is in the
2020  *         array \a begin are added.
2021  *  \return MEDCouplingUMesh * - new instance of MEDCouplingUMesh. The caller is
2022  *         to delete this mesh using decrRef() as it is no more needed. 
2023  *  \throw If the coordinates array is not set.
2024  *  \throw If the nodal connectivity of cells is not defined.
2025  *  \throw If any node id in \a begin is not valid.
2026  *
2027  *  \if ENABLE_EXAMPLES
2028  *  \ref cpp_mcumesh_buildFacePartOfMySelfNode "Here is a C++ example".<br>
2029  *  \ref  py_mcumesh_buildFacePartOfMySelfNode "Here is a Python example".
2030  *  \endif
2031  */
2032 MEDCouplingUMesh *MEDCouplingUMesh::buildFacePartOfMySelfNode(const int *begin, const int *end, bool fullyIn) const
2033 {
2034   MCAuto<DataArrayInt> desc,descIndx,revDesc,revDescIndx;
2035   desc=DataArrayInt::New(); descIndx=DataArrayInt::New(); revDesc=DataArrayInt::New(); revDescIndx=DataArrayInt::New();
2036   MCAuto<MEDCouplingUMesh> subMesh=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
2037   desc=0; descIndx=0; revDesc=0; revDescIndx=0;
2038   return static_cast<MEDCouplingUMesh*>(subMesh->buildPartOfMySelfNode(begin,end,fullyIn));
2039 }
2040
2041 /*!
2042  * Creates a new MEDCouplingUMesh containing cells, of dimension one less than \a
2043  * this->getMeshDimension(), which bound only one cell of \a this mesh.
2044  *  \param [in] keepCoords - if \c true, the result mesh shares the node coordinates
2045  *         array of \a this mesh, else "free" nodes are removed from the result mesh
2046  *         by calling zipCoords().
2047  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is
2048  *         to delete this mesh using decrRef() as it is no more needed. 
2049  *  \throw If the coordinates array is not set.
2050  *  \throw If the nodal connectivity of cells is not defined.
2051  *
2052  *  \if ENABLE_EXAMPLES
2053  *  \ref cpp_mcumesh_buildBoundaryMesh "Here is a C++ example".<br>
2054  *  \ref  py_mcumesh_buildBoundaryMesh "Here is a Python example".
2055  *  \endif
2056  */
2057 MEDCouplingUMesh *MEDCouplingUMesh::buildBoundaryMesh(bool keepCoords) const
2058 {
2059   DataArrayInt *desc=DataArrayInt::New();
2060   DataArrayInt *descIndx=DataArrayInt::New();
2061   DataArrayInt *revDesc=DataArrayInt::New();
2062   DataArrayInt *revDescIndx=DataArrayInt::New();
2063   //
2064   MCAuto<MEDCouplingUMesh> meshDM1=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
2065   revDesc->decrRef();
2066   desc->decrRef();
2067   descIndx->decrRef();
2068   int nbOfCells=meshDM1->getNumberOfCells();
2069   const int *revDescIndxC=revDescIndx->getConstPointer();
2070   std::vector<int> boundaryCells;
2071   for(int i=0;i<nbOfCells;i++)
2072     if(revDescIndxC[i+1]-revDescIndxC[i]==1)
2073       boundaryCells.push_back(i);
2074   revDescIndx->decrRef();
2075   MEDCouplingUMesh *ret=meshDM1->buildPartOfMySelf(&boundaryCells[0],&boundaryCells[0]+boundaryCells.size(),keepCoords);
2076   return ret;
2077 }
2078
2079 /*!
2080  * This method returns a newly created DataArrayInt instance containing ids of cells located in boundary.
2081  * A cell is detected to be on boundary if it contains one or more than one face having only one father.
2082  * This method makes the assumption that \a this is fully defined (coords,connectivity). If not an exception will be thrown. 
2083  */
2084 DataArrayInt *MEDCouplingUMesh::findCellIdsOnBoundary() const
2085 {
2086   checkFullyDefined();
2087   MCAuto<DataArrayInt> desc=DataArrayInt::New();
2088   MCAuto<DataArrayInt> descIndx=DataArrayInt::New();
2089   MCAuto<DataArrayInt> revDesc=DataArrayInt::New();
2090   MCAuto<DataArrayInt> revDescIndx=DataArrayInt::New();
2091   //
2092   buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx)->decrRef();
2093   desc=(DataArrayInt*)0; descIndx=(DataArrayInt*)0;
2094   //
2095   MCAuto<DataArrayInt> tmp=revDescIndx->deltaShiftIndex();
2096   MCAuto<DataArrayInt> faceIds=tmp->findIdsEqual(1); tmp=(DataArrayInt*)0;
2097   const int *revDescPtr=revDesc->getConstPointer();
2098   const int *revDescIndxPtr=revDescIndx->getConstPointer();
2099   int nbOfCells=getNumberOfCells();
2100   std::vector<bool> ret1(nbOfCells,false);
2101   int sz=0;
2102   for(const int *pt=faceIds->begin();pt!=faceIds->end();pt++)
2103     if(!ret1[revDescPtr[revDescIndxPtr[*pt]]])
2104       { ret1[revDescPtr[revDescIndxPtr[*pt]]]=true; sz++; }
2105   //
2106   DataArrayInt *ret2=DataArrayInt::New();
2107   ret2->alloc(sz,1);
2108   int *ret2Ptr=ret2->getPointer();
2109   sz=0;
2110   for(std::vector<bool>::const_iterator it=ret1.begin();it!=ret1.end();it++,sz++)
2111     if(*it)
2112       *ret2Ptr++=sz;
2113   ret2->setName("BoundaryCells");
2114   return ret2;
2115 }
2116
2117 /*!
2118  * This method finds in \b this the cell ids that lie on mesh \b otherDimM1OnSameCoords.
2119  * \b this and \b otherDimM1OnSameCoords have to lie on the same coordinate array pointer. The coherency of that coords array with connectivity
2120  * of \b this and \b otherDimM1OnSameCoords is not important here because this method works only on connectivity.
2121  * this->getMeshDimension() - 1 must be equal to otherDimM1OnSameCoords.getMeshDimension()
2122  *
2123  * s0 is the cell ids set in \b this lying on at least one node in the fetched nodes in \b otherDimM1OnSameCoords.
2124  * This method also returns the cells ids set s1 which contains the cell ids in \b this for which one of the dim-1 constituent
2125  * equals a cell in \b otherDimM1OnSameCoords.
2126  *
2127  * \throw if \b otherDimM1OnSameCoords is not part of constituent of \b this, or if coordinate pointer of \b this and \b otherDimM1OnSameCoords
2128  *        are not same, or if this->getMeshDimension()-1!=otherDimM1OnSameCoords.getMeshDimension()
2129  *
2130  * \param [in] otherDimM1OnSameCoords
2131  * \param [out] cellIdsRk0 a newly allocated array containing the cell ids of s0 (which are cell ids of \b this) in the above algorithm.
2132  * \param [out] cellIdsRk1 a newly allocated array containing the cell ids of s1 \b indexed into the \b cellIdsRk0 subset. To get the absolute ids of s1, simply invoke
2133  *              cellIdsRk1->transformWithIndArr(cellIdsRk0->begin(),cellIdsRk0->end());
2134  */
2135 void MEDCouplingUMesh::findCellIdsLyingOn(const MEDCouplingUMesh& otherDimM1OnSameCoords, DataArrayInt *&cellIdsRk0, DataArrayInt *&cellIdsRk1) const
2136 {
2137   if(getCoords()!=otherDimM1OnSameCoords.getCoords())
2138     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findCellIdsLyingOn : coordinates pointer are not the same ! Use tryToShareSameCoords method !");
2139   checkConnectivityFullyDefined();
2140   otherDimM1OnSameCoords.checkConnectivityFullyDefined();
2141   if(getMeshDimension()-1!=otherDimM1OnSameCoords.getMeshDimension())
2142     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findCellIdsLyingOn : invalid mesh dimension of input mesh regarding meshdimesion of this !");
2143   MCAuto<DataArrayInt> fetchedNodeIds1=otherDimM1OnSameCoords.computeFetchedNodeIds();
2144   MCAuto<DataArrayInt> s0arr=getCellIdsLyingOnNodes(fetchedNodeIds1->begin(),fetchedNodeIds1->end(),false);
2145   MCAuto<MEDCouplingUMesh> thisPart=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(s0arr->begin(),s0arr->end(),true));
2146   MCAuto<DataArrayInt> descThisPart=DataArrayInt::New(),descIThisPart=DataArrayInt::New(),revDescThisPart=DataArrayInt::New(),revDescIThisPart=DataArrayInt::New();
2147   MCAuto<MEDCouplingUMesh> thisPartConsti=thisPart->buildDescendingConnectivity(descThisPart,descIThisPart,revDescThisPart,revDescIThisPart);
2148   const int *revDescThisPartPtr=revDescThisPart->getConstPointer(),*revDescIThisPartPtr=revDescIThisPart->getConstPointer();
2149   DataArrayInt *idsOtherInConsti=0;
2150   bool b=thisPartConsti->areCellsIncludedIn(&otherDimM1OnSameCoords,2,idsOtherInConsti);
2151   MCAuto<DataArrayInt> idsOtherInConstiAuto(idsOtherInConsti);
2152   if(!b)
2153     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findCellIdsLyingOn : the given mdim-1 mesh in other is not a constituent of this !");
2154   std::set<int> s1;
2155   for(const int *idOther=idsOtherInConsti->begin();idOther!=idsOtherInConsti->end();idOther++)
2156     s1.insert(revDescThisPartPtr+revDescIThisPartPtr[*idOther],revDescThisPartPtr+revDescIThisPartPtr[*idOther+1]);
2157   MCAuto<DataArrayInt> s1arr_renum1=DataArrayInt::New(); s1arr_renum1->alloc((int)s1.size(),1); std::copy(s1.begin(),s1.end(),s1arr_renum1->getPointer());
2158   s1arr_renum1->sort();
2159   cellIdsRk0=s0arr.retn();
2160   //cellIdsRk1=s_renum1.retn();
2161   cellIdsRk1=s1arr_renum1.retn();
2162 }
2163
2164 /*!
2165  * This method computes the skin of \b this. That is to say the consituting meshdim-1 mesh is built and only the boundary subpart is
2166  * returned. This subpart of meshdim-1 mesh is built using meshdim-1 cells in it shared only one cell in \b this.
2167  * 
2168  * \return a newly allocated mesh lying on the same coordinates than \b this. The caller has to deal with returned mesh.
2169  */
2170 MEDCouplingUMesh *MEDCouplingUMesh::computeSkin() const
2171 {
2172   MCAuto<DataArrayInt> desc=DataArrayInt::New();
2173   MCAuto<DataArrayInt> descIndx=DataArrayInt::New();
2174   MCAuto<DataArrayInt> revDesc=DataArrayInt::New();
2175   MCAuto<DataArrayInt> revDescIndx=DataArrayInt::New();
2176   //
2177   MCAuto<MEDCouplingUMesh> meshDM1=buildDescendingConnectivity(desc,descIndx,revDesc,revDescIndx);
2178   revDesc=0; desc=0; descIndx=0;
2179   MCAuto<DataArrayInt> revDescIndx2=revDescIndx->deltaShiftIndex();
2180   MCAuto<DataArrayInt> part=revDescIndx2->findIdsEqual(1);
2181   return static_cast<MEDCouplingUMesh *>(meshDM1->buildPartOfMySelf(part->begin(),part->end(),true));
2182 }
2183
2184 /*!
2185  * Finds nodes lying on the boundary of \a this mesh.
2186  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids of found
2187  *          nodes. The caller is to delete this array using decrRef() as it is no
2188  *          more needed.
2189  *  \throw If the coordinates array is not set.
2190  *  \throw If the nodal connectivity of cells is node defined.
2191  *
2192  *  \if ENABLE_EXAMPLES
2193  *  \ref cpp_mcumesh_findBoundaryNodes "Here is a C++ example".<br>
2194  *  \ref  py_mcumesh_findBoundaryNodes "Here is a Python example".
2195  *  \endif
2196  */
2197 DataArrayInt *MEDCouplingUMesh::findBoundaryNodes() const
2198 {
2199   MCAuto<MEDCouplingUMesh> skin=computeSkin();
2200   return skin->computeFetchedNodeIds();
2201 }
2202
2203 MEDCouplingUMesh *MEDCouplingUMesh::buildUnstructured() const
2204 {
2205   incrRef();
2206   return const_cast<MEDCouplingUMesh *>(this);
2207 }
2208
2209 /*!
2210  * This method expects that \b this and \b otherDimM1OnSameCoords share the same coordinates array.
2211  * otherDimM1OnSameCoords->getMeshDimension() is expected to be equal to this->getMeshDimension()-1.
2212  * This method searches for nodes needed to be duplicated. These nodes are nodes fetched by \b otherDimM1OnSameCoords which are not part of the boundary of \b otherDimM1OnSameCoords.
2213  * If a node is in the boundary of \b this \b and in the boundary of \b otherDimM1OnSameCoords this node is considerd as needed to be duplicated.
2214  * When the set of node ids \b nodeIdsToDuplicate is computed, cell ids in \b this is searched so that their connectivity includes at least 1 node in \b nodeIdsToDuplicate.
2215  *
2216  * \param [in] otherDimM1OnSameCoords a mesh lying on the same coords than \b this and with a mesh dimension equal to those of \b this minus 1. WARNING this input
2217  *             parameter is altered during the call.
2218  * \param [out] nodeIdsToDuplicate node ids needed to be duplicated following the algorithm explain above.
2219  * \param [out] cellIdsNeededToBeRenum cell ids in \b this in which the renumber of nodes should be performed.
2220  * \param [out] cellIdsNotModified cell ids int \b this that lies on \b otherDimM1OnSameCoords mesh whose connectivity do \b not need to be modified as it is the case for \b cellIdsNeededToBeRenum.
2221  *
2222  * \warning This method modifies param \b otherDimM1OnSameCoords (for speed reasons).
2223  */
2224 void MEDCouplingUMesh::findNodesToDuplicate(const MEDCouplingUMesh& otherDimM1OnSameCoords, DataArrayInt *& nodeIdsToDuplicate,
2225                                             DataArrayInt *& cellIdsNeededToBeRenum, DataArrayInt *& cellIdsNotModified) const
2226 {
2227   typedef MCAuto<DataArrayInt> DAInt;
2228   typedef MCAuto<MEDCouplingUMesh> MCUMesh;
2229
2230   checkFullyDefined();
2231   otherDimM1OnSameCoords.checkFullyDefined();
2232   if(getCoords()!=otherDimM1OnSameCoords.getCoords())
2233     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findNodesToDuplicate : meshes do not share the same coords array !");
2234   if(otherDimM1OnSameCoords.getMeshDimension()!=getMeshDimension()-1)
2235     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findNodesToDuplicate : the mesh given in other parameter must have this->getMeshDimension()-1 !");
2236
2237   // Checking star-shaped M1 group:
2238   DAInt dt0=DataArrayInt::New(),dit0=DataArrayInt::New(),rdt0=DataArrayInt::New(),rdit0=DataArrayInt::New();
2239   MCUMesh meshM2 = otherDimM1OnSameCoords.buildDescendingConnectivity(dt0, dit0, rdt0, rdit0);
2240   DAInt dsi = rdit0->deltaShiftIndex();
2241   DAInt idsTmp0 = dsi->findIdsNotInRange(-1, 3);
2242   if(idsTmp0->getNumberOfTuples())
2243     throw INTERP_KERNEL::Exception("MEDFileUMesh::buildInnerBoundaryAlongM1Group: group is too complex: some points (or edges) have more than two connected segments (or faces)!");
2244   dt0=0; dit0=0; rdt0=0; rdit0=0; idsTmp0=0;
2245
2246   // Get extreme nodes from the group (they won't be duplicated), ie nodes belonging to boundary cells of M1
2247   DAInt xtremIdsM2 = dsi->findIdsEqual(1); dsi = 0;
2248   MCUMesh meshM2Part = static_cast<MEDCouplingUMesh *>(meshM2->buildPartOfMySelf(xtremIdsM2->begin(), xtremIdsM2->end(),true));
2249   DAInt xtrem = meshM2Part->computeFetchedNodeIds();
2250   // Remove from the list points on the boundary of the M0 mesh (those need duplication!)
2251   dt0=DataArrayInt::New(),dit0=DataArrayInt::New(),rdt0=DataArrayInt::New(),rdit0=DataArrayInt::New();
2252   MCUMesh m0desc = buildDescendingConnectivity(dt0, dit0, rdt0, rdit0); dt0=0; dit0=0; rdt0=0;
2253   dsi = rdit0->deltaShiftIndex();
2254   DAInt boundSegs = dsi->findIdsEqual(1);   // boundary segs/faces of the M0 mesh
2255   MCUMesh m0descSkin = static_cast<MEDCouplingUMesh *>(m0desc->buildPartOfMySelf(boundSegs->begin(),boundSegs->end(), true));
2256   DAInt fNodes = m0descSkin->computeFetchedNodeIds();
2257   // In 3D, some points on the boundary of M0 still need duplication:
2258   DAInt notDup = 0;
2259   if (getMeshDimension() == 3)
2260     {
2261       DAInt dnu1=DataArrayInt::New(), dnu2=DataArrayInt::New(), dnu3=DataArrayInt::New(), dnu4=DataArrayInt::New();
2262       MCUMesh m0descSkinDesc = m0descSkin->buildDescendingConnectivity(dnu1, dnu2, dnu3, dnu4);
2263       dnu1=0;dnu2=0;dnu3=0;dnu4=0;
2264       DataArrayInt * corresp=0;
2265       meshM2->areCellsIncludedIn(m0descSkinDesc,2,corresp);
2266       DAInt validIds = corresp->findIdsInRange(0, meshM2->getNumberOfCells());
2267       corresp->decrRef();
2268       if (validIds->getNumberOfTuples())
2269         {
2270           MCUMesh m1IntersecSkin = static_cast<MEDCouplingUMesh *>(m0descSkinDesc->buildPartOfMySelf(validIds->begin(), validIds->end(), true));
2271           DAInt notDuplSkin = m1IntersecSkin->findBoundaryNodes();
2272           DAInt fNodes1 = fNodes->buildSubstraction(notDuplSkin);
2273           notDup = xtrem->buildSubstraction(fNodes1);
2274         }
2275       else
2276         notDup = xtrem->buildSubstraction(fNodes);
2277     }
2278   else
2279     notDup = xtrem->buildSubstraction(fNodes);
2280
2281   // Now compute cells around group (i.e. cells where we will do the propagation to identify the two sub-sets delimited by the group)
2282   DAInt m1Nodes = otherDimM1OnSameCoords.computeFetchedNodeIds();
2283   DAInt dupl = m1Nodes->buildSubstraction(notDup);
2284   DAInt cellsAroundGroup = getCellIdsLyingOnNodes(dupl->begin(), dupl->end(), false);  // false= take cell in, even if not all nodes are in notDup
2285
2286   //
2287   MCUMesh m0Part2=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(cellsAroundGroup->begin(),cellsAroundGroup->end(),true));
2288   int nCells2 = m0Part2->getNumberOfCells();
2289   DAInt desc00=DataArrayInt::New(),descI00=DataArrayInt::New(),revDesc00=DataArrayInt::New(),revDescI00=DataArrayInt::New();
2290   MCUMesh m01=m0Part2->buildDescendingConnectivity(desc00,descI00,revDesc00,revDescI00);
2291
2292   // Neighbor information of the mesh without considering the crack (serves to count how many connex pieces it is made of)
2293   DataArrayInt *tmp00=0,*tmp11=0;
2294   MEDCouplingUMesh::ComputeNeighborsOfCellsAdv(desc00,descI00,revDesc00,revDescI00, tmp00, tmp11);
2295   DAInt neighInit00(tmp00);
2296   DAInt neighIInit00(tmp11);
2297   // Neighbor information of the mesh WITH the crack (some neighbors are removed):
2298   DataArrayInt *idsTmp=0;
2299   bool b=m01->areCellsIncludedIn(&otherDimM1OnSameCoords,2,idsTmp);
2300   DAInt ids(idsTmp);
2301   // In the neighbor information remove the connection between high dimension cells and its low level constituents which are part
2302   // of the frontier given in parameter (i.e. the cells of low dimension from the group delimiting the crack):
2303   MEDCouplingUMesh::RemoveIdsFromIndexedArrays(ids->begin(),ids->end(),desc00,descI00);
2304   DataArrayInt *tmp0=0,*tmp1=0;
2305   // Compute the neighbor of each cell in m0Part2, taking into account the broken link above. Two
2306   // cells on either side of the crack (defined by the mesh of low dimension) are not neighbor anymore.
2307   ComputeNeighborsOfCellsAdv(desc00,descI00,revDesc00,revDescI00,tmp0,tmp1);
2308   DAInt neigh00(tmp0);
2309   DAInt neighI00(tmp1);
2310
2311   // For each initial connex part of the sub-mesh (or said differently for each independent crack):
2312   int seed = 0, nIter = 0;
2313   int nIterMax = nCells2+1; // Safety net for the loop
2314   DAInt hitCells = DataArrayInt::New(); hitCells->alloc(nCells2);
2315   hitCells->fillWithValue(-1);
2316   DAInt cellsToModifyConn0_torenum = DataArrayInt::New();
2317   cellsToModifyConn0_torenum->alloc(0,1);
2318   while (nIter < nIterMax)
2319     {
2320       DAInt t = hitCells->findIdsEqual(-1);
2321       if (!t->getNumberOfTuples())
2322         break;
2323       // Connex zone without the crack (to compute the next seed really)
2324       int dnu;
2325       DAInt connexCheck = MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed(&seed, &seed+1, neighInit00,neighIInit00, -1, dnu);
2326       int cnt = 0;
2327       for (int * ptr = connexCheck->getPointer(); cnt < connexCheck->getNumberOfTuples(); ptr++, cnt++)
2328         hitCells->setIJ(*ptr,0,1);
2329       // Connex zone WITH the crack (to identify cells lying on either part of the crack)
2330       DAInt spreadZone = MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed(&seed, &seed+1, neigh00,neighI00, -1, dnu);
2331       cellsToModifyConn0_torenum = DataArrayInt::Aggregate(cellsToModifyConn0_torenum, spreadZone, 0);
2332       // Compute next seed, i.e. a cell in another connex part, which was not covered by the previous iterations
2333       DAInt comple = cellsToModifyConn0_torenum->buildComplement(nCells2);
2334       DAInt nonHitCells = hitCells->findIdsEqual(-1);
2335       DAInt intersec = nonHitCells->buildIntersection(comple);
2336       if (intersec->getNumberOfTuples())
2337         { seed = intersec->getIJ(0,0); }
2338       else
2339         { break; }
2340       nIter++;
2341     }
2342   if (nIter >= nIterMax)
2343     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::findNodesToDuplicate(): internal error - too many iterations.");
2344
2345   DAInt cellsToModifyConn1_torenum=cellsToModifyConn0_torenum->buildComplement(neighI00->getNumberOfTuples()-1);
2346   cellsToModifyConn0_torenum->transformWithIndArr(cellsAroundGroup->begin(),cellsAroundGroup->end());
2347   cellsToModifyConn1_torenum->transformWithIndArr(cellsAroundGroup->begin(),cellsAroundGroup->end());
2348   //
2349   cellIdsNeededToBeRenum=cellsToModifyConn0_torenum.retn();
2350   cellIdsNotModified=cellsToModifyConn1_torenum.retn();
2351   nodeIdsToDuplicate=dupl.retn();
2352 }
2353
2354 /*!
2355  * This method operates a modification of the connectivity and coords in \b this.
2356  * Every time that a node id in [ \b nodeIdsToDuplicateBg, \b nodeIdsToDuplicateEnd ) will append in nodal connectivity of \b this 
2357  * its ids will be modified to id this->getNumberOfNodes()+std::distance(nodeIdsToDuplicateBg,std::find(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd,id)).
2358  * More explicitely the renumber array in nodes is not explicitely given in old2new to avoid to build a big array of renumbering whereas typically few node ids needs to be
2359  * renumbered. The node id nodeIdsToDuplicateBg[0] will have id this->getNumberOfNodes()+0, node id nodeIdsToDuplicateBg[1] will have id this->getNumberOfNodes()+1,
2360  * node id nodeIdsToDuplicateBg[2] will have id this->getNumberOfNodes()+2...
2361  * 
2362  * As a consequence nodal connectivity array length will remain unchanged by this method, and nodal connectivity index array will remain unchanged by this method.
2363  * 
2364  * \param [in] nodeIdsToDuplicateBg begin of node ids (included) to be duplicated in connectivity only
2365  * \param [in] nodeIdsToDuplicateEnd end of node ids (excluded) to be duplicated in connectivity only
2366  */
2367 void MEDCouplingUMesh::duplicateNodes(const int *nodeIdsToDuplicateBg, const int *nodeIdsToDuplicateEnd)
2368 {
2369   int nbOfNodes=getNumberOfNodes();
2370   duplicateNodesInCoords(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd);
2371   duplicateNodesInConn(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd,nbOfNodes);
2372 }
2373
2374 /*!
2375  * This method renumbers only nodal connectivity in \a this. The renumbering is only an offset applied. So this method is a specialization of
2376  * \a renumberNodesInConn. \b WARNING, this method does not check that the resulting node ids in the nodal connectivity is in a valid range !
2377  *
2378  * \param [in] offset - specifies the offset to be applied on each element of connectivity.
2379  *
2380  * \sa renumberNodesInConn
2381  */
2382 void MEDCouplingUMesh::renumberNodesWithOffsetInConn(int offset)
2383 {
2384   checkConnectivityFullyDefined();
2385   int *conn(getNodalConnectivity()->getPointer());
2386   const int *connIndex(getNodalConnectivityIndex()->getConstPointer());
2387   int nbOfCells(getNumberOfCells());
2388   for(int i=0;i<nbOfCells;i++)
2389     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2390       {
2391         int& node=conn[iconn];
2392         if(node>=0)//avoid polyhedron separator
2393           {
2394             node+=offset;
2395           }
2396       }
2397   _nodal_connec->declareAsNew();
2398   updateTime();
2399 }
2400
2401 /*!
2402  *  Same than renumberNodesInConn(const int *) except that here the format of old-to-new traducer is using map instead
2403  *  of array. This method is dedicated for renumbering from a big set of nodes the a tiny set of nodes which is the case during extraction
2404  *  of a big mesh.
2405  */
2406 void MEDCouplingUMesh::renumberNodesInConn(const INTERP_KERNEL::HashMap<int,int>& newNodeNumbersO2N)
2407 {
2408   checkConnectivityFullyDefined();
2409   int *conn(getNodalConnectivity()->getPointer());
2410   const int *connIndex(getNodalConnectivityIndex()->getConstPointer());
2411   int nbOfCells(getNumberOfCells());
2412   for(int i=0;i<nbOfCells;i++)
2413     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2414       {
2415         int& node=conn[iconn];
2416         if(node>=0)//avoid polyhedron separator
2417           {
2418             INTERP_KERNEL::HashMap<int,int>::const_iterator it(newNodeNumbersO2N.find(node));
2419             if(it!=newNodeNumbersO2N.end())
2420               {
2421                 node=(*it).second;
2422               }
2423             else
2424               {
2425                 std::ostringstream oss; oss << "MEDCouplingUMesh::renumberNodesInConn(map) : presence in connectivity for cell #" << i << " of node #" << node << " : Not in map !";
2426                 throw INTERP_KERNEL::Exception(oss.str());
2427               }
2428           }
2429       }
2430   _nodal_connec->declareAsNew();
2431   updateTime();
2432 }
2433
2434 /*!
2435  * Changes ids of nodes within the nodal connectivity arrays according to a permutation
2436  * array in "Old to New" mode. The node coordinates array is \b not changed by this method.
2437  * This method is a generalization of shiftNodeNumbersInConn().
2438  *  \warning This method performs no check of validity of new ids. **Use it with care !**
2439  *  \param [in] newNodeNumbersO2N - a permutation array, of length \a
2440  *         this->getNumberOfNodes(), in "Old to New" mode. 
2441  *         See \ref numbering for more info on renumbering modes.
2442  *  \throw If the nodal connectivity of cells is not defined.
2443  *
2444  *  \if ENABLE_EXAMPLES
2445  *  \ref cpp_mcumesh_renumberNodesInConn "Here is a C++ example".<br>
2446  *  \ref  py_mcumesh_renumberNodesInConn "Here is a Python example".
2447  *  \endif
2448  */
2449 void MEDCouplingUMesh::renumberNodesInConn(const int *newNodeNumbersO2N)
2450 {
2451   checkConnectivityFullyDefined();
2452   int *conn=getNodalConnectivity()->getPointer();
2453   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2454   int nbOfCells(getNumberOfCells());
2455   for(int i=0;i<nbOfCells;i++)
2456     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2457       {
2458         int& node=conn[iconn];
2459         if(node>=0)//avoid polyhedron separator
2460           {
2461             node=newNodeNumbersO2N[node];
2462           }
2463       }
2464   _nodal_connec->declareAsNew();
2465   updateTime();
2466 }
2467
2468 /*!
2469  * This method renumbers nodes \b in \b connectivity \b only \b without \b any \b reference \b to \b coords.
2470  * This method performs no check on the fact that new coordinate ids are valid. \b Use \b it \b with \b care !
2471  * This method is an specialization of \ref MEDCoupling::MEDCouplingUMesh::renumberNodesInConn "renumberNodesInConn method".
2472  * 
2473  * \param [in] delta specifies the shift size applied to nodeId in nodal connectivity in \b this.
2474  */
2475 void MEDCouplingUMesh::shiftNodeNumbersInConn(int delta)
2476 {
2477   checkConnectivityFullyDefined();
2478   int *conn=getNodalConnectivity()->getPointer();
2479   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2480   int nbOfCells=getNumberOfCells();
2481   for(int i=0;i<nbOfCells;i++)
2482     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2483       {
2484         int& node=conn[iconn];
2485         if(node>=0)//avoid polyhedron separator
2486           {
2487             node+=delta;
2488           }
2489       }
2490   _nodal_connec->declareAsNew();
2491   updateTime();
2492 }
2493
2494 /*!
2495  * This method operates a modification of the connectivity in \b this.
2496  * Coordinates are \b NOT considered here and will remain unchanged by this method. this->_coords can ever been null for the needs of this method.
2497  * Every time that a node id in [ \b nodeIdsToDuplicateBg, \b nodeIdsToDuplicateEnd ) will append in nodal connectivity of \b this 
2498  * its ids will be modified to id offset+std::distance(nodeIdsToDuplicateBg,std::find(nodeIdsToDuplicateBg,nodeIdsToDuplicateEnd,id)).
2499  * More explicitely the renumber array in nodes is not explicitely given in old2new to avoid to build a big array of renumbering whereas typically few node ids needs to be
2500  * renumbered. The node id nodeIdsToDuplicateBg[0] will have id offset+0, node id nodeIdsToDuplicateBg[1] will have id offset+1,
2501  * node id nodeIdsToDuplicateBg[2] will have id offset+2...
2502  * 
2503  * As a consequence nodal connectivity array length will remain unchanged by this method, and nodal connectivity index array will remain unchanged by this method.
2504  * As an another consequense after the call of this method \b this can be transiently non cohrent.
2505  * 
2506  * \param [in] nodeIdsToDuplicateBg begin of node ids (included) to be duplicated in connectivity only
2507  * \param [in] nodeIdsToDuplicateEnd end of node ids (excluded) to be duplicated in connectivity only
2508  * \param [in] offset the offset applied to all node ids in connectivity that are in [ \a nodeIdsToDuplicateBg, \a nodeIdsToDuplicateEnd ). 
2509  */
2510 void MEDCouplingUMesh::duplicateNodesInConn(const int *nodeIdsToDuplicateBg, const int *nodeIdsToDuplicateEnd, int offset)
2511 {
2512   checkConnectivityFullyDefined();
2513   std::map<int,int> m;
2514   int val=offset;
2515   for(const int *work=nodeIdsToDuplicateBg;work!=nodeIdsToDuplicateEnd;work++,val++)
2516     m[*work]=val;
2517   int *conn=getNodalConnectivity()->getPointer();
2518   const int *connIndex=getNodalConnectivityIndex()->getConstPointer();
2519   int nbOfCells=getNumberOfCells();
2520   for(int i=0;i<nbOfCells;i++)
2521     for(int iconn=connIndex[i]+1;iconn!=connIndex[i+1];iconn++)
2522       {
2523         int& node=conn[iconn];
2524         if(node>=0)//avoid polyhedron separator
2525           {
2526             std::map<int,int>::iterator it=m.find(node);
2527             if(it!=m.end())
2528               node=(*it).second;
2529           }
2530       }
2531   updateTime();
2532 }
2533
2534 /*!
2535  * This method renumbers cells of \a this using the array specified by [old2NewBg;old2NewBg+getNumberOfCells())
2536  *
2537  * Contrary to MEDCouplingPointSet::renumberNodes, this method makes a permutation without any fuse of cell.
2538  * After the call of this method the number of cells remains the same as before.
2539  *
2540  * If 'check' equals true the method will check that any elements in [ \a old2NewBg; \a old2NewEnd ) is unique ; if not
2541  * an INTERP_KERNEL::Exception will be thrown. When 'check' equals true [ \a old2NewBg ; \a old2NewEnd ) is not expected to
2542  * be strictly in [0;this->getNumberOfCells()).
2543  *
2544  * If 'check' equals false the method will not check the content of [ \a old2NewBg ; \a old2NewEnd ).
2545  * To avoid any throw of SIGSEGV when 'check' equals false, the elements in [ \a old2NewBg ; \a old2NewEnd ) should be unique and
2546  * should be contained in[0;this->getNumberOfCells()).
2547  * 
2548  * \param [in] old2NewBg is expected to be a dynamically allocated pointer of size at least equal to this->getNumberOfCells()
2549  * \param check
2550  */
2551 void MEDCouplingUMesh::renumberCells(const int *old2NewBg, bool check)
2552 {
2553   checkConnectivityFullyDefined();
2554   int nbCells=getNumberOfCells();
2555   const int *array=old2NewBg;
2556   if(check)
2557     array=DataArrayInt::CheckAndPreparePermutation(old2NewBg,old2NewBg+nbCells);
2558   //
2559   const int *conn=_nodal_connec->getConstPointer();
2560   const int *connI=_nodal_connec_index->getConstPointer();
2561   MCAuto<DataArrayInt> o2n=DataArrayInt::New(); o2n->useArray(array,false,C_DEALLOC,nbCells,1);
2562   MCAuto<DataArrayInt> n2o=o2n->invertArrayO2N2N2O(nbCells);
2563   const int *n2oPtr=n2o->begin();
2564   MCAuto<DataArrayInt> newConn=DataArrayInt::New();
2565   newConn->alloc(_nodal_connec->getNumberOfTuples(),_nodal_connec->getNumberOfComponents());
2566   newConn->copyStringInfoFrom(*_nodal_connec);
2567   MCAuto<DataArrayInt> newConnI=DataArrayInt::New();
2568   newConnI->alloc(_nodal_connec_index->getNumberOfTuples(),_nodal_connec_index->getNumberOfComponents());
2569   newConnI->copyStringInfoFrom(*_nodal_connec_index);
2570   //
2571   int *newC=newConn->getPointer();
2572   int *newCI=newConnI->getPointer();
2573   int loc=0;
2574   newCI[0]=loc;
2575   for(int i=0;i<nbCells;i++)
2576     {
2577       int pos=n2oPtr[i];
2578       int nbOfElts=connI[pos+1]-connI[pos];
2579       newC=std::copy(conn+connI[pos],conn+connI[pos+1],newC);
2580       loc+=nbOfElts;
2581       newCI[i+1]=loc;
2582     }
2583   //
2584   setConnectivity(newConn,newConnI);
2585   if(check)
2586     free(const_cast<int *>(array));
2587 }
2588
2589 /*!
2590  * Finds cells whose bounding boxes intersect a given bounding box.
2591  *  \param [in] bbox - an array defining the bounding box via coordinates of its
2592  *         extremum points in "no interlace" mode, i.e. xMin, xMax, yMin, yMax, zMin,
2593  *         zMax (if in 3D). 
2594  *  \param [in] eps - a factor used to increase size of the bounding box of cell
2595  *         before comparing it with \a bbox. This factor is multiplied by the maximal
2596  *         extent of the bounding box of cell to produce an addition to this bounding box.
2597  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids for found
2598  *         cells. The caller is to delete this array using decrRef() as it is no more
2599  *         needed. 
2600  *  \throw If the coordinates array is not set.
2601  *  \throw If the nodal connectivity of cells is not defined.
2602  *
2603  *  \if ENABLE_EXAMPLES
2604  *  \ref cpp_mcumesh_getCellsInBoundingBox "Here is a C++ example".<br>
2605  *  \ref  py_mcumesh_getCellsInBoundingBox "Here is a Python example".
2606  *  \endif
2607  */
2608 DataArrayInt *MEDCouplingUMesh::getCellsInBoundingBox(const double *bbox, double eps) const
2609 {
2610   MCAuto<DataArrayInt> elems=DataArrayInt::New(); elems->alloc(0,1);
2611   if(getMeshDimension()==-1)
2612     {
2613       elems->pushBackSilent(0);
2614       return elems.retn();
2615     }
2616   int dim=getSpaceDimension();
2617   INTERP_KERNEL::AutoPtr<double> elem_bb=new double[2*dim];
2618   const int* conn      = getNodalConnectivity()->getConstPointer();
2619   const int* conn_index= getNodalConnectivityIndex()->getConstPointer();
2620   const double* coords = getCoords()->getConstPointer();
2621   int nbOfCells=getNumberOfCells();
2622   for ( int ielem=0; ielem<nbOfCells;ielem++ )
2623     {
2624       for (int i=0; i<dim; i++)
2625         {
2626           elem_bb[i*2]=std::numeric_limits<double>::max();
2627           elem_bb[i*2+1]=-std::numeric_limits<double>::max();
2628         }
2629
2630       for (int inode=conn_index[ielem]+1; inode<conn_index[ielem+1]; inode++)//+1 due to offset of cell type.
2631         {
2632           int node= conn[inode];
2633           if(node>=0)//avoid polyhedron separator
2634             {
2635               for (int idim=0; idim<dim; idim++)
2636                 {
2637                   if ( coords[node*dim+idim] < elem_bb[idim*2] )
2638                     {
2639                       elem_bb[idim*2] = coords[node*dim+idim] ;
2640                     }
2641                   if ( coords[node*dim+idim] > elem_bb[idim*2+1] )
2642                     {
2643                       elem_bb[idim*2+1] = coords[node*dim+idim] ;
2644                     }
2645                 }
2646             }
2647         }
2648       if (intersectsBoundingBox(elem_bb, bbox, dim, eps))
2649         elems->pushBackSilent(ielem);
2650     }
2651   return elems.retn();
2652 }
2653
2654 /*!
2655  * Given a boundary box 'bbox' returns elements 'elems' contained in this 'bbox' or touching 'bbox' (within 'eps' distance).
2656  * Warning 'elems' is incremented during the call so if elems is not empty before call returned elements will be
2657  * added in 'elems' parameter.
2658  */
2659 DataArrayInt *MEDCouplingUMesh::getCellsInBoundingBox(const INTERP_KERNEL::DirectedBoundingBox& bbox, double eps)
2660 {
2661   MCAuto<DataArrayInt> elems=DataArrayInt::New(); elems->alloc(0,1);
2662   if(getMeshDimension()==-1)
2663     {
2664       elems->pushBackSilent(0);
2665       return elems.retn();
2666     }
2667   int dim=getSpaceDimension();
2668   INTERP_KERNEL::AutoPtr<double> elem_bb=new double[2*dim];
2669   const int* conn      = getNodalConnectivity()->getConstPointer();
2670   const int* conn_index= getNodalConnectivityIndex()->getConstPointer();
2671   const double* coords = getCoords()->getConstPointer();
2672   int nbOfCells=getNumberOfCells();
2673   for ( int ielem=0; ielem<nbOfCells;ielem++ )
2674     {
2675       for (int i=0; i<dim; i++)
2676         {
2677           elem_bb[i*2]=std::numeric_limits<double>::max();
2678           elem_bb[i*2+1]=-std::numeric_limits<double>::max();
2679         }
2680
2681       for (int inode=conn_index[ielem]+1; inode<conn_index[ielem+1]; inode++)//+1 due to offset of cell type.
2682         {
2683           int node= conn[inode];
2684           if(node>=0)//avoid polyhedron separator
2685             {
2686               for (int idim=0; idim<dim; idim++)
2687                 {
2688                   if ( coords[node*dim+idim] < elem_bb[idim*2] )
2689                     {
2690                       elem_bb[idim*2] = coords[node*dim+idim] ;
2691                     }
2692                   if ( coords[node*dim+idim] > elem_bb[idim*2+1] )
2693                     {
2694                       elem_bb[idim*2+1] = coords[node*dim+idim] ;
2695                     }
2696                 }
2697             }
2698         }
2699       if(intersectsBoundingBox(bbox, elem_bb, dim, eps))
2700         elems->pushBackSilent(ielem);
2701     }
2702   return elems.retn();
2703 }
2704
2705 /*!
2706  * Returns a type of a cell by its id.
2707  *  \param [in] cellId - the id of the cell of interest.
2708  *  \return INTERP_KERNEL::NormalizedCellType - enumeration item describing the cell type.
2709  *  \throw If \a cellId is invalid. Valid range is [0, \a this->getNumberOfCells() ).
2710  */
2711 INTERP_KERNEL::NormalizedCellType MEDCouplingUMesh::getTypeOfCell(int cellId) const
2712 {
2713   const int *ptI=_nodal_connec_index->getConstPointer();
2714   const int *pt=_nodal_connec->getConstPointer();
2715   if(cellId>=0 && cellId<(int)_nodal_connec_index->getNbOfElems()-1)
2716     return (INTERP_KERNEL::NormalizedCellType) pt[ptI[cellId]];
2717   else
2718     {
2719       std::ostringstream oss; oss << "MEDCouplingUMesh::getTypeOfCell : Requesting type of cell #" << cellId << " but it should be in [0," << _nodal_connec_index->getNbOfElems()-1 << ") !";
2720       throw INTERP_KERNEL::Exception(oss.str());
2721     }
2722 }
2723
2724 /*!
2725  * This method returns a newly allocated array containing cell ids (ascendingly sorted) whose geometric type are equal to type.
2726  * This method does not throw exception if geometric type \a type is not in \a this.
2727  * This method throws an INTERP_KERNEL::Exception if meshdimension of \b this is not equal to those of \b type.
2728  * The coordinates array is not considered here.
2729  *
2730  * \param [in] type the geometric type
2731  * \return cell ids in this having geometric type \a type.
2732  */
2733 DataArrayInt *MEDCouplingUMesh::giveCellsWithType(INTERP_KERNEL::NormalizedCellType type) const
2734 {
2735
2736   MCAuto<DataArrayInt> ret=DataArrayInt::New();
2737   ret->alloc(0,1);
2738   checkConnectivityFullyDefined();
2739   int nbCells=getNumberOfCells();
2740   int mdim=getMeshDimension();
2741   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
2742   if(mdim!=(int)cm.getDimension())
2743     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::giveCellsWithType : Mismatch between mesh dimension and dimension of the cell !");
2744   const int *ptI=_nodal_connec_index->getConstPointer();
2745   const int *pt=_nodal_connec->getConstPointer();
2746   for(int i=0;i<nbCells;i++)
2747     {
2748       if((INTERP_KERNEL::NormalizedCellType)pt[ptI[i]]==type)
2749         ret->pushBackSilent(i);
2750     }
2751   return ret.retn();
2752 }
2753
2754 /*!
2755  * Returns nb of cells having the geometric type \a type. No throw if no cells in \a this has the geometric type \a type.
2756  */
2757 int MEDCouplingUMesh::getNumberOfCellsWithType(INTERP_KERNEL::NormalizedCellType type) const
2758 {
2759   const int *ptI=_nodal_connec_index->getConstPointer();
2760   const int *pt=_nodal_connec->getConstPointer();
2761   int nbOfCells=getNumberOfCells();
2762   int ret=0;
2763   for(int i=0;i<nbOfCells;i++)
2764     if((INTERP_KERNEL::NormalizedCellType) pt[ptI[i]]==type)
2765       ret++;
2766   return ret;
2767 }
2768
2769 /*!
2770  * Returns the nodal connectivity of a given cell.
2771  * The separator of faces within polyhedron connectivity (-1) is not returned, thus
2772  * all returned node ids can be used in getCoordinatesOfNode().
2773  *  \param [in] cellId - an id of the cell of interest.
2774  *  \param [in,out] conn - a vector where the node ids are appended. It is not
2775  *         cleared before the appending.
2776  *  \throw If \a cellId is invalid. Valid range is [0, \a this->getNumberOfCells() ).
2777  */
2778 void MEDCouplingUMesh::getNodeIdsOfCell(int cellId, std::vector<int>& conn) const
2779 {
2780   const int *ptI=_nodal_connec_index->getConstPointer();
2781   const int *pt=_nodal_connec->getConstPointer();
2782   for(const int *w=pt+ptI[cellId]+1;w!=pt+ptI[cellId+1];w++)
2783     if(*w>=0)
2784       conn.push_back(*w);
2785 }
2786
2787 std::string MEDCouplingUMesh::simpleRepr() const
2788 {
2789   static const char msg0[]="No coordinates specified !";
2790   std::ostringstream ret;
2791   ret << "Unstructured mesh with name : \"" << getName() << "\"\n";
2792   ret << "Description of mesh : \"" << getDescription() << "\"\n";
2793   int tmpp1,tmpp2;
2794   double tt=getTime(tmpp1,tmpp2);
2795   ret << "Time attached to the mesh [unit] : " << tt << " [" << getTimeUnit() << "]\n";
2796   ret << "Iteration : " << tmpp1  << " Order : " << tmpp2 << "\n";
2797   if(_mesh_dim>=-1)
2798     { ret << "Mesh dimension : " << _mesh_dim << "\nSpace dimension : "; }
2799   else
2800     { ret << " Mesh dimension has not been set or is invalid !"; }
2801   if(_coords!=0)
2802     {
2803       const int spaceDim=getSpaceDimension();
2804       ret << spaceDim << "\nInfo attached on space dimension : ";
2805       for(int i=0;i<spaceDim;i++)
2806         ret << "\"" << _coords->getInfoOnComponent(i) << "\" ";
2807       ret << "\n";
2808     }
2809   else
2810     ret << msg0 << "\n";
2811   ret << "Number of nodes : ";
2812   if(_coords!=0)
2813     ret << getNumberOfNodes() << "\n";
2814   else
2815     ret << msg0 << "\n";
2816   ret << "Number of cells : ";
2817   if(_nodal_connec!=0 && _nodal_connec_index!=0)
2818     ret << getNumberOfCells() << "\n";
2819   else
2820     ret << "No connectivity specified !" << "\n";
2821   ret << "Cell types present : ";
2822   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=_types.begin();iter!=_types.end();iter++)
2823     {
2824       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(*iter);
2825       ret << cm.getRepr() << " ";
2826     }
2827   ret << "\n";
2828   return ret.str();
2829 }
2830
2831 std::string MEDCouplingUMesh::advancedRepr() const
2832 {
2833   std::ostringstream ret;
2834   ret << simpleRepr();
2835   ret << "\nCoordinates array : \n___________________\n\n";
2836   if(_coords)
2837     _coords->reprWithoutNameStream(ret);
2838   else
2839     ret << "No array set !\n";
2840   ret << "\n\nConnectivity arrays : \n_____________________\n\n";
2841   reprConnectivityOfThisLL(ret);
2842   return ret.str();
2843 }
2844
2845 /*!
2846  * This method returns a C++ code that is a dump of \a this.
2847  * This method will throw if this is not fully defined.
2848  */
2849 std::string MEDCouplingUMesh::cppRepr() const
2850 {
2851   static const char coordsName[]="coords";
2852   static const char connName[]="conn";
2853   static const char connIName[]="connI";
2854   checkFullyDefined();
2855   std::ostringstream ret; ret << "// coordinates" << std::endl;
2856   _coords->reprCppStream(coordsName,ret); ret << std::endl << "// connectivity" << std::endl;
2857   _nodal_connec->reprCppStream(connName,ret); ret << std::endl;
2858   _nodal_connec_index->reprCppStream(connIName,ret); ret << std::endl;
2859   ret << "MEDCouplingUMesh *mesh=MEDCouplingUMesh::New(\"" << getName() << "\"," << getMeshDimension() << ");" << std::endl;
2860   ret << "mesh->setCoords(" << coordsName << ");" << std::endl;
2861   ret << "mesh->setConnectivity(" << connName << "," << connIName << ",true);" << std::endl;
2862   ret << coordsName << "->decrRef(); " << connName << "->decrRef(); " << connIName << "->decrRef();" << std::endl;
2863   return ret.str();
2864 }
2865
2866 std::string MEDCouplingUMesh::reprConnectivityOfThis() const
2867 {
2868   std::ostringstream ret;
2869   reprConnectivityOfThisLL(ret);
2870   return ret.str();
2871 }
2872
2873 /*!
2874  * This method builds a newly allocated instance (with the same name than \a this) that the caller has the responsability to deal with.
2875  * This method returns an instance with all arrays allocated (connectivity, connectivity index, coordinates)
2876  * but with length of these arrays set to 0. It allows to define an "empty" mesh (with nor cells nor nodes but compliant with
2877  * some algos).
2878  * 
2879  * This method expects that \a this has a mesh dimension set and higher or equal to 0. If not an exception will be thrown.
2880  * This method analyzes the 3 arrays of \a this. For each the following behaviour is done : if the array is null a newly one is created
2881  * with number of tuples set to 0, if not the array is taken as this in the returned instance.
2882  */
2883 MEDCouplingUMesh *MEDCouplingUMesh::buildSetInstanceFromThis(int spaceDim) const
2884 {
2885   int mdim=getMeshDimension();
2886   if(mdim<0)
2887     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSetInstanceFromThis : invalid mesh dimension ! Should be >= 0 !");
2888   MCAuto<MEDCouplingUMesh> ret=MEDCouplingUMesh::New(getName(),mdim);
2889   MCAuto<DataArrayInt> tmp1,tmp2;
2890   bool needToCpyCT=true;
2891   if(!_nodal_connec)
2892     {
2893       tmp1=DataArrayInt::New(); tmp1->alloc(0,1);
2894       needToCpyCT=false;
2895     }
2896   else
2897     {
2898       tmp1=_nodal_connec;
2899       tmp1->incrRef();
2900     }
2901   if(!_nodal_connec_index)
2902     {
2903       tmp2=DataArrayInt::New(); tmp2->alloc(1,1); tmp2->setIJ(0,0,0);
2904       needToCpyCT=false;
2905     }
2906   else
2907     {
2908       tmp2=_nodal_connec_index;
2909       tmp2->incrRef();
2910     }
2911   ret->setConnectivity(tmp1,tmp2,false);
2912   if(needToCpyCT)
2913     ret->_types=_types;
2914   if(!_coords)
2915     {
2916       MCAuto<DataArrayDouble> coords=DataArrayDouble::New(); coords->alloc(0,spaceDim);
2917       ret->setCoords(coords);
2918     }
2919   else
2920     ret->setCoords(_coords);
2921   return ret.retn();
2922 }
2923
2924 int MEDCouplingUMesh::getNumberOfNodesInCell(int cellId) const
2925 {
2926   const int *ptI=_nodal_connec_index->getConstPointer();
2927   const int *pt=_nodal_connec->getConstPointer();
2928   if(pt[ptI[cellId]]!=INTERP_KERNEL::NORM_POLYHED)
2929     return ptI[cellId+1]-ptI[cellId]-1;
2930   else
2931     return (int)std::count_if(pt+ptI[cellId]+1,pt+ptI[cellId+1],std::bind2nd(std::not_equal_to<int>(),-1));
2932 }
2933
2934 /*!
2935  * Returns types of cells of the specified part of \a this mesh.
2936  * This method avoids computing sub-mesh explicitely to get its types.
2937  *  \param [in] begin - an array of cell ids of interest.
2938  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
2939  *  \return std::set<INTERP_KERNEL::NormalizedCellType> - a set of enumeration items
2940  *         describing the cell types. 
2941  *  \throw If the coordinates array is not set.
2942  *  \throw If the nodal connectivity of cells is not defined.
2943  *  \sa getAllGeoTypes()
2944  */
2945 std::set<INTERP_KERNEL::NormalizedCellType> MEDCouplingUMesh::getTypesOfPart(const int *begin, const int *end) const
2946 {
2947   checkFullyDefined();
2948   std::set<INTERP_KERNEL::NormalizedCellType> ret;
2949   const int *conn=_nodal_connec->getConstPointer();
2950   const int *connIndex=_nodal_connec_index->getConstPointer();
2951   for(const int *w=begin;w!=end;w++)
2952     ret.insert((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*w]]);
2953   return ret;
2954 }
2955
2956 /*!
2957  * Defines the nodal connectivity using given connectivity arrays in \ref numbering-indirect format.
2958  * Optionally updates
2959  * a set of types of cells constituting \a this mesh. 
2960  * This method is for advanced users having prepared their connectivity before. For
2961  * more info on using this method see \ref MEDCouplingUMeshAdvBuild.
2962  *  \param [in] conn - the nodal connectivity array. 
2963  *  \param [in] connIndex - the nodal connectivity index array.
2964  *  \param [in] isComputingTypes - if \c true, the set of types constituting \a this
2965  *         mesh is updated.
2966  */
2967 void MEDCouplingUMesh::setConnectivity(DataArrayInt *conn, DataArrayInt *connIndex, bool isComputingTypes)
2968 {
2969   DataArrayInt::SetArrayIn(conn,_nodal_connec);
2970   DataArrayInt::SetArrayIn(connIndex,_nodal_connec_index);
2971   if(isComputingTypes)
2972     computeTypes();
2973   declareAsNew();
2974 }
2975
2976 /*!
2977  * Copy constructor. If 'deepCopy' is false \a this is a shallow copy of other.
2978  * If 'deeCpy' is true all arrays (coordinates and connectivities) are deeply copied.
2979  */
2980 MEDCouplingUMesh::MEDCouplingUMesh(const MEDCouplingUMesh& other, bool deepCopy):MEDCouplingPointSet(other,deepCopy),_mesh_dim(other._mesh_dim),
2981     _nodal_connec(0),_nodal_connec_index(0),
2982     _types(other._types)
2983 {
2984   if(other._nodal_connec)
2985     _nodal_connec=other._nodal_connec->performCopyOrIncrRef(deepCopy);
2986   if(other._nodal_connec_index)
2987     _nodal_connec_index=other._nodal_connec_index->performCopyOrIncrRef(deepCopy);
2988 }
2989
2990 MEDCouplingUMesh::~MEDCouplingUMesh()
2991 {
2992   if(_nodal_connec)
2993     _nodal_connec->decrRef();
2994   if(_nodal_connec_index)
2995     _nodal_connec_index->decrRef();
2996 }
2997
2998 /*!
2999  * Recomputes a set of cell types of \a this mesh. For more info see
3000  * \ref MEDCouplingUMeshNodalConnectivity.
3001  */
3002 void MEDCouplingUMesh::computeTypes()
3003 {
3004   ComputeAllTypesInternal(_types,_nodal_connec,_nodal_connec_index);
3005 }
3006
3007
3008 /*!
3009  * Returns a number of cells constituting \a this mesh. 
3010  *  \return int - the number of cells in \a this mesh.
3011  *  \throw If the nodal connectivity of cells is not defined.
3012  */
3013 int MEDCouplingUMesh::getNumberOfCells() const
3014
3015   if(_nodal_connec_index)
3016     return _nodal_connec_index->getNumberOfTuples()-1;
3017   else
3018     if(_mesh_dim==-1)
3019       return 1;
3020     else
3021       throw INTERP_KERNEL::Exception("Unable to get number of cells because no connectivity specified !");
3022 }
3023
3024 /*!
3025  * Returns a dimension of \a this mesh, i.e. a dimension of cells constituting \a this
3026  * mesh. For more info see \ref meshes.
3027  *  \return int - the dimension of \a this mesh.
3028  *  \throw If the mesh dimension is not defined using setMeshDimension().
3029  */
3030 int MEDCouplingUMesh::getMeshDimension() const
3031 {
3032   if(_mesh_dim<-1)
3033     throw INTERP_KERNEL::Exception("No mesh dimension specified !");
3034   return _mesh_dim;
3035 }
3036
3037 /*!
3038  * Returns a length of the nodal connectivity array.
3039  * This method is for test reason. Normally the integer returned is not useable by
3040  * user.  For more info see \ref MEDCouplingUMeshNodalConnectivity.
3041  *  \return int - the length of the nodal connectivity array.
3042  */
3043 int MEDCouplingUMesh::getNodalConnectivityArrayLen() const
3044 {
3045   return _nodal_connec->getNbOfElems();
3046 }
3047
3048 /*!
3049  * First step of serialization process. Used by ParaMEDMEM and MEDCouplingCorba to transfert data between process.
3050  */
3051 void MEDCouplingUMesh::getTinySerializationInformation(std::vector<double>& tinyInfoD, std::vector<int>& tinyInfo, std::vector<std::string>& littleStrings) const
3052 {
3053   MEDCouplingPointSet::getTinySerializationInformation(tinyInfoD,tinyInfo,littleStrings);
3054   tinyInfo.push_back(getMeshDimension());
3055   tinyInfo.push_back(getNumberOfCells());
3056   if(_nodal_connec)
3057     tinyInfo.push_back(getNodalConnectivityArrayLen());
3058   else
3059     tinyInfo.push_back(-1);
3060 }
3061
3062 /*!
3063  * First step of unserialization process.
3064  */
3065 bool MEDCouplingUMesh::isEmptyMesh(const std::vector<int>& tinyInfo) const
3066 {
3067   return tinyInfo[6]<=0;
3068 }
3069
3070 /*!
3071  * Second step of serialization process.
3072  * \param tinyInfo must be equal to the result given by getTinySerializationInformation method.
3073  * \param a1
3074  * \param a2
3075  * \param littleStrings
3076  */
3077 void MEDCouplingUMesh::resizeForUnserialization(const std::vector<int>& tinyInfo, DataArrayInt *a1, DataArrayDouble *a2, std::vector<std::string>& littleStrings) const
3078 {
3079   MEDCouplingPointSet::resizeForUnserialization(tinyInfo,a1,a2,littleStrings);
3080   if(tinyInfo[5]!=-1)
3081     a1->alloc(tinyInfo[7]+tinyInfo[6]+1,1);
3082 }
3083
3084 /*!
3085  * Third and final step of serialization process.
3086  */
3087 void MEDCouplingUMesh::serialize(DataArrayInt *&a1, DataArrayDouble *&a2) const
3088 {
3089   MEDCouplingPointSet::serialize(a1,a2);
3090   if(getMeshDimension()>-1)
3091     {
3092       a1=DataArrayInt::New();
3093       a1->alloc(getNodalConnectivityArrayLen()+getNumberOfCells()+1,1);
3094       int *ptA1=a1->getPointer();
3095       const int *conn=getNodalConnectivity()->getConstPointer();
3096       const int *index=getNodalConnectivityIndex()->getConstPointer();
3097       ptA1=std::copy(index,index+getNumberOfCells()+1,ptA1);
3098       std::copy(conn,conn+getNodalConnectivityArrayLen(),ptA1);
3099     }
3100   else
3101     a1=0;
3102 }
3103
3104 /*!
3105  * Second and final unserialization process.
3106  * \param tinyInfo must be equal to the result given by getTinySerializationInformation method.
3107  */
3108 void MEDCouplingUMesh::unserialization(const std::vector<double>& tinyInfoD, const std::vector<int>& tinyInfo, const DataArrayInt *a1, DataArrayDouble *a2, const std::vector<std::string>& littleStrings)
3109 {
3110   MEDCouplingPointSet::unserialization(tinyInfoD,tinyInfo,a1,a2,littleStrings);
3111   setMeshDimension(tinyInfo[5]);
3112   if(tinyInfo[7]!=-1)
3113     {
3114       // Connectivity
3115       const int *recvBuffer=a1->getConstPointer();
3116       MCAuto<DataArrayInt> myConnecIndex=DataArrayInt::New();
3117       myConnecIndex->alloc(tinyInfo[6]+1,1);
3118       std::copy(recvBuffer,recvBuffer+tinyInfo[6]+1,myConnecIndex->getPointer());
3119       MCAuto<DataArrayInt> myConnec=DataArrayInt::New();
3120       myConnec->alloc(tinyInfo[7],1);
3121       std::copy(recvBuffer+tinyInfo[6]+1,recvBuffer+tinyInfo[6]+1+tinyInfo[7],myConnec->getPointer());
3122       setConnectivity(myConnec, myConnecIndex);
3123     }
3124 }
3125
3126
3127
3128 /*!
3129  * Returns a new MEDCouplingFieldDouble containing volumes of cells constituting \a this
3130  * mesh.<br>
3131  * For 1D cells, the returned field contains lengths.<br>
3132  * For 2D cells, the returned field contains areas.<br>
3133  * For 3D cells, the returned field contains volumes.
3134  *  \param [in] isAbs - if \c true, the computed cell volume does not reflect cell
3135  *         orientation, i.e. the volume is always positive.
3136  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on cells
3137  *         and one time . The caller is to delete this field using decrRef() as it is no
3138  *         more needed.
3139  */
3140 MEDCouplingFieldDouble *MEDCouplingUMesh::getMeasureField(bool isAbs) const
3141 {
3142   std::string name="MeasureOfMesh_";
3143   name+=getName();
3144   int nbelem=getNumberOfCells();
3145   MCAuto<MEDCouplingFieldDouble> field=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3146   field->setName(name);
3147   MCAuto<DataArrayDouble> array=DataArrayDouble::New();
3148   array->alloc(nbelem,1);
3149   double *area_vol=array->getPointer();
3150   field->setArray(array) ; array=0;
3151   field->setMesh(const_cast<MEDCouplingUMesh *>(this));
3152   field->synchronizeTimeWithMesh();
3153   if(getMeshDimension()!=-1)
3154     {
3155       int ipt;
3156       INTERP_KERNEL::NormalizedCellType type;
3157       int dim_space=getSpaceDimension();
3158       const double *coords=getCoords()->getConstPointer();
3159       const int *connec=getNodalConnectivity()->getConstPointer();
3160       const int *connec_index=getNodalConnectivityIndex()->getConstPointer();
3161       for(int iel=0;iel<nbelem;iel++)
3162         {
3163           ipt=connec_index[iel];
3164           type=(INTERP_KERNEL::NormalizedCellType)connec[ipt];
3165           area_vol[iel]=INTERP_KERNEL::computeVolSurfOfCell2<int,INTERP_KERNEL::ALL_C_MODE>(type,connec+ipt+1,connec_index[iel+1]-ipt-1,coords,dim_space);
3166         }
3167       if(isAbs)
3168         std::transform(area_vol,area_vol+nbelem,area_vol,std::ptr_fun<double,double>(fabs));
3169     }
3170   else
3171     {
3172       area_vol[0]=std::numeric_limits<double>::max();
3173     }
3174   return field.retn();
3175 }
3176
3177 /*!
3178  * Returns a new DataArrayDouble containing volumes of specified cells of \a this
3179  * mesh.<br>
3180  * For 1D cells, the returned array contains lengths.<br>
3181  * For 2D cells, the returned array contains areas.<br>
3182  * For 3D cells, the returned array contains volumes.
3183  * This method avoids building explicitly a part of \a this mesh to perform the work.
3184  *  \param [in] isAbs - if \c true, the computed cell volume does not reflect cell
3185  *         orientation, i.e. the volume is always positive.
3186  *  \param [in] begin - an array of cell ids of interest.
3187  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
3188  *  \return DataArrayDouble * - a new instance of DataArrayDouble. The caller is to
3189  *          delete this array using decrRef() as it is no more needed.
3190  * 
3191  *  \if ENABLE_EXAMPLES
3192  *  \ref cpp_mcumesh_getPartMeasureField "Here is a C++ example".<br>
3193  *  \ref  py_mcumesh_getPartMeasureField "Here is a Python example".
3194  *  \endif
3195  *  \sa getMeasureField()
3196  */
3197 DataArrayDouble *MEDCouplingUMesh::getPartMeasureField(bool isAbs, const int *begin, const int *end) const
3198 {
3199   std::string name="PartMeasureOfMesh_";
3200   name+=getName();
3201   int nbelem=(int)std::distance(begin,end);
3202   MCAuto<DataArrayDouble> array=DataArrayDouble::New();
3203   array->setName(name);
3204   array->alloc(nbelem,1);
3205   double *area_vol=array->getPointer();
3206   if(getMeshDimension()!=-1)
3207     {
3208       int ipt;
3209       INTERP_KERNEL::NormalizedCellType type;
3210       int dim_space=getSpaceDimension();
3211       const double *coords=getCoords()->getConstPointer();
3212       const int *connec=getNodalConnectivity()->getConstPointer();
3213       const int *connec_index=getNodalConnectivityIndex()->getConstPointer();
3214       for(const int *iel=begin;iel!=end;iel++)
3215         {
3216           ipt=connec_index[*iel];
3217           type=(INTERP_KERNEL::NormalizedCellType)connec[ipt];
3218           *area_vol++=INTERP_KERNEL::computeVolSurfOfCell2<int,INTERP_KERNEL::ALL_C_MODE>(type,connec+ipt+1,connec_index[*iel+1]-ipt-1,coords,dim_space);
3219         }
3220       if(isAbs)
3221         std::transform(array->getPointer(),area_vol,array->getPointer(),std::ptr_fun<double,double>(fabs));
3222     }
3223   else
3224     {
3225       area_vol[0]=std::numeric_limits<double>::max();
3226     }
3227   return array.retn();
3228 }
3229
3230 /*!
3231  * Returns a new MEDCouplingFieldDouble containing volumes of cells of a dual mesh of
3232  * \a this one. The returned field contains the dual cell volume for each corresponding
3233  * node in \a this mesh. In other words, the field returns the getMeasureField() of
3234  *  the dual mesh in P1 sens of \a this.<br>
3235  * For 1D cells, the returned field contains lengths.<br>
3236  * For 2D cells, the returned field contains areas.<br>
3237  * For 3D cells, the returned field contains volumes.
3238  * This method is useful to check "P1*" conservative interpolators.
3239  *  \param [in] isAbs - if \c true, the computed cell volume does not reflect cell
3240  *         orientation, i.e. the volume is always positive.
3241  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3242  *          nodes and one time. The caller is to delete this array using decrRef() as
3243  *          it is no more needed.
3244  */
3245 MEDCouplingFieldDouble *MEDCouplingUMesh::getMeasureFieldOnNode(bool isAbs) const
3246 {
3247   MCAuto<MEDCouplingFieldDouble> tmp=getMeasureField(isAbs);
3248   std::string name="MeasureOnNodeOfMesh_";
3249   name+=getName();
3250   int nbNodes=getNumberOfNodes();
3251   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_NODES);
3252   double cst=1./((double)getMeshDimension()+1.);
3253   MCAuto<DataArrayDouble> array=DataArrayDouble::New();
3254   array->alloc(nbNodes,1);
3255   double *valsToFill=array->getPointer();
3256   std::fill(valsToFill,valsToFill+nbNodes,0.);
3257   const double *values=tmp->getArray()->getConstPointer();
3258   MCAuto<DataArrayInt> da=DataArrayInt::New();
3259   MCAuto<DataArrayInt> daInd=DataArrayInt::New();
3260   getReverseNodalConnectivity(da,daInd);
3261   const int *daPtr=da->getConstPointer();
3262   const int *daIPtr=daInd->getConstPointer();
3263   for(int i=0;i<nbNodes;i++)
3264     for(const int *cell=daPtr+daIPtr[i];cell!=daPtr+daIPtr[i+1];cell++)
3265       valsToFill[i]+=cst*values[*cell];
3266   ret->setMesh(this);
3267   ret->setArray(array);
3268   return ret.retn();
3269 }
3270
3271 /*!
3272  * Returns a new MEDCouplingFieldDouble holding normal vectors to cells of \a this
3273  * mesh. The returned normal vectors to each cell have a norm2 equal to 1.
3274  * The computed vectors have <em> this->getMeshDimension()+1 </em> components
3275  * and are normalized.
3276  * <br> \a this can be either 
3277  * - a  2D mesh in 2D or 3D space or 
3278  * - an 1D mesh in 2D space.
3279  * 
3280  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3281  *          cells and one time. The caller is to delete this field using decrRef() as
3282  *          it is no more needed.
3283  *  \throw If the nodal connectivity of cells is not defined.
3284  *  \throw If the coordinates array is not set.
3285  *  \throw If the mesh dimension is not set.
3286  *  \throw If the mesh and space dimension is not as specified above.
3287  */
3288 MEDCouplingFieldDouble *MEDCouplingUMesh::buildOrthogonalField() const
3289 {
3290   if((getMeshDimension()!=2) && (getMeshDimension()!=1 || getSpaceDimension()!=2))
3291     throw INTERP_KERNEL::Exception("Expected a umesh with ( meshDim == 2 spaceDim == 2 or 3 ) or ( meshDim == 1 spaceDim == 2 ) !");
3292   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3293   MCAuto<DataArrayDouble> array=DataArrayDouble::New();
3294   int nbOfCells=getNumberOfCells();
3295   int nbComp=getMeshDimension()+1;
3296   array->alloc(nbOfCells,nbComp);
3297   double *vals=array->getPointer();
3298   const int *connI=_nodal_connec_index->getConstPointer();
3299   const int *conn=_nodal_connec->getConstPointer();
3300   const double *coords=_coords->getConstPointer();
3301   if(getMeshDimension()==2)
3302     {
3303       if(getSpaceDimension()==3)
3304         {
3305           MCAuto<DataArrayDouble> loc=computeCellCenterOfMass();
3306           const double *locPtr=loc->getConstPointer();
3307           for(int i=0;i<nbOfCells;i++,vals+=3)
3308             {
3309               int offset=connI[i];
3310               INTERP_KERNEL::crossprod<3>(locPtr+3*i,coords+3*conn[offset+1],coords+3*conn[offset+2],vals);
3311               double n=INTERP_KERNEL::norm<3>(vals);
3312               std::transform(vals,vals+3,vals,std::bind2nd(std::multiplies<double>(),1./n));
3313             }
3314         }
3315       else
3316         {
3317           MCAuto<MEDCouplingFieldDouble> isAbs=getMeasureField(false);
3318           const double *isAbsPtr=isAbs->getArray()->begin();
3319           for(int i=0;i<nbOfCells;i++,isAbsPtr++)
3320             { vals[3*i]=0.; vals[3*i+1]=0.; vals[3*i+2]=*isAbsPtr>0.?1.:-1.; }
3321         }
3322     }
3323   else//meshdimension==1
3324     {
3325       double tmp[2];
3326       for(int i=0;i<nbOfCells;i++)
3327         {
3328           int offset=connI[i];
3329           std::transform(coords+2*conn[offset+2],coords+2*conn[offset+2]+2,coords+2*conn[offset+1],tmp,std::minus<double>());
3330           double n=INTERP_KERNEL::norm<2>(tmp);
3331           std::transform(tmp,tmp+2,tmp,std::bind2nd(std::multiplies<double>(),1./n));
3332           *vals++=-tmp[1];
3333           *vals++=tmp[0];
3334         }
3335     }
3336   ret->setArray(array);
3337   ret->setMesh(this);
3338   ret->synchronizeTimeWithSupport();
3339   return ret.retn();
3340 }
3341
3342 /*!
3343  * Returns a new MEDCouplingFieldDouble holding normal vectors to specified cells of
3344  * \a this mesh. The computed vectors have <em> this->getMeshDimension()+1 </em> components
3345  * and are normalized.
3346  * <br> \a this can be either 
3347  * - a  2D mesh in 2D or 3D space or 
3348  * - an 1D mesh in 2D space.
3349  * 
3350  * This method avoids building explicitly a part of \a this mesh to perform the work.
3351  *  \param [in] begin - an array of cell ids of interest.
3352  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
3353  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3354  *          cells and one time. The caller is to delete this field using decrRef() as
3355  *          it is no more needed.
3356  *  \throw If the nodal connectivity of cells is not defined.
3357  *  \throw If the coordinates array is not set.
3358  *  \throw If the mesh dimension is not set.
3359  *  \throw If the mesh and space dimension is not as specified above.
3360  *  \sa buildOrthogonalField()
3361  *
3362  *  \if ENABLE_EXAMPLES
3363  *  \ref cpp_mcumesh_buildPartOrthogonalField "Here is a C++ example".<br>
3364  *  \ref  py_mcumesh_buildPartOrthogonalField "Here is a Python example".
3365  *  \endif
3366  */
3367 MEDCouplingFieldDouble *MEDCouplingUMesh::buildPartOrthogonalField(const int *begin, const int *end) const
3368 {
3369   if((getMeshDimension()!=2) && (getMeshDimension()!=1 || getSpaceDimension()!=2))
3370     throw INTERP_KERNEL::Exception("Expected a umesh with ( meshDim == 2 spaceDim == 2 or 3 ) or ( meshDim == 1 spaceDim == 2 ) !");
3371   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3372   MCAuto<DataArrayDouble> array=DataArrayDouble::New();
3373   std::size_t nbelems=std::distance(begin,end);
3374   int nbComp=getMeshDimension()+1;
3375   array->alloc((int)nbelems,nbComp);
3376   double *vals=array->getPointer();
3377   const int *connI=_nodal_connec_index->getConstPointer();
3378   const int *conn=_nodal_connec->getConstPointer();
3379   const double *coords=_coords->getConstPointer();
3380   if(getMeshDimension()==2)
3381     {
3382       if(getSpaceDimension()==3)
3383         {
3384           MCAuto<DataArrayDouble> loc=getPartBarycenterAndOwner(begin,end);
3385           const double *locPtr=loc->getConstPointer();
3386           for(const int *i=begin;i!=end;i++,vals+=3,locPtr+=3)
3387             {
3388               int offset=connI[*i];
3389               INTERP_KERNEL::crossprod<3>(locPtr,coords+3*conn[offset+1],coords+3*conn[offset+2],vals);
3390               double n=INTERP_KERNEL::norm<3>(vals);
3391               std::transform(vals,vals+3,vals,std::bind2nd(std::multiplies<double>(),1./n));
3392             }
3393         }
3394       else
3395         {
3396           for(std::size_t i=0;i<nbelems;i++)
3397             { vals[3*i]=0.; vals[3*i+1]=0.; vals[3*i+2]=1.; }
3398         }
3399     }
3400   else//meshdimension==1
3401     {
3402       double tmp[2];
3403       for(const int *i=begin;i!=end;i++)
3404         {
3405           int offset=connI[*i];
3406           std::transform(coords+2*conn[offset+2],coords+2*conn[offset+2]+2,coords+2*conn[offset+1],tmp,std::minus<double>());
3407           double n=INTERP_KERNEL::norm<2>(tmp);
3408           std::transform(tmp,tmp+2,tmp,std::bind2nd(std::multiplies<double>(),1./n));
3409           *vals++=-tmp[1];
3410           *vals++=tmp[0];
3411         }
3412     }
3413   ret->setArray(array);
3414   ret->setMesh(this);
3415   ret->synchronizeTimeWithSupport();
3416   return ret.retn();
3417 }
3418
3419 /*!
3420  * Returns a new MEDCouplingFieldDouble holding a direction vector for each SEG2 in \a
3421  * this 1D mesh. The computed vectors have <em> this->getSpaceDimension() </em> components
3422  * and are \b not normalized.
3423  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
3424  *          cells and one time. The caller is to delete this field using decrRef() as
3425  *          it is no more needed.
3426  *  \throw If the nodal connectivity of cells is not defined.
3427  *  \throw If the coordinates array is not set.
3428  *  \throw If \a this->getMeshDimension() != 1.
3429  *  \throw If \a this mesh includes cells of type other than SEG2.
3430  */
3431 MEDCouplingFieldDouble *MEDCouplingUMesh::buildDirectionVectorField() const
3432 {
3433   if(getMeshDimension()!=1)
3434     throw INTERP_KERNEL::Exception("Expected a umesh with meshDim == 1 for buildDirectionVectorField !");
3435   if(_types.size()!=1 || *(_types.begin())!=INTERP_KERNEL::NORM_SEG2)
3436     throw INTERP_KERNEL::Exception("Expected a umesh with only NORM_SEG2 type of elements for buildDirectionVectorField !");
3437   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
3438   MCAuto<DataArrayDouble> array=DataArrayDouble::New();
3439   int nbOfCells=getNumberOfCells();
3440   int spaceDim=getSpaceDimension();
3441   array->alloc(nbOfCells,spaceDim);
3442   double *pt=array->getPointer();
3443   const double *coo=getCoords()->getConstPointer();
3444   std::vector<int> conn;
3445   conn.reserve(2);
3446   for(int i=0;i<nbOfCells;i++)
3447     {
3448       conn.resize(0);
3449       getNodeIdsOfCell(i,conn);
3450       pt=std::transform(coo+conn[1]*spaceDim,coo+(conn[1]+1)*spaceDim,coo+conn[0]*spaceDim,pt,std::minus<double>());
3451     }
3452   ret->setArray(array);
3453   ret->setMesh(this);
3454   ret->synchronizeTimeWithSupport();
3455   return ret.retn();
3456 }
3457
3458 /*!
3459  * Creates a 2D mesh by cutting \a this 3D mesh with a plane. In addition to the mesh,
3460  * returns a new DataArrayInt, of length equal to the number of 2D cells in the result
3461  * mesh, holding, for each cell in the result mesh, an id of a 3D cell it comes
3462  * from. If a result face is shared by two 3D cells, then the face in included twice in
3463  * the result mesh.
3464  *  \param [in] origin - 3 components of a point defining location of the plane.
3465  *  \param [in] vec - 3 components of a vector normal to the plane. Vector magnitude
3466  *         must be greater than 1e-6.
3467  *  \param [in] eps - half-thickness of the plane.
3468  *  \param [out] cellIds - a new instance of DataArrayInt holding ids of 3D cells
3469  *         producing correspondent 2D cells. The caller is to delete this array
3470  *         using decrRef() as it is no more needed.
3471  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. This mesh does
3472  *         not share the node coordinates array with \a this mesh. The caller is to
3473  *         delete this mesh using decrRef() as it is no more needed.  
3474  *  \throw If the coordinates array is not set.
3475  *  \throw If the nodal connectivity of cells is not defined.
3476  *  \throw If \a this->getMeshDimension() != 3 or \a this->getSpaceDimension() != 3.
3477  *  \throw If magnitude of \a vec is less than 1e-6.
3478  *  \throw If the plane does not intersect any 3D cell of \a this mesh.
3479  *  \throw If \a this includes quadratic cells.
3480  */
3481 MEDCouplingUMesh *MEDCouplingUMesh::buildSlice3D(const double *origin, const double *vec, double eps, DataArrayInt *&cellIds) const
3482 {
3483   checkFullyDefined();
3484   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
3485     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D works on umeshes with meshdim equal to 3 and spaceDim equal to 3 too!");
3486   MCAuto<DataArrayInt> candidates=getCellIdsCrossingPlane(origin,vec,eps);
3487   if(candidates->empty())
3488     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D : No 3D cells in this intercepts the specified plane considering bounding boxes !");
3489   std::vector<int> nodes;
3490   DataArrayInt *cellIds1D=0;
3491   MCAuto<MEDCouplingUMesh> subMesh=static_cast<MEDCouplingUMesh*>(buildPartOfMySelf(candidates->begin(),candidates->end(),false));
3492   subMesh->findNodesOnPlane(origin,vec,eps,nodes);
3493   MCAuto<DataArrayInt> desc1=DataArrayInt::New(),desc2=DataArrayInt::New();
3494   MCAuto<DataArrayInt> descIndx1=DataArrayInt::New(),descIndx2=DataArrayInt::New();
3495   MCAuto<DataArrayInt> revDesc1=DataArrayInt::New(),revDesc2=DataArrayInt::New();
3496   MCAuto<DataArrayInt> revDescIndx1=DataArrayInt::New(),revDescIndx2=DataArrayInt::New();
3497   MCAuto<MEDCouplingUMesh> mDesc2=subMesh->buildDescendingConnectivity(desc2,descIndx2,revDesc2,revDescIndx2);//meshDim==2 spaceDim==3
3498   revDesc2=0; revDescIndx2=0;
3499   MCAuto<MEDCouplingUMesh> mDesc1=mDesc2->buildDescendingConnectivity(desc1,descIndx1,revDesc1,revDescIndx1);//meshDim==1 spaceDim==3
3500   revDesc1=0; revDescIndx1=0;
3501   mDesc1->fillCellIdsToKeepFromNodeIds(&nodes[0],&nodes[0]+nodes.size(),true,cellIds1D);
3502   MCAuto<DataArrayInt> cellIds1DTmp(cellIds1D);
3503   //
3504   std::vector<int> cut3DCurve(mDesc1->getNumberOfCells(),-2);
3505   for(const int *it=cellIds1D->begin();it!=cellIds1D->end();it++)
3506     cut3DCurve[*it]=-1;
3507   mDesc1->split3DCurveWithPlane(origin,vec,eps,cut3DCurve);
3508   std::vector< std::pair<int,int> > cut3DSurf(mDesc2->getNumberOfCells());
3509   AssemblyForSplitFrom3DCurve(cut3DCurve,nodes,mDesc2->getNodalConnectivity()->getConstPointer(),mDesc2->getNodalConnectivityIndex()->getConstPointer(),
3510                               mDesc1->getNodalConnectivity()->getConstPointer(),mDesc1->getNodalConnectivityIndex()->getConstPointer(),
3511                               desc1->getConstPointer(),descIndx1->getConstPointer(),cut3DSurf);
3512   MCAuto<DataArrayInt> conn(DataArrayInt::New()),connI(DataArrayInt::New()),cellIds2(DataArrayInt::New());
3513   connI->pushBackSilent(0); conn->alloc(0,1); cellIds2->alloc(0,1);
3514   subMesh->assemblyForSplitFrom3DSurf(cut3DSurf,desc2->getConstPointer(),descIndx2->getConstPointer(),conn,connI,cellIds2);
3515   if(cellIds2->empty())
3516     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D : No 3D cells in this intercepts the specified plane !");
3517   MCAuto<MEDCouplingUMesh> ret=MEDCouplingUMesh::New("Slice3D",2);
3518   ret->setCoords(mDesc1->getCoords());
3519   ret->setConnectivity(conn,connI,true);
3520   cellIds=candidates->selectByTupleId(cellIds2->begin(),cellIds2->end());
3521   return ret.retn();
3522 }
3523
3524 /*!
3525  * Creates an 1D mesh by cutting \a this 2D mesh in 3D space with a plane. In
3526 addition to the mesh, returns a new DataArrayInt, of length equal to the number of 1D cells in the result mesh, holding, for each cell in the result mesh, an id of a 2D cell it comes
3527 from. If a result segment is shared by two 2D cells, then the segment in included twice in
3528 the result mesh.
3529  *  \param [in] origin - 3 components of a point defining location of the plane.
3530  *  \param [in] vec - 3 components of a vector normal to the plane. Vector magnitude
3531  *         must be greater than 1e-6.
3532  *  \param [in] eps - half-thickness of the plane.
3533  *  \param [out] cellIds - a new instance of DataArrayInt holding ids of faces
3534  *         producing correspondent segments. The caller is to delete this array
3535  *         using decrRef() as it is no more needed.
3536  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. This is an 1D
3537  *         mesh in 3D space. This mesh does not share the node coordinates array with
3538  *         \a this mesh. The caller is to delete this mesh using decrRef() as it is
3539  *         no more needed. 
3540  *  \throw If the coordinates array is not set.
3541  *  \throw If the nodal connectivity of cells is not defined.
3542  *  \throw If \a this->getMeshDimension() != 2 or \a this->getSpaceDimension() != 3.
3543  *  \throw If magnitude of \a vec is less than 1e-6.
3544  *  \throw If the plane does not intersect any 2D cell of \a this mesh.
3545  *  \throw If \a this includes quadratic cells.
3546  */
3547 MEDCouplingUMesh *MEDCouplingUMesh::buildSlice3DSurf(const double *origin, const double *vec, double eps, DataArrayInt *&cellIds) const
3548 {
3549   checkFullyDefined();
3550   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
3551     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3DSurf works on umeshes with meshdim equal to 2 and spaceDim equal to 3 !");
3552   MCAuto<DataArrayInt> candidates(getCellIdsCrossingPlane(origin,vec,eps));
3553   if(candidates->empty())
3554     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3DSurf : No 3D surf cells in this intercepts the specified plane considering bounding boxes !");
3555   std::vector<int> nodes;
3556   DataArrayInt *cellIds1D(0);
3557   MCAuto<MEDCouplingUMesh> subMesh(buildPartOfMySelf(candidates->begin(),candidates->end(),false));
3558   subMesh->findNodesOnPlane(origin,vec,eps,nodes);
3559   MCAuto<DataArrayInt> desc1(DataArrayInt::New()),descIndx1(DataArrayInt::New()),revDesc1(DataArrayInt::New()),revDescIndx1(DataArrayInt::New());
3560   MCAuto<MEDCouplingUMesh> mDesc1(subMesh->buildDescendingConnectivity(desc1,descIndx1,revDesc1,revDescIndx1));//meshDim==1 spaceDim==3
3561   mDesc1->fillCellIdsToKeepFromNodeIds(&nodes[0],&nodes[0]+nodes.size(),true,cellIds1D);
3562   MCAuto<DataArrayInt> cellIds1DTmp(cellIds1D);
3563   //
3564   std::vector<int> cut3DCurve(mDesc1->getNumberOfCells(),-2);
3565   for(const int *it=cellIds1D->begin();it!=cellIds1D->end();it++)
3566     cut3DCurve[*it]=-1;
3567   mDesc1->split3DCurveWithPlane(origin,vec,eps,cut3DCurve);
3568   int ncellsSub=subMesh->getNumberOfCells();
3569   std::vector< std::pair<int,int> > cut3DSurf(ncellsSub);
3570   AssemblyForSplitFrom3DCurve(cut3DCurve,nodes,subMesh->getNodalConnectivity()->getConstPointer(),subMesh->getNodalConnectivityIndex()->getConstPointer(),
3571                               mDesc1->getNodalConnectivity()->getConstPointer(),mDesc1->getNodalConnectivityIndex()->getConstPointer(),
3572                               desc1->getConstPointer(),descIndx1->getConstPointer(),cut3DSurf);
3573   MCAuto<DataArrayInt> conn(DataArrayInt::New()),connI(DataArrayInt::New()),cellIds2(DataArrayInt::New()); connI->pushBackSilent(0);
3574   conn->alloc(0,1);
3575   const int *nodal=subMesh->getNodalConnectivity()->getConstPointer();
3576   const int *nodalI=subMesh->getNodalConnectivityIndex()->getConstPointer();
3577   for(int i=0;i<ncellsSub;i++)
3578     {
3579       if(cut3DSurf[i].first!=-1 && cut3DSurf[i].second!=-1)
3580         {
3581           if(cut3DSurf[i].first!=-2)
3582             {
3583               conn->pushBackSilent((int)INTERP_KERNEL::NORM_SEG2); conn->pushBackSilent(cut3DSurf[i].first); conn->pushBackSilent(cut3DSurf[i].second);
3584               connI->pushBackSilent(conn->getNumberOfTuples());
3585               cellIds2->pushBackSilent(i);
3586             }
3587           else
3588             {
3589               int cellId3DSurf=cut3DSurf[i].second;
3590               int offset=nodalI[cellId3DSurf]+1;
3591               int nbOfEdges=nodalI[cellId3DSurf+1]-offset;
3592               for(int j=0;j<nbOfEdges;j++)
3593                 {
3594                   conn->pushBackSilent((int)INTERP_KERNEL::NORM_SEG2); conn->pushBackSilent(nodal[offset+j]); conn->pushBackSilent(nodal[offset+(j+1)%nbOfEdges]);
3595                   connI->pushBackSilent(conn->getNumberOfTuples());
3596                   cellIds2->pushBackSilent(cellId3DSurf);
3597                 }
3598             }
3599         }
3600     }
3601   if(cellIds2->empty())
3602     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3DSurf : No 3DSurf cells in this intercepts the specified plane !");
3603   MCAuto<MEDCouplingUMesh> ret=MEDCouplingUMesh::New("Slice3DSurf",1);
3604   ret->setCoords(mDesc1->getCoords());
3605   ret->setConnectivity(conn,connI,true);
3606   cellIds=candidates->selectByTupleId(cellIds2->begin(),cellIds2->end());
3607   return ret.retn();
3608 }
3609
3610 MCAuto<MEDCouplingUMesh> MEDCouplingUMesh::clipSingle3DCellByPlane(const double origin[3], const double vec[3], double eps) const
3611 {
3612   checkFullyDefined();
3613   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
3614     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::clipSingle3DCellByPlane works on umeshes with meshdim equal to 3 and spaceDim equal to 3 too!");
3615   if(getNumberOfCells()!=1)
3616     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::clipSingle3DCellByPlane works only on mesh containing exactly one cell !");
3617   //
3618   std::vector<int> nodes;
3619   findNodesOnPlane(origin,vec,eps,nodes);
3620   MCAuto<DataArrayInt> desc1(DataArrayInt::New()),desc2(DataArrayInt::New()),descIndx1(DataArrayInt::New()),descIndx2(DataArrayInt::New()),revDesc1(DataArrayInt::New()),revDesc2(DataArrayInt::New()),revDescIndx1(DataArrayInt::New()),revDescIndx2(DataArrayInt::New());
3621   MCAuto<MEDCouplingUMesh> mDesc2(buildDescendingConnectivity(desc2,descIndx2,revDesc2,revDescIndx2));//meshDim==2 spaceDim==3
3622   revDesc2=0; revDescIndx2=0;
3623   MCAuto<MEDCouplingUMesh> mDesc1(mDesc2->buildDescendingConnectivity(desc1,descIndx1,revDesc1,revDescIndx1));//meshDim==1 spaceDim==3
3624   revDesc1=0; revDescIndx1=0;
3625   DataArrayInt *cellIds1D(0);
3626   mDesc1->fillCellIdsToKeepFromNodeIds(&nodes[0],&nodes[0]+nodes.size(),true,cellIds1D);
3627   MCAuto<DataArrayInt> cellIds1DTmp(cellIds1D);
3628   std::vector<int> cut3DCurve(mDesc1->getNumberOfCells(),-2);
3629   for(const int *it=cellIds1D->begin();it!=cellIds1D->end();it++)
3630     cut3DCurve[*it]=-1;
3631   mDesc1->split3DCurveWithPlane(origin,vec,eps,cut3DCurve);
3632   std::vector< std::pair<int,int> > cut3DSurf(mDesc2->getNumberOfCells());
3633   AssemblyForSplitFrom3DCurve(cut3DCurve,nodes,mDesc2->getNodalConnectivity()->begin(),mDesc2->getNodalConnectivityIndex()->begin(),
3634                               mDesc1->getNodalConnectivity()->begin(),mDesc1->getNodalConnectivityIndex()->begin(),
3635                               desc1->begin(),descIndx1->begin(),cut3DSurf);
3636   MCAuto<DataArrayInt> conn(DataArrayInt::New()),connI(DataArrayInt::New());
3637   connI->pushBackSilent(0); conn->alloc(0,1);
3638   {
3639     MCAuto<DataArrayInt> cellIds2(DataArrayInt::New()); cellIds2->alloc(0,1);
3640     assemblyForSplitFrom3DSurf(cut3DSurf,desc2->begin(),descIndx2->begin(),conn,connI,cellIds2);
3641     if(cellIds2->empty())
3642       throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D : No 3D cells in this intercepts the specified plane !");
3643   }
3644   std::vector<std::vector<int> > res;
3645   buildSubCellsFromCut(cut3DSurf,desc2->begin(),descIndx2->begin(),mDesc1->getCoords()->begin(),eps,res);
3646   std::size_t sz(res.size());
3647   if(res.size()==mDesc1->getNumberOfCells())
3648     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::clipSingle3DCellByPlane : cell is not clipped !");
3649   for(std::size_t i=0;i<sz;i++)
3650     {
3651       conn->pushBackSilent((int)INTERP_KERNEL::NORM_POLYGON);
3652       conn->insertAtTheEnd(res[i].begin(),res[i].end());
3653       connI->pushBackSilent(conn->getNumberOfTuples());
3654     }
3655   MCAuto<MEDCouplingUMesh> ret(MEDCouplingUMesh::New("",2));
3656   ret->setCoords(mDesc1->getCoords());
3657   ret->setConnectivity(conn,connI,true);
3658   int nbCellsRet(ret->getNumberOfCells());
3659   //
3660   MCAuto<DataArrayDouble> vec2(DataArrayDouble::New()); vec2->alloc(1,3); std::copy(vec,vec+3,vec2->getPointer());
3661   MCAuto<MEDCouplingFieldDouble> ortho(ret->buildOrthogonalField());
3662   MCAuto<DataArrayDouble> ortho2(ortho->getArray()->selectByTupleIdSafeSlice(0,1,1));
3663   MCAuto<DataArrayDouble> dott(DataArrayDouble::Dot(ortho2,vec2));
3664   MCAuto<DataArrayDouble> ccm(ret->computeCellCenterOfMass());
3665   MCAuto<DataArrayDouble> occm;
3666   {
3667     MCAuto<DataArrayDouble> pt(DataArrayDouble::New()); pt->alloc(1,3); std::copy(origin,origin+3,pt->getPointer());
3668     occm=DataArrayDouble::Substract(ccm,pt);
3669   }
3670   vec2=DataArrayDouble::New(); vec2->alloc(nbCellsRet,3);
3671   vec2->setPartOfValuesSimple1(vec[0],0,nbCellsRet,1,0,1,1); vec2->setPartOfValuesSimple1(vec[1],0,nbCellsRet,1,1,2,1); vec2->setPartOfValuesSimple1(vec[2],0,nbCellsRet,1,2,3,1);
3672   MCAuto<DataArrayDouble> dott2(DataArrayDouble::Dot(occm,vec2));
3673   //
3674   const int *cPtr(ret->getNodalConnectivity()->begin()),*ciPtr(ret->getNodalConnectivityIndex()->begin());
3675   MCAuto<MEDCouplingUMesh> ret2(MEDCouplingUMesh::New("Clip3D",3));
3676   ret2->setCoords(mDesc1->getCoords());
3677   MCAuto<DataArrayInt> conn2(DataArrayInt::New()),conn2I(DataArrayInt::New());
3678   conn2I->pushBackSilent(0); conn2->alloc(0,1);
3679   std::vector<int> cell0(1,(int)INTERP_KERNEL::NORM_POLYHED);
3680   std::vector<int> cell1(1,(int)INTERP_KERNEL::NORM_POLYHED);
3681   if(dott->getIJ(0,0)>0)
3682     {
3683       cell0.insert(cell0.end(),cPtr+1,cPtr+ciPtr[1]);
3684       std::reverse_copy(cPtr+1,cPtr+ciPtr[1],std::inserter(cell1,cell1.end()));
3685     }
3686   else
3687     {
3688       cell1.insert(cell1.end(),cPtr+1,cPtr+ciPtr[1]);
3689       std::reverse_copy(cPtr+1,cPtr+ciPtr[1],std::inserter(cell0,cell0.end()));
3690     }
3691   for(int i=1;i<nbCellsRet;i++)
3692     {
3693       if(dott2->getIJ(i,0)<0)
3694         {
3695           if(ciPtr[i+1]-ciPtr[i]>=4)
3696             {
3697               cell0.push_back(-1);
3698               cell0.insert(cell0.end(),cPtr+ciPtr[i]+1,cPtr+ciPtr[i+1]);
3699             }
3700         }
3701       else
3702         {
3703           if(ciPtr[i+1]-ciPtr[i]>=4)
3704             {
3705               cell1.push_back(-1);
3706               cell1.insert(cell1.end(),cPtr+ciPtr[i]+1,cPtr+ciPtr[i+1]);
3707             }
3708         }
3709     }
3710   conn2->insertAtTheEnd(cell0.begin(),cell0.end());
3711   conn2I->pushBackSilent(conn2->getNumberOfTuples());
3712   conn2->insertAtTheEnd(cell1.begin(),cell1.end());
3713   conn2I->pushBackSilent(conn2->getNumberOfTuples());
3714   ret2->setConnectivity(conn2,conn2I,true);
3715   ret2->checkConsistencyLight();
3716   ret2->writeVTK("ret2.vtu");
3717   ret2->orientCorrectlyPolyhedrons();
3718   return ret2;
3719 }
3720
3721 /*!
3722  * Finds cells whose bounding boxes intersect a given plane.
3723  *  \param [in] origin - 3 components of a point defining location of the plane.
3724  *  \param [in] vec - 3 components of a vector normal to the plane. Vector magnitude
3725  *         must be greater than 1e-6.
3726  *  \param [in] eps - half-thickness of the plane.
3727  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids of the found
3728  *         cells. The caller is to delete this array using decrRef() as it is no more
3729  *         needed.
3730  *  \throw If the coordinates array is not set.
3731  *  \throw If the nodal connectivity of cells is not defined.
3732  *  \throw If \a this->getSpaceDimension() != 3.
3733  *  \throw If magnitude of \a vec is less than 1e-6.
3734  *  \sa buildSlice3D()
3735  */
3736 DataArrayInt *MEDCouplingUMesh::getCellIdsCrossingPlane(const double *origin, const double *vec, double eps) const
3737 {
3738   checkFullyDefined();
3739   if(getSpaceDimension()!=3)
3740     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSlice3D works on umeshes with spaceDim equal to 3 !");
3741   double normm=sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
3742   if(normm<1e-6)
3743     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getCellIdsCrossingPlane : parameter 'vec' should have a norm2 greater than 1e-6 !");
3744   double vec2[3];
3745   vec2[0]=vec[1]; vec2[1]=-vec[0]; vec2[2]=0.;//vec2 is the result of cross product of vec with (0,0,1)
3746   double angle=acos(vec[2]/normm);
3747   MCAuto<DataArrayInt> cellIds;
3748   double bbox[6];
3749   if(angle>eps)
3750     {
3751       MCAuto<DataArrayDouble> coo=_coords->deepCopy();
3752       double normm2(sqrt(vec2[0]*vec2[0]+vec2[1]*vec2[1]+vec2[2]*vec2[2]));
3753       if(normm2/normm>1e-6)
3754         DataArrayDouble::Rotate3DAlg(origin,vec2,angle,coo->getNumberOfTuples(),coo->getPointer(),coo->getPointer());
3755       MCAuto<MEDCouplingUMesh> mw=clone(false);//false -> shallow copy
3756       mw->setCoords(coo);
3757       mw->getBoundingBox(bbox);
3758       bbox[4]=origin[2]-eps; bbox[5]=origin[2]+eps;
3759       cellIds=mw->getCellsInBoundingBox(bbox,eps);
3760     }
3761   else
3762     {
3763       getBoundingBox(bbox);
3764       bbox[4]=origin[2]-eps; bbox[5]=origin[2]+eps;
3765       cellIds=getCellsInBoundingBox(bbox,eps);
3766     }
3767   return cellIds.retn();
3768 }
3769
3770 /*!
3771  * This method checks that \a this is a contiguous mesh. The user is expected to call this method on a mesh with meshdim==1.
3772  * If not an exception will thrown. If this is an empty mesh with no cell an exception will be thrown too.
3773  * No consideration of coordinate is done by this method.
3774  * A 1D mesh is said contiguous if : a cell i with nodal connectivity (k,p) the cell i+1 the nodal connectivity should be (p,m)
3775  * If not false is returned. In case that false is returned a call to MEDCoupling::MEDCouplingUMesh::mergeNodes could be usefull.
3776  */
3777 bool MEDCouplingUMesh::isContiguous1D() const
3778 {
3779   if(getMeshDimension()!=1)
3780     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::isContiguous1D : this method has a sense only for 1D mesh !");
3781   int nbCells=getNumberOfCells();
3782   if(nbCells<1)
3783     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::isContiguous1D : this method has a sense for non empty mesh !");
3784   const int *connI(_nodal_connec_index->begin()),*conn(_nodal_connec->begin());
3785   int ref=conn[connI[0]+2];
3786   for(int i=1;i<nbCells;i++)
3787     {
3788       if(conn[connI[i]+1]!=ref)
3789         return false;
3790       ref=conn[connI[i]+2];
3791     }
3792   return true;
3793 }
3794
3795 /*!
3796  * This method is only callable on mesh with meshdim == 1 containing only SEG2 and spaceDim==3.
3797  * This method projects this on the 3D line defined by (pt,v). This methods first checks that all SEG2 are along v vector.
3798  * \param pt reference point of the line
3799  * \param v normalized director vector of the line
3800  * \param eps max precision before throwing an exception
3801  * \param res output of size this->getNumberOfCells
3802  */
3803 void MEDCouplingUMesh::project1D(const double *pt, const double *v, double eps, double *res) const
3804 {
3805   if(getMeshDimension()!=1)
3806     throw INTERP_KERNEL::Exception("Expected a umesh with meshDim == 1 for project1D !");
3807   if(_types.size()!=1 || *(_types.begin())!=INTERP_KERNEL::NORM_SEG2)
3808     throw INTERP_KERNEL::Exception("Expected a umesh with only NORM_SEG2 type of elements for project1D !");
3809   if(getSpaceDimension()!=3)
3810     throw INTERP_KERNEL::Exception("Expected a umesh with spaceDim==3 for project1D !");
3811   MCAuto<MEDCouplingFieldDouble> f=buildDirectionVectorField();
3812   const double *fPtr=f->getArray()->getConstPointer();
3813   double tmp[3];
3814   for(int i=0;i<getNumberOfCells();i++)
3815     {
3816       const double *tmp1=fPtr+3*i;
3817       tmp[0]=tmp1[1]*v[2]-tmp1[2]*v[1];
3818       tmp[1]=tmp1[2]*v[0]-tmp1[0]*v[2];
3819       tmp[2]=tmp1[0]*v[1]-tmp1[1]*v[0];
3820       double n1=INTERP_KERNEL::norm<3>(tmp);
3821       n1/=INTERP_KERNEL::norm<3>(tmp1);
3822       if(n1>eps)
3823         throw INTERP_KERNEL::Exception("UMesh::Projection 1D failed !");
3824     }
3825   const double *coo=getCoords()->getConstPointer();
3826   for(int i=0;i<getNumberOfNodes();i++)
3827     {
3828       std::transform(coo+i*3,coo+i*3+3,pt,tmp,std::minus<double>());
3829       std::transform(tmp,tmp+3,v,tmp,std::multiplies<double>());
3830       res[i]=std::accumulate(tmp,tmp+3,0.);
3831     }
3832 }
3833
3834 /*!
3835  * This method computes the distance from a point \a pt to \a this and the first \a cellId in \a this corresponding to the returned distance. 
3836  * \a this is expected to be a mesh so that its space dimension is equal to its
3837  * mesh dimension + 1. Furthermore only mesh dimension 1 and 2 are supported for the moment.
3838  * Distance from \a ptBg to \a ptEnd is expected to be equal to the space dimension. \a this is also expected to be fully defined (connectivity and coordinates).
3839  *
3840  * WARNING, if there is some orphan nodes in \a this (nodes not fetched by any cells in \a this ( see MEDCouplingUMesh::zipCoords ) ) these nodes will ** not ** been taken
3841  * into account in this method. Only cells and nodes lying on them are considered in the algorithm (even if one of these orphan nodes is closer than returned distance).
3842  * A user that needs to consider orphan nodes should invoke DataArrayDouble::minimalDistanceTo method on the coordinates array of \a this.
3843  *
3844  * So this method is more accurate (so, more costly) than simply searching for the closest point in \a this.
3845  * If only this information is enough for you simply call \c getCoords()->distanceToTuple on \a this.
3846  *
3847  * \param [in] ptBg the start pointer (included) of the coordinates of the point
3848  * \param [in] ptEnd the end pointer (not included) of the coordinates of the point
3849  * \param [out] cellId that corresponds to minimal distance. If the closer node is not linked to any cell in \a this -1 is returned.
3850  * \return the positive value of the distance.
3851  * \throw if distance from \a ptBg to \a ptEnd is not equal to the space dimension. An exception is also thrown if mesh dimension of \a this is not equal to space
3852  * dimension - 1.
3853  * \sa DataArrayDouble::distanceToTuple, MEDCouplingUMesh::distanceToPoints
3854  */
3855 double MEDCouplingUMesh::distanceToPoint(const double *ptBg, const double *ptEnd, int& cellId) const
3856 {
3857   int meshDim=getMeshDimension(),spaceDim=getSpaceDimension();
3858   if(meshDim!=spaceDim-1)
3859     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoint works only for spaceDim=meshDim+1 !");
3860   if(meshDim!=2 && meshDim!=1)
3861     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoint : only mesh dimension 2 and 1 are implemented !");
3862   checkFullyDefined();
3863   if((int)std::distance(ptBg,ptEnd)!=spaceDim)
3864     { std::ostringstream oss; oss << "MEDCouplingUMesh::distanceToPoint : input point has to have dimension equal to the space dimension of this (" << spaceDim << ") !"; throw INTERP_KERNEL::Exception(oss.str()); }
3865   DataArrayInt *ret1=0;
3866   MCAuto<DataArrayDouble> pts=DataArrayDouble::New(); pts->useArray(ptBg,false,C_DEALLOC,1,spaceDim);
3867   MCAuto<DataArrayDouble> ret0=distanceToPoints(pts,ret1);
3868   MCAuto<DataArrayInt> ret1Safe(ret1);
3869   cellId=*ret1Safe->begin();
3870   return *ret0->begin();
3871 }
3872
3873 /*!
3874  * This method computes the distance from each point of points serie \a pts (stored in a DataArrayDouble in which each tuple represents a point)
3875  *  to \a this  and the first \a cellId in \a this corresponding to the returned distance. 
3876  * WARNING, if there is some orphan nodes in \a this (nodes not fetched by any cells in \a this ( see MEDCouplingUMesh::zipCoords ) ) these nodes will ** not ** been taken
3877  * into account in this method. Only cells and nodes lying on them are considered in the algorithm (even if one of these orphan nodes is closer than returned distance).
3878  * A user that needs to consider orphan nodes should invoke DataArrayDouble::minimalDistanceTo method on the coordinates array of \a this.
3879  * 
3880  * \a this is expected to be a mesh so that its space dimension is equal to its
3881  * mesh dimension + 1. Furthermore only mesh dimension 1 and 2 are supported for the moment.
3882  * Number of components of \a pts is expected to be equal to the space dimension. \a this is also expected to be fully defined (connectivity and coordinates).
3883  *
3884  * So this method is more accurate (so, more costly) than simply searching for each point in \a pts the closest point in \a this.
3885  * If only this information is enough for you simply call \c getCoords()->distanceToTuple on \a this.
3886  *
3887  * \param [in] pts the list of points in which each tuple represents a point
3888  * \param [out] cellIds a newly allocated object that tells for each point in \a pts the first cell id in \a this that minimizes the distance.
3889  * \return a newly allocated object to be dealed by the caller that tells for each point in \a pts the distance to \a this.
3890  * \throw if number of components of \a pts is not equal to the space dimension.
3891  * \throw if mesh dimension of \a this is not equal to space dimension - 1.
3892  * \sa DataArrayDouble::distanceToTuple, MEDCouplingUMesh::distanceToPoint
3893  */
3894 DataArrayDouble *MEDCouplingUMesh::distanceToPoints(const DataArrayDouble *pts, DataArrayInt *& cellIds) const
3895 {
3896   if(!pts)
3897     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : input points pointer is NULL !");
3898   pts->checkAllocated();
3899   int meshDim=getMeshDimension(),spaceDim=getSpaceDimension();
3900   if(meshDim!=spaceDim-1)
3901     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints works only for spaceDim=meshDim+1 !");
3902   if(meshDim!=2 && meshDim!=1)
3903     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : only mesh dimension 2 and 1 are implemented !");
3904   if(pts->getNumberOfComponents()!=spaceDim)
3905     {
3906       std::ostringstream oss; oss << "MEDCouplingUMesh::distanceToPoints : input pts DataArrayDouble has " << pts->getNumberOfComponents() << " components whereas it should be equal to " << spaceDim << " (mesh spaceDimension) !";
3907       throw INTERP_KERNEL::Exception(oss.str());
3908     }
3909   checkFullyDefined();
3910   int nbCells=getNumberOfCells();
3911   if(nbCells==0)
3912     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : no cells in this !");
3913   int nbOfPts=pts->getNumberOfTuples();
3914   MCAuto<DataArrayDouble> ret0=DataArrayDouble::New(); ret0->alloc(nbOfPts,1);
3915   MCAuto<DataArrayInt> ret1=DataArrayInt::New(); ret1->alloc(nbOfPts,1);
3916   const int *nc=_nodal_connec->begin(),*ncI=_nodal_connec_index->begin(); const double *coords=_coords->begin();
3917   double *ret0Ptr=ret0->getPointer(); int *ret1Ptr=ret1->getPointer(); const double *ptsPtr=pts->begin();
3918   MCAuto<DataArrayDouble> bboxArr(getBoundingBoxForBBTree());
3919   const double *bbox(bboxArr->begin());
3920   switch(spaceDim)
3921   {
3922     case 3:
3923       {
3924         BBTreeDst<3> myTree(bbox,0,0,nbCells);
3925         for(int i=0;i<nbOfPts;i++,ret0Ptr++,ret1Ptr++,ptsPtr+=3)
3926           {
3927             double x=std::numeric_limits<double>::max();
3928             std::vector<int> elems;
3929             myTree.getMinDistanceOfMax(ptsPtr,x);
3930             myTree.getElemsWhoseMinDistanceToPtSmallerThan(ptsPtr,x,elems);
3931             DistanceToPoint3DSurfAlg(ptsPtr,&elems[0],&elems[0]+elems.size(),coords,nc,ncI,*ret0Ptr,*ret1Ptr);
3932           }
3933         break;
3934       }
3935     case 2:
3936       {
3937         BBTreeDst<2> myTree(bbox,0,0,nbCells);
3938         for(int i=0;i<nbOfPts;i++,ret0Ptr++,ret1Ptr++,ptsPtr+=2)
3939           {
3940             double x=std::numeric_limits<double>::max();
3941             std::vector<int> elems;
3942             myTree.getMinDistanceOfMax(ptsPtr,x);
3943             myTree.getElemsWhoseMinDistanceToPtSmallerThan(ptsPtr,x,elems);
3944             DistanceToPoint2DCurveAlg(ptsPtr,&elems[0],&elems[0]+elems.size(),coords,nc,ncI,*ret0Ptr,*ret1Ptr);
3945           }
3946         break;
3947       }
3948     default:
3949       throw INTERP_KERNEL::Exception("MEDCouplingUMesh::distanceToPoints : only spacedim 2 and 3 supported !");
3950   }
3951   cellIds=ret1.retn();
3952   return ret0.retn();
3953 }
3954
3955 /// @cond INTERNAL
3956
3957 /// @endcond
3958
3959 /*!
3960  * Finds cells in contact with a ball (i.e. a point with precision). 
3961  * For speed reasons, the INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6 and INTERP_KERNEL::NORM_QUAD8 cells are considered as convex cells to detect if a point is IN or OUT.
3962  * If it is not the case, please change their types to INTERP_KERNEL::NORM_POLYGON or INTERP_KERNEL::NORM_QPOLYG before invoking this method.
3963  *
3964  * \warning This method is suitable if the caller intends to evaluate only one
3965  *          point, for more points getCellsContainingPoints() is recommended as it is
3966  *          faster. 
3967  *  \param [in] pos - array of coordinates of the ball central point.
3968  *  \param [in] eps - ball radius.
3969  *  \return int - a smallest id of cells being in contact with the ball, -1 in case
3970  *         if there are no such cells.
3971  *  \throw If the coordinates array is not set.
3972  *  \throw If \a this->getMeshDimension() != \a this->getSpaceDimension().
3973  */
3974 int MEDCouplingUMesh::getCellContainingPoint(const double *pos, double eps) const
3975 {
3976   std::vector<int> elts;
3977   getCellsContainingPoint(pos,eps,elts);
3978   if(elts.empty())
3979     return -1;
3980   return elts.front();
3981 }
3982
3983 /*!
3984  * Finds cells in contact with a ball (i.e. a point with precision).
3985  * For speed reasons, the INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6 and INTERP_KERNEL::NORM_QUAD8 cells are considered as convex cells to detect if a point is IN or OUT.
3986  * If it is not the case, please change their types to INTERP_KERNEL::NORM_POLYGON or INTERP_KERNEL::NORM_QPOLYG before invoking this method.
3987  * \warning This method is suitable if the caller intends to evaluate only one
3988  *          point, for more points getCellsContainingPoints() is recommended as it is
3989  *          faster. 
3990  *  \param [in] pos - array of coordinates of the ball central point.
3991  *  \param [in] eps - ball radius.
3992  *  \param [out] elts - vector returning ids of the found cells. It is cleared
3993  *         before inserting ids.
3994  *  \throw If the coordinates array is not set.
3995  *  \throw If \a this->getMeshDimension() != \a this->getSpaceDimension().
3996  *
3997  *  \if ENABLE_EXAMPLES
3998  *  \ref cpp_mcumesh_getCellsContainingPoint "Here is a C++ example".<br>
3999  *  \ref  py_mcumesh_getCellsContainingPoint "Here is a Python example".
4000  *  \endif
4001  */
4002 void MEDCouplingUMesh::getCellsContainingPoint(const double *pos, double eps, std::vector<int>& elts) const
4003 {
4004   MCAuto<DataArrayInt> eltsUg,eltsIndexUg;
4005   getCellsContainingPoints(pos,1,eps,eltsUg,eltsIndexUg);
4006   elts.clear(); elts.insert(elts.end(),eltsUg->begin(),eltsUg->end());
4007 }
4008
4009 /*!
4010  * Finds cells in contact with several balls (i.e. points with precision).
4011  * This method is an extension of getCellContainingPoint() and
4012  * getCellsContainingPoint() for the case of multiple points.
4013  * For speed reasons, the INTERP_KERNEL::NORM_QUAD4, INTERP_KERNEL::NORM_TRI6 and INTERP_KERNEL::NORM_QUAD8 cells are considered as convex cells to detect if a point is IN or OUT.
4014  * If it is not the case, please change their types to INTERP_KERNEL::NORM_POLYGON or INTERP_KERNEL::NORM_QPOLYG before invoking this method.
4015  *  \param [in] pos - an array of coordinates of points in full interlace mode :
4016  *         X0,Y0,Z0,X1,Y1,Z1,... Size of the array must be \a
4017  *         this->getSpaceDimension() * \a nbOfPoints 
4018  *  \param [in] nbOfPoints - number of points to locate within \a this mesh.
4019  *  \param [in] eps - radius of balls (i.e. the precision).
4020  *  \param [out] elts - vector returning ids of found cells.
4021  *  \param [out] eltsIndex - an array, of length \a nbOfPoints + 1,
4022  *         dividing cell ids in \a elts into groups each referring to one
4023  *         point. Its every element (except the last one) is an index pointing to the
4024  *         first id of a group of cells. For example cells in contact with the *i*-th
4025  *         point are described by following range of indices:
4026  *         [ \a eltsIndex[ *i* ], \a eltsIndex[ *i*+1 ] ) and the cell ids are
4027  *         \a elts[ \a eltsIndex[ *i* ]], \a elts[ \a eltsIndex[ *i* ] + 1 ], ...
4028  *         Number of cells in contact with the *i*-th point is
4029  *         \a eltsIndex[ *i*+1 ] - \a eltsIndex[ *i* ].
4030  *  \throw If the coordinates array is not set.
4031  *  \throw If \a this->getMeshDimension() != \a this->getSpaceDimension().
4032  *
4033  *  \if ENABLE_EXAMPLES
4034  *  \ref cpp_mcumesh_getCellsContainingPoints "Here is a C++ example".<br>
4035  *  \ref  py_mcumesh_getCellsContainingPoints "Here is a Python example".
4036  *  \endif
4037  */
4038 void MEDCouplingUMesh::getCellsContainingPoints(const double *pos, int nbOfPoints, double eps,
4039                                                 MCAuto<DataArrayInt>& elts, MCAuto<DataArrayInt>& eltsIndex) const
4040 {
4041   int spaceDim=getSpaceDimension();
4042   int mDim=getMeshDimension();
4043   if(spaceDim==3)
4044     {
4045       if(mDim==3)
4046         {
4047           const double *coords=_coords->getConstPointer();
4048           getCellsContainingPointsAlg<3>(coords,pos,nbOfPoints,eps,elts,eltsIndex);
4049         }
4050       /*else if(mDim==2)
4051         {
4052
4053         }*/
4054       else
4055         throw INTERP_KERNEL::Exception("For spaceDim==3 only meshDim==3 implemented for getelementscontainingpoints !");
4056     }
4057   else if(spaceDim==2)
4058     {
4059       if(mDim==2)
4060         {
4061           const double *coords=_coords->getConstPointer();
4062           getCellsContainingPointsAlg<2>(coords,pos,nbOfPoints,eps,elts,eltsIndex);
4063         }
4064       else
4065         throw INTERP_KERNEL::Exception("For spaceDim==2 only meshDim==2 implemented for getelementscontainingpoints !");
4066     }
4067   else if(spaceDim==1)
4068     {
4069       if(mDim==1)
4070         {
4071           const double *coords=_coords->getConstPointer();
4072           getCellsContainingPointsAlg<1>(coords,pos,nbOfPoints,eps,elts,eltsIndex);
4073         }
4074       else
4075         throw INTERP_KERNEL::Exception("For spaceDim==1 only meshDim==1 implemented for getelementscontainingpoints !");
4076     }
4077   else
4078     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getCellsContainingPoints : not managed for mdim not in [1,2,3] !");
4079 }
4080
4081 /*!
4082  * Finds butterfly cells in \a this mesh. A 2D cell is considered to be butterfly if at
4083  * least two its edges intersect each other anywhere except their extremities. An
4084  * INTERP_KERNEL::NORM_NORI3 cell can \b not be butterfly.
4085  *  \param [in,out] cells - a vector returning ids of the found cells. It is not
4086  *         cleared before filling in.
4087  *  \param [in] eps - precision.
4088  *  \throw If \a this->getMeshDimension() != 2.
4089  *  \throw If \a this->getSpaceDimension() != 2 && \a this->getSpaceDimension() != 3.
4090  */
4091 void MEDCouplingUMesh::checkButterflyCells(std::vector<int>& cells, double eps) const
4092 {
4093   const char msg[]="Butterfly detection work only for 2D cells with spaceDim==2 or 3!";
4094   if(getMeshDimension()!=2)
4095     throw INTERP_KERNEL::Exception(msg);
4096   int spaceDim=getSpaceDimension();
4097   if(spaceDim!=2 && spaceDim!=3)
4098     throw INTERP_KERNEL::Exception(msg);
4099   const int *conn=_nodal_connec->getConstPointer();
4100   const int *connI=_nodal_connec_index->getConstPointer();
4101   int nbOfCells=getNumberOfCells();
4102   std::vector<double> cell2DinS2;
4103   for(int i=0;i<nbOfCells;i++)
4104     {
4105       int offset=connI[i];
4106       int nbOfNodesForCell=connI[i+1]-offset-1;
4107       if(nbOfNodesForCell<=3)
4108         continue;
4109       bool isQuad=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[offset]).isQuadratic();
4110       project2DCellOnXY(conn+offset+1,conn+connI[i+1],cell2DinS2);
4111       if(isButterfly2DCell(cell2DinS2,isQuad,eps))
4112         cells.push_back(i);
4113       cell2DinS2.clear();
4114     }
4115 }
4116
4117 /*!
4118  * This method is typically requested to unbutterfly 2D linear cells in \b this.
4119  *
4120  * This method expects that space dimension is equal to 2 and mesh dimension is equal to 2 too. If it is not the case an INTERP_KERNEL::Exception will be thrown.
4121  * This method works only for linear 2D cells. If there is any of non linear cells (INTERP_KERNEL::NORM_QUAD8 for example) an INTERP_KERNEL::Exception will be thrown too.
4122  * 
4123  * For each 2D linear cell in \b this, this method builds the convex envelop (or the convex hull) of the current cell.
4124  * This convex envelop is computed using Jarvis march algorithm.
4125  * The coordinates and the number of cells of \b this remain unchanged on invocation of this method.
4126  * Only connectivity of some cells could be modified if those cells were not representing a convex envelop. If a cell already equals its convex envelop (regardless orientation)
4127  * its connectivity will remain unchanged. If the computation leads to a modification of nodal connectivity of a cell its geometric type will be modified to INTERP_KERNEL::NORM_POLYGON.
4128  *
4129  * \return a newly allocated array containing cellIds that have been modified if any. If no cells have been impacted by this method NULL is returned.
4130  * \sa MEDCouplingUMesh::colinearize2D
4131  */
4132 DataArrayInt *MEDCouplingUMesh::convexEnvelop2D()
4133 {
4134   if(getMeshDimension()!=2 || getSpaceDimension()!=2)
4135     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convexEnvelop2D  works only for meshDim=2 and spaceDim=2 !");
4136   checkFullyDefined();
4137   const double *coords=getCoords()->getConstPointer();
4138   int nbOfCells=getNumberOfCells();
4139   MCAuto<DataArrayInt> nodalConnecIndexOut=DataArrayInt::New();
4140   nodalConnecIndexOut->alloc(nbOfCells+1,1);
4141   MCAuto<DataArrayInt> nodalConnecOut(DataArrayInt::New());
4142   int *workIndexOut=nodalConnecIndexOut->getPointer();
4143   *workIndexOut=0;
4144   const int *nodalConnecIn=_nodal_connec->getConstPointer();
4145   const int *nodalConnecIndexIn=_nodal_connec_index->getConstPointer();
4146   std::set<INTERP_KERNEL::NormalizedCellType> types;
4147   MCAuto<DataArrayInt> isChanged(DataArrayInt::New());
4148   isChanged->alloc(0,1);
4149   for(int i=0;i<nbOfCells;i++,workIndexOut++)
4150     {
4151       int pos=nodalConnecOut->getNumberOfTuples();
4152       if(BuildConvexEnvelopOf2DCellJarvis(coords,nodalConnecIn+nodalConnecIndexIn[i],nodalConnecIn+nodalConnecIndexIn[i+1],nodalConnecOut))
4153         isChanged->pushBackSilent(i);
4154       types.insert((INTERP_KERNEL::NormalizedCellType)nodalConnecOut->getIJ(pos,0));
4155       workIndexOut[1]=nodalConnecOut->getNumberOfTuples();
4156     }
4157   if(isChanged->empty())
4158     return 0;
4159   setConnectivity(nodalConnecOut,nodalConnecIndexOut,false);
4160   _types=types;
4161   return isChanged.retn();
4162 }
4163
4164 /*!
4165  * This method is \b NOT const because it can modify \a this.
4166  * \a this is expected to be an unstructured mesh with meshDim==2 and spaceDim==3. If not an exception will be thrown.
4167  * \param mesh1D is an unstructured mesh with MeshDim==1 and spaceDim==3. If not an exception will be thrown.
4168  * \param policy specifies the type of extrusion chosen:
4169  *   - \b 0 for translation only (most simple): the cells of the 1D mesh represent the vectors along which the 2D mesh
4170  *   will be repeated to build each level
4171  *   - \b 1 for translation and rotation: the translation is done as above. For each level, an arc of circle is fitted on
4172  *   the 3 preceding points of the 1D mesh. The center of the arc is the center of rotation for each level, the rotation is done
4173  *   along an axis normal to the plane containing the arc, and finally the angle of rotation is defined by the first two points on the
4174  *   arc.
4175  * \return an unstructured mesh with meshDim==3 and spaceDim==3. The returned mesh has the same coords than \a this.  
4176  */
4177 MEDCouplingUMesh *MEDCouplingUMesh::buildExtrudedMesh(const MEDCouplingUMesh *mesh1D, int policy)
4178 {
4179   checkFullyDefined();
4180   mesh1D->checkFullyDefined();
4181   if(!mesh1D->isContiguous1D())
4182     throw INTERP_KERNEL::Exception("buildExtrudedMesh : 1D mesh passed in parameter is not contiguous !");
4183   if(getSpaceDimension()!=mesh1D->getSpaceDimension())
4184     throw INTERP_KERNEL::Exception("Invalid call to buildExtrudedMesh this and mesh1D must have same space dimension !");
4185   if((getMeshDimension()!=2 || getSpaceDimension()!=3) && (getMeshDimension()!=1 || getSpaceDimension()!=2))
4186     throw INTERP_KERNEL::Exception("Invalid 'this' for buildExtrudedMesh method : must be (meshDim==2 and spaceDim==3) or (meshDim==1 and spaceDim==2) !");
4187   if(mesh1D->getMeshDimension()!=1)
4188     throw INTERP_KERNEL::Exception("Invalid 'mesh1D' for buildExtrudedMesh method : must be meshDim==1 !");
4189   bool isQuad=false;
4190   if(isPresenceOfQuadratic())
4191     {
4192       if(mesh1D->isFullyQuadratic())
4193         isQuad=true;
4194       else
4195         throw INTERP_KERNEL::Exception("Invalid 2D mesh and 1D mesh because 2D mesh has quadratic cells and 1D is not fully quadratic !");
4196     }
4197   int oldNbOfNodes(getNumberOfNodes());
4198   MCAuto<DataArrayDouble> newCoords;
4199   switch(policy)
4200   {
4201     case 0:
4202       {
4203         newCoords=fillExtCoordsUsingTranslation(mesh1D,isQuad);
4204         break;
4205       }
4206     case 1:
4207       {
4208         newCoords=fillExtCoordsUsingTranslAndAutoRotation(mesh1D,isQuad);
4209         break;
4210       }
4211     default:
4212       throw INTERP_KERNEL::Exception("Not implemented extrusion policy : must be in (0) !");
4213   }
4214   setCoords(newCoords);
4215   MCAuto<MEDCouplingUMesh> ret(buildExtrudedMeshFromThisLowLev(oldNbOfNodes,isQuad));
4216   updateTime();
4217   return ret.retn();
4218 }
4219
4220
4221 /*!
4222  * Checks if \a this mesh is constituted by only quadratic cells.
4223  *  \return bool - \c true if there are only quadratic cells in \a this mesh.
4224  *  \throw If the coordinates array is not set.
4225  *  \throw If the nodal connectivity of cells is not defined.
4226  */
4227 bool MEDCouplingUMesh::isFullyQuadratic() const
4228 {
4229   checkFullyDefined();
4230   bool ret=true;
4231   int nbOfCells=getNumberOfCells();
4232   for(int i=0;i<nbOfCells && ret;i++)
4233     {
4234       INTERP_KERNEL::NormalizedCellType type=getTypeOfCell(i);
4235       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
4236       ret=cm.isQuadratic();
4237     }
4238   return ret;
4239 }
4240
4241 /*!
4242  * Checks if \a this mesh includes any quadratic cell.
4243  *  \return bool - \c true if there is at least one quadratic cells in \a this mesh.
4244  *  \throw If the coordinates array is not set.
4245  *  \throw If the nodal connectivity of cells is not defined.
4246  */
4247 bool MEDCouplingUMesh::isPresenceOfQuadratic() const
4248 {
4249   checkFullyDefined();
4250   bool ret=false;
4251   int nbOfCells=getNumberOfCells();
4252   for(int i=0;i<nbOfCells && !ret;i++)
4253     {
4254       INTERP_KERNEL::NormalizedCellType type=getTypeOfCell(i);
4255       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
4256       ret=cm.isQuadratic();
4257     }
4258   return ret;
4259 }
4260
4261 /*!
4262  * Converts all quadratic cells to linear ones. If there are no quadratic cells in \a
4263  * this mesh, it remains unchanged.
4264  *  \throw If the coordinates array is not set.
4265  *  \throw If the nodal connectivity of cells is not defined.
4266  */
4267 void MEDCouplingUMesh::convertQuadraticCellsToLinear()
4268 {
4269   checkFullyDefined();
4270   int nbOfCells(getNumberOfCells());
4271   int delta=0;
4272   const int *iciptr=_nodal_connec_index->begin();
4273   for(int i=0;i<nbOfCells;i++)
4274     {
4275       INTERP_KERNEL::NormalizedCellType type=getTypeOfCell(i);
4276       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
4277       if(cm.isQuadratic())
4278         {
4279           INTERP_KERNEL::NormalizedCellType typel=cm.getLinearType();
4280           const INTERP_KERNEL::CellModel& cml=INTERP_KERNEL::CellModel::GetCellModel(typel);
4281           if(!cml.isDynamic())
4282             delta+=cm.getNumberOfNodes()-cml.getNumberOfNodes();
4283           else
4284             delta+=(iciptr[i+1]-iciptr[i]-1)/2;
4285         }
4286     }
4287   if(delta==0)
4288     return ;
4289   MCAuto<DataArrayInt> newConn(DataArrayInt::New()),newConnI(DataArrayInt::New());
4290   const int *icptr(_nodal_connec->begin());
4291   newConn->alloc(getNodalConnectivityArrayLen()-delta,1);
4292   newConnI->alloc(nbOfCells+1,1);
4293   int *ocptr(newConn->getPointer()),*ociptr(newConnI->getPointer());
4294   *ociptr=0;
4295   _types.clear();
4296   for(int i=0;i<nbOfCells;i++,ociptr++)
4297     {
4298       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)icptr[iciptr[i]];
4299       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(type);
4300       if(!cm.isQuadratic())
4301         {
4302           _types.insert(type);
4303           ocptr=std::copy(icptr+iciptr[i],icptr+iciptr[i+1],ocptr);
4304           ociptr[1]=ociptr[0]+iciptr[i+1]-iciptr[i];
4305         }
4306       else
4307         {
4308           INTERP_KERNEL::NormalizedCellType typel=cm.getLinearType();
4309           _types.insert(typel);
4310           const INTERP_KERNEL::CellModel& cml=INTERP_KERNEL::CellModel::GetCellModel(typel);
4311           int newNbOfNodes=cml.getNumberOfNodes();
4312           if(cml.isDynamic())
4313             newNbOfNodes=(iciptr[i+1]-iciptr[i]-1)/2;
4314           *ocptr++=(int)typel;
4315           ocptr=std::copy(icptr+iciptr[i]+1,icptr+iciptr[i]+newNbOfNodes+1,ocptr);
4316           ociptr[1]=ociptr[0]+newNbOfNodes+1;
4317         }
4318     }
4319   setConnectivity(newConn,newConnI,false);
4320 }
4321
4322 /*!
4323  * This method converts all linear cell in \a this to quadratic one.
4324  * Contrary to MEDCouplingUMesh::convertQuadraticCellsToLinear method, here it is needed to specify the target
4325  * type of cells expected. For example INTERP_KERNEL::NORM_TRI3 can be converted to INTERP_KERNEL::NORM_TRI6 if \a conversionType is equal to 0 (the default)
4326  * or to INTERP_KERNEL::NORM_TRI7 if \a conversionType is equal to 1. All non linear cells and polyhedron in \a this are let untouched.
4327  * Contrary to MEDCouplingUMesh::convertQuadraticCellsToLinear method, the coordinates in \a this can be become bigger. All created nodes will be put at the
4328  * end of the existing coordinates.
4329  * 
4330  * \param [in] conversionType specifies the type of conversion expected. Only 0 (default) and 1 are supported presently. 0 those that creates the 'most' simple
4331  *             corresponding quadratic cells. 1 is those creating the 'most' complex.
4332  * \return a newly created DataArrayInt instance that the caller should deal with containing cell ids of converted cells.
4333  * 
4334  * \throw if \a this is not fully defined. It throws too if \a conversionType is not in [0,1].
4335  *
4336  * \sa MEDCouplingUMesh::convertQuadraticCellsToLinear
4337  */
4338 DataArrayInt *MEDCouplingUMesh::convertLinearCellsToQuadratic(int conversionType)
4339 {
4340   DataArrayInt *conn=0,*connI=0;
4341   DataArrayDouble *coords=0;
4342   std::set<INTERP_KERNEL::NormalizedCellType> types;
4343   checkFullyDefined();
4344   MCAuto<DataArrayInt> ret,connSafe,connISafe;
4345   MCAuto<DataArrayDouble> coordsSafe;
4346   int meshDim=getMeshDimension();
4347   switch(conversionType)
4348   {
4349     case 0:
4350       switch(meshDim)
4351       {
4352         case 1:
4353           ret=convertLinearCellsToQuadratic1D0(conn,connI,coords,types);
4354           connSafe=conn; connISafe=connI; coordsSafe=coords;
4355           break;
4356         case 2:
4357           ret=convertLinearCellsToQuadratic2D0(conn,connI,coords,types);
4358           connSafe=conn; connISafe=connI; coordsSafe=coords;
4359           break;
4360         case 3:
4361           ret=convertLinearCellsToQuadratic3D0(conn,connI,coords,types);
4362           connSafe=conn; connISafe=connI; coordsSafe=coords;
4363           break;
4364         default:
4365           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertLinearCellsToQuadratic : conversion of type 0 mesh dimensions available are [1,2,3] !");
4366       }
4367       break;
4368         case 1:
4369           {
4370             switch(meshDim)
4371             {
4372               case 1:
4373                 ret=convertLinearCellsToQuadratic1D0(conn,connI,coords,types);//it is not a bug. In 1D policy 0 and 1 are equals
4374                 connSafe=conn; connISafe=connI; coordsSafe=coords;
4375                 break;
4376               case 2:
4377                 ret=convertLinearCellsToQuadratic2D1(conn,connI,coords,types);
4378                 connSafe=conn; connISafe=connI; coordsSafe=coords;
4379                 break;
4380               case 3:
4381                 ret=convertLinearCellsToQuadratic3D1(conn,connI,coords,types);
4382                 connSafe=conn; connISafe=connI; coordsSafe=coords;
4383                 break;
4384               default:
4385                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertLinearCellsToQuadratic : conversion of type 1 mesh dimensions available are [1,2,3] !");
4386             }
4387             break;
4388           }
4389         default:
4390           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertLinearCellsToQuadratic : conversion type available are 0 (default, the simplest) and 1 (the most complex) !");
4391   }
4392   setConnectivity(connSafe,connISafe,false);
4393   _types=types;
4394   setCoords(coordsSafe);
4395   return ret.retn();
4396 }
4397
4398 /*!
4399  * Tessellates \a this 2D mesh by dividing not straight edges of quadratic faces,
4400  * so that the number of cells remains the same. Quadratic faces are converted to
4401  * polygons. This method works only for 2D meshes in
4402  * 2D space. If no cells are quadratic (INTERP_KERNEL::NORM_QUAD8,
4403  * INTERP_KERNEL::NORM_TRI6, INTERP_KERNEL::NORM_QPOLYG ), \a this mesh remains unchanged.
4404  * \warning This method can lead to a huge amount of nodes if \a eps is very low.
4405  *  \param [in] eps - specifies the maximal angle (in radians) between 2 sub-edges of
4406  *         a polylinized edge constituting the input polygon.
4407  *  \throw If the coordinates array is not set.
4408  *  \throw If the nodal connectivity of cells is not defined.
4409  *  \throw If \a this->getMeshDimension() != 2.
4410  *  \throw If \a this->getSpaceDimension() != 2.
4411  */
4412 void MEDCouplingUMesh::tessellate2D(double eps)
4413 {
4414   int meshDim(getMeshDimension()),spaceDim(getSpaceDimension());
4415   if(spaceDim!=2)
4416     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tessellate2D : works only with space dimension equal to 2 !");
4417   switch(meshDim)
4418     {
4419     case 1:
4420       return tessellate2DCurveInternal(eps);
4421     case 2:
4422       return tessellate2DInternal(eps);
4423     default:
4424       throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tessellate2D : mesh dimension must be in [1,2] !");
4425     }
4426 }
4427 /*!
4428  * Tessellates \a this 1D mesh in 2D space by dividing not straight quadratic edges.
4429  * \warning This method can lead to a huge amount of nodes if \a eps is very low.
4430  *  \param [in] eps - specifies the maximal angle (in radian) between 2 sub-edges of
4431  *         a sub-divided edge.
4432  *  \throw If the coordinates array is not set.
4433  *  \throw If the nodal connectivity of cells is not defined.
4434  *  \throw If \a this->getMeshDimension() != 1.
4435  *  \throw If \a this->getSpaceDimension() != 2.
4436  */
4437
4438 #if 0
4439 /*!
4440  * This method only works if \a this has spaceDimension equal to 2 and meshDimension also equal to 2.
4441  * This method allows to modify connectivity of cells in \a this that shares some edges in \a edgeIdsToBeSplit.
4442  * The nodes to be added in those 2D cells are defined by the pair of \a  nodeIdsToAdd and \a nodeIdsIndexToAdd.
4443  * Length of \a nodeIdsIndexToAdd is expected to equal to length of \a edgeIdsToBeSplit + 1.
4444  * The node ids in \a nodeIdsToAdd should be valid. Those nodes have to be sorted exactly following exactly the direction of the edge.
4445  * This method can be seen as the opposite method of colinearize2D.
4446  * This method can be lead to create some new nodes if quadratic polygon cells have to be split. In this case the added nodes will be put at the end
4447  * to avoid to modify the numbering of existing nodes.
4448  *
4449  * \param [in] nodeIdsToAdd - the list of node ids to be added (\a nodeIdsIndexToAdd array allows to walk on this array)
4450  * \param [in] nodeIdsIndexToAdd - the entry point of \a nodeIdsToAdd to point to the corresponding nodes to be added.
4451  * \param [in] mesh1Desc - 1st output of buildDescendingConnectivity2 on \a this.
4452  * \param [in] desc - 2nd output of buildDescendingConnectivity2 on \a this.
4453  * \param [in] descI - 3rd output of buildDescendingConnectivity2 on \a this.
4454  * \param [in] revDesc - 4th output of buildDescendingConnectivity2 on \a this.
4455  * \param [in] revDescI - 5th output of buildDescendingConnectivity2 on \a this.
4456  *
4457  * \sa buildDescendingConnectivity2
4458  */
4459 void MEDCouplingUMesh::splitSomeEdgesOf2DMesh(const DataArrayInt *nodeIdsToAdd, const DataArrayInt *nodeIdsIndexToAdd, const DataArrayInt *edgeIdsToBeSplit,
4460                                               const MEDCouplingUMesh *mesh1Desc, const DataArrayInt *desc, const DataArrayInt *descI, const DataArrayInt *revDesc, const DataArrayInt *revDescI)
4461 {
4462   if(!nodeIdsToAdd || !nodeIdsIndexToAdd || !edgeIdsToBeSplit || !mesh1Desc || !desc || !descI || !revDesc || !revDescI)
4463     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitSomeEdgesOf2DMesh : input pointers must be not NULL !");
4464   nodeIdsToAdd->checkAllocated(); nodeIdsIndexToAdd->checkAllocated(); edgeIdsToBeSplit->checkAllocated(); desc->checkAllocated(); descI->checkAllocated(); revDesc->checkAllocated(); revDescI->checkAllocated();
4465   if(getSpaceDimension()!=2 || getMeshDimension()!=2)
4466     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitSomeEdgesOf2DMesh : this must have spacedim=meshdim=2 !");
4467   if(mesh1Desc->getSpaceDimension()!=2 || mesh1Desc->getMeshDimension()!=1)
4468     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitSomeEdgesOf2DMesh : mesh1Desc must be the explosion of this with spaceDim=2 and meshDim = 1 !");
4469   //DataArrayInt *out0(0),*outi0(0);
4470   //MEDCouplingUMesh::ExtractFromIndexedArrays(idsInDesc2DToBeRefined->begin(),idsInDesc2DToBeRefined->end(),dd3,dd4,out0,outi0);
4471   //MCAuto<DataArrayInt> out0s(out0),outi0s(outi0);
4472   //out0s=out0s->buildUnique(); out0s->sort(true);
4473 }
4474 #endif
4475
4476
4477 /*!
4478  * Divides every cell of \a this mesh into simplices (triangles in 2D and tetrahedra in 3D).
4479  * In addition, returns an array mapping new cells to old ones. <br>
4480  * This method typically increases the number of cells in \a this mesh
4481  * but the number of nodes remains \b unchanged.
4482  * That's why the 3D splitting policies
4483  * INTERP_KERNEL::GENERAL_24 and INTERP_KERNEL::GENERAL_48 are not available here.
4484  *  \param [in] policy - specifies a pattern used for splitting.
4485  * The semantic of \a policy is:
4486  * - 0 - to split QUAD4 by cutting it along 0-2 diagonal (for 2D mesh only).
4487  * - 1 - to split QUAD4 by cutting it along 1-3 diagonal (for 2D mesh only).
4488  * - INTERP_KERNEL::PLANAR_FACE_5 - to split HEXA8  into 5 TETRA4 (for 3D mesh only - see INTERP_KERNEL::SplittingPolicy for an image).
4489  * - INTERP_KERNEL::PLANAR_FACE_6 - to split HEXA8  into 6 TETRA4 (for 3D mesh only - see INTERP_KERNEL::SplittingPolicy for an image).
4490  *
4491  *
4492  *  \return DataArrayInt * - a new instance of DataArrayInt holding, for each new cell,
4493  *          an id of old cell producing it. The caller is to delete this array using
4494  *         decrRef() as it is no more needed.
4495  *
4496  *  \throw If \a policy is 0 or 1 and \a this->getMeshDimension() != 2.
4497  *  \throw If \a policy is INTERP_KERNEL::PLANAR_FACE_5 or INTERP_KERNEL::PLANAR_FACE_6
4498  *          and \a this->getMeshDimension() != 3. 
4499  *  \throw If \a policy is not one of the four discussed above.
4500  *  \throw If the nodal connectivity of cells is not defined.
4501  * \sa MEDCouplingUMesh::tetrahedrize, MEDCoupling1SGTUMesh::sortHexa8EachOther
4502  */
4503 DataArrayInt *MEDCouplingUMesh::simplexize(int policy)
4504 {
4505   switch(policy)
4506   {
4507     case 0:
4508       return simplexizePol0();
4509     case 1:
4510       return simplexizePol1();
4511     case (int) INTERP_KERNEL::PLANAR_FACE_5:
4512         return simplexizePlanarFace5();
4513     case (int) INTERP_KERNEL::PLANAR_FACE_6:
4514         return simplexizePlanarFace6();
4515     default:
4516       throw INTERP_KERNEL::Exception("MEDCouplingUMesh::simplexize : unrecognized policy ! Must be :\n  - 0 or 1 (only available for meshdim=2) \n  - PLANAR_FACE_5, PLANAR_FACE_6  (only for meshdim=3)");
4517   }
4518 }
4519
4520 /*!
4521  * Checks if \a this mesh is constituted by simplex cells only. Simplex cells are:
4522  * - 1D: INTERP_KERNEL::NORM_SEG2
4523  * - 2D: INTERP_KERNEL::NORM_TRI3
4524  * - 3D: INTERP_KERNEL::NORM_TETRA4.
4525  *
4526  * This method is useful for users that need to use P1 field services as
4527  * MEDCouplingFieldDouble::getValueOn(), MEDCouplingField::buildMeasureField() etc.
4528  * All these methods need mesh support containing only simplex cells.
4529  *  \return bool - \c true if there are only simplex cells in \a this mesh.
4530  *  \throw If the coordinates array is not set.
4531  *  \throw If the nodal connectivity of cells is not defined.
4532  *  \throw If \a this->getMeshDimension() < 1.
4533  */
4534 bool MEDCouplingUMesh::areOnlySimplexCells() const
4535 {
4536   checkFullyDefined();
4537   int mdim=getMeshDimension();
4538   if(mdim<1 || mdim>3)
4539     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::areOnlySimplexCells : only available with meshes having a meshdim 1, 2 or 3 !");
4540   int nbCells=getNumberOfCells();
4541   const int *conn=_nodal_connec->begin();
4542   const int *connI=_nodal_connec_index->begin();
4543   for(int i=0;i<nbCells;i++)
4544     {
4545       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
4546       if(!cm.isSimplex())
4547         return false;
4548     }
4549   return true;
4550 }
4551
4552
4553
4554 /*!
4555  * Converts degenerated 2D or 3D linear cells of \a this mesh into cells of simpler
4556  * type. For example an INTERP_KERNEL::NORM_QUAD4 cell having only three unique nodes in
4557  * its connectivity is transformed into an INTERP_KERNEL::NORM_TRI3 cell. This method
4558  * does \b not perform geometrical checks and checks only nodal connectivity of cells,
4559  * so it can be useful to call mergeNodes() before calling this method.
4560  *  \throw If \a this->getMeshDimension() <= 1.
4561  *  \throw If the coordinates array is not set.
4562  *  \throw If the nodal connectivity of cells is not defined.
4563  */
4564 void MEDCouplingUMesh::convertDegeneratedCells()
4565 {
4566   checkFullyDefined();
4567   if(getMeshDimension()<=1)
4568     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertDegeneratedCells works on umeshes with meshdim equals to 2 or 3 !");
4569   int nbOfCells=getNumberOfCells();
4570   if(nbOfCells<1)
4571     return ;
4572   int initMeshLgth=getNodalConnectivityArrayLen();
4573   int *conn=_nodal_connec->getPointer();
4574   int *index=_nodal_connec_index->getPointer();
4575   int posOfCurCell=0;
4576   int newPos=0;
4577   int lgthOfCurCell;
4578   for(int i=0;i<nbOfCells;i++)
4579     {
4580       lgthOfCurCell=index[i+1]-posOfCurCell;
4581       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[posOfCurCell];
4582       int newLgth;
4583       INTERP_KERNEL::NormalizedCellType newType=INTERP_KERNEL::CellSimplify::simplifyDegeneratedCell(type,conn+posOfCurCell+1,lgthOfCurCell-1,
4584                                                                                                      conn+newPos+1,newLgth);
4585       conn[newPos]=newType;
4586       newPos+=newLgth+1;
4587       posOfCurCell=index[i+1];
4588       index[i+1]=newPos;
4589     }
4590   if(newPos!=initMeshLgth)
4591     _nodal_connec->reAlloc(newPos);
4592   computeTypes();
4593 }
4594
4595 /*!
4596  * Finds incorrectly oriented cells of this 2D mesh in 3D space.
4597  * A cell is considered to be oriented correctly if an angle between its
4598  * normal vector and a given vector is less than \c PI / \c 2.
4599  *  \param [in] vec - 3 components of the vector specifying the correct orientation of
4600  *         cells. 
4601  *  \param [in] polyOnly - if \c true, only polygons are checked, else, all cells are
4602  *         checked.
4603  *  \param [in,out] cells - a vector returning ids of incorrectly oriented cells. It
4604  *         is not cleared before filling in.
4605  *  \throw If \a this->getMeshDimension() != 2.
4606  *  \throw If \a this->getSpaceDimension() != 3.
4607  *
4608  *  \if ENABLE_EXAMPLES
4609  *  \ref cpp_mcumesh_are2DCellsNotCorrectlyOriented "Here is a C++ example".<br>
4610  *  \ref  py_mcumesh_are2DCellsNotCorrectlyOriented "Here is a Python example".
4611  *  \endif
4612  */
4613 void MEDCouplingUMesh::are2DCellsNotCorrectlyOriented(const double *vec, bool polyOnly, std::vector<int>& cells) const
4614 {
4615   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
4616     throw INTERP_KERNEL::Exception("Invalid mesh to apply are2DCellsNotCorrectlyOriented on it : must be meshDim==2 and spaceDim==3 !");
4617   int nbOfCells=getNumberOfCells();
4618   const int *conn=_nodal_connec->begin();
4619   const int *connI=_nodal_connec_index->begin();
4620   const double *coordsPtr=_coords->begin();
4621   for(int i=0;i<nbOfCells;i++)
4622     {
4623       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
4624       if(!polyOnly || (type==INTERP_KERNEL::NORM_POLYGON || type==INTERP_KERNEL::NORM_QPOLYG))
4625         {
4626           bool isQuadratic=INTERP_KERNEL::CellModel::GetCellModel(type).isQuadratic();
4627           if(!IsPolygonWellOriented(isQuadratic,vec,conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4628             cells.push_back(i);
4629         }
4630     }
4631 }
4632
4633 /*!
4634  * Reverse connectivity of 2D cells whose orientation is not correct. A cell is
4635  * considered to be oriented correctly if an angle between its normal vector and a
4636  * given vector is less than \c PI / \c 2. 
4637  *  \param [in] vec - 3 components of the vector specifying the correct orientation of
4638  *         cells. 
4639  *  \param [in] polyOnly - if \c true, only polygons are checked, else, all cells are
4640  *         checked.
4641  *  \throw If \a this->getMeshDimension() != 2.
4642  *  \throw If \a this->getSpaceDimension() != 3.
4643  *
4644  *  \if ENABLE_EXAMPLES
4645  *  \ref cpp_mcumesh_are2DCellsNotCorrectlyOriented "Here is a C++ example".<br>
4646  *  \ref  py_mcumesh_are2DCellsNotCorrectlyOriented "Here is a Python example".
4647  *  \endif
4648  *
4649  *  \sa changeOrientationOfCells
4650  */
4651 void MEDCouplingUMesh::orientCorrectly2DCells(const double *vec, bool polyOnly)
4652 {
4653   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
4654     throw INTERP_KERNEL::Exception("Invalid mesh to apply orientCorrectly2DCells on it : must be meshDim==2 and spaceDim==3 !");
4655   int nbOfCells(getNumberOfCells()),*conn(_nodal_connec->getPointer());
4656   const int *connI(_nodal_connec_index->begin());
4657   const double *coordsPtr(_coords->begin());
4658   bool isModified(false);
4659   for(int i=0;i<nbOfCells;i++)
4660     {
4661       INTERP_KERNEL::NormalizedCellType type((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
4662       if(!polyOnly || (type==INTERP_KERNEL::NORM_POLYGON || type==INTERP_KERNEL::NORM_QPOLYG))
4663         {
4664           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(type));
4665           bool isQuadratic(cm.isQuadratic());
4666           if(!IsPolygonWellOriented(isQuadratic,vec,conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4667             {
4668               isModified=true;
4669               cm.changeOrientationOf2D(conn+connI[i]+1,(unsigned int)(connI[i+1]-connI[i]-1));
4670             }
4671         }
4672     }
4673   if(isModified)
4674     _nodal_connec->declareAsNew();
4675   updateTime();
4676 }
4677
4678 /*!
4679  * This method change the orientation of cells in \a this without any consideration of coordinates. Only connectivity is impacted.
4680  *
4681  * \sa orientCorrectly2DCells
4682  */
4683 void MEDCouplingUMesh::changeOrientationOfCells()
4684 {
4685   int mdim(getMeshDimension());
4686   if(mdim!=2 && mdim!=1)
4687     throw INTERP_KERNEL::Exception("Invalid mesh to apply changeOrientationOfCells on it : must be meshDim==2 or meshDim==1 !");
4688   int nbOfCells(getNumberOfCells()),*conn(_nodal_connec->getPointer());
4689   const int *connI(_nodal_connec_index->begin());
4690   if(mdim==2)
4691     {//2D
4692       for(int i=0;i<nbOfCells;i++)
4693         {
4694           INTERP_KERNEL::NormalizedCellType type((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
4695           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(type));
4696           cm.changeOrientationOf2D(conn+connI[i]+1,(unsigned int)(connI[i+1]-connI[i]-1));
4697         }
4698     }
4699   else
4700     {//1D
4701       for(int i=0;i<nbOfCells;i++)
4702         {
4703           INTERP_KERNEL::NormalizedCellType type((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
4704           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(type));
4705           cm.changeOrientationOf1D(conn+connI[i]+1,(unsigned int)(connI[i+1]-connI[i]-1));
4706         }
4707     }
4708 }
4709
4710 /*!
4711  * Finds incorrectly oriented polyhedral cells, i.e. polyhedrons having correctly
4712  * oriented facets. The normal vector of the facet should point out of the cell.
4713  *  \param [in,out] cells - a vector returning ids of incorrectly oriented cells. It
4714  *         is not cleared before filling in.
4715  *  \throw If \a this->getMeshDimension() != 3.
4716  *  \throw If \a this->getSpaceDimension() != 3.
4717  *  \throw If the coordinates array is not set.
4718  *  \throw If the nodal connectivity of cells is not defined.
4719  *
4720  *  \if ENABLE_EXAMPLES
4721  *  \ref cpp_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a C++ example".<br>
4722  *  \ref  py_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a Python example".
4723  *  \endif
4724  */
4725 void MEDCouplingUMesh::arePolyhedronsNotCorrectlyOriented(std::vector<int>& cells) const
4726 {
4727   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
4728     throw INTERP_KERNEL::Exception("Invalid mesh to apply arePolyhedronsNotCorrectlyOriented on it : must be meshDim==3 and spaceDim==3 !");
4729   int nbOfCells=getNumberOfCells();
4730   const int *conn=_nodal_connec->begin();
4731   const int *connI=_nodal_connec_index->begin();
4732   const double *coordsPtr=_coords->begin();
4733   for(int i=0;i<nbOfCells;i++)
4734     {
4735       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
4736       if(type==INTERP_KERNEL::NORM_POLYHED)
4737         {
4738           if(!IsPolyhedronWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4739             cells.push_back(i);
4740         }
4741     }
4742 }
4743
4744 /*!
4745  * Tries to fix connectivity of polyhedra, so that normal vector of all facets to point
4746  * out of the cell. 
4747  *  \throw If \a this->getMeshDimension() != 3.
4748  *  \throw If \a this->getSpaceDimension() != 3.
4749  *  \throw If the coordinates array is not set.
4750  *  \throw If the nodal connectivity of cells is not defined.
4751  *  \throw If the reparation fails.
4752  *
4753  *  \if ENABLE_EXAMPLES
4754  *  \ref cpp_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a C++ example".<br>
4755  *  \ref  py_mcumesh_arePolyhedronsNotCorrectlyOriented "Here is a Python example".
4756  *  \endif
4757  * \sa MEDCouplingUMesh::findAndCorrectBadOriented3DCells
4758  */
4759 void MEDCouplingUMesh::orientCorrectlyPolyhedrons()
4760 {
4761   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
4762     throw INTERP_KERNEL::Exception("Invalid mesh to apply orientCorrectlyPolyhedrons on it : must be meshDim==3 and spaceDim==3 !");
4763   int nbOfCells=getNumberOfCells();
4764   int *conn=_nodal_connec->getPointer();
4765   const int *connI=_nodal_connec_index->begin();
4766   const double *coordsPtr=_coords->begin();
4767   for(int i=0;i<nbOfCells;i++)
4768     {
4769       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
4770       if(type==INTERP_KERNEL::NORM_POLYHED)
4771         {
4772           try
4773           {
4774               if(!IsPolyhedronWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4775                 TryToCorrectPolyhedronOrientation(conn+connI[i]+1,conn+connI[i+1],coordsPtr);
4776           }
4777           catch(INTERP_KERNEL::Exception& e)
4778           {
4779               std::ostringstream oss; oss << "Something wrong in polyhedron #" << i << " : " << e.what();
4780               throw INTERP_KERNEL::Exception(oss.str());
4781           }
4782         }
4783     }
4784   updateTime();
4785 }
4786
4787 /*!
4788  * Finds and fixes incorrectly oriented linear extruded volumes (INTERP_KERNEL::NORM_HEXA8,
4789  * INTERP_KERNEL::NORM_PENTA6, INTERP_KERNEL::NORM_HEXGP12 etc) to respect the MED convention
4790  * according to which the first facet of the cell should be oriented to have the normal vector
4791  * pointing out of cell.
4792  *  \return DataArrayInt * - a new instance of DataArrayInt holding ids of fixed
4793  *         cells. The caller is to delete this array using decrRef() as it is no more
4794  *         needed. 
4795  *  \throw If \a this->getMeshDimension() != 3.
4796  *  \throw If \a this->getSpaceDimension() != 3.
4797  *  \throw If the coordinates array is not set.
4798  *  \throw If the nodal connectivity of cells is not defined.
4799  *
4800  *  \if ENABLE_EXAMPLES
4801  *  \ref cpp_mcumesh_findAndCorrectBadOriented3DExtrudedCells "Here is a C++ example".<br>
4802  *  \ref  py_mcumesh_findAndCorrectBadOriented3DExtrudedCells "Here is a Python example".
4803  *  \endif
4804  * \sa MEDCouplingUMesh::findAndCorrectBadOriented3DCells
4805  */
4806 DataArrayInt *MEDCouplingUMesh::findAndCorrectBadOriented3DExtrudedCells()
4807 {
4808   const char msg[]="check3DCellsWellOriented detection works only for 3D cells !";
4809   if(getMeshDimension()!=3)
4810     throw INTERP_KERNEL::Exception(msg);
4811   int spaceDim=getSpaceDimension();
4812   if(spaceDim!=3)
4813     throw INTERP_KERNEL::Exception(msg);
4814   //
4815   int nbOfCells=getNumberOfCells();
4816   int *conn=_nodal_connec->getPointer();
4817   const int *connI=_nodal_connec_index->begin();
4818   const double *coo=getCoords()->begin();
4819   MCAuto<DataArrayInt> cells(DataArrayInt::New()); cells->alloc(0,1);
4820   for(int i=0;i<nbOfCells;i++)
4821     {
4822       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[connI[i]]);
4823       if(cm.isExtruded() && !cm.isDynamic() && !cm.isQuadratic())
4824         {
4825           if(!Is3DExtrudedStaticCellWellOriented(conn+connI[i]+1,conn+connI[i+1],coo))
4826             {
4827               CorrectExtrudedStaticCell(conn+connI[i]+1,conn+connI[i+1]);
4828               cells->pushBackSilent(i);
4829             }
4830         }
4831     }
4832   return cells.retn();
4833 }
4834
4835 /*!
4836  * This method is a faster method to correct orientation of all 3D cells in \a this.
4837  * This method works only if \a this is a 3D mesh, that is to say a mesh with mesh dimension 3 and a space dimension 3.
4838  * This method makes the hypothesis that \a this a coherent that is to say MEDCouplingUMesh::checkConsistency should throw no exception.
4839  * 
4840  * \return a newly allocated int array with one components containing cell ids renumbered to fit the convention of MED (MED file and MEDCoupling)
4841  * \sa MEDCouplingUMesh::orientCorrectlyPolyhedrons, 
4842  */
4843 DataArrayInt *MEDCouplingUMesh::findAndCorrectBadOriented3DCells()
4844 {
4845   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
4846     throw INTERP_KERNEL::Exception("Invalid mesh to apply findAndCorrectBadOriented3DCells on it : must be meshDim==3 and spaceDim==3 !");
4847   int nbOfCells=getNumberOfCells();
4848   int *conn=_nodal_connec->getPointer();
4849   const int *connI=_nodal_connec_index->begin();
4850   const double *coordsPtr=_coords->begin();
4851   MCAuto<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(0,1);
4852   for(int i=0;i<nbOfCells;i++)
4853     {
4854       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)conn[connI[i]];
4855       switch(type)
4856       {
4857         case INTERP_KERNEL::NORM_TETRA4:
4858           {
4859             if(!IsTetra4WellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4860               {
4861                 std::swap(*(conn+connI[i]+2),*(conn+connI[i]+3));
4862                 ret->pushBackSilent(i);
4863               }
4864             break;
4865           }
4866         case INTERP_KERNEL::NORM_PYRA5:
4867           {
4868             if(!IsPyra5WellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4869               {
4870                 std::swap(*(conn+connI[i]+2),*(conn+connI[i]+4));
4871                 ret->pushBackSilent(i);
4872               }
4873             break;
4874           }
4875         case INTERP_KERNEL::NORM_PENTA6:
4876         case INTERP_KERNEL::NORM_HEXA8:
4877         case INTERP_KERNEL::NORM_HEXGP12:
4878           {
4879             if(!Is3DExtrudedStaticCellWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4880               {
4881                 CorrectExtrudedStaticCell(conn+connI[i]+1,conn+connI[i+1]);
4882                 ret->pushBackSilent(i);
4883               }
4884             break;
4885           }
4886         case INTERP_KERNEL::NORM_POLYHED:
4887           {
4888             if(!IsPolyhedronWellOriented(conn+connI[i]+1,conn+connI[i+1],coordsPtr))
4889               {
4890                 TryToCorrectPolyhedronOrientation(conn+connI[i]+1,conn+connI[i+1],coordsPtr);
4891                 ret->pushBackSilent(i);
4892               }
4893             break;
4894           }
4895         default:
4896           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::orientCorrectly3DCells : Your mesh contains type of cell not supported yet ! send mail to anthony.geay@cea.fr to add it !");
4897       }
4898     }
4899   updateTime();
4900   return ret.retn();
4901 }
4902
4903 /*!
4904  * This method has a sense for meshes with spaceDim==3 and meshDim==2.
4905  * If it is not the case an exception will be thrown.
4906  * This method is fast because the first cell of \a this is used to compute the plane.
4907  * \param vec output of size at least 3 used to store the normal vector (with norm equal to Area ) of searched plane.
4908  * \param pos output of size at least 3 used to store a point owned of searched plane.
4909  */
4910 void MEDCouplingUMesh::getFastAveragePlaneOfThis(double *vec, double *pos) const
4911 {
4912   if(getMeshDimension()!=2 || getSpaceDimension()!=3)
4913     throw INTERP_KERNEL::Exception("Invalid mesh to apply getFastAveragePlaneOfThis on it : must be meshDim==2 and spaceDim==3 !");
4914   const int *conn=_nodal_connec->begin();
4915   const int *connI=_nodal_connec_index->begin();
4916   const double *coordsPtr=_coords->begin();
4917   INTERP_KERNEL::areaVectorOfPolygon<int,INTERP_KERNEL::ALL_C_MODE>(conn+1,connI[1]-connI[0]-1,coordsPtr,vec);
4918   std::copy(coordsPtr+3*conn[1],coordsPtr+3*conn[1]+3,pos);
4919 }
4920
4921 /*!
4922  * Creates a new MEDCouplingFieldDouble holding Edge Ratio values of all
4923  * cells. Currently cells of the following types are treated:
4924  * INTERP_KERNEL::NORM_TRI3, INTERP_KERNEL::NORM_QUAD4 and INTERP_KERNEL::NORM_TETRA4.
4925  * For a cell of other type an exception is thrown.
4926  * Space dimension of a 2D mesh can be either 2 or 3.
4927  * The Edge Ratio of a cell \f$t\f$ is: 
4928  *  \f$\frac{|t|_\infty}{|t|_0}\f$,
4929  *  where \f$|t|_\infty\f$ and \f$|t|_0\f$ respectively denote the greatest and
4930  *  the smallest edge lengths of \f$t\f$.
4931  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
4932  *          cells and one time, lying on \a this mesh. The caller is to delete this
4933  *          field using decrRef() as it is no more needed. 
4934  *  \throw If the coordinates array is not set.
4935  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
4936  *  \throw If the connectivity data array has more than one component.
4937  *  \throw If the connectivity data array has a named component.
4938  *  \throw If the connectivity index data array has more than one component.
4939  *  \throw If the connectivity index data array has a named component.
4940  *  \throw If \a this->getMeshDimension() is neither 2 nor 3.
4941  *  \throw If \a this->getSpaceDimension() is neither 2 nor 3.
4942  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
4943  */
4944 MEDCouplingFieldDouble *MEDCouplingUMesh::getEdgeRatioField() const
4945 {
4946   checkConsistencyLight();
4947   int spaceDim=getSpaceDimension();
4948   int meshDim=getMeshDimension();
4949   if(spaceDim!=2 && spaceDim!=3)
4950     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getEdgeRatioField : SpaceDimension must be equal to 2 or 3 !");
4951   if(meshDim!=2 && meshDim!=3)
4952     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getEdgeRatioField : MeshDimension must be equal to 2 or 3 !");
4953   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
4954   ret->setMesh(this);
4955   int nbOfCells=getNumberOfCells();
4956   MCAuto<DataArrayDouble> arr=DataArrayDouble::New();
4957   arr->alloc(nbOfCells,1);
4958   double *pt=arr->getPointer();
4959   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
4960   const int *conn=_nodal_connec->begin();
4961   const int *connI=_nodal_connec_index->begin();
4962   const double *coo=_coords->begin();
4963   double tmp[12];
4964   for(int i=0;i<nbOfCells;i++,pt++)
4965     {
4966       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
4967       switch(t)
4968       {
4969         case INTERP_KERNEL::NORM_TRI3:
4970           {
4971             FillInCompact3DMode(spaceDim,3,conn+1,coo,tmp);
4972             *pt=INTERP_KERNEL::triEdgeRatio(tmp);
4973             break;
4974           }
4975         case INTERP_KERNEL::NORM_QUAD4:
4976           {
4977             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
4978             *pt=INTERP_KERNEL::quadEdgeRatio(tmp);
4979             break;
4980           }
4981         case INTERP_KERNEL::NORM_TETRA4:
4982           {
4983             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
4984             *pt=INTERP_KERNEL::tetraEdgeRatio(tmp);
4985             break;
4986           }
4987         default:
4988           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getEdgeRatioField : A cell with not manged type (NORM_TRI3, NORM_QUAD4 and NORM_TETRA4) has been detected !");
4989       }
4990       conn+=connI[i+1]-connI[i];
4991     }
4992   ret->setName("EdgeRatio");
4993   ret->synchronizeTimeWithSupport();
4994   return ret.retn();
4995 }
4996
4997 /*!
4998  * Creates a new MEDCouplingFieldDouble holding Aspect Ratio values of all
4999  * cells. Currently cells of the following types are treated:
5000  * INTERP_KERNEL::NORM_TRI3, INTERP_KERNEL::NORM_QUAD4 and INTERP_KERNEL::NORM_TETRA4.
5001  * For a cell of other type an exception is thrown.
5002  * Space dimension of a 2D mesh can be either 2 or 3.
5003  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
5004  *          cells and one time, lying on \a this mesh. The caller is to delete this
5005  *          field using decrRef() as it is no more needed. 
5006  *  \throw If the coordinates array is not set.
5007  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
5008  *  \throw If the connectivity data array has more than one component.
5009  *  \throw If the connectivity data array has a named component.
5010  *  \throw If the connectivity index data array has more than one component.
5011  *  \throw If the connectivity index data array has a named component.
5012  *  \throw If \a this->getMeshDimension() is neither 2 nor 3.
5013  *  \throw If \a this->getSpaceDimension() is neither 2 nor 3.
5014  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
5015  */
5016 MEDCouplingFieldDouble *MEDCouplingUMesh::getAspectRatioField() const
5017 {
5018   checkConsistencyLight();
5019   int spaceDim=getSpaceDimension();
5020   int meshDim=getMeshDimension();
5021   if(spaceDim!=2 && spaceDim!=3)
5022     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAspectRatioField : SpaceDimension must be equal to 2 or 3 !");
5023   if(meshDim!=2 && meshDim!=3)
5024     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAspectRatioField : MeshDimension must be equal to 2 or 3 !");
5025   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
5026   ret->setMesh(this);
5027   int nbOfCells=getNumberOfCells();
5028   MCAuto<DataArrayDouble> arr=DataArrayDouble::New();
5029   arr->alloc(nbOfCells,1);
5030   double *pt=arr->getPointer();
5031   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
5032   const int *conn=_nodal_connec->begin();
5033   const int *connI=_nodal_connec_index->begin();
5034   const double *coo=_coords->begin();
5035   double tmp[12];
5036   for(int i=0;i<nbOfCells;i++,pt++)
5037     {
5038       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
5039       switch(t)
5040       {
5041         case INTERP_KERNEL::NORM_TRI3:
5042           {
5043             FillInCompact3DMode(spaceDim,3,conn+1,coo,tmp);
5044             *pt=INTERP_KERNEL::triAspectRatio(tmp);
5045             break;
5046           }
5047         case INTERP_KERNEL::NORM_QUAD4:
5048           {
5049             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
5050             *pt=INTERP_KERNEL::quadAspectRatio(tmp);
5051             break;
5052           }
5053         case INTERP_KERNEL::NORM_TETRA4:
5054           {
5055             FillInCompact3DMode(spaceDim,4,conn+1,coo,tmp);
5056             *pt=INTERP_KERNEL::tetraAspectRatio(tmp);
5057             break;
5058           }
5059         default:
5060           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getAspectRatioField : A cell with not manged type (NORM_TRI3, NORM_QUAD4 and NORM_TETRA4) has been detected !");
5061       }
5062       conn+=connI[i+1]-connI[i];
5063     }
5064   ret->setName("AspectRatio");
5065   ret->synchronizeTimeWithSupport();
5066   return ret.retn();
5067 }
5068
5069 /*!
5070  * Creates a new MEDCouplingFieldDouble holding Warping factor values of all
5071  * cells of \a this 2D mesh in 3D space. It is a measure of the "planarity" of 2D cell
5072  * in 3D space. Currently only cells of the following types are
5073  * treated: INTERP_KERNEL::NORM_QUAD4.
5074  * For a cell of other type an exception is thrown.
5075  * The warp field is computed as follows: let (a,b,c,d) be the points of the quad.
5076  * Defining
5077  * \f$t=\vec{da}\times\vec{ab}\f$,
5078  * \f$u=\vec{ab}\times\vec{bc}\f$
5079  * \f$v=\vec{bc}\times\vec{cd}\f$
5080  * \f$w=\vec{cd}\times\vec{da}\f$, the warp is defined as \f$W^3\f$ with
5081  *  \f[
5082  *     W=min(\frac{t}{|t|}\cdot\frac{v}{|v|}, \frac{u}{|u|}\cdot\frac{w}{|w|})
5083  *  \f]
5084  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
5085  *          cells and one time, lying on \a this mesh. The caller is to delete this
5086  *          field using decrRef() as it is no more needed. 
5087  *  \throw If the coordinates array is not set.
5088  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
5089  *  \throw If the connectivity data array has more than one component.
5090  *  \throw If the connectivity data array has a named component.
5091  *  \throw If the connectivity index data array has more than one component.
5092  *  \throw If the connectivity index data array has a named component.
5093  *  \throw If \a this->getMeshDimension() != 2.
5094  *  \throw If \a this->getSpaceDimension() != 3.
5095  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
5096  */
5097 MEDCouplingFieldDouble *MEDCouplingUMesh::getWarpField() const
5098 {
5099   checkConsistencyLight();
5100   int spaceDim=getSpaceDimension();
5101   int meshDim=getMeshDimension();
5102   if(spaceDim!=3)
5103     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getWarpField : SpaceDimension must be equal to 3 !");
5104   if(meshDim!=2)
5105     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getWarpField : MeshDimension must be equal to 2 !");
5106   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
5107   ret->setMesh(this);
5108   int nbOfCells=getNumberOfCells();
5109   MCAuto<DataArrayDouble> arr=DataArrayDouble::New();
5110   arr->alloc(nbOfCells,1);
5111   double *pt=arr->getPointer();
5112   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
5113   const int *conn=_nodal_connec->begin();
5114   const int *connI=_nodal_connec_index->begin();
5115   const double *coo=_coords->begin();
5116   double tmp[12];
5117   for(int i=0;i<nbOfCells;i++,pt++)
5118     {
5119       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
5120       switch(t)
5121       {
5122         case INTERP_KERNEL::NORM_QUAD4:
5123           {
5124             FillInCompact3DMode(3,4,conn+1,coo,tmp);
5125             *pt=INTERP_KERNEL::quadWarp(tmp);
5126             break;
5127           }
5128         default:
5129           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getWarpField : A cell with not manged type (NORM_QUAD4) has been detected !");
5130       }
5131       conn+=connI[i+1]-connI[i];
5132     }
5133   ret->setName("Warp");
5134   ret->synchronizeTimeWithSupport();
5135   return ret.retn();
5136 }
5137
5138
5139 /*!
5140  * Creates a new MEDCouplingFieldDouble holding Skew factor values of all
5141  * cells of \a this 2D mesh in 3D space. Currently cells of the following types are
5142  * treated: INTERP_KERNEL::NORM_QUAD4.
5143  * The skew is computed as follow for a quad with points (a,b,c,d): let
5144  * \f$u=\vec{ab}+\vec{dc}\f$ and \f$v=\vec{ac}+\vec{bd}\f$
5145  * then the skew is computed as:
5146  *  \f[
5147  *    s=\frac{u}{|u|}\cdot\frac{v}{|v|}
5148  *  \f]
5149  *
5150  * For a cell of other type an exception is thrown.
5151  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
5152  *          cells and one time, lying on \a this mesh. The caller is to delete this
5153  *          field using decrRef() as it is no more needed. 
5154  *  \throw If the coordinates array is not set.
5155  *  \throw If \a this mesh contains elements of dimension different from the mesh dimension.
5156  *  \throw If the connectivity data array has more than one component.
5157  *  \throw If the connectivity data array has a named component.
5158  *  \throw If the connectivity index data array has more than one component.
5159  *  \throw If the connectivity index data array has a named component.
5160  *  \throw If \a this->getMeshDimension() != 2.
5161  *  \throw If \a this->getSpaceDimension() != 3.
5162  *  \throw If \a this mesh includes cells of type different from the ones enumerated above.
5163  */
5164 MEDCouplingFieldDouble *MEDCouplingUMesh::getSkewField() const
5165 {
5166   checkConsistencyLight();
5167   int spaceDim=getSpaceDimension();
5168   int meshDim=getMeshDimension();
5169   if(spaceDim!=3)
5170     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getSkewField : SpaceDimension must be equal to 3 !");
5171   if(meshDim!=2)
5172     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getSkewField : MeshDimension must be equal to 2 !");
5173   MCAuto<MEDCouplingFieldDouble> ret=MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME);
5174   ret->setMesh(this);
5175   int nbOfCells=getNumberOfCells();
5176   MCAuto<DataArrayDouble> arr=DataArrayDouble::New();
5177   arr->alloc(nbOfCells,1);
5178   double *pt=arr->getPointer();
5179   ret->setArray(arr);//In case of throw to avoid mem leaks arr will be used after decrRef.
5180   const int *conn=_nodal_connec->begin();
5181   const int *connI=_nodal_connec_index->begin();
5182   const double *coo=_coords->begin();
5183   double tmp[12];
5184   for(int i=0;i<nbOfCells;i++,pt++)
5185     {
5186       INTERP_KERNEL::NormalizedCellType t=(INTERP_KERNEL::NormalizedCellType)*conn;
5187       switch(t)
5188       {
5189         case INTERP_KERNEL::NORM_QUAD4:
5190           {
5191             FillInCompact3DMode(3,4,conn+1,coo,tmp);
5192             *pt=INTERP_KERNEL::quadSkew(tmp);
5193             break;
5194           }
5195         default:
5196           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getSkewField : A cell with not manged type (NORM_QUAD4) has been detected !");
5197       }
5198       conn+=connI[i+1]-connI[i];
5199     }
5200   ret->setName("Skew");
5201   ret->synchronizeTimeWithSupport();
5202   return ret.retn();
5203 }
5204
5205 /*!
5206  * Returns the cell field giving for each cell in \a this its diameter. Diameter means the max length of all possible SEG2 in the cell.
5207  *
5208  * \return a new instance of field containing the result. The returned instance has to be deallocated by the caller.
5209  *
5210  * \sa getSkewField, getWarpField, getAspectRatioField, getEdgeRatioField
5211  */
5212 MEDCouplingFieldDouble *MEDCouplingUMesh::computeDiameterField() const
5213 {
5214   checkConsistencyLight();
5215   MCAuto<MEDCouplingFieldDouble> ret(MEDCouplingFieldDouble::New(ON_CELLS,ONE_TIME));
5216   ret->setMesh(this);
5217   std::set<INTERP_KERNEL::NormalizedCellType> types;
5218   ComputeAllTypesInternal(types,_nodal_connec,_nodal_connec_index);
5219   int spaceDim(getSpaceDimension()),nbCells(getNumberOfCells());
5220   MCAuto<DataArrayDouble> arr(DataArrayDouble::New());
5221   arr->alloc(nbCells,1);
5222   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator it=types.begin();it!=types.end();it++)
5223     {
5224       INTERP_KERNEL::AutoCppPtr<INTERP_KERNEL::DiameterCalculator> dc(INTERP_KERNEL::CellModel::GetCellModel(*it).buildInstanceOfDiameterCalulator(spaceDim));
5225       MCAuto<DataArrayInt> cellIds(giveCellsWithType(*it));
5226       dc->computeForListOfCellIdsUMeshFrmt(cellIds->begin(),cellIds->end(),_nodal_connec_index->begin(),_nodal_connec->begin(),getCoords()->begin(),arr->getPointer());
5227     }
5228   ret->setArray(arr);
5229   ret->setName("Diameter");
5230   return ret.retn();
5231 }
5232
5233 /*!
5234  * This method aggregate the bbox of each cell and put it into bbox parameter (xmin,xmax,ymin,ymax,zmin,zmax).
5235  * 
5236  * \param [in] arcDetEps - a parameter specifying in case of 2D quadratic polygon cell the detection limit between linear and arc circle. (By default 1e-12)
5237  *                         For all other cases this input parameter is ignored.
5238  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
5239  * 
5240  * \throw If \a this is not fully set (coordinates and connectivity).
5241  * \throw If a cell in \a this has no valid nodeId.
5242  * \sa MEDCouplingUMesh::getBoundingBoxForBBTreeFast, MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic
5243  */
5244 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTree(double arcDetEps) const
5245 {
5246   int mDim(getMeshDimension()),sDim(getSpaceDimension());
5247   if((mDim==3 && sDim==3) || (mDim==2 && sDim==3) || (mDim==1 && sDim==1) || ( mDim==1 && sDim==3))  // Compute refined boundary box for quadratic elements only in 2D.
5248     return getBoundingBoxForBBTreeFast();
5249   if((mDim==2 && sDim==2) || (mDim==1 && sDim==2))
5250     {
5251       bool presenceOfQuadratic(false);
5252       for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator it=_types.begin();it!=_types.end();it++)
5253         {
5254           const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel(*it));
5255           if(cm.isQuadratic())
5256             presenceOfQuadratic=true;
5257         }
5258       if(!presenceOfQuadratic)
5259         return getBoundingBoxForBBTreeFast();
5260       if(mDim==2 && sDim==2)
5261         return getBoundingBoxForBBTree2DQuadratic(arcDetEps);
5262       else
5263         return getBoundingBoxForBBTree1DQuadratic(arcDetEps);
5264     }
5265   throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getBoundingBoxForBBTree : Managed dimensions are (mDim=1,sDim=1), (mDim=1,sDim=2), (mDim=1,sDim=3), (mDim=2,sDim=2), (mDim=2,sDim=3) and (mDim=3,sDim=3) !");
5266 }
5267
5268 /*!
5269  * This method aggregate the bbox of each cell only considering the nodes constituting each cell and put it into bbox parameter.
5270  * So meshes having quadratic cells the computed bounding boxes can be invalid !
5271  * 
5272  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
5273  * 
5274  * \throw If \a this is not fully set (coordinates and connectivity).
5275  * \throw If a cell in \a this has no valid nodeId.
5276  */
5277 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTreeFast() const
5278 {
5279   checkFullyDefined();
5280   int spaceDim(getSpaceDimension()),nbOfCells(getNumberOfCells()),nbOfNodes(getNumberOfNodes());
5281   MCAuto<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(nbOfCells,2*spaceDim);
5282   double *bbox(ret->getPointer());
5283   for(int i=0;i<nbOfCells*spaceDim;i++)
5284     {
5285       bbox[2*i]=std::numeric_limits<double>::max();
5286       bbox[2*i+1]=-std::numeric_limits<double>::max();
5287     }
5288   const double *coordsPtr(_coords->begin());
5289   const int *conn(_nodal_connec->begin()),*connI(_nodal_connec_index->begin());
5290   for(int i=0;i<nbOfCells;i++)
5291     {
5292       int offset=connI[i]+1;
5293       int nbOfNodesForCell(connI[i+1]-offset),kk(0);
5294       for(int j=0;j<nbOfNodesForCell;j++)
5295         {
5296           int nodeId=conn[offset+j];
5297           if(nodeId>=0 && nodeId<nbOfNodes)
5298             {
5299               for(int k=0;k<spaceDim;k++)
5300                 {
5301                   bbox[2*spaceDim*i+2*k]=std::min(bbox[2*spaceDim*i+2*k],coordsPtr[spaceDim*nodeId+k]);
5302                   bbox[2*spaceDim*i+2*k+1]=std::max(bbox[2*spaceDim*i+2*k+1],coordsPtr[spaceDim*nodeId+k]);
5303                 }
5304               kk++;
5305             }
5306         }
5307       if(kk==0)
5308         {
5309           std::ostringstream oss; oss << "MEDCouplingUMesh::getBoundingBoxForBBTree : cell #" << i << " contains no valid nodeId !";
5310           throw INTERP_KERNEL::Exception(oss.str());
5311         }
5312     }
5313   return ret.retn();
5314 }
5315
5316 /*!
5317  * This method aggregates the bbox of each 2D cell in \a this considering the whole shape. This method is particularly
5318  * useful for 2D meshes having quadratic cells
5319  * because for this type of cells getBoundingBoxForBBTreeFast method may return invalid bounding boxes (since it just considers
5320  * the two extremities of the arc of circle).
5321  * 
5322  * \param [in] arcDetEps - a parameter specifying in case of 2D quadratic polygon cell the detection limit between linear and arc circle. (By default 1e-12)
5323  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
5324  * \throw If \a this is not fully defined.
5325  * \throw If \a this is not a mesh with meshDimension equal to 2.
5326  * \throw If \a this is not a mesh with spaceDimension equal to 2.
5327  * \sa MEDCouplingUMesh::getBoundingBoxForBBTree1DQuadratic
5328  */
5329 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic(double arcDetEps) const
5330 {
5331   checkFullyDefined();
5332   int spaceDim(getSpaceDimension()),mDim(getMeshDimension()),nbOfCells(getNumberOfCells());
5333   if(spaceDim!=2 || mDim!=2)
5334     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic : This method should be applied on mesh with mesh dimension equal to 2 and space dimension also equal to 2!");
5335   MCAuto<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(nbOfCells,2*spaceDim);
5336   double *bbox(ret->getPointer());
5337   const double *coords(_coords->begin());
5338   const int *conn(_nodal_connec->begin()),*connI(_nodal_connec_index->begin());
5339   for(int i=0;i<nbOfCells;i++,bbox+=4,connI++)
5340     {
5341       const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*connI]));
5342       int sz(connI[1]-connI[0]-1);
5343       INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=arcDetEps;
5344       std::vector<INTERP_KERNEL::Node *> nodes(sz);
5345       INTERP_KERNEL::QuadraticPolygon *pol(0);
5346       for(int j=0;j<sz;j++)
5347         {
5348           int nodeId(conn[*connI+1+j]);
5349           nodes[j]=new INTERP_KERNEL::Node(coords[nodeId*2],coords[nodeId*2+1]);
5350         }
5351       if(!cm.isQuadratic())
5352         pol=INTERP_KERNEL::QuadraticPolygon::BuildLinearPolygon(nodes);
5353       else
5354         pol=INTERP_KERNEL::QuadraticPolygon::BuildArcCirclePolygon(nodes);
5355       INTERP_KERNEL::Bounds b; b.prepareForAggregation(); pol->fillBounds(b); delete pol;
5356       bbox[0]=b.getXMin(); bbox[1]=b.getXMax(); bbox[2]=b.getYMin(); bbox[3]=b.getYMax(); 
5357     }
5358   return ret.retn();
5359 }
5360
5361 /*!
5362  * This method aggregates the bbox of each 1D cell in \a this considering the whole shape. This method is particularly
5363  * useful for 2D meshes having quadratic cells
5364  * because for this type of cells getBoundingBoxForBBTreeFast method may return invalid bounding boxes (since it just considers
5365  * the two extremities of the arc of circle).
5366  * 
5367  * \param [in] arcDetEps - a parameter specifying in case of 2D quadratic polygon cell the detection limit between linear and arc circle. (By default 1e-12)
5368  * \return DataArrayDouble * - newly created object (to be managed by the caller) \a this number of cells tuples and 2*spacedim components.
5369  * \throw If \a this is not fully defined.
5370  * \throw If \a this is not a mesh with meshDimension equal to 1.
5371  * \throw If \a this is not a mesh with spaceDimension equal to 2.
5372  * \sa MEDCouplingUMesh::getBoundingBoxForBBTree2DQuadratic
5373  */
5374 DataArrayDouble *MEDCouplingUMesh::getBoundingBoxForBBTree1DQuadratic(double arcDetEps) const
5375 {
5376   checkFullyDefined();
5377   int spaceDim(getSpaceDimension()),mDim(getMeshDimension()),nbOfCells(getNumberOfCells());
5378   if(spaceDim!=2 || mDim!=1)
5379     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::getBoundingBoxForBBTree1DQuadratic : This method should be applied on mesh with mesh dimension equal to 1 and space dimension also equal to 2!");
5380   MCAuto<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(nbOfCells,2*spaceDim);
5381   double *bbox(ret->getPointer());
5382   const double *coords(_coords->begin());
5383   const int *conn(_nodal_connec->begin()),*connI(_nodal_connec_index->begin());
5384   for(int i=0;i<nbOfCells;i++,bbox+=4,connI++)
5385     {
5386       const INTERP_KERNEL::CellModel& cm(INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*connI]));
5387       int sz(connI[1]-connI[0]-1);
5388       INTERP_KERNEL::QUADRATIC_PLANAR::_arc_detection_precision=arcDetEps;
5389       std::vector<INTERP_KERNEL::Node *> nodes(sz);
5390       INTERP_KERNEL::Edge *edge(0);
5391       for(int j=0;j<sz;j++)
5392         {
5393           int nodeId(conn[*connI+1+j]);
5394           nodes[j]=new INTERP_KERNEL::Node(coords[nodeId*2],coords[nodeId*2+1]);
5395         }
5396       if(!cm.isQuadratic())
5397         edge=INTERP_KERNEL::QuadraticPolygon::BuildLinearEdge(nodes);
5398       else
5399         edge=INTERP_KERNEL::QuadraticPolygon::BuildArcCircleEdge(nodes);
5400       const INTERP_KERNEL::Bounds& b(edge->getBounds());
5401       bbox[0]=b.getXMin(); bbox[1]=b.getXMax(); bbox[2]=b.getYMin(); bbox[3]=b.getYMax(); edge->decrRef();
5402     }
5403   return ret.retn();
5404 }
5405
5406 /// @cond INTERNAL
5407
5408 namespace MEDCouplingImpl
5409 {
5410   class ConnReader
5411   {
5412   public:
5413     ConnReader(const int *c, int val):_conn(c),_val(val) { }
5414     bool operator() (const int& pos) { return _conn[pos]!=_val; }
5415   private:
5416     const int *_conn;
5417     int _val;
5418   };
5419
5420   class ConnReader2
5421   {
5422   public:
5423     ConnReader2(const int *c, int val):_conn(c),_val(val) { }
5424     bool operator() (const int& pos) { return _conn[pos]==_val; }
5425   private:
5426     const int *_conn;
5427     int _val;
5428   };
5429 }
5430
5431 /// @endcond
5432
5433 /*!
5434  * This method expects that \a this is sorted by types. If not an exception will be thrown.
5435  * This method returns in the same format as code (see MEDCouplingUMesh::checkTypeConsistencyAndContig or MEDCouplingUMesh::splitProfilePerType) how
5436  * \a this is composed in cell types.
5437  * The returned array is of size 3*n where n is the number of different types present in \a this. 
5438  * For every k in [0,n] ret[3*k+2]==-1 because it has no sense here. 
5439  * This parameter is kept only for compatibility with other methode listed above.
5440  */
5441 std::vector<int> MEDCouplingUMesh::getDistributionOfTypes() const
5442 {
5443   checkConnectivityFullyDefined();
5444   const int *conn=_nodal_connec->begin();
5445   const int *connI=_nodal_connec_index->begin();
5446   const int *work=connI;
5447   int nbOfCells=getNumberOfCells();
5448   std::size_t n=getAllGeoTypes().size();
5449   std::vector<int> ret(3*n,-1); //ret[3*k+2]==-1 because it has no sense here
5450   std::set<INTERP_KERNEL::NormalizedCellType> types;
5451   for(std::size_t i=0;work!=connI+nbOfCells;i++)
5452     {
5453       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)conn[*work];
5454       if(types.find(typ)!=types.end())
5455         {
5456           std::ostringstream oss; oss << "MEDCouplingUMesh::getDistributionOfTypes : Type " << INTERP_KERNEL::CellModel::GetCellModel(typ).getRepr();
5457           oss << " is not contiguous !";
5458           throw INTERP_KERNEL::Exception(oss.str());
5459         }
5460       types.insert(typ);
5461       ret[3*i]=typ;
5462       const int *work2=std::find_if(work+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,typ));
5463       ret[3*i+1]=(int)std::distance(work,work2);
5464       work=work2;
5465     }
5466   return ret;
5467 }
5468
5469 /*!
5470  * This method is used to check that this has contiguous cell type in same order than described in \a code.
5471  * only for types cell, type node is not managed.
5472  * Format of \a code is the following. \a code should be of size 3*n and non empty. If not an exception is thrown.
5473  * foreach k in [0,n) on 3*k pos represent the geometric type and 3*k+1 number of elements of type 3*k.
5474  * 3*k+2 refers if different from -1 the pos in 'idsPerType' to get the corresponding array.
5475  * If 2 or more same geometric type is in \a code and exception is thrown too.
5476  *
5477  * This method firstly checks
5478  * If it exists k so that 3*k geometric type is not in geometric types of this an exception will be thrown.
5479  * If it exists k so that 3*k geometric type exists but the number of consecutive cell types does not match,
5480  * an exception is thrown too.
5481  * 
5482  * If all geometric types in \a code are exactly those in \a this null pointer is returned.
5483  * If it exists a geometric type in \a this \b not in \a code \b no exception is thrown 
5484  * and a DataArrayInt instance is returned that the user has the responsability to deallocate.
5485  */
5486 DataArrayInt *MEDCouplingUMesh::checkTypeConsistencyAndContig(const std::vector<int>& code, const std::vector<const DataArrayInt *>& idsPerType) const
5487 {
5488   if(code.empty())
5489     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : code is empty, should not !");
5490   std::size_t sz=code.size();
5491   std::size_t n=sz/3;
5492   if(sz%3!=0)
5493     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : code size is NOT %3 !");
5494   std::vector<INTERP_KERNEL::NormalizedCellType> types;
5495   int nb=0;
5496   bool isNoPflUsed=true;
5497   for(std::size_t i=0;i<n;i++)
5498     if(std::find(types.begin(),types.end(),(INTERP_KERNEL::NormalizedCellType)code[3*i])==types.end())
5499       {
5500         types.push_back((INTERP_KERNEL::NormalizedCellType)code[3*i]);
5501         nb+=code[3*i+1];
5502         if(_types.find((INTERP_KERNEL::NormalizedCellType)code[3*i])==_types.end())
5503           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : expected geo types not in this !");
5504         isNoPflUsed=isNoPflUsed && (code[3*i+2]==-1);
5505       }
5506   if(types.size()!=n)
5507     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : code contains duplication of types in unstructured mesh !");
5508   if(isNoPflUsed)
5509     {
5510       if(!checkConsecutiveCellTypesAndOrder(&types[0],&types[0]+types.size()))
5511         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : non contiguous type !");
5512       if(types.size()==_types.size())
5513         return 0;
5514     }
5515   MCAuto<DataArrayInt> ret=DataArrayInt::New();
5516   ret->alloc(nb,1);
5517   int *retPtr=ret->getPointer();
5518   const int *connI=_nodal_connec_index->begin();
5519   const int *conn=_nodal_connec->begin();
5520   int nbOfCells=getNumberOfCells();
5521   const int *i=connI;
5522   int kk=0;
5523   for(std::vector<INTERP_KERNEL::NormalizedCellType>::const_iterator it=types.begin();it!=types.end();it++,kk++)
5524     {
5525       i=std::find_if(i,connI+nbOfCells,MEDCouplingImpl::ConnReader2(conn,(int)(*it)));
5526       int offset=(int)std::distance(connI,i);
5527       const int *j=std::find_if(i+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,(int)(*it)));
5528       int nbOfCellsOfCurType=(int)std::distance(i,j);
5529       if(code[3*kk+2]==-1)
5530         for(int k=0;k<nbOfCellsOfCurType;k++)
5531           *retPtr++=k+offset;
5532       else
5533         {
5534           int idInIdsPerType=code[3*kk+2];
5535           if(idInIdsPerType>=0 && idInIdsPerType<(int)idsPerType.size())
5536             {
5537               const DataArrayInt *zePfl=idsPerType[idInIdsPerType];
5538               if(zePfl)
5539                 {
5540                   zePfl->checkAllocated();
5541                   if(zePfl->getNumberOfComponents()==1)
5542                     {
5543                       for(const int *k=zePfl->begin();k!=zePfl->end();k++,retPtr++)
5544                         {
5545                           if(*k>=0 && *k<nbOfCellsOfCurType)
5546                             *retPtr=(*k)+offset;
5547                           else
5548                             {
5549                               std::ostringstream oss; oss << "MEDCouplingUMesh::checkTypeConsistencyAndContig : the section " << kk << " points to the profile #" << idInIdsPerType;
5550                               oss << ", and this profile contains a value " << *k << " should be in [0," << nbOfCellsOfCurType << ") !";
5551                               throw INTERP_KERNEL::Exception(oss.str());
5552                             }
5553                         }
5554                     }
5555                   else
5556                     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : presence of a profile with nb of compo != 1 !");
5557                 }
5558               else
5559                 throw INTERP_KERNEL::Exception("MEDCouplingUMesh::checkTypeConsistencyAndContig : presence of null profile !");
5560             }
5561           else
5562             {
5563               std::ostringstream oss; oss << "MEDCouplingUMesh::checkTypeConsistencyAndContig : at section " << kk << " of code it points to the array #" << idInIdsPerType;
5564               oss << " should be in [0," << idsPerType.size() << ") !";
5565               throw INTERP_KERNEL::Exception(oss.str());
5566             }
5567         }
5568       i=j;
5569     }
5570   return ret.retn();
5571 }
5572
5573 /*!
5574  * This method makes the hypothesis that \a this is sorted by type. If not an exception will be thrown.
5575  * This method is the opposite of MEDCouplingUMesh::checkTypeConsistencyAndContig method. Given a list of cells in \a profile it returns a list of sub-profiles sorted by geo type.
5576  * The result is put in the array \a idsPerType. In the returned parameter \a code, foreach i \a code[3*i+2] refers (if different from -1) to a location into the \a idsPerType.
5577  * This method has 1 input \a profile and 3 outputs \a code \a idsInPflPerType and \a idsPerType.
5578  * 
5579  * \param [in] profile
5580  * \param [out] code is a vector of size 3*n where n is the number of different geometric type in \a this \b reduced to the profile \a profile. \a code has exactly the same semantic than in MEDCouplingUMesh::checkTypeConsistencyAndContig method.
5581  * \param [out] idsInPflPerType is a vector of size of different geometric type in the subpart defined by \a profile of \a this ( equal to \a code.size()/3). For each i,
5582  *              \a idsInPflPerType[i] stores the tuple ids in \a profile that correspond to the geometric type code[3*i+0]
5583  * \param [out] idsPerType is a vector of size of different sub profiles needed to be defined to represent the profile \a profile for a given geometric type.
5584  *              This vector can be empty in case of all geometric type cells are fully covered in ascending in the given input \a profile.
5585  * \throw if \a profile has not exactly one component. It throws too, if \a profile contains some values not in [0,getNumberOfCells()) or if \a this is not fully defined
5586  */
5587 void MEDCouplingUMesh::splitProfilePerType(const DataArrayInt *profile, std::vector<int>& code, std::vector<DataArrayInt *>& idsInPflPerType, std::vector<DataArrayInt *>& idsPerType) const
5588 {
5589   if(!profile)
5590     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitProfilePerType : input profile is NULL !");
5591   if(profile->getNumberOfComponents()!=1)
5592     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitProfilePerType : input profile should have exactly one component !");
5593   checkConnectivityFullyDefined();
5594   const int *conn=_nodal_connec->begin();
5595   const int *connI=_nodal_connec_index->begin();
5596   int nbOfCells=getNumberOfCells();
5597   std::vector<INTERP_KERNEL::NormalizedCellType> types;
5598   std::vector<int> typeRangeVals(1);
5599   for(const int *i=connI;i!=connI+nbOfCells;)
5600     {
5601       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
5602       if(std::find(types.begin(),types.end(),curType)!=types.end())
5603         {
5604           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::splitProfilePerType : current mesh is not sorted by type !");
5605         }
5606       types.push_back(curType);
5607       i=std::find_if(i+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,(int)curType));
5608       typeRangeVals.push_back((int)std::distance(connI,i));
5609     }
5610   //
5611   DataArrayInt *castArr=0,*rankInsideCast=0,*castsPresent=0;
5612   profile->splitByValueRange(&typeRangeVals[0],&typeRangeVals[0]+typeRangeVals.size(),castArr,rankInsideCast,castsPresent);
5613   MCAuto<DataArrayInt> tmp0=castArr;
5614   MCAuto<DataArrayInt> tmp1=rankInsideCast;
5615   MCAuto<DataArrayInt> tmp2=castsPresent;
5616   //
5617   int nbOfCastsFinal=castsPresent->getNumberOfTuples();
5618   code.resize(3*nbOfCastsFinal);
5619   std::vector< MCAuto<DataArrayInt> > idsInPflPerType2;
5620   std::vector< MCAuto<DataArrayInt> > idsPerType2;
5621   for(int i=0;i<nbOfCastsFinal;i++)
5622     {
5623       int castId=castsPresent->getIJ(i,0);
5624       MCAuto<DataArrayInt> tmp3=castArr->findIdsEqual(castId);
5625       idsInPflPerType2.push_back(tmp3);
5626       code[3*i]=(int)types[castId];
5627       code[3*i+1]=tmp3->getNumberOfTuples();
5628       MCAuto<DataArrayInt> tmp4=rankInsideCast->selectByTupleId(tmp3->begin(),tmp3->begin()+tmp3->getNumberOfTuples());
5629       if(!tmp4->isIota(typeRangeVals[castId+1]-typeRangeVals[castId]))
5630         {
5631           tmp4->copyStringInfoFrom(*profile);
5632           idsPerType2.push_back(tmp4);
5633           code[3*i+2]=(int)idsPerType2.size()-1;
5634         }
5635       else
5636         {
5637           code[3*i+2]=-1;
5638         }
5639     }
5640   std::size_t sz2=idsInPflPerType2.size();
5641   idsInPflPerType.resize(sz2);
5642   for(std::size_t i=0;i<sz2;i++)
5643     {
5644       DataArrayInt *locDa=idsInPflPerType2[i];
5645       locDa->incrRef();
5646       idsInPflPerType[i]=locDa;
5647     }
5648   std::size_t sz=idsPerType2.size();
5649   idsPerType.resize(sz);
5650   for(std::size_t i=0;i<sz;i++)
5651     {
5652       DataArrayInt *locDa=idsPerType2[i];
5653       locDa->incrRef();
5654       idsPerType[i]=locDa;
5655     }
5656 }
5657
5658 /*!
5659  * This method is here too emulate the MEDMEM behaviour on BDC (buildDescendingConnectivity). Hoping this method becomes deprecated very soon.
5660  * This method make the assumption that \a this and 'nM1LevMesh' mesh lyies on same coords (same pointer) as MED and MEDMEM does.
5661  * The following equality should be verified 'nM1LevMesh->getMeshDimension()==this->getMeshDimension()-1'
5662  * This method returns 5+2 elements. 'desc', 'descIndx', 'revDesc', 'revDescIndx' and 'meshnM1' behaves exactly as MEDCoupling::MEDCouplingUMesh::buildDescendingConnectivity except the content as described after. The returned array specifies the n-1 mesh reordered by type as MEDMEM does. 'nM1LevMeshIds' contains the ids in returned 'meshnM1'. Finally 'meshnM1Old2New' contains numbering old2new that is to say the cell #k in coarse 'nM1LevMesh' will have the number ret[k] in returned mesh 'nM1LevMesh' MEDMEM reordered.
5663  */
5664 MEDCouplingUMesh *MEDCouplingUMesh::emulateMEDMEMBDC(const MEDCouplingUMesh *nM1LevMesh, DataArrayInt *desc, DataArrayInt *descIndx, DataArrayInt *&revDesc, DataArrayInt *&revDescIndx, DataArrayInt *& nM1LevMeshIds, DataArrayInt *&meshnM1Old2New) const
5665 {
5666   checkFullyDefined();
5667   nM1LevMesh->checkFullyDefined();
5668   if(getMeshDimension()-1!=nM1LevMesh->getMeshDimension())
5669     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::emulateMEDMEMBDC : The mesh passed as first argument should have a meshDim equal to this->getMeshDimension()-1 !" );
5670   if(_coords!=nM1LevMesh->getCoords())
5671     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::emulateMEDMEMBDC : 'this' and mesh in first argument should share the same coords : Use tryToShareSameCoords method !");
5672   MCAuto<DataArrayInt> tmp0=DataArrayInt::New();
5673   MCAuto<DataArrayInt> tmp1=DataArrayInt::New();
5674   MCAuto<MEDCouplingUMesh> ret1=buildDescendingConnectivity(desc,descIndx,tmp0,tmp1);
5675   MCAuto<DataArrayInt> ret0=ret1->sortCellsInMEDFileFrmt();
5676   desc->transformWithIndArr(ret0->begin(),ret0->begin()+ret0->getNbOfElems());
5677   MCAuto<MEDCouplingUMesh> tmp=MEDCouplingUMesh::New();
5678   tmp->setConnectivity(tmp0,tmp1);
5679   tmp->renumberCells(ret0->begin(),false);
5680   revDesc=tmp->getNodalConnectivity();
5681   revDescIndx=tmp->getNodalConnectivityIndex();
5682   DataArrayInt *ret=0;
5683   if(!ret1->areCellsIncludedIn(nM1LevMesh,2,ret))
5684     {
5685       int tmp2;
5686       ret->getMaxValue(tmp2);
5687       ret->decrRef();
5688       std::ostringstream oss; oss << "MEDCouplingUMesh::emulateMEDMEMBDC : input N-1 mesh present a cell not in descending mesh ... Id of cell is " << tmp2 << " !";
5689       throw INTERP_KERNEL::Exception(oss.str());
5690     }
5691   nM1LevMeshIds=ret;
5692   //
5693   revDesc->incrRef();
5694   revDescIndx->incrRef();
5695   ret1->incrRef();
5696   ret0->incrRef();
5697   meshnM1Old2New=ret0;
5698   return ret1;
5699 }
5700
5701 /*!
5702  * Permutes the nodal connectivity arrays so that the cells are sorted by type, which is
5703  * necessary for writing the mesh to MED file. Additionally returns a permutation array
5704  * in "Old to New" mode.
5705  *  \return DataArrayInt * - a new instance of DataArrayInt. The caller is to delete
5706  *          this array using decrRef() as it is no more needed.
5707  *  \throw If the nodal connectivity of cells is not defined.
5708  */
5709 DataArrayInt *MEDCouplingUMesh::sortCellsInMEDFileFrmt()
5710 {
5711   checkConnectivityFullyDefined();
5712   MCAuto<DataArrayInt> ret=getRenumArrForMEDFileFrmt();
5713   renumberCells(ret->begin(),false);
5714   return ret.retn();
5715 }
5716
5717 /*!
5718  * This methods checks that cells are sorted by their types.
5719  * This method makes asumption (no check) that connectivity is correctly set before calling.
5720  */
5721 bool MEDCouplingUMesh::checkConsecutiveCellTypes() const
5722 {
5723   checkFullyDefined();
5724   const int *conn=_nodal_connec->begin();
5725   const int *connI=_nodal_connec_index->begin();
5726   int nbOfCells=getNumberOfCells();
5727   std::set<INTERP_KERNEL::NormalizedCellType> types;
5728   for(const int *i=connI;i!=connI+nbOfCells;)
5729     {
5730       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
5731       if(types.find(curType)!=types.end())
5732         return false;
5733       types.insert(curType);
5734       i=std::find_if(i+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,(int)curType));
5735     }
5736   return true;
5737 }
5738
5739 /*!
5740  * This method is a specialization of MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder method that is called here.
5741  * The geometric type order is specified by MED file.
5742  * 
5743  * \sa  MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder
5744  */
5745 bool MEDCouplingUMesh::checkConsecutiveCellTypesForMEDFileFrmt() const
5746 {
5747   return checkConsecutiveCellTypesAndOrder(MEDMEM_ORDER,MEDMEM_ORDER+N_MEDMEM_ORDER);
5748 }
5749
5750 /*!
5751  * This method performs the same job as checkConsecutiveCellTypes except that the order of types sequence is analyzed to check
5752  * that the order is specified in array defined by [ \a orderBg , \a orderEnd ).
5753  * If there is some geo types in \a this \b NOT in [ \a orderBg, \a orderEnd ) it is OK (return true) if contiguous.
5754  * If there is some geo types in [ \a orderBg, \a orderEnd ) \b NOT in \a this it is OK too (return true) if contiguous.
5755  */
5756 bool MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder(const INTERP_KERNEL::NormalizedCellType *orderBg, const INTERP_KERNEL::NormalizedCellType *orderEnd) const
5757 {
5758   checkFullyDefined();
5759   const int *conn=_nodal_connec->begin();
5760   const int *connI=_nodal_connec_index->begin();
5761   int nbOfCells=getNumberOfCells();
5762   if(nbOfCells==0)
5763     return true;
5764   int lastPos=-1;
5765   std::set<INTERP_KERNEL::NormalizedCellType> sg;
5766   for(const int *i=connI;i!=connI+nbOfCells;)
5767     {
5768       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
5769       const INTERP_KERNEL::NormalizedCellType *isTypeExists=std::find(orderBg,orderEnd,curType);
5770       if(isTypeExists!=orderEnd)
5771         {
5772           int pos=(int)std::distance(orderBg,isTypeExists);
5773           if(pos<=lastPos)
5774             return false;
5775           lastPos=pos;
5776           i=std::find_if(i+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,(int)curType));
5777         }
5778       else
5779         {
5780           if(sg.find(curType)==sg.end())
5781             {
5782               i=std::find_if(i+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,(int)curType));
5783               sg.insert(curType);
5784             }
5785           else
5786             return false;
5787         }
5788     }
5789   return true;
5790 }
5791
5792 /*!
5793  * This method returns 2 newly allocated DataArrayInt instances. The first is an array of size 'this->getNumberOfCells()' with one component,
5794  * that tells for each cell the pos of its type in the array on type given in input parameter. The 2nd output parameter is an array with the same
5795  * number of tuples than input type array and with one component. This 2nd output array gives type by type the number of occurence of type in 'this'.
5796  */
5797 DataArrayInt *MEDCouplingUMesh::getLevArrPerCellTypes(const INTERP_KERNEL::NormalizedCellType *orderBg, const INTERP_KERNEL::NormalizedCellType *orderEnd, DataArrayInt *&nbPerType) const
5798 {
5799   checkConnectivityFullyDefined();
5800   int nbOfCells=getNumberOfCells();
5801   const int *conn=_nodal_connec->begin();
5802   const int *connI=_nodal_connec_index->begin();
5803   MCAuto<DataArrayInt> tmpa=DataArrayInt::New();
5804   MCAuto<DataArrayInt> tmpb=DataArrayInt::New();
5805   tmpa->alloc(nbOfCells,1);
5806   tmpb->alloc((int)std::distance(orderBg,orderEnd),1);
5807   tmpb->fillWithZero();
5808   int *tmp=tmpa->getPointer();
5809   int *tmp2=tmpb->getPointer();
5810   for(const int *i=connI;i!=connI+nbOfCells;i++)
5811     {
5812       const INTERP_KERNEL::NormalizedCellType *where=std::find(orderBg,orderEnd,(INTERP_KERNEL::NormalizedCellType)conn[*i]);
5813       if(where!=orderEnd)
5814         {
5815           int pos=(int)std::distance(orderBg,where);
5816           tmp2[pos]++;
5817           tmp[std::distance(connI,i)]=pos;
5818         }
5819       else
5820         {
5821           const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)conn[*i]);
5822           std::ostringstream oss; oss << "MEDCouplingUMesh::getLevArrPerCellTypes : Cell #" << std::distance(connI,i);
5823           oss << " has a type " << cm.getRepr() << " not in input array of type !";
5824           throw INTERP_KERNEL::Exception(oss.str());
5825         }
5826     }
5827   nbPerType=tmpb.retn();
5828   return tmpa.retn();
5829 }
5830
5831 /*!
5832  * This method behaves exactly as MEDCouplingUMesh::getRenumArrForConsecutiveCellTypesSpec but the order is those defined in MED file spec.
5833  *
5834  * \return a new object containing the old to new correspondance.
5835  *
5836  * \sa MEDCouplingUMesh::getRenumArrForConsecutiveCellTypesSpec, MEDCouplingUMesh::sortCellsInMEDFileFrmt.
5837  */
5838 DataArrayInt *MEDCouplingUMesh::getRenumArrForMEDFileFrmt() const
5839 {
5840   return getRenumArrForConsecutiveCellTypesSpec(MEDMEM_ORDER,MEDMEM_ORDER+N_MEDMEM_ORDER);
5841 }
5842
5843 /*!
5844  * This method is similar to method MEDCouplingUMesh::rearrange2ConsecutiveCellTypes except that the type order is specfied by [ \a orderBg , \a orderEnd ) (as MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder method) and that this method is \b const and performs \b NO permutation in \a this.
5845  * This method returns an array of size getNumberOfCells() that gives a renumber array old2New that can be used as input of MEDCouplingMesh::renumberCells.
5846  * The mesh after this call to MEDCouplingMesh::renumberCells will pass the test of MEDCouplingUMesh::checkConsecutiveCellTypesAndOrder with the same inputs.
5847  * The returned array minimizes the permutations that is to say the order of cells inside same geometric type remains the same.
5848  */
5849 DataArrayInt *MEDCouplingUMesh::getRenumArrForConsecutiveCellTypesSpec(const INTERP_KERNEL::NormalizedCellType *orderBg, const INTERP_KERNEL::NormalizedCellType *orderEnd) const
5850 {
5851   DataArrayInt *nbPerType=0;
5852   MCAuto<DataArrayInt> tmpa=getLevArrPerCellTypes(orderBg,orderEnd,nbPerType);
5853   nbPerType->decrRef();
5854   return tmpa->buildPermArrPerLevel();
5855 }
5856
5857 /*!
5858  * This method reorganize the cells of \a this so that the cells with same geometric types are put together.
5859  * The number of cells remains unchanged after the call of this method.
5860  * This method tries to minimizes the number of needed permutations. So, this method behaves not exactly as
5861  * MEDCouplingUMesh::sortCellsInMEDFileFrmt.
5862  *
5863  * \return the array giving the correspondance old to new.
5864  */
5865 DataArrayInt *MEDCouplingUMesh::rearrange2ConsecutiveCellTypes()
5866 {
5867   checkFullyDefined();
5868   computeTypes();
5869   const int *conn=_nodal_connec->begin();
5870   const int *connI=_nodal_connec_index->begin();
5871   int nbOfCells=getNumberOfCells();
5872   std::vector<INTERP_KERNEL::NormalizedCellType> types;
5873   for(const int *i=connI;i!=connI+nbOfCells && (types.size()!=_types.size());)
5874     if(std::find(types.begin(),types.end(),(INTERP_KERNEL::NormalizedCellType)conn[*i])==types.end())
5875       {
5876         INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
5877         types.push_back(curType);
5878         for(i++;i!=connI+nbOfCells && (INTERP_KERNEL::NormalizedCellType)conn[*i]==curType;i++);
5879       }
5880   DataArrayInt *ret=DataArrayInt::New();
5881   ret->alloc(nbOfCells,1);
5882   int *retPtr=ret->getPointer();
5883   std::fill(retPtr,retPtr+nbOfCells,-1);
5884   int newCellId=0;
5885   for(std::vector<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=types.begin();iter!=types.end();iter++)
5886     {
5887       for(const int *i=connI;i!=connI+nbOfCells;i++)
5888         if((INTERP_KERNEL::NormalizedCellType)conn[*i]==(*iter))
5889           retPtr[std::distance(connI,i)]=newCellId++;
5890     }
5891   renumberCells(retPtr,false);
5892   return ret;
5893 }
5894
5895 /*!
5896  * This method splits \a this into as mush as untructured meshes that consecutive set of same type cells.
5897  * So this method has typically a sense if MEDCouplingUMesh::checkConsecutiveCellTypes has a sense.
5898  * This method makes asumption that connectivity is correctly set before calling.
5899  */
5900 std::vector<MEDCouplingUMesh *> MEDCouplingUMesh::splitByType() const
5901 {
5902   checkConnectivityFullyDefined();
5903   const int *conn=_nodal_connec->begin();
5904   const int *connI=_nodal_connec_index->begin();
5905   int nbOfCells=getNumberOfCells();
5906   std::vector<MEDCouplingUMesh *> ret;
5907   for(const int *i=connI;i!=connI+nbOfCells;)
5908     {
5909       INTERP_KERNEL::NormalizedCellType curType=(INTERP_KERNEL::NormalizedCellType)conn[*i];
5910       int beginCellId=(int)std::distance(connI,i);
5911       i=std::find_if(i+1,connI+nbOfCells,MEDCouplingImpl::ConnReader(conn,(int)curType));
5912       int endCellId=(int)std::distance(connI,i);
5913       int sz=endCellId-beginCellId;
5914       int *cells=new int[sz];
5915       for(int j=0;j<sz;j++)
5916         cells[j]=beginCellId+j;
5917       MEDCouplingUMesh *m=(MEDCouplingUMesh *)buildPartOfMySelf(cells,cells+sz,true);
5918       delete [] cells;
5919       ret.push_back(m);
5920     }
5921   return ret;
5922 }
5923
5924 /*!
5925  * This method performs the opposite operation than those in MEDCoupling1SGTUMesh::buildUnstructured.
5926  * If \a this is a single geometric type unstructured mesh, it will be converted into a more compact data structure,
5927  * MEDCoupling1GTUMesh instance. The returned instance will aggregate the same DataArrayDouble instance of coordinates than \a this.
5928  *
5929  * \return a newly allocated instance, that the caller must manage.
5930  * \throw If \a this contains more than one geometric type.
5931  * \throw If the nodal connectivity of \a this is not fully defined.
5932  * \throw If the internal data is not coherent.
5933  */
5934 MEDCoupling1GTUMesh *MEDCouplingUMesh::convertIntoSingleGeoTypeMesh() const
5935 {
5936   checkConnectivityFullyDefined();
5937   if(_types.size()!=1)
5938     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertIntoSingleGeoTypeMesh : current mesh does not contain exactly one geometric type !");
5939   INTERP_KERNEL::NormalizedCellType typ=*_types.begin();
5940   MCAuto<MEDCoupling1GTUMesh> ret=MEDCoupling1GTUMesh::New(getName(),typ);
5941   ret->setCoords(getCoords());
5942   MEDCoupling1SGTUMesh *retC=dynamic_cast<MEDCoupling1SGTUMesh *>((MEDCoupling1GTUMesh*)ret);
5943   if(retC)
5944     {
5945       MCAuto<DataArrayInt> c=convertNodalConnectivityToStaticGeoTypeMesh();
5946       retC->setNodalConnectivity(c);
5947     }
5948   else
5949     {
5950       MEDCoupling1DGTUMesh *retD=dynamic_cast<MEDCoupling1DGTUMesh *>((MEDCoupling1GTUMesh*)ret);
5951       if(!retD)
5952         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertIntoSingleGeoTypeMesh : Internal error !");
5953       DataArrayInt *c=0,*ci=0;
5954       convertNodalConnectivityToDynamicGeoTypeMesh(c,ci);
5955       MCAuto<DataArrayInt> cs(c),cis(ci);
5956       retD->setNodalConnectivity(cs,cis);
5957     }
5958   return ret.retn();
5959 }
5960
5961 DataArrayInt *MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh() const
5962 {
5963   checkConnectivityFullyDefined();
5964   if(_types.size()!=1)
5965     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh : current mesh does not contain exactly one geometric type !");
5966   INTERP_KERNEL::NormalizedCellType typ=*_types.begin();
5967   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
5968   if(cm.isDynamic())
5969     {
5970       std::ostringstream oss; oss << "MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh : this contains a single geo type (" << cm.getRepr() << ") but ";
5971       oss << "this type is dynamic ! Only static geometric type is possible for that type ! call convertNodalConnectivityToDynamicGeoTypeMesh instead !";
5972       throw INTERP_KERNEL::Exception(oss.str());
5973     }
5974   int nbCells=getNumberOfCells();
5975   int typi=(int)typ;
5976   int nbNodesPerCell=(int)cm.getNumberOfNodes();
5977   MCAuto<DataArrayInt> connOut=DataArrayInt::New(); connOut->alloc(nbCells*nbNodesPerCell,1);
5978   int *outPtr=connOut->getPointer();
5979   const int *conn=_nodal_connec->begin();
5980   const int *connI=_nodal_connec_index->begin();
5981   nbNodesPerCell++;
5982   for(int i=0;i<nbCells;i++,connI++)
5983     {
5984       if(conn[connI[0]]==typi && connI[1]-connI[0]==nbNodesPerCell)
5985         outPtr=std::copy(conn+connI[0]+1,conn+connI[1],outPtr);
5986       else
5987         {
5988           std::ostringstream oss; oss << "MEDCouplingUMesh::convertNodalConnectivityToStaticGeoTypeMesh : there something wrong in cell #" << i << " ! The type of cell is not those expected, or the length of nodal connectivity is not those expected (" << nbNodesPerCell-1 << ") !";
5989           throw INTERP_KERNEL::Exception(oss.str());
5990         }
5991     }
5992   return connOut.retn();
5993 }
5994
5995 /*!
5996  * Convert the nodal connectivity of the mesh so that all the cells are of dynamic types (polygon or quadratic
5997  * polygon). This returns the corresponding new nodal connectivity in \ref numbering-indirect format.
5998  * \param nodalConn
5999  * \param nodalConnI
6000  */
6001 void MEDCouplingUMesh::convertNodalConnectivityToDynamicGeoTypeMesh(DataArrayInt *&nodalConn, DataArrayInt *&nodalConnIndex) const
6002 {
6003   static const char msg0[]="MEDCouplingUMesh::convertNodalConnectivityToDynamicGeoTypeMesh : nodal connectivity in this are invalid ! Call checkConsistency !";
6004   checkConnectivityFullyDefined();
6005   if(_types.size()!=1)
6006     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::convertNodalConnectivityToDynamicGeoTypeMesh : current mesh does not contain exactly one geometric type !");
6007   int nbCells=getNumberOfCells(),lgth=_nodal_connec->getNumberOfTuples();
6008   if(lgth<nbCells)
6009     throw INTERP_KERNEL::Exception(msg0);
6010   MCAuto<DataArrayInt> c(DataArrayInt::New()),ci(DataArrayInt::New());
6011   c->alloc(lgth-nbCells,1); ci->alloc(nbCells+1,1);
6012   int *cp(c->getPointer()),*cip(ci->getPointer());
6013   const int *incp(_nodal_connec->begin()),*incip(_nodal_connec_index->begin());
6014   cip[0]=0;
6015   for(int i=0;i<nbCells;i++,cip++,incip++)
6016     {
6017       int strt(incip[0]+1),stop(incip[1]);//+1 to skip geo type
6018       int delta(stop-strt);
6019       if(delta>=1)
6020         {
6021           if((strt>=0 && strt<lgth) && (stop>=0 && stop<=lgth))
6022             cp=std::copy(incp+strt,incp+stop,cp);
6023           else
6024             throw INTERP_KERNEL::Exception(msg0);
6025         }
6026       else
6027         throw INTERP_KERNEL::Exception(msg0);
6028       cip[1]=cip[0]+delta;
6029     }
6030   nodalConn=c.retn(); nodalConnIndex=ci.retn();
6031 }
6032
6033 /*!
6034  * This method takes in input a vector of MEDCouplingUMesh instances lying on the same coordinates with same mesh dimensions.
6035  * Each mesh in \b ms must be sorted by type with the same order (typically using MEDCouplingUMesh::sortCellsInMEDFileFrmt).
6036  * This method is particulary useful for MED file interaction. It allows to aggregate several meshes and keeping the type sorting
6037  * and the track of the permutation by chunk of same geotype cells to retrieve it. The traditional formats old2new and new2old
6038  * are not used here to avoid the build of big permutation array.
6039  *
6040  * \param [in] ms meshes with same mesh dimension lying on the same coords and sorted by type following de the same geometric type order than
6041  *                those specified in MEDCouplingUMesh::sortCellsInMEDFileFrmt method.
6042  * \param [out] szOfCellGrpOfSameType is a newly allocated DataArrayInt instance whose number of tuples is equal to the number of chunks of same geotype
6043  *              in all meshes in \b ms. The accumulation of all values of this array is equal to the number of cells of returned mesh.
6044  * \param [out] idInMsOfCellGrpOfSameType is a newly allocated DataArrayInt instance having the same size than \b szOfCellGrpOfSameType. This
6045  *              output array gives for each chunck of same type the corresponding mesh id in \b ms.
6046  * \return A newly allocated unstructured mesh that is the result of the aggregation on same coords of all meshes in \b ms. This returned mesh
6047  *         is sorted by type following the geo cell types order of MEDCouplingUMesh::sortCellsInMEDFileFrmt method.
6048  */
6049 MEDCouplingUMesh *MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords(const std::vector<const MEDCouplingUMesh *>& ms,
6050                                                                             DataArrayInt *&szOfCellGrpOfSameType,
6051                                                                             DataArrayInt *&idInMsOfCellGrpOfSameType)
6052 {
6053   std::vector<const MEDCouplingUMesh *> ms2;
6054   for(std::vector<const MEDCouplingUMesh *>::const_iterator it=ms.begin();it!=ms.end();it++)
6055     if(*it)
6056       {
6057         (*it)->checkConnectivityFullyDefined();
6058         ms2.push_back(*it);
6059       }
6060   if(ms2.empty())
6061     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords : input vector is empty !");
6062   const DataArrayDouble *refCoo=ms2[0]->getCoords();
6063   int meshDim=ms2[0]->getMeshDimension();
6064   std::vector<const MEDCouplingUMesh *> m1ssm;
6065   std::vector< MCAuto<MEDCouplingUMesh> > m1ssmAuto;
6066   //
6067   std::vector<const MEDCouplingUMesh *> m1ssmSingle;
6068   std::vector< MCAuto<MEDCouplingUMesh> > m1ssmSingleAuto;
6069   int fake=0,rk=0;
6070   MCAuto<DataArrayInt> ret1(DataArrayInt::New()),ret2(DataArrayInt::New());
6071   ret1->alloc(0,1); ret2->alloc(0,1);
6072   for(std::vector<const MEDCouplingUMesh *>::const_iterator it=ms2.begin();it!=ms2.end();it++,rk++)
6073     {
6074       if(meshDim!=(*it)->getMeshDimension())
6075         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords : meshdims mismatch !");
6076       if(refCoo!=(*it)->getCoords())
6077         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::AggregateSortedByTypeMeshesOnSameCoords : meshes are not shared by a single coordinates coords !");
6078       std::vector<MEDCouplingUMesh *> sp=(*it)->splitByType();
6079       std::copy(sp.begin(),sp.end(),std::back_insert_iterator< std::vector<const MEDCouplingUMesh *> >(m1ssm));
6080       std::copy(sp.begin(),sp.end(),std::back_insert_iterator< std::vector<MCAuto<MEDCouplingUMesh> > >(m1ssmAuto));
6081       for(std::vector<MEDCouplingUMesh *>::const_iterator it2=sp.begin();it2!=sp.end();it2++)
6082         {
6083           MEDCouplingUMesh *singleCell=static_cast<MEDCouplingUMesh *>((*it2)->buildPartOfMySelf(&fake,&fake+1,true));
6084           m1ssmSingleAuto.push_back(singleCell);
6085           m1ssmSingle.push_back(singleCell);
6086           ret1->pushBackSilent((*it2)->getNumberOfCells()); ret2->pushBackSilent(rk);
6087         }
6088     }
6089   MCAuto<MEDCouplingUMesh> m1ssmSingle2=MEDCouplingUMesh::MergeUMeshesOnSameCoords(m1ssmSingle);
6090   MCAuto<DataArrayInt> renum=m1ssmSingle2->sortCellsInMEDFileFrmt();
6091   std::vector<const MEDCouplingUMesh *> m1ssmfinal(m1ssm.size());
6092   for(std::size_t i=0;i<m1ssm.size();i++)
6093     m1ssmfinal[renum->getIJ(i,0)]=m1ssm[i];
6094   MCAuto<MEDCouplingUMesh> ret0=MEDCouplingUMesh::MergeUMeshesOnSameCoords(m1ssmfinal);
6095   szOfCellGrpOfSameType=ret1->renumber(renum->begin());
6096   idInMsOfCellGrpOfSameType=ret2->renumber(renum->begin());
6097   return ret0.retn();
6098 }
6099
6100 /*!
6101  * This method returns a newly created DataArrayInt instance.
6102  * This method retrieves cell ids in [ \a begin, \a end ) that have the type \a type.
6103  */
6104 DataArrayInt *MEDCouplingUMesh::keepCellIdsByType(INTERP_KERNEL::NormalizedCellType type, const int *begin, const int *end) const
6105 {
6106   checkFullyDefined();
6107   const int *conn=_nodal_connec->begin();
6108   const int *connIndex=_nodal_connec_index->begin();
6109   MCAuto<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(0,1);
6110   for(const int *w=begin;w!=end;w++)
6111     if((INTERP_KERNEL::NormalizedCellType)conn[connIndex[*w]]==type)
6112       ret->pushBackSilent(*w);
6113   return ret.retn();
6114 }
6115
6116 /*!
6117  * This method makes the assumption that da->getNumberOfTuples()<this->getNumberOfCells(). This method makes the assumption that ids contained in 'da'
6118  * are in [0:getNumberOfCells())
6119  */
6120 DataArrayInt *MEDCouplingUMesh::convertCellArrayPerGeoType(const DataArrayInt *da) const
6121 {
6122   checkFullyDefined();
6123   const int *conn=_nodal_connec->begin();
6124   const int *connI=_nodal_connec_index->begin();
6125   int nbOfCells=getNumberOfCells();
6126   std::set<INTERP_KERNEL::NormalizedCellType> types(getAllGeoTypes());
6127   int *tmp=new int[nbOfCells];
6128   for(std::set<INTERP_KERNEL::NormalizedCellType>::const_iterator iter=types.begin();iter!=types.end();iter++)
6129     {
6130       int j=0;
6131       for(const int *i=connI;i!=connI+nbOfCells;i++)
6132         if((INTERP_KERNEL::NormalizedCellType)conn[*i]==(*iter))
6133           tmp[std::distance(connI,i)]=j++;
6134     }
6135   DataArrayInt *ret=DataArrayInt::New();
6136   ret->alloc(da->getNumberOfTuples(),da->getNumberOfComponents());
6137   ret->copyStringInfoFrom(*da);
6138   int *retPtr=ret->getPointer();
6139   const int *daPtr=da->begin();
6140   int nbOfElems=da->getNbOfElems();
6141   for(int k=0;k<nbOfElems;k++)
6142     retPtr[k]=tmp[daPtr[k]];
6143   delete [] tmp;
6144   return ret;
6145 }
6146
6147 /*!
6148  * This method reduced number of cells of this by keeping cells whose type is different from 'type' and if type=='type'
6149  * This method \b works \b for mesh sorted by type.
6150  * cells whose ids is in 'idsPerGeoType' array.
6151  * This method conserves coords and name of mesh.
6152  */
6153 MEDCouplingUMesh *MEDCouplingUMesh::keepSpecifiedCells(INTERP_KERNEL::NormalizedCellType type, const int *idsPerGeoTypeBg, const int *idsPerGeoTypeEnd) const
6154 {
6155   std::vector<int> code=getDistributionOfTypes();
6156   std::size_t nOfTypesInThis=code.size()/3;
6157   int sz=0,szOfType=0;
6158   for(std::size_t i=0;i<nOfTypesInThis;i++)
6159     {
6160       if(code[3*i]!=type)
6161         sz+=code[3*i+1];
6162       else
6163         szOfType=code[3*i+1];
6164     }
6165   for(const int *work=idsPerGeoTypeBg;work!=idsPerGeoTypeEnd;work++)
6166     if(*work<0 || *work>=szOfType)
6167       {
6168         std::ostringstream oss; oss << "MEDCouplingUMesh::keepSpecifiedCells : Request on type " << type << " at place #" << std::distance(idsPerGeoTypeBg,work) << " value " << *work;
6169         oss << ". It should be in [0," << szOfType << ") !";
6170         throw INTERP_KERNEL::Exception(oss.str());
6171       }
6172   MCAuto<DataArrayInt> idsTokeep=DataArrayInt::New(); idsTokeep->alloc(sz+(int)std::distance(idsPerGeoTypeBg,idsPerGeoTypeEnd),1);
6173   int *idsPtr=idsTokeep->getPointer();
6174   int offset=0;
6175   for(std::size_t i=0;i<nOfTypesInThis;i++)
6176     {
6177       if(code[3*i]!=type)
6178         for(int j=0;j<code[3*i+1];j++)
6179           *idsPtr++=offset+j;
6180       else
6181         idsPtr=std::transform(idsPerGeoTypeBg,idsPerGeoTypeEnd,idsPtr,std::bind2nd(std::plus<int>(),offset));
6182       offset+=code[3*i+1];
6183     }
6184   MCAuto<MEDCouplingUMesh> ret=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf(idsTokeep->begin(),idsTokeep->end(),true));
6185   ret->copyTinyInfoFrom(this);
6186   return ret.retn();
6187 }
6188
6189 /*!
6190  * This method returns a vector of size 'this->getNumberOfCells()'.
6191  * This method retrieves for each cell in \a this if it is linear (false) or quadratic(true).
6192  */
6193 std::vector<bool> MEDCouplingUMesh::getQuadraticStatus() const
6194 {
6195   int ncell=getNumberOfCells();
6196   std::vector<bool> ret(ncell);
6197   const int *cI=getNodalConnectivityIndex()->begin();
6198   const int *c=getNodalConnectivity()->begin();
6199   for(int i=0;i<ncell;i++)
6200     {
6201       INTERP_KERNEL::NormalizedCellType typ=(INTERP_KERNEL::NormalizedCellType)c[cI[i]];
6202       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(typ);
6203       ret[i]=cm.isQuadratic();
6204     }
6205   return ret;
6206 }
6207
6208 /*!
6209  * Returns a newly created mesh (with ref count ==1) that contains merge of \a this and \a other.
6210  */
6211 MEDCouplingMesh *MEDCouplingUMesh::mergeMyselfWith(const MEDCouplingMesh *other) const
6212 {
6213   if(other->getType()!=UNSTRUCTURED)
6214     throw INTERP_KERNEL::Exception("Merge of umesh only available with umesh each other !");
6215   const MEDCouplingUMesh *otherC=static_cast<const MEDCouplingUMesh *>(other);
6216   return MergeUMeshes(this,otherC);
6217 }
6218
6219 /*!
6220  * Returns a new DataArrayDouble holding barycenters of all cells. The barycenter is
6221  * computed by averaging coordinates of cell nodes, so this method is not a right
6222  * choice for degnerated meshes (not well oriented, cells with measure close to zero).
6223  *  \return DataArrayDouble * - a new instance of DataArrayDouble, of size \a
6224  *          this->getNumberOfCells() tuples per \a this->getSpaceDimension()
6225  *          components. The caller is to delete this array using decrRef() as it is
6226  *          no more needed.
6227  *  \throw If the coordinates array is not set.
6228  *  \throw If the nodal connectivity of cells is not defined.
6229  *  \sa MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell
6230  */
6231 DataArrayDouble *MEDCouplingUMesh::computeCellCenterOfMass() const
6232 {
6233   MCAuto<DataArrayDouble> ret=DataArrayDouble::New();
6234   int spaceDim=getSpaceDimension();
6235   int nbOfCells=getNumberOfCells();
6236   ret->alloc(nbOfCells,spaceDim);
6237   ret->copyStringInfoFrom(*getCoords());
6238   double *ptToFill=ret->getPointer();
6239   const int *nodal=_nodal_connec->begin();
6240   const int *nodalI=_nodal_connec_index->begin();
6241   const double *coor=_coords->begin();
6242   for(int i=0;i<nbOfCells;i++)
6243     {
6244       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)nodal[nodalI[i]];
6245       INTERP_KERNEL::computeBarycenter2<int,INTERP_KERNEL::ALL_C_MODE>(type,nodal+nodalI[i]+1,nodalI[i+1]-nodalI[i]-1,coor,spaceDim,ptToFill);
6246       ptToFill+=spaceDim;
6247     }
6248   return ret.retn();
6249 }
6250
6251 /*!
6252  * This method computes for each cell in \a this, the location of the iso barycenter of nodes constituting
6253  * the cell. Contrary to badly named MEDCouplingUMesh::computeCellCenterOfMass method that returns the center of inertia of the 
6254  * 
6255  * \return a newly allocated DataArrayDouble instance that the caller has to deal with. The returned 
6256  *          DataArrayDouble instance will have \c this->getNumberOfCells() tuples and \c this->getSpaceDimension() components.
6257  * 
6258  * \sa MEDCouplingUMesh::computeCellCenterOfMass
6259  * \throw If \a this is not fully defined (coordinates and connectivity)
6260  * \throw If there is presence in nodal connectivity in \a this of node ids not in [0, \c this->getNumberOfNodes() )
6261  */
6262 DataArrayDouble *MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell() const
6263 {
6264   checkFullyDefined();
6265   MCAuto<DataArrayDouble> ret=DataArrayDouble::New();
6266   int spaceDim=getSpaceDimension();
6267   int nbOfCells=getNumberOfCells();
6268   int nbOfNodes=getNumberOfNodes();
6269   ret->alloc(nbOfCells,spaceDim);
6270   double *ptToFill=ret->getPointer();
6271   const int *nodal=_nodal_connec->begin();
6272   const int *nodalI=_nodal_connec_index->begin();
6273   const double *coor=_coords->begin();
6274   for(int i=0;i<nbOfCells;i++,ptToFill+=spaceDim)
6275     {
6276       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)nodal[nodalI[i]];
6277       std::fill(ptToFill,ptToFill+spaceDim,0.);
6278       if(type!=INTERP_KERNEL::NORM_POLYHED)
6279         {
6280           for(const int *conn=nodal+nodalI[i]+1;conn!=nodal+nodalI[i+1];conn++)
6281             {
6282               if(*conn>=0 && *conn<nbOfNodes)
6283                 std::transform(coor+spaceDim*conn[0],coor+spaceDim*(conn[0]+1),ptToFill,ptToFill,std::plus<double>());
6284               else
6285                 {
6286                   std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on cell #" << i << " presence of nodeId #" << *conn << " should be in [0," <<   nbOfNodes << ") !";
6287                   throw INTERP_KERNEL::Exception(oss.str());
6288                 }
6289             }
6290           int nbOfNodesInCell=nodalI[i+1]-nodalI[i]-1;
6291           if(nbOfNodesInCell>0)
6292             std::transform(ptToFill,ptToFill+spaceDim,ptToFill,std::bind2nd(std::multiplies<double>(),1./(double)nbOfNodesInCell));
6293           else
6294             {
6295               std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on cell #" << i << " presence of cell with no nodes !";
6296               throw INTERP_KERNEL::Exception(oss.str());
6297             }
6298         }
6299       else
6300         {
6301           std::set<int> s(nodal+nodalI[i]+1,nodal+nodalI[i+1]);
6302           s.erase(-1);
6303           for(std::set<int>::const_iterator it=s.begin();it!=s.end();it++)
6304             {
6305               if(*it>=0 && *it<nbOfNodes)
6306                 std::transform(coor+spaceDim*(*it),coor+spaceDim*((*it)+1),ptToFill,ptToFill,std::plus<double>());
6307               else
6308                 {
6309                   std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on cell polyhedron cell #" << i << " presence of nodeId #" << *it << " should be in [0," <<   nbOfNodes << ") !";
6310                   throw INTERP_KERNEL::Exception(oss.str());
6311                 }
6312             }
6313           if(!s.empty())
6314             std::transform(ptToFill,ptToFill+spaceDim,ptToFill,std::bind2nd(std::multiplies<double>(),1./(double)s.size()));
6315           else
6316             {
6317               std::ostringstream oss; oss << "MEDCouplingUMesh::computeIsoBarycenterOfNodesPerCell : on polyhedron cell #" << i << " there are no nodes !";
6318               throw INTERP_KERNEL::Exception(oss.str());
6319             }
6320         }
6321     }
6322   return ret.retn();
6323 }
6324
6325 /*!
6326  * Returns a new DataArrayDouble holding barycenters of specified cells. The
6327  * barycenter is computed by averaging coordinates of cell nodes. The cells to treat
6328  * are specified via an array of cell ids. 
6329  *  \warning Validity of the specified cell ids is not checked! 
6330  *           Valid range is [ 0, \a this->getNumberOfCells() ).
6331  *  \param [in] begin - an array of cell ids of interest.
6332  *  \param [in] end - the end of \a begin, i.e. a pointer to its (last+1)-th element.
6333  *  \return DataArrayDouble * - a new instance of DataArrayDouble, of size ( \a
6334  *          end - \a begin ) tuples per \a this->getSpaceDimension() components. The
6335  *          caller is to delete this array using decrRef() as it is no more needed. 
6336  *  \throw If the coordinates array is not set.
6337  *  \throw If the nodal connectivity of cells is not defined.
6338  *
6339  *  \if ENABLE_EXAMPLES
6340  *  \ref cpp_mcumesh_getPartBarycenterAndOwner "Here is a C++ example".<br>
6341  *  \ref  py_mcumesh_getPartBarycenterAndOwner "Here is a Python example".
6342  *  \endif
6343  */
6344 DataArrayDouble *MEDCouplingUMesh::getPartBarycenterAndOwner(const int *begin, const int *end) const
6345 {
6346   DataArrayDouble *ret=DataArrayDouble::New();
6347   int spaceDim=getSpaceDimension();
6348   int nbOfTuple=(int)std::distance(begin,end);
6349   ret->alloc(nbOfTuple,spaceDim);
6350   double *ptToFill=ret->getPointer();
6351   double *tmp=new double[spaceDim];
6352   const int *nodal=_nodal_connec->begin();
6353   const int *nodalI=_nodal_connec_index->begin();
6354   const double *coor=_coords->begin();
6355   for(const int *w=begin;w!=end;w++)
6356     {
6357       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)nodal[nodalI[*w]];
6358       INTERP_KERNEL::computeBarycenter2<int,INTERP_KERNEL::ALL_C_MODE>(type,nodal+nodalI[*w]+1,nodalI[*w+1]-nodalI[*w]-1,coor,spaceDim,ptToFill);
6359       ptToFill+=spaceDim;
6360     }
6361   delete [] tmp;
6362   return ret;
6363 }
6364
6365 /*!
6366  * Returns a DataArrayDouble instance giving for each cell in \a this the equation of plane given by "a*X+b*Y+c*Z+d=0".
6367  * So the returned instance will have 4 components and \c this->getNumberOfCells() tuples.
6368  * So this method expects that \a this has a spaceDimension equal to 3 and meshDimension equal to 2.
6369  * The computation of the plane equation is done using each time the 3 first nodes of 2D cells.
6370  * This method is useful to detect 2D cells in 3D space that are not coplanar.
6371  * 
6372  * \return DataArrayDouble * - a new instance of DataArrayDouble having 4 components and a number of tuples equal to number of cells in \a this.
6373  * \throw If spaceDim!=3 or meshDim!=2.
6374  * \throw If connectivity of \a this is invalid.
6375  * \throw If connectivity of a cell in \a this points to an invalid node.
6376  */
6377 DataArrayDouble *MEDCouplingUMesh::computePlaneEquationOf3DFaces() const
6378 {
6379   MCAuto<DataArrayDouble> ret(DataArrayDouble::New());
6380   int nbOfCells(getNumberOfCells()),nbOfNodes(getNumberOfNodes());
6381   if(getSpaceDimension()!=3 || getMeshDimension()!=2)
6382     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::computePlaneEquationOf3DFaces : This method must be applied on a mesh having meshDimension equal 2 and a spaceDimension equal to 3 !");
6383   ret->alloc(nbOfCells,4);
6384   double *retPtr(ret->getPointer());
6385   const int *nodal(_nodal_connec->begin()),*nodalI(_nodal_connec_index->begin());
6386   const double *coor(_coords->begin());
6387   for(int i=0;i<nbOfCells;i++,nodalI++,retPtr+=4)
6388     {
6389       double matrix[16]={0,0,0,1,0,0,0,1,0,0,0,1,1,1,1,0},matrix2[16];
6390       if(nodalI[1]-nodalI[0]>=3)
6391         {
6392           for(int j=0;j<3;j++)
6393             {
6394               int nodeId(nodal[nodalI[0]+1+j]);
6395               if(nodeId>=0 && nodeId<nbOfNodes)
6396                 std::copy(coor+nodeId*3,coor+(nodeId+1)*3,matrix+4*j);
6397               else
6398                 {
6399                   std::ostringstream oss; oss << "MEDCouplingUMesh::computePlaneEquationOf3DFaces : invalid 2D cell #" << i << " ! This cell points to an invalid nodeId : " << nodeId << " !";
6400                   throw INTERP_KERNEL::Exception(oss.str());
6401                 }
6402             }
6403         }
6404       else
6405         {
6406           std::ostringstream oss; oss << "MEDCouplingUMesh::computePlaneEquationOf3DFaces : invalid 2D cell #" << i << " ! Must be constitued by more than 3 nodes !";
6407           throw INTERP_KERNEL::Exception(oss.str());
6408         }
6409       INTERP_KERNEL::inverseMatrix(matrix,4,matrix2);
6410       retPtr[0]=matrix2[3]; retPtr[1]=matrix2[7]; retPtr[2]=matrix2[11]; retPtr[3]=matrix2[15];
6411     }
6412   return ret.retn();
6413 }
6414
6415 /*!
6416  * This method expects as input a DataArrayDouble non nul instance 'da' that should be allocated. If not an exception is thrown.
6417  * 
6418  */
6419 MEDCouplingUMesh *MEDCouplingUMesh::Build0DMeshFromCoords(DataArrayDouble *da)
6420 {
6421   if(!da)
6422     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Build0DMeshFromCoords : instance of DataArrayDouble must be not null !");
6423   da->checkAllocated();
6424   std::string name(da->getName());
6425   MCAuto<MEDCouplingUMesh> ret(MEDCouplingUMesh::New(name,0));
6426   if(name.empty())
6427     ret->setName("Mesh");
6428   ret->setCoords(da);
6429   int nbOfTuples(da->getNumberOfTuples());
6430   MCAuto<DataArrayInt> c(DataArrayInt::New()),cI(DataArrayInt::New());
6431   c->alloc(2*nbOfTuples,1);
6432   cI->alloc(nbOfTuples+1,1);
6433   int *cp(c->getPointer()),*cip(cI->getPointer());
6434   *cip++=0;
6435   for(int i=0;i<nbOfTuples;i++)
6436     {
6437       *cp++=INTERP_KERNEL::NORM_POINT1;
6438       *cp++=i;
6439       *cip++=2*(i+1);
6440     }
6441   ret->setConnectivity(c,cI,true);
6442   return ret.retn();
6443 }
6444
6445 MCAuto<MEDCouplingUMesh> MEDCouplingUMesh::Build1DMeshFromCoords(DataArrayDouble *da)
6446 {
6447   if(!da)
6448     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Build01MeshFromCoords : instance of DataArrayDouble must be not null !");
6449   da->checkAllocated();
6450   std::string name(da->getName());
6451   MCAuto<MEDCouplingUMesh> ret;
6452   {
6453     MCAuto<MEDCouplingCMesh> tmp(MEDCouplingCMesh::New());
6454     MCAuto<DataArrayDouble> arr(DataArrayDouble::New());
6455     arr->alloc(da->getNumberOfTuples());
6456     tmp->setCoordsAt(0,arr);
6457     ret=tmp->buildUnstructured();
6458   }
6459   ret->setCoords(da);
6460   if(name.empty())
6461     ret->setName("Mesh");
6462   else
6463     ret->setName(name);
6464   return ret;
6465 }
6466
6467 /*!
6468  * Creates a new MEDCouplingUMesh by concatenating two given meshes of the same dimension.
6469  * Cells and nodes of
6470  * the first mesh precede cells and nodes of the second mesh within the result mesh.
6471  *  \param [in] mesh1 - the first mesh.
6472  *  \param [in] mesh2 - the second mesh.
6473  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
6474  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
6475  *          is no more needed.
6476  *  \throw If \a mesh1 == NULL or \a mesh2 == NULL.
6477  *  \throw If the coordinates array is not set in none of the meshes.
6478  *  \throw If \a mesh1->getMeshDimension() < 0 or \a mesh2->getMeshDimension() < 0.
6479  *  \throw If \a mesh1->getMeshDimension() != \a mesh2->getMeshDimension().
6480  */
6481 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshes(const MEDCouplingUMesh *mesh1, const MEDCouplingUMesh *mesh2)
6482 {
6483   std::vector<const MEDCouplingUMesh *> tmp(2);
6484   tmp[0]=const_cast<MEDCouplingUMesh *>(mesh1); tmp[1]=const_cast<MEDCouplingUMesh *>(mesh2);
6485   return MergeUMeshes(tmp);
6486 }
6487
6488 /*!
6489  * Creates a new MEDCouplingUMesh by concatenating all given meshes of the same dimension.
6490  * Cells and nodes of
6491  * the *i*-th mesh precede cells and nodes of the (*i*+1)-th mesh within the result mesh.
6492  *  \param [in] a - a vector of meshes (MEDCouplingUMesh) to concatenate.
6493  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
6494  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
6495  *          is no more needed.
6496  *  \throw If \a a.size() == 0.
6497  *  \throw If \a a[ *i* ] == NULL.
6498  *  \throw If the coordinates array is not set in none of the meshes.
6499  *  \throw If \a a[ *i* ]->getMeshDimension() < 0.
6500  *  \throw If the meshes in \a a are of different dimension (getMeshDimension()).
6501  */
6502 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshes(const std::vector<const MEDCouplingUMesh *>& a)
6503 {
6504   std::size_t sz=a.size();
6505   if(sz==0)
6506     return MergeUMeshesLL(a);
6507   for(std::size_t ii=0;ii<sz;ii++)
6508     if(!a[ii])
6509       {
6510         std::ostringstream oss; oss << "MEDCouplingUMesh::MergeUMeshes : item #" << ii << " in input array of size "<< sz << " is empty !";
6511         throw INTERP_KERNEL::Exception(oss.str());
6512       }
6513   std::vector< MCAuto<MEDCouplingUMesh> > bb(sz);
6514   std::vector< const MEDCouplingUMesh * > aa(sz);
6515   int spaceDim=-3;
6516   for(std::size_t i=0;i<sz && spaceDim==-3;i++)
6517     {
6518       const MEDCouplingUMesh *cur=a[i];
6519       const DataArrayDouble *coo=cur->getCoords();
6520       if(coo)
6521         spaceDim=coo->getNumberOfComponents();
6522     }
6523   if(spaceDim==-3)
6524     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::MergeUMeshes : no spaceDim specified ! unable to perform merge !");
6525   for(std::size_t i=0;i<sz;i++)
6526     {
6527       bb[i]=a[i]->buildSetInstanceFromThis(spaceDim);
6528       aa[i]=bb[i];
6529     }
6530   return MergeUMeshesLL(aa);
6531 }
6532
6533 /*!
6534  * Creates a new MEDCouplingUMesh by concatenating cells of two given meshes of same
6535  * dimension and sharing the node coordinates array.
6536  * All cells of the first mesh precede all cells of the second mesh
6537  * within the result mesh.
6538  *  \param [in] mesh1 - the first mesh.
6539  *  \param [in] mesh2 - the second mesh.
6540  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
6541  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
6542  *          is no more needed.
6543  *  \throw If \a mesh1 == NULL or \a mesh2 == NULL.
6544  *  \throw If the meshes do not share the node coordinates array.
6545  *  \throw If \a mesh1->getMeshDimension() < 0 or \a mesh2->getMeshDimension() < 0.
6546  *  \throw If \a mesh1->getMeshDimension() != \a mesh2->getMeshDimension().
6547  */
6548 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshesOnSameCoords(const MEDCouplingUMesh *mesh1, const MEDCouplingUMesh *mesh2)
6549 {
6550   std::vector<const MEDCouplingUMesh *> tmp(2);
6551   tmp[0]=mesh1; tmp[1]=mesh2;
6552   return MergeUMeshesOnSameCoords(tmp);
6553 }
6554
6555 /*!
6556  * Creates a new MEDCouplingUMesh by concatenating cells of all given meshes of same
6557  * dimension and sharing the node coordinates array.
6558  * All cells of the *i*-th mesh precede all cells of the
6559  * (*i*+1)-th mesh within the result mesh.
6560  *  \param [in] meshes - a vector of meshes (MEDCouplingUMesh) to concatenate.
6561  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
6562  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
6563  *          is no more needed.
6564  *  \throw If \a a.size() == 0.
6565  *  \throw If \a a[ *i* ] == NULL.
6566  *  \throw If the meshes do not share the node coordinates array.
6567  *  \throw If \a a[ *i* ]->getMeshDimension() < 0.
6568  *  \throw If the meshes in \a a are of different dimension (getMeshDimension()).
6569  */
6570 MEDCouplingUMesh *MEDCouplingUMesh::MergeUMeshesOnSameCoords(const std::vector<const MEDCouplingUMesh *>& meshes)
6571 {
6572   if(meshes.empty())
6573     throw INTERP_KERNEL::Exception("meshes input parameter is expected to be non empty.");
6574   for(std::size_t ii=0;ii<meshes.size();ii++)
6575     if(!meshes[ii])
6576       {
6577         std::ostringstream oss; oss << "MEDCouplingUMesh::MergeUMeshesOnSameCoords : item #" << ii << " in input array of size "<< meshes.size() << " is empty !";
6578         throw INTERP_KERNEL::Exception(oss.str());
6579       }
6580   const DataArrayDouble *coords=meshes.front()->getCoords();
6581   int meshDim=meshes.front()->getMeshDimension();
6582   std::vector<const MEDCouplingUMesh *>::const_iterator iter=meshes.begin();
6583   int meshLgth=0;
6584   int meshIndexLgth=0;
6585   for(;iter!=meshes.end();iter++)
6586     {
6587       if(coords!=(*iter)->getCoords())
6588         throw INTERP_KERNEL::Exception("meshes does not share the same coords ! Try using tryToShareSameCoords method !");
6589       if(meshDim!=(*iter)->getMeshDimension())
6590         throw INTERP_KERNEL::Exception("Mesh dimensions mismatches, FuseUMeshesOnSameCoords impossible !");
6591       meshLgth+=(*iter)->getNodalConnectivityArrayLen();
6592       meshIndexLgth+=(*iter)->getNumberOfCells();
6593     }
6594   MCAuto<DataArrayInt> nodal=DataArrayInt::New();
6595   nodal->alloc(meshLgth,1);
6596   int *nodalPtr=nodal->getPointer();
6597   MCAuto<DataArrayInt> nodalIndex=DataArrayInt::New();
6598   nodalIndex->alloc(meshIndexLgth+1,1);
6599   int *nodalIndexPtr=nodalIndex->getPointer();
6600   int offset=0;
6601   for(iter=meshes.begin();iter!=meshes.end();iter++)
6602     {
6603       const int *nod=(*iter)->getNodalConnectivity()->begin();
6604       const int *index=(*iter)->getNodalConnectivityIndex()->begin();
6605       int nbOfCells=(*iter)->getNumberOfCells();
6606       int meshLgth2=(*iter)->getNodalConnectivityArrayLen();
6607       nodalPtr=std::copy(nod,nod+meshLgth2,nodalPtr);
6608       if(iter!=meshes.begin())
6609         nodalIndexPtr=std::transform(index+1,index+nbOfCells+1,nodalIndexPtr,std::bind2nd(std::plus<int>(),offset));
6610       else
6611         nodalIndexPtr=std::copy(index,index+nbOfCells+1,nodalIndexPtr);
6612       offset+=meshLgth2;
6613     }
6614   MEDCouplingUMesh *ret=MEDCouplingUMesh::New();
6615   ret->setName("merge");
6616   ret->setMeshDimension(meshDim);
6617   ret->setConnectivity(nodal,nodalIndex,true);
6618   ret->setCoords(coords);
6619   return ret;
6620 }
6621
6622 /*!
6623  * Creates a new MEDCouplingUMesh by concatenating cells of all given meshes of same
6624  * dimension and sharing the node coordinates array. Cells of the *i*-th mesh precede
6625  * cells of the (*i*+1)-th mesh within the result mesh. Duplicates of cells are
6626  * removed from \a this mesh and arrays mapping between new and old cell ids in "Old to
6627  * New" mode are returned for each input mesh.
6628  *  \param [in] meshes - a vector of meshes (MEDCouplingUMesh) to concatenate.
6629  *  \param [in] compType - specifies a cell comparison technique. For meaning of its
6630  *          valid values [0,1,2], see zipConnectivityTraducer().
6631  *  \param [in,out] corr - an array of DataArrayInt, of the same size as \a
6632  *          meshes. The *i*-th array describes cell ids mapping for \a meshes[ *i* ]
6633  *          mesh. The caller is to delete each of the arrays using decrRef() as it is
6634  *          no more needed.
6635  *  \return MEDCouplingUMesh * - the result mesh. It is a new instance of
6636  *          MEDCouplingUMesh. The caller is to delete this mesh using decrRef() as it
6637  *          is no more needed.
6638  *  \throw If \a meshes.size() == 0.
6639  *  \throw If \a meshes[ *i* ] == NULL.
6640  *  \throw If the meshes do not share the node coordinates array.
6641  *  \throw If \a meshes[ *i* ]->getMeshDimension() < 0.
6642  *  \throw If the \a meshes are of different dimension (getMeshDimension()).
6643  *  \throw If the nodal connectivity of cells of any of \a meshes is not defined.
6644  *  \throw If the nodal connectivity any of \a meshes includes an invalid id.
6645  */
6646 MEDCouplingUMesh *MEDCouplingUMesh::FuseUMeshesOnSameCoords(const std::vector<const MEDCouplingUMesh *>& meshes, int compType, std::vector<DataArrayInt *>& corr)
6647 {
6648   //All checks are delegated to MergeUMeshesOnSameCoords
6649   MCAuto<MEDCouplingUMesh> ret=MergeUMeshesOnSameCoords(meshes);
6650   MCAuto<DataArrayInt> o2n=ret->zipConnectivityTraducer(compType);
6651   corr.resize(meshes.size());
6652   std::size_t nbOfMeshes=meshes.size();
6653   int offset=0;
6654   const int *o2nPtr=o2n->begin();
6655   for(std::size_t i=0;i<nbOfMeshes;i++)
6656     {
6657       DataArrayInt *tmp=DataArrayInt::New();
6658       int curNbOfCells=meshes[i]->getNumberOfCells();
6659       tmp->alloc(curNbOfCells,1);
6660       std::copy(o2nPtr+offset,o2nPtr+offset+curNbOfCells,tmp->getPointer());
6661       offset+=curNbOfCells;
6662       tmp->setName(meshes[i]->getName());
6663       corr[i]=tmp;
6664     }
6665   return ret.retn();
6666 }
6667
6668 /*!
6669  * Makes all given meshes share the nodal connectivity array. The common connectivity
6670  * array is created by concatenating the connectivity arrays of all given meshes. All
6671  * the given meshes must be of the same space dimension but dimension of cells **can
6672  * differ**. This method is particulary useful in MEDLoader context to build a \ref
6673  * MEDCoupling::MEDFileUMesh "MEDFileUMesh" instance that expects that underlying
6674  * MEDCouplingUMesh'es of different dimension share the same nodal connectivity array.
6675  *  \param [in,out] meshes - a vector of meshes to update.
6676  *  \throw If any of \a meshes is NULL.
6677  *  \throw If the coordinates array is not set in any of \a meshes.
6678  *  \throw If the nodal connectivity of cells is not defined in any of \a meshes.
6679  *  \throw If \a meshes are of different space dimension.
6680  */
6681 void MEDCouplingUMesh::PutUMeshesOnSameAggregatedCoords(const std::vector<MEDCouplingUMesh *>& meshes)
6682 {
6683   std::size_t sz=meshes.size();
6684   if(sz==0 || sz==1)
6685     return;
6686   std::vector< const DataArrayDouble * > coords(meshes.size());
6687   std::vector< const DataArrayDouble * >::iterator it2=coords.begin();
6688   for(std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();it!=meshes.end();it++,it2++)
6689     {
6690       if((*it))
6691         {
6692           (*it)->checkConnectivityFullyDefined();
6693           const DataArrayDouble *coo=(*it)->getCoords();
6694           if(coo)
6695             *it2=coo;
6696           else
6697             {
6698               std::ostringstream oss; oss << " MEDCouplingUMesh::PutUMeshesOnSameAggregatedCoords : Item #" << std::distance(meshes.begin(),it) << " inside the vector of length " << meshes.size();
6699               oss << " has no coordinate array defined !";
6700               throw INTERP_KERNEL::Exception(oss.str());
6701             }
6702         }
6703       else
6704         {
6705           std::ostringstream oss; oss << " MEDCouplingUMesh::PutUMeshesOnSameAggregatedCoords : Item #" << std::distance(meshes.begin(),it) << " inside the vector of length " << meshes.size();
6706           oss << " is null !";
6707           throw INTERP_KERNEL::Exception(oss.str());
6708         }
6709     }
6710   MCAuto<DataArrayDouble> res=DataArrayDouble::Aggregate(coords);
6711   std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();
6712   int offset=(*it)->getNumberOfNodes();
6713   (*it++)->setCoords(res);
6714   for(;it!=meshes.end();it++)
6715     {
6716       int oldNumberOfNodes=(*it)->getNumberOfNodes();
6717       (*it)->setCoords(res);
6718       (*it)->shiftNodeNumbersInConn(offset);
6719       offset+=oldNumberOfNodes;
6720     }
6721 }
6722
6723 /*!
6724  * Merges nodes coincident with a given precision within all given meshes that share
6725  * the nodal connectivity array. The given meshes **can be of different** mesh
6726  * dimension. This method is particulary useful in MEDLoader context to build a \ref
6727  * MEDCoupling::MEDFileUMesh "MEDFileUMesh" instance that expects that underlying
6728  * MEDCouplingUMesh'es of different dimension share the same nodal connectivity array. 
6729  *  \param [in,out] meshes - a vector of meshes to update.
6730  *  \param [in] eps - the precision used to detect coincident nodes (infinite norm).
6731  *  \throw If any of \a meshes is NULL.
6732  *  \throw If the \a meshes do not share the same node coordinates array.
6733  *  \throw If the nodal connectivity of cells is not defined in any of \a meshes.
6734  */
6735 void MEDCouplingUMesh::MergeNodesOnUMeshesSharingSameCoords(const std::vector<MEDCouplingUMesh *>& meshes, double eps)
6736 {
6737   if(meshes.empty())
6738     return ;
6739   std::set<const DataArrayDouble *> s;
6740   for(std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();it!=meshes.end();it++)
6741     {
6742       if(*it)
6743         s.insert((*it)->getCoords());
6744       else
6745         {
6746           std::ostringstream oss; oss << "MEDCouplingUMesh::MergeNodesOnUMeshesSharingSameCoords : In input vector of unstructured meshes of size " << meshes.size() << " the element #" << std::distance(meshes.begin(),it) << " is null !";
6747           throw INTERP_KERNEL::Exception(oss.str());
6748         }
6749     }
6750   if(s.size()!=1)
6751     {
6752       std::ostringstream oss; oss << "MEDCouplingUMesh::MergeNodesOnUMeshesSharingSameCoords : In input vector of unstructured meshes of size " << meshes.size() << ", it appears that they do not share the same instance of DataArrayDouble for coordiantes ! tryToShareSameCoordsPermute method can help to reach that !";
6753       throw INTERP_KERNEL::Exception(oss.str());
6754     }
6755   const DataArrayDouble *coo=*(s.begin());
6756   if(!coo)
6757     return;
6758   //
6759   DataArrayInt *comm,*commI;
6760   coo->findCommonTuples(eps,-1,comm,commI);
6761   MCAuto<DataArrayInt> tmp1(comm),tmp2(commI);
6762   int oldNbOfNodes=coo->getNumberOfTuples();
6763   int newNbOfNodes;
6764   MCAuto<DataArrayInt> o2n=DataArrayInt::ConvertIndexArrayToO2N(oldNbOfNodes,comm->begin(),commI->begin(),commI->end(),newNbOfNodes);
6765   if(oldNbOfNodes==newNbOfNodes)
6766     return ;
6767   MCAuto<DataArrayDouble> newCoords=coo->renumberAndReduce(o2n->begin(),newNbOfNodes);
6768   for(std::vector<MEDCouplingUMesh *>::const_iterator it=meshes.begin();it!=meshes.end();it++)
6769     {
6770       (*it)->renumberNodesInConn(o2n->begin());
6771       (*it)->setCoords(newCoords);
6772     } 
6773 }
6774
6775
6776 /*!
6777  * This static operates only for coords in 3D. The polygon is specfied by its connectivity nodes in [ \a begin , \a end ).
6778  */
6779 bool MEDCouplingUMesh::IsPolygonWellOriented(bool isQuadratic, const double *vec, const int *begin, const int *end, const double *coords)
6780 {
6781   std::size_t i, ip1;
6782   double v[3]={0.,0.,0.};
6783   std::size_t sz=std::distance(begin,end);
6784   if(isQuadratic)
6785     sz/=2;
6786   for(i=0;i<sz;i++)
6787     {
6788       v[0]+=coords[3*begin[i]+1]*coords[3*begin[(i+1)%sz]+2]-coords[3*begin[i]+2]*coords[3*begin[(i+1)%sz]+1];
6789       v[1]+=coords[3*begin[i]+2]*coords[3*begin[(i+1)%sz]]-coords[3*begin[i]]*coords[3*begin[(i+1)%sz]+2];
6790       v[2]+=coords[3*begin[i]]*coords[3*begin[(i+1)%sz]+1]-coords[3*begin[i]+1]*coords[3*begin[(i+1)%sz]];
6791     }
6792   double ret = vec[0]*v[0]+vec[1]*v[1]+vec[2]*v[2];
6793
6794   // Try using quadratic points if standard points are degenerated (for example a QPOLYG with two
6795   // SEG3 forming a circle):
6796   if (fabs(ret) < INTERP_KERNEL::DEFAULT_ABS_TOL && isQuadratic)
6797     {
6798       v[0] = 0.0; v[1] = 0.0; v[2] = 0.0;
6799       for(std::size_t j=0;j<sz;j++)
6800         {
6801           if (j%2)  // current point i is quadratic, next point i+1 is standard
6802             {
6803               i = sz+j;
6804               ip1 = (j+1)%sz; // ip1 = "i+1"
6805             }
6806           else      // current point i is standard, next point i+1 is quadratic
6807             {
6808               i = j;
6809               ip1 = j+sz;
6810             }
6811           v[0]+=coords[3*begin[i]+1]*coords[3*begin[ip1]+2]-coords[3*begin[i]+2]*coords[3*begin[ip1]+1];
6812           v[1]+=coords[3*begin[i]+2]*coords[3*begin[ip1]]-coords[3*begin[i]]*coords[3*begin[ip1]+2];
6813           v[2]+=coords[3*begin[i]]*coords[3*begin[ip1]+1]-coords[3*begin[i]+1]*coords[3*begin[ip1]];
6814         }
6815       ret = vec[0]*v[0]+vec[1]*v[1]+vec[2]*v[2];
6816     }
6817   return (ret>0.);
6818 }
6819
6820 /*!
6821  * The polyhedron is specfied by its connectivity nodes in [ \a begin , \a end ).
6822  */
6823 bool MEDCouplingUMesh::IsPolyhedronWellOriented(const int *begin, const int *end, const double *coords)
6824 {
6825   std::vector<std::pair<int,int> > edges;
6826   std::size_t nbOfFaces=std::count(begin,end,-1)+1;
6827   const int *bgFace=begin;
6828   for(std::size_t i=0;i<nbOfFaces;i++)
6829     {
6830       const int *endFace=std::find(bgFace+1,end,-1);
6831       std::size_t nbOfEdgesInFace=std::distance(bgFace,endFace);
6832       for(std::size_t j=0;j<nbOfEdgesInFace;j++)
6833         {
6834           std::pair<int,int> p1(bgFace[j],bgFace[(j+1)%nbOfEdgesInFace]);
6835           if(std::find(edges.begin(),edges.end(),p1)!=edges.end())
6836             return false;
6837           edges.push_back(p1);
6838         }
6839       bgFace=endFace+1;
6840     }
6841   return INTERP_KERNEL::calculateVolumeForPolyh2<int,INTERP_KERNEL::ALL_C_MODE>(begin,(int)std::distance(begin,end),coords)>-EPS_FOR_POLYH_ORIENTATION;
6842 }
6843
6844 /*!
6845  * The 3D extruded static cell (PENTA6,HEXA8,HEXAGP12...) its connectivity nodes in [ \a begin , \a end ).
6846  */
6847 bool MEDCouplingUMesh::Is3DExtrudedStaticCellWellOriented(const int *begin, const int *end, const double *coords)
6848 {
6849   double vec0[3],vec1[3];
6850   std::size_t sz=std::distance(begin,end);
6851   if(sz%2!=0)
6852     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::Is3DExtrudedStaticCellWellOriented : the length of nodal connectivity of extruded cell is not even !");
6853   int nbOfNodes=(int)sz/2;
6854   INTERP_KERNEL::areaVectorOfPolygon<int,INTERP_KERNEL::ALL_C_MODE>(begin,nbOfNodes,coords,vec0);
6855   const double *pt0=coords+3*begin[0];
6856   const double *pt1=coords+3*begin[nbOfNodes];
6857   vec1[0]=pt1[0]-pt0[0]; vec1[1]=pt1[1]-pt0[1]; vec1[2]=pt1[2]-pt0[2];
6858   return (vec0[0]*vec1[0]+vec0[1]*vec1[1]+vec0[2]*vec1[2])<0.;
6859 }
6860
6861 void MEDCouplingUMesh::CorrectExtrudedStaticCell(int *begin, int *end)
6862 {
6863   std::size_t sz=std::distance(begin,end);
6864   INTERP_KERNEL::AutoPtr<int> tmp=new int[sz];
6865   std::size_t nbOfNodes(sz/2);
6866   std::copy(begin,end,(int *)tmp);
6867   for(std::size_t j=1;j<nbOfNodes;j++)
6868     {
6869       begin[j]=tmp[nbOfNodes-j];
6870       begin[j+nbOfNodes]=tmp[nbOfNodes+nbOfNodes-j];
6871     }
6872 }
6873
6874 bool MEDCouplingUMesh::IsTetra4WellOriented(const int *begin, const int *end, const double *coords)
6875 {
6876   std::size_t sz=std::distance(begin,end);
6877   if(sz!=4)
6878     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::IsTetra4WellOriented : Tetra4 cell with not 4 nodes ! Call checkConsistency !");
6879   double vec0[3],vec1[3];
6880   const double *pt0=coords+3*begin[0],*pt1=coords+3*begin[1],*pt2=coords+3*begin[2],*pt3=coords+3*begin[3];
6881   vec0[0]=pt1[0]-pt0[0]; vec0[1]=pt1[1]-pt0[1]; vec0[2]=pt1[2]-pt0[2]; vec1[0]=pt2[0]-pt0[0]; vec1[1]=pt2[1]-pt0[1]; vec1[2]=pt2[2]-pt0[2]; 
6882   return ((vec0[1]*vec1[2]-vec0[2]*vec1[1])*(pt3[0]-pt0[0])+(vec0[2]*vec1[0]-vec0[0]*vec1[2])*(pt3[1]-pt0[1])+(vec0[0]*vec1[1]-vec0[1]*vec1[0])*(pt3[2]-pt0[2]))<0;
6883 }
6884
6885 bool MEDCouplingUMesh::IsPyra5WellOriented(const int *begin, const int *end, const double *coords)
6886 {
6887   std::size_t sz=std::distance(begin,end);
6888   if(sz!=5)
6889     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::IsPyra5WellOriented : Pyra5 cell with not 5 nodes ! Call checkConsistency !");
6890   double vec0[3];
6891   INTERP_KERNEL::areaVectorOfPolygon<int,INTERP_KERNEL::ALL_C_MODE>(begin,4,coords,vec0);
6892   const double *pt0=coords+3*begin[0],*pt1=coords+3*begin[4];
6893   return (vec0[0]*(pt1[0]-pt0[0])+vec0[1]*(pt1[1]-pt0[1])+vec0[2]*(pt1[2]-pt0[2]))<0.;
6894 }
6895
6896 /*!
6897  * This method performs a simplyfication of a single polyedron cell. To do that each face of cell whose connectivity is defined by [ \b begin , \b end ) 
6898  * is compared with the others in order to find faces in the same plane (with approx of eps). If any, the cells are grouped together and projected to
6899  * a 2D space.
6900  *
6901  * \param [in] eps is a relative precision that allows to establish if some 3D plane are coplanar or not.
6902  * \param [in] coords the coordinates with nb of components exactly equal to 3
6903  * \param [in] begin begin of the nodal connectivity (geometric type included) of a single polyhedron cell
6904  * \param [in] end end of nodal connectivity of a single polyhedron cell (excluded)
6905  * \param [out] res the result is put at the end of the vector without any alteration of the data.
6906  */
6907 void MEDCouplingUMesh::SimplifyPolyhedronCell(double eps, const DataArrayDouble *coords, const int *begin, const int *end, DataArrayInt *res)
6908 {
6909   int nbFaces=std::count(begin+1,end,-1)+1;
6910   MCAuto<DataArrayDouble> v=DataArrayDouble::New(); v->alloc(nbFaces,3);
6911   double *vPtr=v->getPointer();
6912   MCAuto<DataArrayDouble> p=DataArrayDouble::New(); p->alloc(nbFaces,1);
6913   double *pPtr=p->getPointer();
6914   const int *stFaceConn=begin+1;
6915   for(int i=0;i<nbFaces;i++,vPtr+=3,pPtr++)
6916     {
6917       const int *endFaceConn=std::find(stFaceConn,end,-1);
6918       ComputeVecAndPtOfFace(eps,coords->begin(),stFaceConn,endFaceConn,vPtr,pPtr);
6919       stFaceConn=endFaceConn+1;
6920     }
6921   pPtr=p->getPointer(); vPtr=v->getPointer();
6922   DataArrayInt *comm1=0,*commI1=0;
6923   v->findCommonTuples(eps,-1,comm1,commI1);
6924   MCAuto<DataArrayInt> comm1Auto(comm1),commI1Auto(commI1);
6925   const int *comm1Ptr=comm1->begin();
6926   const int *commI1Ptr=commI1->begin();
6927   int nbOfGrps1=commI1Auto->getNumberOfTuples()-1;
6928   res->pushBackSilent((int)INTERP_KERNEL::NORM_POLYHED);
6929   //
6930   MCAuto<MEDCouplingUMesh> mm=MEDCouplingUMesh::New("",3);
6931   mm->setCoords(const_cast<DataArrayDouble *>(coords)); mm->allocateCells(1); mm->insertNextCell(INTERP_KERNEL::NORM_POLYHED,(int)std::distance(begin+1,end),begin+1);
6932   mm->finishInsertingCells();
6933   //
6934   for(int i=0;i<nbOfGrps1;i++)
6935     {
6936       int vecId=comm1Ptr[commI1Ptr[i]];
6937       MCAuto<DataArrayDouble> tmpgrp2=p->selectByTupleId(comm1Ptr+commI1Ptr[i],comm1Ptr+commI1Ptr[i+1]);
6938       DataArrayInt *comm2=0,*commI2=0;
6939       tmpgrp2->findCommonTuples(eps,-1,comm2,commI2);
6940       MCAuto<DataArrayInt> comm2Auto(comm2),commI2Auto(commI2);
6941       const int *comm2Ptr=comm2->begin();
6942       const int *commI2Ptr=commI2->begin();
6943       int nbOfGrps2=commI2Auto->getNumberOfTuples()-1;
6944       for(int j=0;j<nbOfGrps2;j++)
6945         {
6946           if(commI2Ptr[j+1]-commI2Ptr[j]<=1)
6947             {
6948               res->insertAtTheEnd(begin,end);
6949               res->pushBackSilent(-1);
6950             }
6951           else
6952             {
6953               int pointId=comm1Ptr[commI1Ptr[i]+comm2Ptr[commI2Ptr[j]]];
6954               MCAuto<DataArrayInt> ids2=comm2->selectByTupleIdSafeSlice(commI2Ptr[j],commI2Ptr[j+1],1);
6955               ids2->transformWithIndArr(comm1Ptr+commI1Ptr[i],comm1Ptr+commI1Ptr[i+1]);
6956               DataArrayInt *tmp0=DataArrayInt::New(),*tmp1=DataArrayInt::New(),*tmp2=DataArrayInt::New(),*tmp3=DataArrayInt::New();
6957               MCAuto<MEDCouplingUMesh> mm2=mm->buildDescendingConnectivity(tmp0,tmp1,tmp2,tmp3); tmp0->decrRef(); tmp1->decrRef(); tmp2->decrRef(); tmp3->decrRef();
6958               MCAuto<MEDCouplingUMesh> mm3=static_cast<MEDCouplingUMesh *>(mm2->buildPartOfMySelf(ids2->begin(),ids2->end(),true));
6959               MCAuto<DataArrayInt> idsNodeTmp=mm3->zipCoordsTraducer();
6960               MCAuto<DataArrayInt> idsNode=idsNodeTmp->invertArrayO2N2N2O(mm3->getNumberOfNodes());
6961               const int *idsNodePtr=idsNode->begin();
6962               double center[3]; center[0]=pPtr[pointId]*vPtr[3*vecId]; center[1]=pPtr[pointId]*vPtr[3*vecId+1]; center[2]=pPtr[pointId]*vPtr[3*vecId+2];
6963               double vec[3]; vec[0]=vPtr[3*vecId+1]; vec[1]=-vPtr[3*vecId]; vec[2]=0.;
6964               double norm=vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2];
6965               if(std::abs(norm)>eps)
6966                 {
6967                   double angle=INTERP_KERNEL::EdgeArcCircle::SafeAsin(norm);
6968                   mm3->rotate(center,vec,angle);
6969                 }
6970               mm3->changeSpaceDimension(2);
6971               MCAuto<MEDCouplingUMesh> mm4=mm3->buildSpreadZonesWithPoly();
6972               const int *conn4=mm4->getNodalConnectivity()->begin();
6973               const int *connI4=mm4->getNodalConnectivityIndex()->begin();
6974               int nbOfCells=mm4->getNumberOfCells();
6975               for(int k=0;k<nbOfCells;k++)
6976                 {
6977                   int l=0;
6978                   for(const int *work=conn4+connI4[k]+1;work!=conn4+connI4[k+1];work++,l++)
6979                     res->pushBackSilent(idsNodePtr[*work]);
6980                   res->pushBackSilent(-1);
6981                 }
6982             }
6983         }
6984     }
6985   res->popBackSilent();
6986 }
6987
6988 /*!
6989  * This method computes the normalized vector of the plane and the pos of the point belonging to the plane and the line defined by the vector going
6990  * through origin. The plane is defined by its nodal connectivity [ \b begin, \b end ).
6991  * 
6992  * \param [in] eps below that value the dot product of 2 vectors is considered as colinears
6993  * \param [in] coords coordinates expected to have 3 components.
6994  * \param [in] begin start of the nodal connectivity of the face.
6995  * \param [in] end end of the nodal connectivity (excluded) of the face.
6996  * \param [out] v the normalized vector of size 3
6997  * \param [out] p the pos of plane
6998  */
6999 void MEDCouplingUMesh::ComputeVecAndPtOfFace(double eps, const double *coords, const int *begin, const int *end, double *v, double *p)
7000 {
7001   std::size_t nbPoints=std::distance(begin,end);
7002   if(nbPoints<3)
7003     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeVecAndPtOfFace : < of 3 points in face ! not able to find a plane on that face !");
7004   double vec[3]={0.,0.,0.};
7005   std::size_t j=0;
7006   bool refFound=false;
7007   for(;j<nbPoints-1 && !refFound;j++)
7008     {
7009       vec[0]=coords[3*begin[j+1]]-coords[3*begin[j]];
7010       vec[1]=coords[3*begin[j+1]+1]-coords[3*begin[j]+1];
7011       vec[2]=coords[3*begin[j+1]+2]-coords[3*begin[j]+2];
7012       double norm=sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
7013       if(norm>eps)
7014         {
7015           refFound=true;
7016           vec[0]/=norm; vec[1]/=norm; vec[2]/=norm;
7017         }
7018     }
7019   for(std::size_t i=j;i<nbPoints-1;i++)
7020     {
7021       double curVec[3];
7022       curVec[0]=coords[3*begin[i+1]]-coords[3*begin[i]];
7023       curVec[1]=coords[3*begin[i+1]+1]-coords[3*begin[i]+1];
7024       curVec[2]=coords[3*begin[i+1]+2]-coords[3*begin[i]+2];
7025       double norm=sqrt(curVec[0]*curVec[0]+curVec[1]*curVec[1]+curVec[2]*curVec[2]);
7026       if(norm<eps)
7027         continue;
7028       curVec[0]/=norm; curVec[1]/=norm; curVec[2]/=norm;
7029       v[0]=vec[1]*curVec[2]-vec[2]*curVec[1]; v[1]=vec[2]*curVec[0]-vec[0]*curVec[2]; v[2]=vec[0]*curVec[1]-vec[1]*curVec[0];
7030       norm=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
7031       if(norm>eps)
7032         {
7033           v[0]/=norm; v[1]/=norm; v[2]/=norm;
7034           *p=v[0]*coords[3*begin[i]]+v[1]*coords[3*begin[i]+1]+v[2]*coords[3*begin[i]+2];
7035           return ;
7036         }
7037     }
7038   throw INTERP_KERNEL::Exception("Not able to find a normal vector of that 3D face !");
7039 }
7040
7041 /*!
7042  * This method tries to obtain a well oriented polyhedron.
7043  * If the algorithm fails, an exception will be thrown.
7044  */
7045 void MEDCouplingUMesh::TryToCorrectPolyhedronOrientation(int *begin, int *end, const double *coords)
7046 {
7047   std::list< std::pair<int,int> > edgesOK,edgesFinished;
7048   std::size_t nbOfFaces=std::count(begin,end,-1)+1;
7049   std::vector<bool> isPerm(nbOfFaces,false);//field on faces False: I don't know, True : oriented
7050   isPerm[0]=true;
7051   int *bgFace=begin,*endFace=std::find(begin+1,end,-1);
7052   std::size_t nbOfEdgesInFace=std::distance(bgFace,endFace);
7053   for(std::size_t l=0;l<nbOfEdgesInFace;l++) { std::pair<int,int> p1(bgFace[l],bgFace[(l+1)%nbOfEdgesInFace]); edgesOK.push_back(p1); }
7054   //
7055   while(std::find(isPerm.begin(),isPerm.end(),false)!=isPerm.end())
7056     {
7057       bgFace=begin;
7058       std::size_t smthChanged=0;
7059       for(std::size_t i=0;i<nbOfFaces;i++)
7060         {
7061           endFace=std::find(bgFace+1,end,-1);
7062           nbOfEdgesInFace=std::distance(bgFace,endFace);
7063           if(!isPerm[i])
7064             {
7065               bool b;
7066               for(std::size_t j=0;j<nbOfEdgesInFace;j++)
7067                 {
7068                   std::pair<int,int> p1(bgFace[j],bgFace[(j+1)%nbOfEdgesInFace]);
7069                   std::pair<int,int> p2(p1.second,p1.first);
7070                   bool b1=std::find(edgesOK.begin(),edgesOK.end(),p1)!=edgesOK.end();
7071                   bool b2=std::find(edgesOK.begin(),edgesOK.end(),p2)!=edgesOK.end();
7072                   if(b1 || b2) { b=b2; isPerm[i]=true; smthChanged++; break; }
7073                 }
7074               if(isPerm[i])
7075                 { 
7076                   if(!b)
7077                     std::reverse(bgFace+1,endFace);
7078                   for(std::size_t j=0;j<nbOfEdgesInFace;j++)
7079                     {
7080                       std::pair<int,int> p1(bgFace[j],bgFace[(j+1)%nbOfEdgesInFace]);
7081                       std::pair<int,int> p2(p1.second,p1.first);
7082                       if(std::find(edgesOK.begin(),edgesOK.end(),p1)!=edgesOK.end())
7083                         { std::ostringstream oss; oss << "Face #" << j << " of polyhedron looks bad !"; throw INTERP_KERNEL::Exception(oss.str()); }
7084                       if(std::find(edgesFinished.begin(),edgesFinished.end(),p1)!=edgesFinished.end() || std::find(edgesFinished.begin(),edgesFinished.end(),p2)!=edgesFinished.end())
7085                         { std::ostringstream oss; oss << "Face #" << j << " of polyhedron looks bad !"; throw INTERP_KERNEL::Exception(oss.str()); }
7086                       std::list< std::pair<int,int> >::iterator it=std::find(edgesOK.begin(),edgesOK.end(),p2);
7087                       if(it!=edgesOK.end())
7088                         {
7089                           edgesOK.erase(it);
7090                           edgesFinished.push_back(p1);
7091                         }
7092                       else
7093                         edgesOK.push_back(p1);
7094                     }
7095                 }
7096             }
7097           bgFace=endFace+1;
7098         }
7099       if(smthChanged==0)
7100         { throw INTERP_KERNEL::Exception("The polyhedron looks too bad to be repaired !"); }
7101     }
7102   if(!edgesOK.empty())
7103     { throw INTERP_KERNEL::Exception("The polyhedron looks too bad to be repaired : Some edges are shared only once !"); }
7104   if(INTERP_KERNEL::calculateVolumeForPolyh2<int,INTERP_KERNEL::ALL_C_MODE>(begin,(int)std::distance(begin,end),coords)<-EPS_FOR_POLYH_ORIENTATION)
7105     {//not lucky ! The first face was not correctly oriented : reorient all faces...
7106       bgFace=begin;
7107       for(std::size_t i=0;i<nbOfFaces;i++)
7108         {
7109           endFace=std::find(bgFace+1,end,-1);
7110           std::reverse(bgFace+1,endFace);
7111           bgFace=endFace+1;
7112         }
7113     }
7114 }
7115
7116
7117 /*!
7118  * This method makes the assumption spacedimension == meshdimension == 2.
7119  * This method works only for linear cells.
7120  * 
7121  * \return a newly allocated array containing the connectivity of a polygon type enum included (NORM_POLYGON in pos#0)
7122  */
7123 DataArrayInt *MEDCouplingUMesh::buildUnionOf2DMesh() const
7124 {
7125   if(getMeshDimension()!=2 || getSpaceDimension()!=2)
7126     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMesh : meshdimension, spacedimension must be equal to 2 !");
7127   MCAuto<MEDCouplingUMesh> skin(computeSkin());
7128   int oldNbOfNodes(skin->getNumberOfNodes());
7129   MCAuto<DataArrayInt> o2n(skin->zipCoordsTraducer());
7130   int nbOfNodesExpected(skin->getNumberOfNodes());
7131   MCAuto<DataArrayInt> n2o(o2n->invertArrayO2N2N2O(oldNbOfNodes));
7132   int nbCells(skin->getNumberOfCells());
7133   if(nbCells==nbOfNodesExpected)
7134     return buildUnionOf2DMeshLinear(skin,n2o);
7135   else if(2*nbCells==nbOfNodesExpected)
7136     return buildUnionOf2DMeshQuadratic(skin,n2o);
7137   else
7138     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf2DMesh : the mesh 2D in input appears to be not in a single part of a 2D mesh !");
7139 }
7140
7141 /*!
7142  * This method makes the assumption spacedimension == meshdimension == 3.
7143  * This method works only for linear cells.
7144  * 
7145  * \return a newly allocated array containing the connectivity of a polygon type enum included (NORM_POLYHED in pos#0)
7146  */
7147 DataArrayInt *MEDCouplingUMesh::buildUnionOf3DMesh() const
7148 {
7149   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
7150     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildUnionOf3DMesh : meshdimension, spacedimension must be equal to 2 !");
7151   MCAuto<MEDCouplingUMesh> m=computeSkin();
7152   const int *conn=m->getNodalConnectivity()->begin();
7153   const int *connI=m->getNodalConnectivityIndex()->begin();
7154   int nbOfCells=m->getNumberOfCells();
7155   MCAuto<DataArrayInt> ret=DataArrayInt::New(); ret->alloc(m->getNodalConnectivity()->getNumberOfTuples(),1);
7156   int *work=ret->getPointer();  *work++=INTERP_KERNEL::NORM_POLYHED;
7157   if(nbOfCells<1)
7158     return ret.retn();
7159   work=std::copy(conn+connI[0]+1,conn+connI[1],work);
7160   for(int i=1;i<nbOfCells;i++)
7161     {
7162       *work++=-1;
7163       work=std::copy(conn+connI[i]+1,conn+connI[i+1],work);
7164     }
7165   return ret.retn();
7166 }
7167
7168 /*!
7169  * \brief Creates a graph of cell neighbors
7170  *  \return MEDCouplingSkyLineArray * - an sky line array the user should delete.
7171  *  In the sky line array, graph arcs are stored in terms of (index,value) notation.
7172  *  For example
7173  *  - index:  0 3 5 6 6
7174  *  - value:  1 2 3 2 3 3
7175  *  means 6 arcs (0,1), (0,2), (0,3), (1,2), (1,3), (2,3)
7176  *  Arcs are not doubled but reflexive (1,1) arcs are present for each cell
7177  */
7178 MEDCouplingSkyLineArray* MEDCouplingUMesh::generateGraph() const
7179 {
7180   checkConnectivityFullyDefined();
7181
7182   int meshDim = this->getMeshDimension();
7183   MEDCoupling::DataArrayInt* indexr=MEDCoupling::DataArrayInt::New();
7184   MEDCoupling::DataArrayInt* revConn=MEDCoupling::DataArrayInt::New();
7185   this->getReverseNodalConnectivity(revConn,indexr);
7186   const int* indexr_ptr=indexr->begin();
7187   const int* revConn_ptr=revConn->begin();
7188
7189   const MEDCoupling::DataArrayInt* index;
7190   const MEDCoupling::DataArrayInt* conn;
7191   conn=this->getNodalConnectivity(); // it includes a type as the 1st element!!!
7192   index=this->getNodalConnectivityIndex();
7193   int nbCells=this->getNumberOfCells();
7194   const int* index_ptr=index->begin();
7195   const int* conn_ptr=conn->begin();
7196
7197   //creating graph arcs (cell to cell relations)
7198   //arcs are stored in terms of (index,value) notation
7199   // 0 3 5 6 6
7200   // 1 2 3 2 3 3
7201   // means 6 arcs (0,1), (0,2), (0,3), (1,2), (1,3), (2,3)
7202   // in present version arcs are not doubled but reflexive (1,1) arcs are present for each cell
7203
7204   //warning here one node have less than or equal effective number of cell with it
7205   //but cell could have more than effective nodes
7206   //because other equals nodes in other domain (with other global inode)
7207   std::vector <int> cell2cell_index(nbCells+1,0);
7208   std::vector <int> cell2cell;
7209   cell2cell.reserve(3*nbCells);
7210
7211   for (int icell=0; icell<nbCells;icell++)
7212     {
7213       std::map<int,int > counter;
7214       for (int iconn=index_ptr[icell]+1; iconn<index_ptr[icell+1];iconn++)
7215         {
7216           int inode=conn_ptr[iconn];
7217           for (int iconnr=indexr_ptr[inode]; iconnr<indexr_ptr[inode+1];iconnr++)
7218             {
7219               int icell2=revConn_ptr[iconnr];
7220               std::map<int,int>::iterator iter=counter.find(icell2);
7221               if (iter!=counter.end()) (iter->second)++;
7222               else counter.insert(std::make_pair(icell2,1));
7223             }
7224         }
7225       for (std::map<int,int>::const_iterator iter=counter.begin();
7226            iter!=counter.end(); iter++)
7227         if (iter->second >= meshDim)
7228           {
7229             cell2cell_index[icell+1]++;
7230             cell2cell.push_back(iter->first);
7231           }
7232     }
7233   indexr->decrRef();
7234   revConn->decrRef();
7235   cell2cell_index[0]=0;
7236   for (int icell=0; icell<nbCells;icell++)
7237     cell2cell_index[icell+1]=cell2cell_index[icell]+cell2cell_index[icell+1];
7238
7239   //filling up index and value to create skylinearray structure
7240   MEDCouplingSkyLineArray * array(MEDCouplingSkyLineArray::New(cell2cell_index,cell2cell));
7241   return array;
7242 }
7243
7244
7245 void MEDCouplingUMesh::writeVTKLL(std::ostream& ofs, const std::string& cellData, const std::string& pointData, DataArrayByte *byteData) const
7246 {
7247   int nbOfCells=getNumberOfCells();
7248   if(nbOfCells<=0)
7249     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::writeVTK : the unstructured mesh has no cells !");
7250   ofs << "  <" << getVTKDataSetType() << ">\n";
7251   ofs << "    <Piece NumberOfPoints=\"" << getNumberOfNodes() << "\" NumberOfCells=\"" << nbOfCells << "\">\n";
7252   ofs << "      <PointData>\n" << pointData << std::endl;
7253   ofs << "      </PointData>\n";
7254   ofs << "      <CellData>\n" << cellData << std::endl;
7255   ofs << "      </CellData>\n";
7256   ofs << "      <Points>\n";
7257   if(getSpaceDimension()==3)
7258     _coords->writeVTK(ofs,8,"Points",byteData);
7259   else
7260     {
7261       MCAuto<DataArrayDouble> coo=_coords->changeNbOfComponents(3,0.);
7262       coo->writeVTK(ofs,8,"Points",byteData);
7263     }
7264   ofs << "      </Points>\n";
7265   ofs << "      <Cells>\n";
7266   const int *cPtr=_nodal_connec->begin();
7267   const int *cIPtr=_nodal_connec_index->begin();
7268   MCAuto<DataArrayInt> faceoffsets=DataArrayInt::New(); faceoffsets->alloc(nbOfCells,1);
7269   MCAuto<DataArrayInt> types=DataArrayInt::New(); types->alloc(nbOfCells,1);
7270   MCAuto<DataArrayInt> offsets=DataArrayInt::New(); offsets->alloc(nbOfCells,1);
7271   MCAuto<DataArrayInt> connectivity=DataArrayInt::New(); connectivity->alloc(_nodal_connec->getNumberOfTuples()-nbOfCells,1);
7272   int *w1=faceoffsets->getPointer(),*w2=types->getPointer(),*w3=offsets->getPointer(),*w4=connectivity->getPointer();
7273   int szFaceOffsets=0,szConn=0;
7274   for(int i=0;i<nbOfCells;i++,w1++,w2++,w3++)
7275     {
7276       *w2=cPtr[cIPtr[i]];
7277       if((INTERP_KERNEL::NormalizedCellType)cPtr[cIPtr[i]]!=INTERP_KERNEL::NORM_POLYHED)
7278         {
7279           *w1=-1;
7280           *w3=szConn+cIPtr[i+1]-cIPtr[i]-1; szConn+=cIPtr[i+1]-cIPtr[i]-1;
7281           w4=std::copy(cPtr+cIPtr[i]+1,cPtr+cIPtr[i+1],w4);
7282         }
7283       else
7284         {
7285           int deltaFaceOffset=cIPtr[i+1]-cIPtr[i]+1;
7286           *w1=szFaceOffsets+deltaFaceOffset; szFaceOffsets+=deltaFaceOffset;
7287           std::set<int> c(cPtr+cIPtr[i]+1,cPtr+cIPtr[i+1]); c.erase(-1);
7288           *w3=szConn+(int)c.size(); szConn+=(int)c.size();
7289           w4=std::copy(c.begin(),c.end(),w4);
7290         }
7291     }
7292   types->transformWithIndArr(MEDCOUPLING2VTKTYPETRADUCER,MEDCOUPLING2VTKTYPETRADUCER+INTERP_KERNEL::NORM_MAXTYPE+1);
7293   types->writeVTK(ofs,8,"UInt8","types",byteData);
7294   offsets->writeVTK(ofs,8,"Int32","offsets",byteData);
7295   if(szFaceOffsets!=0)
7296     {//presence of Polyhedra
7297       connectivity->reAlloc(szConn);
7298       faceoffsets->writeVTK(ofs,8,"Int32","faceoffsets",byteData);
7299       MCAuto<DataArrayInt> faces=DataArrayInt::New(); faces->alloc(szFaceOffsets,1);
7300       w1=faces->getPointer();
7301       for(int i=0;i<nbOfCells;i++)
7302         if((INTERP_KERNEL::NormalizedCellType)cPtr[cIPtr[i]]==INTERP_KERNEL::NORM_POLYHED)
7303           {
7304             int nbFaces=std::count(cPtr+cIPtr[i]+1,cPtr+cIPtr[i+1],-1)+1;
7305             *w1++=nbFaces;
7306             const int *w6=cPtr+cIPtr[i]+1,*w5=0;
7307             for(int j=0;j<nbFaces;j++)
7308               {
7309                 w5=std::find(w6,cPtr+cIPtr[i+1],-1);
7310                 *w1++=(int)std::distance(w6,w5);
7311                 w1=std::copy(w6,w5,w1);
7312                 w6=w5+1;
7313               }
7314           }
7315       faces->writeVTK(ofs,8,"Int32","faces",byteData);
7316     }
7317   connectivity->writeVTK(ofs,8,"Int32","connectivity",byteData);
7318   ofs << "      </Cells>\n";
7319   ofs << "    </Piece>\n";
7320   ofs << "  </" << getVTKDataSetType() << ">\n";
7321 }
7322
7323 void MEDCouplingUMesh::reprQuickOverview(std::ostream& stream) const
7324 {
7325   stream << "MEDCouplingUMesh C++ instance at " << this << ". Name : \"" << getName() << "\".";
7326   if(_mesh_dim==-2)
7327     { stream << " Not set !"; return ; }
7328   stream << " Mesh dimension : " << _mesh_dim << ".";
7329   if(_mesh_dim==-1)
7330     return ;
7331   if(!_coords)
7332     { stream << " No coordinates set !"; return ; }
7333   if(!_coords->isAllocated())
7334     { stream << " Coordinates set but not allocated !"; return ; }
7335   stream << " Space dimension : " << _coords->getNumberOfComponents() << "." << std::endl;
7336   stream << "Number of nodes : " << _coords->getNumberOfTuples() << ".";
7337   if(!_nodal_connec_index)
7338     { stream << std::endl << "Nodal connectivity NOT set !"; return ; }
7339   if(!_nodal_connec_index->isAllocated())
7340     { stream << std::endl << "Nodal connectivity set but not allocated !"; return ; }
7341   int lgth=_nodal_connec_index->getNumberOfTuples();
7342   int cpt=_nodal_connec_index->getNumberOfComponents();
7343   if(cpt!=1 || lgth<1)
7344     return ;
7345   stream << std::endl << "Number of cells : " << lgth-1 << ".";
7346 }
7347
7348 std::string MEDCouplingUMesh::getVTKDataSetType() const
7349 {
7350   return std::string("UnstructuredGrid");
7351 }
7352
7353 std::string MEDCouplingUMesh::getVTKFileExtension() const
7354 {
7355   return std::string("vtu");
7356 }
7357
7358
7359
7360 /**
7361  * Provides a renumbering of the cells of this (which has to be a piecewise connected 1D line), so that
7362  * the segments of the line are indexed in consecutive order (i.e. cells \a i and \a i+1 are neighbors).
7363  * This doesn't modify the mesh. This method only works using nodal connectivity consideration. Coordinates of nodes are ignored here.
7364  * The caller is to deal with the resulting DataArrayInt.
7365  *  \throw If the coordinate array is not set.
7366  *  \throw If the nodal connectivity of the cells is not defined.
7367  *  \throw If m1 is not a mesh of dimension 2, or m1 is not a mesh of dimension 1
7368  *  \throw If m2 is not a (piecewise) line (i.e. if a point has more than 2 adjacent segments)
7369  *
7370  * \sa DataArrayInt::sortEachPairToMakeALinkedList
7371  */
7372 DataArrayInt *MEDCouplingUMesh::orderConsecutiveCells1D() const
7373 {
7374   checkFullyDefined();
7375   if(getMeshDimension()!=1)
7376     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::orderConsecutiveCells1D works on unstructured mesh with meshdim = 1 !");
7377
7378   // Check that this is a line (and not a more complex 1D mesh) - each point is used at most by 2 segments:
7379   MCAuto<DataArrayInt> _d(DataArrayInt::New()),_dI(DataArrayInt::New());
7380   MCAuto<DataArrayInt> _rD(DataArrayInt::New()),_rDI(DataArrayInt::New());
7381   MCAuto<MEDCouplingUMesh> m_points(buildDescendingConnectivity(_d, _dI, _rD, _rDI));
7382   const int *d(_d->begin()), *dI(_dI->begin());
7383   const int *rD(_rD->begin()), *rDI(_rDI->begin());
7384   MCAuto<DataArrayInt> _dsi(_rDI->deltaShiftIndex());
7385   const int * dsi(_dsi->begin());
7386   MCAuto<DataArrayInt> dsii = _dsi->findIdsNotInRange(0,3);
7387   m_points=0;
7388   if (dsii->getNumberOfTuples())
7389     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::orderConsecutiveCells1D only work with a mesh being a (piecewise) connected line!");
7390
7391   int nc(getNumberOfCells());
7392   MCAuto<DataArrayInt> result(DataArrayInt::New());
7393   result->alloc(nc,1);
7394
7395   // set of edges not used so far
7396   std::set<int> edgeSet;
7397   for (int i=0; i<nc; edgeSet.insert(i), i++);
7398
7399   int startSeg=0;
7400   int newIdx=0;
7401   // while we have points with only one neighbor segments
7402   do
7403     {
7404       std::list<int> linePiece;
7405       // fills a list of consecutive segment linked to startSeg. This can go forward or backward.
7406       for (int direction=0;direction<2;direction++) // direction=0 --> forward, direction=1 --> backward
7407         {
7408           // Fill the list forward (resp. backward) from the start segment:
7409           int activeSeg = startSeg;
7410           int prevPointId = -20;
7411           int ptId;
7412           while (!edgeSet.empty())
7413             {
7414               if (!(direction == 1 && prevPointId==-20)) // prevent adding twice startSeg
7415                 {
7416                   if (direction==0)
7417                     linePiece.push_back(activeSeg);
7418                   else
7419                     linePiece.push_front(activeSeg);
7420                   edgeSet.erase(activeSeg);
7421                 }
7422
7423               int ptId1 = d[dI[activeSeg]], ptId2 = d[dI[activeSeg]+1];
7424               ptId = direction ? (ptId1 == prevPointId ? ptId2 : ptId1) : (ptId2 == prevPointId ? ptId1 : ptId2);
7425               if (dsi[ptId] == 1) // hitting the end of the line
7426                 break;
7427               prevPointId = ptId;
7428               int seg1 = rD[rDI[ptId]], seg2 = rD[rDI[ptId]+1];
7429               activeSeg = (seg1 == activeSeg) ? seg2 : seg1;
7430             }
7431         }
7432       // Done, save final piece into DA:
7433       std::copy(linePiece.begin(), linePiece.end(), result->getPointer()+newIdx);
7434       newIdx += linePiece.size();
7435
7436       // identify next valid start segment (one which is not consumed)
7437       if(!edgeSet.empty())
7438         startSeg = *(edgeSet.begin());
7439     }
7440   while (!edgeSet.empty());
7441   return result.retn();
7442 }
7443
7444 /**
7445  * This method split some of edges of 2D cells in \a this. The edges to be split are specified in \a subNodesInSeg
7446  * and in \a subNodesInSegI using \ref numbering-indirect storage mode.
7447  * To do the work this method can optionally needs information about middle of subedges for quadratic cases if
7448  * a minimal creation of new nodes is wanted.
7449  * So this method try to reduce at most the number of new nodes. The only case that can lead this method to add
7450  * nodes if a SEG3 is split without information of middle.
7451  * \b WARNING : is returned value is different from 0 a call to MEDCouplingUMesh::mergeNodes is necessary to
7452  * avoid to have a non conform mesh.
7453  *
7454  * \return int - the number of new nodes created (in most of cases 0).
7455  * 
7456  * \throw If \a this is not coherent.
7457  * \throw If \a this has not spaceDim equal to 2.
7458  * \throw If \a this has not meshDim equal to 2.
7459  * \throw If some subcells needed to be split are orphan.
7460  * \sa MEDCouplingUMesh::conformize2D
7461  */
7462 int MEDCouplingUMesh::split2DCells(const DataArrayInt *desc, const DataArrayInt *descI, const DataArrayInt *subNodesInSeg, const DataArrayInt *subNodesInSegI, const DataArrayInt *midOpt, const DataArrayInt *midOptI)
7463 {
7464   if(!desc || !descI || !subNodesInSeg || !subNodesInSegI)
7465     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCells : the 4 first arrays must be not null !");
7466   desc->checkAllocated(); descI->checkAllocated(); subNodesInSeg->checkAllocated(); subNodesInSegI->checkAllocated();
7467   if(getSpaceDimension()!=2 || getMeshDimension()!=2)
7468     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCells : This method only works for meshes with spaceDim=2 and meshDim=2 !");
7469   if(midOpt==0 && midOptI==0)
7470     {
7471       split2DCellsLinear(desc,descI,subNodesInSeg,subNodesInSegI);
7472       return 0;
7473     }
7474   else if(midOpt!=0 && midOptI!=0)
7475     return split2DCellsQuadratic(desc,descI,subNodesInSeg,subNodesInSegI,midOpt,midOptI);
7476   else
7477     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::split2DCells : middle parameters must be set to null for all or not null for all.");
7478 }
7479
7480 /*!
7481  * This method compute the convex hull of a single 2D cell. This method tries to conserve at maximum the given input connectivity. In particular, if the orientation of cell is not clockwise
7482  * as in MED format norm. If definitely the result of Jarvis algorithm is not matchable with the input connectivity, the result will be copied into \b nodalConnecOut parameter and
7483  * the geometric cell type set to INTERP_KERNEL::NORM_POLYGON.
7484  * This method excepts that \b coords parameter is expected to be in dimension 2. [ \b nodalConnBg , \b nodalConnEnd ) is the nodal connectivity of the input
7485  * cell (geometric cell type included at the position 0). If the meshdimension of the input cell is not equal to 2 an INTERP_KERNEL::Exception will be thrown.
7486  * 
7487  * \return false if the input connectivity represents already the convex hull, true if the input cell needs to be reordered.
7488  */
7489 bool MEDCouplingUMesh::BuildConvexEnvelopOf2DCellJarvis(const double *coords, const int *nodalConnBg, const int *nodalConnEnd, DataArrayInt *nodalConnecOut)
7490 {
7491   std::size_t sz=std::distance(nodalConnBg,nodalConnEnd);
7492   if(sz>=4)
7493     {
7494       const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)*nodalConnBg);
7495       if(cm.getDimension()==2)
7496         {
7497           const int *node=nodalConnBg+1;
7498           int startNode=*node++;
7499           double refX=coords[2*startNode];
7500           for(;node!=nodalConnEnd;node++)
7501             {
7502               if(coords[2*(*node)]<refX)
7503                 {
7504                   startNode=*node;
7505                   refX=coords[2*startNode];
7506                 }
7507             }
7508           std::vector<int> tmpOut; tmpOut.reserve(sz); tmpOut.push_back(startNode);
7509           refX=1e300;
7510           double tmp1;
7511           double tmp2[2];
7512           double angle0=-M_PI/2;
7513           //
7514           int nextNode=-1;
7515           int prevNode=-1;
7516           double resRef;
7517           double angleNext=0.;
7518           while(nextNode!=startNode)
7519             {
7520               nextNode=-1;
7521               resRef=1e300;
7522               for(node=nodalConnBg+1;node!=nodalConnEnd;node++)
7523                 {
7524                   if(*node!=tmpOut.back() && *node!=prevNode)
7525                     {
7526                       tmp2[0]=coords[2*(*node)]-coords[2*tmpOut.back()]; tmp2[1]=coords[2*(*node)+1]-coords[2*tmpOut.back()+1];
7527                       double angleM=INTERP_KERNEL::EdgeArcCircle::GetAbsoluteAngle(tmp2,tmp1);
7528                       double res;
7529                       if(angleM<=angle0)
7530                         res=angle0-angleM;
7531                       else
7532                         res=angle0-angleM+2.*M_PI;
7533                       if(res<resRef)
7534                         {
7535                           nextNode=*node;
7536                           resRef=res;
7537                           angleNext=angleM;
7538                         }
7539                     }
7540                 }
7541               if(nextNode!=startNode)
7542                 {
7543                   angle0=angleNext-M_PI;
7544                   if(angle0<-M_PI)
7545                     angle0+=2*M_PI;
7546                   prevNode=tmpOut.back();
7547                   tmpOut.push_back(nextNode);
7548                 }
7549             }
7550           std::vector<int> tmp3(2*(sz-1));
7551           std::vector<int>::iterator it=std::copy(nodalConnBg+1,nodalConnEnd,tmp3.begin());
7552           std::copy(nodalConnBg+1,nodalConnEnd,it);
7553           if(std::search(tmp3.begin(),tmp3.end(),tmpOut.begin(),tmpOut.end())!=tmp3.end())
7554             {
7555               nodalConnecOut->insertAtTheEnd(nodalConnBg,nodalConnEnd);
7556               return false;
7557             }
7558           if(std::search(tmp3.rbegin(),tmp3.rend(),tmpOut.begin(),tmpOut.end())!=tmp3.rend())
7559             {
7560               nodalConnecOut->insertAtTheEnd(nodalConnBg,nodalConnEnd);
7561               return false;
7562             }
7563           else
7564             {
7565               nodalConnecOut->pushBackSilent((int)INTERP_KERNEL::NORM_POLYGON);
7566               nodalConnecOut->insertAtTheEnd(tmpOut.begin(),tmpOut.end());
7567               return true;
7568             }
7569         }
7570       else
7571         throw INTERP_KERNEL::Exception("MEDCouplingUMesh::BuildConvexEnvelopOf2DCellJarvis : invalid 2D cell connectivity !");
7572     }
7573   else
7574     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::BuildConvexEnvelopOf2DCellJarvis : invalid 2D cell connectivity !");
7575 }
7576
7577 /*!
7578  * This method works on an input pair (\b arr, \b arrIndx) where \b arr indexes is in \b arrIndx.
7579  * This method will not impact the size of inout parameter \b arrIndx but the size of \b arr will be modified in case of suppression.
7580  * 
7581  * \param [in] idsToRemoveBg begin of set of ids to remove in \b arr (included)
7582  * \param [in] idsToRemoveEnd end of set of ids to remove in \b arr (excluded)
7583  * \param [in,out] arr array in which the remove operation will be done.
7584  * \param [in,out] arrIndx array in the remove operation will modify
7585  * \param [in] offsetForRemoval (by default 0) offset so that for each i in [0,arrIndx->getNumberOfTuples()-1) removal process will be performed in the following range [arr+arrIndx[i]+offsetForRemoval,arr+arr[i+1])
7586  * \return true if \b arr and \b arrIndx have been modified, false if not.
7587  */
7588 bool MEDCouplingUMesh::RemoveIdsFromIndexedArrays(const int *idsToRemoveBg, const int *idsToRemoveEnd, DataArrayInt *arr, DataArrayInt *arrIndx, int offsetForRemoval)
7589 {
7590   if(!arrIndx || !arr)
7591     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::RemoveIdsFromIndexedArrays : some input arrays are empty !");
7592   if(offsetForRemoval<0)
7593     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::RemoveIdsFromIndexedArrays : offsetForRemoval should be >=0 !");
7594   std::set<int> s(idsToRemoveBg,idsToRemoveEnd);
7595   int nbOfGrps=arrIndx->getNumberOfTuples()-1;
7596   int *arrIPtr=arrIndx->getPointer();
7597   *arrIPtr++=0;
7598   int previousArrI=0;
7599   const int *arrPtr=arr->begin();
7600   std::vector<int> arrOut;//no utility to switch to DataArrayInt because copy always needed
7601   for(int i=0;i<nbOfGrps;i++,arrIPtr++)
7602     {
7603       if(*arrIPtr-previousArrI>offsetForRemoval)
7604         {
7605           for(const int *work=arrPtr+previousArrI+offsetForRemoval;work!=arrPtr+*arrIPtr;work++)
7606             {
7607               if(s.find(*work)==s.end())
7608                 arrOut.push_back(*work);
7609             }
7610         }
7611       previousArrI=*arrIPtr;
7612       *arrIPtr=(int)arrOut.size();
7613     }
7614   if(arr->getNumberOfTuples()==(int)arrOut.size())
7615     return false;
7616   arr->alloc((int)arrOut.size(),1);
7617   std::copy(arrOut.begin(),arrOut.end(),arr->getPointer());
7618   return true;
7619 }
7620
7621 /*!
7622  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn
7623  * (\ref numbering-indirect).
7624  * This method returns the result of the extraction ( specified by a set of ids in [\b idsOfSelectBg , \b idsOfSelectEnd ) ).
7625  * The selection of extraction is done standardly in new2old format.
7626  * This method returns indexed arrays (\ref numbering-indirect) using 2 arrays (arrOut,arrIndexOut).
7627  *
7628  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
7629  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
7630  * \param [in] arrIn arr origin array from which the extraction will be done.
7631  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7632  * \param [out] arrOut the resulting array
7633  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
7634  * \sa MEDCouplingUMesh::ExtractFromIndexedArraysSlice
7635  */
7636 void MEDCouplingUMesh::ExtractFromIndexedArrays(const int *idsOfSelectBg, const int *idsOfSelectEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
7637                                                 DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
7638 {
7639   if(!arrIn || !arrIndxIn)
7640     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays : input pointer is NULL !");
7641   arrIn->checkAllocated(); arrIndxIn->checkAllocated();
7642   if(arrIn->getNumberOfComponents()!=1 || arrIndxIn->getNumberOfComponents()!=1)
7643     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays : input arrays must have exactly one component !");
7644   std::size_t sz=std::distance(idsOfSelectBg,idsOfSelectEnd);
7645   const int *arrInPtr=arrIn->begin();
7646   const int *arrIndxPtr=arrIndxIn->begin();
7647   int nbOfGrps=arrIndxIn->getNumberOfTuples()-1;
7648   if(nbOfGrps<0)
7649     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArrays : The format of \"arrIndxIn\" is invalid ! Its nb of tuples should be >=1 !");
7650   int maxSizeOfArr=arrIn->getNumberOfTuples();
7651   MCAuto<DataArrayInt> arro=DataArrayInt::New();
7652   MCAuto<DataArrayInt> arrIo=DataArrayInt::New();
7653   arrIo->alloc((int)(sz+1),1);
7654   const int *idsIt=idsOfSelectBg;
7655   int *work=arrIo->getPointer();
7656   *work++=0;
7657   int lgth=0;
7658   for(std::size_t i=0;i<sz;i++,work++,idsIt++)
7659     {
7660       if(*idsIt>=0 && *idsIt<nbOfGrps)
7661         lgth+=arrIndxPtr[*idsIt+1]-arrIndxPtr[*idsIt];
7662       else
7663         {
7664           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays : id located on pos #" << i << " value is " << *idsIt << " ! Must be in [0," << nbOfGrps << ") !";
7665           throw INTERP_KERNEL::Exception(oss.str());
7666         }
7667       if(lgth>=work[-1])
7668         *work=lgth;
7669       else
7670         {
7671           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays : id located on pos #" << i << " value is " << *idsIt << " and at this pos arrIndxIn[" << *idsIt;
7672           oss << "+1]-arrIndxIn[" << *idsIt << "] < 0 ! The input index array is bugged !";
7673           throw INTERP_KERNEL::Exception(oss.str());
7674         }
7675     }
7676   arro->alloc(lgth,1);
7677   work=arro->getPointer();
7678   idsIt=idsOfSelectBg;
7679   for(std::size_t i=0;i<sz;i++,idsIt++)
7680     {
7681       if(arrIndxPtr[*idsIt]>=0 && arrIndxPtr[*idsIt+1]<=maxSizeOfArr)
7682         work=std::copy(arrInPtr+arrIndxPtr[*idsIt],arrInPtr+arrIndxPtr[*idsIt+1],work);
7683       else
7684         {
7685           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArrays : id located on pos #" << i << " value is " << *idsIt << " arrIndx[" << *idsIt << "] must be >= 0 and arrIndx[";
7686           oss << *idsIt << "+1] <= " << maxSizeOfArr << " (the size of arrIn)!";
7687           throw INTERP_KERNEL::Exception(oss.str());
7688         }
7689     }
7690   arrOut=arro.retn();
7691   arrIndexOut=arrIo.retn();
7692 }
7693
7694 /*!
7695  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn
7696  * (\ref numbering-indirect).
7697  * This method returns the result of the extraction ( specified by a set of ids with a slice given by \a idsOfSelectStart, \a idsOfSelectStop and \a idsOfSelectStep ).
7698  * The selection of extraction is done standardly in new2old format.
7699  * This method returns indexed arrays (\ref numbering-indirect) using 2 arrays (arrOut,arrIndexOut).
7700  *
7701  * \param [in] idsOfSelectStart begin of set of ids of the input extraction (included)
7702  * \param [in] idsOfSelectStop end of set of ids of the input extraction (excluded)
7703  * \param [in] idsOfSelectStep
7704  * \param [in] arrIn arr origin array from which the extraction will be done.
7705  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7706  * \param [out] arrOut the resulting array
7707  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
7708  * \sa MEDCouplingUMesh::ExtractFromIndexedArrays
7709  */
7710 void MEDCouplingUMesh::ExtractFromIndexedArraysSlice(int idsOfSelectStart, int idsOfSelectStop, int idsOfSelectStep, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
7711                                                  DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
7712 {
7713   if(!arrIn || !arrIndxIn)
7714     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArraysSlice : input pointer is NULL !");
7715   arrIn->checkAllocated(); arrIndxIn->checkAllocated();
7716   if(arrIn->getNumberOfComponents()!=1 || arrIndxIn->getNumberOfComponents()!=1)
7717     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArraysSlice : input arrays must have exactly one component !");
7718   int sz=DataArrayInt::GetNumberOfItemGivenBESRelative(idsOfSelectStart,idsOfSelectStop,idsOfSelectStep,"MEDCouplingUMesh::ExtractFromIndexedArraysSlice : Input slice ");
7719   const int *arrInPtr=arrIn->begin();
7720   const int *arrIndxPtr=arrIndxIn->begin();
7721   int nbOfGrps=arrIndxIn->getNumberOfTuples()-1;
7722   if(nbOfGrps<0)
7723     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ExtractFromIndexedArraysSlice : The format of \"arrIndxIn\" is invalid ! Its nb of tuples should be >=1 !");
7724   int maxSizeOfArr=arrIn->getNumberOfTuples();
7725   MCAuto<DataArrayInt> arro=DataArrayInt::New();
7726   MCAuto<DataArrayInt> arrIo=DataArrayInt::New();
7727   arrIo->alloc((int)(sz+1),1);
7728   int idsIt=idsOfSelectStart;
7729   int *work=arrIo->getPointer();
7730   *work++=0;
7731   int lgth=0;
7732   for(int i=0;i<sz;i++,work++,idsIt+=idsOfSelectStep)
7733     {
7734       if(idsIt>=0 && idsIt<nbOfGrps)
7735         lgth+=arrIndxPtr[idsIt+1]-arrIndxPtr[idsIt];
7736       else
7737         {
7738           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArraysSlice : id located on pos #" << i << " value is " << idsIt << " ! Must be in [0," << nbOfGrps << ") !";
7739           throw INTERP_KERNEL::Exception(oss.str());
7740         }
7741       if(lgth>=work[-1])
7742         *work=lgth;
7743       else
7744         {
7745           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArraysSlice : id located on pos #" << i << " value is " << idsIt << " and at this pos arrIndxIn[" << idsIt;
7746           oss << "+1]-arrIndxIn[" << idsIt << "] < 0 ! The input index array is bugged !";
7747           throw INTERP_KERNEL::Exception(oss.str());
7748         }
7749     }
7750   arro->alloc(lgth,1);
7751   work=arro->getPointer();
7752   idsIt=idsOfSelectStart;
7753   for(int i=0;i<sz;i++,idsIt+=idsOfSelectStep)
7754     {
7755       if(arrIndxPtr[idsIt]>=0 && arrIndxPtr[idsIt+1]<=maxSizeOfArr)
7756         work=std::copy(arrInPtr+arrIndxPtr[idsIt],arrInPtr+arrIndxPtr[idsIt+1],work);
7757       else
7758         {
7759           std::ostringstream oss; oss << "MEDCouplingUMesh::ExtractFromIndexedArraysSlice : id located on pos #" << i << " value is " << idsIt << " arrIndx[" << idsIt << "] must be >= 0 and arrIndx[";
7760           oss << idsIt << "+1] <= " << maxSizeOfArr << " (the size of arrIn)!";
7761           throw INTERP_KERNEL::Exception(oss.str());
7762         }
7763     }
7764   arrOut=arro.retn();
7765   arrIndexOut=arrIo.retn();
7766 }
7767
7768 /*!
7769  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
7770  * This method builds an output pair (\b arrOut,\b arrIndexOut) that is a copy from \b arrIn for all cell ids \b not \b in [ \b idsOfSelectBg , \b idsOfSelectEnd ) and for
7771  * cellIds \b in [ \b idsOfSelectBg , \b idsOfSelectEnd ) a copy coming from the corresponding values in input pair (\b srcArr, \b srcArrIndex).
7772  * This method is an generalization of MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx that performs the same thing but by without building explicitely a result output arrays.
7773  *
7774  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
7775  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
7776  * \param [in] arrIn arr origin array from which the extraction will be done.
7777  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7778  * \param [in] srcArr input array that will be used as source of copy for ids in [ \b idsOfSelectBg, \b idsOfSelectEnd )
7779  * \param [in] srcArrIndex index array of \b srcArr
7780  * \param [out] arrOut the resulting array
7781  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
7782  * 
7783  * \sa MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx
7784  */
7785 void MEDCouplingUMesh::SetPartOfIndexedArrays(const int *idsOfSelectBg, const int *idsOfSelectEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
7786                                               const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex,
7787                                               DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
7788 {
7789   if(arrIn==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
7790     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArrays : presence of null pointer in input parameter !");
7791   MCAuto<DataArrayInt> arro=DataArrayInt::New();
7792   MCAuto<DataArrayInt> arrIo=DataArrayInt::New();
7793   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
7794   std::vector<bool> v(nbOfTuples,true);
7795   int offset=0;
7796   const int *arrIndxInPtr=arrIndxIn->begin();
7797   const int *srcArrIndexPtr=srcArrIndex->begin();
7798   for(const int *it=idsOfSelectBg;it!=idsOfSelectEnd;it++,srcArrIndexPtr++)
7799     {
7800       if(*it>=0 && *it<nbOfTuples)
7801         {
7802           v[*it]=false;
7803           offset+=(srcArrIndexPtr[1]-srcArrIndexPtr[0])-(arrIndxInPtr[*it+1]-arrIndxInPtr[*it]);
7804         }
7805       else
7806         {
7807           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArrays : On pos #" << std::distance(idsOfSelectBg,it) << " value is " << *it << " not in [0," << nbOfTuples << ") !";
7808           throw INTERP_KERNEL::Exception(oss.str());
7809         }
7810     }
7811   srcArrIndexPtr=srcArrIndex->begin();
7812   arrIo->alloc(nbOfTuples+1,1);
7813   arro->alloc(arrIn->getNumberOfTuples()+offset,1);
7814   const int *arrInPtr=arrIn->begin();
7815   const int *srcArrPtr=srcArr->begin();
7816   int *arrIoPtr=arrIo->getPointer(); *arrIoPtr++=0;
7817   int *arroPtr=arro->getPointer();
7818   for(int ii=0;ii<nbOfTuples;ii++,arrIoPtr++)
7819     {
7820       if(v[ii])
7821         {
7822           arroPtr=std::copy(arrInPtr+arrIndxInPtr[ii],arrInPtr+arrIndxInPtr[ii+1],arroPtr);
7823           *arrIoPtr=arrIoPtr[-1]+(arrIndxInPtr[ii+1]-arrIndxInPtr[ii]);
7824         }
7825       else
7826         {
7827           std::size_t pos=std::distance(idsOfSelectBg,std::find(idsOfSelectBg,idsOfSelectEnd,ii));
7828           arroPtr=std::copy(srcArrPtr+srcArrIndexPtr[pos],srcArrPtr+srcArrIndexPtr[pos+1],arroPtr);
7829           *arrIoPtr=arrIoPtr[-1]+(srcArrIndexPtr[pos+1]-srcArrIndexPtr[pos]);
7830         }
7831     }
7832   arrOut=arro.retn();
7833   arrIndexOut=arrIo.retn();
7834 }
7835
7836 /*!
7837  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
7838  * This method is an specialization of MEDCouplingUMesh::SetPartOfIndexedArrays in the case of assignement do not modify the index in \b arrIndxIn.
7839  *
7840  * \param [in] idsOfSelectBg begin of set of ids of the input extraction (included)
7841  * \param [in] idsOfSelectEnd end of set of ids of the input extraction (excluded)
7842  * \param [in,out] arrInOut arr origin array from which the extraction will be done.
7843  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7844  * \param [in] srcArr input array that will be used as source of copy for ids in [ \b idsOfSelectBg , \b idsOfSelectEnd )
7845  * \param [in] srcArrIndex index array of \b srcArr
7846  * 
7847  * \sa MEDCouplingUMesh::SetPartOfIndexedArrays
7848  */
7849 void MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx(const int *idsOfSelectBg, const int *idsOfSelectEnd, DataArrayInt *arrInOut, const DataArrayInt *arrIndxIn,
7850                                                      const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex)
7851 {
7852   if(arrInOut==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
7853     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx : presence of null pointer in input parameter !");
7854   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
7855   const int *arrIndxInPtr=arrIndxIn->begin();
7856   const int *srcArrIndexPtr=srcArrIndex->begin();
7857   int *arrInOutPtr=arrInOut->getPointer();
7858   const int *srcArrPtr=srcArr->begin();
7859   for(const int *it=idsOfSelectBg;it!=idsOfSelectEnd;it++,srcArrIndexPtr++)
7860     {
7861       if(*it>=0 && *it<nbOfTuples)
7862         {
7863           if(srcArrIndexPtr[1]-srcArrIndexPtr[0]==arrIndxInPtr[*it+1]-arrIndxInPtr[*it])
7864             std::copy(srcArrPtr+srcArrIndexPtr[0],srcArrPtr+srcArrIndexPtr[1],arrInOutPtr+arrIndxInPtr[*it]);
7865           else
7866             {
7867               std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx : On pos #" << std::distance(idsOfSelectBg,it) << " id (idsOfSelectBg[" << std::distance(idsOfSelectBg,it)<< "]) is " << *it << " arrIndxIn[id+1]-arrIndxIn[id]!=srcArrIndex[pos+1]-srcArrIndex[pos] !";
7868               throw INTERP_KERNEL::Exception(oss.str());
7869             }
7870         }
7871       else
7872         {
7873           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx : On pos #" << std::distance(idsOfSelectBg,it) << " value is " << *it << " not in [0," << nbOfTuples << ") !";
7874           throw INTERP_KERNEL::Exception(oss.str());
7875         }
7876     }
7877 }
7878
7879 /*!
7880  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arr indexes is in \b arrIndxIn.
7881  * This method expects that these two input arrays come from the output of MEDCouplingUMesh::computeNeighborsOfCells method.
7882  * This method start from id 0 that will be contained in output DataArrayInt. It searches then all neighbors of id0 looking at arrIn[arrIndxIn[0]:arrIndxIn[0+1]].
7883  * Then it is repeated recursively until either all ids are fetched or no more ids are reachable step by step.
7884  * A negative value in \b arrIn means that it is ignored.
7885  * This method is useful to see if a mesh is contiguous regarding its connectivity. If it is not the case the size of returned array is different from arrIndxIn->getNumberOfTuples()-1.
7886  * 
7887  * \param [in] arrIn arr origin array from which the extraction will be done.
7888  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7889  * \return a newly allocated DataArray that stores all ids fetched by the gradually spread process.
7890  * \sa MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed, MEDCouplingUMesh::partitionBySpreadZone
7891  */
7892 DataArrayInt *MEDCouplingUMesh::ComputeSpreadZoneGradually(const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn)
7893 {
7894   int seed=0,nbOfDepthPeelingPerformed=0;
7895   return ComputeSpreadZoneGraduallyFromSeed(&seed,&seed+1,arrIn,arrIndxIn,-1,nbOfDepthPeelingPerformed);
7896 }
7897
7898 /*!
7899  * This method works on a pair input (\b arrIn, \b arrIndxIn) where \b arr indexes is in \b arrIndxIn.
7900  * This method expects that these two input arrays come from the output of MEDCouplingUMesh::computeNeighborsOfCells method.
7901  * This method start from id 0 that will be contained in output DataArrayInt. It searches then all neighbors of id0 regarding arrIn[arrIndxIn[0]:arrIndxIn[0+1]].
7902  * Then it is repeated recursively until either all ids are fetched or no more ids are reachable step by step.
7903  * A negative value in \b arrIn means that it is ignored.
7904  * This method is useful to see if a mesh is contiguous regarding its connectivity. If it is not the case the size of returned array is different from arrIndxIn->getNumberOfTuples()-1.
7905  * \param [in] seedBg the begin pointer (included) of an array containing the seed of the search zone
7906  * \param [in] seedEnd the end pointer (not included) of an array containing the seed of the search zone
7907  * \param [in] arrIn arr origin array from which the extraction will be done.
7908  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7909  * \param [in] nbOfDepthPeeling the max number of peels requested in search. By default -1, that is to say, no limit.
7910  * \param [out] nbOfDepthPeelingPerformed the number of peels effectively performed. May be different from \a nbOfDepthPeeling
7911  * \return a newly allocated DataArray that stores all ids fetched by the gradually spread process.
7912  * \sa MEDCouplingUMesh::partitionBySpreadZone
7913  */
7914 DataArrayInt *MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed(const int *seedBg, const int *seedEnd, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn, int nbOfDepthPeeling, int& nbOfDepthPeelingPerformed)
7915 {
7916   nbOfDepthPeelingPerformed=0;
7917   if(!arrIndxIn)
7918     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeSpreadZoneGraduallyFromSeed : arrIndxIn input pointer is NULL !");
7919   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
7920   if(nbOfTuples<=0)
7921     {
7922       DataArrayInt *ret=DataArrayInt::New(); ret->alloc(0,1);
7923       return ret;
7924     }
7925   //
7926   std::vector<bool> fetched(nbOfTuples,false);
7927   return ComputeSpreadZoneGraduallyFromSeedAlg(fetched,seedBg,seedEnd,arrIn,arrIndxIn,nbOfDepthPeeling,nbOfDepthPeelingPerformed);
7928 }
7929
7930
7931 /*!
7932  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
7933  * This method builds an output pair (\b arrOut,\b arrIndexOut) that is a copy from \b arrIn for all cell ids \b not \b in [ \b idsOfSelectBg , \b idsOfSelectEnd ) and for
7934  * cellIds \b in [\b idsOfSelectBg, \b idsOfSelectEnd) a copy coming from the corresponding values in input pair (\b srcArr, \b srcArrIndex).
7935  * This method is an generalization of MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx that performs the same thing but by without building explicitely a result output arrays.
7936  *
7937  * \param [in] start begin of set of ids of the input extraction (included)
7938  * \param [in] end end of set of ids of the input extraction (excluded)
7939  * \param [in] step step of the set of ids in range mode.
7940  * \param [in] arrIn arr origin array from which the extraction will be done.
7941  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
7942  * \param [in] srcArr input array that will be used as source of copy for ids in [\b idsOfSelectBg, \b idsOfSelectEnd)
7943  * \param [in] srcArrIndex index array of \b srcArr
7944  * \param [out] arrOut the resulting array
7945  * \param [out] arrIndexOut the index array of the resulting array \b arrOut
7946  * 
7947  * \sa MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx MEDCouplingUMesh::SetPartOfIndexedArrays
7948  */
7949 void MEDCouplingUMesh::SetPartOfIndexedArraysSlice(int start, int end, int step, const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn,
7950                                                const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex,
7951                                                DataArrayInt* &arrOut, DataArrayInt* &arrIndexOut)
7952 {
7953   if(arrIn==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
7954     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArraysSlice : presence of null pointer in input parameter !");
7955   MCAuto<DataArrayInt> arro=DataArrayInt::New();
7956   MCAuto<DataArrayInt> arrIo=DataArrayInt::New();
7957   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
7958   int offset=0;
7959   const int *arrIndxInPtr=arrIndxIn->begin();
7960   const int *srcArrIndexPtr=srcArrIndex->begin();
7961   int nbOfElemsToSet=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::SetPartOfIndexedArraysSlice : ");
7962   int it=start;
7963   for(int i=0;i<nbOfElemsToSet;i++,srcArrIndexPtr++,it+=step)
7964     {
7965       if(it>=0 && it<nbOfTuples)
7966         offset+=(srcArrIndexPtr[1]-srcArrIndexPtr[0])-(arrIndxInPtr[it+1]-arrIndxInPtr[it]);
7967       else
7968         {
7969           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSlice : On pos #" << i << " value is " << it << " not in [0," << nbOfTuples << ") !";
7970           throw INTERP_KERNEL::Exception(oss.str());
7971         }
7972     }
7973   srcArrIndexPtr=srcArrIndex->begin();
7974   arrIo->alloc(nbOfTuples+1,1);
7975   arro->alloc(arrIn->getNumberOfTuples()+offset,1);
7976   const int *arrInPtr=arrIn->begin();
7977   const int *srcArrPtr=srcArr->begin();
7978   int *arrIoPtr=arrIo->getPointer(); *arrIoPtr++=0;
7979   int *arroPtr=arro->getPointer();
7980   for(int ii=0;ii<nbOfTuples;ii++,arrIoPtr++)
7981     {
7982       int pos=DataArray::GetPosOfItemGivenBESRelativeNoThrow(ii,start,end,step);
7983       if(pos<0)
7984         {
7985           arroPtr=std::copy(arrInPtr+arrIndxInPtr[ii],arrInPtr+arrIndxInPtr[ii+1],arroPtr);
7986           *arrIoPtr=arrIoPtr[-1]+(arrIndxInPtr[ii+1]-arrIndxInPtr[ii]);
7987         }
7988       else
7989         {
7990           arroPtr=std::copy(srcArrPtr+srcArrIndexPtr[pos],srcArrPtr+srcArrIndexPtr[pos+1],arroPtr);
7991           *arrIoPtr=arrIoPtr[-1]+(srcArrIndexPtr[pos+1]-srcArrIndexPtr[pos]);
7992         }
7993     }
7994   arrOut=arro.retn();
7995   arrIndexOut=arrIo.retn();
7996 }
7997
7998 /*!
7999  * This method works on an input pair (\b arrIn, \b arrIndxIn) where \b arrIn indexes is in \b arrIndxIn.
8000  * This method is an specialization of MEDCouplingUMesh::SetPartOfIndexedArrays in the case of assignement do not modify the index in \b arrIndxIn.
8001  *
8002  * \param [in] start begin of set of ids of the input extraction (included)
8003  * \param [in] end end of set of ids of the input extraction (excluded)
8004  * \param [in] step step of the set of ids in range mode.
8005  * \param [in,out] arrInOut arr origin array from which the extraction will be done.
8006  * \param [in] arrIndxIn is the input index array allowing to walk into \b arrIn
8007  * \param [in] srcArr input array that will be used as source of copy for ids in [\b idsOfSelectBg, \b idsOfSelectEnd)
8008  * \param [in] srcArrIndex index array of \b srcArr
8009  * 
8010  * \sa MEDCouplingUMesh::SetPartOfIndexedArraysSlice MEDCouplingUMesh::SetPartOfIndexedArraysSameIdx
8011  */
8012 void MEDCouplingUMesh::SetPartOfIndexedArraysSameIdxSlice(int start, int end, int step, DataArrayInt *arrInOut, const DataArrayInt *arrIndxIn,
8013                                                       const DataArrayInt *srcArr, const DataArrayInt *srcArrIndex)
8014 {
8015   if(arrInOut==0 || arrIndxIn==0 || srcArr==0 || srcArrIndex==0)
8016     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::SetPartOfIndexedArraysSameIdxSlice : presence of null pointer in input parameter !");
8017   int nbOfTuples=arrIndxIn->getNumberOfTuples()-1;
8018   const int *arrIndxInPtr=arrIndxIn->begin();
8019   const int *srcArrIndexPtr=srcArrIndex->begin();
8020   int *arrInOutPtr=arrInOut->getPointer();
8021   const int *srcArrPtr=srcArr->begin();
8022   int nbOfElemsToSet=DataArray::GetNumberOfItemGivenBESRelative(start,end,step,"MEDCouplingUMesh::SetPartOfIndexedArraysSameIdxSlice : ");
8023   int it=start;
8024   for(int i=0;i<nbOfElemsToSet;i++,srcArrIndexPtr++,it+=step)
8025     {
8026       if(it>=0 && it<nbOfTuples)
8027         {
8028           if(srcArrIndexPtr[1]-srcArrIndexPtr[0]==arrIndxInPtr[it+1]-arrIndxInPtr[it])
8029             std::copy(srcArrPtr+srcArrIndexPtr[0],srcArrPtr+srcArrIndexPtr[1],arrInOutPtr+arrIndxInPtr[it]);
8030           else
8031             {
8032               std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdxSlice : On pos #" << i << " id (idsOfSelectBg[" << i << "]) is " << it << " arrIndxIn[id+1]-arrIndxIn[id]!=srcArrIndex[pos+1]-srcArrIndex[pos] !";
8033               throw INTERP_KERNEL::Exception(oss.str());
8034             }
8035         }
8036       else
8037         {
8038           std::ostringstream oss; oss << "MEDCouplingUMesh::SetPartOfIndexedArraysSameIdxSlice : On pos #" << i << " value is " << it << " not in [0," << nbOfTuples << ") !";
8039           throw INTERP_KERNEL::Exception(oss.str());
8040         }
8041     }
8042 }
8043
8044 /*!
8045  * \b this is expected to be a mesh fully defined whose spaceDim==meshDim.
8046  * It returns a new allocated mesh having the same mesh dimension and lying on same coordinates.
8047  * The returned mesh contains as poly cells as number of contiguous zone (regarding connectivity).
8048  * A spread contiguous zone is built using poly cells (polyhedra in 3D, polygons in 2D and polyline in 1D).
8049  * The sum of measure field of returned mesh is equal to the sum of measure field of this.
8050  * 
8051  * \return a newly allocated mesh lying on the same coords than \b this with same meshdimension than \b this.
8052  */
8053 MEDCouplingUMesh *MEDCouplingUMesh::buildSpreadZonesWithPoly() const
8054 {
8055   checkFullyDefined();
8056   int mdim=getMeshDimension();
8057   int spaceDim=getSpaceDimension();
8058   if(mdim!=spaceDim)
8059     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSpreadZonesWithPoly : meshdimension and spacedimension do not match !");
8060   std::vector<DataArrayInt *> partition=partitionBySpreadZone();
8061   std::vector< MCAuto<DataArrayInt> > partitionAuto; partitionAuto.reserve(partition.size());
8062   std::copy(partition.begin(),partition.end(),std::back_insert_iterator<std::vector< MCAuto<DataArrayInt> > >(partitionAuto));
8063   MCAuto<MEDCouplingUMesh> ret=MEDCouplingUMesh::New(getName(),mdim);
8064   ret->setCoords(getCoords());
8065   ret->allocateCells((int)partition.size());
8066   //
8067   for(std::vector<DataArrayInt *>::const_iterator it=partition.begin();it!=partition.end();it++)
8068     {
8069       MCAuto<MEDCouplingUMesh> tmp=static_cast<MEDCouplingUMesh *>(buildPartOfMySelf((*it)->begin(),(*it)->end(),true));
8070       MCAuto<DataArrayInt> cell;
8071       switch(mdim)
8072       {
8073         case 2:
8074           cell=tmp->buildUnionOf2DMesh();
8075           break;
8076         case 3:
8077           cell=tmp->buildUnionOf3DMesh();
8078           break;
8079         default:
8080           throw INTERP_KERNEL::Exception("MEDCouplingUMesh::buildSpreadZonesWithPoly : meshdimension supported are [2,3] ! Not implemented yet for others !");
8081       }
8082
8083       ret->insertNextCell((INTERP_KERNEL::NormalizedCellType)cell->getIJSafe(0,0),cell->getNumberOfTuples()-1,cell->begin()+1);
8084     }
8085   //
8086   ret->finishInsertingCells();
8087   return ret.retn();
8088 }
8089
8090 /*!
8091  * This method partitions \b this into contiguous zone.
8092  * This method only needs a well defined connectivity. Coordinates are not considered here.
8093  * This method returns a vector of \b newly allocated arrays that the caller has to deal with.
8094  */
8095 std::vector<DataArrayInt *> MEDCouplingUMesh::partitionBySpreadZone() const
8096 {
8097   DataArrayInt *neigh=0,*neighI=0;
8098   computeNeighborsOfCells(neigh,neighI);
8099   MCAuto<DataArrayInt> neighAuto(neigh),neighIAuto(neighI);
8100   return PartitionBySpreadZone(neighAuto,neighIAuto);
8101 }
8102
8103 std::vector<DataArrayInt *> MEDCouplingUMesh::PartitionBySpreadZone(const DataArrayInt *arrIn, const DataArrayInt *arrIndxIn)
8104 {
8105   if(!arrIn || !arrIndxIn)
8106     throw INTERP_KERNEL::Exception("PartitionBySpreadZone : null input pointers !");
8107   arrIn->checkAllocated(); arrIndxIn->checkAllocated();
8108   int nbOfTuples(arrIndxIn->getNumberOfTuples());
8109   if(arrIn->getNumberOfComponents()!=1 || arrIndxIn->getNumberOfComponents()!=1 || nbOfTuples<1)
8110     throw INTERP_KERNEL::Exception("PartitionBySpreadZone : invalid arrays in input !");
8111   int nbOfCellsCur(nbOfTuples-1);
8112   std::vector<DataArrayInt *> ret;
8113   if(nbOfCellsCur<=0)
8114     return ret;
8115   std::vector<bool> fetchedCells(nbOfCellsCur,false);
8116   std::vector< MCAuto<DataArrayInt> > ret2;
8117   int seed=0;
8118   while(seed<nbOfCellsCur)
8119     {
8120       int nbOfPeelPerformed=0;
8121       ret2.push_back(ComputeSpreadZoneGraduallyFromSeedAlg(fetchedCells,&seed,&seed+1,arrIn,arrIndxIn,-1,nbOfPeelPerformed));
8122       seed=(int)std::distance(fetchedCells.begin(),std::find(fetchedCells.begin()+seed,fetchedCells.end(),false));
8123     }
8124   for(std::vector< MCAuto<DataArrayInt> >::iterator it=ret2.begin();it!=ret2.end();it++)
8125     ret.push_back((*it).retn());
8126   return ret;
8127 }
8128
8129 /*!
8130  * This method returns given a distribution of cell type (returned for example by MEDCouplingUMesh::getDistributionOfTypes method and customized after) a
8131  * newly allocated DataArrayInt instance with 2 components ready to be interpreted as input of DataArrayInt::findRangeIdForEachTuple method.
8132  *
8133  * \param [in] code a code with the same format than those returned by MEDCouplingUMesh::getDistributionOfTypes except for the code[3*k+2] that should contain start id of chunck.
8134  * \return a newly allocated DataArrayInt to be managed by the caller.
8135  * \throw In case of \a code has not the right format (typically of size 3*n)
8136  */
8137 DataArrayInt *MEDCouplingUMesh::ComputeRangesFromTypeDistribution(const std::vector<int>& code)
8138 {
8139   MCAuto<DataArrayInt> ret=DataArrayInt::New();
8140   std::size_t nb=code.size()/3;
8141   if(code.size()%3!=0)
8142     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::ComputeRangesFromTypeDistribution : invalid input code !");
8143   ret->alloc((int)nb,2);
8144   int *retPtr=ret->getPointer();
8145   for(std::size_t i=0;i<nb;i++,retPtr+=2)
8146     {
8147       retPtr[0]=code[3*i+2];
8148       retPtr[1]=code[3*i+2]+code[3*i+1];
8149     }
8150   return ret.retn();
8151 }
8152
8153 /*!
8154  * This method expects that \a this a 3D mesh (spaceDim=3 and meshDim=3) with all coordinates and connectivities set.
8155  * All cells in \a this are expected to be linear 3D cells.
8156  * This method will split **all** 3D cells in \a this into INTERP_KERNEL::NORM_TETRA4 cells and put them in the returned mesh.
8157  * It leads to an increase to number of cells.
8158  * This method contrary to MEDCouplingUMesh::simplexize can append coordinates in \a this to perform its work.
8159  * The \a nbOfAdditionalPoints returned value informs about it. If > 0, the coordinates array in returned mesh will have \a nbOfAdditionalPoints 
8160  * more tuples (nodes) than in \a this. Anyway, all the nodes in \a this (with the same order) will be in the returned mesh.
8161  *
8162  * \param [in] policy - the policy of splitting that must be in (PLANAR_FACE_5, PLANAR_FACE_6, GENERAL_24, GENERAL_48). The policy will be used only for INTERP_KERNEL::NORM_HEXA8 cells.
8163  *                      For all other cells, the splitting policy will be ignored. See INTERP_KERNEL::SplittingPolicy for the images.
8164  * \param [out] nbOfAdditionalPoints - number of nodes added to \c this->_coords. If > 0 a new coordinates object will be constructed result of the aggregation of the old one and the new points added. 
8165  * \param [out] n2oCells - A new instance of DataArrayInt holding, for each new cell,
8166  *          an id of old cell producing it. The caller is to delete this array using
8167  *         decrRef() as it is no more needed.
8168  * \return MEDCoupling1SGTUMesh * - the mesh containing only INTERP_KERNEL::NORM_TETRA4 cells.
8169  *
8170  * \warning This method operates on each cells in this independantly ! So it can leads to non conform mesh in returned value ! If you expect to have a conform mesh in output
8171  * the policy PLANAR_FACE_6 should be used on a mesh sorted with MEDCoupling1SGTUMesh::sortHexa8EachOther.
8172  * 
8173  * \throw If \a this is not a 3D mesh (spaceDim==3 and meshDim==3).
8174  * \throw If \a this is not fully constituted with linear 3D cells.
8175  * \sa MEDCouplingUMesh::simplexize, MEDCoupling1SGTUMesh::sortHexa8EachOther
8176  */
8177 MEDCoupling1SGTUMesh *MEDCouplingUMesh::tetrahedrize(int policy, DataArrayInt *& n2oCells, int& nbOfAdditionalPoints) const
8178 {
8179   INTERP_KERNEL::SplittingPolicy pol((INTERP_KERNEL::SplittingPolicy)policy);
8180   checkConnectivityFullyDefined();
8181   if(getMeshDimension()!=3 || getSpaceDimension()!=3)
8182     throw INTERP_KERNEL::Exception("MEDCouplingUMesh::tetrahedrize : only available for mesh with meshdim == 3 and spacedim == 3 !");
8183   int nbOfCells(getNumberOfCells()),nbNodes(getNumberOfNodes());
8184   MCAuto<MEDCoupling1SGTUMesh> ret0(MEDCoupling1SGTUMesh::New(getName(),INTERP_KERNEL::NORM_TETRA4));
8185   MCAuto<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(nbOfCells,1);
8186   int *retPt(ret->getPointer());
8187   MCAuto<DataArrayInt> newConn(DataArrayInt::New()); newConn->alloc(0,1);
8188   MCAuto<DataArrayDouble> addPts(DataArrayDouble::New()); addPts->alloc(0,1);
8189   const int *oldc(_nodal_connec->begin());
8190   const int *oldci(_nodal_connec_index->begin());
8191   const double *coords(_coords->begin());
8192   for(int i=0;i<nbOfCells;i++,oldci++,retPt++)
8193     {
8194       std::vector<int> a; std::vector<double> b;
8195       INTERP_KERNEL::SplitIntoTetras(pol,(INTERP_KERNEL::NormalizedCellType)oldc[oldci[0]],oldc+oldci[0]+1,oldc+oldci[1],coords,a,b);
8196       std::size_t nbOfTet(a.size()/4); *retPt=(int)nbOfTet;
8197       const int *aa(&a[0]);
8198       if(!b.empty())
8199         {
8200           for(std::vector<int>::iterator it=a.begin();it!=a.end();it++)
8201             if(*it<0)
8202               *it=(-(*(it))-1+nbNodes);
8203           addPts->insertAtTheEnd(b.begin(),b.end());
8204           nbNodes+=(int)b.size()/3;
8205         }
8206       for(std::size_t j=0;j<nbOfTet;j++,aa+=4)
8207         newConn->insertAtTheEnd(aa,aa+4);
8208     }
8209   if(!addPts->empty())
8210     {
8211       addPts->rearrange(3);
8212       nbOfAdditionalPoints=addPts->getNumberOfTuples();
8213       addPts=DataArrayDouble::Aggregate(getCoords(),addPts);
8214       ret0->setCoords(addPts);
8215     }
8216   else
8217     {
8218       nbOfAdditionalPoints=0;
8219       ret0->setCoords(getCoords());
8220     }
8221   ret0->setNodalConnectivity(newConn);
8222   //
8223   ret->computeOffsetsFull();
8224   n2oCells=ret->buildExplicitArrOfSliceOnScaledArr(0,nbOfCells,1);
8225   return ret0.retn();
8226 }
8227
8228 MEDCouplingUMeshCellIterator::MEDCouplingUMeshCellIterator(MEDCouplingUMesh *mesh):_mesh(mesh),_cell(new MEDCouplingUMeshCell(mesh)),
8229     _own_cell(true),_cell_id(-1),_nb_cell(0)
8230 {
8231   if(mesh)
8232     {
8233       mesh->incrRef();
8234       _nb_cell=mesh->getNumberOfCells();
8235     }
8236 }
8237
8238 MEDCouplingUMeshCellIterator::~MEDCouplingUMeshCellIterator()
8239 {
8240   if(_mesh)
8241     _mesh->decrRef();
8242   if(_own_cell)
8243     delete _cell;
8244 }
8245
8246 MEDCouplingUMeshCellIterator::MEDCouplingUMeshCellIterator(MEDCouplingUMesh *mesh, MEDCouplingUMeshCell *itc, int bg, int end):_mesh(mesh),_cell(itc),
8247     _own_cell(false),_cell_id(bg-1),
8248     _nb_cell(end)
8249 {
8250   if(mesh)
8251     mesh->incrRef();
8252 }
8253
8254 MEDCouplingUMeshCell *MEDCouplingUMeshCellIterator::nextt()
8255 {
8256   _cell_id++;
8257   if(_cell_id<_nb_cell)
8258     {
8259       _cell->next();
8260       return _cell;
8261     }
8262   else
8263     return 0;
8264 }
8265
8266 MEDCouplingUMeshCellByTypeEntry::MEDCouplingUMeshCellByTypeEntry(MEDCouplingUMesh *mesh):_mesh(mesh)
8267 {
8268   if(_mesh)
8269     _mesh->incrRef();
8270 }
8271
8272 MEDCouplingUMeshCellByTypeIterator *MEDCouplingUMeshCellByTypeEntry::iterator()
8273 {
8274   return new MEDCouplingUMeshCellByTypeIterator(_mesh);
8275 }
8276
8277 MEDCouplingUMeshCellByTypeEntry::~MEDCouplingUMeshCellByTypeEntry()
8278 {
8279   if(_mesh)
8280     _mesh->decrRef();
8281 }
8282
8283 MEDCouplingUMeshCellEntry::MEDCouplingUMeshCellEntry(MEDCouplingUMesh *mesh,  INTERP_KERNEL::NormalizedCellType type, MEDCouplingUMeshCell *itc, int bg, int end):_mesh(mesh),_type(type),
8284     _itc(itc),
8285     _bg(bg),_end(end)
8286 {
8287   if(_mesh)
8288     _mesh->incrRef();
8289 }
8290
8291 MEDCouplingUMeshCellEntry::~MEDCouplingUMeshCellEntry()
8292 {
8293   if(_mesh)
8294     _mesh->decrRef();
8295 }
8296
8297 INTERP_KERNEL::NormalizedCellType MEDCouplingUMeshCellEntry::getType() const
8298 {
8299   return _type;
8300 }
8301
8302 int MEDCouplingUMeshCellEntry::getNumberOfElems() const
8303 {
8304   return _end-_bg;
8305 }
8306
8307 MEDCouplingUMeshCellIterator *MEDCouplingUMeshCellEntry::iterator()
8308 {
8309   return new MEDCouplingUMeshCellIterator(_mesh,_itc,_bg,_end);
8310 }
8311
8312 MEDCouplingUMeshCellByTypeIterator::MEDCouplingUMeshCellByTypeIterator(MEDCouplingUMesh *mesh):_mesh(mesh),_cell(new MEDCouplingUMeshCell(mesh)),_cell_id(0),_nb_cell(0)
8313 {
8314   if(mesh)
8315     {
8316       mesh->incrRef();
8317       _nb_cell=mesh->getNumberOfCells();
8318     }
8319 }
8320
8321 MEDCouplingUMeshCellByTypeIterator::~MEDCouplingUMeshCellByTypeIterator()
8322 {
8323   if(_mesh)
8324     _mesh->decrRef();
8325   delete _cell;
8326 }
8327
8328 MEDCouplingUMeshCellEntry *MEDCouplingUMeshCellByTypeIterator::nextt()
8329 {
8330   const int *c=_mesh->getNodalConnectivity()->begin();
8331   const int *ci=_mesh->getNodalConnectivityIndex()->begin();
8332   if(_cell_id<_nb_cell)
8333     {
8334       INTERP_KERNEL::NormalizedCellType type=(INTERP_KERNEL::NormalizedCellType)c[ci[_cell_id]];
8335       int nbOfElems=(int)std::distance(ci+_cell_id,std::find_if(ci+_cell_id,ci+_nb_cell,MEDCouplingImpl::ConnReader(c,type)));
8336       int startId=_cell_id;
8337       _cell_id+=nbOfElems;
8338       return new MEDCouplingUMeshCellEntry(_mesh,type,_cell,startId,_cell_id);
8339     }
8340   else
8341     return 0;
8342 }
8343
8344 MEDCouplingUMeshCell::MEDCouplingUMeshCell(MEDCouplingUMesh *mesh):_conn(0),_conn_indx(0),_conn_lgth(NOTICABLE_FIRST_VAL)
8345 {
8346   if(mesh)
8347     {
8348       _conn=mesh->getNodalConnectivity()->getPointer();
8349       _conn_indx=mesh->getNodalConnectivityIndex()->getPointer();
8350     }
8351 }
8352
8353 void MEDCouplingUMeshCell::next()
8354 {
8355   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
8356     {
8357       _conn+=_conn_lgth;
8358       _conn_indx++;
8359     }
8360   _conn_lgth=_conn_indx[1]-_conn_indx[0];
8361 }
8362
8363 std::string MEDCouplingUMeshCell::repr() const
8364 {
8365   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
8366     {
8367       std::ostringstream oss; oss << "Cell Type " << INTERP_KERNEL::CellModel::GetCellModel((INTERP_KERNEL::NormalizedCellType)_conn[0]).getRepr();
8368       oss << " : ";
8369       std::copy(_conn+1,_conn+_conn_lgth,std::ostream_iterator<int>(oss," "));
8370       return oss.str();
8371     }
8372   else
8373     return std::string("MEDCouplingUMeshCell::repr : Invalid pos");
8374 }
8375
8376 INTERP_KERNEL::NormalizedCellType MEDCouplingUMeshCell::getType() const
8377 {
8378   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
8379     return (INTERP_KERNEL::NormalizedCellType)_conn[0];
8380   else
8381     return INTERP_KERNEL::NORM_ERROR;
8382 }
8383
8384 const int *MEDCouplingUMeshCell::getAllConn(int& lgth) const
8385 {
8386   lgth=_conn_lgth;
8387   if(_conn_lgth!=NOTICABLE_FIRST_VAL)
8388     return _conn;
8389   else
8390     return 0;
8391 }