Salome HOME
0208d74252444c61d10a36697299ab530b01b0d0
[tools/medcoupling.git] / src / MEDCoupling / MEDCouplingCartesianAMRMesh.cxx
1 // Copyright (C) 2007-2014  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
20
21 #include "MEDCouplingCartesianAMRMesh.hxx"
22 #include "MEDCoupling1GTUMesh.hxx"
23 #include "MEDCouplingIMesh.hxx"
24 #include "MEDCouplingUMesh.hxx"
25
26 #include <limits>
27 #include <sstream>
28 #include <numeric>
29
30 using namespace ParaMEDMEM;
31
32 /// @cond INTERNAL
33
34 int MEDCouplingCartesianAMRPatchGen::getNumberOfCellsRecursiveWithOverlap() const
35 {
36   return _mesh->getNumberOfCellsRecursiveWithOverlap();
37 }
38
39 int MEDCouplingCartesianAMRPatchGen::getNumberOfCellsRecursiveWithoutOverlap() const
40 {
41   return _mesh->getNumberOfCellsRecursiveWithoutOverlap();
42 }
43
44 int MEDCouplingCartesianAMRPatchGen::getMaxNumberOfLevelsRelativeToThis() const
45 {
46   return _mesh->getMaxNumberOfLevelsRelativeToThis();
47 }
48
49 MEDCouplingCartesianAMRPatchGen::MEDCouplingCartesianAMRPatchGen(MEDCouplingCartesianAMRMeshGen *mesh)
50 {
51   if(!mesh)
52     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatchGen constructor : input mesh is NULL !");
53   _mesh=mesh; _mesh->incrRef();
54 }
55
56 const MEDCouplingCartesianAMRMeshGen *MEDCouplingCartesianAMRPatchGen::getMeshSafe() const
57 {
58   const MEDCouplingCartesianAMRMeshGen *mesh(_mesh);
59   if(!mesh)
60     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatchGen::getMeshSafe const : the mesh is NULL !");
61   return mesh;
62 }
63
64 MEDCouplingCartesianAMRMeshGen *MEDCouplingCartesianAMRPatchGen::getMeshSafe()
65 {
66   MEDCouplingCartesianAMRMeshGen *mesh(_mesh);
67     if(!mesh)
68       throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatchGen::getMeshSafe : the mesh is NULL !");
69     return mesh;
70 }
71
72 std::vector<const BigMemoryObject *> MEDCouplingCartesianAMRPatchGen::getDirectChildren() const
73 {
74   std::vector<const BigMemoryObject *> ret;
75   if((const MEDCouplingCartesianAMRMeshGen *)_mesh)
76     ret.push_back((const MEDCouplingCartesianAMRMeshGen *)_mesh);
77   return ret;
78 }
79
80 /*!
81  * \param [in] mesh not null pointer of refined mesh replacing the cell range of \a father defined by the bottom left and top right just after.
82  * \param [in] bottomLeftTopRight a vector equal to the space dimension of \a mesh that specifies for each dimension, the included cell start of the range for the first element of the pair,
83  *                                a the end cell (\b excluded) of the range for the second element of the pair.
84  */
85 MEDCouplingCartesianAMRPatch::MEDCouplingCartesianAMRPatch(MEDCouplingCartesianAMRMeshGen *mesh, const std::vector< std::pair<int,int> >& bottomLeftTopRight):MEDCouplingCartesianAMRPatchGen(mesh),_bl_tr(bottomLeftTopRight)
86 {
87   int dim((int)bottomLeftTopRight.size()),dimExp(_mesh->getSpaceDimension());
88   if(dim!=dimExp)
89     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatch constructor : space dimension of father and input bottomLeft/topRight size mismatches !");
90 }
91
92 void MEDCouplingCartesianAMRPatch::addPatch(const std::vector< std::pair<int,int> >& bottomLeftTopRight, const std::vector<int>& factors)
93 {
94   return getMeshSafe()->addPatch(bottomLeftTopRight,factors);
95 }
96
97 int MEDCouplingCartesianAMRPatch::getNumberOfOverlapedCellsForFather() const
98 {
99   return MEDCouplingStructuredMesh::DeduceNumberOfGivenRangeInCompactFrmt(_bl_tr);
100 }
101
102 /*!
103  * This method states if \a other patch is in the neighborhood of \a this. The neighborhood zone is defined by \a ghostLev parameter
104  * the must be >= 0.
105  *
106  * \param [in] other - The other patch
107  * \param [in] ghostLev - The size of the neighborhood zone.
108  *
109  * \throw if \a this or \a other are invalid (end before start).
110  * \throw if \a ghostLev is \b not >= 0 .
111  * \throw if \a this and \a other have not the same space dimension.
112  */
113 bool MEDCouplingCartesianAMRPatch::isInMyNeighborhood(const MEDCouplingCartesianAMRPatch *other, int ghostLev) const
114 {
115   if(ghostLev<0)
116     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatch::isInMyNeighborhood : the size of the neighborhood must be >= 0 !");
117   if(!other)
118     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatch::isInMyNeighborhood : the input patch is NULL !");
119   const std::vector< std::pair<int,int> >& thisp(getBLTRRange());
120   const std::vector< std::pair<int,int> >& otherp(other->getBLTRRange());
121   std::size_t thispsize(thisp.size());
122   if(thispsize!=otherp.size())
123     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatch::isInMyNeighborhood : the dimensions must be the same !");
124   for(std::size_t i=0;i<thispsize;i++)
125     {
126       const std::pair<int,int>& thispp(thisp[i]);
127       const std::pair<int,int>& otherpp(otherp[i]);
128       if(thispp.second<thispp.first)
129         throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatch::isInMyNeighborhood : this patch is invalid !");
130       if(otherpp.second<otherpp.first)
131         throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRPatch::isInMyNeighborhood : this patch is invalid !");
132       if(otherpp.first==thispp.second+ghostLev-1)
133         continue;
134       if(otherpp.second+ghostLev-1==thispp.first)
135         continue;
136       int start(std::max(thispp.first,otherpp.first)),end(std::min(thispp.second,otherpp.second));
137       if(end<start)
138         return false;
139     }
140   return true;
141 }
142
143 std::size_t MEDCouplingCartesianAMRPatch::getHeapMemorySizeWithoutChildren() const
144 {
145   std::size_t ret(sizeof(MEDCouplingCartesianAMRPatch));
146   ret+=_bl_tr.capacity()*sizeof(std::pair<int,int>);
147   return ret;
148 }
149
150 MEDCouplingCartesianAMRPatchGF::MEDCouplingCartesianAMRPatchGF(MEDCouplingCartesianAMRMesh *mesh):MEDCouplingCartesianAMRPatchGen(mesh)
151 {
152 }
153
154 std::size_t MEDCouplingCartesianAMRPatchGF::getHeapMemorySizeWithoutChildren() const
155 {
156   return sizeof(MEDCouplingCartesianAMRPatchGF);
157 }
158
159 MEDCouplingDataForGodFather::MEDCouplingDataForGodFather(MEDCouplingCartesianAMRMesh *gf):_gf(gf),_tlc(gf)
160 {
161   if(!_gf)
162     throw INTERP_KERNEL::Exception("MEDCouplingDataForGodFather constructor : A data has to be attached to a AMR Mesh instance !");
163   _gf->setData(this);
164 }
165
166 void MEDCouplingDataForGodFather::checkGodFatherFrozen() const
167 {
168   _tlc.checkConst();
169 }
170
171 bool MEDCouplingDataForGodFather::changeGodFather(MEDCouplingCartesianAMRMesh *gf)
172 {
173   bool ret(_tlc.keepTrackOfNewTL(gf));
174   if(ret)
175     {
176       _gf=gf;
177     }
178   return ret;
179 }
180
181 /// @endcond
182
183 int MEDCouplingCartesianAMRMeshGen::getSpaceDimension() const
184 {
185   return _mesh->getSpaceDimension();
186 }
187
188 void MEDCouplingCartesianAMRMeshGen::setFactors(const std::vector<int>& newFactors)
189 {
190   if(getSpaceDimension()!=(int)newFactors.size())
191     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen::setFactors : size of input factors is not equal to the space dimension !");
192   if(_factors.empty())
193     {
194       _factors=newFactors;
195       return ;
196     }
197   if(_factors==newFactors)
198     return ;
199   if(!_patches.empty())
200     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen::setFactors : modification of factors is not allowed when presence of patches !");
201   _factors=newFactors;
202   declareAsNew();
203 }
204
205 int MEDCouplingCartesianAMRMeshGen::getMaxNumberOfLevelsRelativeToThis() const
206 {
207   int ret(1);
208   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
209     ret=std::max(ret,(*it)->getMaxNumberOfLevelsRelativeToThis()+1);
210   return ret;
211 }
212
213 /*!
214  * This method returns the number of cells of \a this with the help of the MEDCouplingIMesh instance representing \a this.
215  * The patches in \a this are ignored here.
216  * \sa getNumberOfCellsAtCurrentLevelGhost, getNumberOfCellsRecursiveWithOverlap
217  */
218 int MEDCouplingCartesianAMRMeshGen::getNumberOfCellsAtCurrentLevel() const
219 {
220   return _mesh->getNumberOfCells();
221 }
222
223 /*!
224  * This method returns the number of cells of \a this with the help of the MEDCouplingIMesh instance representing \a this enlarged by \a ghostLev size
225  * to take into account of the ghost cells for future computation.
226  * The patches in \a this are ignored here.
227  *
228  * \sa getNumberOfCellsAtCurrentLevel
229  */
230 int MEDCouplingCartesianAMRMeshGen::getNumberOfCellsAtCurrentLevelGhost(int ghostLev) const
231 {
232   MEDCouplingAutoRefCountObjectPtr<MEDCouplingIMesh> tmp(_mesh->buildWithGhost(ghostLev));
233   return tmp->getNumberOfCells();
234 }
235
236 /*!
237  * This method returns the number of cells including the current level but \b also \b including recursively all cells of other levels
238  * starting from this. The set of cells which size is returned here are generally overlapping each other.
239  */
240 int MEDCouplingCartesianAMRMeshGen::getNumberOfCellsRecursiveWithOverlap() const
241 {
242   int ret(_mesh->getNumberOfCells());
243   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
244     {
245       ret+=(*it)->getNumberOfCellsRecursiveWithOverlap();
246     }
247   return ret;
248 }
249
250 /*!
251  * This method returns the max number of cells covering all the space without overlapping.
252  */
253 int MEDCouplingCartesianAMRMeshGen::getNumberOfCellsRecursiveWithoutOverlap() const
254 {
255   int ret(_mesh->getNumberOfCells());
256   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
257     {
258       ret-=(*it)->getNumberOfOverlapedCellsForFather();
259       ret+=(*it)->getNumberOfCellsRecursiveWithoutOverlap();
260     }
261   return ret;
262 }
263
264 const MEDCouplingCartesianAMRMeshGen *MEDCouplingCartesianAMRMeshGen::getFather() const
265 {
266   return _father;
267 }
268
269 const MEDCouplingCartesianAMRMeshGen *MEDCouplingCartesianAMRMeshGen::getGodFather() const
270 {
271   if(_father==0)
272     return this;
273   else
274     return _father->getGodFather();
275 }
276
277 /*!
278  * This method returns the level of \a this. 0 for god father. -1 for children of god father ...
279  */
280 int MEDCouplingCartesianAMRMeshGen::getAbsoluteLevel() const
281 {
282   if(_father==0)
283     return 0;
284   else
285     return _father->getAbsoluteLevel()-1;
286 }
287
288 /*!
289  * This method returns grids relative to god father to specified level \a absoluteLev.
290  *
291  * \return std::vector<MEDCouplingCartesianAMRPatchGen *> - objects in vector are to be managed (decrRef) by the caller.
292  */
293 std::vector<MEDCouplingCartesianAMRPatchGen *> MEDCouplingCartesianAMRMeshGen::retrieveGridsAt(int absoluteLev) const
294 {
295   if(absoluteLev<0)
296     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::retrieveGridsAt : absolute level must be >=0 !");
297   if(_father)
298     return getGodFather()->retrieveGridsAt(absoluteLev);
299   //
300   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatchGen> > rets;
301   retrieveGridsAtInternal(absoluteLev,rets);
302   std::vector< MEDCouplingCartesianAMRPatchGen * > ret(rets.size());
303   for(std::size_t i=0;i<rets.size();i++)
304     {
305       ret[i]=rets[i].retn();
306     }
307   return ret;
308 }
309
310 void MEDCouplingCartesianAMRMeshGen::detachFromFather()
311 {
312   _father=0;
313   declareAsNew();
314 }
315
316 /*!
317  * \param [in] bottomLeftTopRight a vector equal to the space dimension of \a mesh that specifies for each dimension, the included cell start of the range for the first element of the pair,
318  *                                a the end cell (\b excluded) of the range for the second element of the pair.
319  * \param [in] factors The factor of refinement per axis (different from 0).
320  */
321 void MEDCouplingCartesianAMRMeshGen::addPatch(const std::vector< std::pair<int,int> >& bottomLeftTopRight, const std::vector<int>& factors)
322 {
323   checkFactorsAndIfNotSetAssign(factors);
324   MEDCouplingAutoRefCountObjectPtr<MEDCouplingIMesh> mesh(static_cast<MEDCouplingIMesh *>(_mesh->buildStructuredSubPart(bottomLeftTopRight)));
325   mesh->refineWithFactor(factors);
326   MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRMeshSub> zeMesh(new MEDCouplingCartesianAMRMeshSub(this,mesh));
327   MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> elt(new MEDCouplingCartesianAMRPatch(zeMesh,bottomLeftTopRight));
328   _patches.push_back(elt);
329   declareAsNew();
330 }
331
332 /// @cond INTERNAL
333
334 class InternalPatch : public RefCountObjectOnly
335 {
336 public:
337   InternalPatch():_nb_of_true(0) { }
338   int getDimension() const { return (int)_part.size(); }
339   double getEfficiency() const { return (double)_nb_of_true/(double)_crit.size(); }
340   int getNumberOfCells() const { return (int)_crit.size(); }
341   void setNumberOfTrue(int nboft) { _nb_of_true=nboft; }
342   std::vector<bool>& getCriterion() { return _crit; }
343   const std::vector<bool>& getConstCriterion() const { return _crit; }
344   void setPart(const std::vector< std::pair<int,int> >& part) { _part=part; }
345   std::vector< std::pair<int,int> >& getPart() { return _part; }
346   const std::vector< std::pair<int,int> >& getConstPart() const { return _part; }
347   bool presenceOfTrue() const { return _nb_of_true>0; }
348   std::vector<int> computeCGS() const { return MEDCouplingStructuredMesh::GetDimensionsFromCompactFrmt(_part); }
349   std::vector< std::vector<int> > computeSignature() const { return MEDCouplingStructuredMesh::ComputeSignaturePerAxisOf(computeCGS(),getConstCriterion()); }
350   double getEfficiencyPerAxis(int axisId) const { return (double)_nb_of_true/((double)(_part[axisId].second-_part[axisId].first)); }
351   void zipToFitOnCriterion();
352   void updateNumberOfTrue() const;
353   MEDCouplingAutoRefCountObjectPtr<InternalPatch> extractPart(const std::vector< std::pair<int,int> >&partInGlobal) const;
354   MEDCouplingAutoRefCountObjectPtr<InternalPatch> deepCpy() const;
355 protected:
356   ~InternalPatch() { }
357 private:
358   mutable int _nb_of_true;
359   std::vector<bool> _crit;
360   //! _part is global
361   std::vector< std::pair<int,int> > _part;
362 };
363
364 void InternalPatch::zipToFitOnCriterion()
365 {
366   std::vector<int> cgs(computeCGS());
367   std::vector<bool> newCrit;
368   std::vector< std::pair<int,int> > newPart,newPart2;
369   int newNbOfTrue(MEDCouplingStructuredMesh::FindMinimalPartOf(cgs,_crit,newCrit,newPart));
370   MEDCouplingStructuredMesh::ChangeReferenceToGlobalOfCompactFrmt(_part,newPart,newPart2);
371   if(newNbOfTrue!=_nb_of_true)
372     throw INTERP_KERNEL::Exception("InternalPatch::zipToFitOnCrit : internal error !");
373   _crit=newCrit; _part=newPart2;
374 }
375
376 void InternalPatch::updateNumberOfTrue() const
377 {
378   _nb_of_true=(int)std::count(_crit.begin(),_crit.end(),true);
379 }
380
381 MEDCouplingAutoRefCountObjectPtr<InternalPatch> InternalPatch::extractPart(const std::vector< std::pair<int,int> >&partInGlobal) const
382 {
383   MEDCouplingAutoRefCountObjectPtr<InternalPatch> ret(new InternalPatch);
384   std::vector<int> cgs(computeCGS());
385   std::vector< std::pair<int,int> > newPart;
386   MEDCouplingStructuredMesh::ChangeReferenceFromGlobalOfCompactFrmt(_part,partInGlobal,newPart);
387   MEDCouplingStructuredMesh::ExtractFieldOfBoolFrom(cgs,_crit,newPart,ret->getCriterion());
388   ret->setPart(partInGlobal);
389   ret->updateNumberOfTrue();
390   return ret;
391 }
392
393 MEDCouplingAutoRefCountObjectPtr<InternalPatch> InternalPatch::deepCpy() const
394 {
395   MEDCouplingAutoRefCountObjectPtr<InternalPatch> ret(new InternalPatch);
396   (*ret)=*this;
397   return ret;
398 }
399
400 void DissectBigPatch(const INTERP_KERNEL::BoxSplittingOptions& bso, const InternalPatch *patchToBeSplit, int axisId, int rangeOfAxisId, bool& cutFound, int& cutPlace)
401 {
402   cutFound=false; cutPlace=-1;
403   std::vector<double> ratio(rangeOfAxisId-1);
404   for(int id=0;id<rangeOfAxisId-1;id++)
405     {
406       double efficiency[2];
407       for(int h=0;h<2;h++)
408         {
409           std::vector< std::pair<int,int> > rectH(patchToBeSplit->getConstPart());
410           if(h==0)
411             rectH[axisId].second=patchToBeSplit->getConstPart()[axisId].first+id;
412           else
413             rectH[axisId].first=patchToBeSplit->getConstPart()[axisId].first+id;
414           MEDCouplingAutoRefCountObjectPtr<InternalPatch> p(patchToBeSplit->deepCpy());
415           p->zipToFitOnCriterion();
416           //anouar rectH ?
417           efficiency[h]=p->getEfficiencyPerAxis(axisId);
418         }
419       ratio[id]=std::max(efficiency[0],efficiency[1])/std::min(efficiency[0],efficiency[1]);
420     }
421   int minCellDirection(bso.getMinCellDirection()),indexMin(-1);
422   int dimRatioInner(rangeOfAxisId-1-2*(minCellDirection-1));
423   std::vector<double> ratio_inner(dimRatioInner);
424   double minRatio(1.e10);
425   for(int i=0; i<dimRatioInner; i++)
426     {
427       if(ratio[minCellDirection-1+i]<minRatio)
428         {
429           minRatio=ratio[minCellDirection-1+i];
430           indexMin=i+minCellDirection;
431         }
432     }
433   cutFound=true; cutPlace=indexMin+patchToBeSplit->getConstPart()[axisId].first-1;
434 }
435
436 void FindHole(const INTERP_KERNEL::BoxSplittingOptions& bso, const InternalPatch *patchToBeSplit, int& axisId, bool& cutFound, int& cutPlace)
437 {
438   cutPlace=-1; cutFound=false;
439   int minCellDirection(bso.getMinCellDirection());
440   const int dim(patchToBeSplit->getDimension());
441   std::vector< std::vector<int> > signatures(patchToBeSplit->computeSignature());
442   for(int id=0;id<dim;id++)
443     {
444       const std::vector<int>& signature(signatures[id]);
445       std::vector<int> hole;
446       std::vector<double> distance;
447       int len((int)signature.size());
448       for(int i=0;i<len;i++)
449         if(signature[i]==0)
450           if(len>= 2*minCellDirection && i >= minCellDirection-1 && i <= len-minCellDirection-1)
451             hole.push_back(i);
452       if(!hole.empty())
453         {
454           double center(((double)len/2.));
455           for(std::size_t i=0;i<hole.size();i++)
456             distance.push_back(fabs(hole[i]+1.-center));
457
458           std::size_t posDistanceMin(std::distance(distance.begin(),std::min_element(distance.begin(),distance.end())));
459           cutFound=true;
460           axisId=id;
461           cutPlace=hole[posDistanceMin]+patchToBeSplit->getConstPart()[axisId].first+1;
462           return ;
463         }
464     }
465 }
466
467 void FindInflection(const INTERP_KERNEL::BoxSplittingOptions& bso, const InternalPatch *patchToBeSplit, bool& cutFound, int& cutPlace, int& axisId)
468 {
469   cutFound=false; cutPlace=-1;// do not set axisId before to be sure that cutFound was set to true
470
471   const std::vector< std::pair<int,int> >& part(patchToBeSplit->getConstPart());
472   int sign,minCellDirection(bso.getMinCellDirection());
473   const int dim(patchToBeSplit->getDimension());
474
475   std::vector<int> zeroCrossDims(dim,-1);
476   std::vector<int> zeroCrossVals(dim,-1);
477   std::vector< std::vector<int> > signatures(patchToBeSplit->computeSignature());
478   for (int id=0;id<dim;id++)
479     {
480       const std::vector<int>& signature(signatures[id]);
481
482       std::vector<int> derivate_second_order,gradient_absolute,signe_change,zero_cross,edge,max_cross_list ;
483       std::vector<double> distance ;
484
485       for (unsigned int i=1;i<signature.size()-1;i++)
486         derivate_second_order.push_back(signature[i-1]-2*signature[i]+signature[i+1]) ;
487
488       // Gradient absolute value
489       for ( unsigned int i=1;i<derivate_second_order.size();i++)
490         gradient_absolute.push_back(fabs(derivate_second_order[i]-derivate_second_order[i-1])) ;
491       if(derivate_second_order.empty())
492         continue;
493       for (unsigned int i=0;i<derivate_second_order.size()-1;i++)
494         {
495           if (derivate_second_order[i]*derivate_second_order[i+1] < 0 )
496             sign = -1 ;
497           if (derivate_second_order[i]*derivate_second_order[i+1] > 0 )
498             sign = 1 ;
499           if (derivate_second_order[i]*derivate_second_order[i+1] == 0 )
500             sign = 0 ;
501           if ( sign==0 || sign==-1 )
502             if ( i >= (unsigned int)minCellDirection-2 && i <= signature.size()-minCellDirection-2 )
503               {
504                 zero_cross.push_back(i) ;
505                 edge.push_back(gradient_absolute[i]) ;
506               }
507           signe_change.push_back(sign) ;
508         }
509       if ( zero_cross.size() > 0 )
510         {
511           int max_cross=*max_element(edge.begin(),edge.end()) ;
512           for (unsigned int i=0;i<edge.size();i++)
513             if (edge[i]==max_cross)
514               max_cross_list.push_back(zero_cross[i]+1) ;
515
516           double center((signature.size()/2.0));
517           for (unsigned int i=0;i<max_cross_list.size();i++)
518             distance.push_back(fabs(max_cross_list[i]+1-center));
519
520           float distance_min=*min_element(distance.begin(),distance.end()) ;
521           int pos_distance_min=find(distance.begin(),distance.end(),distance_min)-distance.begin();
522           int best_place = max_cross_list[pos_distance_min] + part[id].first ;
523           if ( max_cross >=0 )
524             {
525               zeroCrossDims[id] = best_place ;
526               zeroCrossVals[id] = max_cross ;
527             }
528         }
529       derivate_second_order.clear() ;
530       gradient_absolute.clear() ;
531       signe_change.clear() ;
532       zero_cross.clear() ;
533       edge.clear() ;
534       max_cross_list.clear() ;
535       distance.clear() ;
536     }
537
538   if ( zeroCrossDims[0]!=-1 || zeroCrossDims[1]!=-1  )
539     {
540       int max_cross_dims = *max_element(zeroCrossVals.begin(),zeroCrossVals.end()) ;
541
542       if (zeroCrossVals[0]==max_cross_dims &&  zeroCrossVals[1]==max_cross_dims )
543         {
544           int nl_left(part[0].second-part[0].first);
545           int nc_left(part[1].second-part[1].first);
546           if ( nl_left >=  nc_left )
547             max_cross_dims = 0 ;
548           else
549             max_cross_dims = 1 ;
550         }
551       else
552         max_cross_dims=std::find(zeroCrossVals.begin(),zeroCrossVals.end(),max_cross_dims)-zeroCrossVals.begin();
553       cutFound=true;
554       cutPlace=zeroCrossDims[max_cross_dims];
555       axisId=max_cross_dims ;
556     }
557 }
558
559 void TryAction4(const INTERP_KERNEL::BoxSplittingOptions& bso, const InternalPatch *patchToBeSplit, int axisId, int rangeOfAxisId, bool& cutFound, int& cutPlace)
560 {
561   cutFound=false;
562   if(patchToBeSplit->getEfficiency()<=bso.getEffeciencySnd())
563     {
564       if(rangeOfAxisId>=2*bso.getMinCellDirection())
565         {
566           cutFound=true;
567           cutPlace=rangeOfAxisId/2+patchToBeSplit->getConstPart()[axisId].first-1;
568         }
569     }
570   else
571     {
572       if(patchToBeSplit->getNumberOfCells()>bso.getMaxCells())
573         {
574           DissectBigPatch(bso,patchToBeSplit,axisId,rangeOfAxisId,cutFound,cutPlace);
575         }
576     }
577 }
578
579 MEDCouplingAutoRefCountObjectPtr<InternalPatch> DealWithNoCut(const InternalPatch *patch)
580 {
581   MEDCouplingAutoRefCountObjectPtr<InternalPatch> ret(const_cast<InternalPatch *>(patch));
582   ret->incrRef();
583   return ret;
584 }
585
586 void DealWithCut(const InternalPatch *patchToBeSplit, int axisId, int cutPlace, std::vector<MEDCouplingAutoRefCountObjectPtr<InternalPatch> >& listOfPatches)
587 {
588   MEDCouplingAutoRefCountObjectPtr<InternalPatch> leftPart,rightPart;
589   std::vector< std::pair<int,int> > rect(patchToBeSplit->getConstPart());
590   std::vector< std::pair<int,int> > leftRect(rect),rightRect(rect);
591   leftRect[axisId].second=cutPlace+1;
592   rightRect[axisId].first=cutPlace+1;
593   leftPart=patchToBeSplit->extractPart(leftRect);
594   rightPart=patchToBeSplit->extractPart(rightRect);
595   leftPart->zipToFitOnCriterion(); rightPart->zipToFitOnCriterion();
596   listOfPatches.push_back(leftPart);
597   listOfPatches.push_back(rightPart);
598 }
599
600 /// @endcond
601
602 /*!
603  * This method creates patches in \a this (by destroying the patches if any). This method uses \a criterion array as a field on cells on this level.
604  */
605 void MEDCouplingCartesianAMRMeshGen::createPatchesFromCriterion(const INTERP_KERNEL::BoxSplittingOptions& bso, const std::vector<bool>& criterion, const std::vector<int>& factors)
606 {
607   int nbCells(getNumberOfCellsAtCurrentLevel());
608   if(nbCells!=(int)criterion.size())
609     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::createPatchesFromCriterion : the number of tuples of criterion array must be equal to the number of cells at the current level !");
610   _patches.clear();
611   std::vector<int> cgs(_mesh->getCellGridStructure());
612   std::vector< MEDCouplingAutoRefCountObjectPtr<InternalPatch> > listOfPatches,listOfPatchesOK;
613   //
614   MEDCouplingAutoRefCountObjectPtr<InternalPatch> p(new InternalPatch);
615   p->setNumberOfTrue(MEDCouplingStructuredMesh::FindMinimalPartOf(cgs,criterion,p->getCriterion(),p->getPart()));
616   if(p->presenceOfTrue())
617     listOfPatches.push_back(p);
618   while(!listOfPatches.empty())
619     {
620       std::vector< MEDCouplingAutoRefCountObjectPtr<InternalPatch> > listOfPatchesTmp;
621       for(std::vector< MEDCouplingAutoRefCountObjectPtr<InternalPatch> >::iterator it=listOfPatches.begin();it!=listOfPatches.end();it++)
622         {
623           //
624           int axisId,rangeOfAxisId,cutPlace;
625           bool cutFound;
626           MEDCouplingStructuredMesh::FindTheWidestAxisOfGivenRangeInCompactFrmt((*it)->getConstPart(),axisId,rangeOfAxisId);
627           if((*it)->getEfficiency()>=bso.getEffeciency() && (*it)->getNumberOfCells()<bso.getMaxCells())
628             { listOfPatchesOK.push_back(DealWithNoCut(*it)); continue; }//action 1
629           FindHole(bso,*it,axisId,cutFound,cutPlace);//axisId overwritten here if FindHole equal to true !
630           if(cutFound)
631             { DealWithCut(*it,axisId,cutPlace,listOfPatchesTmp); continue; }//action 2
632           FindInflection(bso,*it,cutFound,cutPlace,axisId);//axisId overwritten here if cutFound equal to true !
633           if(cutFound)
634             { DealWithCut(*it,axisId,cutPlace,listOfPatchesTmp); continue; }//action 3
635           TryAction4(bso,*it,axisId,rangeOfAxisId,cutFound,cutPlace);
636           if(cutFound)
637             { DealWithCut(*it,axisId,cutPlace,listOfPatchesTmp); continue; }//action 4
638           listOfPatchesOK.push_back(DealWithNoCut(*it));
639         }
640       listOfPatches=listOfPatchesTmp;
641     }
642   for(std::vector< MEDCouplingAutoRefCountObjectPtr<InternalPatch> >::const_iterator it=listOfPatchesOK.begin();it!=listOfPatchesOK.end();it++)
643     addPatch((*it)->getConstPart(),factors);
644   declareAsNew();
645 }
646
647 /*!
648  * This method creates patches in \a this (by destroying the patches if any). This method uses \a criterion array as a field on cells on this level.
649  */
650 void MEDCouplingCartesianAMRMeshGen::createPatchesFromCriterion(const INTERP_KERNEL::BoxSplittingOptions& bso, const DataArrayByte *criterion, const std::vector<int>& factors)
651 {
652   if(!criterion || !criterion->isAllocated())
653     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::createPatchesFromCriterion : the criterion DataArrayByte instance must be allocated and not NULL !");
654   std::vector<bool> crit(criterion->toVectorOfBool());//check that criterion has one component.
655   createPatchesFromCriterion(bso,crit,factors);
656   declareAsNew();
657 }
658
659 void MEDCouplingCartesianAMRMeshGen::removeAllPatches()
660 {
661   _patches.clear();
662   declareAsNew();
663 }
664
665 void MEDCouplingCartesianAMRMeshGen::removePatch(int patchId)
666 {
667   checkPatchId(patchId);
668   int sz((int)_patches.size()),j(0);
669   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> > patches(sz-1);
670   for(int i=0;i<sz;i++)
671     if(i!=patchId)
672       patches[j++]=_patches[i];
673   (const_cast<MEDCouplingCartesianAMRMeshGen *>(_patches[patchId]->getMesh()))->detachFromFather();
674   _patches=patches;
675   declareAsNew();
676 }
677
678 int MEDCouplingCartesianAMRMeshGen::getNumberOfPatches() const
679 {
680   return (int)_patches.size();
681 }
682
683 const MEDCouplingCartesianAMRPatch *MEDCouplingCartesianAMRMeshGen::getPatch(int patchId) const
684 {
685   checkPatchId(patchId);
686   return _patches[patchId];
687 }
688
689 /*!
690  * This method states if patch2 (with id \a patchId2) is in the neighborhood of patch1 (with id \a patchId1).
691  * The neighborhood size is defined by \a ghostLev in the reference of \a this ( \b not in the reference of patches !).
692  */
693 bool MEDCouplingCartesianAMRMeshGen::isPatchInNeighborhoodOf(int patchId1, int patchId2, int ghostLev) const
694 {
695   if(ghostLev<0)
696     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::isPatchInNeighborhoodOf : the ghost size must be >=0 !");
697   const MEDCouplingCartesianAMRPatch *p1(getPatch(patchId1)),*p2(getPatch(patchId2));
698   if(_factors.empty())
699     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::isPatchInNeighborhoodOf : no factors defined !");
700   int ghostLevInPatchRef;
701   if(ghostLev==0)
702     ghostLevInPatchRef=0;
703   else
704     {
705       ghostLevInPatchRef=(ghostLev-1)/_factors[0]+1;
706       for(std::size_t i=0;i<_factors.size();i++)
707         ghostLevInPatchRef=std::max(ghostLevInPatchRef,(ghostLev-1)/_factors[i]+1);
708     }
709   return p1->isInMyNeighborhood(p2,ghostLevInPatchRef);
710 }
711
712 /*!
713  * This method creates a new cell field array on given \a patchId patch in \a this starting from a coarse cell field on \a this \a cellFieldOnThis.
714  * This method can be seen as a fast projection from the cell field \a cellFieldOnThis on \c this->getImageMesh() to a refined part of \a this
715  * defined by the patch with id \a patchId.
716  *
717  * \param [in] patchId - The id of the patch \a cellFieldOnThis has to be put on.
718  * \param [in] cellFieldOnThis - The array of the cell field on \c this->getImageMesh() to be projected to patch having id \a patchId.
719  * \return DataArrayDouble * - The array of the cell field on the requested patch
720  *
721  * \throw if \a patchId is not in [ 0 , \c this->getNumberOfPatches() )
722  * \throw if \a cellFieldOnThis is NULL or not allocated
723  * \sa fillCellFieldOnPatch, MEDCouplingIMesh::SpreadCoarseToFine
724  */
725 DataArrayDouble *MEDCouplingCartesianAMRMeshGen::createCellFieldOnPatch(int patchId, const DataArrayDouble *cellFieldOnThis) const
726 {
727   if(!cellFieldOnThis || !cellFieldOnThis->isAllocated())
728     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::createCellFieldOnPatch : the input cell field array is NULL or not allocated !");
729   const MEDCouplingCartesianAMRPatch *patch(getPatch(patchId));
730   const MEDCouplingIMesh *fine(patch->getMesh()->getImageMesh());
731   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ret(DataArrayDouble::New()); ret->alloc(fine->getNumberOfCells(),cellFieldOnThis->getNumberOfComponents());
732   ret->copyStringInfoFrom(*cellFieldOnThis);
733   MEDCouplingIMesh::SpreadCoarseToFine(cellFieldOnThis,_mesh->getCellGridStructure(),ret,patch->getBLTRRange(),getFactors());
734   return ret.retn();
735 }
736
737 /*!
738  * This method is equivalent to MEDCouplingCartesianAMRMesh::createCellFieldOnPatch except that here instead of creating a new instance
739  * it fills the value into the \a cellFieldOnPatch data.
740  *
741  * \param [in] patchId - The id of the patch \a cellFieldOnThis has to be put on.
742  * \param [in] cellFieldOnThis - The array of the cell field on \c this->getImageMesh() to be projected to patch having id \a patchId.
743  * \param [in,out] cellFieldOnPatch - The array of the cell field on the requested patch to be filled.
744  *
745  * \sa createCellFieldOnPatch, fillCellFieldComingFromPatch
746  */
747 void MEDCouplingCartesianAMRMeshGen::fillCellFieldOnPatch(int patchId, const DataArrayDouble *cellFieldOnThis, DataArrayDouble *cellFieldOnPatch) const
748 {
749   if(!cellFieldOnThis || !cellFieldOnThis->isAllocated())
750     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::createCellFieldOnPatch : the input cell field array is NULL or not allocated !");
751   const MEDCouplingCartesianAMRPatch *patch(getPatch(patchId));
752   MEDCouplingIMesh::SpreadCoarseToFine(cellFieldOnThis,_mesh->getCellGridStructure(),cellFieldOnPatch,patch->getBLTRRange(),getFactors());
753 }
754
755 /*!
756  * This method is the generalization of fillCellFieldOnPatch method. This method only projects coarse to fine without considering the
757  * potential neighbor patches covered by the ghost cells of patch with id \a patchId.
758  *
759  * \param [in] patchId - The id of the patch \a cellFieldOnThis has to be put on.
760  * \param [in] cellFieldOnThis - The array of the cell field on \c this->getImageMesh() to be projected to patch having id \a patchId.
761  * \param [in,out] cellFieldOnPatch - The array of the cell field on the requested patch to be filled.
762  * \param [in] ghostLev - The size of the ghost zone (must be >=0 !)
763  *
764  * \sa fillCellFieldOnPatch, fillCellFieldOnPatchGhostAdv
765  */
766 void MEDCouplingCartesianAMRMeshGen::fillCellFieldOnPatchGhost(int patchId, const DataArrayDouble *cellFieldOnThis, DataArrayDouble *cellFieldOnPatch, int ghostLev) const
767 {
768   if(!cellFieldOnThis || !cellFieldOnThis->isAllocated())
769     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::createCellFieldOnPatchGhost : the input cell field array is NULL or not allocated !");
770   const MEDCouplingCartesianAMRPatch *patch(getPatch(patchId));
771   MEDCouplingIMesh::SpreadCoarseToFineGhost(cellFieldOnThis,_mesh->getCellGridStructure(),cellFieldOnPatch,patch->getBLTRRange(),getFactors(),ghostLev);
772 }
773
774 /*!
775  * This method is a refinement of fillCellFieldOnPatchGhost. fillCellFieldOnPatchGhost is first called.
776  * Then for all other patches than those pointed by \a patchId that overlap the ghost zone of the patch impact the ghost zone adequately.
777  *
778  * \param [in] patchId - The id of the patch \a cellFieldOnThis has to be put on.
779  * \param [in] cellFieldOnThis - The array of the cell field on \c this->getImageMesh() to be projected to patch having id \a patchId.
780  * \param [in,out] cellFieldOnPatch - The array of the cell field on the requested patch to be filled.
781  * \param [in] ghostLev - The size of the ghost zone (must be >=0 !)
782  * \param [in] arrsOnPatches - \b WARNING arrsOnPatches[patchId] is \b NOT \b const. All others are const.
783  *
784  * \sa fillCellFieldOnPatchOnlyGhostAdv
785  */
786 void MEDCouplingCartesianAMRMeshGen::fillCellFieldOnPatchGhostAdv(int patchId, const DataArrayDouble *cellFieldOnThis, int ghostLev, const std::vector<const DataArrayDouble *>& arrsOnPatches) const
787 {
788   int nbp(getNumberOfPatches());
789   if(nbp!=(int)arrsOnPatches.size())
790     {
791       std::ostringstream oss; oss << "MEDCouplingCartesianAMRMesh::fillCellFieldOnPatchGhostAdv : there are " << nbp << " patches in this and " << arrsOnPatches.size() << " arrays in the last parameter !";
792       throw INTERP_KERNEL::Exception(oss.str().c_str());
793     }
794   DataArrayDouble *theFieldToFill(const_cast<DataArrayDouble *>(arrsOnPatches[patchId]));
795   // first, do as usual
796   fillCellFieldOnPatchGhost(patchId,cellFieldOnThis,theFieldToFill,ghostLev);
797   fillCellFieldOnPatchOnlyGhostAdv(patchId,ghostLev,arrsOnPatches);
798 }
799
800 void MEDCouplingCartesianAMRMeshGen::fillCellFieldOnPatchOnlyGhostAdv(int patchId, int ghostLev, const std::vector<const DataArrayDouble *>& arrsOnPatches) const
801 {
802   int nbp(getNumberOfPatches()),dim(getSpaceDimension());
803   if(nbp!=(int)arrsOnPatches.size())
804     {
805       std::ostringstream oss; oss << "MEDCouplingCartesianAMRMesh::fillCellFieldOnPatchOnlyGhostAdv : there are " << nbp << " patches in this and " << arrsOnPatches.size() << " arrays in the last parameter !";
806       throw INTERP_KERNEL::Exception(oss.str().c_str());
807     }
808   DataArrayDouble *theFieldToFill(const_cast<DataArrayDouble *>(arrsOnPatches[patchId]));
809   const MEDCouplingCartesianAMRPatch *refP(getPatch(patchId));
810   const std::vector< std::pair<int,int> >& refBLTR(refP->getBLTRRange());//[(1,4),(2,4)]
811   std::vector<int> dimsCoarse(MEDCouplingStructuredMesh::GetDimensionsFromCompactFrmt(refBLTR));//[3,2]
812   std::transform(dimsCoarse.begin(),dimsCoarse.end(),_factors.begin(),dimsCoarse.begin(),std::multiplies<int>());//[12,8]
813   std::transform(dimsCoarse.begin(),dimsCoarse.end(),dimsCoarse.begin(),std::bind2nd(std::plus<int>(),2*ghostLev));//[14,10]
814   std::vector< std::pair<int,int> > rangeCoarse(MEDCouplingStructuredMesh::GetCompactFrmtFromDimensions(dimsCoarse));//[(0,14),(0,10)]
815   std::vector<int> fakeFactors(dim,1);
816   //
817   for(int i=0;i<nbp;i++)
818     {
819       if(i!=patchId)
820         if(isPatchInNeighborhoodOf(i,patchId,ghostLev))
821           {
822             const MEDCouplingCartesianAMRPatch *otherP(getPatch(i));
823             const std::vector< std::pair<int,int> >& otherBLTR(otherP->getBLTRRange());//[(4,5),(3,4)]
824             std::vector< std::pair<int,int> > tmp0,tmp1,tmp2;
825             MEDCouplingStructuredMesh::ChangeReferenceFromGlobalOfCompactFrmt(refBLTR,otherBLTR,tmp0,false);//tmp0=[(3,4),(1,2)]
826             ApplyFactorsOnCompactFrmt(tmp0,_factors);//tmp0=[(12,16),(4,8)]
827             ApplyGhostOnCompactFrmt(tmp0,ghostLev);//tmp0=[(13,17),(5,9)]
828             std::vector< std::pair<int,int> > interstRange(MEDCouplingStructuredMesh::IntersectRanges(tmp0,rangeCoarse));//interstRange=[(13,14),(5,9)]
829             MEDCouplingStructuredMesh::ChangeReferenceFromGlobalOfCompactFrmt(otherBLTR,refBLTR,tmp1,false);//tmp1=[(-3,0),(-1,1)]
830             ApplyFactorsOnCompactFrmt(tmp1,_factors);//tmp1=[(-12,-4),(-4,0)]
831             MEDCouplingStructuredMesh::ChangeReferenceToGlobalOfCompactFrmt(tmp1,interstRange,tmp2,false);//tmp2=[(1,2),(1,5)]
832             //
833             std::vector< std::pair<int,int> > dimsFine(otherBLTR);
834             ApplyFactorsOnCompactFrmt(dimsFine,_factors);
835             ApplyAllGhostOnCompactFrmt(dimsFine,ghostLev);
836             //
837             MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> ghostVals(MEDCouplingStructuredMesh::ExtractFieldOfDoubleFrom(MEDCouplingStructuredMesh::GetDimensionsFromCompactFrmt(dimsFine),arrsOnPatches[i],tmp2));
838             MEDCouplingIMesh::CondenseFineToCoarse(dimsCoarse,ghostVals,interstRange,fakeFactors,theFieldToFill);
839           }
840     }
841 }
842
843 /*!
844  * This method updates \a cellFieldOnThis part of values coming from the cell field \a cellFieldOnPatch lying on patch having id \a patchId.
845  *
846  * \param [in] patchId - The id of the patch \a cellFieldOnThis has to be put on.
847  * \param [in] cellFieldOnPatch - The array of the cell field on patch with id \a patchId.
848  * \param [in,out] cellFieldOnThis The array of the cell field on \a this to be updated only on the part concerning the patch with id \a patchId.
849  *
850  * \throw if \a patchId is not in [ 0 , \c this->getNumberOfPatches() )
851  * \throw if \a cellFieldOnPatch is NULL or not allocated
852  * \sa createCellFieldOnPatch, MEDCouplingIMesh::CondenseFineToCoarse,fillCellFieldComingFromPatchGhost
853  */
854 void MEDCouplingCartesianAMRMeshGen::fillCellFieldComingFromPatch(int patchId, const DataArrayDouble *cellFieldOnPatch, DataArrayDouble *cellFieldOnThis) const
855 {
856   if(!cellFieldOnPatch || !cellFieldOnPatch->isAllocated())
857       throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::fillCellFieldComingFromPatch : the input cell field array is NULL or not allocated !");
858   const MEDCouplingCartesianAMRPatch *patch(getPatch(patchId));
859   MEDCouplingIMesh::CondenseFineToCoarse(_mesh->getCellGridStructure(),cellFieldOnPatch,patch->getBLTRRange(),getFactors(),cellFieldOnThis);
860 }
861
862 /*!
863  * This method is the extension of MEDCouplingCartesianAMRMesh::fillCellFieldComingFromPatch managing the ghost cells. If this
864  * method is called with \a ghostLev equal to 0 it behaves exactly as MEDCouplingCartesianAMRMesh::fillCellFieldComingFromPatch.
865  *
866  * \param [in] patchId - The id of the patch \a cellFieldOnThis has to be put on.
867  * \param [in] cellFieldOnPatch - The array of the cell field on patch with id \a patchId.
868  * \param [in,out] cellFieldOnThis The array of the cell field on \a this to be updated only on the part concerning the patch with id \a patchId.
869  * \param [in] ghostLev The size of ghost zone (must be >= 0 !)
870  *
871  * \throw if \a patchId is not in [ 0 , \c this->getNumberOfPatches() )
872  * \throw if \a cellFieldOnPatch is NULL or not allocated
873  * \sa fillCellFieldComingFromPatch
874  */
875 void MEDCouplingCartesianAMRMeshGen::fillCellFieldComingFromPatchGhost(int patchId, const DataArrayDouble *cellFieldOnPatch, DataArrayDouble *cellFieldOnThis, int ghostLev) const
876 {
877   if(!cellFieldOnPatch || !cellFieldOnPatch->isAllocated())
878     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::fillCellFieldComingFromPatchGhost : the input cell field array is NULL or not allocated !");
879   const MEDCouplingCartesianAMRPatch *patch(getPatch(patchId));
880   MEDCouplingIMesh::CondenseFineToCoarseGhost(_mesh->getCellGridStructure(),cellFieldOnPatch,patch->getBLTRRange(),getFactors(),cellFieldOnThis,ghostLev);
881 }
882
883 /*!
884  * This method finds all patches (located by their ids) that are in the neighborhood of patch with id \a patchId. The neighborhood size is
885  * defined by ghostLev.
886  *
887  * \param [in] patchId - the id of the considered patch.
888  * \param [in] ghostLev - the size of the neighborhood.
889  * \return DataArrayInt * - the newly allocated array containing the list of patches in the neighborhood of the considered patch. This array is to be deallocated by the caller.
890  */
891 DataArrayInt *MEDCouplingCartesianAMRMeshGen::findPatchesInTheNeighborhoodOf(int patchId, int ghostLev) const
892 {
893   int nbp(getNumberOfPatches());
894   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New()); ret->alloc(0,1);
895   for(int i=0;i<nbp;i++)
896     {
897       if(i!=patchId)
898         if(isPatchInNeighborhoodOf(i,patchId,ghostLev))
899           ret->pushBackSilent(i);
900     }
901   return ret.retn();
902 }
903
904 MEDCouplingUMesh *MEDCouplingCartesianAMRMeshGen::buildUnstructured() const
905 {
906   MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> part(_mesh->buildUnstructured());
907   std::vector<bool> bs(_mesh->getNumberOfCells(),false);
908   std::vector<int> cgs(_mesh->getCellGridStructure());
909   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingUMesh> > msSafe(_patches.size()+1);
910   std::size_t ii(0);
911   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++,ii++)
912     {
913       MEDCouplingStructuredMesh::SwitchOnIdsFrom(cgs,(*it)->getBLTRRange(),bs);
914       msSafe[ii+1]=(*it)->getMesh()->buildUnstructured();
915     }
916   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> eltsOff(DataArrayInt::BuildListOfSwitchedOff(bs));
917   msSafe[0]=static_cast<MEDCouplingUMesh *>(part->buildPartOfMySelf(eltsOff->begin(),eltsOff->end(),false));
918   std::vector< const MEDCouplingUMesh * > ms(msSafe.size());
919   for(std::size_t i=0;i<msSafe.size();i++)
920     ms[i]=msSafe[i];
921   return MEDCouplingUMesh::MergeUMeshes(ms);
922 }
923
924 /*!
925  * This method returns a mesh containing as cells that there is patches at the current level.
926  * The patches are seen like 'boxes' that is too say the refinement will not appear here.
927  *
928  * \return MEDCoupling1SGTUMesh * - A new object to be managed by the caller containing as cells as there are patches in \a this.
929  */
930 MEDCoupling1SGTUMesh *MEDCouplingCartesianAMRMeshGen::buildMeshFromPatchEnvelop() const
931 {
932   std::vector<const MEDCoupling1SGTUMesh *> cells;
933   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> > cellsSafe;
934   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
935     {
936       const MEDCouplingCartesianAMRPatch *patch(*it);
937       if(patch)
938         {
939           MEDCouplingAutoRefCountObjectPtr<MEDCouplingIMesh> cell(patch->getMesh()->getImageMesh()->asSingleCell());
940           MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> cell1SGT(cell->build1SGTUnstructured());
941           cellsSafe.push_back(cell1SGT); cells.push_back(cell1SGT);
942         }
943     }
944   return MEDCoupling1SGTUMesh::Merge1SGTUMeshes(cells);
945 }
946
947 MEDCoupling1SGTUMesh *MEDCouplingCartesianAMRMeshGen::buildMeshOfDirectChildrenOnly() const
948 {
949   std::vector<const MEDCoupling1SGTUMesh *> patches;
950   std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> > patchesSafe;
951   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
952       {
953         const MEDCouplingCartesianAMRPatch *patch(*it);
954         if(patch)
955           {
956             MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> patchMesh(patch->getMesh()->getImageMesh()->build1SGTUnstructured());
957             patchesSafe.push_back(patchMesh); patches.push_back(patchMesh);
958           }
959       }
960     return MEDCoupling1SGTUMesh::Merge1SGTUMeshes(patches);
961 }
962
963 MEDCouplingCartesianAMRMeshGen::MEDCouplingCartesianAMRMeshGen(const std::string& meshName, int spaceDim, const int *nodeStrctStart, const int *nodeStrctStop,
964                                                                const double *originStart, const double *originStop, const double *dxyzStart, const double *dxyzStop):_father(0)
965 {
966   _mesh=MEDCouplingIMesh::New(meshName,spaceDim,nodeStrctStart,nodeStrctStop,originStart,originStop,dxyzStart,dxyzStop);
967 }
968
969 MEDCouplingCartesianAMRMeshGen::MEDCouplingCartesianAMRMeshGen(MEDCouplingCartesianAMRMeshGen *father, MEDCouplingIMesh *mesh):_father(father)
970 {
971   if(!_father)
972     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen(MEDCouplingIMesh *mesh) constructor : empty father !");
973   if(!mesh)
974     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen(MEDCouplingIMesh *mesh) constructor : The input mesh is null !");
975   mesh->checkCoherency();
976   _mesh=mesh; _mesh->incrRef();
977 }
978
979 void MEDCouplingCartesianAMRMeshGen::checkPatchId(int patchId) const
980 {
981   int sz(getNumberOfPatches());
982   if(patchId<0 || patchId>=sz)
983     {
984       std::ostringstream oss; oss << "MEDCouplingCartesianAMRMeshGen::checkPatchId : invalid patchId (" << patchId << ") ! Must be in [0," << sz << ") !";
985       throw INTERP_KERNEL::Exception(oss.str().c_str());
986     }
987 }
988
989 void MEDCouplingCartesianAMRMeshGen::checkFactorsAndIfNotSetAssign(const std::vector<int>& factors)
990 {
991   if(getSpaceDimension()!=(int)factors.size())
992     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen::checkFactorsAndIfNotSetAssign : invalid size of factors ! size must be equal to the spaceDimension !");
993   if(_factors.empty())
994     {
995       _factors=factors;
996     }
997   else
998     {
999       if(_factors!=factors)
1000         throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::checkFactorsAndIfNotSetAssign : the factors ");
1001     }
1002 }
1003
1004 void MEDCouplingCartesianAMRMeshGen::retrieveGridsAtInternal(int lev, std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatchGen> >& grids) const
1005 {
1006   if(lev==0)
1007     {
1008       const MEDCouplingCartesianAMRMesh *thisc(dynamic_cast<const MEDCouplingCartesianAMRMesh *>(this));//tony
1009       MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatchGF> elt(new MEDCouplingCartesianAMRPatchGF(const_cast<MEDCouplingCartesianAMRMesh *>(thisc)));
1010       grids.push_back(DynamicCastSafe<MEDCouplingCartesianAMRPatchGF,MEDCouplingCartesianAMRPatchGen>(elt));
1011     }
1012   else if(lev==1)
1013     {
1014       for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
1015         {
1016           const MEDCouplingCartesianAMRPatch *pt(*it);
1017           if(pt)
1018             {
1019               MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> tmp1(*it);
1020               grids.push_back(DynamicCastSafe<MEDCouplingCartesianAMRPatch,MEDCouplingCartesianAMRPatchGen>(tmp1));
1021             }
1022         }
1023     }
1024   else
1025     {
1026       for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
1027         {
1028           const MEDCouplingCartesianAMRPatch *pt(*it);
1029           if(pt)
1030             pt->getMesh()->retrieveGridsAtInternal(lev-1,grids);
1031         }
1032     }
1033 }
1034
1035 /*!
1036  * \param [in,out] partBeforeFact - the part of a image mesh in compact format that will be put in refined reference.
1037  * \param [in] factors - the factors per axis.
1038  */
1039 void MEDCouplingCartesianAMRMeshGen::ApplyFactorsOnCompactFrmt(std::vector< std::pair<int,int> >& partBeforeFact, const std::vector<int>& factors)
1040 {
1041   std::size_t sz(factors.size());
1042   if(sz!=partBeforeFact.size())
1043     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen::ApplyFactorsOnCompactFrmt : size of input vectors must be the same !");
1044   for(std::size_t i=0;i<sz;i++)
1045     {
1046       partBeforeFact[i].first*=factors[i];
1047       partBeforeFact[i].second*=factors[i];
1048     }
1049 }
1050
1051 /*!
1052  * \param [in,out] partBeforeFact - the part of a image mesh in compact format that will be put in ghost reference.
1053  * \param [in] ghostSize - the ghost size of zone for all axis.
1054  */
1055 void MEDCouplingCartesianAMRMeshGen::ApplyGhostOnCompactFrmt(std::vector< std::pair<int,int> >& partBeforeFact, int ghostSize)
1056 {
1057   if(ghostSize<0)
1058     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen::ApplyGhostOnCompactFrmt : ghost size must be >= 0 !");
1059   std::size_t sz(partBeforeFact.size());
1060   for(std::size_t i=0;i<sz;i++)
1061     {
1062       partBeforeFact[i].first+=ghostSize;
1063       partBeforeFact[i].second+=ghostSize;
1064     }
1065 }
1066
1067 /*!
1068  * This method is different than ApplyGhostOnCompactFrmt
1069  *
1070  * \param [in,out] partBeforeFact - the part of a image mesh in compact format that will be put in ghost reference.
1071  * \param [in] ghostSize - the ghost size of zone for all axis.
1072  */
1073 void MEDCouplingCartesianAMRMeshGen::ApplyAllGhostOnCompactFrmt(std::vector< std::pair<int,int> >& partBeforeFact, int ghostSize)
1074 {
1075   if(ghostSize<0)
1076     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMeshGen::ApplyAllGhostOnCompactFrmt : ghost size must be >= 0 !");
1077   std::size_t sz(partBeforeFact.size());
1078   for(std::size_t i=0;i<sz;i++)
1079     {
1080       partBeforeFact[i].first-=ghostSize;
1081       partBeforeFact[i].second+=ghostSize;
1082     }
1083 }
1084
1085 std::size_t MEDCouplingCartesianAMRMeshGen::getHeapMemorySizeWithoutChildren() const
1086 {
1087   return sizeof(MEDCouplingCartesianAMRMeshGen);
1088 }
1089
1090 std::vector<const BigMemoryObject *> MEDCouplingCartesianAMRMeshGen::getDirectChildren() const
1091 {
1092   std::vector<const BigMemoryObject *> ret;
1093   if((const MEDCouplingIMesh *)_mesh)
1094     ret.push_back((const MEDCouplingIMesh *)_mesh);
1095   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
1096     {
1097       if((const MEDCouplingCartesianAMRPatch*)*it)
1098         ret.push_back((const MEDCouplingCartesianAMRPatch*)*it);
1099     }
1100   return ret;
1101 }
1102
1103 void MEDCouplingCartesianAMRMeshGen::updateTime() const
1104 {
1105   if((const MEDCouplingIMesh *)_mesh)
1106     updateTimeWith(*_mesh);
1107   for(std::vector< MEDCouplingAutoRefCountObjectPtr<MEDCouplingCartesianAMRPatch> >::const_iterator it=_patches.begin();it!=_patches.end();it++)
1108     {
1109       const MEDCouplingCartesianAMRPatch *elt(*it);
1110       if(!elt)
1111         continue;
1112       const MEDCouplingCartesianAMRMeshGen *mesh(elt->getMesh());
1113       if(mesh)
1114         updateTimeWith(*mesh);
1115     }
1116 }
1117
1118 MEDCouplingCartesianAMRMeshSub::MEDCouplingCartesianAMRMeshSub(MEDCouplingCartesianAMRMeshGen *father, MEDCouplingIMesh *mesh):MEDCouplingCartesianAMRMeshGen(father,mesh)
1119 {
1120 }
1121
1122 MEDCouplingCartesianAMRMesh *MEDCouplingCartesianAMRMesh::New(const std::string& meshName, int spaceDim, const int *nodeStrctStart, const int *nodeStrctStop,
1123                                                               const double *originStart, const double *originStop, const double *dxyzStart, const double *dxyzStop)
1124 {
1125   return new MEDCouplingCartesianAMRMesh(meshName,spaceDim,nodeStrctStart,nodeStrctStop,originStart,originStop,dxyzStart,dxyzStop);
1126 }
1127
1128 void MEDCouplingCartesianAMRMesh::setData(MEDCouplingDataForGodFather *data)
1129 {
1130   MEDCouplingDataForGodFather *myData(_data);
1131   if(myData==data)
1132     return ;
1133   if(myData)
1134     myData->changeGodFather(0);
1135   _data=data;
1136   if(data)
1137     data->incrRef();
1138 }
1139
1140 void MEDCouplingCartesianAMRMesh::allocData(int ghostLev) const
1141 {
1142   checkData();
1143   _data->alloc(ghostLev);
1144 }
1145
1146 void MEDCouplingCartesianAMRMesh::deallocData() const
1147 {
1148   checkData();
1149   _data->dealloc();
1150 }
1151
1152 MEDCouplingCartesianAMRMesh::MEDCouplingCartesianAMRMesh(const std::string& meshName, int spaceDim, const int *nodeStrctStart, const int *nodeStrctStop,
1153                                                          const double *originStart, const double *originStop, const double *dxyzStart, const double *dxyzStop):MEDCouplingCartesianAMRMeshGen(meshName,spaceDim,nodeStrctStart,nodeStrctStop,originStart,originStop,dxyzStart,dxyzStop)
1154 {
1155 }
1156
1157 std::vector<const BigMemoryObject *> MEDCouplingCartesianAMRMesh::getDirectChildren() const
1158 {
1159   std::vector<const BigMemoryObject *> ret(MEDCouplingCartesianAMRMeshGen::getDirectChildren());
1160   const MEDCouplingDataForGodFather *pt(_data);
1161   if(pt)
1162     ret.push_back(pt);
1163   return ret;
1164 }
1165
1166 void MEDCouplingCartesianAMRMesh::checkData() const
1167 {
1168   const MEDCouplingDataForGodFather *data(_data);
1169   if(!data)
1170     throw INTERP_KERNEL::Exception("MEDCouplingCartesianAMRMesh::checkData : no data set !");
1171 }
1172
1173 MEDCouplingCartesianAMRMesh::~MEDCouplingCartesianAMRMesh()
1174 {
1175   MEDCouplingDataForGodFather *data(_data);
1176   if(!data)
1177     data->changeGodFather(0);
1178 }