OpenFOAM logo
The Open Source CFD Toolbox
  Source Guide OpenCFD Solutions Contact OpenFOAM

meshRefinement.C

Go to the documentation of this file.
00001 /*---------------------------------------------------------------------------*\
00002   =========                 |
00003   \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
00004    \\    /   O peration     |
00005     \\  /    A nd           | Copyright (C) 1991-2009 OpenCFD Ltd.
00006      \\/     M anipulation  |
00007 -------------------------------------------------------------------------------
00008 License
00009     This file is part of OpenFOAM.
00010 
00011     OpenFOAM is free software; you can redistribute it and/or modify it
00012     under the terms of the GNU General Public License as published by the
00013     Free Software Foundation; either version 2 of the License, or (at your
00014     option) any later version.
00015 
00016     OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
00017     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
00018     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
00019     for more details.
00020 
00021     You should have received a copy of the GNU General Public License
00022     along with OpenFOAM; if not, write to the Free Software Foundation,
00023     Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
00024 
00025 \*----------------------------------------------------------------------------*/
00026 
00027 #include "meshRefinement.H"
00028 #include "volMesh.H"
00029 #include "volFields.H"
00030 #include "surfaceMesh.H"
00031 #include "syncTools.H"
00032 #include "Time.H"
00033 #include "refinementHistory.H"
00034 #include "refinementSurfaces.H"
00035 #include "decompositionMethod.H"
00036 #include "regionSplit.H"
00037 #include "fvMeshDistribute.H"
00038 #include "indirectPrimitivePatch.H"
00039 #include "polyTopoChange.H"
00040 #include "removeCells.H"
00041 #include "mapDistributePolyMesh.H"
00042 #include "localPointRegion.H"
00043 #include "pointMesh.H"
00044 #include "pointFields.H"
00045 #include "slipPointPatchFields.H"
00046 #include "fixedValuePointPatchFields.H"
00047 #include "globalPointPatchFields.H"
00048 #include "calculatedPointPatchFields.H"
00049 #include "processorPointPatch.H"
00050 #include "globalIndex.H"
00051 #include "meshTools.H"
00052 #include "OFstream.H"
00053 #include "geomDecomp.H"
00054 #include "Random.H"
00055 #include "searchableSurfaces.H"
00056 #include "treeBoundBox.H"
00057 
00058 // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
00059 
00060 namespace Foam
00061 {
00062     defineTypeNameAndDebug(meshRefinement, 0);
00063 }
00064 
00065 // * * * * * * * * * * * * * Private Member Functions  * * * * * * * * * * * //
00066 
00067 void Foam::meshRefinement::calcNeighbourData
00068 (
00069     labelList& neiLevel,
00070     pointField& neiCc
00071 )  const
00072 {
00073     const labelList& cellLevel = meshCutter_.cellLevel();
00074     const pointField& cellCentres = mesh_.cellCentres();
00075 
00076     label nBoundaryFaces = mesh_.nFaces() - mesh_.nInternalFaces();
00077 
00078     if (neiLevel.size() != nBoundaryFaces || neiCc.size() != nBoundaryFaces)
00079     {
00080         FatalErrorIn("meshRefinement::calcNeighbour(..)") << "nBoundaries:"
00081             << nBoundaryFaces << " neiLevel:" << neiLevel.size()
00082             << abort(FatalError);
00083     }
00084 
00085     const polyBoundaryMesh& patches = mesh_.boundaryMesh();
00086 
00087     labelHashSet addedPatchIDSet(meshedPatches());
00088 
00089     forAll(patches, patchI)
00090     {
00091         const polyPatch& pp = patches[patchI];
00092 
00093         const unallocLabelList& faceCells = pp.faceCells();
00094         const vectorField::subField faceCentres = pp.faceCentres();
00095         const vectorField::subField faceAreas = pp.faceAreas();
00096 
00097         label bFaceI = pp.start()-mesh_.nInternalFaces();
00098 
00099         if (pp.coupled())
00100         {
00101             forAll(faceCells, i)
00102             {
00103                 neiLevel[bFaceI] = cellLevel[faceCells[i]];
00104                 neiCc[bFaceI] = cellCentres[faceCells[i]];
00105                 bFaceI++;
00106             }
00107         }
00108         else if (addedPatchIDSet.found(patchI))
00109         {
00110             // Face was introduced from cell-cell intersection. Try to
00111             // reconstruct other side cell(centre). Three possibilities:
00112             // - cells same size.
00113             // - preserved cell smaller. Not handled.
00114             // - preserved cell larger.
00115             forAll(faceCells, i)
00116             {
00117                 // Extrapolate the face centre.
00118                 vector fn = faceAreas[i];
00119                 fn /= mag(fn)+VSMALL;
00120 
00121                 label own = faceCells[i];
00122                 label ownLevel = cellLevel[own];
00123                 label faceLevel = meshCutter_.getAnchorLevel(pp.start()+i);
00124 
00125                 // Normal distance from face centre to cell centre
00126                 scalar d = ((faceCentres[i] - cellCentres[own]) & fn);
00127                 if (faceLevel > ownLevel)
00128                 {
00129                     // Other cell more refined. Adjust normal distance
00130                     d *= 0.5;
00131                 }
00132                 neiLevel[bFaceI] = cellLevel[ownLevel];
00133                 // Calculate other cell centre by extrapolation
00134                 neiCc[bFaceI] = faceCentres[i] + d*fn;
00135                 bFaceI++;
00136             }
00137         }
00138         else
00139         {
00140             forAll(faceCells, i)
00141             {
00142                 neiLevel[bFaceI] = cellLevel[faceCells[i]];
00143                 neiCc[bFaceI] = faceCentres[i];
00144                 bFaceI++;
00145             }
00146         }
00147     }
00148 
00149     // Swap coupled boundaries. Apply separation to cc since is coordinate.
00150     syncTools::swapBoundaryFaceList(mesh_, neiCc, true);
00151     syncTools::swapBoundaryFaceList(mesh_, neiLevel, false);
00152 }
00153 
00154 
00155 // Find intersections of edges (given by their two endpoints) with surfaces.
00156 // Returns first intersection if there are more than one.
00157 void Foam::meshRefinement::updateIntersections(const labelList& changedFaces)
00158 {
00159     const pointField& cellCentres = mesh_.cellCentres();
00160 
00161     // Stats on edges to test. Count proc faces only once.
00162     PackedBoolList isMasterFace(syncTools::getMasterFaces(mesh_));
00163 
00164     {
00165         label nMasterFaces = 0;
00166         forAll(isMasterFace, faceI)
00167         {
00168             if (isMasterFace.get(faceI) == 1)
00169             {
00170                 nMasterFaces++;
00171             }
00172         }
00173         reduce(nMasterFaces, sumOp<label>());
00174 
00175         label nChangedFaces = 0;
00176         forAll(changedFaces, i)
00177         {
00178             if (isMasterFace.get(changedFaces[i]) == 1)
00179             {
00180                 nChangedFaces++;
00181             }
00182         }
00183         reduce(nChangedFaces, sumOp<label>());
00184 
00185         Info<< "Edge intersection testing:" << nl
00186             << "    Number of edges             : " << nMasterFaces << nl
00187             << "    Number of edges to retest   : " << nChangedFaces
00188             << endl;
00189     }
00190 
00191 
00192     // Get boundary face centre and level. Coupled aware.
00193     labelList neiLevel(mesh_.nFaces()-mesh_.nInternalFaces());
00194     pointField neiCc(mesh_.nFaces()-mesh_.nInternalFaces());
00195     calcNeighbourData(neiLevel, neiCc);
00196 
00197     // Collect segments we want to test for
00198     pointField start(changedFaces.size());
00199     pointField end(changedFaces.size());
00200 
00201     forAll(changedFaces, i)
00202     {
00203         label faceI = changedFaces[i];
00204         label own = mesh_.faceOwner()[faceI];
00205 
00206         start[i] = cellCentres[own];
00207         if (mesh_.isInternalFace(faceI))
00208         {
00209             end[i] = cellCentres[mesh_.faceNeighbour()[faceI]];
00210         }
00211         else
00212         {
00213             end[i] = neiCc[faceI-mesh_.nInternalFaces()];
00214         }
00215     }
00216 
00217     // Do tests in one go
00218     labelList surfaceHit;
00219     {
00220         labelList surfaceLevel;
00221         surfaces_.findHigherIntersection
00222         (
00223             start,
00224             end,
00225             labelList(start.size(), -1),    // accept any intersection
00226             surfaceHit,
00227             surfaceLevel
00228         );
00229     }
00230 
00231     // Keep just surface hit
00232     forAll(surfaceHit, i)
00233     {
00234         surfaceIndex_[changedFaces[i]] = surfaceHit[i];
00235     }
00236 
00237     // Make sure both sides have same information. This should be
00238     // case in general since same vectors but just to make sure.
00239     syncTools::syncFaceList(mesh_, surfaceIndex_, maxEqOp<label>(), false);
00240 
00241     label nHits = countHits();
00242     label nTotHits = returnReduce(nHits, sumOp<label>());
00243 
00244     Info<< "    Number of intersected edges : " << nTotHits << endl;
00245 
00246     // Set files to same time as mesh
00247     setInstance(mesh_.facesInstance());
00248 }
00249 
00250 
00251 void Foam::meshRefinement::checkData()
00252 {
00253     Pout<< "meshRefinement::checkData() : Checking refinement structure."
00254         << endl;
00255     meshCutter_.checkMesh();
00256 
00257     Pout<< "meshRefinement::checkData() : Checking refinement levels."
00258         << endl;
00259     meshCutter_.checkRefinementLevels(1, labelList(0));
00260 
00261 
00262     Pout<< "meshRefinement::checkData() : Checking synchronization."
00263         << endl;
00264 
00265     // Check face centres
00266     {
00267         // Boundary face centres
00268         pointField::subList boundaryFc
00269         (
00270             mesh_.faceCentres(),
00271             mesh_.nFaces()-mesh_.nInternalFaces(),
00272             mesh_.nInternalFaces()
00273         );
00274 
00275         // Get neighbouring face centres
00276         pointField neiBoundaryFc(boundaryFc);
00277         syncTools::swapBoundaryFaceList
00278         (
00279             mesh_,
00280             neiBoundaryFc,
00281             true
00282         );
00283 
00284         // Compare
00285         testSyncBoundaryFaceList
00286         (
00287             mergeDistance_,
00288             "testing faceCentres : ",
00289             boundaryFc,
00290             neiBoundaryFc
00291         );
00292     }
00293     // Check meshRefinement
00294     {
00295         // Get boundary face centre and level. Coupled aware.
00296         labelList neiLevel(mesh_.nFaces()-mesh_.nInternalFaces());
00297         pointField neiCc(mesh_.nFaces()-mesh_.nInternalFaces());
00298         calcNeighbourData(neiLevel, neiCc);
00299 
00300         // Collect segments we want to test for
00301         pointField start(mesh_.nFaces());
00302         pointField end(mesh_.nFaces());
00303 
00304         forAll(start, faceI)
00305         {
00306             start[faceI] = mesh_.cellCentres()[mesh_.faceOwner()[faceI]];
00307 
00308             if (mesh_.isInternalFace(faceI))
00309             {
00310                 end[faceI] = mesh_.cellCentres()[mesh_.faceNeighbour()[faceI]];
00311             }
00312             else
00313             {
00314                 end[faceI] = neiCc[faceI-mesh_.nInternalFaces()];
00315             }
00316         }
00317 
00318         // Do tests in one go
00319         labelList surfaceHit;
00320         {
00321             labelList surfaceLevel;
00322             surfaces_.findHigherIntersection
00323             (
00324                 start,
00325                 end,
00326                 labelList(start.size(), -1),    // accept any intersection
00327                 surfaceHit,
00328                 surfaceLevel
00329             );
00330         }
00331 
00332         // Check
00333         forAll(surfaceHit, faceI)
00334         {
00335             if (surfaceHit[faceI] != surfaceIndex_[faceI])
00336             {
00337                 if (mesh_.isInternalFace(faceI))
00338                 {
00339                     WarningIn("meshRefinement::checkData()")
00340                         << "Internal face:" << faceI
00341                         << " fc:" << mesh_.faceCentres()[faceI]
00342                         << " cached surfaceIndex_:" << surfaceIndex_[faceI]
00343                         << " current:" << surfaceHit[faceI]
00344                         << " ownCc:"
00345                         << mesh_.cellCentres()[mesh_.faceOwner()[faceI]]
00346                         << " neiCc:"
00347                         << mesh_.cellCentres()[mesh_.faceNeighbour()[faceI]]
00348                         << endl;
00349                 }
00350                 else
00351                 {
00352                     WarningIn("meshRefinement::checkData()")
00353                         << "Boundary face:" << faceI
00354                         << " fc:" << mesh_.faceCentres()[faceI]
00355                         << " cached surfaceIndex_:" << surfaceIndex_[faceI]
00356                         << " current:" << surfaceHit[faceI]
00357                         << " ownCc:"
00358                         << mesh_.cellCentres()[mesh_.faceOwner()[faceI]]
00359                         << endl;
00360                 }
00361             }
00362         }
00363     }
00364     {
00365         labelList::subList boundarySurface
00366         (
00367             surfaceIndex_,
00368             mesh_.nFaces()-mesh_.nInternalFaces(),
00369             mesh_.nInternalFaces()
00370         );
00371 
00372         labelList neiBoundarySurface(boundarySurface);
00373         syncTools::swapBoundaryFaceList
00374         (
00375             mesh_,
00376             neiBoundarySurface,
00377             false
00378         );
00379 
00380         // Compare
00381         testSyncBoundaryFaceList
00382         (
00383             0,                              // tolerance
00384             "testing surfaceIndex() : ",
00385             boundarySurface,
00386             neiBoundarySurface
00387         );
00388     }
00389 
00390 
00391     // Find duplicate faces
00392     Pout<< "meshRefinement::checkData() : Counting duplicate faces."
00393         << endl;
00394 
00395     labelList duplicateFace
00396     (
00397         localPointRegion::findDuplicateFaces
00398         (
00399             mesh_,
00400             identity(mesh_.nFaces()-mesh_.nInternalFaces())
00401           + mesh_.nInternalFaces()
00402         )
00403     );
00404 
00405     // Count
00406     {
00407         label nDup = 0;
00408 
00409         forAll(duplicateFace, i)
00410         {
00411             if (duplicateFace[i] != -1)
00412             {
00413                 nDup++;
00414             }
00415         }
00416         nDup /= 2;  // will have counted both faces of duplicate
00417         Pout<< "meshRefinement::checkData() : Found " << nDup
00418             << " duplicate pairs of faces." << endl;
00419     }
00420 }
00421 
00422 
00423 void Foam::meshRefinement::setInstance(const fileName& inst)
00424 {
00425     meshCutter_.setInstance(inst);
00426     surfaceIndex_.instance() = inst;
00427 }
00428 
00429 
00430 // Remove cells. Put exposedFaces (output of getExposedFaces(cellsToRemove))
00431 // into exposedPatchIDs.
00432 Foam::autoPtr<Foam::mapPolyMesh> Foam::meshRefinement::doRemoveCells
00433 (
00434     const labelList& cellsToRemove,
00435     const labelList& exposedFaces,
00436     const labelList& exposedPatchIDs,
00437     removeCells& cellRemover
00438 )
00439 {
00440     polyTopoChange meshMod(mesh_);
00441 
00442     // Arbitrary: put exposed faces into last patch.
00443     cellRemover.setRefinement
00444     (
00445         cellsToRemove,
00446         exposedFaces,
00447         exposedPatchIDs,
00448         meshMod
00449     );
00450 
00451     // Change the mesh (no inflation)
00452     autoPtr<mapPolyMesh> map = meshMod.changeMesh(mesh_, false, true);
00453 
00454     // Update fields
00455     mesh_.updateMesh(map);
00456 
00457     // Move mesh (since morphing might not do this)
00458     if (map().hasMotionPoints())
00459     {
00460         mesh_.movePoints(map().preMotionPoints());
00461     }
00462     else
00463     {
00464         // Delete mesh volumes. No other way to do this?
00465         mesh_.clearOut();
00466     }
00467 
00468     if (overwrite_)
00469     {
00470         mesh_.setInstance(oldInstance_);
00471     }
00472 
00473     // Update local mesh data
00474     cellRemover.updateMesh(map);
00475 
00476     // Update intersections. Recalculate intersections for exposed faces.
00477     labelList newExposedFaces = renumber
00478     (
00479         map().reverseFaceMap(),
00480         exposedFaces
00481     );
00482 
00483     //Pout<< "removeCells : updating intersections for "
00484     //    << newExposedFaces.size() << " newly exposed faces." << endl;
00485 
00486     updateMesh(map, newExposedFaces);
00487 
00488     return map;
00489 }
00490 
00491 
00492 // Determine for multi-processor regions the lowest numbered cell on the lowest
00493 // numbered processor.
00494 void Foam::meshRefinement::getCoupledRegionMaster
00495 (
00496     const globalIndex& globalCells,
00497     const boolList& blockedFace,
00498     const regionSplit& globalRegion,
00499     Map<label>& regionToMaster
00500 ) const
00501 {
00502     const polyBoundaryMesh& patches = mesh_.boundaryMesh();
00503 
00504     forAll(patches, patchI)
00505     {
00506         const polyPatch& pp = patches[patchI];
00507 
00508         if (isA<processorPolyPatch>(pp))
00509         {
00510             forAll(pp, i)
00511             {
00512                 label faceI = pp.start()+i;
00513 
00514                 if (!blockedFace[faceI])
00515                 {
00516                     // Only if there is a connection to the neighbour
00517                     // will there be a multi-domain region; if not through
00518                     // this face then through another.
00519 
00520                     label cellI = mesh_.faceOwner()[faceI];
00521                     label globalCellI = globalCells.toGlobal(cellI);
00522 
00523                     Map<label>::iterator iter =
00524                         regionToMaster.find(globalRegion[cellI]);
00525 
00526                     if (iter != regionToMaster.end())
00527                     {
00528                         label master = iter();
00529                         iter() = min(master, globalCellI);
00530                     }
00531                     else
00532                     {
00533                         regionToMaster.insert
00534                         (
00535                             globalRegion[cellI],
00536                             globalCellI
00537                         );
00538                     }
00539                 }
00540             }
00541         }
00542     }
00543 
00544     // Do reduction
00545     Pstream::mapCombineGather(regionToMaster, minEqOp<label>());
00546     Pstream::mapCombineScatter(regionToMaster);
00547 }
00548 
00549 
00550 void Foam::meshRefinement::calcLocalRegions
00551 (
00552     const globalIndex& globalCells,
00553     const labelList& globalRegion,
00554     const Map<label>& coupledRegionToMaster,
00555 
00556     Map<label>& globalToLocalRegion,
00557     pointField& localPoints
00558 ) const
00559 {
00560     globalToLocalRegion.resize(globalRegion.size());
00561     DynamicList<point> localCc(globalRegion.size()/2);
00562 
00563     forAll(globalRegion, cellI)
00564     {
00565         Map<label>::const_iterator fndMaster =
00566             coupledRegionToMaster.find(globalRegion[cellI]);
00567 
00568         if (fndMaster != coupledRegionToMaster.end())
00569         {
00570             // Multi-processor region.
00571             if (globalCells.toGlobal(cellI) == fndMaster())
00572             {
00573                 // I am master. Allocate region for me.
00574                 globalToLocalRegion.insert(globalRegion[cellI], localCc.size());
00575                 localCc.append(mesh_.cellCentres()[cellI]);
00576             }
00577         }
00578         else
00579         {
00580             // Single processor region.
00581             if (globalToLocalRegion.insert(globalRegion[cellI], localCc.size()))
00582             {
00583                 localCc.append(mesh_.cellCentres()[cellI]);
00584             }
00585         }
00586     }
00587 
00588     localPoints.transfer(localCc);
00589 
00590     if (localPoints.size() != globalToLocalRegion.size())
00591     {
00592         FatalErrorIn("calcLocalRegions(..)")
00593             << "localPoints:" << localPoints.size()
00594             << " globalToLocalRegion:" << globalToLocalRegion.size()
00595             << exit(FatalError);
00596     }
00597 }
00598 
00599 
00600 Foam::label Foam::meshRefinement::getShiftedRegion
00601 (
00602     const globalIndex& indexer,
00603     const Map<label>& globalToLocalRegion,
00604     const Map<label>& coupledRegionToShifted,
00605     const label globalRegion
00606 )
00607 {
00608     Map<label>::const_iterator iter =
00609         globalToLocalRegion.find(globalRegion);
00610 
00611     if (iter != globalToLocalRegion.end())
00612     {
00613         // Region is 'owned' locally. Convert local region index into global.
00614         return indexer.toGlobal(iter());
00615     }
00616     else
00617     {
00618         return coupledRegionToShifted[globalRegion];
00619     }
00620 }
00621 
00622 
00623 // Add if not yet present
00624 void Foam::meshRefinement::addUnique(const label elem, labelList& lst)
00625 {
00626     if (findIndex(lst, elem) == -1)
00627     {
00628         label sz = lst.size();
00629         lst.setSize(sz+1);
00630         lst[sz] = elem;
00631     }
00632 }
00633 
00634 
00635 void Foam::meshRefinement::calcRegionRegions
00636 (
00637     const labelList& globalRegion,
00638     const Map<label>& globalToLocalRegion,
00639     const Map<label>& coupledRegionToMaster,
00640     labelListList& regionRegions
00641 ) const
00642 {
00643     // Global region indexing since we now know the shifted regions.
00644     globalIndex shiftIndexer(globalToLocalRegion.size());
00645 
00646     // Redo the coupledRegionToMaster to be in shifted region indexing.
00647     Map<label> coupledRegionToShifted(coupledRegionToMaster.size());
00648     forAllConstIter(Map<label>, coupledRegionToMaster, iter)
00649     {
00650         label region = iter.key();
00651 
00652         Map<label>::const_iterator fndRegion = globalToLocalRegion.find(region);
00653 
00654         if (fndRegion != globalToLocalRegion.end())
00655         {
00656             // A local cell is master of this region. Get its shifted region.
00657             coupledRegionToShifted.insert
00658             (
00659                 region,
00660                 shiftIndexer.toGlobal(fndRegion())
00661             );
00662         }
00663         Pstream::mapCombineGather(coupledRegionToShifted, minEqOp<label>());
00664         Pstream::mapCombineScatter(coupledRegionToShifted);
00665     }
00666 
00667 
00668     // Determine region-region connectivity.
00669     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
00670     // This is for all my regions (so my local ones or the ones I am master
00671     // of) the neighbouring region indices.
00672 
00673 
00674     // Transfer lists.
00675     PtrList<HashSet<edge, Hash<edge> > > regionConnectivity(Pstream::nProcs());
00676     forAll(regionConnectivity, procI)
00677     {
00678         if (procI != Pstream::myProcNo())
00679         {
00680             regionConnectivity.set
00681             (
00682                 procI,
00683                 new HashSet<edge, Hash<edge> >
00684                 (
00685                     coupledRegionToShifted.size()
00686                   / Pstream::nProcs()
00687                 )
00688             );
00689         }
00690     }
00691 
00692 
00693     // Connectivity. For all my local regions the connected regions.
00694     regionRegions.setSize(globalToLocalRegion.size());
00695 
00696     // Add all local connectivity to regionRegions; add all non-local
00697     // to the transferlists.
00698     for (label faceI = 0; faceI < mesh_.nInternalFaces(); faceI++)
00699     {
00700         label ownRegion = globalRegion[mesh_.faceOwner()[faceI]];
00701         label neiRegion = globalRegion[mesh_.faceNeighbour()[faceI]];
00702 
00703         if (ownRegion != neiRegion)
00704         {
00705             label shiftOwnRegion = getShiftedRegion
00706             (
00707                 shiftIndexer,
00708                 globalToLocalRegion,
00709                 coupledRegionToShifted,
00710                 ownRegion
00711             );
00712             label shiftNeiRegion = getShiftedRegion
00713             (
00714                 shiftIndexer,
00715                 globalToLocalRegion,
00716                 coupledRegionToShifted,
00717                 neiRegion
00718             );
00719 
00720 
00721             // Connection between two regions. Send to owner of region.
00722             // - is ownRegion 'owned' by me
00723             // - is neiRegion 'owned' by me
00724 
00725             if (shiftIndexer.isLocal(shiftOwnRegion))
00726             {
00727                 label localI = shiftIndexer.toLocal(shiftOwnRegion);
00728                 addUnique(shiftNeiRegion, regionRegions[localI]);
00729             }
00730             else
00731             {
00732                 label masterProc = shiftIndexer.whichProcID(shiftOwnRegion);
00733                 regionConnectivity[masterProc].insert
00734                 (
00735                     edge(shiftOwnRegion, shiftNeiRegion)
00736                 );
00737             }
00738 
00739             if (shiftIndexer.isLocal(shiftNeiRegion))
00740             {
00741                 label localI = shiftIndexer.toLocal(shiftNeiRegion);
00742                 addUnique(shiftOwnRegion, regionRegions[localI]);
00743             }
00744             else
00745             {
00746                 label masterProc = shiftIndexer.whichProcID(shiftNeiRegion);
00747                 regionConnectivity[masterProc].insert
00748                 (
00749                     edge(shiftOwnRegion, shiftNeiRegion)
00750                 );
00751             }
00752         }
00753     }
00754 
00755 
00756     // Send
00757     forAll(regionConnectivity, procI)
00758     {
00759         if (procI != Pstream::myProcNo())
00760         {
00761             OPstream str(Pstream::blocking, procI);
00762             str << regionConnectivity[procI];
00763         }
00764     }
00765     // Receive
00766     forAll(regionConnectivity, procI)
00767     {
00768         if (procI != Pstream::myProcNo())
00769         {
00770             IPstream str(Pstream::blocking, procI);
00771             str >> regionConnectivity[procI];
00772         }
00773     }
00774 
00775     // Add to addressing.
00776     forAll(regionConnectivity, procI)
00777     {
00778         if (procI != Pstream::myProcNo())
00779         {
00780             for
00781             (
00782                 HashSet<edge, Hash<edge> >::const_iterator iter =
00783                     regionConnectivity[procI].begin();
00784                 iter != regionConnectivity[procI].end();
00785                 ++iter
00786             )
00787             {
00788                 const edge& e = iter.key();
00789 
00790                 bool someLocal = false;
00791                 if (shiftIndexer.isLocal(e[0]))
00792                 {
00793                     label localI = shiftIndexer.toLocal(e[0]);
00794                     addUnique(e[1], regionRegions[localI]);
00795                     someLocal = true;
00796                 }
00797                 if (shiftIndexer.isLocal(e[1]))
00798                 {
00799                     label localI = shiftIndexer.toLocal(e[1]);
00800                     addUnique(e[0], regionRegions[localI]);
00801                     someLocal = true;
00802                 }
00803 
00804                 if (!someLocal)
00805                 {
00806                     FatalErrorIn("calcRegionRegions(..)")
00807                         << "Received from processor " << procI
00808                         << " connection " << e
00809                         << " where none of the elements is local to me."
00810                         << abort(FatalError);
00811                 }
00812             }
00813         }
00814     }
00815 }
00816 
00817 
00818 // * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //
00819 
00820 // Construct from components
00821 Foam::meshRefinement::meshRefinement
00822 (
00823     fvMesh& mesh,
00824     const scalar mergeDistance,
00825     const bool overwrite,
00826     const refinementSurfaces& surfaces,
00827     const shellSurfaces& shells
00828 )
00829 :
00830     mesh_(mesh),
00831     mergeDistance_(mergeDistance),
00832     overwrite_(overwrite),
00833     oldInstance_(mesh.pointsInstance()),
00834     surfaces_(surfaces),
00835     shells_(shells),
00836     meshCutter_
00837     (
00838         mesh,
00839         labelIOList
00840         (
00841             IOobject
00842             (
00843                 "cellLevel",
00844                 mesh_.facesInstance(),
00845                 fvMesh::meshSubDir,
00846                 mesh,
00847                 IOobject::READ_IF_PRESENT,
00848                 IOobject::NO_WRITE,
00849                 false
00850             ),
00851             labelList(mesh_.nCells(), 0)
00852         ),
00853         labelIOList
00854         (
00855             IOobject
00856             (
00857                 "pointLevel",
00858                 mesh_.facesInstance(),
00859                 fvMesh::meshSubDir,
00860                 mesh,
00861                 IOobject::READ_IF_PRESENT,
00862                 IOobject::NO_WRITE,
00863                 false
00864             ),
00865             labelList(mesh_.nPoints(), 0)
00866         ),
00867         refinementHistory
00868         (
00869             IOobject
00870             (
00871                 "refinementHistory",
00872                 mesh_.facesInstance(),
00873                 fvMesh::meshSubDir,
00874                 mesh_,
00875                 IOobject::NO_READ,
00876                 IOobject::NO_WRITE,
00877                 false
00878             ),
00879             List<refinementHistory::splitCell8>(0),
00880             labelList(0)
00881         )   // no unrefinement
00882     ),
00883     surfaceIndex_
00884     (
00885         IOobject
00886         (
00887             "surfaceIndex",
00888             mesh_.facesInstance(),
00889             fvMesh::meshSubDir,
00890             mesh_,
00891             IOobject::NO_READ,
00892             IOobject::NO_WRITE,
00893             false
00894         ),
00895         labelList(mesh_.nFaces(), -1)
00896     ),
00897     userFaceData_(0)
00898 {
00899     // recalculate intersections for all faces
00900     updateIntersections(identity(mesh_.nFaces()));
00901 }
00902 
00903 
00904 // * * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * //
00905 
00906 Foam::label Foam::meshRefinement::countHits() const
00907 {
00908     // Stats on edges to test. Count proc faces only once.
00909     PackedBoolList isMasterFace(syncTools::getMasterFaces(mesh_));
00910 
00911     label nHits = 0;
00912 
00913     forAll(surfaceIndex_, faceI)
00914     {
00915         if (surfaceIndex_[faceI] >= 0 && isMasterFace.get(faceI) == 1)
00916         {
00917             nHits++;
00918         }
00919     }
00920     return nHits;
00921 }
00922 
00923 
00924 // Determine distribution to move connected regions onto one processor.
00925 Foam::labelList Foam::meshRefinement::decomposeCombineRegions
00926 (
00927     const boolList& blockedFace,
00928     const List<labelPair>& explicitConnections,
00929     decompositionMethod& decomposer
00930 ) const
00931 {
00932     // Determine global regions, separated by blockedFaces
00933     regionSplit globalRegion(mesh_, blockedFace, explicitConnections);
00934 
00935     // Now globalRegion has global region per cell. Problem is that
00936     // the region might span multiple domains so we want to get
00937     // a "region master" per domain. Note that multi-processor
00938     // regions can only occur on cells on coupled patches.
00939     // Note: since the number of regions does not change by this the
00940     // process can be seen as just a shift of a region onto a single
00941     // processor.
00942 
00943 
00944     // Global cell numbering engine
00945     globalIndex globalCells(mesh_.nCells());
00946 
00947 
00948     // Determine per coupled region the master cell (lowest numbered cell
00949     // on lowest numbered processor)
00950     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
00951     // (does not determine master for non-coupled=fully-local regions)
00952 
00953     Map<label> coupledRegionToMaster(mesh_.nFaces()-mesh_.nInternalFaces());
00954     getCoupledRegionMaster
00955     (
00956         globalCells,
00957         blockedFace,
00958         globalRegion,
00959         coupledRegionToMaster
00960     );
00961 
00962     // Determine my regions
00963     // ~~~~~~~~~~~~~~~~~~~~
00964     // These are the fully local ones or the coupled ones of which I am master.
00965 
00966     Map<label> globalToLocalRegion;
00967     pointField localPoints;
00968     calcLocalRegions
00969     (
00970         globalCells,
00971         globalRegion,
00972         coupledRegionToMaster,
00973 
00974         globalToLocalRegion,
00975         localPoints
00976     );
00977 
00978 
00979 
00980     // Find distribution for regions
00981     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
00982 
00983     labelList regionDistribution;
00984 
00985     if (isA<geomDecomp>(decomposer))
00986     {
00987         regionDistribution = decomposer.decompose(localPoints);
00988     }
00989     else
00990     {
00991         labelListList regionRegions;
00992         calcRegionRegions
00993         (
00994             globalRegion,
00995             globalToLocalRegion,
00996             coupledRegionToMaster,
00997 
00998             regionRegions
00999         );
01000 
01001         regionDistribution = decomposer.decompose(regionRegions, localPoints);
01002     }
01003 
01004 
01005 
01006     // Convert region-based decomposition back to cell-based one
01007     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
01008 
01009     // Transfer destination processor back to all. Use global reduce for now.
01010     Map<label> regionToDist(coupledRegionToMaster.size());
01011     forAllConstIter(Map<label>, coupledRegionToMaster, iter)
01012     {
01013         label region = iter.key();
01014 
01015         Map<label>::const_iterator regionFnd = globalToLocalRegion.find(region);
01016 
01017         if (regionFnd != globalToLocalRegion.end())
01018         {
01019             // Master cell is local. Store my distribution.
01020             regionToDist.insert(iter.key(), regionDistribution[regionFnd()]);
01021         }
01022         else
01023         {
01024             // Master cell is not on this processor. Make sure it is overridden.
01025             regionToDist.insert(iter.key(), labelMax);
01026         }
01027     }
01028     Pstream::mapCombineGather(regionToDist, minEqOp<label>());
01029     Pstream::mapCombineScatter(regionToDist);
01030 
01031 
01032     // Determine destination for all cells
01033     labelList distribution(mesh_.nCells());
01034 
01035     forAll(globalRegion, cellI)
01036     {
01037         Map<label>::const_iterator fndRegion =
01038             regionToDist.find(globalRegion[cellI]);
01039 
01040         if (fndRegion != regionToDist.end())
01041         {
01042             distribution[cellI] = fndRegion();
01043         }
01044         else
01045         {
01046             // region is local to the processor.
01047             label localRegionI = globalToLocalRegion[globalRegion[cellI]];
01048 
01049             distribution[cellI] = regionDistribution[localRegionI];
01050         }
01051     }
01052 
01053     return distribution;
01054 }
01055 
01056 
01057 Foam::autoPtr<Foam::mapDistributePolyMesh> Foam::meshRefinement::balance
01058 (
01059     const bool keepZoneFaces,
01060     const bool keepBaffles,
01061     decompositionMethod& decomposer,
01062     fvMeshDistribute& distributor
01063 )
01064 {
01065     autoPtr<mapDistributePolyMesh> map;
01066 
01067     if (Pstream::parRun())
01068     {
01069         //if (debug_)
01070         //{
01071         //    const_cast<Time&>(mesh_.time())++;
01072         //}
01073 
01074         // Wanted distribution
01075         labelList distribution;
01076 
01077         if (keepZoneFaces || keepBaffles)
01078         {
01079             // Faces where owner and neighbour are not 'connected' so can
01080             // go to different processors.
01081             boolList blockedFace(mesh_.nFaces(), true);
01082             label nUnblocked = 0;
01083             // Pairs of baffles
01084             List<labelPair> couples;
01085 
01086             if (keepZoneFaces)
01087             {
01088                 // Determine decomposition to keep/move surface zones
01089                 // on one processor. The reason is that snapping will make these
01090                 // into baffles, move and convert them back so if they were
01091                 // proc boundaries after baffling&moving the points might be no
01092                 // longer snychronised so recoupling will fail. To prevent this
01093                 // keep owner&neighbour of such a surface zone on the same
01094                 // processor.
01095 
01096                 const wordList& fzNames = surfaces().faceZoneNames();
01097                 const faceZoneMesh& fZones = mesh_.faceZones();
01098 
01099                 // Get faces whose owner and neighbour should stay together,
01100                 // i.e. they are not 'blocked'.
01101 
01102                 forAll(fzNames, surfI)
01103                 {
01104                     if (fzNames[surfI].size())
01105                     {
01106                         // Get zone
01107                         label zoneI = fZones.findZoneID(fzNames[surfI]);
01108 
01109                         const faceZone& fZone = fZones[zoneI];
01110 
01111                         forAll(fZone, i)
01112                         {
01113                             if (blockedFace[fZone[i]])
01114                             {
01115                                 blockedFace[fZone[i]] = false;
01116                                 nUnblocked++;
01117                             }
01118                         }
01119                     }
01120                 }
01121             }
01122             reduce(nUnblocked, sumOp<label>());
01123 
01124             if (keepZoneFaces)
01125             {
01126                 Info<< "Found " << nUnblocked
01127                     << " zoned faces to keep together." << endl;
01128             }
01129 
01130             if (keepBaffles)
01131             {
01132                 // Get boundary baffles that need to stay together.
01133                 couples = getDuplicateFaces   // all baffles
01134                 (
01135                     identity(mesh_.nFaces()-mesh_.nInternalFaces())
01136                    +mesh_.nInternalFaces()
01137                 );
01138             }
01139             label nCouples = returnReduce(couples.size(), sumOp<label>());
01140 
01141             if (keepBaffles)
01142             {
01143                 Info<< "Found " << nCouples << " baffles to keep together."
01144                     << endl;
01145             }
01146 
01147             if (nUnblocked > 0 || nCouples > 0)
01148             {
01149                 Info<< "Applying special decomposition to keep baffles"
01150                     << " and zoned faces together." << endl;
01151 
01152                 distribution = decomposeCombineRegions
01153                 (
01154                     blockedFace,
01155                     couples,
01156                     decomposer
01157                 );
01158 
01159                 labelList nProcCells(distributor.countCells(distribution));
01160                 Pstream::listCombineGather(nProcCells, plusEqOp<label>());
01161                 Pstream::listCombineScatter(nProcCells);
01162 
01163                 Info<< "Calculated decomposition:" << endl;
01164                 forAll(nProcCells, procI)
01165                 {
01166                     Info<< "    " << procI << '\t' << nProcCells[procI] << endl;
01167                 }
01168                 Info<< endl;
01169             }
01170             else
01171             {
01172                 // Normal decomposition
01173                 distribution = decomposer.decompose(mesh_.cellCentres());
01174             }
01175         }
01176         else
01177         {
01178             // Normal decomposition
01179             distribution = decomposer.decompose(mesh_.cellCentres());
01180         }
01181 
01182         if (debug)
01183         {
01184             labelList nProcCells(distributor.countCells(distribution));
01185             Pout<< "Wanted distribution:" << nProcCells << endl;
01186 
01187             Pstream::listCombineGather(nProcCells, plusEqOp<label>());
01188             Pstream::listCombineScatter(nProcCells);
01189 
01190             Pout<< "Wanted resulting decomposition:" << endl;
01191             forAll(nProcCells, procI)
01192             {
01193                 Pout<< "    " << procI << '\t' << nProcCells[procI] << endl;
01194             }
01195             Pout<< endl;
01196         }
01197         // Do actual sending/receiving of mesh
01198         map = distributor.distribute(distribution);
01199 
01200         // Update numbering of meshRefiner
01201         distribute(map);
01202     }
01203     return map;
01204 }
01205 
01206 
01207 // Helper function to get intersected faces
01208 Foam::labelList Foam::meshRefinement::intersectedFaces() const
01209 {
01210     label nBoundaryFaces = 0;
01211 
01212     forAll(surfaceIndex_, faceI)
01213     {
01214         if (surfaceIndex_[faceI] != -1)
01215         {
01216             nBoundaryFaces++;
01217         }
01218     }
01219 
01220     labelList surfaceFaces(nBoundaryFaces);
01221     nBoundaryFaces = 0;
01222 
01223     forAll(surfaceIndex_, faceI)
01224     {
01225         if (surfaceIndex_[faceI] != -1)
01226         {
01227             surfaceFaces[nBoundaryFaces++] = faceI;
01228         }
01229     }
01230     return surfaceFaces;
01231 }
01232 
01233 
01234 // Helper function to get points used by faces
01235 Foam::labelList Foam::meshRefinement::intersectedPoints() const
01236 {
01237     const faceList& faces = mesh_.faces();
01238 
01239     // Mark all points on faces that will become baffles
01240     PackedBoolList isBoundaryPoint(mesh_.nPoints(), 0u);
01241     label nBoundaryPoints = 0;
01242 
01243     forAll(surfaceIndex_, faceI)
01244     {
01245         if (surfaceIndex_[faceI] != -1)
01246         {
01247             const face& f = faces[faceI];
01248 
01249             forAll(f, fp)
01250             {
01251                 if (isBoundaryPoint.set(f[fp], 1u))
01252                 {
01253                     nBoundaryPoints++;
01254                 }
01255             }
01256         }
01257     }
01258 
01260     //labelList adaptPatchIDs(meshedPatches());
01261     //forAll(adaptPatchIDs, i)
01262     //{
01263     //    label patchI = adaptPatchIDs[i];
01264     //
01265     //    if (patchI != -1)
01266     //    {
01267     //        const polyPatch& pp = mesh_.boundaryMesh()[patchI];
01268     //
01269     //        label faceI = pp.start();
01270     //
01271     //        forAll(pp, i)
01272     //        {
01273     //            const face& f = faces[faceI];
01274     //
01275     //            forAll(f, fp)
01276     //            {
01277     //                if (isBoundaryPoint.set(f[fp], 1u))
01278     //                    nBoundaryPoints++;
01279     //                }
01280     //            }
01281     //            faceI++;
01282     //        }
01283     //    }
01284     //}
01285 
01286 
01287     // Pack
01288     labelList boundaryPoints(nBoundaryPoints);
01289     nBoundaryPoints = 0;
01290     forAll(isBoundaryPoint, pointI)
01291     {
01292         if (isBoundaryPoint.get(pointI) == 1u)
01293         {
01294             boundaryPoints[nBoundaryPoints++] = pointI;
01295         }
01296     }
01297 
01298     return boundaryPoints;
01299 }
01300 
01301 
01302 //- Create patch from set of patches
01303 Foam::autoPtr<Foam::indirectPrimitivePatch> Foam::meshRefinement::makePatch
01304 (
01305     const polyMesh& mesh,
01306     const labelList& patchIDs
01307 )
01308 {
01309     const polyBoundaryMesh& patches = mesh.boundaryMesh();
01310 
01311     // Count faces.
01312     label nFaces = 0;
01313 
01314     forAll(patchIDs, i)
01315     {
01316         const polyPatch& pp = patches[patchIDs[i]];
01317 
01318         nFaces += pp.size();
01319     }
01320 
01321     // Collect faces.
01322     labelList addressing(nFaces);
01323     nFaces = 0;
01324 
01325     forAll(patchIDs, i)
01326     {
01327         const polyPatch& pp = patches[patchIDs[i]];
01328 
01329         label meshFaceI = pp.start();
01330 
01331         forAll(pp, i)
01332         {
01333             addressing[nFaces++] = meshFaceI++;
01334         }
01335     }
01336 
01337     return autoPtr<indirectPrimitivePatch>
01338     (
01339         new indirectPrimitivePatch
01340         (
01341             IndirectList<face>(mesh.faces(), addressing),
01342             mesh.points()
01343         )
01344     );
01345 }
01346 
01347 
01348 // Construct pointVectorField with correct boundary conditions
01349 Foam::tmp<Foam::pointVectorField> Foam::meshRefinement::makeDisplacementField
01350 (
01351     const pointMesh& pMesh,
01352     const labelList& adaptPatchIDs
01353 )
01354 {
01355     const polyMesh& mesh = pMesh();
01356 
01357     // Construct displacement field.
01358     const pointBoundaryMesh& pointPatches = pMesh.boundary();
01359 
01360     wordList patchFieldTypes
01361     (
01362         pointPatches.size(),
01363         slipPointPatchVectorField::typeName
01364     );
01365 
01366     forAll(adaptPatchIDs, i)
01367     {
01368         patchFieldTypes[adaptPatchIDs[i]] =
01369             fixedValuePointPatchVectorField::typeName;
01370     }
01371 
01372     forAll(pointPatches, patchI)
01373     {
01374         if (isA<globalPointPatch>(pointPatches[patchI]))
01375         {
01376             patchFieldTypes[patchI] = globalPointPatchVectorField::typeName;
01377         }
01378         else if (isA<processorPointPatch>(pointPatches[patchI]))
01379         {
01380             patchFieldTypes[patchI] = calculatedPointPatchVectorField::typeName;
01381         }
01382     }
01383 
01384     tmp<pointVectorField> tfld
01385     (
01386         new pointVectorField
01387         (
01388             IOobject
01389             (
01390                 "pointDisplacement",
01391                 mesh.time().timeName(), //timeName(),
01392                 mesh,
01393                 IOobject::NO_READ,
01394                 IOobject::AUTO_WRITE
01395             ),
01396             pMesh,
01397             dimensionedVector("displacement", dimLength, vector::zero),
01398             patchFieldTypes
01399         )
01400     );
01401     return tfld;
01402 }
01403 
01404 
01405 void Foam::meshRefinement::checkCoupledFaceZones(const polyMesh& mesh)
01406 {
01407     const faceZoneMesh& fZones = mesh.faceZones();
01408 
01409     // Check any zones are present anywhere and in same order
01410 
01411     {
01412         List<wordList> zoneNames(Pstream::nProcs());
01413         zoneNames[Pstream::myProcNo()] = fZones.names();
01414         Pstream::gatherList(zoneNames);
01415         Pstream::scatterList(zoneNames);
01416         // All have same data now. Check.
01417         forAll(zoneNames, procI)
01418         {
01419             if (procI != Pstream::myProcNo())
01420             {
01421                 if (zoneNames[procI] != zoneNames[Pstream::myProcNo()])
01422                 {
01423                     FatalErrorIn
01424                     (
01425                         "meshRefinement::checkCoupledFaceZones(const polyMesh&)"
01426                     )   << "faceZones are not synchronised on processors." << nl
01427                         << "Processor " << procI << " has faceZones "
01428                         << zoneNames[procI] << nl
01429                         << "Processor " << Pstream::myProcNo()
01430                         << " has faceZones "
01431                         << zoneNames[Pstream::myProcNo()] << nl
01432                         << exit(FatalError);
01433                 }
01434             }
01435         }
01436     }
01437 
01438     // Check that coupled faces are present on both sides.
01439 
01440     labelList faceToZone(mesh.nFaces()-mesh.nInternalFaces(), -1);
01441 
01442     forAll(fZones, zoneI)
01443     {
01444         const faceZone& fZone = fZones[zoneI];
01445 
01446         forAll(fZone, i)
01447         {
01448             label bFaceI = fZone[i]-mesh.nInternalFaces();
01449 
01450             if (bFaceI >= 0)
01451             {
01452                 if (faceToZone[bFaceI] == -1)
01453                 {
01454                     faceToZone[bFaceI] = zoneI;
01455                 }
01456                 else if (faceToZone[bFaceI] == zoneI)
01457                 {
01458                     FatalErrorIn
01459                     (
01460                         "meshRefinement::checkCoupledFaceZones(const polyMesh&)"
01461                     )   << "Face " << fZone[i] << " in zone "
01462                         << fZone.name()
01463                         << " is twice in zone!"
01464                         << abort(FatalError);
01465                 }
01466                 else
01467                 {
01468                     FatalErrorIn
01469                     (
01470                         "meshRefinement::checkCoupledFaceZones(const polyMesh&)"
01471                     )   << "Face " << fZone[i] << " in zone "
01472                         << fZone.name()
01473                         << " is also in zone "
01474                         << fZones[faceToZone[bFaceI]].name()
01475                         << abort(FatalError);
01476                 }
01477             }
01478         }
01479     }
01480 
01481     labelList neiFaceToZone(faceToZone);
01482     syncTools::swapBoundaryFaceList(mesh, neiFaceToZone, false);
01483 
01484     forAll(faceToZone, i)
01485     {
01486         if (faceToZone[i] != neiFaceToZone[i])
01487         {
01488             FatalErrorIn
01489             (
01490                 "meshRefinement::checkCoupledFaceZones(const polyMesh&)"
01491             )   << "Face " << mesh.nInternalFaces()+i
01492                 << " is in zone " << faceToZone[i]
01493                 << ", its coupled face is in zone " << neiFaceToZone[i]
01494                 << abort(FatalError);
01495         }
01496     }
01497 }
01498 
01499 
01500 // Adds patch if not yet there. Returns patchID.
01501 Foam::label Foam::meshRefinement::addPatch
01502 (
01503     fvMesh& mesh,
01504     const word& patchName,
01505     const word& patchType
01506 )
01507 {
01508     polyBoundaryMesh& polyPatches =
01509         const_cast<polyBoundaryMesh&>(mesh.boundaryMesh());
01510 
01511     label patchI = polyPatches.findPatchID(patchName);
01512     if (patchI != -1)
01513     {
01514         if (polyPatches[patchI].type() == patchType)
01515         {
01516             // Already there
01517             return patchI;
01518         }
01519         //else
01520         //{
01521         //    FatalErrorIn
01522         //    (
01523         //        "meshRefinement::addPatch(fvMesh&, const word&, const word&)"
01524         //    )   << "Patch " << patchName << " already exists but with type "
01525         //        << patchType << nl
01526         //        << "Current patch names:" << polyPatches.names()
01527         //        << exit(FatalError);
01528         //}
01529     }
01530 
01531 
01532     label insertPatchI = polyPatches.size();
01533     label startFaceI = mesh.nFaces();
01534 
01535     forAll(polyPatches, patchI)
01536     {
01537         const polyPatch& pp = polyPatches[patchI];
01538 
01539         if (isA<processorPolyPatch>(pp))
01540         {
01541             insertPatchI = patchI;
01542             startFaceI = pp.start();
01543             break;
01544         }
01545     }
01546 
01547 
01548     // Below is all quite a hack. Feel free to change once there is a better
01549     // mechanism to insert and reorder patches.
01550 
01551     // Clear local fields and e.g. polyMesh parallelInfo.
01552     mesh.clearOut();
01553 
01554     label sz = polyPatches.size();
01555 
01556     fvBoundaryMesh& fvPatches = const_cast<fvBoundaryMesh&>(mesh.boundary());
01557 
01558     // Add polyPatch at the end
01559     polyPatches.setSize(sz+1);
01560     polyPatches.set
01561     (
01562         sz,
01563         polyPatch::New
01564         (
01565             patchType,
01566             patchName,
01567             0,              // size
01568             startFaceI,
01569             insertPatchI,
01570             polyPatches
01571         )
01572     );
01573     fvPatches.setSize(sz+1);
01574     fvPatches.set
01575     (
01576         sz,
01577         fvPatch::New
01578         (
01579             polyPatches[sz],  // point to newly added polyPatch
01580             mesh.boundary()
01581         )
01582     );
01583 
01584     addPatchFields<volScalarField>
01585     (
01586         mesh,
01587         calculatedFvPatchField<scalar>::typeName
01588     );
01589     addPatchFields<volVectorField>
01590     (
01591         mesh,
01592         calculatedFvPatchField<vector>::typeName
01593     );
01594     addPatchFields<volSphericalTensorField>
01595     (
01596         mesh,
01597         calculatedFvPatchField<sphericalTensor>::typeName
01598     );
01599     addPatchFields<volSymmTensorField>
01600     (
01601         mesh,
01602         calculatedFvPatchField<symmTensor>::typeName
01603     );
01604     addPatchFields<volTensorField>
01605     (
01606         mesh,
01607         calculatedFvPatchField<tensor>::typeName
01608     );
01609 
01610     // Surface fields
01611 
01612     addPatchFields<surfaceScalarField>
01613     (
01614         mesh,
01615         calculatedFvPatchField<scalar>::typeName
01616     );
01617     addPatchFields<surfaceVectorField>
01618     (
01619         mesh,
01620         calculatedFvPatchField<vector>::typeName
01621     );
01622     addPatchFields<surfaceSphericalTensorField>
01623     (
01624         mesh,
01625         calculatedFvPatchField<sphericalTensor>::typeName
01626     );
01627     addPatchFields<surfaceSymmTensorField>
01628     (
01629         mesh,
01630         calculatedFvPatchField<symmTensor>::typeName
01631     );
01632     addPatchFields<surfaceTensorField>
01633     (
01634         mesh,
01635         calculatedFvPatchField<tensor>::typeName
01636     );
01637 
01638     // Create reordering list
01639     // patches before insert position stay as is
01640     labelList oldToNew(sz+1);
01641     for (label i = 0; i < insertPatchI; i++)
01642     {
01643         oldToNew[i] = i;
01644     }
01645     // patches after insert position move one up
01646     for (label i = insertPatchI; i < sz; i++)
01647     {
01648         oldToNew[i] = i+1;
01649     }
01650     // appended patch gets moved to insert position
01651     oldToNew[sz] = insertPatchI;
01652 
01653     // Shuffle into place
01654     polyPatches.reorder(oldToNew);
01655     fvPatches.reorder(oldToNew);
01656 
01657     reorderPatchFields<volScalarField>(mesh, oldToNew);
01658     reorderPatchFields<volVectorField>(mesh, oldToNew);
01659     reorderPatchFields<volSphericalTensorField>(mesh, oldToNew);
01660     reorderPatchFields<volSymmTensorField>(mesh, oldToNew);
01661     reorderPatchFields<volTensorField>(mesh, oldToNew);
01662     reorderPatchFields<surfaceScalarField>(mesh, oldToNew);
01663     reorderPatchFields<surfaceVectorField>(mesh, oldToNew);
01664     reorderPatchFields<surfaceSphericalTensorField>(mesh, oldToNew);
01665     reorderPatchFields<surfaceSymmTensorField>(mesh, oldToNew);
01666     reorderPatchFields<surfaceTensorField>(mesh, oldToNew);
01667 
01668     return insertPatchI;
01669 }
01670 
01671 
01672 Foam::label Foam::meshRefinement::addMeshedPatch
01673 (
01674     const word& name,   
01675     const word& type
01676 )
01677 {
01678     label meshedI = findIndex(meshedPatches_, name);
01679 
01680     if (meshedI != -1)
01681     {
01682         // Already there. Get corresponding polypatch
01683         return mesh_.boundaryMesh().findPatchID(name);
01684     }
01685     else
01686     {
01687         // Add patch
01688         label patchI = addPatch(mesh_, name, type);
01689 
01690         // Store
01691         label sz = meshedPatches_.size();
01692         meshedPatches_.setSize(sz+1);
01693         meshedPatches_[sz] = name;
01694 
01695         return patchI;
01696     }
01697 }
01698 
01699 
01700 Foam::labelList Foam::meshRefinement::meshedPatches() const
01701 {
01702     labelList patchIDs(meshedPatches_.size());
01703     forAll(meshedPatches_, i)
01704     {
01705         patchIDs[i] = mesh_.boundaryMesh().findPatchID(meshedPatches_[i]);
01706 
01707         if (patchIDs[i] == -1)
01708         {
01709             FatalErrorIn("meshRefinement::meshedPatches() const")
01710                 << "Problem : did not find patch " << meshedPatches_[i]
01711                 << abort(FatalError);
01712         }
01713     }
01714 
01715     return patchIDs;
01716 }
01717 
01718 
01719 Foam::autoPtr<Foam::mapPolyMesh> Foam::meshRefinement::splitMeshRegions
01720 (
01721     const point& keepPoint
01722 )
01723 {
01724     // Determine connected regions. regionSplit is the labelList with the
01725     // region per cell.
01726     regionSplit cellRegion(mesh_);
01727 
01728     label regionI = -1;
01729 
01730     label cellI = mesh_.findCell(keepPoint);
01731 
01732     if (cellI != -1)
01733     {
01734         regionI = cellRegion[cellI];
01735     }
01736 
01737     reduce(regionI, maxOp<label>());
01738 
01739     if (regionI == -1)
01740     {
01741         FatalErrorIn
01742         (
01743             "meshRefinement::splitMeshRegions(const point&)"
01744         )   << "Point " << keepPoint
01745             << " is not inside the mesh." << nl
01746             << "Bounding box of the mesh:" << mesh_.globalData().bb()
01747             << exit(FatalError);
01748     }
01749 
01750     // Subset
01751     // ~~~~~~
01752 
01753     // Get cells to remove
01754     DynamicList<label> cellsToRemove(mesh_.nCells());
01755     forAll(cellRegion, cellI)
01756     {
01757         if (cellRegion[cellI] != regionI)
01758         {
01759             cellsToRemove.append(cellI);
01760         }
01761     }
01762     cellsToRemove.shrink();
01763 
01764     label nCellsToKeep = mesh_.nCells() - cellsToRemove.size();
01765     reduce(nCellsToKeep, sumOp<label>());
01766 
01767     Info<< "Keeping all cells in region " << regionI
01768         << " containing point " << keepPoint << endl
01769         << "Selected for keeping : "
01770         << nCellsToKeep
01771         << " cells." << endl;
01772 
01773 
01774     // Remove cells
01775     removeCells cellRemover(mesh_);
01776 
01777     labelList exposedFaces(cellRemover.getExposedFaces(cellsToRemove));
01778 
01779     if (exposedFaces.size())
01780     {
01781         FatalErrorIn
01782         (
01783             "meshRefinement::splitMeshRegions(const point&)"
01784         )   << "Removing non-reachable cells should only expose boundary faces"
01785             << nl
01786             << "ExposedFaces:" << exposedFaces << abort(FatalError);
01787     }
01788 
01789     return doRemoveCells
01790     (
01791         cellsToRemove,
01792         exposedFaces,
01793         labelList(exposedFaces.size(),-1),  // irrelevant since 0 size.
01794         cellRemover
01795     );
01796 }
01797 
01798 
01799 void Foam::meshRefinement::distribute(const mapDistributePolyMesh& map)
01800 {
01801     // mesh_ already distributed; distribute my member data
01802 
01803     // surfaceQueries_ ok.
01804 
01805     // refinement
01806     meshCutter_.distribute(map);
01807 
01808     // surfaceIndex is face data.
01809     map.distributeFaceData(surfaceIndex_);
01810 
01811     // maintainedFaces are indices of faces.
01812     forAll(userFaceData_, i)
01813     {
01814         map.distributeFaceData(userFaceData_[i].second());
01815     }
01816 
01817     // Redistribute surface and any fields on it.
01818     {
01819         Random rndGen(653213);
01820 
01821         // Get local mesh bounding box. Single box for now.
01822         List<treeBoundBox> meshBb(1);
01823         treeBoundBox& bb = meshBb[0];
01824         bb = boundBox(mesh_.points(), false);
01825         bb = bb.extend(rndGen, 1E-4);
01826 
01827         // Distribute all geometry (so refinementSurfaces and shellSurfaces)
01828         searchableSurfaces& geometry =
01829             const_cast<searchableSurfaces&>(surfaces_.geometry());
01830 
01831         forAll(geometry, i)
01832         {
01833             autoPtr<mapDistribute> faceMap;
01834             autoPtr<mapDistribute> pointMap;
01835             geometry[i].distribute
01836             (
01837                 meshBb,
01838                 false,          // do not keep outside triangles
01839                 faceMap,
01840                 pointMap
01841             );
01842 
01843             if (faceMap.valid())
01844             {
01845                 // (ab)use the instance() to signal current modification time
01846                 geometry[i].instance() = geometry[i].time().timeName();
01847             }
01848 
01849             faceMap.clear();
01850             pointMap.clear();
01851         }
01852     }
01853 }
01854 
01855 
01856 void Foam::meshRefinement::updateMesh
01857 (
01858     const mapPolyMesh& map,
01859     const labelList& changedFaces
01860 )
01861 {
01862     Map<label> dummyMap(0);
01863 
01864     updateMesh(map, changedFaces, dummyMap, dummyMap, dummyMap);
01865 }
01866 
01867 
01868 void Foam::meshRefinement::storeData
01869 (
01870     const labelList& pointsToStore,
01871     const labelList& facesToStore,
01872     const labelList& cellsToStore
01873 )
01874 {
01875     // For now only meshCutter has storable/retrievable data.
01876     meshCutter_.storeData
01877     (
01878         pointsToStore,
01879         facesToStore,
01880         cellsToStore
01881     );
01882 }
01883 
01884 
01885 void Foam::meshRefinement::updateMesh
01886 (
01887     const mapPolyMesh& map,
01888     const labelList& changedFaces,
01889     const Map<label>& pointsToRestore,
01890     const Map<label>& facesToRestore,
01891     const Map<label>& cellsToRestore
01892 )
01893 {
01894     // For now only meshCutter has storable/retrievable data.
01895 
01896     // Update numbering of cells/vertices.
01897     meshCutter_.updateMesh
01898     (
01899         map,
01900         pointsToRestore,
01901         facesToRestore,
01902         cellsToRestore
01903     );
01904 
01905     // Update surfaceIndex
01906     updateList(map.faceMap(), -1, surfaceIndex_);
01907 
01908     // Update cached intersection information
01909     updateIntersections(changedFaces);
01910 
01911     // Update maintained faces
01912     forAll(userFaceData_, i)
01913     {
01914         labelList& data = userFaceData_[i].second();
01915 
01916         if (userFaceData_[i].first() == KEEPALL)
01917         {
01918             // extend list with face-from-face data
01919             updateList(map.faceMap(), -1, data);
01920         }
01921         else if (userFaceData_[i].first() == MASTERONLY)
01922         {
01923             // keep master only
01924             labelList newFaceData(map.faceMap().size(), -1);
01925 
01926             forAll(newFaceData, faceI)
01927             {
01928                 label oldFaceI = map.faceMap()[faceI];
01929 
01930                 if (oldFaceI >= 0 && map.reverseFaceMap()[oldFaceI] == faceI)
01931                 {
01932                     newFaceData[faceI] = data[oldFaceI];
01933                 }
01934             }
01935             data.transfer(newFaceData);
01936         }
01937         else
01938         {
01939             // remove any face that has been refined i.e. referenced more than
01940             // once.
01941 
01942             // 1. Determine all old faces that get referenced more than once.
01943             // These get marked with -1 in reverseFaceMap
01944             labelList reverseFaceMap(map.reverseFaceMap());
01945 
01946             forAll(map.faceMap(), faceI)
01947             {
01948                 label oldFaceI = map.faceMap()[faceI];
01949 
01950                 if (oldFaceI >= 0)
01951                 {
01952                     if (reverseFaceMap[oldFaceI] != faceI)
01953                     {
01954                         // faceI is slave face. Mark old face.
01955                         reverseFaceMap[oldFaceI] = -1;
01956                     }
01957                 }
01958             }
01959 
01960             // 2. Map only faces with intact reverseFaceMap
01961             labelList newFaceData(map.faceMap().size(), -1);
01962             forAll(newFaceData, faceI)
01963             {
01964                 label oldFaceI = map.faceMap()[faceI];
01965 
01966                 if (oldFaceI >= 0)
01967                 {
01968                     if (reverseFaceMap[oldFaceI] == faceI)
01969                     {
01970                         newFaceData[faceI] = data[oldFaceI];
01971                     }
01972                 }
01973             }
01974             data.transfer(newFaceData);
01975         }
01976     }
01977 }
01978 
01979 
01980 bool Foam::meshRefinement::write() const
01981 {
01982     bool writeOk =
01983         mesh_.write()
01984      && meshCutter_.write()
01985      && surfaceIndex_.write();
01986 
01987 
01988     // Make sure that any distributed surfaces (so ones which probably have
01989     // been changed) get written as well.
01990     // Note: should ideally have some 'modified' flag to say whether it
01991     // has been changed or not.
01992     searchableSurfaces& geometry =
01993         const_cast<searchableSurfaces&>(surfaces_.geometry());
01994 
01995     forAll(geometry, i)
01996     {
01997         searchableSurface& s = geometry[i];
01998 
01999         // Check if instance() of surface is not constant or system.
02000         // Is good hint that surface is distributed.
02001         if
02002         (
02003             s.instance() != s.time().system()
02004          && s.instance() != s.time().caseSystem()
02005          && s.instance() != s.time().constant()
02006          && s.instance() != s.time().caseConstant()
02007         )
02008         {
02009             // Make sure it gets written to current time, not constant.
02010             s.instance() = s.time().timeName();
02011             writeOk = writeOk && s.write();
02012         }
02013     }
02014 
02015     return writeOk;
02016 }
02017 
02018 
02019 void Foam::meshRefinement::printMeshInfo(const bool debug, const string& msg)
02020  const
02021 {
02022     const globalMeshData& pData = mesh_.globalData();
02023 
02024     if (debug)
02025     {
02026         Pout<< msg.c_str()
02027             << " : cells(local):" << mesh_.nCells()
02028             << "  faces(local):" << mesh_.nFaces()
02029             << "  points(local):" << mesh_.nPoints()
02030             << endl;
02031     }
02032     else
02033     {
02034         Info<< msg.c_str()
02035             << " : cells:" << pData.nTotalCells()
02036             << "  faces:" << pData.nTotalFaces()
02037             << "  points:" << pData.nTotalPoints()
02038             << endl;
02039     }
02040 
02041 
02042     //if (debug)
02043     {
02044         const labelList& cellLevel = meshCutter_.cellLevel();
02045 
02046         labelList nCells(gMax(cellLevel)+1, 0);
02047 
02048         forAll(cellLevel, cellI)
02049         {
02050             nCells[cellLevel[cellI]]++;
02051         }
02052 
02053         Pstream::listCombineGather(nCells, plusEqOp<label>());
02054         Pstream::listCombineScatter(nCells);
02055 
02056         Info<< "Cells per refinement level:" << endl;
02057         forAll(nCells, levelI)
02058         {
02059             Info<< "    " << levelI << '\t' << nCells[levelI]
02060                 << endl;
02061         }
02062     }
02063 }
02064 
02065 
02066 //- Return either time().constant() or oldInstance
02067 Foam::word Foam::meshRefinement::timeName() const
02068 {
02069     if (overwrite_ && mesh_.time().timeIndex() == 0)
02070     {
02071         return oldInstance_;
02072     }
02073     else
02074     {
02075         return mesh_.time().timeName();
02076     }
02077 }
02078 
02079 
02080 void Foam::meshRefinement::dumpRefinementLevel() const
02081 {
02082     volScalarField volRefLevel
02083     (
02084         IOobject
02085         (
02086             "cellLevel",
02087             timeName(),
02088             mesh_,
02089             IOobject::NO_READ,
02090             IOobject::AUTO_WRITE,
02091             false
02092         ),
02093         mesh_,
02094         dimensionedScalar("zero", dimless, 0)
02095     );
02096 
02097     const labelList& cellLevel = meshCutter_.cellLevel();
02098 
02099     forAll(volRefLevel, cellI)
02100     {
02101         volRefLevel[cellI] = cellLevel[cellI];
02102     }
02103 
02104     volRefLevel.write();
02105 
02106 
02107     const pointMesh& pMesh = pointMesh::New(mesh_);
02108 
02109     pointScalarField pointRefLevel
02110     (
02111         IOobject
02112         (
02113             "pointLevel",
02114             timeName(),
02115             mesh_,
02116             IOobject::NO_READ,
02117             IOobject::NO_WRITE,
02118             false
02119         ),
02120         pMesh,
02121         dimensionedScalar("zero", dimless, 0)
02122     );
02123 
02124     const labelList& pointLevel = meshCutter_.pointLevel();
02125 
02126     forAll(pointRefLevel, pointI)
02127     {
02128         pointRefLevel[pointI] = pointLevel[pointI];
02129     }
02130 
02131     pointRefLevel.write();
02132 }
02133 
02134 
02135 void Foam::meshRefinement::dumpIntersections(const fileName& prefix) const
02136 {
02137     {
02138         const pointField& cellCentres = mesh_.cellCentres();
02139 
02140         OFstream str(prefix + "_edges.obj");
02141         label vertI = 0;
02142         Pout<< "meshRefinement::dumpIntersections :"
02143             << " Writing cellcentre-cellcentre intersections to file "
02144             << str.name() << endl;
02145 
02146 
02147         // Redo all intersections
02148         // ~~~~~~~~~~~~~~~~~~~~~~
02149 
02150         // Get boundary face centre and level. Coupled aware.
02151         labelList neiLevel(mesh_.nFaces()-mesh_.nInternalFaces());
02152         pointField neiCc(mesh_.nFaces()-mesh_.nInternalFaces());
02153         calcNeighbourData(neiLevel, neiCc);
02154 
02155         labelList intersectionFaces(intersectedFaces());
02156 
02157         // Collect segments we want to test for
02158         pointField start(intersectionFaces.size());
02159         pointField end(intersectionFaces.size());
02160 
02161         forAll(intersectionFaces, i)
02162         {
02163             label faceI = intersectionFaces[i];
02164             start[i] = cellCentres[mesh_.faceOwner()[faceI]];
02165 
02166             if (mesh_.isInternalFace(faceI))
02167             {
02168                 end[i] = cellCentres[mesh_.faceNeighbour()[faceI]];
02169             }
02170             else
02171             {
02172                 end[i] = neiCc[faceI-mesh_.nInternalFaces()];
02173             }
02174         }
02175 
02176         // Do tests in one go
02177         labelList surfaceHit;
02178         List<pointIndexHit> surfaceHitInfo;
02179         surfaces_.findAnyIntersection
02180         (
02181             start,
02182             end,
02183             surfaceHit,
02184             surfaceHitInfo
02185         );
02186 
02187         forAll(intersectionFaces, i)
02188         {
02189             if (surfaceHit[i] != -1)
02190             {
02191                 meshTools::writeOBJ(str, start[i]);
02192                 vertI++;
02193                 meshTools::writeOBJ(str, surfaceHitInfo[i].hitPoint());
02194                 vertI++;
02195                 meshTools::writeOBJ(str, end[i]);
02196                 vertI++;
02197                 str << "l " << vertI-2 << ' ' << vertI-1 << nl
02198                     << "l " << vertI-1 << ' ' << vertI << nl;
02199             }
02200         }
02201     }
02202 
02203     // Convert to vtk format
02204     string cmd
02205     (
02206         "objToVTK " + prefix + "_edges.obj " + prefix + "_edges.vtk > /dev/null"
02207     );
02208     system(cmd.c_str());
02209 
02210     Pout<< endl;
02211 }
02212 
02213 
02214 void Foam::meshRefinement::write
02215 (
02216     const label flag,
02217     const fileName& prefix
02218 ) const
02219 {
02220     if (flag & MESH)
02221     {
02222         write();
02223     }
02224     if (flag & SCALARLEVELS)
02225     {
02226         dumpRefinementLevel();
02227     }
02228     if (flag & OBJINTERSECTIONS && prefix.size())
02229     {
02230         dumpIntersections(prefix);
02231     }
02232 }
02233 
02234 
02235 // ************************************************************************* //
Copyright © 2000-2009 OpenCFD Ltd