xref: /petsc/src/dm/impls/plex/plexfluent.c (revision 9371c9d470a9602b6d10a8bf50c9b2280a79e45a)
1 #define PETSC_DESIRE_FEATURE_TEST_MACROS /* for fileno() */
2 #define PETSCDM_DLL
3 #include <petsc/private/dmpleximpl.h> /*I   "petscdmplex.h"   I*/
4 
5 /*@C
6   DMPlexCreateFluentFromFile - Create a DMPlex mesh from a Fluent mesh file
7 
8 + comm        - The MPI communicator
9 . filename    - Name of the Fluent mesh file
10 - interpolate - Create faces and edges in the mesh
11 
12   Output Parameter:
13 . dm  - The DM object representing the mesh
14 
15   Level: beginner
16 
17 .seealso: `DMPlexCreateFromFile()`, `DMPlexCreateFluent()`, `DMPlexCreate()`
18 @*/
19 PetscErrorCode DMPlexCreateFluentFromFile(MPI_Comm comm, const char filename[], PetscBool interpolate, DM *dm) {
20   PetscViewer viewer;
21 
22   PetscFunctionBegin;
23   /* Create file viewer and build plex */
24   PetscCall(PetscViewerCreate(comm, &viewer));
25   PetscCall(PetscViewerSetType(viewer, PETSCVIEWERASCII));
26   PetscCall(PetscViewerFileSetMode(viewer, FILE_MODE_READ));
27   PetscCall(PetscViewerFileSetName(viewer, filename));
28   PetscCall(DMPlexCreateFluent(comm, viewer, interpolate, dm));
29   PetscCall(PetscViewerDestroy(&viewer));
30   PetscFunctionReturn(0);
31 }
32 
33 static PetscErrorCode DMPlexCreateFluent_ReadString(PetscViewer viewer, char *buffer, char delim) {
34   PetscInt ret, i = 0;
35 
36   PetscFunctionBegin;
37   do PetscCall(PetscViewerRead(viewer, &(buffer[i++]), 1, &ret, PETSC_CHAR));
38   while (ret > 0 && buffer[i - 1] != '\0' && buffer[i - 1] != delim);
39   if (!ret) buffer[i - 1] = '\0';
40   else buffer[i] = '\0';
41   PetscFunctionReturn(0);
42 }
43 
44 static PetscErrorCode DMPlexCreateFluent_ReadValues(PetscViewer viewer, void *data, PetscInt count, PetscDataType dtype, PetscBool binary) {
45   int      fdes = 0;
46   FILE    *file;
47   PetscInt i;
48 
49   PetscFunctionBegin;
50   if (binary) {
51     /* Extract raw file descriptor to read binary block */
52     PetscCall(PetscViewerASCIIGetPointer(viewer, &file));
53     fflush(file);
54     fdes = fileno(file);
55   }
56 
57   if (!binary && dtype == PETSC_INT) {
58     char         cbuf[256];
59     unsigned int ibuf;
60     int          snum;
61     /* Parse hexadecimal ascii integers */
62     for (i = 0; i < count; i++) {
63       PetscCall(PetscViewerRead(viewer, cbuf, 1, NULL, PETSC_STRING));
64       snum = sscanf(cbuf, "%x", &ibuf);
65       PetscCheck(snum == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
66       ((PetscInt *)data)[i] = (PetscInt)ibuf;
67     }
68   } else if (binary && dtype == PETSC_INT) {
69     /* Always read 32-bit ints and cast to PetscInt */
70     int *ibuf;
71     PetscCall(PetscMalloc1(count, &ibuf));
72     PetscCall(PetscBinaryRead(fdes, ibuf, count, NULL, PETSC_ENUM));
73     PetscCall(PetscByteSwap(ibuf, PETSC_ENUM, count));
74     for (i = 0; i < count; i++) ((PetscInt *)data)[i] = (PetscInt)(ibuf[i]);
75     PetscCall(PetscFree(ibuf));
76 
77   } else if (binary && dtype == PETSC_SCALAR) {
78     float *fbuf;
79     /* Always read 32-bit floats and cast to PetscScalar */
80     PetscCall(PetscMalloc1(count, &fbuf));
81     PetscCall(PetscBinaryRead(fdes, fbuf, count, NULL, PETSC_FLOAT));
82     PetscCall(PetscByteSwap(fbuf, PETSC_FLOAT, count));
83     for (i = 0; i < count; i++) ((PetscScalar *)data)[i] = (PetscScalar)(fbuf[i]);
84     PetscCall(PetscFree(fbuf));
85   } else {
86     PetscCall(PetscViewerASCIIRead(viewer, data, count, NULL, dtype));
87   }
88   PetscFunctionReturn(0);
89 }
90 
91 static PetscErrorCode DMPlexCreateFluent_ReadSection(PetscViewer viewer, FluentSection *s) {
92   char buffer[PETSC_MAX_PATH_LEN];
93   int  snum;
94 
95   PetscFunctionBegin;
96   /* Fast-forward to next section and derive its index */
97   PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, '('));
98   PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ' '));
99   snum = sscanf(buffer, "%d", &(s->index));
100   /* If we can't match an index return -1 to signal end-of-file */
101   if (snum < 1) {
102     s->index = -1;
103     PetscFunctionReturn(0);
104   }
105 
106   if (s->index == 0) { /* Comment */
107     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
108 
109   } else if (s->index == 2) { /* Dimension */
110     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
111     snum = sscanf(buffer, "%d", &(s->nd));
112     PetscCheck(snum == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
113 
114   } else if (s->index == 10 || s->index == 2010) { /* Vertices */
115     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
116     snum = sscanf(buffer, "(%x %x %x %d %d)", &(s->zoneID), &(s->first), &(s->last), &(s->type), &(s->nd));
117     PetscCheck(snum == 5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
118     if (s->zoneID > 0) {
119       PetscInt numCoords = s->last - s->first + 1;
120       PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, '('));
121       PetscCall(PetscMalloc1(s->nd * numCoords, (PetscScalar **)&s->data));
122       PetscCall(DMPlexCreateFluent_ReadValues(viewer, s->data, s->nd * numCoords, PETSC_SCALAR, s->index == 2010 ? PETSC_TRUE : PETSC_FALSE));
123       PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
124     }
125     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
126 
127   } else if (s->index == 12 || s->index == 2012) { /* Cells */
128     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
129     snum = sscanf(buffer, "(%x", &(s->zoneID));
130     PetscCheck(snum == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
131     if (s->zoneID == 0) { /* Header section */
132       snum = sscanf(buffer, "(%x %x %x %d)", &(s->zoneID), &(s->first), &(s->last), &(s->nd));
133       PetscCheck(snum == 4, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
134     } else { /* Data section */
135       snum = sscanf(buffer, "(%x %x %x %d %d)", &(s->zoneID), &(s->first), &(s->last), &(s->type), &(s->nd));
136       PetscCheck(snum == 5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
137       if (s->nd == 0) {
138         /* Read cell type definitions for mixed cells */
139         PetscInt numCells = s->last - s->first + 1;
140         PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, '('));
141         PetscCall(PetscMalloc1(numCells, (PetscInt **)&s->data));
142         PetscCall(DMPlexCreateFluent_ReadValues(viewer, s->data, numCells, PETSC_INT, s->index == 2012 ? PETSC_TRUE : PETSC_FALSE));
143         PetscCall(PetscFree(s->data));
144         PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
145       }
146     }
147     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
148 
149   } else if (s->index == 13 || s->index == 2013) { /* Faces */
150     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
151     snum = sscanf(buffer, "(%x", &(s->zoneID));
152     PetscCheck(snum == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
153     if (s->zoneID == 0) { /* Header section */
154       snum = sscanf(buffer, "(%x %x %x %d)", &(s->zoneID), &(s->first), &(s->last), &(s->nd));
155       PetscCheck(snum == 4, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
156     } else { /* Data section */
157       PetscInt f, numEntries, numFaces;
158       snum = sscanf(buffer, "(%x %x %x %d %d)", &(s->zoneID), &(s->first), &(s->last), &(s->type), &(s->nd));
159       PetscCheck(snum == 5, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "File is not a valid Fluent file");
160       PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, '('));
161       switch (s->nd) {
162       case 0: numEntries = PETSC_DETERMINE; break;
163       case 2: numEntries = 2 + 2; break; /* linear */
164       case 3: numEntries = 2 + 3; break; /* triangular */
165       case 4: numEntries = 2 + 4; break; /* quadrilateral */
166       default: SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown face type in Fluent file");
167       }
168       numFaces = s->last - s->first + 1;
169       if (numEntries != PETSC_DETERMINE) {
170         /* Allocate space only if we already know the size of the block */
171         PetscCall(PetscMalloc1(numEntries * numFaces, (PetscInt **)&s->data));
172       }
173       for (f = 0; f < numFaces; f++) {
174         if (s->nd == 0) {
175           /* Determine the size of the block for "mixed" facets */
176           PetscInt numFaceVert = 0;
177           PetscCall(DMPlexCreateFluent_ReadValues(viewer, &numFaceVert, 1, PETSC_INT, s->index == 2013 ? PETSC_TRUE : PETSC_FALSE));
178           if (numEntries == PETSC_DETERMINE) {
179             numEntries = numFaceVert + 2;
180             PetscCall(PetscMalloc1(numEntries * numFaces, (PetscInt **)&s->data));
181           } else {
182             PetscCheck(numEntries == numFaceVert + 2, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No support for mixed faces in Fluent files");
183           }
184         }
185         PetscCall(DMPlexCreateFluent_ReadValues(viewer, &(((PetscInt *)s->data)[f * numEntries]), numEntries, PETSC_INT, s->index == 2013 ? PETSC_TRUE : PETSC_FALSE));
186       }
187       s->nd = numEntries - 2;
188       PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
189     }
190     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, ')'));
191 
192   } else { /* Unknown section type */
193     PetscInt depth = 1;
194     do {
195       /* Match parentheses when parsing unknown sections */
196       do PetscCall(PetscViewerRead(viewer, &(buffer[0]), 1, NULL, PETSC_CHAR));
197       while (buffer[0] != '(' && buffer[0] != ')');
198       if (buffer[0] == '(') depth++;
199       if (buffer[0] == ')') depth--;
200     } while (depth > 0);
201     PetscCall(DMPlexCreateFluent_ReadString(viewer, buffer, '\n'));
202   }
203   PetscFunctionReturn(0);
204 }
205 
206 /*@C
207   DMPlexCreateFluent - Create a DMPlex mesh from a Fluent mesh file.
208 
209   Collective
210 
211   Input Parameters:
212 + comm  - The MPI communicator
213 . viewer - The Viewer associated with a Fluent mesh file
214 - interpolate - Create faces and edges in the mesh
215 
216   Output Parameter:
217 . dm  - The DM object representing the mesh
218 
219   Note: http://aerojet.engr.ucdavis.edu/fluenthelp/html/ug/node1490.htm
220 
221   Level: beginner
222 
223 .seealso: `DMPLEX`, `DMCreate()`
224 @*/
225 PetscErrorCode DMPlexCreateFluent(MPI_Comm comm, PetscViewer viewer, PetscBool interpolate, DM *dm) {
226   PetscMPIInt  rank;
227   PetscInt     c, v, dim = PETSC_DETERMINE, numCells = 0, numVertices = 0, numCellVertices = PETSC_DETERMINE;
228   PetscInt     numFaces = PETSC_DETERMINE, f, numFaceEntries = PETSC_DETERMINE, numFaceVertices = PETSC_DETERMINE;
229   PetscInt    *faces = NULL, *cellVertices = NULL, *faceZoneIDs = NULL;
230   DMLabel      faceSets = NULL;
231   PetscInt     d, coordSize;
232   PetscScalar *coords, *coordsIn = NULL;
233   PetscSection coordSection;
234   Vec          coordinates;
235 
236   PetscFunctionBegin;
237   PetscCallMPI(MPI_Comm_rank(comm, &rank));
238 
239   if (rank == 0) {
240     FluentSection s;
241     do {
242       PetscCall(DMPlexCreateFluent_ReadSection(viewer, &s));
243       if (s.index == 2) { /* Dimension */
244         dim = s.nd;
245 
246       } else if (s.index == 10 || s.index == 2010) { /* Vertices */
247         if (s.zoneID == 0) numVertices = s.last;
248         else {
249           PetscCheck(!coordsIn, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Currently no support for multiple coordinate sets in Fluent files");
250           coordsIn = (PetscScalar *)s.data;
251         }
252 
253       } else if (s.index == 12 || s.index == 2012) { /* Cells */
254         if (s.zoneID == 0) numCells = s.last;
255         else {
256           switch (s.nd) {
257           case 0: numCellVertices = PETSC_DETERMINE; break;
258           case 1: numCellVertices = 3; break; /* triangular */
259           case 2: numCellVertices = 4; break; /* tetrahedral */
260           case 3: numCellVertices = 4; break; /* quadrilateral */
261           case 4: numCellVertices = 8; break; /* hexahedral */
262           case 5: numCellVertices = 5; break; /* pyramid */
263           case 6: numCellVertices = 6; break; /* wedge */
264           default: numCellVertices = PETSC_DETERMINE;
265           }
266         }
267 
268       } else if (s.index == 13 || s.index == 2013) { /* Facets */
269         if (s.zoneID == 0) {                         /* Header section */
270           numFaces = (PetscInt)(s.last - s.first + 1);
271           if (s.nd == 0 || s.nd == 5) numFaceVertices = PETSC_DETERMINE;
272           else numFaceVertices = s.nd;
273         } else { /* Data section */
274           unsigned int z;
275 
276           PetscCheck(numFaceVertices == PETSC_DETERMINE || s.nd == numFaceVertices, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Mixed facets in Fluent files are not supported");
277           PetscCheck(numFaces >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "No header section for facets in Fluent file");
278           if (numFaceVertices == PETSC_DETERMINE) numFaceVertices = s.nd;
279           numFaceEntries = numFaceVertices + 2;
280           if (!faces) PetscCall(PetscMalloc1(numFaces * numFaceEntries, &faces));
281           if (!faceZoneIDs) PetscCall(PetscMalloc1(numFaces, &faceZoneIDs));
282           PetscCall(PetscMemcpy(&faces[(s.first - 1) * numFaceEntries], s.data, (s.last - s.first + 1) * numFaceEntries * sizeof(PetscInt)));
283           /* Record the zoneID for each face set */
284           for (z = s.first - 1; z < s.last; z++) faceZoneIDs[z] = s.zoneID;
285           PetscCall(PetscFree(s.data));
286         }
287       }
288     } while (s.index >= 0);
289   }
290   PetscCallMPI(MPI_Bcast(&dim, 1, MPIU_INT, 0, comm));
291   PetscCheck(dim >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Fluent file does not include dimension");
292 
293   /* Allocate cell-vertex mesh */
294   PetscCall(DMCreate(comm, dm));
295   PetscCall(DMSetType(*dm, DMPLEX));
296   PetscCall(DMSetDimension(*dm, dim));
297   PetscCall(DMPlexSetChart(*dm, 0, numCells + numVertices));
298   if (rank == 0) {
299     PetscCheck(numCells >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown number of cells in Fluent file");
300     /* If no cell type was given we assume simplices */
301     if (numCellVertices == PETSC_DETERMINE) numCellVertices = numFaceVertices + 1;
302     for (c = 0; c < numCells; ++c) PetscCall(DMPlexSetConeSize(*dm, c, numCellVertices));
303   }
304   PetscCall(DMSetUp(*dm));
305 
306   if (rank == 0 && faces) {
307     /* Derive cell-vertex list from face-vertex and face-cell maps */
308     PetscCall(PetscMalloc1(numCells * numCellVertices, &cellVertices));
309     for (c = 0; c < numCells * numCellVertices; c++) cellVertices[c] = -1;
310     for (f = 0; f < numFaces; f++) {
311       PetscInt       *cell;
312       const PetscInt  cl   = faces[f * numFaceEntries + numFaceVertices];
313       const PetscInt  cr   = faces[f * numFaceEntries + numFaceVertices + 1];
314       const PetscInt *face = &(faces[f * numFaceEntries]);
315 
316       if (cl > 0) {
317         cell = &(cellVertices[(cl - 1) * numCellVertices]);
318         for (v = 0; v < numFaceVertices; v++) {
319           PetscBool found = PETSC_FALSE;
320           for (c = 0; c < numCellVertices; c++) {
321             if (cell[c] < 0) break;
322             if (cell[c] == face[v] - 1 + numCells) {
323               found = PETSC_TRUE;
324               break;
325             }
326           }
327           if (!found) cell[c] = face[v] - 1 + numCells;
328         }
329       }
330       if (cr > 0) {
331         cell = &(cellVertices[(cr - 1) * numCellVertices]);
332         for (v = 0; v < numFaceVertices; v++) {
333           PetscBool found = PETSC_FALSE;
334           for (c = 0; c < numCellVertices; c++) {
335             if (cell[c] < 0) break;
336             if (cell[c] == face[v] - 1 + numCells) {
337               found = PETSC_TRUE;
338               break;
339             }
340           }
341           if (!found) cell[c] = face[v] - 1 + numCells;
342         }
343       }
344     }
345     for (c = 0; c < numCells; c++) { PetscCall(DMPlexSetCone(*dm, c, &(cellVertices[c * numCellVertices]))); }
346   }
347   PetscCall(DMPlexSymmetrize(*dm));
348   PetscCall(DMPlexStratify(*dm));
349   if (interpolate) {
350     DM idm;
351 
352     PetscCall(DMPlexInterpolate(*dm, &idm));
353     PetscCall(DMDestroy(dm));
354     *dm = idm;
355   }
356 
357   if (rank == 0 && faces) {
358     PetscInt        fi, joinSize, meetSize, *fverts, cells[2];
359     const PetscInt *join, *meet;
360     PetscCall(PetscMalloc1(numFaceVertices, &fverts));
361     /* Mark facets by finding the full join of all adjacent vertices */
362     for (f = 0; f < numFaces; f++) {
363       const PetscInt cl = faces[f * numFaceEntries + numFaceVertices] - 1;
364       const PetscInt cr = faces[f * numFaceEntries + numFaceVertices + 1] - 1;
365       if (cl > 0 && cr > 0) {
366         /* If we know both adjoining cells we can use a single-level meet */
367         cells[0] = cl;
368         cells[1] = cr;
369         PetscCall(DMPlexGetMeet(*dm, 2, cells, &meetSize, &meet));
370         PetscCheck(meetSize == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not determine Plex facet for Fluent face %" PetscInt_FMT, f);
371         PetscCall(DMSetLabelValue_Fast(*dm, &faceSets, "Face Sets", meet[0], faceZoneIDs[f]));
372         PetscCall(DMPlexRestoreMeet(*dm, numFaceVertices, fverts, &meetSize, &meet));
373       } else {
374         for (fi = 0; fi < numFaceVertices; fi++) fverts[fi] = faces[f * numFaceEntries + fi] + numCells - 1;
375         PetscCall(DMPlexGetFullJoin(*dm, numFaceVertices, fverts, &joinSize, &join));
376         PetscCheck(joinSize == 1, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Could not determine Plex facet for Fluent face %" PetscInt_FMT, f);
377         PetscCall(DMSetLabelValue_Fast(*dm, &faceSets, "Face Sets", join[0], faceZoneIDs[f]));
378         PetscCall(DMPlexRestoreJoin(*dm, numFaceVertices, fverts, &joinSize, &join));
379       }
380     }
381     PetscCall(PetscFree(fverts));
382   }
383 
384   { /* Create Face Sets label at all processes */
385     enum {
386       n = 1
387     };
388     PetscBool flag[n];
389 
390     flag[0] = faceSets ? PETSC_TRUE : PETSC_FALSE;
391     PetscCallMPI(MPI_Bcast(flag, n, MPIU_BOOL, 0, comm));
392     if (flag[0]) PetscCall(DMCreateLabel(*dm, "Face Sets"));
393   }
394 
395   /* Read coordinates */
396   PetscCall(DMGetCoordinateSection(*dm, &coordSection));
397   PetscCall(PetscSectionSetNumFields(coordSection, 1));
398   PetscCall(PetscSectionSetFieldComponents(coordSection, 0, dim));
399   PetscCall(PetscSectionSetChart(coordSection, numCells, numCells + numVertices));
400   for (v = numCells; v < numCells + numVertices; ++v) {
401     PetscCall(PetscSectionSetDof(coordSection, v, dim));
402     PetscCall(PetscSectionSetFieldDof(coordSection, v, 0, dim));
403   }
404   PetscCall(PetscSectionSetUp(coordSection));
405   PetscCall(PetscSectionGetStorageSize(coordSection, &coordSize));
406   PetscCall(VecCreate(PETSC_COMM_SELF, &coordinates));
407   PetscCall(PetscObjectSetName((PetscObject)coordinates, "coordinates"));
408   PetscCall(VecSetSizes(coordinates, coordSize, PETSC_DETERMINE));
409   PetscCall(VecSetType(coordinates, VECSTANDARD));
410   PetscCall(VecGetArray(coordinates, &coords));
411   if (rank == 0 && coordsIn) {
412     for (v = 0; v < numVertices; ++v) {
413       for (d = 0; d < dim; ++d) { coords[v * dim + d] = coordsIn[v * dim + d]; }
414     }
415   }
416   PetscCall(VecRestoreArray(coordinates, &coords));
417   PetscCall(DMSetCoordinatesLocal(*dm, coordinates));
418   PetscCall(VecDestroy(&coordinates));
419 
420   if (rank == 0) {
421     PetscCall(PetscFree(cellVertices));
422     PetscCall(PetscFree(faces));
423     PetscCall(PetscFree(faceZoneIDs));
424     PetscCall(PetscFree(coordsIn));
425   }
426   PetscFunctionReturn(0);
427 }
428