Salome HOME
Addition of new reference coords including degenerated cells.
[modules/med.git] / src / MEDCoupling / MEDCouplingStructuredMesh.cxx
1 // Copyright (C) 2007-2013  CEA/DEN, EDF R&D
2 //
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
7 //
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11 // Lesser General Public License for more details.
12 //
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 //
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
18 //
19 // 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  * See MEDCouplingUMesh::getDistributionOfTypes for more information
172  */
173 std::vector<int> MEDCouplingStructuredMesh::getDistributionOfTypes() const
174 {
175   //only one type of cell
176   std::vector<int> ret(3);
177   ret[0]=getTypeOfCell(0);
178   ret[1]=getNumberOfCells();
179   ret[2]=-1; //ret[3*k+2]==-1 because it has no sense here
180   return ret;
181 }
182
183 /*!
184  * This method tries to minimize at most the number of deep copy.
185  * So if \a idsPerType is not empty it can be returned directly (without copy, but with ref count incremented) in return.
186  * 
187  * See MEDCouplingUMesh::checkTypeConsistencyAndContig for more information
188  */
189 DataArrayInt *MEDCouplingStructuredMesh::checkTypeConsistencyAndContig(const std::vector<int>& code, const std::vector<const DataArrayInt *>& idsPerType) const
190 {
191   int nbOfCells=getNumberOfCells();
192   if(code.size()!=3)
193     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : invalid input code should be exactly of size 3 !");
194   if(code[0]!=(int)getTypeOfCell(0))
195     {
196       std::ostringstream oss; oss << "MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : Mismatch of geometric type ! Asking for " << code[0] << " whereas the geometric type is \a this is " << getTypeOfCell(0) << " !";
197       throw INTERP_KERNEL::Exception(oss.str().c_str());
198     }
199   if(code[2]==-1)
200     {
201       if(code[1]==nbOfCells)
202         return 0;
203       else
204         {
205           std::ostringstream oss; oss << "MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : mismatch between the number of cells in this (" << nbOfCells << ") and the number of non profile (" << code[1] << ") !";
206           throw INTERP_KERNEL::Exception(oss.str().c_str());
207         }
208     }
209   if(code[2]!=0)
210     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : single geo type mesh ! 0 or -1 is expected at pos #2 of input code !");
211   if(idsPerType.size()!=1)
212     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : input code points to DataArrayInt #0 whereas the size of idsPerType is not equal to 1 !");
213   const DataArrayInt *pfl=idsPerType[0];
214   if(!pfl)
215     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : the input code points to a NULL DataArrayInt at rank 0 !");
216   if(pfl->getNumberOfComponents()!=1)
217     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::checkTypeConsistencyAndContig : input profile should have exactly one component !");
218   pfl->checkAllIdsInRange(0,nbOfCells);
219   pfl->incrRef();
220   return const_cast<DataArrayInt *>(pfl);
221 }
222
223 /*!
224  * 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.
225  * 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.
226  * This method has 1 input \a profile and 3 outputs \a code \a idsInPflPerType and \a idsPerType.
227  * 
228  * \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.
229  * \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,
230  *              \a idsInPflPerType[i] stores the tuple ids in \a profile that correspond to the geometric type code[3*i+0]
231  * \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.
232  *              This vector can be empty in case of all geometric type cells are fully covered in ascending in the given input \a profile.
233  * 
234  * \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.
235  *
236  * \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
237  *
238  *  \b Example1: <br>
239  *          - Before \a this has 3 cells \a profile contains [0,1,2]
240  *          - After \a code contains [NORM_...,nbCells,-1], \a idsInPflPerType [[0,1,2]] and \a idsPerType is empty <br>
241  * 
242  *  \b Example2: <br>
243  *          - Before \a this has 3 cells \a profile contains [1,2]
244  *          - After \a code contains [NORM_...,nbCells,0], \a idsInPflPerType [[0,1]] and \a idsPerType is [[1,2]] <br>
245
246  */
247 void MEDCouplingStructuredMesh::splitProfilePerType(const DataArrayInt *profile, std::vector<int>& code, std::vector<DataArrayInt *>& idsInPflPerType, std::vector<DataArrayInt *>& idsPerType) const
248 {
249   if(!profile || !profile->isAllocated())
250     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::splitProfilePerType : input profile is NULL or not allocated !");
251   if(profile->getNumberOfComponents()!=1)
252     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::splitProfilePerType : input profile should have exactly one component !");
253   int nbTuples=profile->getNumberOfTuples();
254   int nbOfCells=getNumberOfCells();
255   code.resize(3); idsInPflPerType.resize(1);
256   code[0]=(int)getTypeOfCell(0); code[1]=nbOfCells;
257   idsInPflPerType.resize(1);
258   if(profile->isIdentity() && nbTuples==nbOfCells)
259     {
260       code[2]=-1;
261       idsInPflPerType[0]=0;
262       idsPerType.clear();
263       return ;
264     }
265   code[1]=profile->getNumberOfTuples();
266   code[2]=0;
267   profile->checkAllIdsInRange(0,nbOfCells);
268   idsPerType.resize(1);
269   idsPerType[0]=profile->deepCpy();
270   idsInPflPerType[0]=DataArrayInt::Range(0,nbTuples,1);
271 }
272
273 /*!
274  * Creates a new unstructured mesh (MEDCoupling1SGTUMesh) from \a this structured one.
275  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is to
276  * delete this array using decrRef() as it is no more needed. 
277  *  \throw If \a this->getMeshDimension() is not among [1,2,3].
278  */
279 MEDCoupling1SGTUMesh *MEDCouplingStructuredMesh::build1SGTUnstructured() const
280 {
281   int meshDim=getMeshDimension(); 
282   if(meshDim<0 || meshDim>3)
283     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::build1SGTUnstructured : meshdim must be in [1,2,3] !");
284   MEDCouplingAutoRefCountObjectPtr<DataArrayDouble> coords(getCoordinatesAndOwner());
285   int ns[3];
286   getNodeGridStructure(ns);
287   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(Build1GTNodalConnectivity(ns,ns+meshDim));
288   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> ret(MEDCoupling1SGTUMesh::New(getName(),GetGeoTypeGivenMeshDimension(meshDim)));
289   ret->setNodalConnectivity(conn); ret->setCoords(coords);
290   return ret.retn();
291 }
292
293 /*!
294  * Creates a new unstructured mesh (MEDCouplingUMesh) from \a this structured one.
295  *  \return MEDCouplingUMesh * - a new instance of MEDCouplingUMesh. The caller is to
296  * delete this array using decrRef() as it is no more needed. 
297  *  \throw If \a this->getMeshDimension() is not among [1,2,3].
298  */
299 MEDCouplingUMesh *MEDCouplingStructuredMesh::buildUnstructured() const
300 {
301   MEDCouplingAutoRefCountObjectPtr<MEDCoupling1SGTUMesh> ret0(build1SGTUnstructured());
302   return ret0->buildUnstructured();
303 }
304
305 /*!
306  * Creates a new MEDCouplingUMesh containing a part of cells of \a this mesh.
307  * The cells to include to the
308  * result mesh are specified by an array of cell ids.
309  *  \param [in] start - an array of cell ids to include to the result mesh.
310  *  \param [in] end - specifies the end of the array \a start, so that
311  *              the last value of \a start is \a end[ -1 ].
312  *  \return MEDCouplingMesh * - a new instance of MEDCouplingUMesh. The caller is to
313  *         delete this mesh using decrRef() as it is no more needed. 
314  */
315 MEDCouplingMesh *MEDCouplingStructuredMesh::buildPart(const int *start, const int *end) const
316 {
317   MEDCouplingUMesh *um=buildUnstructured();
318   MEDCouplingMesh *ret=um->buildPart(start,end);
319   um->decrRef();
320   return ret;
321 }
322
323 MEDCouplingMesh *MEDCouplingStructuredMesh::buildPartAndReduceNodes(const int *start, const int *end, DataArrayInt*& arr) const
324 {
325   std::vector<int> cgs(getCellGridStructure());
326   std::vector< std::pair<int,int> > cellPartFormat,nodePartFormat;
327   if(IsPartStructured(start,end,cgs,cellPartFormat))
328     {
329       MEDCouplingAutoRefCountObjectPtr<MEDCouplingStructuredMesh> ret(buildStructuredSubPart(cellPartFormat));
330       nodePartFormat=cellPartFormat;
331       for(std::vector< std::pair<int,int> >::iterator it=nodePartFormat.begin();it!=nodePartFormat.end();it++)
332         (*it).second++;
333       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp1(BuildExplicitIdsFrom(getNodeGridStructure(),nodePartFormat));
334       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp2(DataArrayInt::New()); tmp2->alloc(getNumberOfNodes(),1);
335       tmp2->fillWithValue(-1);
336       MEDCouplingAutoRefCountObjectPtr<DataArrayInt> tmp3(DataArrayInt::New()); tmp3->alloc(tmp1->getNumberOfTuples(),1); tmp3->iota(0);
337       tmp2->setPartOfValues3(tmp3,tmp1->begin(),tmp1->end(),0,1,1);
338       arr=tmp2.retn();
339       return ret.retn();
340     }
341   else
342     {
343       MEDCouplingUMesh *um=buildUnstructured();
344       MEDCouplingMesh *ret=um->buildPartAndReduceNodes(start,end,arr);
345       um->decrRef();
346       return ret;
347     }
348 }
349
350 DataArrayInt *MEDCouplingStructuredMesh::simplexize(int policy)
351 {
352   throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::simplexize : not available for Cartesian mesh !");
353 }
354
355 /*!
356  * Returns a new MEDCouplingFieldDouble holding normal vectors to cells of \a this
357  * 2D mesh. The computed vectors have 3 components and are normalized.
358  *  \return MEDCouplingFieldDouble * - a new instance of MEDCouplingFieldDouble on
359  *          cells and one time. The caller is to delete this field using decrRef() as
360  *          it is no more needed.
361  *  \throw If \a this->getMeshDimension() != 2.
362  */
363 MEDCouplingFieldDouble *MEDCouplingStructuredMesh::buildOrthogonalField() const
364 {
365   if(getMeshDimension()!=2)
366     throw INTERP_KERNEL::Exception("Expected a MEDCouplingStructuredMesh with meshDim == 2 !");
367   MEDCouplingFieldDouble *ret=MEDCouplingFieldDouble::New(ON_CELLS,NO_TIME);
368   DataArrayDouble *array=DataArrayDouble::New();
369   int nbOfCells=getNumberOfCells();
370   array->alloc(nbOfCells,3);
371   double *vals=array->getPointer();
372   for(int i=0;i<nbOfCells;i++)
373     { vals[3*i]=0.; vals[3*i+1]=0.; vals[3*i+2]=1.; }
374   ret->setArray(array);
375   array->decrRef();
376   ret->setMesh(this);
377   return ret;
378 }
379
380 void MEDCouplingStructuredMesh::getReverseNodalConnectivity(DataArrayInt *revNodal, DataArrayInt *revNodalIndx) const
381 {
382   std::vector<int> ngs(getNodeGridStructure());
383   int dim(getSpaceDimension());
384   switch(dim)
385   {
386     case 1:
387       return GetReverseNodalConnectivity1(ngs,revNodal,revNodalIndx);
388     case 2:
389       return GetReverseNodalConnectivity2(ngs,revNodal,revNodalIndx);
390     case 3:
391       return GetReverseNodalConnectivity3(ngs,revNodal,revNodalIndx);
392     default:
393       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::getReverseNodalConnectivity : only dimensions 1, 2 and 3 are supported !");
394   }
395 }
396
397 void MEDCouplingStructuredMesh::GetReverseNodalConnectivity1(const std::vector<int>& ngs, DataArrayInt *revNodal, DataArrayInt *revNodalIndx)
398 {
399   int nbNodes(ngs[0]);
400   revNodalIndx->alloc(nbNodes+1,1);
401   if(nbNodes==0)
402     { revNodal->alloc(0,1); revNodalIndx->setIJ(0,0,0); return ; }
403   if(nbNodes==1)
404     { revNodal->alloc(1,1); revNodal->setIJ(0,0,0); revNodalIndx->setIJ(0,0,0); revNodalIndx->setIJ(1,0,1); return ; }
405   revNodal->alloc(2*(nbNodes-1),1);
406   int *rn(revNodal->getPointer()),*rni(revNodalIndx->getPointer());
407   *rni++=0; *rni=1; *rn++=0;
408   for(int i=1;i<nbNodes-1;i++,rni++)
409     {
410       rn[0]=i-1; rn[1]=i;
411       rni[1]=rni[0]+2;
412       rn+=2;
413     }
414   rn[0]=nbNodes-2; rni[1]=rni[0]+1;
415 }
416
417 void MEDCouplingStructuredMesh::GetReverseNodalConnectivity2(const std::vector<int>& ngs, DataArrayInt *revNodal, DataArrayInt *revNodalIndx)
418 {
419   int nbNodesX(ngs[0]),nbNodesY(ngs[1]);
420   int nbNodes(nbNodesX*nbNodesY);
421   if(nbNodesX==0 || nbNodesY==0)
422     { revNodal->alloc(0,1); revNodalIndx->setIJ(0,0,0); return ; }
423   if(nbNodesX==1 || nbNodesY==1)
424     { std::vector<int> ngs2(1); ngs2[0]=std::max(nbNodesX,nbNodesY); return GetReverseNodalConnectivity1(ngs2,revNodal,revNodalIndx); }
425   revNodalIndx->alloc(nbNodes+1,1);
426   int nbCellsX(nbNodesX-1),nbCellsY(nbNodesY-1);
427   revNodal->alloc(4*(nbNodesX-2)*(nbNodesY-2)+2*2*(nbNodesX-2)+2*2*(nbNodesY-2)+4,1);
428   int *rn(revNodal->getPointer()),*rni(revNodalIndx->getPointer());
429   *rni++=0; *rni=1; *rn++=0;
430   for(int i=1;i<nbNodesX-1;i++,rni++,rn+=2)
431     {
432       rn[0]=i-1; rn[1]=i;
433       rni[1]=rni[0]+2;
434     }
435   rni[1]=rni[0]+1; *rn++=nbCellsX-1;
436   rni++;
437   for(int j=1;j<nbNodesY-1;j++)
438     {
439       int off(nbCellsX*(j-1)),off2(nbCellsX*j);
440       rni[1]=rni[0]+2; rn[0]=off; rn[1]=off2;
441       rni++; rn+=2;
442       for(int i=1;i<nbNodesX-1;i++,rni++,rn+=4)
443         {
444           rn[0]=i-1+off; rn[1]=i+off; rn[2]=i-1+off2; rn[3]=i+off2;
445           rni[1]=rni[0]+4;
446         }
447       rni[1]=rni[0]+2; rn[0]=off+nbCellsX-1; rn[1]=off2+nbCellsX-1;
448       rni++; rn+=2;
449     }
450   int off3(nbCellsX*(nbCellsY-1));
451   rni[1]=rni[0]+1;
452   rni++; *rn++=off3;
453   for(int i=1;i<nbNodesX-1;i++,rni++,rn+=2)
454     {
455       rn[0]=i-1+off3; rn[1]=i+off3;
456       rni[1]=rni[0]+2;
457     }
458   rni[1]=rni[0]+1; rn[0]=nbCellsX*nbCellsY-1;
459 }
460
461 void MEDCouplingStructuredMesh::GetReverseNodalConnectivity3(const std::vector<int>& ngs, DataArrayInt *revNodal, DataArrayInt *revNodalIndx)
462 {
463   int nbNodesX(ngs[0]),nbNodesY(ngs[1]),nbNodesZ(ngs[2]);
464   int nbNodes(nbNodesX*nbNodesY*nbNodesZ);
465   if(nbNodesX==0 || nbNodesY==0 || nbNodesZ==0)
466     { revNodal->alloc(0,1); revNodalIndx->setIJ(0,0,0); return ; }
467   if(nbNodesX==1 || nbNodesY==1 || nbNodesZ==1)
468     {
469       std::vector<int> ngs2(2);
470       int pos(0);
471       bool pass(false);
472       for(int i=0;i<3;i++)
473         {
474           if(pass)
475             { ngs2[pos++]=ngs[i]; }
476           else
477             {
478               pass=ngs[i]==1;
479               if(!pass)
480                 { ngs2[pos++]=ngs[i]; }
481             }
482         }
483       return GetReverseNodalConnectivity2(ngs2,revNodal,revNodalIndx);
484     }
485   revNodalIndx->alloc(nbNodes+1,1);
486   int nbCellsX(nbNodesX-1),nbCellsY(nbNodesY-1),nbCellsZ(nbNodesZ-1);
487   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);
488   int *rn(revNodal->getPointer()),*rni(revNodalIndx->getPointer());
489   *rni=0;
490   for(int k=0;k<nbNodesZ;k++)
491     {
492       bool factZ(k!=0 && k!=nbNodesZ-1);
493       int offZ0((k-1)*nbCellsX*nbCellsY),offZ1(k*nbCellsX*nbCellsY);
494       for(int j=0;j<nbNodesY;j++)
495         {
496           bool factYZ(factZ && (j!=0 && j!=nbNodesY-1));
497           int off00((j-1)*nbCellsX+offZ0),off01(j*nbCellsX+offZ0),off10((j-1)*nbCellsX+offZ1),off11(j*nbCellsX+offZ1);
498           for(int i=0;i<nbNodesX;i++,rni++)
499             {
500               int fact(factYZ && (i!=0 && i!=nbNodesX-1));
501               if(fact)
502                 {//most of points fall in this part of code
503                   rn[0]=off00+i-1; rn[1]=off00+i; rn[2]=off01+i-1; rn[3]=off01+i;
504                   rn[4]=off10+i-1; rn[5]=off10+i; rn[6]=off11+i-1; rn[7]=off11+i;
505                   rni[1]=rni[0]+8;
506                   rn+=8;
507                 }
508               else
509                 {
510                   int *rnRef(rn);
511                   if(k>=1 && j>=1 && i>=1)
512                     *rn++=off00+i-1;
513                   if(k>=1 && j>=1 && i<nbCellsX)
514                     *rn++=off00+i;
515                   if(k>=1 && j<nbCellsY && i>=1)
516                     *rn++=off01+i-1;
517                   if(k>=1 && j<nbCellsY && i<nbCellsX)
518                     *rn++=off01+i;
519                   //
520                   if(k<nbCellsZ && j>=1 && i>=1)
521                     *rn++=off10+i-1;
522                   if(k<nbCellsZ && j>=1 && i<nbCellsX)
523                     *rn++=off10+i;
524                   if(k<nbCellsZ && j<nbCellsY && i>=1)
525                     *rn++=off11+i-1;
526                   if(k<nbCellsZ && j<nbCellsY && i<nbCellsX)
527                     *rn++=off11+i;
528                   rni[1]=rni[0]+(int)(std::distance(rnRef,rn));
529                 }
530             }
531         }
532     }
533 }
534
535 /*!
536  * \return DataArrayInt * - newly allocated instance of nodal connectivity compatible for MEDCoupling1SGTMesh instance
537  */
538 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity(const int *nodeStBg, const int *nodeStEnd)
539 {
540   std::size_t dim=std::distance(nodeStBg,nodeStEnd);
541   switch(dim)
542     {
543     case 0:
544       {
545         MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
546         conn->alloc(1,1); conn->setIJ(0,0,0);
547         return conn.retn();
548       }
549     case 1:
550       return Build1GTNodalConnectivity1D(nodeStBg);
551     case 2:
552       return Build1GTNodalConnectivity2D(nodeStBg);
553     case 3:
554       return Build1GTNodalConnectivity3D(nodeStBg);
555     default:
556       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::Build1GTNodalConnectivity : only dimension in [0,1,2,3] supported !");
557     }
558 }
559
560 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity1D(const int *nodeStBg)
561 {
562   int nbOfCells(*nodeStBg-1);
563   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
564   conn->alloc(2*nbOfCells,1);
565   int *cp=conn->getPointer();
566   for(int i=0;i<nbOfCells;i++)
567     {
568       cp[2*i+0]=i;
569       cp[2*i+1]=i+1;
570     }
571   return conn.retn();
572 }
573
574 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity2D(const int *nodeStBg)
575 {
576   int n1=nodeStBg[0]-1;
577   int n2=nodeStBg[1]-1;
578   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
579   conn->alloc(4*n1*n2,1);
580   int *cp=conn->getPointer();
581   int pos=0;
582   for(int j=0;j<n2;j++)
583     for(int i=0;i<n1;i++,pos++)
584       {
585         cp[4*pos+0]=i+1+j*(n1+1);
586         cp[4*pos+1]=i+j*(n1+1);
587         cp[4*pos+2]=i+(j+1)*(n1+1);
588         cp[4*pos+3]=i+1+(j+1)*(n1+1);
589     }
590   return conn.retn();
591 }
592
593 DataArrayInt *MEDCouplingStructuredMesh::Build1GTNodalConnectivity3D(const int *nodeStBg)
594 {
595   int n1=nodeStBg[0]-1;
596   int n2=nodeStBg[1]-1;
597   int n3=nodeStBg[2]-1;
598   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> conn(DataArrayInt::New());
599   conn->alloc(8*n1*n2*n3,1);
600   int *cp=conn->getPointer();
601   int pos=0;
602   for(int k=0;k<n3;k++)
603     for(int j=0;j<n2;j++)
604       for(int i=0;i<n1;i++,pos++)
605         {
606           int tmp=(n1+1)*(n2+1);
607           cp[8*pos+0]=i+1+j*(n1+1)+k*tmp;
608           cp[8*pos+1]=i+j*(n1+1)+k*tmp;
609           cp[8*pos+2]=i+(j+1)*(n1+1)+k*tmp;
610           cp[8*pos+3]=i+1+(j+1)*(n1+1)+k*tmp;
611           cp[8*pos+4]=i+1+j*(n1+1)+(k+1)*tmp;
612           cp[8*pos+5]=i+j*(n1+1)+(k+1)*tmp;
613           cp[8*pos+6]=i+(j+1)*(n1+1)+(k+1)*tmp;
614           cp[8*pos+7]=i+1+(j+1)*(n1+1)+(k+1)*tmp;
615         }
616   return conn.retn();
617 }
618
619 /*!
620  * Returns a cell id by its (i,j,k) index. The cell is located between the i-th and
621  * ( i + 1 )-th nodes along X axis etc.
622  *  \param [in] i - a index of node coordinates array along X axis.
623  *  \param [in] j - a index of node coordinates array along Y axis.
624  *  \param [in] k - a index of node coordinates array along Z axis.
625  *  \return int - a cell id in \a this mesh.
626  */
627 int MEDCouplingStructuredMesh::getCellIdFromPos(int i, int j, int k) const
628 {
629   int tmp[3]={i,j,k};
630   int tmp2[3];
631   int meshDim(getMeshDimension());
632   getSplitCellValues(tmp2);
633   std::transform(tmp,tmp+meshDim,tmp2,tmp,std::multiplies<int>());
634   return std::accumulate(tmp,tmp+meshDim,0);
635 }
636
637 /*!
638  * Returns a node id by its (i,j,k) index.
639  *  \param [in] i - a index of node coordinates array along X axis.
640  *  \param [in] j - a index of node coordinates array along Y axis.
641  *  \param [in] k - a index of node coordinates array along Z axis.
642  *  \return int - a node id in \a this mesh.
643  */
644 int MEDCouplingStructuredMesh::getNodeIdFromPos(int i, int j, int k) const
645 {
646   int tmp[3]={i,j,k};
647   int tmp2[3];
648   int spaceDim(getSpaceDimension());
649   getSplitNodeValues(tmp2);
650   std::transform(tmp,tmp+spaceDim,tmp2,tmp,std::multiplies<int>());
651   return std::accumulate(tmp,tmp+spaceDim,0);
652 }
653
654 void MEDCouplingStructuredMesh::GetPosFromId(int nodeId, int meshDim, const int *split, int *res)
655 {
656   int work=nodeId;
657   for(int i=meshDim-1;i>=0;i--)
658     {
659       int pos=work/split[i];
660       work=work%split[i];
661       res[i]=pos;
662     }
663 }
664
665 std::vector<int> MEDCouplingStructuredMesh::getCellGridStructure() const
666 {
667   std::vector<int> ret(getNodeGridStructure());
668   std::transform(ret.begin(),ret.end(),ret.begin(),std::bind2nd(std::plus<int>(),-1));
669   return ret;
670 }
671
672 /*!
673  * 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.
674  * If true is returned \a partCompactFormat will contain the information to build the corresponding part.
675  *
676  * \sa MEDCouplingStructuredMesh::BuildExplicitIdsFrom
677  */
678 bool MEDCouplingStructuredMesh::IsPartStructured(const int *startIds, const int *stopIds, const std::vector<int>& st, std::vector< std::pair<int,int> >& partCompactFormat)
679 {
680   int dim((int)st.size());
681   partCompactFormat.resize(dim);
682   if(dim<1 || dim>3)
683     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::isPartStructured : input structure must be of dimension in [1,2,3] !");
684   std::vector<int> tmp2(dim),tmp(dim),tmp3(dim),tmp4(dim); tmp2[0]=1;
685   for(int i=1;i<dim;i++)
686     tmp2[i]=tmp2[i-1]*st[i-1];
687   std::size_t sz(std::distance(startIds,stopIds));
688   if(sz==0)
689     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : empty input !");
690   GetPosFromId(*startIds,dim,&tmp2[0],&tmp[0]);
691   partCompactFormat.resize(dim);
692   for(int i=0;i<dim;i++)
693     partCompactFormat[i].first=tmp[i];
694   if(tmp[dim-1]<0 || tmp[dim-1]>=st[dim-1])
695     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : first id in input is not in valid range !");
696   if(sz==1)
697     {
698       for(int i=0;i<dim;i++)
699         partCompactFormat[i].second=tmp[i]+1;
700       return true;
701     }
702   GetPosFromId(startIds[sz-1],dim,&tmp2[0],&tmp3[0]);
703   int szExp(1);
704   for(int i=0;i<dim;i++)
705     {
706       if(tmp3[i]<0 || tmp3[i]>=st[i])
707         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : last id in input is not in valid range !");
708       partCompactFormat[i].second=tmp3[i]+1;
709       tmp4[i]=partCompactFormat[i].second-partCompactFormat[i].first;
710       if(tmp4[i]<=0)
711         return false;
712       szExp*=tmp4[i];
713     }
714   if(szExp!=(int)sz)
715     return false;
716   const int *w(startIds);
717   switch(dim)
718     {
719     case 3:
720       {
721         for(int i=0;i<tmp4[2];i++)
722           {
723             int a=tmp2[2]*(partCompactFormat[2].first+i);
724             for(int j=0;j<tmp4[1];j++)
725               {
726                 int b=tmp2[1]*(partCompactFormat[1].first+j);
727                 for(int k=0;k<tmp4[0];k++,w++)
728                   {
729                     if(partCompactFormat[0].first+k+b+a!=*w)
730                       return false;
731                   }
732               }
733           }
734         return true;
735       }
736     case 2:
737       {
738         for(int j=0;j<tmp4[1];j++)
739           {
740             int b=tmp2[1]*(partCompactFormat[1].first+j);
741             for(int k=0;k<tmp4[0];k++,w++)
742               {
743                 if(partCompactFormat[0].first+k+b!=*w)
744                   return false;
745               }
746           }
747         return true;
748       }
749     case 1:
750       {
751         for(int k=0;k<tmp4[0];k++,w++)
752           {
753             if(partCompactFormat[0].first+k!=*w)
754               return false;
755           }
756         return true;
757       }
758     default:
759       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::IsPartStructured : internal error !");
760     }
761 }
762
763 /*!
764  * This method builds the explicit entity array from the structure in \a st and the range in \a partCompactFormat.
765  *If the range contains invalid values regarding sructure an exception will be thrown.
766  *
767  * \return DataArrayInt * - a new object.
768  * \sa MEDCouplingStructuredMesh::IsPartStructured
769  */
770 DataArrayInt *MEDCouplingStructuredMesh::BuildExplicitIdsFrom(const std::vector<int>& st, const std::vector< std::pair<int,int> >& partCompactFormat)
771 {
772   if(st.size()!=partCompactFormat.size())
773     throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : input arrays must have the same size !");
774   int nbOfItems(1);
775   std::vector<int> dims(st.size());
776   for(std::size_t i=0;i<st.size();i++)
777     {
778       if(partCompactFormat[i].first<0 || partCompactFormat[i].first>st[i])
779         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : invalid input range 1 !");
780       if(partCompactFormat[i].second<0 || partCompactFormat[i].second>st[i])
781         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : invalid input range 2 !");
782       if(partCompactFormat[i].second<=partCompactFormat[i].first)
783         throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : invalid input range 3 !");
784       dims[i]=partCompactFormat[i].second-partCompactFormat[i].first;
785       nbOfItems*=dims[i];
786     }
787   MEDCouplingAutoRefCountObjectPtr<DataArrayInt> ret(DataArrayInt::New());
788   ret->alloc(nbOfItems,1);
789   int *pt(ret->getPointer());
790   switch(st.size())
791     {
792     case 3:
793       {
794         for(int i=0;i<dims[2];i++)
795           {
796             int a=(partCompactFormat[2].first+i)*st[0]*st[1];
797             for(int j=0;j<dims[1];j++)
798               {
799                 int b=(partCompactFormat[1].first+j)*st[0];
800                 for(int k=0;k<dims[0];k++,pt++)
801                   *pt=partCompactFormat[0].first+k+b+a;
802               }
803           }
804         break;
805       }
806     case 2:
807       {
808         for(int j=0;j<dims[1];j++)
809           {
810             int b=(partCompactFormat[1].first+j)*st[0];
811             for(int k=0;k<dims[0];k++,pt++)
812               *pt=partCompactFormat[0].first+k+b;
813           }
814         break;
815       }
816     case 1:
817       {
818         for(int k=0;k<dims[0];k++,pt++)
819           *pt=partCompactFormat[0].first+k;
820         break;
821       }
822     default:
823       throw INTERP_KERNEL::Exception("MEDCouplingStructuredMesh::BuildExplicitIdsFrom : Dimension supported are 1,2 or 3 !");
824     }
825   return ret.retn();
826 }