subsetMesh.C
Go to the documentation of this file.
1 /*---------------------------------------------------------------------------*\
2  ========= |
3  \\ / F ield | OpenFOAM: The Open Source CFD Toolbox
4  \\ / O peration | Website: https://openfoam.org
5  \\ / A nd | Copyright (C) 2011-2026 OpenFOAM Foundation
6  \\/ M anipulation |
7 -------------------------------------------------------------------------------
8 License
9  This file is part of OpenFOAM.
10 
11  OpenFOAM is free software: you can redistribute it and/or modify it
12  under the terms of the GNU General Public License as published by
13  the Free Software Foundation, either version 3 of the License, or
14  (at your option) any later version.
15 
16  OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
17  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18  FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
19  for more details.
20 
21  You should have received a copy of the GNU General Public License
22  along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
23 
24 Application
25  subsetMesh
26 
27 Description
28  Selects a section of mesh based on a cellZone or cellSet.
29 
30  The utility sub-sets the mesh to choose only a part of interest.
31 
32  The mesh will subset all points, faces and cells needed to make a sub-mesh
33  but will not preserve attached boundary types.
34 
35 \*---------------------------------------------------------------------------*/
36 
37 #include "fvMeshSubset.H"
38 #include "argList.H"
39 #include "zoneGenerator.H"
40 #include "cellSet.H"
41 #include "IOobjectList.H"
42 #include "volFields.H"
43 #include "polyTopoChangeMap.H"
44 #include "hexRef8Data.H"
45 #include "systemDict.H"
46 
47 using namespace Foam;
48 
49 // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
50 
51 template<class GeoField>
52 void subsetFields
53 (
54  const fvMeshSubset& subsetter,
55  const typename GeoField::Mesh& mesh,
56  const wordList& fieldNames,
57  PtrList<GeoField>& subFields
58 )
59 {
60  forAll(fieldNames, i)
61  {
62  Info<< "Subsetting " << GeoField::typeName
63  << " " << fieldNames[i] << endl;
64 
65  GeoField fld
66  (
67  IOobject
68  (
69  fieldNames[i],
70  subsetter.baseMesh().time().name(),
71  subsetter.baseMesh(),
74  ),
75  mesh
76  );
77 
78  subFields.set(i, subsetter.interpolate(fld));
79  }
80 }
81 
82 
83 int main(int argc, char *argv[])
84 {
86  (
87  "select a mesh subset based on a cellSet"
88  );
89 
90  #include "addNoOverwriteOption.H"
91  #include "addMeshOption.H"
92  #include "addRegionOption.H"
93  #include "addDictOption.H"
95  (
96  "cellSet",
97  "cellSet",
98  "set of cells included in the sub-mesh"
99  );
101  (
102  "cellZone",
103  "cellZone",
104  "zone of cells included in the sub-mesh"
105  );
107  (
108  "patch",
109  "name",
110  "add exposed internal faces to specified patch instead of to "
111  "'oldInternalFaces'"
112  );
114  (
115  "resultTime",
116  "time",
117  "specify a time for the resulting mesh"
118  );
120  (
121  "noFields",
122  "do not update fields"
123  );
124 
127 
128  Foam::word meshRegionName = polyMesh::defaultRegion;
129  args.optionReadIfPresent("region", meshRegionName);
130 
132 
133  const word zoneName = args.optionLookupOrDefault
134  (
135  "cellZone",
136  word::null
137  );
138 
139  const word setName = args.optionLookupOrDefault
140  (
141  "cellSet",
142  word::null
143  );
144 
145  word meshInstance = mesh.pointsInstance();
146  word fieldsInstance = runTime.name();
147 
148  #include "setNoOverwrite.H"
149  const bool specifiedInstance = args.optionReadIfPresent
150  (
151  "resultTime",
152  fieldsInstance
153  );
154  if (specifiedInstance)
155  {
156  // Set both mesh and field to this time
157  meshInstance = fieldsInstance;
158  }
159  const bool fields = !args.optionFound("noFields");
160 
161 
162  // Create mesh subsetting engine
163  fvMeshSubset subsetter(mesh);
164 
165  label patchi = -1;
166 
167  if (args.optionFound("patch"))
168  {
169  const word patchName = args["patch"];
170 
171  patchi = mesh.poly().boundary().findIndex(patchName);
172 
173  if (patchi == -1)
174  {
176  << nl << "Valid patches are " << mesh.poly().boundary().names()
177  << exit(FatalError);
178  }
179 
180  Info<< "Adding exposed internal faces to patch " << patchName << endl
181  << endl;
182  }
183  else
184  {
185  Info<< "Adding exposed internal faces to a patch called"
186  << " \"oldInternalFaces\" (created if necessary)" << endl
187  << endl;
188  }
189 
190 
191  // Read hexRef8 data, if any
192  hexRef8Data refData
193  (
194  IOobject
195  (
196  "dummy",
199  mesh,
202  false
203  )
204  );
205 
206  if (zoneName != word::null)
207  {
208  Info<< indent << "Selecting cellZone " << zoneName << endl << endl;
209  subsetter.setLargeCellSubset
210  (
211  labelHashSet(mesh.cellZones()[zoneName]),
212  patchi,
213  true
214  );
215  }
216  else if (setName != word::null)
217  {
218  Info<< indent << "Selecting cellSet " << setName << endl << endl;
219  const cellSet currentSet(mesh, setName);
220  subsetter.setLargeCellSubset(currentSet, patchi, true);
221  }
222  else
223  {
224  const dictionary subsetDict
225  (
226  systemDict("subsetMeshDict", args, mesh)
227  );
228 
229  if (patchi == -1 && subsetDict.found("patch"))
230  {
231  const word patchName(subsetDict.lookup("patch"));
232  patchi = mesh.poly().boundary().findIndex(patchName);
233 
234  if (patchi == -1)
235  {
237  << nl << "Valid patches are "
238  << mesh.poly().boundary().names()
239  << exit(FatalError);
240  }
241  }
242 
243  labelHashSet subCells;
244 
245  if (subsetDict.isDict("zone"))
246  {
248  (
250  (
251  "zone",
253  mesh,
254  subsetDict.subDict("zone")
255  )
256  );
257 
258  Info<< indent << "Selecting cellZone " << zg->zoneName()
259  << " of type " << zg->type() << endl;
260 
261  subCells = zg->generate().cZone();
262  }
263  else
264  {
265  const word cellZoneName(subsetDict.lookup("zone"));
266 
267  Info<< indent << "Selecting cellZone " << cellZoneName << endl;
268 
269  subCells = mesh.cellZones()[cellZoneName];
270  }
271 
272  subsetter.setLargeCellSubset(subCells, patchi, true);
273  }
274 
275  if (fields)
276  {
277  const pointMesh& pMesh = pointMesh::New(mesh);
278 
279  IOobjectList objects(mesh, runTime.name());
280 
281  // Subset all the fields
282  #define SubsetTypeGeoFields(Type, GeoField, mesh) \
283  wordList Type##GeoField##Names \
284  ( \
285  objects.names(GeoField<Type>::typeName) \
286  ); \
287  PtrList<GeoField<Type>> Type##GeoField##s \
288  ( \
289  Type##GeoField##Names.size() \
290  ); \
291  subsetFields \
292  ( \
293  subsetter, \
294  mesh, \
295  Type##GeoField##Names, \
296  Type##GeoField##s \
297  );
298  FOR_ALL_FIELD_TYPES(SubsetTypeGeoFields, VolField, mesh);
299  FOR_ALL_FIELD_TYPES(SubsetTypeGeoFields, VolInternalField, mesh);
300  FOR_ALL_FIELD_TYPES(SubsetTypeGeoFields, SurfaceField, mesh);
301  FOR_ALL_FIELD_TYPES(SubsetTypeGeoFields, PointField, pMesh);
302 
303  // Set the instance
304  if (overwrite || specifiedInstance)
305  {
306  runTime.setTime(instant(fieldsInstance), 0);
307  subsetter.subMesh().setInstance(meshInstance);
308  }
309  else
310  {
311  runTime++;
312  }
313 
314  Info<< "Writing mesh to ";
315  subsetter.subMesh().write();
316  Info<< subsetter.subMesh().facesInstance()/mesh.meshDir() << endl;
317 
318  // Subsetting adds a 'subset' prefix. Rename the fields to remove this.
319  #define RenameTypeGeoFields(Type, GeoField) \
320  forAll(Type##GeoField##s, i) \
321  { \
322  Type##GeoField##s[i].rename(Type##GeoField##Names[i]); \
323  Type##GeoField##s[i].write(); \
324  }
325  FOR_ALL_FIELD_TYPES(RenameTypeGeoFields, VolField);
326  FOR_ALL_FIELD_TYPES(RenameTypeGeoFields, VolInternalField);
327  FOR_ALL_FIELD_TYPES(RenameTypeGeoFields, SurfaceField);
328  FOR_ALL_FIELD_TYPES(RenameTypeGeoFields, PointField);
329  }
330  else
331  {
332  // Set the instance
333  if (overwrite || specifiedInstance)
334  {
335  runTime.setTime(instant(fieldsInstance), 0);
336  subsetter.subMesh().setInstance(meshInstance);
337  }
338  else
339  {
340  runTime++;
341  }
342 
343  Info<< "Writing mesh to ";
344  subsetter.subMesh().write();
345  Info<< subsetter.subMesh().facesInstance()/mesh.meshDir() << endl;
346  }
347 
348 
349  // Map the hexRef8 data
351  (
352  mesh,
353  mesh.nPoints(), // nOldPoints,
354  mesh.nFaces(), // nOldFaces,
355  mesh.nCells(), // nOldCells,
356  labelList(subsetter.pointMap()),// pointMap,
357  List<objectMap>(0), // pointsFromPoints,
358  labelList(0), // faceMap,
359  List<objectMap>(0), // facesFromFaces,
360  labelList(subsetter.cellMap()), // cellMap,
361  List<objectMap>(0), // cellsFromCells,
362  labelList(0), // reversePointMap,
363  labelList(0), // reverseFaceMap,
364  labelList(0), // reverseCellMap,
365  labelHashSet(0), // flipFaceFlux,
366  labelListList(0), // patchPointMap,
367  labelList(0), // oldPatchSizes,
368  labelList(0), // oldPatchStarts,
369  labelList(0), // oldPatchNMeshPoints,
370  autoPtr<scalarField>() // oldCellVolumesPtr
371  );
372  refData.topoChange(map);
373  refData.write();
374 
375 
376  Info<< "End\n" << endl;
377 
378  return 0;
379 }
380 
381 
382 // ************************************************************************* //
#define forAll(list, i)
Loop across all elements in list.
Definition: UList.H:449
static pointMesh & New(const word &name, const polyMesh &mesh)
Construct and return the named DemandDrivenMeshObject.
Generic GeometricField class.
List of IOobjects with searching and retrieving facilities.
Definition: IOobjectList.H:53
IOobject defines the attributes of an object for which implicit objectRegistry management is supporte...
Definition: IOobject.H:99
A templated 1D list of pointers to objects of type <T>, where the size of the array is known and used...
Definition: PtrList.H:75
bool set(const label) const
Is element set.
Definition: PtrListI.H:62
static void addOption(const word &opt, const string &param="", const string &usage="")
Add to an option to validOptions with usage information.
Definition: argList.C:121
static void addNote(const string &)
Add extra notes for the usage information.
Definition: argList.C:152
static void addBoolOption(const word &opt, const string &usage="")
Add to a bool option to validOptions with usage information.
Definition: argList.C:111
bool optionFound(const word &opt) const
Return true if the named option is found.
Definition: argListI.H:114
bool optionReadIfPresent(const word &opt, T &) const
Read a value from the named option if present.
Definition: argListI.H:255
T optionLookupOrDefault(const word &opt, const T &deflt) const
Read a value from the named option if present.
Definition: argListI.H:294
An auto-pointer similar to the STL auto_ptr but with automatic casting to a reference to the type and...
Definition: autoPtr.H:51
A collection of cell labels.
Definition: cellSet.H:51
A list of keywords followed by any number of values (e.g. words and numbers) or sub-dictionaries.
Definition: dictionary.H:162
const word & name() const
Return const reference to name.
Post-processing mesh subset tool. Given the original mesh and the list of selected cells,...
Definition: fvMeshSubset.H:74
const fvMesh & baseMesh() const
Original mesh.
Definition: fvMeshSubset.H:222
const labelList & cellMap() const
Return cell map.
void setLargeCellSubset(const labelList &region, const label currentRegion, const label patchID=-1, const bool syncCouples=true)
Set the subset from all cells with region == currentRegion.
Definition: fvMeshSubset.C:916
const fvMesh & subMesh() const
Return reference to subset mesh.
const labelList & pointMap() const
Return point map.
static tmp< VolField< Type > > interpolate(const VolField< Type > &, const fvMesh &sMesh, const labelList &patchMap, const labelList &cellMap, const labelList &faceMap)
Map volume field.
const Time & time() const
Return the top-level database.
Definition: fvMesh.H:433
const word & name() const
Return reference to name.
Definition: fvMesh.H:447
const polyMesh & poly() const
Return reference to polyMesh.
Definition: fvMesh.H:456
Various for reading/decomposing/reconstructing/distributing refinement data.
Definition: hexRef8Data.H:58
An instant of time. Contains the time value and name.
Definition: instant.H:67
Mesh representing a set of points created from polyMesh.
Definition: pointMesh.H:52
label findIndex(const word &patchName) const
Find patch index given a name.
wordList names() const
Return the list of patch names.
const fileName & facesInstance() const
Return the current instance directory for faces.
Definition: polyMesh.C:1012
const cellZoneList & cellZones() const
Return cell zones.
Definition: polyMesh.H:438
static word defaultRegion
Return the default region name.
Definition: polyMesh.H:260
const polyBoundaryMesh & boundary() const
Return boundary mesh.
Definition: polyMesh.H:393
fileName meshDir() const
Return the local mesh directory (dbDir()/meshSubDir)
Definition: polyMesh.C:1000
const fileName & pointsInstance() const
Return the current instance directory for points.
Definition: polyMesh.C:1006
static word meshSubDir
Return the mesh sub-directory name (usually "polyMesh")
Definition: polyMesh.H:263
void setInstance(const fileName &)
Set the instance for mesh files.
Definition: polyMeshIO.C:102
Class containing mesh-to-mesh mapping information after a change in polyMesh topology.
label nCells() const
label nPoints() const
label nFaces() const
virtual bool write(const bool write=true) const
Write using setting from DB.
A class for handling words, derived from string.
Definition: word.H:63
static const word null
An empty word.
Definition: word.H:78
static autoPtr< zoneGenerator > New(const word &name, const polyMesh &mesh, const dictionary &dict)
Select constructed from name, mesh and dictionary.
Definition: zoneGenerator.C:66
Foam::fvMesh mesh(Foam::IOobject(regionName, runTime.name(), runTime, Foam::IOobject::MUST_READ), false)
#define FatalErrorInFunction
Report an error message using Foam::FatalError.
Definition: error.H:334
int main(int argc, char *argv[])
Definition: financialFoam.C:44
label patchi
static List< word > fieldNames
Definition: globalFoam.H:46
gmvFile<< "tracers "<< particles.size()<< nl;{ pointField positions(particles.size());label particlei=0;forAllConstIter(lagrangian::Cloud< passiveParticle >, particles, iter) { positions[particlei++]=iter().position(mesh);} for(i=0;i< pTraits< point >::nComponents;i++) { forAll(positions, particlei) { gmvFile<< component(positions[particlei], i)<< ' ';} gmvFile<< nl;}}forAll(lagrangianScalarNames, i){ const word &name=lagrangianScalarNames[i];IOField< scalar > fld(IOobject(name, runTime.name(), lagrangian::cloud::prefix, mesh, IOobject::MUST_READ, IOobject::NO_WRITE))
Info<< "Calculating turbulent flame speed field St\n"<< endl;volScalarField St(IOobject("St", runTime.name(), mesh, IOobject::NO_READ, IOobject::AUTO_WRITE), flameWrinkling->Xi() *Su);multivariateSurfaceInterpolationScheme< scalar >::fieldTable fields
Definition: createFields.H:234
Namespace for OpenFOAM.
errorManipArg< error, int > exit(error &err, const int errNo=1)
Definition: errorManip.H:124
List< label > labelList
A List of labels.
Definition: labelList.H:56
intWM_LABEL_SIZE_t label
A label is an int32_t or int64_t as specified by the pre-processor macro WM_LABEL_SIZE.
Definition: label.H:59
Ostream & endl(Ostream &os)
Add newline and flush stream.
Definition: Ostream.H:288
String typeName(const std::type_info &info)
Return the un-mangled name given the standard type info.
FOR_ALL_FIELD_TYPES(makeDimensionedPointFieldFunctions)
messageStream Info
List< labelList > labelListList
A List of labelList.
Definition: labelList.H:57
typename VolField< Type >::Internal VolInternalField
Definition: volFieldsFwd.H:59
HashSet< label, Hash< label > > labelHashSet
A HashSet with label keys.
Definition: HashSet.H:213
error FatalError
IOdictionary systemDict(const word &dictName, const argList &args, const objectRegistry &ob, const word &regionName=polyMesh::defaultRegion, const fileName &path=fileName::null)
Definition: systemDict.C:93
Ostream & indent(Ostream &os)
Indent stream.
Definition: Ostream.H:243
static const char nl
Definition: Ostream.H:297
objects
const bool overwrite
Definition: setNoOverwrite.H:1
Foam::argList args(argc, argv)