Salome HOME
954521368c6085e75c00f3735c5f1e495f41a7f9
[tools/medcoupling.git] / src / MEDCoupling / MEDCouplingStructuredMesh.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 (CEA/DEN)
20
21 #include "MEDCouplingStructuredMesh.hxx"
22 #include "MEDCouplingFieldDouble.hxx"
23 #include "MEDCouplingMemArray.hxx"
24 #include "MEDCoupling1GTUMesh.hxx"
25 #include "MEDCouplingUMesh.hxx"
26
27 #include <numeric>
28
29 using namespace ParaMEDMEM;
30
31 MEDCouplingStructuredMesh::MEDCouplingStructuredMesh()
32 {
33 }
34
35 MEDCouplingStructuredMesh::MEDCouplingStructuredMesh(const MEDCouplingStructuredMesh& other, bool deepCopy):MEDCouplingMesh(other)
36 {
37 }
38
39 MEDCouplingStructuredMesh::~MEDCouplingStructuredMesh()
40 {
41 }
42
43 std::size_t MEDCouplingStructuredMesh::getHeapMemorySizeWithoutChildren() const
44 {
45   return MEDCouplingMesh::getHeapMemorySizeWithoutChildren();
46 }
47
48 void MEDCouplingStructuredMesh::copyTinyStringsFrom(const MEDCouplingMesh *other)
49 {
50   MEDCouplingMesh::copyTinyStringsFrom(other);
51 }
52
53 bool MEDCouplingStructuredMesh::isEqualIfNotWhy(const MEDCouplingMesh *other, double prec, std::string& reason) const
54 {
55   return MEDCouplingMesh::isEqualIfNotWhy(other,prec,reason);
56 }
57
58 INTERP_KERNEL::NormalizedCellType MEDCouplingStructuredMesh::getTypeOfCell(int cellId) const
59 {
60   return GetGeoTypeGivenMeshDimension(getMeshDimension());
61 }
62
63 INTERP_KERNEL::NormalizedCellType MEDCouplingStructuredMesh::GetGeoTypeGivenMeshDimension(int meshDim)
64 {
65   switch(meshDim)
66   {
67     case 3:
68       return INTERP_KERNEL::NORM_HEXA8;
69     case 2:
70       return INTERP_KERNEL::NORM_QUAD4;
71     case 1:
72       return INTERP_KERNEL::NORM_SEG2;
73     case 0:
74       return INTERP_KERNEL::NORM_POINT1;
75     default:
76       throw INTERP_KERNEL::Exception("Unexpected dimension for MEDCouplingStructuredMesh::GetGeoTypeGivenMeshDimension !");
77   }
78 }
79
80 std::set<INTERP_KERNEL::NormalizedCellType> MEDCouplingStructuredMesh::getAllGeoTypes() const
81 {
82   std::set<INTERP_KERNEL::NormalizedCellType> ret2;
83   ret2.insert(getTypeOfCell(0));
84   return ret2;
85 }
86
87 int MEDCouplingStructuredMesh::getNumberOfCellsWithType(INTERP_KERNEL::NormalizedCellType type) const
88 {
89   int ret=getNumberOfCells();
90   if(type==getTypeOfCell(0))
91     return ret;
92   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(getTypeOfCell(0));
93   std::ostringstream oss; oss << "MEDCouplingStructuredMesh::getNumberOfCellsWithType : no specified type ! Type available is " << cm.getRepr() << " !";
94   throw INTERP_KERNEL::Exception(oss.str().c_str());
95 }
96
97 DataArrayInt *MEDCouplingStructuredMesh::giveCellsWithType(INTERP_KERNEL::NormalizedCellType type) const
98 {
99   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
100   if(getTypeOfCell(0)==type)
101     {
102       ret->alloc(getNumberOfCells(),1);
103       ret->iota(0);
104     }
105   else
106     ret->alloc(0,1);
107   return ret.retn();
108 }
109
110 DataArrayInt *MEDCouplingStructuredMesh::computeNbOfNodesPerCell() const
111 {
112   int nbCells=getNumberOfCells();
113   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
114   ret->alloc(nbCells,1);
115   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(getTypeOfCell(0));
116   ret->fillWithValue((int)cm.getNumberOfNodes());
117   return ret.retn();
118 }
119
120 DataArrayInt *MEDCouplingStructuredMesh::computeNbOfFacesPerCell() const
121 {
122   int nbCells=getNumberOfCells();
123   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret=DataArrayInt::New();
124   ret->alloc(nbCells,1);
125   const INTERP_KERNEL::CellModel& cm=INTERP_KERNEL::CellModel::GetCellModel(getTypeOfCell(0));
126   ret->fillWithValue((int)cm.getNumberOfSons());
127   return ret.retn();
128 }
129
130 /*!
131  * This method computes effective number of nodes per cell. That is to say nodes appearing several times in nodal connectivity of a cell,
132  * will be counted only once here whereas it will be counted several times in MEDCouplingMesh::computeNbOfNodesPerCell method.
133  * Here for structured mesh it returns exactly as MEDCouplingStructuredMesh::computeNbOfNodesPerCell does.
134  *
135  * \return DataArrayInt * - new object to be deallocated by the caller.
136  */
137 DataArrayInt *MEDCouplingStructuredMesh::computeEffectiveNbOfNodesPerCell() const
138 {
139   return computeNbOfNodesPerCell();
140 }
141
142 void MEDCouplingStructuredMesh::getNodeIdsOfCell(int cellId, std::vector<int>& conn) const
143 {
144   int meshDim=getMeshDimension();
145   int tmpCell[3],tmpNode[3];
146   getSplitCellValues(tmpCell);
147   getSplitNodeValues(tmpNode);
148   int tmp2[3];
149   GetPosFromId(cellId,meshDim,tmpCell,tmp2);
150   switch(meshDim)
151   {
152     case 1:
153       conn.push_back(tmp2[0]); conn.push_back(tmp2[0]+1);
154       break;
155     case 2:
156       conn.push_back(tmp2[1]*tmpNode[1]+tmp2[0]); conn.push_back(tmp2[1]*tmpNode[1]+tmp2[0]+1);
157       conn.push_back((tmp2[1]+1)*tmpNode[1]+tmp2[0]+1); conn.push_back((tmp2[1]+1)*tmpNode[1]+tmp2[0]);
158       break;
159     case 3:
160       conn.push_back(tmp2[1]*tmpNode[1]+tmp2[0]+tmp2[2]*tmpNode[2]); conn.push_back(tmp2[1]*tmpNode[1]+tmp2[0]+1+tmp2[2]*tmpNode[2]);
161       conn.push_back((tmp2[1]+1)*tmpNode[1]+tmp2[0]+1+tmp2[2]*tmpNode[2]); conn.push_back((tmp2[1]+1)*tmpNode[1]+tmp2[0]+tmp2[2]*tmpNode[2]);
162       conn.push_back(tmp2[1]*tmpNode[1]+tmp2[0]+(tmp2[2]+1)*tmpNode[2]); conn.push_back(tmp2[1]*tmpNode[1]+tmp2[0]+1+(tmp2[2]+1)*tmpNode[2]);
163       conn.push_back((tmp2[1]+1)*tmpNode[1]+tmp2[0]+1+(tmp2[2]+1)*tmpNode[2]); conn.push_back((tmp2[1]+1)*tmpNode[1]+tmp2[0]+(tmp2[2]+1)*tmpNode[2]);
164       break;
165     default:
166       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::getNodeIdsOfCell : big problem spacedim must be in 1,2 or 3 !");
167   };
168 }
169
170 /*!
171  * This method returns the number of cells of unstructured sub level mesh, without building it.
172  */
173 int MEDCouplingStructuredMesh::getNumberOfCellsOfSubLevelMesh() const
174 {
175   std::vector<int> cgs(getCellGridStructure());
176   return GetNumberOfCellsOfSubLevelMesh(cgs,getMeshDimension());
177 }
178
179 /*!
180  * See MEDCouplingUMesh::getDistributionOfTypes for more information
181  */
182 std::vector<int> MEDCouplingStructuredMesh::getDistributionOfTypes() const
183 {
184   //only one type of cell
185   std::vector<int> ret(3);
186   ret[0]=getTypeOfCell(0);
187   ret[1]=getNumberOfCells();
188   ret[2]=-1; //ret[3*k+2]==-1 because it has no sense here
189   return ret;
190 }
191
192 /*!
193  * This method tries to minimize at most the number of deep copy.
194  * So if \a idsPerType is not empty it can be returned directly (without copy, but with ref count incremented) in return.
195  * 
196  * See MEDCouplingUMesh::checkTypeConsistencyAndContig for more information
197  */
198 DataArrayInt *MEDCouplingStructuredMesh::checkTypeConsistencyAndContig(const std::vector<int>& code, const std::vector<const DataArrayInt *>& idsPerType) const
199 {
200   int nbOfCells=getNumberOfCells();
201   if(code.size()!=3)
202     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : invalid input code should be exactly of size 3 !");
203   if(code[0]!=(int)getTypeOfCell(0))
204     {
205       std::ostringstream oss; oss << "MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : Mismatch of geometric type ! Asking for " << code[0] << " whereas the geometric type is \a this is " << getTypeOfCell(0) << " !";
206       throw INTERP_KERNEL::Exception(oss.str().c_str());
207     }
208   if(code[2]==-1)
209     {
210       if(code[1]==nbOfCells)
211         return 0;
212       else
213         {
214           std::ostringstream oss; oss << "MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : mismatch between the number of cells in this (" << nbOfCells << ") and the number of non profile (" << code[1] << ") !";
215           throw INTERP_KERNEL::Exception(oss.str().c_str());
216         }
217     }
218   if(code[2]!=0)
219     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : single geo type mesh ! 0 or -1 is expected at pos #2 of input code !");
220   if(idsPerType.size()!=1)
221     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : input code points to DataArrayInt #0 whereas the size of idsPerType is not equal to 1 !");
222   const DataArrayInt *pfl=idsPerType[0];
223   if(!pfl)
224     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : the input code points to a NULL DataArrayInt at rank 0 !");
225   if(pfl->getNumberOfComponents()!=1)
226     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : input profile should have exactly one component !");
227   pfl->checkAllIdsInRange(0,nbOfCells);
228   pfl->incrRef();
229   return const_cast<DataArrayInt *>(pfl);
230 }
231
232 /*!
233  * 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.
234  * 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.
235  * This method has 1 input \a profile and 3 outputs \a code \a idsInPflPerType and \a idsPerType.
236  * 
237  * \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.
238  * \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,
239  *              \a idsInPflPerType[i] stores the tuple ids in \a profile that correspond to the geometric type code[3*i+0]
240  * \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.
241  *              This vector can be empty in case of all geometric type cells are fully covered in ascending in the given input \a profile.
242  * 
243  * \warning for performance reasons no deep copy will be performed, if \a profile can been used as this in output parameters \a idsInPflPerType and \a idsPerType.
244  *
245  * \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
246  *
247  *  \b Example1: <br>
248  *          - Before \a this has 3 cells \a profile contains [0,1,2]
249  *          - After \a code contains [NORM_...,nbCells,-1], \a idsInPflPerType [[0,1,2]] and \a idsPerType is empty <br>
250  * 
251  *  \b Example2: <br>
252  *          - Before \a this has 3 cells \a profile contains [1,2]
253  *          - After \a code contains [NORM_...,nbCells,0], \a idsInPflPerType [[0,1]] and \a idsPerType is [[1,2]] <br>
254
255  */
256 void MEDCouplingStructuredMesh::splitProfilePerType(const DataArrayInt *profile, std::vector<int>& code, std::vector<DataArrayInt *>& idsInPflPerType, std::vector<DataArrayInt *>& idsPerType) const
257 {
258   if(!profile || !profile->isAllocated())
259     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::splitProfilePerType : input profile is NULL or not allocated !");
260   if(profile->getNumberOfComponents()!=1)
261     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::splitProfilePerType : input profile should have exactly one component !");
262   int nbTuples=profile->getNumberOfTuples();
263   int nbOfCells=getNumberOfCells();
264   code.resize(3); idsInPflPerType.resize(1);
265   code[0]=(int)getTypeOfCell(0); code[1]=nbOfCells;
266   idsInPflPerType.resize(1);
267   if(profile->isIdentity() && nbTuples==nbOfCells)
268     {
269       code[2]=-1;
270       idsInPflPerType[0]=0;
271       idsPerType.clear();
272       return ;
273     }
274   code[1]=profile->getNumberOfTuples();
275   code[2]=0;
276   profile->checkAllIdsInRange(0,nbOfCells);
277   idsPerType.resize(1);
278   idsPerType[0]=profile->deepCpy();
279   idsInPflPerType[0]=DataArrayInt::Range(0,nbTuples,1);
280 }
281
282 /*!
283  * Creates a new unstructured mesh (MEDCoupling1SGTUMesh) from \a this structured one.
284  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is to
285  * delete this array using decrRef() as it is no more needed. 
286  *  \throw If \a this->getMeshDimension() is not among [1,2,3].
287  */
288 MEDCoupling1SGTUMesh *MEDCouplingStructuredMesh::build1SGTUnstructured() const
289 {
290   int meshDim(getMeshDimension());
291   if(meshDim<0 || meshDim>3)
292     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::build1SGTUnstructured : meshdim must be in [1,2,3] !");
293   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coords(getCoordinatesAndOwner());
294   int ns[3];
295   getNodeGridStructure(ns);
296   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(Build1GTNodalConnectivity(ns,ns+meshDim));
297   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> ret(MEDCoupling1SGTUMesh::New(getName(),GetGeoTypeGivenMeshDimension(meshDim)));
298   ret->setNodalConnectivity(conn); ret->setCoords(coords);
299   return ret.retn();
300 }
301
302 /*!
303  * This method returns the unstructured mesh (having single geometric type) of the sub level mesh of \a this.
304  * This method is equivalent to computing MEDCouplingUMesh::buildDescendingConnectivity on the unstructurized \a this mesh.
305  * 
306  * The caller is to delete the returned mesh using decrRef() as it is no more needed. 
307  */
308 MEDCoupling1SGTUMesh *MEDCouplingStructuredMesh::build1SGTSubLevelMesh() const
309 {
310   int meshDim(getMeshDimension());
311   if(meshDim<1 || meshDim>3)
312     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::build1SGTSubLevelMesh : meshdim must be in [2,3] !");
313   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coords(getCoordinatesAndOwner());
314   int ns[3];
315   getNodeGridStructure(ns);
316   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(Build1GTNodalConnectivityOfSubLevelMesh(ns,ns+meshDim));
317   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> ret(MEDCoupling1SGTUMesh::New(getName(),GetGeoTypeGivenMeshDimension(meshDim-1)));
318   ret->setNodalConnectivity(conn); ret->setCoords(coords);
319   return ret.retn();
320 }
321
322 /*!
323  * Creates a new unstructured mesh (MEDCouplingUMesh) from \a this structured one.
324  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is to
325  * delete this array using decrRef() as it is no more needed. 
326  *  \throw If \a this->getMeshDimension() is not among [1,2,3].
327  */
328 MEDCouplingUMesh *MEDCouplingStructuredMesh::buildUnstructured() const
329 {
330   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> ret0(build1SGTUnstructured());
331   return ret0->buildUnstructured();
332 }
333
334 /*!
335  * Creates a new MEDCouplingUMesh containing a part of cells of \a this mesh.
336  * The cells to include to the
337  * result mesh are specified by an array of cell ids.
338  *  \param [in] start - an array of cell ids to include to the result mesh.
339  *  \param [in] end - specifies the end of the array \a start, so that
340  *              the last value of \a start is \a end[ -1 ].
341  *  \return MEDCouplingMesh * - a new instance of MEDCouplingUMesh. The caller is to
342  *         delete this mesh using decrRef() as it is no more needed. 
343  */
344 MEDCouplingMesh *MEDCouplingStructuredMesh::buildPart(const int *start, const int *end) const
345 {
346   MEDCouplingUMesh *um=buildUnstructured();
347   MEDCouplingMesh *ret=um->buildPart(start,end);
348   um->decrRef();
349   return ret;
350 }
351
352 MEDCouplingMesh *MEDCouplingStructuredMesh::buildPartAndReduceNodes(const int *start, const int *end, DataArrayInt*& arr) const
353 {
354   std::vector<int> cgs(getCellGridStructure());
355   std::vector< std::pair<int,int> > cellPartFormat,nodePartFormat;
356   if(IsPartStructured(start,end,cgs,cellPartFormat))
357     {
358       MEDCouplingAutoRefCountObjectPtr<MEDCouplingStructuredMesh> ret(buildStructuredSubPart(cellPartFormat));
359       nodePartFormat=cellPartFormat;
360       for(std::vector< std::pair<int,int> >::iterator it=nodePartFormat.begin();it!=nodePartFormat.end();it++)
361         (*it).second++;
362       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp1(BuildExplicitIdsFrom(getNodeGridStructure(),nodePartFormat));
363       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp2(DataArrayInt::New()); tmp2->alloc(getNumberOfNodes(),1);
364       tmp2->fillWithValue(-1);
365       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp3(DataArrayInt::New()); tmp3->alloc(tmp1->getNumberOfTuples(),1); tmp3->iota(0);
366       tmp2->setPartOfValues3(tmp3,tmp1->begin(),tmp1->end(),0,1,1);
367       arr=tmp2.retn();
368       return ret.retn();
369     }
370   else
371     {
372       MEDCouplingUMesh *um=buildUnstructured();
373       MEDCouplingMesh *ret=um->buildPartAndReduceNodes(start,end,arr);
374       um->decrRef();
375       return ret;
376     }
377 }
378
379 DataArrayInt *MEDCouplingStructuredMesh::simplexize(int policy)
380 {
381   throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::simplexize : not available for Cartesian mesh !");
382 }
383
384 /*!
385  * Returns a new MEDCouplingFieldDouble holding normal vectors to cells of \a this
386  * 2D mesh. The computed vectors have 3 components and are normalized.
387  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
388  *          cells and one time. The caller is to delete this field using decrRef() as
389  *          it is no more needed.
390  *  \throw If \a this->getMeshDimension() != 2.
391  */
392 MEDCouplingFieldDouble *MEDCouplingStructuredMesh::buildOrthogonalField() const
393 {
394   if(getMeshDimension()!=2)
395     throw INTERP_KERNEL::Exception("Expected a MEDCouplingStructuredMesh with meshDim == 2 !");
396   MEDCouplingFieldDouble *ret=MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME);
397   DataArrayDouble *array=DataArrayDouble::New();
398   int nbOfCells=getNumberOfCells();
399   array->alloc(nbOfCells,3);
400   double *vals=array->getPointer();
401   for(int i=0;i<nbOfCells;i++)
402     { vals[3*i]=0.; vals[3*i+1]=0.; vals[3*i+2]=1.; }
403   ret->setArray(array);
404   array->decrRef();
405   ret->setMesh(this);
406   return ret;
407 }
408
409 void MEDCouplingStructuredMesh::getReverseNodalConnectivity(DataArrayInt *revNodal, DataArrayInt *revNodalIndx) const
410 {
411   std::vector<int> ngs(getNodeGridStructure());
412   int dim(getSpaceDimension());
413   switch(dim)
414   {
415     case 1:
416       return GetReverseNodalConnectivity1(ngs,revNodal,revNodalIndx);
417     case 2:
418       return GetReverseNodalConnectivity2(ngs,revNodal,revNodalIndx);
419     case 3:
420       return GetReverseNodalConnectivity3(ngs,revNodal,revNodalIndx);
421     default:
422       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::getReverseNodalConnectivity : only dimensions 1, 2 and 3 are supported !");
423   }
424 }
425
426 void MEDCouplingStructuredMesh::GetReverseNodalConnectivity1(const std::vector<int>& ngs, DataArrayInt *revNodal, DataArrayInt *revNodalIndx)
427 {
428   int nbNodes(ngs[0]);
429   revNodalIndx->alloc(nbNodes+1,1);
430   if(nbNodes==0)
431     { revNodal->alloc(0,1); revNodalIndx->setIJ(0,0,0); return ; }
432   if(nbNodes==1)
433     { revNodal->alloc(1,1); revNodal->setIJ(0,0,0); revNodalIndx->setIJ(0,0,0); revNodalIndx->setIJ(1,0,1); return ; }
434   revNodal->alloc(2*(nbNodes-1),1);
435   int *rn(revNodal->getPointer()),*rni(revNodalIndx->getPointer());
436   *rni++=0; *rni=1; *rn++=0;
437   for(int i=1;i<nbNodes-1;i++,rni++)
438     {
439       rn[0]=i-1; rn[1]=i;
440       rni[1]=rni[0]+2;
441       rn+=2;
442     }
443   rn[0]=nbNodes-2; rni[1]=rni[0]+1;
444 }
445
446 void MEDCouplingStructuredMesh::GetReverseNodalConnectivity2(const std::vector<int>& ngs, DataArrayInt *revNodal, DataArrayInt *revNodalIndx)
447 {
448   int nbNodesX(ngs[0]),nbNodesY(ngs[1]);
449   int nbNodes(nbNodesX*nbNodesY);
450   if(nbNodesX==0 || nbNodesY==0)
451     { revNodal->alloc(0,1); revNodalIndx->setIJ(0,0,0); return ; }
452   if(nbNodesX==1 || nbNodesY==1)
453     { std::vector<int> ngs2(1); ngs2[0]=std::max(nbNodesX,nbNodesY); return GetReverseNodalConnectivity1(ngs2,revNodal,revNodalIndx); }
454   revNodalIndx->alloc(nbNodes+1,1);
455   int nbCellsX(nbNodesX-1),nbCellsY(nbNodesY-1);
456   revNodal->alloc(4*(nbNodesX-2)*(nbNodesY-2)+2*2*(nbNodesX-2)+2*2*(nbNodesY-2)+4,1);
457   int *rn(revNodal->getPointer()),*rni(revNodalIndx->getPointer());
458   *rni++=0; *rni=1; *rn++=0;
459   for(int i=1;i<nbNodesX-1;i++,rni++,rn+=2)
460     {
461       rn[0]=i-1; rn[1]=i;
462       rni[1]=rni[0]+2;
463     }
464   rni[1]=rni[0]+1; *rn++=nbCellsX-1;
465   rni++;
466   for(int j=1;j<nbNodesY-1;j++)
467     {
468       int off(nbCellsX*(j-1)),off2(nbCellsX*j);
469       rni[1]=rni[0]+2; rn[0]=off; rn[1]=off2;
470       rni++; rn+=2;
471       for(int i=1;i<nbNodesX-1;i++,rni++,rn+=4)
472         {
473           rn[0]=i-1+off; rn[1]=i+off; rn[2]=i-1+off2; rn[3]=i+off2;
474           rni[1]=rni[0]+4;
475         }
476       rni[1]=rni[0]+2; rn[0]=off+nbCellsX-1; rn[1]=off2+nbCellsX-1;
477       rni++; rn+=2;
478     }
479   int off3(nbCellsX*(nbCellsY-1));
480   rni[1]=rni[0]+1;
481   rni++; *rn++=off3;
482   for(int i=1;i<nbNodesX-1;i++,rni++,rn+=2)
483     {
484       rn[0]=i-1+off3; rn[1]=i+off3;
485       rni[1]=rni[0]+2;
486     }
487   rni[1]=rni[0]+1; rn[0]=nbCellsX*nbCellsY-1;
488 }
489
490 void MEDCouplingStructuredMesh::GetReverseNodalConnectivity3(const std::vector<int>& ngs, DataArrayInt *revNodal, DataArrayInt *revNodalIndx)
491 {
492   int nbNodesX(ngs[0]),nbNodesY(ngs[1]),nbNodesZ(ngs[2]);
493   int nbNodes(nbNodesX*nbNodesY*nbNodesZ);
494   if(nbNodesX==0 || nbNodesY==0 || nbNodesZ==0)
495     { revNodal->alloc(0,1); revNodalIndx->setIJ(0,0,0); return ; }
496   if(nbNodesX==1 || nbNodesY==1 || nbNodesZ==1)
497     {
498       std::vector<int> ngs2(2);
499       int pos(0);
500       bool pass(false);
501       for(int i=0;i<3;i++)
502         {
503           if(pass)
504             { ngs2[pos++]=ngs[i]; }
505           else
506             {
507               pass=ngs[i]==1;
508               if(!pass)
509                 { ngs2[pos++]=ngs[i]; }
510             }
511         }
512       return GetReverseNodalConnectivity2(ngs2,revNodal,revNodalIndx);
513     }
514   revNodalIndx->alloc(nbNodes+1,1);
515   int nbCellsX(nbNodesX-1),nbCellsY(nbNodesY-1),nbCellsZ(nbNodesZ-1);
516   revNodal->alloc(8*(nbNodesX-2)*(nbNodesY-2)*(nbNodesZ-2)+4*(2*(nbNodesX-2)*(nbNodesY-2)+2*(nbNodesX-2)*(nbNodesZ-2)+2*(nbNodesY-2)*(nbNodesZ-2))+2*4*(nbNodesX-2)+2*4*(nbNodesY-2)+2*4*(nbNodesZ-2)+8,1);
517   int *rn(revNodal->getPointer()),*rni(revNodalIndx->getPointer());
518   *rni=0;
519   for(int k=0;k<nbNodesZ;k++)
520     {
521       bool factZ(k!=0 && k!=nbNodesZ-1);
522       int offZ0((k-1)*nbCellsX*nbCellsY),offZ1(k*nbCellsX*nbCellsY);
523       for(int j=0;j<nbNodesY;j++)
524         {
525           bool factYZ(factZ && (j!=0 && j!=nbNodesY-1));
526           int off00((j-1)*nbCellsX+offZ0),off01(j*nbCellsX+offZ0),off10((j-1)*nbCellsX+offZ1),off11(j*nbCellsX+offZ1);
527           for(int i=0;i<nbNodesX;i++,rni++)
528             {
529               int fact(factYZ && (i!=0 && i!=nbNodesX-1));
530               if(fact)
531                 {//most of points fall in this part of code
532                   rn[0]=off00+i-1; rn[1]=off00+i; rn[2]=off01+i-1; rn[3]=off01+i;
533                   rn[4]=off10+i-1; rn[5]=off10+i; rn[6]=off11+i-1; rn[7]=off11+i;
534                   rni[1]=rni[0]+8;
535                   rn+=8;
536                 }
537               else
538                 {
539                   int *rnRef(rn);
540                   if(k>=1 && j>=1 && i>=1)
541                     *rn++=off00+i-1;
542                   if(k>=1 && j>=1 && i<nbCellsX)
543                     *rn++=off00+i;
544                   if(k>=1 && j<nbCellsY && i>=1)
545                     *rn++=off01+i-1;
546                   if(k>=1 && j<nbCellsY && i<nbCellsX)
547                     *rn++=off01+i;
548                   //
549                   if(k<nbCellsZ && j>=1 && i>=1)
550                     *rn++=off10+i-1;
551                   if(k<nbCellsZ && j>=1 && i<nbCellsX)
552                     *rn++=off10+i;
553                   if(k<nbCellsZ && j<nbCellsY && i>=1)
554                     *rn++=off11+i-1;
555                   if(k<nbCellsZ && j<nbCellsY && i<nbCellsX)
556                     *rn++=off11+i;
557                   rni[1]=rni[0]+(int)(std::distance(rnRef,rn));
558                 }
559             }
560         }
561     }
562 }
563
564 /*!
565  * \return DataArrayInt * - newly allocated instance of nodal connectivity compatible for MEDCoupling1SGTMesh instance
566  */
567 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity(const int *nodeStBg, const int *nodeStEnd)
568 {
569   std::size_t dim(std::distance(nodeStBg,nodeStEnd));
570   switch(dim)
571   {
572     case 0:
573       {
574         MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
575         conn->alloc(1,1); conn->setIJ(0,0,0);
576         return conn.retn();
577       }
578     case 1:
579       return Build1GTNodalConnectivity1D(nodeStBg);
580     case 2:
581       return Build1GTNodalConnectivity2D(nodeStBg);
582     case 3:
583       return Build1GTNodalConnectivity3D(nodeStBg);
584     default:
585       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::Build1GTNodalConnectivity : only dimension in [0,1,2,3] supported !");
586   }
587 }
588
589 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivityOfSubLevelMesh(const int *nodeStBg, const int *nodeStEnd)
590 {
591   std::size_t dim(std::distance(nodeStBg,nodeStEnd));
592   switch(dim)
593   {
594     case 3:
595       return Build1GTNodalConnectivityOfSubLevelMesh3D(nodeStBg);
596     case 2:
597       return Build1GTNodalConnectivityOfSubLevelMesh2D(nodeStBg);
598     default:
599       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::Build1GTNodalConnectivityOfSubLevelMesh: only dimension in [2,3] supported !");
600   }
601 }
602
603 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity1D(const int *nodeStBg)
604 {
605   int nbOfCells(*nodeStBg-1);
606   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
607   conn->alloc(2*nbOfCells,1);
608   int *cp=conn->getPointer();
609   for(int i=0;i<nbOfCells;i++)
610     {
611       cp[2*i+0]=i;
612       cp[2*i+1]=i+1;
613     }
614   return conn.retn();
615 }
616
617 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity2D(const int *nodeStBg)
618 {
619   int n1=nodeStBg[0]-1;
620   int n2=nodeStBg[1]-1;
621   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
622   conn->alloc(4*n1*n2,1);
623   int *cp=conn->getPointer();
624   int pos=0;
625   for(int j=0;j<n2;j++)
626     for(int i=0;i<n1;i++,pos++)
627       {
628         cp[4*pos+0]=i+1+j*(n1+1);
629         cp[4*pos+1]=i+j*(n1+1);
630         cp[4*pos+2]=i+(j+1)*(n1+1);
631         cp[4*pos+3]=i+1+(j+1)*(n1+1);
632       }
633   return conn.retn();
634 }
635
636 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity3D(const int *nodeStBg)
637 {
638   int n1=nodeStBg[0]-1;
639   int n2=nodeStBg[1]-1;
640   int n3=nodeStBg[2]-1;
641   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
642   conn->alloc(8*n1*n2*n3,1);
643   int *cp=conn->getPointer();
644   int pos=0;
645   for(int k=0;k<n3;k++)
646     for(int j=0;j<n2;j++)
647       for(int i=0;i<n1;i++,pos++)
648         {
649           int tmp=(n1+1)*(n2+1);
650           cp[8*pos+0]=i+1+j*(n1+1)+k*tmp;
651           cp[8*pos+1]=i+j*(n1+1)+k*tmp;
652           cp[8*pos+2]=i+(j+1)*(n1+1)+k*tmp;
653           cp[8*pos+3]=i+1+(j+1)*(n1+1)+k*tmp;
654           cp[8*pos+4]=i+1+j*(n1+1)+(k+1)*tmp;
655           cp[8*pos+5]=i+j*(n1+1)+(k+1)*tmp;
656           cp[8*pos+6]=i+(j+1)*(n1+1)+(k+1)*tmp;
657           cp[8*pos+7]=i+1+(j+1)*(n1+1)+(k+1)*tmp;
658         }
659   return conn.retn();
660 }
661
662 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivityOfSubLevelMesh3D(const int *nodeStBg)
663 {
664   std::vector<int> ngs(3);
665   int n0(nodeStBg[0]-1),n1(nodeStBg[1]-1),n2(nodeStBg[2]-1); ngs[0]=n0; ngs[1]=n1; ngs[2]=n2;
666   int off0(nodeStBg[0]),off1(nodeStBg[0]*nodeStBg[1]);
667   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
668   conn->alloc(4*GetNumberOfCellsOfSubLevelMesh(ngs,3));
669   int *cp(conn->getPointer());
670   //X
671   for(int i=0;i<nodeStBg[0];i++)
672     for(int j=0;j<n1;j++)
673       for(int k=0;k<n2;k++,cp+=4)
674         { cp[0]=k*off1+j*off0+i; cp[1]=(k+1)*off1+j*off0+i; cp[2]=(k+1)*off1+(j+1)*off0+i; cp[3]=k*off1+(j+1)*off0+i; }
675   //Y
676   for(int j=0;j<nodeStBg[1];j++)
677     for(int i=0;i<n0;i++)
678       for(int k=0;k<n2;k++,cp+=4)
679         { cp[0]=k*off1+j*off0+i; cp[1]=(k+1)*off1+j*off0+i; cp[2]=(k+1)*off1+j*off0+(i+1); cp[3]=k*off1+j*off0+(i+1); }
680   //Z
681   for(int k=0;k<nodeStBg[2];k++)
682     for(int i=0;i<n0;i++)
683       for(int j=0;j<n1;j++,cp+=4)
684         { cp[0]=k*off1+j*off0+i; cp[1]=k*off1+j*off0+(i+1); cp[2]=k*off1+(j+1)*off0+(i+1); cp[3]=k*off1+(j+1)*off0+i; }
685   return conn.retn();
686 }
687
688 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivityOfSubLevelMesh2D(const int *nodeStBg)
689 {
690   std::vector<int> ngs(2);
691   int n0(nodeStBg[0]-1),n1(nodeStBg[1]-1); ngs[0]=n0; ngs[1]=n1;
692   int off0(nodeStBg[0]);
693   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
694   conn->alloc(2*GetNumberOfCellsOfSubLevelMesh(ngs,2));
695   int *cp(conn->getPointer());
696   //X
697   for(int i=0;i<nodeStBg[0];i++)
698     for(int j=0;j<n1;j++,cp+=2)
699       { cp[0]=j*off0+i; cp[1]=(j+1)*off0+i; }
700   //Y
701   for(int j=0;j<nodeStBg[1];j++)
702     for(int i=0;i<n0;i++,cp+=2)
703       { cp[0]=j*off0+i; cp[1]=j*off0+(i+1); }
704   return conn.retn();
705 }
706
707 /*!
708  * Returns a cell id by its (i,j,k) index. The cell is located between the i-th and
709  * ( i + 1 )-th nodes along X axis etc.
710  *  \param [in] i - a index of node coordinates array along X axis.
711  *  \param [in] j - a index of node coordinates array along Y axis.
712  *  \param [in] k - a index of node coordinates array along Z axis.
713  *  \return int - a cell id in \a this mesh.
714  */
715 int MEDCouplingStructuredMesh::getCellIdFromPos(int i, int j, int k) const
716 {
717   int tmp[3]={i,j,k};
718   int tmp2[3];
719   int meshDim(getMeshDimension());
720   getSplitCellValues(tmp2);
721   std::transform(tmp,tmp+meshDim,tmp2,tmp,std::multiplies<int>());
722   return std::accumulate(tmp,tmp+meshDim,0);
723 }
724
725 /*!
726  * Returns a node id by its (i,j,k) index.
727  *  \param [in] i - a index of node coordinates array along X axis.
728  *  \param [in] j - a index of node coordinates array along Y axis.
729  *  \param [in] k - a index of node coordinates array along Z axis.
730  *  \return int - a node id in \a this mesh.
731  */
732 int MEDCouplingStructuredMesh::getNodeIdFromPos(int i, int j, int k) const
733 {
734   int tmp[3]={i,j,k};
735   int tmp2[3];
736   int spaceDim(getSpaceDimension());
737   getSplitNodeValues(tmp2);
738   std::transform(tmp,tmp+spaceDim,tmp2,tmp,std::multiplies<int>());
739   return std::accumulate(tmp,tmp+spaceDim,0);
740 }
741
742 void MEDCouplingStructuredMesh::GetPosFromId(int nodeId, int meshDim, const int *split, int *res)
743 {
744   int work=nodeId;
745   for(int i=meshDim-1;i>=0;i--)
746     {
747       int pos=work/split[i];
748       work=work%split[i];
749       res[i]=pos;
750     }
751 }
752
753 std::vector<int> MEDCouplingStructuredMesh::getCellGridStructure() const
754 {
755   std::vector<int> ret(getNodeGridStructure());
756   std::transform(ret.begin(),ret.end(),ret.begin(),std::bind2nd(std::plus<int>(),-1));
757   return ret;
758 }
759
760 /*!
761  * This method states if given part ids [ \a startIds, \a stopIds) and a structure \a st returns if it can be considered as a structured dataset.
762  * If true is returned \a partCompactFormat will contain the information to build the corresponding part.
763  *
764  * \sa MEDCouplingStructuredMesh::BuildExplicitIdsFrom
765  */
766 bool MEDCouplingStructuredMesh::IsPartStructured(const int *startIds, const int *stopIds, const std::vector<int>& st, std::vector< std::pair<int,int> >& partCompactFormat)
767 {
768   int dim((int)st.size());
769   partCompactFormat.resize(dim);
770   if(dim<1 || dim>3)
771     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::isPartStructured : input structure must be of dimension in [1,2,3] !");
772   std::vector<int> tmp2(dim),tmp(dim),tmp3(dim),tmp4(dim); tmp2[0]=1;
773   for(int i=1;i<dim;i++)
774     tmp2[i]=tmp2[i-1]*st[i-1];
775   std::size_t sz(std::distance(startIds,stopIds));
776   if(sz==0)
777     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : empty input !");
778   GetPosFromId(*startIds,dim,&tmp2[0],&tmp[0]);
779   partCompactFormat.resize(dim);
780   for(int i=0;i<dim;i++)
781     partCompactFormat[i].first=tmp[i];
782   if(tmp[dim-1]<0 || tmp[dim-1]>=st[dim-1])
783     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : first id in input is not in valid range !");
784   if(sz==1)
785     {
786       for(int i=0;i<dim;i++)
787         partCompactFormat[i].second=tmp[i]+1;
788       return true;
789     }
790   GetPosFromId(startIds[sz-1],dim,&tmp2[0],&tmp3[0]);
791   int szExp(1);
792   for(int i=0;i<dim;i++)
793     {
794       if(tmp3[i]<0 || tmp3[i]>=st[i])
795         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : last id in input is not in valid range !");
796       partCompactFormat[i].second=tmp3[i]+1;
797       tmp4[i]=partCompactFormat[i].second-partCompactFormat[i].first;
798       if(tmp4[i]<=0)
799         return false;
800       szExp*=tmp4[i];
801     }
802   if(szExp!=(int)sz)
803     return false;
804   const int *w(startIds);
805   switch(dim)
806   {
807     case 3:
808       {
809         for(int i=0;i<tmp4[2];i++)
810           {
811             int a=tmp2[2]*(partCompactFormat[2].first+i);
812             for(int j=0;j<tmp4[1];j++)
813               {
814                 int b=tmp2[1]*(partCompactFormat[1].first+j);
815                 for(int k=0;k<tmp4[0];k++,w++)
816                   {
817                     if(partCompactFormat[0].first+k+b+a!=*w)
818                       return false;
819                   }
820               }
821           }
822         return true;
823       }
824     case 2:
825       {
826         for(int j=0;j<tmp4[1];j++)
827           {
828             int b=tmp2[1]*(partCompactFormat[1].first+j);
829             for(int k=0;k<tmp4[0];k++,w++)
830               {
831                 if(partCompactFormat[0].first+k+b!=*w)
832                   return false;
833               }
834           }
835         return true;
836       }
837     case 1:
838       {
839         for(int k=0;k<tmp4[0];k++,w++)
840           {
841             if(partCompactFormat[0].first+k!=*w)
842               return false;
843           }
844         return true;
845       }
846     default:
847       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : internal error !");
848   }
849 }
850
851 /*!
852  * This method builds the explicit entity array from the structure in \a st and the range in \a partCompactFormat.
853  *If the range contains invalid values regarding sructure an exception will be thrown.
854  *
855  * \return DataArrayInt * - a new object.
856  * \sa MEDCouplingStructuredMesh::IsPartStructured
857  */
858 DataArrayInt *MEDCouplingStructuredMesh::BuildExplicitIdsFrom(const std::vector<int>& st, const std::vector< std::pair<int,int> >& partCompactFormat)
859 {
860   if(st.size()!=partCompactFormat.size())
861     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : input arrays must have the same size !");
862   int nbOfItems(1);
863   std::vector<int> dims(st.size());
864   for(std::size_t i=0;i<st.size();i++)
865     {
866       if(partCompactFormat[i].first<0 || partCompactFormat[i].first>st[i])
867         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : invalid input range 1 !");
868       if(partCompactFormat[i].second<0 || partCompactFormat[i].second>st[i])
869         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : invalid input range 2 !");
870       if(partCompactFormat[i].second<=partCompactFormat[i].first)
871         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : invalid input range 3 !");
872       dims[i]=partCompactFormat[i].second-partCompactFormat[i].first;
873       nbOfItems*=dims[i];
874     }
875   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New());
876   ret->alloc(nbOfItems,1);
877   int *pt(ret->getPointer());
878   switch(st.size())
879   {
880     case 3:
881       {
882         for(int i=0;i<dims[2];i++)
883           {
884             int a=(partCompactFormat[2].first+i)*st[0]*st[1];
885             for(int j=0;j<dims[1];j++)
886               {
887                 int b=(partCompactFormat[1].first+j)*st[0];
888                 for(int k=0;k<dims[0];k++,pt++)
889                   *pt=partCompactFormat[0].first+k+b+a;
890               }
891           }
892         break;
893       }
894     case 2:
895       {
896         for(int j=0;j<dims[1];j++)
897           {
898             int b=(partCompactFormat[1].first+j)*st[0];
899             for(int k=0;k<dims[0];k++,pt++)
900               *pt=partCompactFormat[0].first+k+b;
901           }
902         break;
903       }
904     case 1:
905       {
906         for(int k=0;k<dims[0];k++,pt++)
907           *pt=partCompactFormat[0].first+k;
908         break;
909       }
910     default:
911       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : Dimension supported are 1,2 or 3 !");
912   }
913   return ret.retn();
914 }
915
916 int MEDCouplingStructuredMesh::GetNumberOfCellsOfSubLevelMesh(const std::vector<int>& cgs, int mdim)
917 {
918   int ret(0);
919   for(int i=0;i<mdim;i++)
920     {
921       int locRet(1);
922       for(int j=0;j<mdim;j++)
923         if(j!=i)
924           locRet*=cgs[j];
925         else
926           locRet*=cgs[j]+1;
927       ret+=locRet;
928     }
929   return ret;
930 }