xref: /petsc/src/binding/petsc4py/test/test_dmplex.py (revision 8ebe3e4e9e00d86ece2e9fcd0cc84910b0ad437c)
1import petsc4py
2from petsc4py import PETSc
3import unittest
4import os
5import filecmp
6import numpy as np
7
8# --------------------------------------------------------------------
9
10ERR_ARG_OUTOFRANGE = 63
11
12class BaseTestPlex(object):
13
14    COMM = PETSc.COMM_WORLD
15    DIM = 1
16    CELLS = [[0, 1], [1, 2]]
17    COORDS = [[0.], [0.5], [1.]]
18    COMP = 1
19    DOFS = [1, 0]
20
21    def setUp(self):
22        self.plex = PETSc.DMPlex().createFromCellList(self.DIM,
23                                                      self.CELLS,
24                                                      self.COORDS,
25                                                      comm=self.COMM)
26
27    def tearDown(self):
28        self.plex.destroy()
29        self.plex = None
30
31    def testTopology(self):
32        rank = self.COMM.rank
33        dim = self.plex.getDimension()
34        pStart, pEnd = self.plex.getChart()
35        cStart, cEnd = self.plex.getHeightStratum(0)
36        vStart, vEnd = self.plex.getDepthStratum(0)
37        numDepths = self.plex.getLabelSize("depth")
38        coords_raw = self.plex.getCoordinates().getArray()
39        coords = np.reshape(coords_raw, (vEnd - vStart, dim))
40        self.assertEqual(dim, self.DIM)
41        self.assertEqual(numDepths, self.DIM+1)
42        if rank == 0 and self.CELLS is not None:
43            self.assertEqual(cEnd-cStart, len(self.CELLS))
44        if rank == 0 and self.COORDS is not None:
45            self.assertEqual(vEnd-vStart, len(self.COORDS))
46            self.assertTrue((coords == self.COORDS).all())
47
48    def testClosure(self):
49        pStart, pEnd = self.plex.getChart()
50        for p in range(pStart, pEnd):
51            closure = self.plex.getTransitiveClosure(p)[0]
52            for c in closure:
53                cone = self.plex.getCone(c)
54                self.assertEqual(self.plex.getConeSize(c), len(cone))
55                for i in cone:
56                    self.assertIn(i, closure)
57            star = self.plex.getTransitiveClosure(p, useCone=False)[0]
58            for s in star:
59                support = self.plex.getSupport(s)
60                self.assertEqual(self.plex.getSupportSize(s), len(support))
61                for i in support:
62                    self.assertIn(i, star)
63
64    def testAdjacency(self):
65        PETSc.DMPlex.setAdjacencyUseAnchors(self.plex, False)
66        flag = PETSc.DMPlex.getAdjacencyUseAnchors(self.plex)
67        self.assertFalse(flag)
68        PETSc.DMPlex.setAdjacencyUseAnchors(self.plex, True)
69        flag = PETSc.DMPlex.getAdjacencyUseAnchors(self.plex)
70        self.assertTrue(flag)
71        PETSc.DMPlex.setBasicAdjacency(self.plex, False, False)
72        flagA, flagB = PETSc.DMPlex.getBasicAdjacency(self.plex)
73        self.assertFalse(flagA)
74        self.assertFalse(flagB)
75        PETSc.DMPlex.setBasicAdjacency(self.plex, True, True)
76        flagA, flagB = PETSc.DMPlex.getBasicAdjacency(self.plex)
77        self.assertTrue(flagA)
78        self.assertTrue(flagB)
79        pStart, pEnd = self.plex.getChart()
80        for p in range(pStart, pEnd):
81            adjacency = self.plex.getAdjacency(p)
82            self.assertTrue(p in adjacency)
83            self.assertTrue(len(adjacency) > 1)
84
85    def testSectionDofs(self):
86        self.plex.setNumFields(1)
87        section = self.plex.createSection([self.COMP], [self.DOFS])
88        size = section.getStorageSize()
89        entity_dofs = [self.plex.getStratumSize("depth", d) *
90                       self.DOFS[d] for d in range(self.DIM+1)]
91        self.assertEqual(sum(entity_dofs), size)
92
93    def testSectionClosure(self):
94        section = self.plex.createSection([self.COMP], [self.DOFS])
95        self.plex.setSection(section)
96        vec = self.plex.createLocalVec()
97        pStart, pEnd = self.plex.getChart()
98        for p in range(pStart, pEnd):
99            for i in range(section.getDof(p)):
100                off = section.getOffset(p)
101                vec.setValue(off+i, p)
102
103        for p in range(pStart, pEnd):
104            point_closure = self.plex.getTransitiveClosure(p)[0]
105            dof_closure = self.plex.vecGetClosure(section, vec, p)
106            for p in dof_closure:
107                self.assertIn(p, point_closure)
108
109    def testBoundaryLabel(self):
110        pStart, pEnd = self.plex.getChart()
111        if (pEnd - pStart == 0): return
112
113        self.assertFalse(self.plex.hasLabel("boundary"))
114        self.plex.markBoundaryFaces("boundary")
115        self.assertTrue(self.plex.hasLabel("boundary"))
116
117        faces = self.plex.getStratumIS("boundary", 1)
118        for f in faces.getIndices():
119            points, orient = self.plex.getTransitiveClosure(f, useCone=True)
120            for p in points:
121                self.plex.setLabelValue("boundary", p, 1)
122
123        for p in range(pStart, pEnd):
124            if self.plex.getLabelValue("boundary", p) != 1:
125                self.plex.setLabelValue("boundary", p, 2)
126
127        numBoundary = self.plex.getStratumSize("boundary", 1)
128        numInterior = self.plex.getStratumSize("boundary", 2)
129        self.assertNotEqual(numBoundary, pEnd - pStart)
130        self.assertNotEqual(numInterior, pEnd - pStart)
131        self.assertEqual(numBoundary + numInterior, pEnd - pStart)
132
133    def testMetric(self):
134        if self.DIM == 1: return
135        self.plex.distribute()
136        if self.CELLS is None and not self.plex.isSimplex(): return
137        self.plex.orient()
138
139        h_min = 1.0e-30
140        h_max = 1.0e+30
141        a_max = 1.0e+10
142        target = 10.0
143        p = 1.0
144        beta = 1.3
145        self.plex.metricSetIsotropic(False)
146        self.plex.metricSetRestrictAnisotropyFirst(False)
147        self.plex.metricSetNoInsertion(False)
148        self.plex.metricSetNoSwapping(False)
149        self.plex.metricSetNoMovement(False)
150        self.plex.metricSetVerbosity(-1)
151        self.plex.metricSetNumIterations(3)
152        self.plex.metricSetMinimumMagnitude(h_min)
153        self.plex.metricSetMaximumMagnitude(h_max)
154        self.plex.metricSetMaximumAnisotropy(a_max)
155        self.plex.metricSetTargetComplexity(target)
156        self.plex.metricSetNormalizationOrder(p)
157        self.plex.metricSetGradationFactor(beta)
158
159        self.assertFalse(self.plex.metricIsIsotropic())
160        self.assertFalse(self.plex.metricRestrictAnisotropyFirst())
161        self.assertFalse(self.plex.metricNoInsertion())
162        self.assertFalse(self.plex.metricNoSwapping())
163        self.assertFalse(self.plex.metricNoMovement())
164        assert self.plex.metricGetVerbosity() == -1
165        assert self.plex.metricGetNumIterations() == 3
166        assert np.isclose(self.plex.metricGetMinimumMagnitude(), h_min)
167        assert np.isclose(self.plex.metricGetMaximumMagnitude(), h_max)
168        assert np.isclose(self.plex.metricGetMaximumAnisotropy(), a_max)
169        assert np.isclose(self.plex.metricGetTargetComplexity(), target)
170        assert np.isclose(self.plex.metricGetNormalizationOrder(), p)
171        assert np.isclose(self.plex.metricGetGradationFactor(), beta)
172
173        metric1 = self.plex.metricCreateUniform(1.0)
174        metric2 = self.plex.metricCreateUniform(2.0)
175        metric = self.plex.metricAverage2(metric1, metric2)
176        metric2.array[:] *= 0.75
177        assert np.allclose(metric.array, metric2.array)
178        metric = self.plex.metricIntersection2(metric1, metric2)
179        assert np.allclose(metric.array, metric1.array)
180        metric = self.plex.metricEnforceSPD(metric)
181        assert np.allclose(metric.array, metric1.array)
182        nMetric = self.plex.metricNormalize(metric, restrictSizes=False, restrictAnisotropy=False)
183        metric.scale(pow(target, 2.0/self.DIM))
184        assert np.allclose(metric.array, nMetric.array)
185
186    def testAdapt(self):
187        if self.DIM == 1: return
188        self.plex.orient()
189        plex = self.plex.refine()
190        plex.distribute()
191        if self.CELLS is None and not plex.isSimplex(): return
192        if sum(self.DOFS) > 1: return
193        metric = plex.metricCreateUniform(9.0)
194        try:
195            newplex = plex.adaptMetric(metric,"")
196        except PETSc.Error as exc:
197            if exc.ierr != ERR_ARG_OUTOFRANGE: raise
198
199
200# --------------------------------------------------------------------
201
202class BaseTestPlex_2D(BaseTestPlex):
203    DIM = 2
204    CELLS = [[0, 1, 3], [1, 3, 4], [1, 2, 4], [2, 4, 5],
205             [3, 4, 6], [4, 6, 7], [4, 5, 7], [5, 7, 8]]
206    COORDS = [[0.0, 0.0], [0.5, 0.0], [1.0, 0.0],
207              [0.0, 0.5], [0.5, 0.5], [1.0, 0.5],
208              [0.0, 1.0], [0.5, 1.0], [1.0, 1.0]]
209    DOFS = [1, 0, 0]
210
211class BaseTestPlex_3D(BaseTestPlex):
212    DIM = 3
213    CELLS = [[0, 2, 3, 7], [0, 2, 6, 7], [0, 4, 6, 7],
214             [0, 1, 3, 7], [0, 1, 5, 7], [0, 4, 5, 7]]
215    COORDS = [[0., 0., 0.], [1., 0., 0.], [0., 1., 0.], [1., 1., 0.],
216              [0., 0., 1.], [1., 0., 1.], [0., 1., 1.], [1., 1., 1.]]
217    DOFS = [1, 0, 0, 0]
218
219# --------------------------------------------------------------------
220
221class TestPlex_1D(BaseTestPlex, unittest.TestCase):
222    pass
223
224class TestPlex_2D(BaseTestPlex_2D, unittest.TestCase):
225    pass
226
227class TestPlex_3D(BaseTestPlex_3D, unittest.TestCase):
228    pass
229
230class TestPlex_2D_P3(BaseTestPlex_2D, unittest.TestCase):
231    DOFS = [1, 2, 1]
232
233class TestPlex_3D_P3(BaseTestPlex_3D, unittest.TestCase):
234    DOFS = [1, 2, 1, 0]
235
236class TestPlex_3D_P4(BaseTestPlex_3D, unittest.TestCase):
237    DOFS = [1, 3, 3, 1]
238
239class TestPlex_2D_BoxTensor(BaseTestPlex_2D, unittest.TestCase):
240    CELLS = None
241    COORDS = None
242    def setUp(self):
243        self.plex = PETSc.DMPlex().createBoxMesh([3,3], simplex=False)
244
245class TestPlex_3D_BoxTensor(BaseTestPlex_3D, unittest.TestCase):
246    CELLS = None
247    COORDS = None
248    def setUp(self):
249        self.plex = PETSc.DMPlex().createBoxMesh([3,3,3], simplex=False)
250
251try:
252    raise PETSc.Error
253    PETSc.DMPlex().createBoxMesh([2,2], simplex=True, comm=PETSc.COMM_SELF).destroy()
254except PETSc.Error:
255    pass
256else:
257    class TestPlex_2D_Box(BaseTestPlex_2D, unittest.TestCase):
258        CELLS = None
259        COORDS = None
260        def setUp(self):
261            self.plex = PETSc.DMPlex().createBoxMesh([1,1], simplex=True)
262
263    class TestPlex_2D_Boundary(BaseTestPlex_2D, unittest.TestCase):
264        CELLS = None
265        COORDS = None
266        def setUp(self):
267            boundary = PETSc.DMPlex().create(self.COMM)
268            boundary.createSquareBoundary([0., 0.], [1., 1.], [2, 2])
269            boundary.setDimension(self.DIM-1)
270            self.plex = PETSc.DMPlex().generate(boundary)
271
272    class TestPlex_3D_Box(BaseTestPlex_3D, unittest.TestCase):
273        CELLS = None
274        COORDS = None
275        def setUp(self):
276            self.plex = PETSc.DMPlex().createBoxMesh([1,1,1], simplex=True)
277
278    class TestPlex_3D_Boundary(BaseTestPlex_3D, unittest.TestCase):
279        CELLS = None
280        COORDS = None
281        def setUp(self):
282            boundary = PETSc.DMPlex().create(self.COMM)
283            boundary.createCubeBoundary([0., 0., 0.], [1., 1., 1.], [1, 1, 1])
284            boundary.setDimension(self.DIM-1)
285            self.plex = PETSc.DMPlex().generate(boundary)
286
287# --------------------------------------------------------------------
288
289PETSC_DIR = petsc4py.get_config()['PETSC_DIR']
290
291def check_dtype(method):
292    def wrapper(self, *args, **kwargs):
293        if PETSc.ScalarType is PETSc.ComplexType:
294            return
295        else:
296            return method(self, *args, **kwargs)
297    return wrapper
298
299def check_package(method):
300    def wrapper(self, *args, **kwargs):
301        if not PETSc.Sys.hasExternalPackage("hdf5"):
302            return
303        elif self.PARTITIONERTYPE != "simple" and \
304           not PETSc.Sys.hasExternalPackage(self.PARTITIONERTYPE):
305            return
306        else:
307            return method(self, *args, **kwargs)
308    return wrapper
309
310def check_nsize(method):
311    def wrapper(self, *args, **kwargs):
312        if PETSc.COMM_WORLD.size != self.NSIZE:
313            return
314        else:
315            return method(self, *args, **kwargs)
316    return wrapper
317
318class BaseTestPlexHDF5(object):
319    NSIZE = 4
320    NTIMES = 3
321
322    def setUp(self):
323        self.txtvwr = PETSc.Viewer()
324
325    def tearDown(self):
326        if not PETSc.COMM_WORLD.rank:
327            if os.path.exists(self.outfile()):
328                os.remove(self.outfile())
329            if os.path.exists(self.tmp_output_file()):
330                os.remove(self.tmp_output_file())
331        self.txtvwr = None
332
333    def _name(self):
334        return "%s_outformat-%s_%s" % (self.SUFFIX,
335                                       self.OUTFORMAT,
336                                       self.PARTITIONERTYPE)
337
338    def infile(self):
339        return os.path.join(PETSC_DIR, "share/petsc/datafiles/",
340                            "meshes/blockcylinder-50.h5")
341
342    def outfile(self):
343        return os.path.join("./temp_test_dmplex_%s.h5" % self._name())
344
345    def informat(self):
346        return PETSc.Viewer.Format.HDF5_XDMF
347
348    def outformat(self):
349        d = {"hdf5_petsc": PETSc.Viewer.Format.HDF5_PETSC,
350             "hdf5_xdmf": PETSc.Viewer.Format.HDF5_XDMF}
351        return d[self.OUTFORMAT]
352
353    def partitionerType(self):
354        d = {"simple": PETSc.Partitioner.Type.SIMPLE,
355             "ptscotch": PETSc.Partitioner.Type.PTSCOTCH,
356             "parmetis": PETSc.Partitioner.Type.PARMETIS}
357        return d[self.PARTITIONERTYPE]
358
359    def ref_output_file(self):
360        return os.path.join(PETSC_DIR, "src/dm/impls/plex/tutorials/",
361                            "output/ex5_%s.out" % self._name())
362
363    def tmp_output_file(self):
364        return os.path.join("./temp_test_dmplex_%s.out" % self._name())
365
366    def outputText(self, msg, comm):
367        if not comm.rank:
368            with open(self.tmp_output_file(), 'a') as f:
369                f.write(msg)
370
371    def outputPlex(self, plex):
372        self.txtvwr.createASCII(self.tmp_output_file(),
373                                mode='a', comm=plex.comm)
374        plex.view(viewer=self.txtvwr)
375        self.txtvwr.destroy()
376
377    @check_dtype
378    @check_package
379    @check_nsize
380    def testViewLoadCycle(self):
381        grank = PETSc.COMM_WORLD.rank
382        for i in range(self.NTIMES):
383            if i == 0:
384                infname = self.infile()
385                informt = self.informat()
386            else:
387                infname = self.outfile()
388                informt = self.outformat()
389            if self.HETEROGENEOUS:
390                mycolor = (grank > self.NTIMES - i)
391            else:
392                mycolor = 0
393            try:
394                import mpi4py
395            except ImportError:
396                self.skipTest('mpi4py') # throws special exception to signal test skip
397            mpicomm = PETSc.COMM_WORLD.tompi4py()
398            comm = PETSc.Comm(comm=mpicomm.Split(color=mycolor, key=grank))
399            if mycolor == 0:
400                self.outputText("Begin cycle %d\n" % i, comm)
401                plex = PETSc.DMPlex()
402                vwr = PETSc.ViewerHDF5()
403                # Create plex
404                plex.create(comm=comm)
405                plex.setName("DMPlex Object")
406                # Load data from XDMF into dm in parallel
407                vwr.create(infname, mode='r', comm=comm)
408                vwr.pushFormat(format=informt)
409                plex.load(viewer=vwr)
410                plex.setOptionsPrefix("loaded_")
411                plex.setFromOptions()
412                vwr.popFormat()
413                vwr.destroy()
414                self.outputPlex(plex)
415                # Test DM is indeed distributed
416                flg = plex.isDistributed()
417                self.outputText("Loaded mesh distributed? %s\n" %
418                                str(flg).upper(), comm)
419                # Interpolate
420                plex.interpolate()
421                plex.setOptionsPrefix("interpolated_")
422                plex.setFromOptions()
423                self.outputPlex(plex)
424                # Redistribute
425                part = plex.getPartitioner()
426                part.setType(self.partitionerType())
427                _ = plex.distribute(overlap=0)
428                plex.setOptionsPrefix("redistributed_")
429                plex.setFromOptions()
430                self.outputPlex(plex)
431                # Save redistributed dm to XDMF in parallel
432                vwr.create(self.outfile(), mode='w', comm=comm)
433                vwr.pushFormat(format=self.outformat())
434                plex.setName("DMPlex Object")
435                plex.view(viewer=vwr)
436                vwr.popFormat()
437                vwr.destroy()
438                # Destroy plex
439                plex.destroy()
440                self.outputText("End   cycle %d\n--------\n" % i, comm)
441            PETSc.COMM_WORLD.Barrier()
442        # Check that the output is identical to that of plex/tutorial/ex5.c.
443        self.assertTrue(filecmp.cmp(self.tmp_output_file(),
444                                    self.ref_output_file(), shallow=False),
445                        'Contents of the files not the same.')
446        PETSc.COMM_WORLD.Barrier()
447
448class BaseTestPlexHDF5Homogeneous(BaseTestPlexHDF5):
449    """Test save on N / load on N."""
450    SUFFIX = 0
451    HETEROGENEOUS = False
452
453class BaseTestPlexHDF5Heterogeneous(BaseTestPlexHDF5):
454    """Test save on N / load on M."""
455    SUFFIX = 1
456    HETEROGENEOUS = True
457
458class TestPlexHDF5PETSCSimpleHomogeneous(BaseTestPlexHDF5Homogeneous,
459                                         unittest.TestCase):
460    OUTFORMAT = "hdf5_petsc"
461    PARTITIONERTYPE = "simple"
462
463"""
464Skipping. PTScotch produces different distributions when run
465in a sequence in a single session.
466
467class TestPlexHDF5PETSCPTScotchHomogeneous(BaseTestPlexHDF5Homogeneous,
468                                           unittest.TestCase):
469    OUTFORMAT = "hdf5_petsc"
470    PARTITIONERTYPE = "ptscotch"
471"""
472
473class TestPlexHDF5PETSCParmetisHomogeneous(BaseTestPlexHDF5Homogeneous,
474                                           unittest.TestCase):
475    OUTFORMAT = "hdf5_petsc"
476    PARTITIONERTYPE = "parmetis"
477
478class TestPlexHDF5XDMFSimpleHomogeneous(BaseTestPlexHDF5Homogeneous,
479                                        unittest.TestCase):
480    OUTFORMAT = "hdf5_xdmf"
481    PARTITIONERTYPE = "simple"
482
483"""
484Skipping. PTScotch produces different distributions when run
485in a sequence in a single session.
486
487class TestPlexHDF5XDMFPTScotchHomogeneous(BaseTestPlexHDF5Homogeneous,
488                                          unittest.TestCase):
489    OUTFORMAT = "hdf5_xdmf"
490    PARTITIONERTYPE = "ptscotch"
491"""
492
493class TestPlexHDF5XDMFParmetisHomogeneous(BaseTestPlexHDF5Homogeneous,
494                                          unittest.TestCase):
495    OUTFORMAT = "hdf5_xdmf"
496    PARTITIONERTYPE = "parmetis"
497
498class TestPlexHDF5PETSCSimpleHeterogeneous(BaseTestPlexHDF5Heterogeneous,
499                                           unittest.TestCase):
500    OUTFORMAT = "hdf5_petsc"
501    PARTITIONERTYPE = "simple"
502
503"""
504Skipping. PTScotch produces different distributions when run
505in a sequence in a single session.
506
507class TestPlexHDF5PETSCPTScotchHeterogeneous(BaseTestPlexHDF5Heterogeneous,
508                                             unittest.TestCase):
509    OUTFORMAT = "hdf5_petsc"
510    PARTITIONERTYPE = "ptscotch"
511"""
512
513class TestPlexHDF5PETSCParmetisHeterogeneous(BaseTestPlexHDF5Heterogeneous,
514                                             unittest.TestCase):
515    OUTFORMAT = "hdf5_petsc"
516    PARTITIONERTYPE = "parmetis"
517
518class TestPlexHDF5XDMFSimpleHeterogeneous(BaseTestPlexHDF5Heterogeneous,
519                                          unittest.TestCase):
520    OUTFORMAT = "hdf5_xdmf"
521    PARTITIONERTYPE = "simple"
522
523class TestPlexHDF5XDMFPTScotchHeterogeneous(BaseTestPlexHDF5Heterogeneous,
524                                            unittest.TestCase):
525    OUTFORMAT = "hdf5_xdmf"
526    PARTITIONERTYPE = "ptscotch"
527
528class TestPlexHDF5XDMFParmetisHeterogeneous(BaseTestPlexHDF5Heterogeneous,
529                                            unittest.TestCase):
530    OUTFORMAT = "hdf5_xdmf"
531    PARTITIONERTYPE = "parmetis"
532
533# --------------------------------------------------------------------
534
535if __name__ == '__main__':
536    unittest.main()
537